Create FastAPI Todo App

Create a simple Todo API with FastAPI and SQLite with CRUD functionality,
health check, error handling, and API documentation.
This commit is contained in:
Automated Action 2025-05-31 21:13:37 +00:00
parent 19c0cc654c
commit e01f3a4d57
25 changed files with 862 additions and 2 deletions

149
README.md
View File

@ -1,3 +1,148 @@
# FastAPI Application
# FastAPI Todo App
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A simple Todo API built with FastAPI and SQLite.
## Features
- 📝 **Todo Management**: Create, read, update, and delete todo items
- 🔍 **Filtering & Pagination**: Filter todos by completion status and paginate results
- 📊 **Health Monitoring**: Endpoint to check application and database health
- 🛡️ **Error Handling**: Comprehensive error handling with meaningful messages
- 📚 **API Documentation**: Auto-generated Swagger/OpenAPI documentation
## Tech Stack
- **FastAPI**: Modern, fast (high-performance) web framework for building APIs
- **SQLAlchemy**: SQL toolkit and Object-Relational Mapping (ORM)
- **Alembic**: Database migration tool
- **SQLite**: Lightweight, file-based database
- **Pydantic**: Data validation and settings management
- **Uvicorn**: ASGI server for running the application
## Project Structure
```
├── app/
│ ├── api/
│ │ └── v1/
│ │ ├── health.py # Health check endpoint
│ │ ├── router.py # API router
│ │ └── todos.py # Todo CRUD endpoints
│ ├── core/
│ │ ├── config.py # Application configuration
│ │ └── exceptions.py # Custom exception handlers
│ ├── database/
│ │ └── session.py # Database session setup
│ ├── models/
│ │ └── todo.py # SQLAlchemy models
│ └── schemas/
│ └── todo.py # Pydantic schemas
├── migrations/ # Alembic migration files
├── alembic.ini # Alembic configuration
├── main.py # Application entry point
└── requirements.txt # Project dependencies
```
## Setup Instructions
### Prerequisites
- Python 3.8+
- pip (Python package installer)
### Installation
1. Clone the repository:
```bash
git clone <repository-url>
cd todoapp-us6a2a
```
2. Install dependencies:
```bash
pip install -r requirements.txt
```
3. Create the database and run migrations:
```bash
alembic upgrade head
```
### Running the Application
Start the application with:
```bash
uvicorn main:app --host 0.0.0.0 --port 8000 --reload
```
The API will be available at: http://localhost:8000
## API Documentation
Interactive API documentation is available at:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
## API Endpoints
### Health Check
- `GET /health` - Check application health
### Todo Endpoints
- `GET /api/v1/todos` - List all todos (with optional filtering and pagination)
- `POST /api/v1/todos` - Create a new todo
- `GET /api/v1/todos/{todo_id}` - Get a specific todo
- `PATCH /api/v1/todos/{todo_id}` - Update a todo
- `DELETE /api/v1/todos/{todo_id}` - Delete a todo
## Example Usage
### Create a Todo
```bash
curl -X 'POST' \
'http://localhost:8000/api/v1/todos/' \
-H 'Content-Type: application/json' \
-d '{
"title": "Learn FastAPI",
"description": "Build a sample todo app",
"completed": false
}'
```
### List All Todos
```bash
curl -X 'GET' 'http://localhost:8000/api/v1/todos/'
```
### Get a Specific Todo
```bash
curl -X 'GET' 'http://localhost:8000/api/v1/todos/1'
```
### Update a Todo
```bash
curl -X 'PATCH' \
'http://localhost:8000/api/v1/todos/1' \
-H 'Content-Type: application/json' \
-d '{
"completed": true
}'
```
### Delete a Todo
```bash
curl -X 'DELETE' 'http://localhost:8000/api/v1/todos/1'
```
## License
This project is licensed under the MIT License.

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 example
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

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

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

@ -0,0 +1,49 @@
import platform
import sys
from datetime import datetime
from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session
from app.core.config import settings
from app.database.session import get_db
router = APIRouter()
@router.get(
"/health",
summary="Check health status",
status_code=status.HTTP_200_OK,
tags=["health"]
)
def health_check(db: Session = Depends(get_db)):
"""
Check the health of the application.
Returns:
dict: A dictionary containing health status information.
"""
health_data = {
"status": "ok",
"timestamp": datetime.utcnow().isoformat(),
"app_name": settings.PROJECT_NAME,
"environment": {
"python_version": sys.version,
"platform": platform.platform(),
},
"database": {
"status": "connected",
"type": "sqlite",
}
}
try:
# Verify database connectivity
db.execute("SELECT 1")
except Exception as e:
health_data["status"] = "error"
health_data["database"]["status"] = "error"
health_data["database"]["error"] = str(e)
return health_data

8
app/api/v1/router.py Normal file
View File

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

137
app/api/v1/todos.py Normal file
View File

@ -0,0 +1,137 @@
from typing import List, Optional
from fastapi import APIRouter, Depends, Path, Query, status
from sqlalchemy.orm import Session
from app.core.exceptions import TodoException
from app.database.session import get_db
from app.models import Todo as TodoModel
from app.schemas import Todo as TodoSchema
from app.schemas import TodoCreate, TodoUpdate
router = APIRouter()
@router.post(
"/",
response_model=TodoSchema,
status_code=status.HTTP_201_CREATED,
summary="Create a new todo item"
)
def create_todo(
todo_in: TodoCreate,
db: Session = Depends(get_db)
):
"""
Create a new todo item.
"""
db_todo = TodoModel(**todo_in.model_dump())
db.add(db_todo)
db.commit()
db.refresh(db_todo)
return db_todo
@router.get(
"/",
response_model=List[TodoSchema],
summary="Get all todo items"
)
def read_todos(
skip: int = Query(0, ge=0, description="Number of items to skip"),
limit: int = Query(
100,
ge=1,
le=100,
description="Maximum number of items to return"
),
completed: Optional[bool] = Query(None, description="Filter by completed status"),
db: Session = Depends(get_db)
):
"""
Get all todo items with optional filtering and pagination.
"""
query = db.query(TodoModel)
# Apply filter if completed status is provided
if completed is not None:
query = query.filter(TodoModel.completed == completed)
todos = query.offset(skip).limit(limit).all()
return todos
@router.get(
"/{todo_id}",
response_model=TodoSchema,
summary="Get a specific todo item"
)
def read_todo(
todo_id: int = Path(..., gt=0, description="The ID of the todo item"),
db: Session = Depends(get_db)
):
"""
Get a specific todo item by ID.
"""
todo = db.query(TodoModel).filter(TodoModel.id == todo_id).first()
if todo is None:
raise TodoException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Todo with ID {todo_id} not found"
)
return todo
@router.patch(
"/{todo_id}",
response_model=TodoSchema,
summary="Update a todo item"
)
def update_todo(
todo_id: int = Path(..., gt=0, description="The ID of the todo item"),
todo_in: TodoUpdate = ...,
db: Session = Depends(get_db)
):
"""
Update a todo item.
"""
todo = db.query(TodoModel).filter(TodoModel.id == todo_id).first()
if todo is None:
raise TodoException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Todo with ID {todo_id} not found"
)
update_data = todo_in.model_dump(exclude_unset=True)
for field, value in update_data.items():
setattr(todo, field, value)
db.add(todo)
db.commit()
db.refresh(todo)
return todo
@router.delete(
"/{todo_id}",
status_code=status.HTTP_204_NO_CONTENT,
response_model=None,
summary="Delete a todo item"
)
def delete_todo(
todo_id: int = Path(..., gt=0, description="The ID of the todo item"),
db: Session = Depends(get_db)
):
"""
Delete a todo item.
"""
todo = db.query(TodoModel).filter(TodoModel.id == todo_id).first()
if todo is None:
raise TodoException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Todo with ID {todo_id} not found"
)
db.delete(todo)
db.commit()
return None

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

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

@ -0,0 +1,22 @@
from pathlib import Path
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
PROJECT_NAME: str = "Todo API"
API_V1_STR: str = "/api/v1"
# Database settings
DB_DIR: Path = Path("/app") / "storage" / "db"
DB_NAME: str = "db.sqlite"
class Config:
env_file = ".env"
case_sensitive = True
settings = Settings()
# Ensure DB directory exists
settings.DB_DIR.mkdir(parents=True, exist_ok=True)

59
app/core/exceptions.py Normal file
View File

@ -0,0 +1,59 @@
from fastapi import FastAPI, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from sqlalchemy.exc import SQLAlchemyError
class TodoException(Exception):
"""Base exception class for the Todo application."""
def __init__(self, status_code: int, detail: str):
self.status_code = status_code
self.detail = detail
def add_exception_handlers(app: FastAPI) -> None:
"""
Add exception handlers to the FastAPI application.
Args:
app: The FastAPI application instance.
"""
@app.exception_handler(TodoException)
async def todo_exception_handler(request: Request, exc: TodoException):
"""Handle custom TodoException."""
return JSONResponse(
status_code=exc.status_code,
content={"detail": exc.detail},
)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(
request: Request,
exc: RequestValidationError
):
"""Handle request validation errors."""
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content={
"detail": "Validation error",
"errors": exc.errors(),
},
)
@app.exception_handler(SQLAlchemyError)
async def sqlalchemy_exception_handler(request: Request, exc: SQLAlchemyError):
"""Handle SQLAlchemy errors."""
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"detail": "Database error. Please try again later."},
)
@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
"""Handle all other exceptions."""
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"detail": "Internal server error. Please try again later."},
)

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

30
app/database/session.py Normal file
View File

@ -0,0 +1,30 @@
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
settings.DB_DIR.mkdir(parents=True, exist_ok=True)
SQLALCHEMY_DATABASE_URL = f"sqlite:///{settings.DB_DIR}/{settings.DB_NAME}"
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
"""
Dependency function to get a database session.
"""
db = SessionLocal()
try:
yield db
finally:
db.close()

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

@ -0,0 +1,3 @@
from app.models.todo import Todo
__all__ = ["Todo"]

19
app/models/todo.py Normal file
View File

@ -0,0 +1,19 @@
from datetime import datetime
from sqlalchemy import Boolean, Column, DateTime, Integer, String, Text
from app.database.session import Base
class Todo(Base):
"""
SQLAlchemy model for todo items.
"""
__tablename__ = "todos"
id = Column(Integer, primary_key=True, index=True)
title = Column(String(100), nullable=False)
description = Column(Text, nullable=True)
completed = Column(Boolean, default=False)
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

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

@ -0,0 +1,3 @@
from app.schemas.todo import Todo, TodoCreate, TodoUpdate
__all__ = ["Todo", "TodoCreate", "TodoUpdate"]

71
app/schemas/todo.py Normal file
View File

@ -0,0 +1,71 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
class TodoBase(BaseModel):
"""
Base schema for Todo items with common attributes.
"""
title: str = Field(
...,
min_length=1,
max_length=100,
description="The title of the todo item"
)
description: Optional[str] = Field(
None,
description="An optional description of the todo item"
)
completed: bool = Field(
False,
description="Whether the todo item is completed"
)
class TodoCreate(TodoBase):
"""
Schema for creating a new Todo item.
"""
pass
class TodoUpdate(BaseModel):
"""
Schema for updating an existing Todo item.
All fields are optional to allow partial updates.
"""
title: Optional[str] = Field(
None,
min_length=1,
max_length=100,
description="The title of the todo item"
)
description: Optional[str] = Field(
None,
description="An optional description of the todo item"
)
completed: Optional[bool] = Field(
None,
description="Whether the todo item is completed"
)
class TodoInDBBase(TodoBase):
"""
Schema for Todo items as stored in the database.
"""
id: int
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True
class Todo(TodoInDBBase):
"""
Schema for Todo items returned to clients.
"""
pass

47
main.py Normal file
View File

@ -0,0 +1,47 @@
import uvicorn
from fastapi import FastAPI, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse
from app.api.v1.health import health_check
from app.api.v1.router import api_router
from app.core.config import settings
from app.core.exceptions import add_exception_handlers
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url="/openapi.json",
description="A simple Todo API built with FastAPI and SQLite",
version="0.1.0",
)
# Set up CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Add exception handlers
add_exception_handlers(app)
# Root endpoint - redirect to docs
@app.get("/", include_in_schema=False)
def root():
return RedirectResponse(url="/docs")
# Root health endpoint for easy access
app.get(
"/health",
summary="Check health status",
status_code=status.HTTP_200_OK,
tags=["health"],
)(health_check)
# Include API router
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)

1
migrations/README Normal file
View File

@ -0,0 +1 @@
Generic single-database configuration with SQLite.

0
migrations/__init__.py Normal file
View File

83
migrations/env.py Normal file
View File

@ -0,0 +1,83 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from app.models import Base
from app.core.config import settings
# 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
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, # Important for SQLite
compare_type=True,
)
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,35 @@
"""Create todos table
Revision ID: 1a1a1a1a1a1a
Revises:
Create Date: 2023-10-01 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1a1a1a1a1a1a'
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
'todos',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(100), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('completed', sa.Boolean(), default=False),
sa.Column('created_at', sa.DateTime(), default=sa.func.current_timestamp()),
sa.Column('updated_at', sa.DateTime(), default=sa.func.current_timestamp(), onupdate=sa.func.current_timestamp()),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_todos_id'), 'todos', ['id'], unique=False)
def downgrade() -> None:
op.drop_index(op.f('ix_todos_id'), table_name='todos')
op.drop_table('todos')

31
pyproject.toml Normal file
View File

@ -0,0 +1,31 @@
[tool.ruff]
# Exclude a variety of commonly ignored directories.
exclude = [
".git",
".ruff_cache",
"__pycache__",
"venv",
"migrations",
]
# Same as Black.
line-length = 88
# Assume Python 3.10
target-version = "py310"
[tool.ruff.lint]
# Enable flake8-bugbear (`B`) rules.
select = ["E", "F", "B", "I"]
# Allow unused variables when underscore-prefixed.
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
# Ignore some errors
ignore = ["B008"] # Ignore function call in argument defaults which is common in FastAPI
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]
[tool.ruff.lint.isort]
known-third-party = ["fastapi", "pydantic", "sqlalchemy", "alembic", "uvicorn"]

8
requirements.txt Normal file
View File

@ -0,0 +1,8 @@
fastapi>=0.100.0
uvicorn>=0.22.0
sqlalchemy>=2.0.0
alembic>=1.11.0
pydantic>=2.0.0
python-dotenv>=1.0.0
ruff>=0.0.292
pathlib>=1.0.1