Implement Todo List API with FastAPI and SQLite

This commit is contained in:
Automated Action 2025-05-19 20:36:01 +00:00
parent 4f4716316c
commit 8aa3dbf80f
24 changed files with 793 additions and 2 deletions

162
README.md
View File

@ -1,3 +1,161 @@
# FastAPI Application
# Todo List API
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A simple Todo List API built with FastAPI and SQLite.
## Features
- Create, read, update, and delete todo items
- Filter todo items by completion status
- Pagination support
- SQLite database with SQLAlchemy ORM
- Database migrations with Alembic
- Health check endpoint
- OpenAPI documentation
## Project Structure
```
todo-list-api/
├── alembic.ini # Alembic configuration
├── app/ # Main application package
│ ├── api/ # API endpoints
│ │ └── routes/ # API route handlers
│ │ ├── health.py # Health check endpoint
│ │ └── todo.py # Todo endpoints
│ ├── core/ # Core application code
│ │ └── config.py # Application configuration
│ ├── crud/ # CRUD operations
│ │ └── todo.py # Todo CRUD operations
│ ├── db/ # Database related code
│ │ └── session.py # Database session setup
│ ├── models/ # SQLAlchemy models
│ │ └── todo.py # Todo model
│ └── schemas/ # Pydantic schemas
│ └── todo.py # Todo schemas
├── main.py # Application entry point
├── migrations/ # Alembic migrations
│ ├── env.py # Alembic environment configuration
│ ├── script.py.mako # Migration script template
│ └── versions/ # Migration script versions
│ └── 001_create_todos_table.py # Initial migration
└── requirements.txt # Python dependencies
```
## Requirements
- Python 3.9+
- FastAPI
- SQLAlchemy
- Pydantic
- Alembic
- Uvicorn
## Installation
1. Clone the repository:
```bash
git clone https://github.com/yourusername/todo-list-api.git
cd todo-list-api
```
2. Install the required dependencies:
```bash
pip install -r requirements.txt
```
3. Run database migrations:
```bash
alembic upgrade head
```
## Running the Application
Start the application with:
```bash
uvicorn main:app --reload
```
The API will be available at `http://localhost:8000`.
## API Documentation
After starting the application, you can access the interactive API documentation:
- Swagger UI: `http://localhost:8000/docs`
- ReDoc: `http://localhost:8000/redoc`
## API Endpoints
### Health Check
- `GET /api/health`: Check if the API is healthy
### Todo Operations
- `GET /api/todos`: Get a list of todo items
- Query parameters:
- `skip`: Number of items to skip (pagination)
- `limit`: Maximum number of items to return (pagination)
- `completed`: Filter by completion status (optional)
- `POST /api/todos`: Create a new todo item
- Request body: `TodoCreate` schema
- `GET /api/todos/{todo_id}`: Get a specific todo item by ID
- `PUT /api/todos/{todo_id}`: Update a specific todo item by ID
- Request body: `TodoUpdate` schema
- `DELETE /api/todos/{todo_id}`: Delete a specific todo item by ID
## Examples
### Create a Todo
```bash
curl -X 'POST' \
'http://localhost:8000/api/todos' \
-H 'Content-Type: application/json' \
-d '{
"title": "Buy groceries",
"description": "Milk, eggs, bread",
"completed": false
}'
```
### Get All Todos
```bash
curl -X 'GET' 'http://localhost:8000/api/todos'
```
### Get Completed Todos
```bash
curl -X 'GET' 'http://localhost:8000/api/todos?completed=true'
```
### Update a Todo
```bash
curl -X 'PUT' \
'http://localhost:8000/api/todos/1' \
-H 'Content-Type: application/json' \
-d '{
"completed": true
}'
```
### Delete a Todo
```bash
curl -X 'DELETE' 'http://localhost:8000/api/todos/1'
```
## License
MIT

102
alembic.ini Normal file
View File

@ -0,0 +1,102 @@
# 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
# 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
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

View File

9
app/api/routes/health.py Normal file
View File

@ -0,0 +1,9 @@
from fastapi import APIRouter, status
router = APIRouter(tags=["health"])
@router.get("/health", status_code=status.HTTP_200_OK)
async def health_check():
"""Health check endpoint to verify the application is running."""
return {"status": "healthy"}

88
app/api/routes/todo.py Normal file
View File

@ -0,0 +1,88 @@
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from app.crud import todo as todo_crud
from app.db.session import get_db
from app.schemas.todo import Todo, TodoCreate, TodoList, TodoUpdate
router = APIRouter(tags=["todos"])
@router.get("/todos", response_model=TodoList)
async def get_todos(
skip: int = Query(0, ge=0, description="Number of items to skip"),
limit: int = Query(100, ge=1, le=100, description="Number of items to return"),
completed: Optional[bool] = Query(None, description="Filter by completion status"),
db: Session = Depends(get_db),
):
"""
Get a list of todo items with pagination and optional filtering by completion status.
"""
todos = todo_crud.get_todos(db, skip=skip, limit=limit, completed=completed)
count = todo_crud.get_todos_count(db, completed=completed)
return {"items": todos, "count": count}
@router.post("/todos", response_model=Todo, status_code=status.HTTP_201_CREATED)
async def create_todo(
todo: TodoCreate,
db: Session = Depends(get_db),
):
"""
Create a new todo item.
"""
return todo_crud.create_todo(db, todo)
@router.get("/todos/{todo_id}", response_model=Todo)
async def get_todo(
todo_id: int,
db: Session = Depends(get_db),
):
"""
Get a specific todo item by ID.
"""
db_todo = todo_crud.get_todo(db, todo_id)
if db_todo is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Todo with ID {todo_id} not found",
)
return db_todo
@router.put("/todos/{todo_id}", response_model=Todo)
async def update_todo(
todo_id: int,
todo: TodoUpdate,
db: Session = Depends(get_db),
):
"""
Update a specific todo item by ID.
"""
db_todo = todo_crud.update_todo(db, todo_id, todo)
if db_todo is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Todo with ID {todo_id} not found",
)
return db_todo
@router.delete("/todos/{todo_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
async def delete_todo(
todo_id: int,
db: Session = Depends(get_db),
):
"""
Delete a specific todo item by ID.
"""
result = todo_crud.delete_todo(db, todo_id)
if result is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Todo with ID {todo_id} not found",
)
return None

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

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

@ -0,0 +1,30 @@
from pathlib import Path
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
# Project settings
PROJECT_NAME: str = "Todo List API"
PROJECT_DESCRIPTION: str = "A simple Todo List API built with FastAPI and SQLite"
PROJECT_VERSION: str = "0.1.0"
# API settings
API_PREFIX: str = "/api"
HOST: str = "0.0.0.0"
PORT: int = 8000
DEBUG: bool = True
# CORS settings
CORS_ORIGINS: list[str] = ["*"]
# Database settings
DB_DIR: Path = Path("/app") / "storage" / "db"
DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite"
class Config:
env_file = ".env"
case_sensitive = True
settings = Settings()

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

@ -0,0 +1,17 @@
from app.crud.todo import (
create_todo,
delete_todo,
get_todo,
get_todos,
get_todos_count,
update_todo,
)
__all__ = [
"create_todo",
"delete_todo",
"get_todo",
"get_todos",
"get_todos_count",
"update_todo",
]

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

@ -0,0 +1,72 @@
from typing import Optional, Union
from sqlalchemy import desc
from sqlalchemy.orm import Session
from app.models.todo import Todo
from app.schemas.todo import TodoCreate, TodoUpdate
def get_todo(db: Session, todo_id: int) -> Optional[Todo]:
"""Get a todo item by its ID."""
return db.query(Todo).filter(Todo.id == todo_id).first()
def get_todos(
db: Session,
skip: int = 0,
limit: int = 100,
completed: Optional[bool] = None
) -> list[Todo]:
"""Get a list of todo items, optionally filtered by completion status."""
query = db.query(Todo)
if completed is not None:
query = query.filter(Todo.completed == completed)
return query.order_by(desc(Todo.created_at)).offset(skip).limit(limit).all()
def get_todos_count(db: Session, completed: Optional[bool] = None) -> int:
"""Get the total count of todo items, optionally filtered by completion status."""
query = db.query(Todo)
if completed is not None:
query = query.filter(Todo.completed == completed)
return query.count()
def create_todo(db: Session, todo: TodoCreate) -> Todo:
"""Create a new todo item."""
db_todo = Todo(**todo.model_dump())
db.add(db_todo)
db.commit()
db.refresh(db_todo)
return db_todo
def update_todo(db: Session, todo_id: int, todo: TodoUpdate) -> Optional[Todo]:
"""Update an existing todo item."""
db_todo = get_todo(db, todo_id)
if db_todo is None:
return None
update_data = todo.model_dump(exclude_unset=True)
for field, value in update_data.items():
setattr(db_todo, field, value)
db.commit()
db.refresh(db_todo)
return db_todo
def delete_todo(db: Session, todo_id: int) -> Union[bool, None]:
"""Delete a todo item by its ID."""
db_todo = get_todo(db, todo_id)
if db_todo is None:
return None
db.delete(db_todo)
db.commit()
return True

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

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

@ -0,0 +1,30 @@
from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from app.core.config import settings
# Ensure directory exists
Path(settings.DB_DIR).mkdir(parents=True, exist_ok=True)
SQLALCHEMY_DATABASE_URL = f"sqlite:///{settings.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()
def get_db():
"""Dependency for getting DB 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"]

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

@ -0,0 +1,17 @@
from sqlalchemy import Boolean, Column, DateTime, Integer, String, Text
from sqlalchemy.sql import func
from app.db.session import Base
class Todo(Base):
"""SQLAlchemy Todo model."""
__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(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())

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

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

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

@ -0,0 +1,50 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
class TodoBase(BaseModel):
"""Base Todo schema with common attributes."""
title: str = Field(..., min_length=1, max_length=100, description="Title of the todo item")
description: Optional[str] = Field(None, description="Detailed 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."""
title: Optional[str] = Field(
None,
min_length=1,
max_length=100,
description="Title of the todo item"
)
description: Optional[str] = Field(None, description="Detailed description of the todo item")
completed: Optional[bool] = Field(None, description="Whether the todo item is completed")
class TodoInDB(TodoBase):
"""Schema for a todo item as stored in the database."""
id: int
created_at: datetime
updated_at: datetime
class Config:
"""Pydantic config."""
orm_mode = True
class Todo(TodoInDB):
"""Schema for a todo item returned by the API."""
pass
class TodoList(BaseModel):
"""Schema for a list of todo items."""
items: list[Todo]
count: int

37
main.py Normal file
View File

@ -0,0 +1,37 @@
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.routes.health import router as health_router
from app.api.routes.todo import router as todo_router
from app.core.config import settings
app = FastAPI(
title=settings.PROJECT_NAME,
description=settings.PROJECT_DESCRIPTION,
version=settings.PROJECT_VERSION,
openapi_url=f"{settings.API_PREFIX}/openapi.json",
docs_url="/docs",
redoc_url="/redoc",
)
# Set CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
app.include_router(todo_router, prefix=settings.API_PREFIX)
app.include_router(health_router, prefix=settings.API_PREFIX)
if __name__ == "__main__":
uvicorn.run(
"main:app",
host=settings.HOST,
port=settings.PORT,
reload=settings.DEBUG,
)

72
migrations/env.py Normal file
View File

@ -0,0 +1,72 @@
import os
import sys
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
# Add the parent directory to sys.path
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
# Import the SQLAlchemy models
import app.models.todo # noqa
from app.db.session import Base
# This is the Alembic Config object
config = context.config
# Interpret the config file for Python logging
fileConfig(config.config_file_name)
# Get SQLAlchemy metadata object
target_metadata = Base.metadata
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.
"""
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, # Enable batch mode for SQLite
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

26
migrations/script.py.mako Normal file
View File

@ -0,0 +1,26 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}

View File

@ -0,0 +1,47 @@
"""Create todos table
Revision ID: 001
Revises:
Create Date: 2023-05-21 12:00:00.000000
"""
from collections.abc import Sequence
from typing import Union
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = '001'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
'todos',
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('completed', sa.Boolean(), nullable=True, default=False),
sa.Column(
'created_at',
sa.DateTime(timezone=True),
server_default=sa.text('(CURRENT_TIMESTAMP)'),
nullable=True
),
sa.Column(
'updated_at',
sa.DateTime(timezone=True),
server_default=sa.text('(CURRENT_TIMESTAMP)'),
nullable=True
),
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')

View File

23
pyproject.toml Normal file
View File

@ -0,0 +1,23 @@
[tool.ruff]
target-version = "py39"
line-length = 100
[tool.ruff.lint]
select = [
"E", # pycodestyle errors
"F", # pyflakes
"I", # isort
"C4", # flake8-comprehensions
"B", # flake8-bugbear
"UP", # pyupgrade
]
ignore = [
"B008", # do not perform function calls in argument defaults (FastAPI dependency injection)
]
[tool.ruff.lint.isort]
known-third-party = ["fastapi", "pydantic", "sqlalchemy"]
[tool.ruff.lint.flake8-quotes]
docstring-quotes = "double"
inline-quotes = "double"

7
requirements.txt Normal file
View File

@ -0,0 +1,7 @@
fastapi>=0.95.0
uvicorn>=0.21.1
sqlalchemy>=2.0.0
pydantic>=2.0.0
alembic>=1.10.0
python-dotenv>=1.0.0
ruff>=0.0.262