Create simple todo app with FastAPI and SQLite

- Set up project structure and FastAPI application
- Create database models with SQLAlchemy
- Set up Alembic for database migrations
- Create API endpoints for todo CRUD operations
- Add health check endpoint
- Add unit tests for API endpoints
- Configure Ruff for linting and formatting
This commit is contained in:
Automated Action 2025-05-22 10:47:24 +00:00
parent 0eb8170434
commit 0d888832b4
24 changed files with 760 additions and 2 deletions

View File

@ -1,3 +1,92 @@
# FastAPI Application
# Simple Todo App
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
This is a FastAPI-based Todo application with SQLite as the database backend. The application provides a REST API for managing todo items.
## Features
- Create, read, update, and delete todo items
- SQLite database for data persistence
- Alembic for database migrations
- Health check endpoint
- API documentation with Swagger UI and ReDoc
## Project Structure
```
├── alembic.ini # Alembic configuration
├── app # Application package
│ ├── api # API routes
│ │ ├── api.py # Main API router
│ │ └── endpoints # API endpoints
│ │ └── todos.py # Todo endpoints
│ ├── core # Core functionality
│ │ └── config.py # Application configuration
│ ├── db # Database related modules
│ │ └── 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
│ ├── README # Migrations README
│ ├── script.py.mako # Script template
│ └── versions # Migration versions
│ └── 001_create_todos_table.py # Initial migration
├── requirements.txt # Project dependencies
└── tests # Tests
└── test_api.py # API tests
```
## Getting Started
### Prerequisites
- Python 3.8 or higher
### Installation
1. Clone the repository
2. Install dependencies:
```bash
pip install -r requirements.txt
```
3. Run database migrations:
```bash
alembic upgrade head
```
4. Start the application:
```bash
uvicorn main:app --reload
```
5. Access the API documentation:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
## API Endpoints
| Method | Endpoint | Description |
|--------|--------------|--------------------------------------|
| GET | /health | Health check endpoint |
| GET | /todos | Get all todo items |
| GET | /todos/{id} | Get a specific todo item |
| POST | /todos | Create a new todo item |
| PUT | /todos/{id} | Update an existing todo item |
| DELETE | /todos/{id} | Delete a todo item |
## Testing
Run tests with pytest:
```bash
pytest
```
## License
This project is licensed under the MIT License.

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
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

7
app/api/api.py Normal file
View File

@ -0,0 +1,7 @@
from fastapi import APIRouter
from app.api.endpoints import todos
api_router = APIRouter()
api_router.include_router(todos.router, prefix="/todos", tags=["todos"])

View File

View File

@ -0,0 +1,76 @@
from typing import List
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
from app.schemas.todo import TodoCreate, TodoResponse, TodoUpdate
router = APIRouter()
@router.post("", response_model=TodoResponse, status_code=status.HTTP_201_CREATED)
def create_todo(todo_in: TodoCreate, db: Session = Depends(get_db)) -> TodoResponse:
"""Create a new todo item."""
db_todo = Todo(
title=todo_in.title,
description=todo_in.description,
completed=todo_in.completed,
)
db.add(db_todo)
db.commit()
db.refresh(db_todo)
return db_todo
@router.get("", response_model=List[TodoResponse])
def read_todos(
skip: int = 0,
limit: int = 100,
db: Session = Depends(get_db),
) -> List[TodoResponse]:
"""Read all todo items with pagination."""
todos = db.query(Todo).offset(skip).limit(limit).all()
return todos
@router.get("/{todo_id}", response_model=TodoResponse)
def read_todo(todo_id: int, db: Session = Depends(get_db)) -> TodoResponse:
"""Read a specific todo item by ID."""
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
if db_todo is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Todo not found")
return db_todo
@router.put("/{todo_id}", response_model=TodoResponse)
def update_todo(
todo_id: int,
todo_in: TodoUpdate,
db: Session = Depends(get_db),
) -> TodoResponse:
"""Update a todo item."""
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
if db_todo is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Todo not found")
update_data = todo_in.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(get_db)) -> None:
"""Delete a todo item."""
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
if db_todo is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Todo not found")
db.delete(db_todo)
db.commit()
return None

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

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

@ -0,0 +1,25 @@
from pathlib import Path
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
"""Application settings."""
APP_NAME: str = "Simple Todo App"
APP_VERSION: str = "0.1.0"
DEBUG: bool = False
class Config:
env_file = ".env"
env_file_encoding = "utf-8"
case_sensitive = True
settings = Settings()
# Database setup
DB_DIR = Path("/app") / "storage" / "db"
DB_DIR.mkdir(parents=True, exist_ok=True)
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"

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

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

@ -0,0 +1,28 @@
from typing import Generator
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session, sessionmaker
from app.core.config import SQLALCHEMY_DATABASE_URL
# Create SQLAlchemy engine
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False}, # Needed for SQLite
)
# Create session factory
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# Create base class for models
Base = declarative_base()
def get_db() -> Generator[Session, None, None]:
"""Dependency to get database session."""
db = SessionLocal()
try:
yield db
finally:
db.close()

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

@ -0,0 +1 @@
from app.models.todo import Todo # noqa

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

@ -0,0 +1,21 @@
from datetime import datetime
from sqlalchemy import Boolean, Column, DateTime, Integer, String, Text
from app.db.session import Base
class Todo(Base):
"""Todo model for database."""
__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, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
def __repr__(self) -> str:
return f"<Todo id={self.id} title={self.title} completed={self.completed}>"

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

@ -0,0 +1 @@
from app.schemas.todo import TodoBase, TodoCreate, TodoUpdate, TodoInDB, TodoResponse # noqa

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

@ -0,0 +1,43 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
class TodoBase(BaseModel):
"""Base schema for Todo."""
title: str = Field(..., min_length=1, max_length=100)
description: Optional[str] = None
completed: bool = False
class TodoCreate(TodoBase):
"""Schema for creating a Todo."""
pass
class TodoUpdate(BaseModel):
"""Schema for updating a Todo."""
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 stored in DB."""
id: int
created_at: datetime
updated_at: datetime
class Config:
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.api import api_router
from app.core.config import settings
app = FastAPI(
title=settings.APP_NAME,
version=settings.APP_VERSION,
debug=settings.DEBUG,
)
# Configure CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allows all origins
allow_credentials=True,
allow_methods=["*"], # Allows all methods
allow_headers=["*"], # Allows all headers
)
# Include API router
app.include_router(api_router)
@app.get("/health", tags=["Health"])
async def health_check() -> dict[str, str]:
"""Health check endpoint."""
return {"status": "ok"}

1
migrations/README Normal file
View File

@ -0,0 +1 @@
Generic single-database configuration with SQLite.

85
migrations/env.py Normal file
View File

@ -0,0 +1,85 @@
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.abspath(os.path.join(os.path.dirname(__file__), "..")))
# Import models
from app.db.session import Base
from app.models 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.
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():
"""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:
is_sqlite = connection.dialect.name == "sqlite"
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=is_sqlite, # Required for 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():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}

View File

@ -0,0 +1,40 @@
"""create todos table
Revision ID: 001
Revises:
Create Date: 2023-09-20
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "001"
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(length=100), nullable=False),
sa.Column("description", sa.Text(), nullable=True),
sa.Column("completed", sa.Boolean(), default=False),
sa.Column("created_at", sa.DateTime(), default=sa.func.current_timestamp()),
sa.Column(
"updated_at",
sa.DateTime(),
default=sa.func.current_timestamp(),
onupdate=sa.func.current_timestamp(),
),
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")

15
pyproject.toml Normal file
View File

@ -0,0 +1,15 @@
[tool.ruff]
line-length = 100
target-version = "py38"
[tool.ruff.lint]
select = ["E", "F", "B", "I", "N", "UP", "ANN", "S", "A", "COM"]
ignore = ["ANN101", "ANN102", "S101", "B008", "ANN201", "ANN204"]
[tool.ruff.lint.isort]
known-first-party = ["app"]
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
line-ending = "auto"

10
requirements.txt Normal file
View File

@ -0,0 +1,10 @@
fastapi>=0.103.1
uvicorn>=0.23.2
sqlalchemy>=2.0.20
alembic>=1.12.0
pydantic>=2.3.0
pydantic-settings>=2.0.3
python-dotenv>=1.0.0
ruff>=0.0.290
pytest>=7.4.2
httpx>=0.24.1

0
tests/__init__.py Normal file
View File

158
tests/test_api.py Normal file
View File

@ -0,0 +1,158 @@
from fastapi.testclient import TestClient
from app.db.session import Base, engine
from main import app
# Create test client
client = TestClient(app)
def test_health_check():
"""Test health check endpoint."""
response = client.get("/health")
assert response.status_code == 200
assert response.json() == {"status": "ok"}
def test_create_todo():
"""Test creating a todo item."""
# Create test database tables
Base.metadata.create_all(bind=engine)
# Define test data
test_todo = {
"title": "Test Todo",
"description": "This is a test todo",
"completed": False,
}
# Send POST request
response = client.post("/todos", json=test_todo)
# Check response
assert response.status_code == 201
data = response.json()
assert data["title"] == test_todo["title"]
assert data["description"] == test_todo["description"]
assert data["completed"] == test_todo["completed"]
assert "id" in data
assert "created_at" in data
assert "updated_at" in data
# Cleanup test data
client.delete(f"/todos/{data['id']}")
def test_read_todos():
"""Test reading all todo items."""
# Create test database tables
Base.metadata.create_all(bind=engine)
# Create a test todo item
test_todo = {
"title": "Test Todo for Reading",
"description": "This is a test todo for reading",
"completed": False,
}
create_response = client.post("/todos", json=test_todo)
created_todo = create_response.json()
# Send GET request
response = client.get("/todos")
# Check response
assert response.status_code == 200
assert isinstance(response.json(), list)
# Cleanup test data
client.delete(f"/todos/{created_todo['id']}")
def test_read_todo():
"""Test reading a specific todo item."""
# Create test database tables
Base.metadata.create_all(bind=engine)
# Create a test todo item
test_todo = {
"title": "Test Todo for Reading One",
"description": "This is a test todo for reading one",
"completed": False,
}
create_response = client.post("/todos", json=test_todo)
created_todo = create_response.json()
# Send GET request
response = client.get(f"/todos/{created_todo['id']}")
# Check response
assert response.status_code == 200
data = response.json()
assert data["id"] == created_todo["id"]
assert data["title"] == test_todo["title"]
assert data["description"] == test_todo["description"]
assert data["completed"] == test_todo["completed"]
# Cleanup test data
client.delete(f"/todos/{created_todo['id']}")
def test_update_todo():
"""Test updating a todo item."""
# Create test database tables
Base.metadata.create_all(bind=engine)
# Create a test todo item
test_todo = {
"title": "Test Todo for Updating",
"description": "This is a test todo for updating",
"completed": False,
}
create_response = client.post("/todos", json=test_todo)
created_todo = create_response.json()
# Define update data
update_data = {
"title": "Updated Test Todo",
"completed": True,
}
# Send PUT request
response = client.put(f"/todos/{created_todo['id']}", json=update_data)
# Check response
assert response.status_code == 200
data = response.json()
assert data["id"] == created_todo["id"]
assert data["title"] == update_data["title"]
assert data["description"] == test_todo["description"] # Should remain unchanged
assert data["completed"] == update_data["completed"]
# Cleanup test data
client.delete(f"/todos/{created_todo['id']}")
def test_delete_todo():
"""Test deleting a todo item."""
# Create test database tables
Base.metadata.create_all(bind=engine)
# Create a test todo item
test_todo = {
"title": "Test Todo for Deleting",
"description": "This is a test todo for deleting",
"completed": False,
}
create_response = client.post("/todos", json=test_todo)
created_todo = create_response.json()
# Send DELETE request
response = client.delete(f"/todos/{created_todo['id']}")
# Check response
assert response.status_code == 204
assert response.content == b"" # No content should be returned
# Verify the todo is deleted
get_response = client.get(f"/todos/{created_todo['id']}")
assert get_response.status_code == 404