Create simple Todo API with FastAPI and SQLite

This commit is contained in:
Automated Action 2025-05-17 03:24:28 +00:00
parent 4e5a9116ec
commit cd40319cde
19 changed files with 719 additions and 2 deletions

View File

@ -1,3 +1,78 @@
# FastAPI Application # Simple Todo App
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. A simple Todo API built with FastAPI and SQLite.
## Features
- Create, read, update and delete Todo items
- Filter todos by completion status
- Health check endpoint to verify API and database status
- API documentation with Swagger UI and ReDoc
## Requirements
- Python 3.8+
- FastAPI
- SQLAlchemy
- Alembic (for database migrations)
- Uvicorn (ASGI server)
- SQLite
## Project Structure
```
.
├── alembic.ini # Alembic configuration file
├── app/ # Application package
│ ├── api/ # API endpoints
│ │ ├── deps.py # API dependencies
│ │ ├── health.py # Health check endpoint
│ │ └── v1/ # API version 1
│ │ ├── api.py # API router
│ │ └── endpoints/ # API endpoints by resource
│ │ └── todos.py # Todo CRUD operations
│ ├── core/ # Core modules
│ │ └── config.py # Application configuration
│ ├── db/ # Database related code
│ │ └── session.py # Database session
│ ├── models/ # SQLAlchemy models
│ │ └── todo.py # Todo model
│ ├── schemas/ # Pydantic schemas
│ │ └── todo.py # Todo schemas
│ └── storage/ # Storage directory
│ └── db/ # Database files
├── main.py # Application entry point
├── migrations/ # Alembic migrations
│ ├── env.py # Migration environment
│ ├── script.py.mako # Migration script template
│ └── versions/ # Migration versions
│ └── initial_migration.py # Initial migration
├── pyproject.toml # Project configuration for tools
└── requirements.txt # Python dependencies
```
## Quick Start
1. Clone the repository
2. Create a virtual environment: `python -m venv venv`
3. Activate the virtual environment: `source venv/bin/activate` (Linux/Mac) or `venv\Scripts\activate` (Windows)
4. Install dependencies: `pip install -r requirements.txt`
5. Run the application: `uvicorn main:app --reload`
The API will be available at http://localhost:8000
## API Documentation
Once the application is running, you can access:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
## API Endpoints
- **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
- **PATCH /api/v1/todos/{todo_id}**: Update a todo
- **DELETE /api/v1/todos/{todo_id}**: Delete a todo
- **GET /health**: Health check endpoint
- **GET /**: Root endpoint with welcome message

105
alembic.ini Normal file
View File

@ -0,0 +1,105 @@
# 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
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# 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

4
app/api/deps.py Normal file
View File

@ -0,0 +1,4 @@
from app.db.session import get_db
# Re-export the get_db dependency
db_dependency = get_db

26
app/api/health.py Normal file
View File

@ -0,0 +1,26 @@
from fastapi import APIRouter, Depends
from sqlalchemy import text
from sqlalchemy.orm import Session
from app.api.deps import db_dependency
router = APIRouter()
@router.get("/health")
def health_check(db: Session = Depends(db_dependency)):
"""
Health check endpoint to verify the API and database are working properly.
"""
try:
# Test database connection
db.execute(text("SELECT 1"))
db_status = "healthy"
except Exception:
db_status = "unhealthy"
return {
"status": "ok" if db_status == "healthy" else "error",
"api": "healthy",
"database": db_status
}

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()
api_router.include_router(todos.router, prefix="/todos", tags=["todos"])

View File

View File

@ -0,0 +1,105 @@
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.api.deps import db_dependency
from app.models.todo import Todo
from app.schemas.todo import Todo as TodoSchema
from app.schemas.todo import TodoCreate, TodoUpdate
router = APIRouter()
@router.get("/", response_model=List[TodoSchema])
def read_todos(
skip: int = 0,
limit: int = 100,
completed: Optional[bool] = None,
db: Session = Depends(db_dependency),
):
"""
Retrieve todos.
- **skip**: Number of records to skip for pagination
- **limit**: Maximum number of records to return
- **completed**: Filter by completion status (optional)
"""
query = db.query(Todo)
if completed is not None:
query = query.filter(Todo.completed == completed)
todos = query.offset(skip).limit(limit).all()
return todos
@router.post("/", response_model=TodoSchema, status_code=status.HTTP_201_CREATED)
def create_todo(
todo: TodoCreate,
db: Session = Depends(db_dependency),
):
"""
Create new todo.
"""
db_todo = Todo(**todo.model_dump())
db.add(db_todo)
db.commit()
db.refresh(db_todo)
return db_todo
@router.get("/{todo_id}", response_model=TodoSchema)
def read_todo(
todo_id: int,
db: Session = Depends(db_dependency),
):
"""
Get a specific todo by ID.
"""
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
return db_todo
@router.patch("/{todo_id}", response_model=TodoSchema)
def update_todo(
todo_id: int,
todo: TodoUpdate,
db: Session = Depends(db_dependency),
):
"""
Update a todo.
"""
db_todo = db.query(Todo).filter(Todo.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 field, value in update_data.items():
setattr(db_todo, field, value)
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(db_dependency),
):
"""
Delete a todo.
"""
db_todo = db.query(Todo).filter(Todo.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

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

@ -0,0 +1,15 @@
from pathlib import Path
# Project directories
BASE_DIR = Path("/projects/simpletodoapp-3hunrv")
APP_DIR = BASE_DIR / "app"
# Database
DB_DIR = Path("/app") / "storage" / "db"
DB_DIR.mkdir(parents=True, exist_ok=True)
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
# API settings
API_V1_STR = "/api/v1"
PROJECT_NAME = "Simple Todo App"

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

@ -0,0 +1,23 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from app.core.config import SQLALCHEMY_DATABASE_URL
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()

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

@ -0,0 +1,20 @@
from sqlalchemy import Boolean, Column, DateTime, Integer, String, Text
from sqlalchemy.sql import func
from app.db.session import Base
class Todo(Base):
"""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()
)

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

@ -0,0 +1,38 @@
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: 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 are optional"""
title: Optional[str] = Field(None, min_length=1, max_length=100)
description: Optional[str] = None
completed: Optional[bool] = None
class TodoInDB(TodoBase):
"""Schema for Todo as stored in the database"""
id: int
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True
class Todo(TodoInDB):
"""Schema for Todo responses"""
pass

41
main.py Normal file
View File

@ -0,0 +1,41 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.health import router as health_router
from app.api.v1.api import api_router
from app.core.config import API_V1_STR, PROJECT_NAME
from app.db.session import Base, engine
# Create tables if they don't exist
Base.metadata.create_all(bind=engine)
app = FastAPI(
title=PROJECT_NAME,
description="A simple Todo API built with FastAPI and SQLite",
version="0.1.0",
docs_url="/docs",
redoc_url="/redoc",
)
# Set all CORS enabled origins
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allow all origins in development
allow_credentials=True,
allow_methods=["*"], # Allow all methods
allow_headers=["*"], # Allow all headers
)
# Include routers
app.include_router(api_router, prefix=API_V1_STR)
app.include_router(health_router)
@app.get("/")
def root():
"""
Root endpoint that redirects to the API documentation.
"""
return {
"message": "Welcome to the Todo API! Visit /docs for the API documentation."
}

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
from app.db.session import Base
from app.models.todo import Todo # noqa
# 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
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:
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()

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,47 @@
"""Initial migration
Revision ID: initial
Revises:
Create Date: 2023-10-31
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = 'initial'
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
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),
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)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_todos_id'), table_name='todos')
op.drop_table('todos')
# ### end Alembic commands ###

11
pyproject.toml Normal file
View File

@ -0,0 +1,11 @@
[tool.ruff]
line-length = 88
target-version = "py310"
[tool.ruff.lint]
select = ["E", "F", "I"]
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
line-ending = "auto"

7
requirements.txt Normal file
View File

@ -0,0 +1,7 @@
fastapi>=0.104.0
uvicorn>=0.23.2
sqlalchemy>=2.0.0
pydantic>=2.4.2
alembic>=1.12.0
python-dotenv>=1.0.0
ruff>=0.1.6

87
test_app.py Normal file
View File

@ -0,0 +1,87 @@
#!/usr/bin/env python3
"""
Test script for the Todo API.
This script tests the basic functionality of the Todo API.
"""
import sys
from pprint import pprint
import requests
def main():
"""Main function to test the Todo API."""
base_url = "http://localhost:8000"
api_base = f"{base_url}/api/v1"
todos_url = f"{api_base}/todos"
# Test health endpoint
print("\n=== Testing health endpoint ===")
health_response = requests.get(f"{base_url}/health")
pprint(health_response.json())
# Test create todo
print("\n=== Testing create todo ===")
new_todo = {
"title": "Test Todo",
"description": "This is a test todo item",
"completed": False
}
create_response = requests.post(todos_url, json=new_todo)
if create_response.status_code != 201:
print(f"Error creating todo: {create_response.status_code}")
sys.exit(1)
created_todo = create_response.json()
todo_id = created_todo["id"]
pprint(created_todo)
# Test get all todos
print("\n=== Testing get all todos ===")
get_all_response = requests.get(todos_url)
pprint(get_all_response.json())
# Test get single todo
print(f"\n=== Testing get todo with id {todo_id} ===")
get_single_response = requests.get(f"{todos_url}/{todo_id}")
pprint(get_single_response.json())
# Test update todo
print(f"\n=== Testing update todo with id {todo_id} ===")
update_data = {
"title": "Updated Test Todo",
"completed": True
}
update_response = requests.patch(f"{todos_url}/{todo_id}", json=update_data)
pprint(update_response.json())
# Test filter by completed
print("\n=== Testing filter by completed status ===")
filter_response = requests.get(f"{todos_url}?completed=true")
pprint(filter_response.json())
# Test delete todo
print(f"\n=== Testing delete todo with id {todo_id} ===")
delete_response = requests.delete(f"{todos_url}/{todo_id}")
if delete_response.status_code != 204:
print(f"Error deleting todo: {delete_response.status_code}")
sys.exit(1)
print(f"Todo with id {todo_id} deleted successfully")
# Verify todo is deleted
print("\n=== Verifying todo was deleted ===")
verify_response = requests.get(f"{todos_url}/{todo_id}")
if verify_response.status_code == 404:
print(f"Todo with id {todo_id} no longer exists (as expected)")
else:
print(
f"Error: Todo with id {todo_id} still exists "
f"with status code {verify_response.status_code}"
)
print("\nAll tests completed successfully!")
if __name__ == "__main__":
main()