Implement Todo API application with FastAPI and SQLite

- Created project structure with FastAPI setup
- Added SQLite database connection with SQLAlchemy ORM
- Implemented Todo model and schemas
- Added CRUD operations for Todo items
- Created API endpoints for Todo management
- Added health check endpoint
- Configured Alembic for database migrations
- Updated project documentation in README.md
This commit is contained in:
Automated Action 2025-05-24 22:41:36 +00:00
parent c82146be5d
commit 2f75e43b7f
27 changed files with 686 additions and 2 deletions

104
README.md
View File

@ -1,3 +1,103 @@
# FastAPI Application
# Todo API
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A simple Todo application API built with FastAPI and SQLite.
## Features
- RESTful API using FastAPI
- SQLite database with SQLAlchemy ORM
- Database migrations using Alembic
- CRUD operations for Todo items
- Health check endpoint
- OpenAPI documentation
## Project Structure
```
/
├── app/
│ ├── api/
│ │ ├── v1/
│ │ │ ├── health.py
│ │ │ └── todos.py
│ │ ├── deps.py
│ │ └── routers.py
│ ├── core/
│ │ └── config.py
│ ├── crud/
│ │ ├── base.py
│ │ └── todo.py
│ ├── db/
│ │ ├── base.py
│ │ ├── base_class.py
│ │ └── session.py
│ ├── models/
│ │ └── todo.py
│ └── schemas/
│ └── todo.py
├── migrations/
│ ├── versions/
│ │ └── 01_initial_todo_table.py
│ ├── env.py
│ └── script.py.mako
├── alembic.ini
├── main.py
└── requirements.txt
```
## Installation
1. Clone the repository
2. Install dependencies:
```bash
pip install -r requirements.txt
```
## Database Setup
The application uses SQLite as its database. The database will be created at `/app/storage/db/db.sqlite` when the application starts.
To run the migrations:
```bash
alembic upgrade head
```
## Running the Application
To run the application locally:
```bash
uvicorn main:app --reload
```
The API will be available at http://localhost:8000
## API Documentation
API documentation is available at:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
## API Endpoints
### Health Check
- `GET /api/v1/health` - Check API health
### Todo Endpoints
- `GET /api/v1/todos` - List all todos
- `POST /api/v1/todos` - Create a new todo
- `GET /api/v1/todos/{id}` - Get a specific todo
- `PUT /api/v1/todos/{id}` - Update a todo
- `DELETE /api/v1/todos/{id}` - Delete a todo
## Query Parameters
### List todos
- `skip` - Number of records to skip (default: 0)
- `limit` - Maximum number of records to return (default: 100)
- `completed` - Filter by completion status (optional, boolean)

73
alembic.ini Normal file
View File

@ -0,0 +1,73 @@
# 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
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
# 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

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

@ -0,0 +1,2 @@

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

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

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

28
app/api/v1/health.py Normal file
View File

@ -0,0 +1,28 @@
from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session
from app.db.session import get_db
router = APIRouter()
@router.get("/", status_code=status.HTTP_200_OK)
def health_check(db: Session = Depends(get_db)):
"""
Check the health of the API.
"""
try:
# Validate database connection
db.execute("SELECT 1")
return {
"status": "ok",
"message": "API is healthy",
"database": "connected"
}
except Exception as e:
return {
"status": "error",
"message": "API health check failed",
"database": "disconnected",
"error": str(e)
}

99
app/api/v1/todos.py Normal file
View File

@ -0,0 +1,99 @@
from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app import crud, schemas
from app.db.session import get_db
router = APIRouter()
@router.get("/", response_model=List[schemas.todo.Todo])
def read_todos(
db: Session = Depends(get_db),
skip: int = 0,
limit: int = 100,
completed: bool = None,
) -> Any:
"""
Retrieve todos.
"""
if completed is not None:
if completed:
todos = crud.todo.get_completed(db, skip=skip, limit=limit)
else:
todos = crud.todo.get_incomplete(db, skip=skip, limit=limit)
else:
todos = crud.todo.get_multi(db, skip=skip, limit=limit)
return todos
@router.post("/", response_model=schemas.todo.Todo, status_code=status.HTTP_201_CREATED)
def create_todo(
*,
db: Session = Depends(get_db),
todo_in: schemas.todo.TodoCreate,
) -> Any:
"""
Create new todo.
"""
todo = crud.todo.create(db=db, obj_in=todo_in)
return todo
@router.get("/{id}", response_model=schemas.todo.Todo)
def read_todo(
*,
db: Session = Depends(get_db),
id: int,
) -> Any:
"""
Get todo by ID.
"""
todo = crud.todo.get(db=db, id=id)
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Todo not found",
)
return todo
@router.put("/{id}", response_model=schemas.todo.Todo)
def update_todo(
*,
db: Session = Depends(get_db),
id: int,
todo_in: schemas.todo.TodoUpdate,
) -> Any:
"""
Update a todo.
"""
todo = crud.todo.get(db=db, id=id)
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Todo not found",
)
todo = crud.todo.update(db=db, db_obj=todo, obj_in=todo_in)
return todo
@router.delete("/{id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
def delete_todo(
*,
db: Session = Depends(get_db),
id: int,
) -> Any:
"""
Delete a todo.
"""
todo = crud.todo.get(db=db, id=id)
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Todo not found",
)
crud.todo.remove(db=db, id=id)
return None

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

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

@ -0,0 +1,30 @@
from pathlib import Path
from typing import List
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
# API Configuration
API_V1_STR: str = "/api/v1"
PROJECT_NAME: str = "Todo API"
PROJECT_DESCRIPTION: str = "A simple TODO application API"
PROJECT_VERSION: str = "0.1.0"
# CORS Configuration
CORS_ORIGINS: List[str] = ["*"]
# Database Configuration
DB_DIR: Path = Path("/app/storage/db")
SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite"
class Config:
env_file = ".env"
env_file_encoding = "utf-8"
case_sensitive = True
settings = Settings()
# Create DB directory if it doesn't exist
settings.DB_DIR.mkdir(parents=True, exist_ok=True)

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

65
app/crud/base.py Normal file
View File

@ -0,0 +1,65 @@
from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.db.base_class import Base
ModelType = TypeVar("ModelType", bound=Base)
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
def __init__(self, model: Type[ModelType]):
"""
CRUD base class with default methods to Create, Read, Update, Delete (CRUD).
**Parameters**
* `model`: A SQLAlchemy model class
"""
self.model = model
def get(self, db: Session, id: Any) -> Optional[ModelType]:
return db.query(self.model).filter(self.model.id == id).first()
def get_multi(
self, db: Session, *, skip: int = 0, limit: int = 100
) -> List[ModelType]:
return db.query(self.model).offset(skip).limit(limit).all()
def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType:
obj_in_data = jsonable_encoder(obj_in)
db_obj = self.model(**obj_in_data)
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def update(
self,
db: Session,
*,
db_obj: ModelType,
obj_in: Union[UpdateSchemaType, Dict[str, Any]]
) -> ModelType:
obj_data = jsonable_encoder(db_obj)
if isinstance(obj_in, dict):
update_data = obj_in
else:
update_data = obj_in.dict(exclude_unset=True)
for field in obj_data:
if field in update_data:
setattr(db_obj, field, update_data[field])
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def remove(self, db: Session, *, id: int) -> ModelType:
obj = db.query(self.model).get(id)
db.delete(obj)
db.commit()
return obj

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

@ -0,0 +1,24 @@
from typing import List, Optional
from sqlalchemy.orm import Session
from app.crud.base import CRUDBase
from app.models.todo import Todo
from app.schemas.todo import TodoCreate, TodoUpdate
class CRUDTodo(CRUDBase[Todo, TodoCreate, TodoUpdate]):
def get_by_title(self, db: Session, *, title: str) -> Optional[Todo]:
"""Get a todo by title"""
return db.query(Todo).filter(Todo.title == title).first()
def get_completed(self, db: Session, *, skip: int = 0, limit: int = 100) -> List[Todo]:
"""Get all completed todos"""
return db.query(Todo).filter(Todo.completed.is_(True)).offset(skip).limit(limit).all()
def get_incomplete(self, db: Session, *, skip: int = 0, limit: int = 100) -> List[Todo]:
"""Get all incomplete todos"""
return db.query(Todo).filter(Todo.completed.is_(False)).offset(skip).limit(limit).all()
todo = CRUDTodo(Todo)

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

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

@ -0,0 +1 @@
# Import all models for Alembic to detect

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

@ -0,0 +1,14 @@
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()

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

@ -0,0 +1,25 @@
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.core.config import settings
# Create SQLAlchemy engine
engine = create_engine(
settings.SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False} # Needed for SQLite
)
# Create a SessionLocal class
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get_db():
"""
Dependency function that creates a new SQLAlchemy SessionLocal
that will be used in a single request, and then closed.
"""
db = SessionLocal()
try:
yield db
finally:
db.close()

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

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

@ -0,0 +1,14 @@
from datetime import datetime
from sqlalchemy import Boolean, Column, DateTime, Integer, String, Text
from app.db.base_class import Base
class Todo(Base):
id = Column(Integer, primary_key=True, index=True)
title = Column(String(255), nullable=False, index=True)
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)

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

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

@ -0,0 +1,37 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
# Shared properties
class TodoBase(BaseModel):
title: str = Field(..., min_length=1, max_length=255)
description: Optional[str] = None
completed: Optional[bool] = False
# Properties to receive via API on creation
class TodoCreate(TodoBase):
pass
# Properties to receive via API on update
class TodoUpdate(BaseModel):
title: Optional[str] = Field(None, min_length=1, max_length=255)
description: Optional[str] = None
completed: Optional[bool] = None
class TodoInDBBase(TodoBase):
id: int
created_at: datetime
updated_at: datetime
class Config:
orm_mode = True
# Additional properties to return via API
class Todo(TodoInDBBase):
pass

37
main.py Normal file
View File

@ -0,0 +1,37 @@
from pathlib import Path
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.routers import router as api_router
from app.core.config import settings
app = FastAPI(
title=settings.PROJECT_NAME,
description=settings.PROJECT_DESCRIPTION,
version=settings.PROJECT_VERSION,
openapi_url=f"{settings.API_V1_STR}/openapi.json",
docs_url="/docs",
redoc_url="/redoc",
)
# Set up CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include API router
app.include_router(api_router, prefix=settings.API_V1_STR)
# Ensure storage directory exists
storage_dir = Path("/app/storage")
storage_dir.mkdir(parents=True, exist_ok=True)
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

62
migrations/env.py Normal file
View File

@ -0,0 +1,62 @@
import sys
from pathlib import Path
from alembic import context
from sqlalchemy import engine_from_config, pool
# Add app directory to path
sys.path.insert(0, str(Path(__file__).parent.parent))
# Import models
from app.db.base import Base
from app.core.config import settings
# Alembic Config object
config = context.config
# Set SQLAlchemy URL in Alembic config
config.set_main_option("sqlalchemy.url", settings.SQLALCHEMY_DATABASE_URL)
# Metadata for autogenerate support
target_metadata = Base.metadata
def run_migrations_offline():
"""Run migrations in 'offline' mode."""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
compare_type=True,
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode."""
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,
compare_type=True,
render_as_batch=is_sqlite, # Enable batch mode 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,35 @@
"""Initial todo table
Revision ID: 01_initial_todo_table
Revises:
Create Date: 2023-09-15
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '01_initial_todo_table'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'todo',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(255), nullable=False, index=True),
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_todo_id'), 'todo', ['id'], unique=False)
def downgrade():
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.287