Create Simple Todo API with FastAPI and SQLite

- Set up FastAPI project structure
- Configure SQLAlchemy with SQLite
- Create Todo model and schemas
- Implement CRUD operations
- Add API endpoints for Todo management
- Configure Alembic for database migrations
- Add health check endpoint
- Add comprehensive documentation
This commit is contained in:
Automated Action 2025-05-17 20:16:30 +00:00
parent 468e670783
commit bf1393d643
16 changed files with 673 additions and 2 deletions

120
README.md
View File

@ -1,3 +1,119 @@
# FastAPI Application
# SimpleTodoAPI
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A simple FastAPI-based RESTful API for managing todo items with SQLite database.
## Features
- Create, read, update, and delete todo items
- SQLite database with SQLAlchemy ORM
- Database migrations with Alembic
- API documentation with Swagger UI and ReDoc
- Health check endpoint
- Input validation with Pydantic
## Project Structure
```
.
├── alembic.ini # Alembic configuration
├── app # Application package
│ ├── api # API endpoints
│ │ └── routes # API routes
│ │ ├── health.py # Health check endpoint
│ │ └── todo.py # Todo endpoints
│ ├── core # Core module
│ │ └── config.py # Application configuration
│ ├── crud # CRUD operations
│ │ └── todo.py # Todo CRUD operations
│ ├── db # Database module
│ │ ├── base.py # Base DB class and model imports
│ │ └── session.py # Database session management
│ ├── 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
│ ├── script.py.mako # Migration script template
│ └── versions # Migration versions
│ └── 20231031_010000_create_todos_table.py # Initial migration
└── requirements.txt # Project dependencies
```
## API Endpoints
- **GET /health** - Health check endpoint
- **GET /api/v1/todos/** - List all todos
- **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
## API Documentation
When the server is running, you can access:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
## Requirements
- Python 3.7+
- FastAPI
- Uvicorn
- SQLAlchemy
- Alembic
- Pydantic
- Ruff (for linting)
## Installation
```bash
# Clone the repository
git clone <repository-url>
# Change to the project directory
cd simpletodoapi
# Install dependencies
pip install -r requirements.txt
```
## Database Setup
```bash
# Apply database migrations
alembic upgrade head
```
## Running the Application
```bash
# Start the server
uvicorn main:app --reload
```
The API will be available at http://localhost:8000.
## Development
### Creating new migrations
```bash
# Generate a new migration
alembic revision -m "description of changes"
```
### Linting
```bash
# Run ruff linter
ruff check .
# Run ruff formatter
ruff format .
```
## License
This project is licensed under the MIT License.

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 = %%(year)d%%(month).2d%%(day).2d_%%(hour).2d%%(minute).2d%%(second).2d_%%(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 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
# 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

View File

@ -0,0 +1,4 @@
from app.api.routes.todo import router as todo_router
from app.api.routes.health import router as health_router
__all__ = ["todo_router", "health_router"]

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

@ -0,0 +1,25 @@
from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session
from app.db.session import get_db
router = APIRouter()
@router.get("/health", status_code=status.HTTP_200_OK)
def health_check(db: Session = Depends(get_db)):
"""
Health check endpoint to verify API is running and database is accessible
"""
try:
# Execute a simple query to check if database is accessible
db.execute("SELECT 1")
return {
"status": "healthy",
"message": "API is running and database is accessible",
}
except Exception as e:
return {
"status": "unhealthy",
"message": f"API is running but database is not accessible: {str(e)}",
}

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

@ -0,0 +1,54 @@
from typing import List
from fastapi import APIRouter, Depends, HTTPException, 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 TodoCreate, TodoResponse, TodoUpdate
router = APIRouter()
@router.get("/todos/", response_model=List[TodoResponse])
def read_todos(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
"""Get all todos with optional pagination"""
todos = todo_crud.get_todos(db, skip=skip, limit=limit)
return todos
@router.post(
"/todos/", response_model=TodoResponse, status_code=status.HTTP_201_CREATED
)
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
"""Create a new todo"""
return todo_crud.create_todo(db=db, todo=todo)
@router.get("/todos/{todo_id}", response_model=TodoResponse)
def read_todo(todo_id: int, db: Session = Depends(get_db)):
"""Get a specific todo by ID"""
db_todo = todo_crud.get_todo(db, todo_id=todo_id)
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
return db_todo
@router.put("/todos/{todo_id}", response_model=TodoResponse)
def update_todo(todo_id: int, todo: TodoUpdate, db: Session = Depends(get_db)):
"""Update a todo by ID"""
db_todo = todo_crud.update_todo(db, todo_id=todo_id, todo=todo)
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
return db_todo
@router.delete(
"/todos/{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 by ID"""
success = todo_crud.delete_todo(db, todo_id=todo_id)
if not success:
raise HTTPException(status_code=404, detail="Todo not found")
return None

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

@ -0,0 +1,31 @@
from pathlib import Path
from typing import List
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
# Project settings
PROJECT_NAME: str = "SimpleTodoAPI"
PROJECT_DESCRIPTION: str = "A simple FastAPI Todo API with SQLite"
PROJECT_VERSION: str = "0.1.0"
# CORS
CORS_ORIGINS: List[str] = ["*"]
# Database
DB_DIR: Path = Path("/app") / "storage" / "db"
SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite"
model_config = SettingsConfigDict(
case_sensitive=True,
env_file=".env",
env_file_encoding="utf-8",
)
# Create instance of Settings
settings = Settings()
# Ensure database directory exists
settings.DB_DIR.mkdir(parents=True, exist_ok=True)

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

@ -0,0 +1,53 @@
from typing import List, Optional
from sqlalchemy.orm import Session
from app.models.todo import Todo
from app.schemas.todo import TodoCreate, TodoUpdate
def get_todos(db: Session, skip: int = 0, limit: int = 100) -> List[Todo]:
"""Get all todos with optional pagination"""
return db.query(Todo).offset(skip).limit(limit).all()
def get_todo(db: Session, todo_id: int) -> Optional[Todo]:
"""Get a single 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.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 a todo"""
db_todo = get_todo(db, todo_id)
if not db_todo:
return None
# Only update fields that are present in the update schema
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
def delete_todo(db: Session, todo_id: int) -> bool:
"""Delete a todo"""
db_todo = get_todo(db, todo_id)
if not db_todo:
return False
db.delete(db_todo)
db.commit()
return True

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

@ -0,0 +1,5 @@
from app.db.session import Base
from app.models.todo import Todo
# Import all models here that should be included in the database
__all__ = ["Todo", "Base"]

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

@ -0,0 +1,26 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from app.core.config import settings
# Create engine
engine = create_engine(
settings.SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False}, # SQLite specific
)
# Create SessionLocal class
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# Create Base class
Base = declarative_base()
def get_db():
"""Dependency for getting DB session"""
db = SessionLocal()
try:
yield db
finally:
db.close()

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

@ -0,0 +1,19 @@
from sqlalchemy import Column, Integer, String, Boolean, DateTime, func
from sqlalchemy.sql import expression
from app.db.session import Base
class Todo(Base):
"""Todo model for database representation"""
__tablename__ = "todos"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, nullable=False)
description = Column(String, nullable=True)
completed = Column(Boolean, server_default=expression.false(), nullable=False)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
)

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

@ -0,0 +1,45 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel
class TodoBase(BaseModel):
"""Base schema for Todo"""
title: str
description: Optional[str] = None
completed: bool = False
class TodoCreate(TodoBase):
"""Schema for creating a new Todo"""
pass
class TodoUpdate(BaseModel):
"""Schema for updating a Todo (all fields optional)"""
title: Optional[str] = None
description: Optional[str] = None
completed: Optional[bool] = None
class TodoInDB(TodoBase):
"""Schema for Todo stored in DB"""
id: int
created_at: datetime
updated_at: datetime
class Config:
"""Configure pydantic model"""
from_attributes = True
class TodoResponse(TodoInDB):
"""Schema for Todo response"""
pass

29
main.py Normal file
View File

@ -0,0 +1,29 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.routes import todo_router, health_router
from app.core.config import settings
app = FastAPI(
title=settings.PROJECT_NAME,
description=settings.PROJECT_DESCRIPTION,
version=settings.PROJECT_VERSION,
)
# CORS configuration
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
app.include_router(health_router, tags=["health"])
app.include_router(todo_router, prefix="/api/v1", tags=["todos"])
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

95
migrations/env.py Normal file
View File

@ -0,0 +1,95 @@
import os
import sys
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# Append the app directory to sys.path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Import the Base model
from app.db.base import Base
from app.core.config import settings
# 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)
# Set the SQLAlchemy URL from settings
config.set_main_option("sqlalchemy.url", settings.SQLALCHEMY_DATABASE_URL)
# add your model's MetaData object here
# for 'autogenerate' support
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"},
# For SQLite, we need to support column and table alterations
render_as_batch=url.startswith("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:
# For SQLite, we need to support column and table alterations
is_sqlite = connection.dialect.name == "sqlite"
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=is_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,50 @@
"""create todos table
Revision ID: 20231031_010000
Revises:
Create Date: 2023-10-31 01:00:00
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "20231031_010000"
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(), nullable=False),
sa.Column("description", sa.String(), nullable=True),
sa.Column(
"completed", sa.Boolean(), server_default=sa.text("0"), nullable=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")

8
requirements.txt Normal file
View File

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