Create a REST API with FastAPI and SQLite

- Setup FastAPI project structure with main.py and requirements.txt
- Implement SQLAlchemy ORM with SQLite database
- Create Item model with CRUD operations
- Implement health endpoint for monitoring
- Setup Alembic for database migrations
- Add comprehensive documentation in README.md
- Configure Ruff for code linting
This commit is contained in:
Automated Action 2025-05-23 10:10:10 +00:00
parent 4ea71bda14
commit e0b4ac8ba6
20 changed files with 814 additions and 2 deletions

128
README.md
View File

@ -1,3 +1,127 @@
# FastAPI Application
# REST API Service
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A modern REST API service built with FastAPI and SQLite.
## Features
- **FastAPI Framework**: High-performance, easy to learn, fast to code, ready for production
- **SQLAlchemy ORM**: SQL toolkit and Object-Relational Mapping
- **SQLite Database**: Lightweight disk-based database
- **Alembic Migrations**: Database migration tool for SQLAlchemy
- **Pydantic Models**: Data validation and settings management
- **OpenAPI Documentation**: Interactive API documentation at /docs and /redoc
- **Health Check Endpoint**: Monitoring endpoint for service health
## Project Structure
```
.
├── alembic.ini # Alembic configuration
├── app # Application package
│ ├── api # API endpoints
│ │ ├── __init__.py # API router setup
│ │ ├── health.py # Health check endpoint
│ │ └── items.py # Items endpoints
│ ├── core # Core application configuration
│ │ └── config.py # Application settings
│ ├── crud # CRUD operations
│ │ ├── __init__.py # CRUD exports
│ │ ├── base.py # Base CRUD class
│ │ └── crud_item.py # Item CRUD operations
│ ├── db # Database setup
│ │ └── session.py # Database session management
│ ├── models # SQLAlchemy models
│ │ ├── __init__.py # Model exports
│ │ └── item.py # Item model
│ └── schemas # Pydantic schemas
│ ├── __init__.py # Schema exports
│ └── item.py # Item schemas
├── main.py # Application entry point
├── migrations # Database migrations
│ ├── env.py # Alembic environment configuration
│ ├── script.py.mako # Alembic template for migrations
│ └── versions # Migration scripts
│ └── initial_migration.py # Initial database schema
└── requirements.txt # Python dependencies
```
## Installation
1. Clone the repository:
```bash
git clone <repository-url>
cd <repository-name>
```
2. Create a virtual environment:
```bash
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
```
3. Install dependencies:
```bash
pip install -r requirements.txt
```
4. Run database migrations:
```bash
alembic upgrade head
```
## Running the Application
Start the application with Uvicorn:
```bash
uvicorn main:app --reload
```
The API will be available at http://localhost:8000
## API Documentation
- **OpenAPI Swagger UI**: http://localhost:8000/docs
- **ReDoc**: http://localhost:8000/redoc
## API Endpoints
### Health Check
- `GET /api/v1/health`: Check the health of the API
### Items
- `GET /api/v1/items/`: Get all items
- `POST /api/v1/items/`: Create a new item
- `GET /api/v1/items/{item_id}`: Get an item by ID
- `PUT /api/v1/items/{item_id}`: Update an item
- `DELETE /api/v1/items/{item_id}`: Delete an item
## Database
The application uses SQLite as its database, stored at `/app/storage/db/db.sqlite`.
## Development
### Creating a new migration
After making changes to the SQLAlchemy models, create a new migration script:
```bash
alembic revision --autogenerate -m "Description of changes"
```
### Running migrations
Apply all pending migrations:
```bash
alembic upgrade head
```
Revert the last migration:
```bash
alembic downgrade -1
```

103
alembic.ini Normal file
View File

@ -0,0 +1,103 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = migrations
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python-dateutil library that can be
# installed by adding `alembic[tz]` to the pip requirements
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to migrations/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# SQLite URL - using absolute path
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

7
app/api/__init__.py Normal file
View File

@ -0,0 +1,7 @@
from fastapi import APIRouter
from app.api import health, items
api_router = APIRouter()
api_router.include_router(health.router, tags=["health"])
api_router.include_router(items.router, tags=["items"])

30
app/api/health.py Normal file
View File

@ -0,0 +1,30 @@
from datetime import datetime
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.db.session import get_db
router = APIRouter()
@router.get("/health", summary="Health check endpoint")
def health_check(db: Session = Depends(get_db)):
"""
Check the health of the API.
Returns:
dict: Health status information including uptime and database status
"""
db_status = "ok"
try:
# Test database connection
db.execute("SELECT 1")
except Exception as e:
db_status = f"error: {str(e)}"
return {
"status": "ok",
"timestamp": datetime.utcnow().isoformat(),
"database": db_status,
}

135
app/api/items.py Normal file
View File

@ -0,0 +1,135 @@
from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app import crud, schemas
from app.db.session import get_db
router = APIRouter()
@router.get("/items/", response_model=List[schemas.Item])
def read_items(
db: Session = Depends(get_db),
skip: int = 0,
limit: int = 100,
active_only: bool = False,
) -> Any:
"""
Retrieve items.
Args:
skip: Number of items to skip
limit: Maximum number of items to return
active_only: If True, only return active items
Returns:
List of items
"""
if active_only:
items = crud.item.get_multi_active(db, skip=skip, limit=limit)
else:
items = crud.item.get_multi(db, skip=skip, limit=limit)
return items
@router.post("/items/", response_model=schemas.Item, status_code=status.HTTP_201_CREATED)
def create_item(
*,
db: Session = Depends(get_db),
item_in: schemas.ItemCreate,
) -> Any:
"""
Create new item.
Args:
item_in: Item data
Returns:
Created item
"""
item = crud.item.get_by_title(db, title=item_in.title)
if item:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="An item with this title already exists.",
)
item = crud.item.create(db, obj_in=item_in)
return item
@router.get("/items/{item_id}", response_model=schemas.Item)
def read_item(
*,
db: Session = Depends(get_db),
item_id: int,
) -> Any:
"""
Get item by ID.
Args:
item_id: ID of item to get
Returns:
Item information
"""
item = crud.item.get(db=db, id=item_id)
if not item:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Item not found",
)
return item
@router.put("/items/{item_id}", response_model=schemas.Item)
def update_item(
*,
db: Session = Depends(get_db),
item_id: int,
item_in: schemas.ItemUpdate,
) -> Any:
"""
Update an item.
Args:
item_id: ID of item to update
item_in: New item data
Returns:
Updated item
"""
item = crud.item.get(db=db, id=item_id)
if not item:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Item not found",
)
item = crud.item.update(db=db, db_obj=item, obj_in=item_in)
return item
@router.delete("/items/{item_id}", response_model=schemas.Item)
def delete_item(
*,
db: Session = Depends(get_db),
item_id: int,
) -> Any:
"""
Delete an item.
Args:
item_id: ID of item to delete
Returns:
Deleted item
"""
item = crud.item.get(db=db, id=item_id)
if not item:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Item not found",
)
item = crud.item.remove(db=db, id=item_id)
return item

28
app/core/config.py Normal file
View File

@ -0,0 +1,28 @@
from pathlib import Path
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
# API configuration
API_V1_STR: str = "/api/v1"
PROJECT_NAME: str = "RESTAPIService"
PROJECT_DESCRIPTION: str = "FastAPI REST API Service"
VERSION: str = "0.1.0"
# CORS Origins
BACKEND_CORS_ORIGINS: list[str] = ["*"]
# Database
DB_DIR = Path("/app") / "storage" / "db"
DB_DIR.mkdir(parents=True, exist_ok=True)
# SQLite Database URL
SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite"
class Config:
case_sensitive = True
env_file = ".env"
settings = Settings()

3
app/crud/__init__.py Normal file
View File

@ -0,0 +1,3 @@
from app.crud.crud_item import item # noqa: F401
__all__ = ["item"]

66
app/crud/base.py Normal file
View File

@ -0,0 +1,66 @@
from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.db.session import Base
ModelType = TypeVar("ModelType", bound=Base)
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
def __init__(self, model: Type[ModelType]):
"""
CRUD object with default methods to Create, Read, Update, Delete (CRUD).
**Parameters**
* `model`: A SQLAlchemy model class
* `schema`: A Pydantic model (schema) class
"""
self.model = model
def get(self, db: Session, id: Any) -> Optional[ModelType]:
return db.query(self.model).filter(self.model.id == id).first()
def get_multi(
self, db: Session, *, skip: int = 0, limit: int = 100
) -> List[ModelType]:
return db.query(self.model).offset(skip).limit(limit).all()
def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType:
obj_in_data = jsonable_encoder(obj_in)
db_obj = self.model(**obj_in_data) # type: ignore
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def update(
self,
db: Session,
*,
db_obj: ModelType,
obj_in: Union[UpdateSchemaType, Dict[str, Any]]
) -> ModelType:
obj_data = jsonable_encoder(db_obj)
if isinstance(obj_in, dict):
update_data = obj_in
else:
update_data = obj_in.model_dump(exclude_unset=True)
for field in obj_data:
if field in update_data:
setattr(db_obj, field, update_data[field])
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def remove(self, db: Session, *, id: int) -> ModelType:
obj = db.query(self.model).get(id)
db.delete(obj)
db.commit()
return obj

26
app/crud/crud_item.py Normal file
View File

@ -0,0 +1,26 @@
from typing import List, Optional
from sqlalchemy.orm import Session
from app.crud.base import CRUDBase
from app.models.item import Item
from app.schemas.item import ItemCreate, ItemUpdate
class CRUDItem(CRUDBase[Item, ItemCreate, ItemUpdate]):
def get_by_title(self, db: Session, *, title: str) -> Optional[Item]:
return db.query(Item).filter(Item.title == title).first()
def get_multi_active(
self, db: Session, *, skip: int = 0, limit: int = 100
) -> List[Item]:
return (
db.query(Item)
.filter(Item.is_active == True) # noqa: E712
.offset(skip)
.limit(limit)
.all()
)
item = CRUDItem(Item)

27
app/db/session.py Normal file
View File

@ -0,0 +1,27 @@
from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from app.core.config import settings
# Ensure DB directory exists
Path(settings.DB_DIR).mkdir(parents=True, exist_ok=True)
engine = create_engine(
settings.SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False} # needed only for SQLite
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
# Dependency to get DB session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

3
app/models/__init__.py Normal file
View File

@ -0,0 +1,3 @@
from app.models.item import Item # noqa: F401
__all__ = ["Item"]

15
app/models/item.py Normal file
View File

@ -0,0 +1,15 @@
from sqlalchemy import Boolean, Column, DateTime, Integer, String
from sqlalchemy.sql import func
from app.db.session import Base
class Item(Base):
__tablename__ = "items"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
description = Column(String, index=True)
is_active = Column(Boolean(), default=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())

3
app/schemas/__init__.py Normal file
View File

@ -0,0 +1,3 @@
from app.schemas.item import Item, ItemCreate, ItemInDB, ItemUpdate # noqa: F401
__all__ = ["Item", "ItemCreate", "ItemUpdate", "ItemInDB"]

45
app/schemas/item.py Normal file
View File

@ -0,0 +1,45 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
# Shared properties
class ItemBase(BaseModel):
title: Optional[str] = None
description: Optional[str] = None
is_active: Optional[bool] = True
# Properties to receive on item creation
class ItemCreate(ItemBase):
title: str = Field(..., min_length=1, max_length=100)
description: str = Field(..., min_length=1)
# Properties to receive on item update
class ItemUpdate(ItemBase):
pass
# Properties shared by models stored in DB
class ItemInDBBase(ItemBase):
id: int
title: str
description: str
is_active: bool
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
from_attributes = True
# Properties to return to client
class Item(ItemInDBBase):
pass
# Properties stored in DB
class ItemInDB(ItemInDBBase):
pass

20
main.py Normal file
View File

@ -0,0 +1,20 @@
import uvicorn
from fastapi import FastAPI
from app.api import api_router
from app.core.config import settings
app = FastAPI(
title=settings.PROJECT_NAME,
description=settings.PROJECT_DESCRIPTION,
version=settings.VERSION,
openapi_url=f"{settings.API_V1_STR}/openapi.json",
docs_url="/docs",
redoc_url="/redoc",
)
app.include_router(api_router, prefix=settings.API_V1_STR)
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

80
migrations/env.py Normal file
View File

@ -0,0 +1,80 @@
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
from app.db.session import Base
from app.models import Item # noqa
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
is_sqlite = connection.dialect.name == "sqlite"
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=is_sqlite, # Enable batch mode for SQLite
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

24
migrations/script.py.mako Normal file
View File

@ -0,0 +1,24 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}

View File

@ -0,0 +1,39 @@
"""initial migration
Revision ID: 000001
Revises:
Create Date: 2023-07-01
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '000001'
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
# Create items table
op.create_table(
'items',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=True),
sa.Column('description', sa.String(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=True, default=True),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)')),
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_items_id'), 'items', ['id'], unique=False)
op.create_index(op.f('ix_items_title'), 'items', ['title'], unique=False)
op.create_index(op.f('ix_items_description'), 'items', ['description'], unique=False)
def downgrade() -> None:
op.drop_index(op.f('ix_items_description'), table_name='items')
op.drop_index(op.f('ix_items_title'), table_name='items')
op.drop_index(op.f('ix_items_id'), table_name='items')
op.drop_table('items')

25
pyproject.toml Normal file
View File

@ -0,0 +1,25 @@
[tool.ruff]
line-length = 100
target-version = "py310"
[tool.ruff.lint]
# Enable Pyflakes, pycodestyle, isort
select = ["F", "E", "W", "I"]
# Ignore specific rules
ignore = [
"E501", # Line too long
"W293", # Blank line contains whitespace - docstrings often have this
]
# Exclude files and directories
exclude = [
".git",
".venv",
"venv",
"__pycache__",
"migrations",
]
[tool.ruff.lint.isort]
known-third-party = ["fastapi", "pydantic", "sqlalchemy", "alembic", "starlette"]

9
requirements.txt Normal file
View File

@ -0,0 +1,9 @@
fastapi>=0.100.0
uvicorn>=0.23.0
sqlalchemy>=2.0.0
pydantic>=2.0.0
alembic>=1.11.0
python-dotenv>=1.0.0
ruff>=0.0.272
email-validator>=2.0.0
pydantic[email]>=2.0.0