Create FastAPI REST API with SQLite

Features:
- Project structure with FastAPI framework
- SQLAlchemy models with SQLite database
- Alembic migrations system
- CRUD operations for items
- API routers with endpoints for items
- Health endpoint for monitoring
- Error handling and validation
- Comprehensive documentation
This commit is contained in:
Automated Action 2025-05-18 05:45:33 +00:00
parent df57520007
commit e1b1b89511
29 changed files with 874 additions and 2 deletions

199
README.md
View File

@ -1,3 +1,198 @@
# FastAPI Application
# Generic REST API Service
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A generic REST API service built with FastAPI and SQLite.
## Features
- FastAPI framework for high performance
- SQLite database with SQLAlchemy ORM
- Alembic for database migrations
- CRUD operations for resource management
- Pydantic models for request/response validation
- Error handling with custom exceptions
- API documentation (Swagger UI and ReDoc)
- Health check endpoint
## Project Structure
```
.
├── app # Application package
│ ├── api # API endpoints
│ │ ├── v1 # API version 1
│ │ │ ├── health.py # Health check endpoint
│ │ │ └── items.py # Items endpoints
│ │ ├── deps.py # Dependencies
│ │ ├── errors.py # Error handlers and custom exceptions
│ │ └── router.py # Main router
│ ├── core # Core modules
│ │ └── config.py # Configuration settings
│ ├── crud # CRUD operations
│ │ ├── base.py # Base CRUD class
│ │ └── crud_item.py # Item CRUD operations
│ ├── db # Database
│ │ ├── base.py # Base imports for Alembic
│ │ ├── base_class.py # Base class for models
│ │ └── session.py # Database session
│ ├── models # SQLAlchemy models
│ │ └── item.py # Item model
│ └── schemas # Pydantic schemas
│ └── item.py # Item schemas
├── migrations # Alembic migrations
│ ├── versions # Migration versions
│ │ └── 001_initial_migration.py # Initial migration
│ ├── env.py # Alembic environment
│ └── script.py.mako # Migration script template
├── alembic.ini # Alembic configuration
├── main.py # Application entry point
└── requirements.txt # Dependencies
```
## Setup and Installation
1. Clone the repository:
```bash
git clone https://github.com/your-username/genericrestapiservice.git
cd genericrestapiservice
```
2. Create and activate 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
```
5. Start the application:
```bash
uvicorn main:app --reload
```
The API will be available at http://localhost:8000.
## API Documentation
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
## API Endpoints
### Health Check
- `GET /api/v1/health` - Check API and database health
### 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
## Example Usage
### Create an item
```bash
curl -X 'POST' \
'http://localhost:8000/api/v1/items' \
-H 'Content-Type: application/json' \
-d '{
"title": "My First Item",
"description": "This is an example item",
"is_active": true
}'
```
### Get all items
```bash
curl -X 'GET' 'http://localhost:8000/api/v1/items'
```
### Get an item by ID
```bash
curl -X 'GET' 'http://localhost:8000/api/v1/items/1'
```
### Update an item
```bash
curl -X 'PUT' \
'http://localhost:8000/api/v1/items/1' \
-H 'Content-Type: application/json' \
-d '{
"title": "Updated Item",
"description": "This item has been updated"
}'
```
### Delete an item
```bash
curl -X 'DELETE' 'http://localhost:8000/api/v1/items/1'
```
## Database Configuration
The API uses SQLite as the database engine. The database file is located at `/app/storage/db/db.sqlite`. This path is configured in `app/core/config.py`. You can change the database configuration by modifying this file.
## Running with Docker
You can use Docker to run the API. Here's an example Dockerfile:
```dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
# Create storage directory
RUN mkdir -p /app/storage/db
# Run migrations
RUN alembic upgrade head
# Expose the port
EXPOSE 8000
# Run the application
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
```
To build and run the Docker container:
```bash
docker build -t genericrestapiservice .
docker run -p 8000:8000 genericrestapiservice
```
## Development
### Code Style
This project uses Ruff for linting and formatting. To lint the code:
```bash
ruff check .
```
To format the code:
```bash
ruff format .
```

85
alembic.ini Normal file
View File

@ -0,0 +1,85 @@
# 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
# timezone to use when rendering the date
# within the migration file as well as the filename.
# 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
# version_locations = %(here)s/bar %(here)s/bat migrations/versions
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# SQLite URL - use absolute path for SQLite
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
# 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

0
app/__init__.py Normal file
View File

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

1
app/api/deps.py Normal file
View File

@ -0,0 +1 @@

42
app/api/errors.py Normal file
View File

@ -0,0 +1,42 @@
from fastapi import HTTPException, Request, status
from fastapi.responses import JSONResponse
class BaseAPIException(HTTPException):
def __init__(
self,
status_code: int,
detail: str = None,
headers: dict = None,
):
super().__init__(status_code=status_code, detail=detail, headers=headers)
class ItemNotFoundException(BaseAPIException):
def __init__(self, item_id: int):
super().__init__(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Item with ID {item_id} not found",
)
class ValidationError(BaseAPIException):
def __init__(self, detail: str = "Validation error"):
super().__init__(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=detail,
)
async def validation_exception_handler(request: Request, exc: ValidationError):
return JSONResponse(
status_code=exc.status_code,
content={"detail": exc.detail},
)
async def item_not_found_handler(request: Request, exc: ItemNotFoundException):
return JSONResponse(
status_code=exc.status_code,
content={"detail": exc.detail},
)

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

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

0
app/api/v1/__init__.py Normal file
View File

15
app/api/v1/health.py Normal file
View File

@ -0,0 +1,15 @@
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.db.session import get_db
router = APIRouter()
@router.get("", status_code=200)
def health_check(db: Session = Depends(get_db)):
"""
Health check endpoint to verify API is running and database connection is working.
"""
health_status = {"status": "ok", "database": "connected" if db else "disconnected"}
return health_status

90
app/api/v1/items.py Normal file
View File

@ -0,0 +1,90 @@
from typing import Any, List, Optional
from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session
from app import crud, schemas
from app.api.errors import ItemNotFoundException
from app.db.session import get_db
router = APIRouter()
@router.get("", response_model=List[schemas.Item])
def read_items(
db: Session = Depends(get_db),
skip: int = 0,
limit: int = 100,
is_active: Optional[bool] = None,
) -> Any:
"""
Retrieve items.
"""
if is_active is not None:
items = crud.item.get_multi_by_active(
db, skip=skip, limit=limit, is_active=is_active
)
else:
items = crud.item.get_multi(db, skip=skip, limit=limit)
return items
@router.post("", 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.
"""
item = crud.item.create(db=db, obj_in=item_in)
return item
@router.get("/{item_id}", response_model=schemas.Item)
def read_item(
*,
db: Session = Depends(get_db),
item_id: int,
) -> Any:
"""
Get item by ID.
"""
item = crud.item.get(db=db, id=item_id)
if not item:
raise ItemNotFoundException(item_id=item_id)
return item
@router.put("/{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.
"""
item = crud.item.get(db=db, id=item_id)
if not item:
raise ItemNotFoundException(item_id=item_id)
item = crud.item.update(db=db, db_obj=item, obj_in=item_in)
return item
@router.delete("/{item_id}", response_model=schemas.Item)
def delete_item(
*,
db: Session = Depends(get_db),
item_id: int,
) -> Any:
"""
Delete an item.
"""
item = crud.item.get(db=db, id=item_id)
if not item:
raise ItemNotFoundException(item_id=item_id)
item = crud.item.remove(db=db, id=item_id)
return item

0
app/core/__init__.py Normal file
View File

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

@ -0,0 +1,23 @@
from pathlib import Path
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
API_V1_STR: str = "/api/v1"
PROJECT_NAME: str = "Generic REST API Service"
PROJECT_DESCRIPTION: str = (
"A generic REST API service built with FastAPI and SQLite"
)
VERSION: str = "0.1.0"
# Database configuration
DB_DIR = Path("/app") / "storage" / "db"
DB_DIR.mkdir(parents=True, exist_ok=True)
SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite"
class Config:
case_sensitive = True
settings = Settings()

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

@ -0,0 +1 @@
from .crud_item import item as item # noqa: F401

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.base_class 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_by_active(
self, db: Session, *, skip: int = 0, limit: int = 100, is_active: bool = True
) -> List[Item]:
return (
db.query(Item)
.filter(Item.is_active == is_active)
.offset(skip)
.limit(limit)
.all()
)
item = CRUDItem(Item)

0
app/db/__init__.py Normal file
View File

4
app/db/base.py Normal file
View File

@ -0,0 +1,4 @@
# Import all the models, so that Base has them before being
# imported by Alembic
from app.db.base_class import Base # noqa
from app.models.item import Item # noqa

14
app/db/base_class.py Normal file
View File

@ -0,0 +1,14 @@
from typing import Any
from sqlalchemy.ext.declarative import as_declarative, declared_attr
@as_declarative()
class Base:
id: Any
__name__: str
# Generate __tablename__ automatically based on class name
@declared_attr
def __tablename__(cls) -> str:
return cls.__name__.lower()

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

@ -0,0 +1,22 @@
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.core.config import settings
# Create an engine for the database
engine = create_engine(
settings.SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False}, # Needed for SQLite
)
# Create a SessionLocal class for session creation
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# Dependency to get the database session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

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

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

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

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

@ -0,0 +1,6 @@
from .item import ( # noqa: F401
Item as Item,
ItemCreate as ItemCreate,
ItemUpdate as ItemUpdate,
ItemInDBBase as ItemInDBBase,
)

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

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

53
main.py Normal file
View File

@ -0,0 +1,53 @@
import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from pydantic import ValidationError
from app.api.errors import (
ItemNotFoundException,
validation_exception_handler,
item_not_found_handler,
)
from app.api.router 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",
)
# Exception handlers
app.add_exception_handler(ValidationError, validation_exception_handler)
app.add_exception_handler(ItemNotFoundException, item_not_found_handler)
@app.exception_handler(Exception)
async def generic_exception_handler(request: Request, exc: Exception):
return JSONResponse(
status_code=500,
content={"detail": "Internal server error"},
)
app.include_router(api_router, prefix=settings.API_V1_STR)
@app.get("/")
def root():
"""
Root endpoint with API information.
"""
return {
"name": settings.PROJECT_NAME,
"version": settings.VERSION,
"docs": "/docs",
"redoc": "/redoc",
}
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 sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# 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.
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
from app.db.base import Base # 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():
"""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():
"""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, # Key configuration 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():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}

View File

@ -0,0 +1,44 @@
"""Initial migration
Revision ID: 001
Revises:
Create Date: 2023-10-08
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import func
# revision identifiers, used by Alembic.
revision = "001"
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# Create item table
op.create_table(
"item",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("title", sa.String(length=100), nullable=False),
sa.Column("description", sa.Text(), nullable=True),
sa.Column("is_active", sa.Boolean(), nullable=True, default=True),
sa.Column("created_at", sa.DateTime(timezone=True), server_default=func.now()),
sa.Column(
"updated_at",
sa.DateTime(timezone=True),
server_default=func.now(),
onupdate=func.now(),
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_item_id"), "item", ["id"], unique=False)
op.create_index(op.f("ix_item_title"), "item", ["title"], unique=False)
def downgrade():
op.drop_index(op.f("ix_item_title"), table_name="item")
op.drop_index(op.f("ix_item_id"), table_name="item")
op.drop_table("item")

View File

@ -0,0 +1,3 @@
This directory contains Alembic migration scripts.
Each file is a migration step. To apply migrations, run:
`alembic upgrade head`

10
requirements.txt Normal file
View File

@ -0,0 +1,10 @@
fastapi>=0.103.1,<0.104.0
uvicorn>=0.23.2,<0.24.0
sqlalchemy>=2.0.21,<2.1.0
alembic>=1.12.0,<1.13.0
pydantic>=2.4.2,<2.5.0
pydantic-settings>=2.0.3,<2.1.0
python-multipart>=0.0.6,<0.1.0
email-validator>=2.0.0,<2.1.0
ruff>=0.0.292,<0.1.0
pathlib>=1.0.1,<1.1.0