Complete FastAPI Todo application with full CRUD functionality

- Add SQLAlchemy models for Todo with timestamps
- Create Pydantic schemas for request/response validation
- Implement CRUD operations for Todo management
- Add REST API endpoints for todo operations (GET, POST, PUT, DELETE)
- Configure SQLite database with proper connection settings
- Set up Alembic migrations for database schema management
- Add comprehensive API documentation and health check endpoint
- Enable CORS for all origins
- Include proper error handling and HTTP status codes
- Update README with complete setup and usage instructions
This commit is contained in:
Automated Action 2025-06-17 05:28:06 +00:00
parent 1aa9055725
commit 7b3cd8d0dd
26 changed files with 695 additions and 2 deletions

126
README.md
View File

@ -1,3 +1,125 @@
# FastAPI Application
# Todo App 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
- ✅ Create, read, update, and delete todos
- ✅ SQLite database with SQLAlchemy ORM
- ✅ Database migrations with Alembic
- ✅ API documentation with Swagger UI
- ✅ Health check endpoint
- ✅ CORS enabled for all origins
- ✅ Input validation with Pydantic
## Quick Start
### Prerequisites
- Python 3.8+
### Installation
1. Install dependencies:
```bash
pip install -r requirements.txt
```
2. Run database migrations:
```bash
alembic upgrade head
```
3. Start the development server:
```bash
uvicorn main:app --host 0.0.0.0 --port 8000 --reload
```
Or alternatively:
```bash
python main.py
```
## API Endpoints
The API is available at `http://localhost:8000`
### Documentation
- **Swagger UI**: http://localhost:8000/docs
- **ReDoc**: http://localhost:8000/redoc
- **OpenAPI JSON**: http://localhost:8000/openapi.json
### Core Endpoints
- **GET** `/` - Root endpoint with project information
- **GET** `/health` - Health check endpoint
### Todo Endpoints
- **GET** `/api/v1/todos/` - List all todos (with pagination)
- **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 specific todo
- **DELETE** `/api/v1/todos/{todo_id}` - Delete a specific todo
## Database
The application uses SQLite database stored at `/app/storage/db/db.sqlite`.
### Schema
**todos** table:
- `id` (Integer, Primary Key)
- `title` (String, Required)
- `description` (String, Optional)
- `completed` (Boolean, Default: False)
- `created_at` (DateTime with timezone)
- `updated_at` (DateTime with timezone)
## Development
### Linting and Formatting
```bash
# Check and fix linting issues
ruff check . --fix
# Format code
ruff format .
```
### Database Migrations
```bash
# Create a new migration
alembic revision --autogenerate -m "Description of changes"
# Apply migrations
alembic upgrade head
# Downgrade
alembic downgrade -1
```
## Project Structure
```
├── app/
│ ├── api/
│ │ └── v1/
│ │ ├── api.py # API router
│ │ └── todos.py # Todo endpoints
│ ├── core/
│ │ └── config.py # Configuration settings
│ ├── crud/
│ │ └── todo.py # CRUD operations
│ ├── db/
│ │ ├── base.py # SQLAlchemy base
│ │ ├── base_model.py # Model imports
│ │ └── session.py # Database session
│ ├── models/
│ │ └── todo.py # SQLAlchemy models
│ └── schemas/
│ └── todo.py # Pydantic schemas
├── migrations/ # Alembic migrations
├── main.py # FastAPI application
└── requirements.txt # Python dependencies
```

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

0
app/__init__.py Normal file
View File

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

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

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

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

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

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

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

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

@ -0,0 +1,30 @@
import os
from pathlib import Path
from pydantic_settings import BaseSettings
# Build paths inside the project
BASE_DIR = Path(__file__).resolve().parent.parent.parent
class Settings(BaseSettings):
API_V1_STR: str = "/api/v1"
PROJECT_NAME: str = "Todo App API"
PROJECT_DESCRIPTION: str = (
"A simple Todo application API built with FastAPI and SQLite"
)
VERSION: str = "0.1.0"
# SQLite Database settings
DB_DIR = Path("/app") / "storage" / "db"
SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite"
class Config:
case_sensitive = True
env_file = os.path.join(BASE_DIR, ".env")
settings = Settings()
# Ensure database directory exists
settings.DB_DIR.mkdir(parents=True, exist_ok=True)

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

@ -0,0 +1,3 @@
from .todo import todo
__all__ = ["todo"]

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

@ -0,0 +1,51 @@
from typing import List, Optional
from sqlalchemy.orm import Session
from app.models.todo import Todo
from app.schemas.todo import TodoCreate, TodoUpdate
class CRUDTodo:
"""CRUD operations for Todo model."""
def get(self, db: Session, todo_id: int) -> Optional[Todo]:
"""Get a single todo by ID."""
return db.query(Todo).filter(Todo.id == todo_id).first()
def get_multi(self, db: Session, *, skip: int = 0, limit: int = 100) -> List[Todo]:
"""Get multiple todos with pagination."""
return db.query(Todo).offset(skip).limit(limit).all()
def create(self, db: Session, *, obj_in: TodoCreate) -> Todo:
"""Create a new todo."""
db_obj = Todo(
title=obj_in.title,
description=obj_in.description,
completed=obj_in.completed,
)
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def update(self, db: Session, *, db_obj: Todo, obj_in: TodoUpdate) -> Todo:
"""Update a todo."""
update_data = obj_in.model_dump(exclude_unset=True)
for field, value in update_data.items():
setattr(db_obj, field, value)
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def remove(self, db: Session, *, todo_id: int) -> Optional[Todo]:
"""Delete a todo."""
obj = db.query(Todo).get(todo_id)
if obj:
db.delete(obj)
db.commit()
return obj
todo = CRUDTodo()

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

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

@ -0,0 +1,4 @@
from sqlalchemy.ext.declarative import declarative_base
# Create a Base class for SQLAlchemy models
Base = declarative_base()

4
app/db/base_model.py Normal file
View File

@ -0,0 +1,4 @@
"""Import all models here to ensure they are registered with SQLAlchemy."""
from app.db.base import Base # noqa
from app.models.todo import Todo # noqa

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

@ -0,0 +1,22 @@
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 session factory
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get_db():
"""Dependency for getting DB session."""
db = SessionLocal()
try:
yield db
finally:
db.close()

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

@ -0,0 +1,4 @@
from app.models.todo import Todo # noqa
# Add all models here for easy importing
__all__ = ["Todo"]

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

@ -0,0 +1,17 @@
from sqlalchemy import Boolean, Column, Integer, String, DateTime
from sqlalchemy.sql import func
from app.db.base import Base
class Todo(Base):
"""SQLAlchemy model for a Todo item."""
__tablename__ = "todos"
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(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())

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

@ -0,0 +1,3 @@
from .todo import TodoBase, TodoCreate, TodoUpdate, TodoResponse
__all__ = ["TodoBase", "TodoCreate", "TodoUpdate", "TodoResponse"]

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
class TodoBase(BaseModel):
"""Base schema for Todo."""
title: str
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] = None
description: Optional[str] = None
completed: Optional[bool] = None
class TodoResponse(TodoBase):
"""Schema for Todo response."""
id: int
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
from_attributes = True

49
main.py Normal file
View File

@ -0,0 +1,49 @@
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,
description=settings.PROJECT_DESCRIPTION,
version=settings.VERSION,
openapi_url="/openapi.json",
docs_url="/docs",
redoc_url="/redoc",
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include API router
app.include_router(api_router, prefix=settings.API_V1_STR)
@app.get("/")
async def root():
"""Root endpoint returning project info and links."""
return {
"title": settings.PROJECT_NAME,
"version": settings.VERSION,
"description": settings.PROJECT_DESCRIPTION,
"docs": "/docs",
"health": "/health",
}
@app.get("/health", status_code=200)
async def health_check():
"""Health check endpoint."""
return {"status": "healthy"}
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

0
migrations/__init__.py Normal file
View File

90
migrations/env.py Normal file
View File

@ -0,0 +1,90 @@
import sys
from logging.config import fileConfig
from pathlib import Path
from sqlalchemy import engine_from_config, pool
from alembic import context
# Add the project root directory to the Python path
sys.path.append(str(Path(__file__).resolve().parent.parent))
# Import Base from app.db.base
from app.db.base_model import Base # noqa
from app.core.config import settings # 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.
"""
configuration = config.get_section(config.config_ini_section)
# Ensure SQLite uses batch mode for migrations
connectable = engine_from_config(
configuration,
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
# Ensure SQLite uses batch mode for migrations
is_sqlite = connection.dialect.name == "sqlite"
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=is_sqlite, # Critical 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,46 @@
"""Create todos table
Revision ID: 001
Revises:
Create Date: 2023-10-30
"""
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():
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(), nullable=False, default=False),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.text("(CURRENT_TIMESTAMP)"),
),
sa.Column(
"updated_at",
sa.DateTime(timezone=True),
onupdate=sa.text("(CURRENT_TIMESTAMP)"),
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_todos_id"), "todos", ["id"], unique=False)
op.create_index(op.f("ix_todos_title"), "todos", ["title"], unique=False)
def downgrade():
op.drop_index(op.f("ix_todos_title"), table_name="todos")
op.drop_index(op.f("ix_todos_id"), table_name="todos")
op.drop_table("todos")

View File

8
requirements.txt Normal file
View File

@ -0,0 +1,8 @@
fastapi>=0.104.0
uvicorn>=0.23.2
sqlalchemy>=2.0.0
pydantic>=2.4.2
pydantic[email]>=2.4.2
alembic>=1.12.0
python-dotenv>=1.0.0
ruff>=0.1.3