Create simple Todo app with FastAPI and SQLite

- Setup project structure with FastAPI
- Create Todo model and database schemas
- Implement CRUD operations for Todo items
- Create API endpoints for Todo operations
- Add health check endpoint
- Configure Alembic for database migrations
- Add detailed documentation in README.md
This commit is contained in:
Automated Action 2025-05-27 16:58:01 +00:00
parent 8174ea3466
commit 5fbf8c4171
28 changed files with 783 additions and 2 deletions

View File

@ -1,3 +1,87 @@
# FastAPI Application
# Todo App API
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A simple Todo app API built with FastAPI and SQLite. This project provides a RESTful API for managing todo items.
## Features
- CRUD operations for todo items (Create, Read, Update, Delete)
- Filter todos by priority (low, medium, high) and completion status
- SQLite database with SQLAlchemy ORM
- Database migrations with Alembic
- API documentation with Swagger UI and ReDoc
## Project Structure
```
├── app/
│ ├── api/ # API endpoints
│ │ └── v1/ # API version 1
│ │ └── endpoints/
│ │ └── todos.py
│ ├── core/ # Core application settings
│ │ └── config.py
│ ├── crud/ # Database CRUD operations
│ │ ├── base.py
│ │ └── crud_todo.py
│ ├── db/ # Database setup
│ │ ├── base.py
│ │ ├── base_class.py
│ │ └── session.py
│ ├── models/ # SQLAlchemy models
│ │ └── todo.py
│ └── schemas/ # Pydantic schemas
│ └── todo.py
├── migrations/ # Alembic migrations
│ └── versions/
│ └── 0001_create_todo_table.py
├── .env # Environment variables
├── alembic.ini # Alembic configuration
├── main.py # Application entry point
└── requirements.txt # Python dependencies
```
## Getting Started
### Prerequisites
- Python 3.8+
### Installation
1. Clone the repository
2. Install dependencies:
```
pip install -r requirements.txt
```
3. Run the application:
```
uvicorn main:app --reload
```
## 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
- `GET /health`: Health check endpoint
- `GET /docs`: API documentation (Swagger UI)
- `GET /redoc`: API documentation (ReDoc)
## Database Migrations
To apply migrations:
```
alembic upgrade head
```
## Environment Variables
Configuration via environment variables in `.env` file:
- `PROJECT_NAME`: Name of the project
- `PROJECT_DESCRIPTION`: Description of the project
- `PROJECT_VERSION`: Version of the project
- `BACKEND_CORS_ORIGINS`: List of allowed CORS origins

104
alembic.ini Normal file
View File

@ -0,0 +1,104 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = migrations
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(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 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 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

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

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

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

View File

View File

@ -0,0 +1,100 @@
from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Response, status
from sqlalchemy.orm import Session
from app import crud, schemas
from app.db.session import get_db
from app.models.todo import TodoPriority
router = APIRouter()
@router.get("/", response_model=List[schemas.Todo])
def read_todos(
db: Session = Depends(get_db),
skip: int = 0,
limit: int = 100,
priority: Optional[TodoPriority] = None,
completed: Optional[bool] = None,
) -> Any:
"""
Retrieve todos with optional filtering by priority and completion status.
"""
if priority is not None:
todos = crud.todo.get_by_priority(db, priority=priority, skip=skip, limit=limit)
elif completed is not None:
todos = crud.todo.get_completed(db, completed=completed, skip=skip, limit=limit)
else:
todos = crud.todo.get_multi(db, skip=skip, limit=limit)
return todos
@router.post("/", response_model=schemas.Todo, status_code=status.HTTP_201_CREATED)
def create_todo(
*,
db: Session = Depends(get_db),
todo_in: schemas.TodoCreate,
) -> Any:
"""
Create new todo.
"""
todo = crud.todo.create(db=db, obj_in=todo_in)
return todo
@router.get("/{todo_id}", response_model=schemas.Todo)
def read_todo(
*,
db: Session = Depends(get_db),
todo_id: int,
) -> Any:
"""
Get todo by ID.
"""
todo = crud.todo.get(db=db, 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=schemas.Todo)
def update_todo(
*,
db: Session = Depends(get_db),
todo_id: int,
todo_in: schemas.TodoUpdate,
) -> Any:
"""
Update a todo.
"""
todo = crud.todo.get(db=db, 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, 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,
) -> Response:
"""
Delete a todo.
"""
todo = crud.todo.get(db=db, id=todo_id)
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Todo not found",
)
crud.todo.remove(db=db, id=todo_id)
return Response(status_code=status.HTTP_204_NO_CONTENT)

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

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

@ -0,0 +1,26 @@
from typing import List, Union
from pydantic import field_validator
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
PROJECT_NAME: str
PROJECT_DESCRIPTION: str
PROJECT_VERSION: str
BACKEND_CORS_ORIGINS: List[str] = []
@field_validator("BACKEND_CORS_ORIGINS", mode="before")
def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], 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:
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_todo import todo
__all__ = ["todo"]

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

@ -0,0 +1,83 @@
from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from sqlalchemy import select
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]:
"""
Get a single record by ID.
"""
return db.get(self.model, id)
def get_multi(
self, db: Session, *, skip: int = 0, limit: int = 100
) -> List[ModelType]:
"""
Get multiple records with pagination.
"""
statement = select(self.model).offset(skip).limit(limit)
return list(db.execute(statement).scalars().all())
def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType:
"""
Create a new record.
"""
obj_in_data = jsonable_encoder(obj_in)
db_obj = self.model(**obj_in_data)
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:
"""
Update a record.
"""
obj_data = jsonable_encoder(db_obj)
if isinstance(obj_in, dict):
update_data = obj_in
else:
update_data = obj_in.dict(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:
"""
Remove a record.
"""
obj = db.get(self.model, id)
db.delete(obj)
db.commit()
return obj

37
app/crud/crud_todo.py Normal file
View File

@ -0,0 +1,37 @@
from typing import List, Optional
from sqlalchemy import select
from sqlalchemy.orm import Session
from app.crud.base import CRUDBase
from app.models.todo import Todo, TodoPriority
from app.schemas.todo import TodoCreate, TodoUpdate
class CRUDTodo(CRUDBase[Todo, TodoCreate, TodoUpdate]):
def get_by_title(self, db: Session, *, title: str) -> Optional[Todo]:
"""
Get a Todo item by title.
"""
return db.execute(select(Todo).where(Todo.title == title)).scalars().first()
def get_by_priority(
self, db: Session, *, priority: TodoPriority, skip: int = 0, limit: int = 100
) -> List[Todo]:
"""
Get Todo items by priority level.
"""
statement = select(Todo).where(Todo.priority == priority).offset(skip).limit(limit)
return list(db.execute(statement).scalars().all())
def get_completed(
self, db: Session, *, completed: bool = True, skip: int = 0, limit: int = 100
) -> List[Todo]:
"""
Get completed or uncompleted Todo items.
"""
statement = select(Todo).where(Todo.completed == completed).offset(skip).limit(limit)
return list(db.execute(statement).scalars().all())
todo = CRUDTodo(Todo)

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.todo import Todo # noqa

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

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

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

@ -0,0 +1,23 @@
from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
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)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

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

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

@ -0,0 +1,33 @@
from datetime import datetime
from enum import Enum as PyEnum
from typing import Optional
from sqlalchemy import Boolean, DateTime, Enum, String, func
from sqlalchemy.orm import Mapped, mapped_column
from app.db.base_class import Base
class TodoPriority(str, PyEnum):
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
class Todo(Base):
"""
Model for Todo items in the database.
"""
id: Mapped[int] = mapped_column(primary_key=True, index=True)
title: Mapped[str] = mapped_column(String(255), index=True)
description: Mapped[Optional[str]] = mapped_column(String(1000), nullable=True)
priority: Mapped[TodoPriority] = mapped_column(
Enum(TodoPriority), default=TodoPriority.MEDIUM
)
completed: Mapped[bool] = mapped_column(Boolean, default=False)
created_at: Mapped[datetime] = mapped_column(
DateTime, default=func.now(), nullable=False
)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=func.now(), onupdate=func.now(), nullable=False
)

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"]

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

@ -0,0 +1,42 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
from app.models.todo import TodoPriority
# Shared properties
class TodoBase(BaseModel):
title: str = Field(..., min_length=1, max_length=255, description="Title of the todo item")
description: Optional[str] = Field(None, max_length=1000, description="Detailed description of the todo item")
priority: TodoPriority = Field(TodoPriority.MEDIUM, description="Priority level of the todo item")
completed: bool = Field(False, description="Whether the todo item is completed")
# Properties to receive on todo creation
class TodoCreate(TodoBase):
pass
# Properties to receive on todo update
class TodoUpdate(BaseModel):
title: Optional[str] = Field(None, min_length=1, max_length=255, description="Title of the todo item")
description: Optional[str] = Field(None, max_length=1000, description="Detailed description of the todo item")
priority: Optional[TodoPriority] = Field(None, description="Priority level of the todo item")
completed: Optional[bool] = Field(None, description="Whether the todo item is completed")
# Properties shared by models stored in DB
class TodoInDBBase(TodoBase):
id: int
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True
# Properties to return to client
class Todo(TodoInDBBase):
pass

39
main.py Normal file
View File

@ -0,0 +1,39 @@
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.v1.api import api_router
from app.core.config import settings
app = FastAPI(
title=settings.PROJECT_NAME,
description=settings.PROJECT_DESCRIPTION,
version=settings.PROJECT_VERSION,
openapi_url="/openapi.json",
docs_url="/docs",
redoc_url="/redoc",
)
# Set all CORS enabled origins
if settings.BACKEND_CORS_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(api_router)
@app.get("/health", tags=["Health"])
async def health_check():
"""
Health check endpoint to verify the API is running.
"""
return {"status": "healthy"}
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.

83
migrations/env.py Normal file
View File

@ -0,0 +1,83 @@
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 myapp import mymodel
# target_metadata = mymodel.Base.metadata
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() -> 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,
)
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:
# Check if we're using SQLite
is_sqlite = connection.dialect.name == "sqlite"
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=is_sqlite, # Use 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,50 @@
"""create todo table
Revision ID: 0001
Revises:
Create Date: 2023-10-30
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '0001'
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
# Create enum type for todo priority
priority_enum = sa.Enum('low', 'medium', 'high', name='todopriority')
priority_enum.create(op.get_bind(), checkfirst=True)
# Create todos 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.String(length=1000), nullable=True),
sa.Column('priority', priority_enum, nullable=False, default='medium'),
sa.Column('completed', sa.Boolean(), nullable=False, default=False),
sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()),
sa.Column('updated_at', sa.DateTime(), nullable=False, server_default=sa.func.now(), onupdate=sa.func.now()),
sa.PrimaryKeyConstraint('id')
)
# Create indexes
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() -> None:
# Drop indexes
op.drop_index(op.f('ix_todo_title'), table_name='todo')
op.drop_index(op.f('ix_todo_id'), table_name='todo')
# Drop table
op.drop_table('todo')
# Drop enum type
sa.Enum(name='todopriority').drop(op.get_bind(), checkfirst=True)

14
pyproject.toml Normal file
View File

@ -0,0 +1,14 @@
[tool.ruff]
line-length = 120
target-version = "py38"
[tool.ruff.lint]
select = ["E", "F", "I", "B", "W", "C90"]
ignore = ["B008"] # Allow function calls in argument defaults, which is common in FastAPI
[tool.ruff.lint.isort]
known-first-party = ["app"]
[tool.ruff.lint.flake8-quotes]
docstring-quotes = "double"
inline-quotes = "double"

8
requirements.txt Normal file
View File

@ -0,0 +1,8 @@
fastapi>=0.104.0
uvicorn>=0.23.2
pydantic>=2.4.2
pydantic-settings>=2.0.3
sqlalchemy>=2.0.23
alembic>=1.12.0
python-dotenv>=1.0.0
ruff>=0.1.1