Create Todo API application with FastAPI and SQLite

This commit is contained in:
Automated Action 2025-05-26 18:53:00 +00:00
parent c4ed3651b3
commit 9e50f1fa57
24 changed files with 812 additions and 2 deletions

103
README.md
View File

@ -1,3 +1,102 @@
# FastAPI Application
# Todo API
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A simple REST API for managing todo items built with FastAPI and SQLite.
## Features
- Create, read, update, and delete todo items
- Filter todos by completion status
- Input validation with Pydantic
- Database migrations with Alembic
- Error handling and structured responses
- Health check endpoint
- API documentation with Swagger UI
## Technologies Used
- [FastAPI](https://fastapi.tiangolo.com/) - Modern web framework for building APIs
- [SQLAlchemy](https://www.sqlalchemy.org/) - SQL toolkit and ORM
- [Pydantic](https://docs.pydantic.dev/) - Data validation and settings management
- [Alembic](https://alembic.sqlalchemy.org/) - Database migration tool
- [SQLite](https://www.sqlite.org/) - File-based SQL database
- [Uvicorn](https://www.uvicorn.org/) - ASGI server
- [Ruff](https://beta.ruff.rs/docs/) - Python linter and formatter
## Project Structure
```
todoapi/
├── alembic.ini # Alembic configuration
├── app/ # Application package
│ ├── api/ # API endpoints
│ │ ├── endpoints/ # Endpoint handlers
│ │ │ └── todos.py # Todo endpoints
│ │ ├── api.py # API router
│ │ └── errors.py # Error handling
│ ├── db/ # Database
│ │ └── database.py # Database configuration
│ ├── models/ # SQLAlchemy models
│ │ └── todo.py # Todo model
│ └── schemas/ # Pydantic schemas
│ └── todo.py # Todo schemas
├── main.py # Application entry point
├── migrations/ # Database migrations
│ ├── env.py # Alembic environment
│ ├── script.py.mako # Migration template
│ └── versions/ # Migration scripts
├── pyproject.toml # Project configuration
└── requirements.txt # Dependencies
```
## API Endpoints
- `GET /health` - Health check endpoint
- `GET /todos` - List all todo items (with optional filtering)
- `GET /todos/{todo_id}` - Get a specific todo item
- `POST /todos` - Create a new todo item
- `PUT /todos/{todo_id}` - Update a todo item
- `DELETE /todos/{todo_id}` - Delete a todo item
## Getting Started
### Prerequisites
- Python 3.9 or higher
### Installation
1. Clone the repository
2. Install dependencies:
```bash
pip install -r requirements.txt
```
3. Run the application:
```bash
uvicorn main:app --reload
```
4. Visit the API documentation at http://localhost:8000/docs
## Database Migrations
The application uses Alembic for database migrations:
```bash
# Apply migrations
alembic upgrade head
# Create a new migration (after modifying models)
alembic revision --autogenerate -m "description"
```
## Development
To lint and format the code:
```bash
ruff check .
ruff check --fix .
```

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

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

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

View File

View File

@ -0,0 +1,95 @@
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.db.database import get_db
from app.models.todo import Todo
from app.schemas.todo import Todo as TodoSchema
from app.schemas.todo import TodoCreate, TodoUpdate
router = APIRouter()
@router.post("/", response_model=TodoSchema, status_code=status.HTTP_201_CREATED)
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
"""
Create a new todo item.
"""
db_todo = Todo(
title=todo.title,
description=todo.description,
completed=todo.completed
)
db.add(db_todo)
db.commit()
db.refresh(db_todo)
return db_todo
@router.get("/", response_model=list[TodoSchema])
def read_todos(
skip: int = 0,
limit: int = 100,
completed: Optional[bool] = None,
db: Session = Depends(get_db)
):
"""
Retrieve all todo items with optional filtering.
"""
query = db.query(Todo)
# Filter by completion status if specified
if completed is not None:
query = query.filter(Todo.completed == completed)
todos = query.offset(skip).limit(limit).all()
return todos
@router.get("/{todo_id}", response_model=TodoSchema)
def read_todo(todo_id: int, db: Session = Depends(get_db)):
"""
Retrieve a specific todo item by ID.
"""
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
return db_todo
@router.put("/{todo_id}", response_model=TodoSchema)
def update_todo(todo_id: int, todo: TodoUpdate, db: Session = Depends(get_db)):
"""
Update a todo item.
"""
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
# Update fields that are provided
todo_data = todo.model_dump(exclude_unset=True)
for key, value in todo_data.items():
setattr(db_todo, key, value)
db.commit()
db.refresh(db_todo)
return db_todo
@router.delete(
"/{todo_id}",
status_code=status.HTTP_204_NO_CONTENT,
response_model=None
)
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
"""
Delete a todo item.
"""
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
db.delete(db_todo)
db.commit()
return None

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

@ -0,0 +1,58 @@
from fastapi import HTTPException, Request, status
from fastapi.responses import JSONResponse
from pydantic import ValidationError
class APIError(HTTPException):
def __init__(
self,
status_code: int,
detail: str,
error_code: str = None,
):
super().__init__(status_code=status_code, detail=detail)
self.error_code = error_code
async def http_error_handler(request: Request, exc: HTTPException) -> JSONResponse:
"""
Handle HTTP exceptions.
"""
return JSONResponse(
status_code=exc.status_code,
content={"detail": exc.detail}
)
async def api_error_handler(request: Request, exc: APIError) -> JSONResponse:
"""
Handle custom API exceptions.
"""
headers = getattr(exc, "headers", None)
if exc.error_code:
content = {"detail": exc.detail, "code": exc.error_code}
else:
content = {"detail": exc.detail}
return JSONResponse(
status_code=exc.status_code,
content=content,
headers=headers,
)
async def validation_error_handler(
request: Request,
exc: ValidationError
) -> JSONResponse:
"""
Handle validation errors.
"""
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content={
"detail": exc.errors(),
"body": exc.body,
},
)

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

29
app/db/database.py Normal file
View File

@ -0,0 +1,29 @@
from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# Create DB directory if it doesn't exist
DB_DIR = Path("/app") / "storage" / "db"
DB_DIR.mkdir(parents=True, exist_ok=True)
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

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

15
app/models/todo.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.database import Base
class Todo(Base):
__tablename__ = "todos"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
description = Column(String)
completed = Column(Boolean, default=False)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())

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

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

@ -0,0 +1,33 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
class TodoBase(BaseModel):
title: str = Field(..., min_length=1, max_length=100)
description: Optional[str] = Field(None, max_length=1000)
completed: bool = False
class TodoCreate(TodoBase):
pass
class TodoUpdate(BaseModel):
title: Optional[str] = Field(None, min_length=1, max_length=100)
description: Optional[str] = Field(None, max_length=1000)
completed: Optional[bool] = None
class TodoInDB(TodoBase):
id: int
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
from_attributes = True
class Todo(TodoInDB):
pass

48
main.py Normal file
View File

@ -0,0 +1,48 @@
import uvicorn
from fastapi import FastAPI, HTTPException, status
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from pydantic import ValidationError
from app.api.api import api_router
from app.api.errors import (
APIError,
api_error_handler,
http_error_handler,
validation_error_handler,
)
# Create all tables in the database
# Comment this out if you're using Alembic migrations
# Base.metadata.create_all(bind=engine)
app = FastAPI(
title="Todo API",
description="A simple REST API for managing todo items",
version="0.1.0",
)
# Add exception handlers
app.add_exception_handler(HTTPException, http_error_handler)
app.add_exception_handler(APIError, api_error_handler)
app.add_exception_handler(RequestValidationError, validation_error_handler)
app.add_exception_handler(ValidationError, validation_error_handler)
# Enable CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include the API router
app.include_router(api_router)
@app.get("/health", status_code=status.HTTP_200_OK)
async def health_check():
return {"status": "healthy"}
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

0
migrations/__init__.py Normal file
View File

81
migrations/env.py Normal file
View File

@ -0,0 +1,81 @@
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.models.todo import Todo
from app.db.database import Base
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
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():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}

View File

View File

@ -0,0 +1,38 @@
"""initial migration
Revision ID: 001
Revises:
Create Date: 2023-08-01
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '001'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# Create todos table
op.create_table('todos',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=True),
sa.Column('description', sa.String(), nullable=True),
sa.Column('completed', sa.Boolean(), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_todos_id'), 'todos', ['id'], unique=False)
op.create_index(op.f('ix_todos_title'), 'todos', ['title'], unique=False)
def downgrade():
# Drop todos table
op.drop_index(op.f('ix_todos_title'), table_name='todos')
op.drop_index(op.f('ix_todos_id'), table_name='todos')
op.drop_table('todos')

19
pyproject.toml Normal file
View File

@ -0,0 +1,19 @@
[tool.ruff]
line-length = 88
target-version = "py39"
exclude = [
".git",
".ruff_cache",
".venv",
"venv",
"migrations",
]
[tool.ruff.lint]
select = ["E", "F", "I", "UP"]
ignore = []
fixable = ["ALL"]
unfixable = []
[tool.ruff.lint.isort]
known-third-party = ["fastapi", "pydantic", "sqlalchemy", "alembic", "uvicorn"]

10
requirements.txt Normal file
View File

@ -0,0 +1,10 @@
fastapi>=0.101.0
uvicorn>=0.23.2
pydantic>=2.0.0
sqlalchemy>=2.0.0
alembic>=1.11.0
ruff>=0.0.290
python-dotenv>=1.0.0
pydantic-settings>=2.0.0
httpx>=0.24.1
pytest>=7.4.0

0
tests/__init__.py Normal file
View File

169
tests/test_api.py Normal file
View File

@ -0,0 +1,169 @@
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.db.database import Base, get_db
from app.models.todo import Todo
from main import app
# Setup in-memory SQLite database for testing
SQLALCHEMY_DATABASE_URL = "sqlite:///:memory:"
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
@pytest.fixture
def test_db():
# Create the tables in the test database
Base.metadata.create_all(bind=engine)
# Create a session for testing
db = TestingSessionLocal()
try:
yield db
finally:
db.close()
# Drop all tables after the test
Base.metadata.drop_all(bind=engine)
@pytest.fixture
def client(test_db):
# Override the get_db dependency
def override_get_db():
try:
yield test_db
finally:
pass
app.dependency_overrides[get_db] = override_get_db
with TestClient(app) as c:
yield c
# Clear overrides
app.dependency_overrides.clear()
def test_health_check(client):
response = client.get("/health")
assert response.status_code == 200
assert response.json() == {"status": "healthy"}
def test_create_todo(client):
response = client.post(
"/todos/",
json={
"title": "Test Todo",
"description": "This is a test",
"completed": False
},
)
assert response.status_code == 201
data = response.json()
assert data["title"] == "Test Todo"
assert data["description"] == "This is a test"
assert data["completed"] is False
assert "id" in data
assert "created_at" in data
def test_read_todos_empty(client):
response = client.get("/todos/")
assert response.status_code == 200
assert response.json() == []
def test_read_todos(client, test_db):
# Add a test todo to the database
todo = Todo(title="Test Todo", description="Test Description", completed=False)
test_db.add(todo)
test_db.commit()
test_db.refresh(todo)
response = client.get("/todos/")
assert response.status_code == 200
data = response.json()
assert len(data) == 1
assert data[0]["title"] == "Test Todo"
assert data[0]["description"] == "Test Description"
assert data[0]["id"] == todo.id
def test_read_todo(client, test_db):
# Add a test todo to the database
todo = Todo(title="Test Todo", description="Test Description", completed=False)
test_db.add(todo)
test_db.commit()
test_db.refresh(todo)
response = client.get(f"/todos/{todo.id}")
assert response.status_code == 200
data = response.json()
assert data["title"] == "Test Todo"
assert data["description"] == "Test Description"
assert data["id"] == todo.id
def test_read_todo_not_found(client):
response = client.get("/todos/999")
assert response.status_code == 404
assert response.json() == {"detail": "Todo not found"}
def test_update_todo(client, test_db):
# Add a test todo to the database
todo = Todo(title="Test Todo", description="Test Description", completed=False)
test_db.add(todo)
test_db.commit()
test_db.refresh(todo)
response = client.put(
f"/todos/{todo.id}",
json={"title": "Updated Todo", "completed": True},
)
assert response.status_code == 200
data = response.json()
assert data["title"] == "Updated Todo"
assert data["description"] == "Test Description" # Unchanged
assert data["completed"] is True # Updated
assert data["id"] == todo.id
def test_update_todo_not_found(client):
response = client.put(
"/todos/999",
json={"title": "Updated Todo", "completed": True},
)
assert response.status_code == 404
assert response.json() == {"detail": "Todo not found"}
def test_delete_todo(client, test_db):
# Add a test todo to the database
todo = Todo(title="Test Todo", description="Test Description", completed=False)
test_db.add(todo)
test_db.commit()
test_db.refresh(todo)
response = client.delete(f"/todos/{todo.id}")
assert response.status_code == 204
# Verify it's deleted
todo_check = test_db.query(Todo).filter(Todo.id == todo.id).first()
assert todo_check is None
def test_delete_todo_not_found(client):
response = client.delete("/todos/999")
assert response.status_code == 404
assert response.json() == {"detail": "Todo not found"}