Complete Todo API implementation with FastAPI and SQLite

- Add SQLite database configuration
- Create Todo model, schemas, and CRUD operations
- Implement Todo API endpoints
- Add Alembic migration for todo table
- Set up database initialization in main.py
- Update README with project details and instructions
- Add pyproject.toml with Ruff configuration
This commit is contained in:
Automated Action 2025-06-10 15:40:42 +00:00
parent 3b18371814
commit 53566813bd
28 changed files with 852 additions and 2 deletions

View File

@ -1,3 +1,68 @@
# FastAPI Application
# Todo API
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
This is a FastAPI Todo API application that allows you to manage todo items.
## Features
- Create, read, update, and delete todo items
- Filter todos by completion status and title
- Pagination support
- SQLite database backend
- Alembic migrations
## Requirements
- Python 3.9+
- FastAPI
- SQLAlchemy
- Alembic
- Uvicorn
- Other dependencies in requirements.txt
## Installation
1. Clone the repository
2. Install the dependencies:
```bash
pip install -r requirements.txt
```
## Database Setup
The application uses SQLite as the database backend. The database will be automatically created in the `/app/storage/db` directory when the application starts.
To run the 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
The API documentation is available at:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
## API Endpoints
- `GET /api/v1/todos`: List all todos with optional filtering
- `POST /api/v1/todos`: Create a new todo
- `GET /api/v1/todos/{todo_id}`: Get a specific todo
- `PUT /api/v1/todos/{todo_id}`: Update a todo
- `DELETE /api/v1/todos/{todo_id}`: Delete a todo
## Health Check
The application includes a health check endpoint at `/health` that can be used to verify that the service is running properly.

74
alembic.ini Normal file
View File

@ -0,0 +1,74 @@
# 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 using absolute path
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
# 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

View File

6
app/api/api_v1/api.py Normal file
View File

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

View File

View File

@ -0,0 +1,110 @@
from typing import Any, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.api.deps import get_db
from app.crud import todo as crud_todo
from app.schemas.todo import Todo, TodoCreate, TodoList, TodoUpdate
router = APIRouter()
@router.get("/", response_model=TodoList)
def read_todos(
db: Session = Depends(get_db),
skip: int = 0,
limit: int = 100,
completed: Optional[bool] = None,
title: Optional[str] = None,
) -> Any:
"""
Retrieve todos.
- **skip**: Number of records to skip for pagination
- **limit**: Maximum number of records to return
- **completed**: Filter by completion status
- **title**: Filter by title (partial match)
"""
filters = {}
if completed is not None:
filters["completed"] = completed
if title:
filters["title"] = title
todos = crud_todo.get_multi(db, skip=skip, limit=limit, filters=filters)
count = crud_todo.count(db, filters=filters)
return {"items": todos, "count": count}
@router.post("/", response_model=Todo, status_code=status.HTTP_201_CREATED)
def create_todo(
*,
db: Session = Depends(get_db),
todo_in: TodoCreate,
) -> Any:
"""
Create new todo.
"""
todo = crud_todo.create(db, obj_in=todo_in)
return todo
@router.get("/{todo_id}", response_model=Todo)
def read_todo(
*,
db: Session = Depends(get_db),
todo_id: int,
) -> Any:
"""
Get todo by ID.
"""
todo = crud_todo.get(db, todo_id=todo_id)
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Todo not found"
)
return todo
@router.put("/{todo_id}", response_model=Todo)
def update_todo(
*,
db: Session = Depends(get_db),
todo_id: int,
todo_in: TodoUpdate,
) -> Any:
"""
Update a todo.
"""
todo = crud_todo.get(db, todo_id=todo_id)
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Todo not found"
)
todo = crud_todo.update(db, db_obj=todo, obj_in=todo_in)
return todo
@router.delete(
"/{todo_id}",
status_code=status.HTTP_204_NO_CONTENT,
response_model=None
)
def delete_todo(
*,
db: Session = Depends(get_db),
todo_id: int,
) -> None:
"""
Delete a todo.
"""
todo = crud_todo.get(db, todo_id=todo_id)
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Todo not found"
)
crud_todo.remove(db, todo_id=todo_id)

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

@ -0,0 +1,14 @@
from collections.abc import Generator
from app.db.session import SessionLocal
def get_db() -> Generator:
"""
Dependency for getting the database session.
"""
db = SessionLocal()
try:
yield db
finally:
db.close()

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

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

@ -0,0 +1,26 @@
from pydantic import validator
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
API_V1_STR: str = "/api/v1"
PROJECT_NAME: str = "Todo API"
VERSION: str = "0.1.0"
# CORS Configuration
BACKEND_CORS_ORIGINS: list[str] = ["*"]
@validator("BACKEND_CORS_ORIGINS", pre=True)
def assemble_cors_origins(cls, v: list[str]) -> list[str]:
if isinstance(v, str) and not v.startswith("["):
return [i.strip() for i in v.split(",")]
elif isinstance(v, (list, str)):
return v
raise ValueError(v)
class Config:
env_file = ".env"
case_sensitive = True
settings = Settings()

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

145
app/crud/todo.py Normal file
View File

@ -0,0 +1,145 @@
from typing import Any, Dict, Optional, Union
from sqlalchemy.orm import Session
from app.models.todo import Todo
from app.schemas.todo import TodoCreate, TodoUpdate
def get(db: Session, todo_id: int) -> Optional[Todo]:
"""
Get a single todo item by ID.
Args:
db: Database session
todo_id: ID of the todo item to retrieve
Returns:
Todo object if found, None otherwise
"""
return db.query(Todo).filter(Todo.id == todo_id).first()
def get_multi(
db: Session,
*,
skip: int = 0,
limit: int = 100,
filters: Optional[Dict[str, Any]] = None
) -> list[Todo]:
"""
Get multiple todo items with optional filtering, pagination.
Args:
db: Database session
skip: Number of records to skip (for pagination)
limit: Maximum number of records to return
filters: Optional dictionary of filter conditions
Returns:
List of Todo objects
"""
query = db.query(Todo)
# Apply filters if provided
if filters:
if "completed" in filters:
query = query.filter(Todo.completed == filters["completed"])
if "title" in filters:
query = query.filter(Todo.title.ilike(f"%{filters['title']}%"))
return query.order_by(Todo.created_at.desc()).offset(skip).limit(limit).all()
def create(db: Session, *, obj_in: TodoCreate) -> Todo:
"""
Create a new todo item.
Args:
db: Database session
obj_in: TodoCreate schema with the data for the new todo
Returns:
Created Todo object
"""
db_obj = Todo(
title=obj_in.title,
description=obj_in.description,
completed=obj_in.completed,
)
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def update(
db: Session, *, db_obj: Todo, obj_in: Union[TodoUpdate, Dict[str, Any]]
) -> Todo:
"""
Update a todo item.
Args:
db: Database session
db_obj: Existing Todo object to update
obj_in: TodoUpdate schema or dict with fields to update
Returns:
Updated Todo object
"""
if isinstance(obj_in, dict):
update_data = obj_in
else:
update_data = obj_in.model_dump(exclude_unset=True)
for field in update_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(db: Session, *, todo_id: int) -> Optional[Todo]:
"""
Delete a todo item.
Args:
db: Database session
todo_id: ID of the todo item to delete
Returns:
Deleted Todo object if found, None otherwise
"""
obj = db.query(Todo).get(todo_id)
if obj:
db.delete(obj)
db.commit()
return obj
def count(db: Session, *, filters: Optional[Dict[str, Any]] = None) -> int:
"""
Count todo items with optional filtering.
Args:
db: Database session
filters: Optional dictionary of filter conditions
Returns:
Count of Todo objects matching the filters
"""
query = db.query(Todo)
# Apply filters if provided
if filters:
if "completed" in filters:
query = query.filter(Todo.completed == filters["completed"])
if "title" in filters:
query = query.filter(Todo.title.ilike(f"%{filters['title']}%"))
return query.count()

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

@ -0,0 +1,2 @@
# Import for convenience
from app.db.base import Base

2
app/db/all_models.py Normal file
View File

@ -0,0 +1,2 @@
# Import all models here for Alembic's sake
# Import models below

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

@ -0,0 +1,4 @@
from sqlalchemy.ext.declarative import declarative_base
# Define the SQLAlchemy base
Base = declarative_base()

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

@ -0,0 +1,15 @@
from datetime import datetime
from sqlalchemy import Column, DateTime
from sqlalchemy.ext.declarative import declared_attr
class BaseClass:
# Generate __tablename__ automatically based on class name
@declared_attr
def __tablename__(cls) -> str:
return cls.__name__.lower()
# Add created_at and updated_at columns to all models
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

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

@ -0,0 +1,17 @@
from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# Create a storage directory for the SQLite database
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)

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

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

@ -0,0 +1,14 @@
from sqlalchemy import Boolean, Column, Integer, String, Text
from app.db.base import Base
from app.db.base_class import BaseClass
class Todo(Base, BaseClass):
"""
SQLAlchemy model for Todo items.
"""
id = Column(Integer, primary_key=True, index=True)
title = Column(String(255), nullable=False, index=True)
description = Column(Text, nullable=True)
completed = Column(Boolean, default=False, nullable=False)

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

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

@ -0,0 +1,79 @@
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=255,
description="The title of the todo item"
)
description: Optional[str] = Field(
None,
description="An optional detailed description of the todo item"
)
completed: bool = Field(
False,
description="Whether the todo item has been 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=255,
description="The title of the todo item"
)
description: Optional[str] = Field(
None,
description="An optional detailed description of the todo item"
)
completed: Optional[bool] = Field(
None,
description="Whether the todo item has been 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 the client.
"""
pass
class TodoList(BaseModel):
"""
Schema for a list of Todo items.
"""
items: list[Todo]
count: int

89
main.py Normal file
View File

@ -0,0 +1,89 @@
import logging
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.utils import get_openapi
from app.api.api_v1.api import api_router
from app.core.config import settings
from app.db.base import Base
from app.db.session import engine
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Create database tables
def create_tables():
try:
logger.info("Creating database tables")
# Import all models to ensure they are registered with Base
from app.db.all_models import * # noqa
Base.metadata.create_all(bind=engine)
logger.info("Database tables created successfully")
except Exception as e:
logger.error(f"Error creating database tables: {e}")
raise
# Initialize FastAPI app
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url="/openapi.json",
docs_url="/docs",
redoc_url="/redoc",
)
# Set all CORS enabled origins
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include API router
app.include_router(api_router, prefix=settings.API_V1_STR)
# Create tables on startup if they don't exist
@app.on_event("startup")
async def startup_event():
create_tables()
@app.get("/", tags=["status"])
async def root():
"""
Root endpoint that returns basic service information.
"""
return {
"name": settings.PROJECT_NAME,
"docs": "/docs",
"health": "/health"
}
@app.get("/health", tags=["status"])
async def health():
"""
Health check endpoint.
"""
return {"status": "healthy"}
def custom_openapi():
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title=settings.PROJECT_NAME,
version=settings.VERSION,
description="A FastAPI Todo API",
routes=app.routes,
)
app.openapi_schema = openapi_schema
return app.openapi_schema
app.openapi = custom_openapi

77
migrations/env.py Normal file
View File

@ -0,0 +1,77 @@
import sys
from logging.config import fileConfig
from pathlib import Path
from alembic import context
from sqlalchemy import engine_from_config, pool
# Add the parent directory to sys.path
sys.path.append(str(Path(__file__).resolve().parents[1]))
# Import the Base class from our app
from app.db.base import Base # noqa
# Import all the models so that Alembic can see them
from app.db.all_models import * # noqa
# This is the Alembic Config object
config = context.config
# Interpret the config file for Python logging
fileConfig(config.config_file_name)
# Set the target metadata for the database
target_metadata = Base.metadata
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"},
render_as_batch=True, # For SQLite
)
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, # 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,42 @@
"""create todo table
Revision ID: 7f2ea9b3e5c8
Revises:
Create Date: 2023-06-10 16:00:00.000000
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '7f2ea9b3e5c8'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# Create the todo table
op.create_table(
'todo',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(length=255), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('completed', sa.Boolean(), nullable=False, default=False),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
# Create an index on the title column
op.create_index(op.f('ix_todo_id'), 'todo', ['id'], unique=False)
op.create_index(op.f('ix_todo_title'), 'todo', ['title'], unique=False)
def downgrade():
# Drop the indexes
op.drop_index(op.f('ix_todo_title'), table_name='todo')
op.drop_index(op.f('ix_todo_id'), table_name='todo')
# Drop the todo table
op.drop_table('todo')

37
pyproject.toml Normal file
View File

@ -0,0 +1,37 @@
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "todoapi"
version = "0.1.0"
description = "FastAPI Todo API"
readme = "README.md"
requires-python = ">=3.9"
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
]
[tool.ruff]
# Same as Black.
line-length = 88
indent-width = 4
# Target Python 3.9.
target-version = "py39"
[tool.ruff.lint]
# Enable pycodestyle ('E'), Pyflakes ('F'), isort ('I')
select = ["E", "F", "I"]
ignore = []
# Allow unused variables when underscore-prefixed.
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]
[tool.ruff.lint.isort]
known-third-party = ["fastapi", "pydantic", "sqlalchemy", "alembic"]

8
requirements.txt Normal file
View File

@ -0,0 +1,8 @@
fastapi>=0.104.0
uvicorn>=0.24.0
sqlalchemy>=2.0.0
alembic>=1.12.0
pydantic>=2.4.2
pydantic-settings>=2.0.3
python-dotenv>=1.0.0
ruff>=0.1.3