Initial Todo app backend implementation with FastAPI and SQLite

- Created FastAPI application structure
- Added Todo model and CRUD operations
- Added database integration with SQLAlchemy
- Added migrations with Alembic
- Added health endpoint
- Added API documentation with Swagger UI and ReDoc
This commit is contained in:
Automated Action 2025-05-16 00:35:49 +00:00
parent a87bc726cd
commit 8e26cae20e
21 changed files with 624 additions and 2 deletions

43
.gitignore vendored Normal file
View File

@ -0,0 +1,43 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# Virtual environment
venv/
env/
ENV/
# IDE
.idea/
.vscode/
*.swp
*.swo
# SQLite
*.sqlite
*.db
# Logs
*.log
# Local environment variables
.env
.env.local

View File

@ -1,3 +1,55 @@
# FastAPI Application # SimpleTodoApp API
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. A FastAPI-based backend for a simple Todo application with SQLite database.
## Features
- Create, read, update, and delete Todo items
- Health check endpoint
- SQLite database with SQLAlchemy ORM
- Database migrations with Alembic
- Comprehensive API documentation with Swagger UI and ReDoc
## Project Structure
```
simpletodoapp/
├── api/ # API-related code
│ ├── crud/ # CRUD operations
│ ├── routers/ # API endpoints
│ └── schemas/ # Pydantic models for request/response validation
├── db/ # Database-related code
│ ├── database.py # Database connection and session
│ └── models.py # SQLAlchemy models
├── migrations/ # Alembic migrations
├── alembic.ini # Alembic configuration
├── main.py # FastAPI application entry point
└── requirements.txt # Project dependencies
```
## Installation & Setup
1. Clone this repository
2. Install dependencies:
```
pip install -r requirements.txt
```
3. Run the application:
```
uvicorn main:app --reload
```
## API Documentation
Once the server is running, you can access:
- Swagger UI documentation at `/docs`
- ReDoc documentation at `/redoc`
## API Endpoints
- `GET /health` - Health check endpoint
- `GET /api/todos` - List all todos
- `GET /api/todos/{id}` - Get a single todo by ID
- `POST /api/todos` - Create a new todo
- `PATCH /api/todos/{id}` - Update a todo (partial update)
- `DELETE /api/todos/{id}` - Delete a todo

82
alembic.ini Normal file
View File

@ -0,0 +1,82 @@
# 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
# SQLite with absolute path
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

1
api/__init__.py Normal file
View File

@ -0,0 +1 @@
# This file makes the api directory a Python package

1
api/crud/__init__.py Normal file
View File

@ -0,0 +1 @@
# This file makes the crud directory a Python package

61
api/crud/todo.py Normal file
View File

@ -0,0 +1,61 @@
from sqlalchemy.orm import Session
from typing import List, Optional
from db.models import Todo
from api.schemas.todo import TodoCreate, TodoUpdate
def get_todos(db: Session, skip: int = 0, limit: int = 100) -> List[Todo]:
"""
Get all todos with pagination
"""
return db.query(Todo).offset(skip).limit(limit).all()
def get_todo(db: Session, todo_id: int) -> Optional[Todo]:
"""
Get a specific todo by ID
"""
return db.query(Todo).filter(Todo.id == todo_id).first()
def create_todo(db: Session, todo: TodoCreate) -> Todo:
"""
Create a new todo
"""
db_todo = Todo(**todo.dict())
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
"""
db_todo = get_todo(db, todo_id)
if db_todo is None:
return None
# Update only provided fields
todo_data = todo.dict(exclude_unset=True)
for key, value in todo_data.items():
setattr(db_todo, key, value)
db.commit()
db.refresh(db_todo)
return db_todo
def delete_todo(db: Session, todo_id: int) -> bool:
"""
Delete a todo by ID
Returns True if the todo was deleted, False if it didn't exist
"""
db_todo = get_todo(db, todo_id)
if db_todo is None:
return False
db.delete(db_todo)
db.commit()
return True

1
api/routers/__init__.py Normal file
View File

@ -0,0 +1 @@
# This file makes the routers directory a Python package

View File

@ -0,0 +1,34 @@
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
import platform
import sys
from db.database import get_db
from api.schemas.health import HealthResponse
router = APIRouter()
@router.get("/health", response_model=HealthResponse)
def health_check(db: Session = Depends(get_db)):
"""
Health check endpoint that verifies the API is running correctly
and can connect to the database
"""
# Verify database connection
try:
# Just run a simple query to verify DB connection
db.execute("SELECT 1")
db_status = "healthy"
except Exception as e:
db_status = f"unhealthy: {str(e)}"
return HealthResponse(
status="healthy",
version="0.1.0",
details={
"database": db_status,
"python_version": sys.version,
"platform": platform.platform(),
}
)

View File

@ -0,0 +1,59 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from db.database import get_db
from api.schemas.todo import TodoCreate, TodoResponse, TodoUpdate
from api.crud.todo import get_todos, get_todo, create_todo, update_todo, delete_todo
router = APIRouter()
@router.get("/", response_model=List[TodoResponse])
def read_todos(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
"""
Get all todos with pagination
"""
todos = get_todos(db, skip=skip, limit=limit)
return todos
@router.get("/{todo_id}", response_model=TodoResponse)
def read_todo(todo_id: int, db: Session = Depends(get_db)):
"""
Get a specific todo by ID
"""
db_todo = get_todo(db, todo_id=todo_id)
if db_todo is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Todo not found")
return db_todo
@router.post("/", response_model=TodoResponse, status_code=status.HTTP_201_CREATED)
def create_new_todo(todo: TodoCreate, db: Session = Depends(get_db)):
"""
Create a new todo
"""
return create_todo(db=db, todo=todo)
@router.patch("/{todo_id}", response_model=TodoResponse)
def update_existing_todo(todo_id: int, todo: TodoUpdate, db: Session = Depends(get_db)):
"""
Update an existing todo (partial update)
"""
db_todo = update_todo(db=db, todo_id=todo_id, todo=todo)
if db_todo is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Todo not found")
return db_todo
@router.delete("/{todo_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_existing_todo(todo_id: int, db: Session = Depends(get_db)):
"""
Delete a todo
"""
success = delete_todo(db=db, todo_id=todo_id)
if not success:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Todo not found")
return None

1
api/schemas/__init__.py Normal file
View File

@ -0,0 +1 @@
# This file makes the schemas directory a Python package

9
api/schemas/health.py Normal file
View File

@ -0,0 +1,9 @@
from pydantic import BaseModel
from typing import Dict, Any
class HealthResponse(BaseModel):
"""Response schema for the health check endpoint"""
status: str
version: str
details: Dict[str, Any]

34
api/schemas/todo.py Normal file
View File

@ -0,0 +1,34 @@
from pydantic import BaseModel, Field
from typing import Optional
from datetime import datetime
class TodoBase(BaseModel):
"""Base Todo schema with common attributes"""
title: str = Field(..., min_length=1, max_length=100, description="Title of the todo")
description: Optional[str] = Field(None, max_length=500, description="Detailed description of the todo")
completed: bool = Field(False, description="Whether the todo is completed")
class TodoCreate(TodoBase):
"""Schema for creating a new todo"""
pass
class TodoUpdate(BaseModel):
"""Schema for updating an existing todo, all fields are optional"""
title: Optional[str] = Field(None, min_length=1, max_length=100, description="Title of the todo")
description: Optional[str] = Field(None, max_length=500, description="Detailed description of the todo")
completed: Optional[bool] = Field(None, description="Whether the todo is completed")
class TodoResponse(TodoBase):
"""Schema for todo response that includes database fields"""
id: int
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
"""ORM mode config for the TodoResponse schema"""
orm_mode = True
from_attributes = True

39
db/database.py Normal file
View File

@ -0,0 +1,39 @@
from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# Create database directory if it doesn't exist
DB_DIR = Path("/app") / "storage" / "db"
DB_DIR.mkdir(parents=True, exist_ok=True)
# Database URL
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
# Create engine
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False}
)
# Create session factory
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# Create base class for models
Base = declarative_base()
def get_db():
"""
Get database session dependency
"""
db = SessionLocal()
try:
yield db
finally:
db.close()
def create_tables():
"""
Create all tables defined in models
"""
Base.metadata.create_all(bind=engine)

17
db/models.py Normal file
View File

@ -0,0 +1,17 @@
from sqlalchemy import Column, Integer, String, Boolean, DateTime
from sqlalchemy.sql import func
from .database import Base
class Todo(Base):
"""
Todo model representing a task to be done
"""
__tablename__ = "todos"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, nullable=False)
description = Column(String, nullable=True)
completed = Column(Boolean, default=False)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())

32
main.py Normal file
View File

@ -0,0 +1,32 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from api.routers import todo_router, health_router
from db.database import create_tables
app = FastAPI(
title="SimpleTodoApp API",
description="API for a simple todo application",
version="0.1.0",
)
# CORS settings
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # For development, in production specify your frontend domain
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
app.include_router(todo_router.router, prefix="/api/todos", tags=["todos"])
app.include_router(health_router.router, tags=["health"])
# Create database tables on startup
@app.on_event("startup")
async def startup():
create_tables()
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.

79
migrations/env.py Normal file
View File

@ -0,0 +1,79 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from db.models import Base
# 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 myapp import mymodel
# target_metadata = mymodel.Base.metadata
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:
context.configure(
connection=connection, target_metadata=target_metadata
)
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,35 @@
"""Initial create todos table
Revision ID: 1_initial_create_todos_table
Revises:
Create Date: 2023-09-20 12:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1_initial_create_todos_table'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'todos',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=False),
sa.Column('description', sa.String(), nullable=True),
sa.Column('completed', sa.Boolean(), default=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.func.now()),
sa.Column('updated_at', sa.DateTime(timezone=True), onupdate=sa.func.now()),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_todos_id'), 'todos', ['id'], unique=False)
def downgrade():
op.drop_index(op.f('ix_todos_id'), table_name='todos')
op.drop_table('todos')

8
pyproject.toml Normal file
View File

@ -0,0 +1,8 @@
[tool.ruff]
line-length = 100
target-version = "py39"
select = ["E", "F", "I", "W", "N", "B", "A", "COM", "C4", "UP", "S", "BLE", "T10", "ISC", "G"]
ignore = []
[tool.ruff.isort]
known-third-party = ["fastapi", "sqlalchemy", "pydantic", "alembic"]

9
requirements.txt Normal file
View File

@ -0,0 +1,9 @@
fastapi>=0.101.0
uvicorn>=0.23.2
sqlalchemy>=2.0.19
pydantic>=2.1.1
alembic>=1.11.1
ruff>=0.0.280
python-dotenv>=1.0.0
python-multipart>=0.0.6
pathlib>=1.0.1