Create barebones Todo API with FastAPI and SQLite

This commit is contained in:
Automated Action 2025-06-09 13:37:02 +00:00
parent 71440ba59e
commit e3a20d9c4b
24 changed files with 584 additions and 2 deletions

View File

@ -1,3 +1,93 @@
# FastAPI Application
# Barebones Todo API
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A simple, lightweight RESTful API for managing todo items built with FastAPI and SQLite.
## Features
- Create, read, update, and delete todo items
- Filter todos by completion status
- SQLite database for data persistence
- FastAPI for high performance and automatic API documentation
- Alembic for database migrations
## Project Structure
```
├── app/
│ ├── api/ # API routes
│ │ └── v1/ # API version 1
│ │ └── endpoints/
│ │ └── todos.py
│ ├── core/ # Core application code
│ │ └── config.py # Configuration settings
│ ├── db/ # Database setup
│ │ ├── base.py
│ │ ├── base_class.py
│ │ └── session.py
│ ├── models/ # SQLAlchemy models
│ │ └── todo.py
│ └── schemas/ # Pydantic schemas
│ └── todo.py
├── migrations/ # Alembic migrations
├── storage/ # Storage directory
│ └── db/ # Database storage
├── alembic.ini # Alembic configuration
├── main.py # Application entry point
└── requirements.txt # Project dependencies
```
## Installation
1. Clone the repository
2. Install dependencies
```bash
pip install -r requirements.txt
```
3. Apply database migrations
```bash
alembic upgrade head
```
## Running the API
Start the API server with:
```bash
uvicorn main:app --reload
```
The API will be available at http://localhost:8000
## API Documentation
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
- OpenAPI JSON: http://localhost:8000/openapi.json
## API Endpoints
### Base URL
- `GET /` - Returns basic API information
- `GET /health` - Health check endpoint
### Todo Endpoints
- `GET /api/v1/todos` - List all todos (with optional filters)
- `POST /api/v1/todos` - Create a new todo
- `GET /api/v1/todos/{todo_id}` - Retrieve a specific todo
- `PUT /api/v1/todos/{todo_id}` - Update a todo
- `DELETE /api/v1/todos/{todo_id}` - Delete a todo
## Database Migrations
This project uses Alembic for database migrations. To create a new migration after model changes:
```bash
alembic revision --autogenerate -m "Description of changes"
```
To apply migrations:
```bash
alembic upgrade head
```

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 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
# 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
app/__init__.py Normal file
View File

@ -0,0 +1 @@
# app package initialization

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

@ -0,0 +1 @@
# API package initialization

1
app/api/v1/__init__.py Normal file
View File

@ -0,0 +1 @@
# API v1 package initialization

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

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

@ -0,0 +1 @@
# Endpoints package initialization

View File

@ -0,0 +1,92 @@
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.db.session import get_db
from app.models.todo import Todo as TodoModel
from app.schemas.todo import Todo, TodoCreate, TodoUpdate
router = APIRouter()
@router.get("/", response_model=List[Todo])
def read_todos(
skip: int = 0,
limit: int = 100,
completed: Optional[bool] = None,
db: Session = Depends(get_db)
):
"""
Retrieve todos with optional filtering by completion status.
"""
if completed is not None:
return db.query(TodoModel).filter(TodoModel.completed == completed).offset(skip).limit(limit).all()
return db.query(TodoModel).offset(skip).limit(limit).all()
@router.post("/", response_model=Todo, status_code=status.HTTP_201_CREATED)
def create_todo(
todo: TodoCreate,
db: Session = Depends(get_db)
):
"""
Create a new todo item.
"""
db_todo = TodoModel(**todo.model_dump())
db.add(db_todo)
db.commit()
db.refresh(db_todo)
return db_todo
@router.get("/{todo_id}", response_model=Todo)
def read_todo(
todo_id: int,
db: Session = Depends(get_db)
):
"""
Get a specific todo by ID.
"""
db_todo = db.query(TodoModel).filter(TodoModel.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=Todo)
def update_todo(
todo_id: int,
todo: TodoUpdate,
db: Session = Depends(get_db)
):
"""
Update a todo item.
"""
db_todo = db.query(TodoModel).filter(TodoModel.id == todo_id).first()
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
update_data = todo.model_dump(exclude_unset=True)
for key, value in update_data.items():
setattr(db_todo, key, value)
db.add(db_todo)
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(TodoModel).filter(TodoModel.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

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

@ -0,0 +1 @@
# Core package initialization

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

@ -0,0 +1,28 @@
from pathlib import Path
from pydantic import field_validator
from pydantic_settings import BaseSettings
# Build paths
BASE_DIR = Path(__file__).resolve().parent.parent.parent
class Settings(BaseSettings):
PROJECT_NAME: str = "Barebones Todo API"
API_V1_STR: str = "/api/v1"
# SQLite Database settings
DB_DIR: Path = BASE_DIR / "storage" / "db"
SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite"
@field_validator("SQLALCHEMY_DATABASE_URL")
def validate_db_url(cls, v, values):
# Ensure directory exists
db_dir = values.data.get("DB_DIR")
if db_dir:
db_dir.mkdir(parents=True, exist_ok=True)
return v
class Config:
env_file = ".env"
case_sensitive = True
settings = Settings()

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

@ -0,0 +1 @@
# Database package initialization

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

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

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

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

@ -0,0 +1,24 @@
from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# Ensure directory exists
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)
# Dependency to get DB session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

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

@ -0,0 +1 @@
# Models package initialization

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

@ -0,0 +1,12 @@
from datetime import datetime
from sqlalchemy import Boolean, Column, Integer, String, DateTime
from app.db.base_class import Base
class Todo(Base):
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
description = Column(String, nullable=True)
completed = Column(Boolean, default=False)
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

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

@ -0,0 +1,6 @@
# Schemas package initialization
from app.schemas.todo import Todo as Todo
from app.schemas.todo import TodoCreate as TodoCreate
from app.schemas.todo import TodoUpdate as TodoUpdate
__all__ = ["Todo", "TodoCreate", "TodoUpdate"]

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

@ -0,0 +1,32 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel
# Shared properties
class TodoBase(BaseModel):
title: str
description: Optional[str] = None
completed: bool = False
# Properties to receive on todo creation
class TodoCreate(TodoBase):
pass
# Properties to receive on todo update
class TodoUpdate(TodoBase):
title: Optional[str] = None
completed: Optional[bool] = None
# 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

40
main.py Normal file
View File

@ -0,0 +1,40 @@
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,
openapi_url="/openapi.json",
version="0.1.0",
)
# Set up CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include API router
app.include_router(api_router)
# Root endpoint
@app.get("/")
async def root():
return {
"title": settings.PROJECT_NAME,
"docs": "/docs",
"health": "/health"
}
# Health check endpoint
@app.get("/health")
async def health_check():
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.

74
migrations/env.py Normal file
View File

@ -0,0 +1,74 @@
import os
import sys
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# Add the project root directory to the Python path so we can import app
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Import Base from the app
from app.db.base import Base # noqa
# This is the Alembic Config object
config = context.config
# Interpret the config file for Python logging
fileConfig(config.config_file_name)
# Import all models for Alembic to detect
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, # Required for SQLite to handle ALTER TABLE operations properly
)
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,39 @@
"""Initial todos table
Revision ID: 001
Revises:
Create Date: 2023-09-20
"""
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(
'todo',
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, nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
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 todos table
op.drop_index(op.f('ix_todo_title'), table_name='todo')
op.drop_index(op.f('ix_todo_id'), table_name='todo')
op.drop_table('todo')

7
requirements.txt Normal file
View File

@ -0,0 +1,7 @@
fastapi>=0.103.1
uvicorn>=0.23.2
sqlalchemy>=2.0.20
alembic>=1.12.0
pydantic>=2.3.0
python-dotenv>=1.0.0
ruff>=0.0.290