Implement complete Todo API with CRUD endpoints

- Created FastAPI application with Todo CRUD operations
- Implemented GET /api/v1/todos/ for listing todos with pagination
- Implemented POST /api/v1/todos/ for creating new todos
- Implemented GET /api/v1/todos/{id} for retrieving specific todos
- Implemented PUT /api/v1/todos/{id} for updating todos
- Implemented DELETE /api/v1/todos/{id} for deleting todos
- Added proper error handling with 404 responses
- Configured SQLAlchemy with SQLite database
- Set up Alembic for database migrations
- Added Pydantic schemas for request/response validation
- Enabled CORS for all origins
- Added health check endpoint at /health
- Updated README with complete API documentation
This commit is contained in:
Automated Action 2025-06-20 02:28:53 +00:00
parent 76ee64db16
commit 29d1f9d0d1
13 changed files with 467 additions and 40 deletions

View File

@ -1,3 +1,89 @@
# FastAPI Application # Todo API
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. A simple Todo API built with FastAPI, SQLAlchemy, and SQLite.
## Features
- Full CRUD operations for todos
- RESTful API design
- Automatic API documentation with Swagger/OpenAPI
- SQLite database with SQLAlchemy ORM
- Database migrations with Alembic
- CORS enabled for all origins
- Health check endpoint
## API Endpoints
### Base Endpoints
- `GET /` - Root endpoint with API information
- `GET /health` - Health check endpoint
- `GET /docs` - Swagger UI documentation
- `GET /redoc` - ReDoc documentation
### Todo Endpoints
All todo endpoints are prefixed with `/api/v1/todos`
- `GET /api/v1/todos/` - List all todos (with pagination)
- Query parameters: `skip` (default: 0), `limit` (default: 100)
- `POST /api/v1/todos/` - Create a new todo
- `GET /api/v1/todos/{todo_id}` - Get a specific todo by ID
- `PUT /api/v1/todos/{todo_id}` - Update a todo by ID
- `DELETE /api/v1/todos/{todo_id}` - Delete a todo by ID
## Data Model
Each todo has the following fields:
- `id` (integer) - Unique identifier
- `title` (string, required) - Todo title (1-200 characters)
- `description` (string, optional) - Todo description (max 1000 characters)
- `completed` (boolean) - Completion status (default: false)
- `created_at` (datetime) - Creation timestamp
- `updated_at` (datetime) - Last update timestamp
## Quick Start
1. Install dependencies:
```bash
pip install -r requirements.txt
```
2. Start the application:
```bash
uvicorn main:app --reload
```
3. The API will be available at `http://localhost:8000`
- API documentation: `http://localhost:8000/docs`
- Alternative docs: `http://localhost:8000/redoc`
## Database
The application uses SQLite with the database file stored at `/app/storage/db/db.sqlite`. Database tables are automatically created when the application starts.
## Project Structure
```
/
├── main.py # FastAPI application entry point
├── requirements.txt # Python dependencies
├── alembic.ini # Alembic configuration
├── alembic/ # Database migrations
├── app/
│ ├── __init__.py
│ ├── api/ # API routes
│ │ ├── __init__.py
│ │ └── todos.py # Todo CRUD endpoints
│ ├── db/ # Database configuration
│ │ ├── __init__.py
│ │ ├── base.py # SQLAlchemy Base
│ │ └── session.py # Database session management
│ ├── models/ # SQLAlchemy models
│ │ ├── __init__.py
│ │ └── todo.py # Todo model
│ └── schemas/ # Pydantic schemas
│ ├── __init__.py
│ └── todo.py # Todo request/response schemas
```

96
alembic.ini Normal file
View File

@ -0,0 +1,96 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = alembic
# 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
# 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 number format
version_num_format = %(migration_id)s_%(slug)s
# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "space", for backward
# compatibility. If using multiple databases, please set to ":" or some other character
# that isn't a space
version_path_separator = :
# 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
[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

1
alembic/README Normal file
View File

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

83
alembic/env.py Normal file
View File

@ -0,0 +1,83 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
import sys
import os
# Add the project root directory to the Python path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Import your models here
from app.db.base import Base
from app.models.todo import Todo
# 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"},
)
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:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

24
alembic/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,38 @@
"""Initial migration
Revision ID: 001
Revises:
Create Date: 2024-01-01 12:00:00.000000
"""
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() -> None:
# ### commands auto generated by Alembic - please adjust! ###
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),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.Column('updated_at', sa.DateTime(timezone=True), 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 ###

View File

@ -0,0 +1 @@
# Alembic versions package

View File

@ -0,0 +1 @@
# API package

88
app/api/todos.py Normal file
View File

@ -0,0 +1,88 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from app.db.session import get_db
from app.models.todo import Todo
from app.schemas.todo import TodoCreate, TodoUpdate, TodoResponse
router = APIRouter(prefix="/todos", tags=["todos"])
@router.get("/", response_model=List[TodoResponse])
def get_todos(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
"""
Retrieve all todos with optional pagination.
"""
todos = db.query(Todo).offset(skip).limit(limit).all()
return todos
@router.post("/", response_model=TodoResponse, status_code=status.HTTP_201_CREATED)
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
"""
Create a new todo item.
"""
db_todo = Todo(
title=todo.title,
description=todo.description,
completed=todo.completed
)
db.add(db_todo)
db.commit()
db.refresh(db_todo)
return db_todo
@router.get("/{todo_id}", response_model=TodoResponse)
def get_todo(todo_id: int, db: Session = Depends(get_db)):
"""
Retrieve a specific todo by ID.
"""
todo = db.query(Todo).filter(Todo.id == todo_id).first()
if todo is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Todo with id {todo_id} not found"
)
return todo
@router.put("/{todo_id}", response_model=TodoResponse)
def update_todo(todo_id: int, todo_update: TodoUpdate, db: Session = Depends(get_db)):
"""
Update a specific todo by ID.
"""
todo = db.query(Todo).filter(Todo.id == todo_id).first()
if todo is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Todo with id {todo_id} not found"
)
# Update only the fields that are provided
update_data = todo_update.model_dump(exclude_unset=True)
for field, value in update_data.items():
setattr(todo, field, value)
db.commit()
db.refresh(todo)
return todo
@router.delete("/{todo_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
"""
Delete a specific todo by ID.
"""
todo = db.query(Todo).filter(Todo.id == todo_id).first()
if todo is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Todo with id {todo_id} not found"
)
db.delete(todo)
db.commit()
return None

View File

@ -2,9 +2,7 @@ from pathlib import Path
from sqlalchemy import create_engine from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import sessionmaker
from .base import Base # Database directory setup
# Database setup with absolute path as specified in guidelines
DB_DIR = Path("/app") / "storage" / "db" DB_DIR = Path("/app") / "storage" / "db"
DB_DIR.mkdir(parents=True, exist_ok=True) DB_DIR.mkdir(parents=True, exist_ok=True)
@ -17,11 +15,9 @@ engine = create_engine(
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# Create tables
Base.metadata.create_all(bind=engine)
# Dependency to get database session
def get_db(): def get_db():
"""Dependency to get database session"""
db = SessionLocal() db = SessionLocal()
try: try:
yield db yield db

View File

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

View File

@ -1,26 +1,28 @@
from datetime import datetime from pydantic import BaseModel, Field
from typing import Optional from typing import Optional
from pydantic import BaseModel from datetime import datetime
class TodoCreate(BaseModel): class TodoBase(BaseModel):
title: str title: str = Field(..., min_length=1, max_length=200)
description: Optional[str] = None description: Optional[str] = Field(None, max_length=1000)
completed: bool = False
class TodoCreate(TodoBase):
pass
class TodoUpdate(BaseModel): class TodoUpdate(BaseModel):
title: Optional[str] = None title: Optional[str] = Field(None, min_length=1, max_length=200)
description: Optional[str] = None description: Optional[str] = Field(None, max_length=1000)
completed: Optional[bool] = None completed: Optional[bool] = None
class TodoResponse(BaseModel): class TodoResponse(TodoBase):
id: int id: int
title: str
description: Optional[str] = None
completed: bool
created_at: datetime created_at: datetime
updated_at: datetime updated_at: Optional[datetime] = None
class Config: class Config:
from_attributes = True from_attributes = True

45
main.py
View File

@ -1,16 +1,20 @@
from fastapi import FastAPI from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from app.api.todos import router as todos_router
from app.db.base import Base
from app.db.session import engine
# Create database tables
Base.metadata.create_all(bind=engine)
app = FastAPI( app = FastAPI(
title="Todo App API", title="Todo API",
description="A simple Todo application API built with FastAPI", description="A simple Todo API built with FastAPI",
version="1.0.0", version="1.0.0",
openapi_url="/openapi.json", openapi_url="/openapi.json"
docs_url="/docs",
redoc_url="/redoc"
) )
# Configure CORS # Add CORS middleware
app.add_middleware( app.add_middleware(
CORSMiddleware, CORSMiddleware,
allow_origins=["*"], allow_origins=["*"],
@ -19,13 +23,18 @@ app.add_middleware(
allow_headers=["*"], allow_headers=["*"],
) )
# Include routers
app.include_router(todos_router, prefix="/api/v1")
@app.get("/") @app.get("/")
async def root(): def root():
"""Base endpoint that returns app information""" """
Root endpoint that returns basic information about the API.
"""
return { return {
"title": "Todo App API", "title": "Todo API",
"description": "A simple Todo application API built with FastAPI", "description": "A simple Todo API built with FastAPI",
"version": "1.0.0", "version": "1.0.0",
"documentation": "/docs", "documentation": "/docs",
"health_check": "/health" "health_check": "/health"
@ -33,11 +42,11 @@ async def root():
@app.get("/health") @app.get("/health")
async def health_check(): def health_check():
"""Health check endpoint""" """
return {"status": "healthy", "message": "Todo App API is running"} Health check endpoint to verify the application is running.
"""
return {
if __name__ == "__main__": "status": "healthy",
import uvicorn "message": "Todo API is running successfully"
uvicorn.run(app, host="0.0.0.0", port=8000) }