diff --git a/README.md b/README.md index e8acfba..4aefca8 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,93 @@ -# FastAPI Application +# Barebones Todo API -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A simple, lightweight RESTful API for managing todo items built with FastAPI and SQLite. + +## Features + +- Create, read, update, and delete todo items +- Filter todos by completion status +- SQLite database for data persistence +- FastAPI for high performance and automatic API documentation +- Alembic for database migrations + +## Project Structure + +``` +├── app/ +│ ├── api/ # API routes +│ │ └── v1/ # API version 1 +│ │ └── endpoints/ +│ │ └── todos.py +│ ├── core/ # Core application code +│ │ └── config.py # Configuration settings +│ ├── db/ # Database setup +│ │ ├── base.py +│ │ ├── base_class.py +│ │ └── session.py +│ ├── models/ # SQLAlchemy models +│ │ └── todo.py +│ └── schemas/ # Pydantic schemas +│ └── todo.py +├── migrations/ # Alembic migrations +├── storage/ # Storage directory +│ └── db/ # Database storage +├── alembic.ini # Alembic configuration +├── main.py # Application entry point +└── requirements.txt # Project dependencies +``` + +## Installation + +1. Clone the repository + +2. Install dependencies +```bash +pip install -r requirements.txt +``` + +3. Apply database migrations +```bash +alembic upgrade head +``` + +## Running the API + +Start the API server with: +```bash +uvicorn main:app --reload +``` + +The API will be available at http://localhost:8000 + +## API Documentation + +- Swagger UI: http://localhost:8000/docs +- ReDoc: http://localhost:8000/redoc +- OpenAPI JSON: http://localhost:8000/openapi.json + +## API Endpoints + +### Base URL +- `GET /` - Returns basic API information +- `GET /health` - Health check endpoint + +### Todo Endpoints +- `GET /api/v1/todos` - List all todos (with optional filters) +- `POST /api/v1/todos` - Create a new todo +- `GET /api/v1/todos/{todo_id}` - Retrieve a specific todo +- `PUT /api/v1/todos/{todo_id}` - Update a todo +- `DELETE /api/v1/todos/{todo_id}` - Delete a todo + +## Database Migrations + +This project uses Alembic for database migrations. To create a new migration after model changes: + +```bash +alembic revision --autogenerate -m "Description of changes" +``` + +To apply migrations: + +```bash +alembic upgrade head +``` \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..82db3dd --- /dev/null +++ b/alembic.ini @@ -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 with absolute path +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 \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..ac825f9 --- /dev/null +++ b/app/__init__.py @@ -0,0 +1 @@ +# app package initialization \ No newline at end of file diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..80fb947 --- /dev/null +++ b/app/api/__init__.py @@ -0,0 +1 @@ +# API package initialization \ No newline at end of file diff --git a/app/api/v1/__init__.py b/app/api/v1/__init__.py new file mode 100644 index 0000000..84eb528 --- /dev/null +++ b/app/api/v1/__init__.py @@ -0,0 +1 @@ +# API v1 package initialization \ No newline at end of file diff --git a/app/api/v1/api.py b/app/api/v1/api.py new file mode 100644 index 0000000..930ddb7 --- /dev/null +++ b/app/api/v1/api.py @@ -0,0 +1,5 @@ +from fastapi import APIRouter +from app.api.v1.endpoints import todos + +api_router = APIRouter(prefix="/api/v1") +api_router.include_router(todos.router, prefix="/todos", tags=["todos"]) \ No newline at end of file diff --git a/app/api/v1/endpoints/__init__.py b/app/api/v1/endpoints/__init__.py new file mode 100644 index 0000000..8bbe46e --- /dev/null +++ b/app/api/v1/endpoints/__init__.py @@ -0,0 +1 @@ +# Endpoints package initialization \ No newline at end of file diff --git a/app/api/v1/endpoints/todos.py b/app/api/v1/endpoints/todos.py new file mode 100644 index 0000000..34d3d0a --- /dev/null +++ b/app/api/v1/endpoints/todos.py @@ -0,0 +1,92 @@ +from typing import List, Optional +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 as TodoModel +from app.schemas.todo import Todo, TodoCreate, TodoUpdate + +router = APIRouter() + +@router.get("/", response_model=List[Todo]) +def read_todos( + skip: int = 0, + limit: int = 100, + completed: Optional[bool] = None, + db: Session = Depends(get_db) +): + """ + Retrieve todos with optional filtering by completion status. + """ + if completed is not None: + return db.query(TodoModel).filter(TodoModel.completed == completed).offset(skip).limit(limit).all() + return db.query(TodoModel).offset(skip).limit(limit).all() + + +@router.post("/", response_model=Todo, status_code=status.HTTP_201_CREATED) +def create_todo( + todo: TodoCreate, + db: Session = Depends(get_db) +): + """ + Create a new todo item. + """ + db_todo = TodoModel(**todo.model_dump()) + db.add(db_todo) + db.commit() + db.refresh(db_todo) + return db_todo + + +@router.get("/{todo_id}", response_model=Todo) +def read_todo( + todo_id: int, + db: Session = Depends(get_db) +): + """ + Get a specific todo by ID. + """ + db_todo = db.query(TodoModel).filter(TodoModel.id == todo_id).first() + if db_todo is None: + raise HTTPException(status_code=404, detail="Todo not found") + return db_todo + + +@router.put("/{todo_id}", response_model=Todo) +def update_todo( + todo_id: int, + todo: TodoUpdate, + db: Session = Depends(get_db) +): + """ + Update a todo item. + """ + db_todo = db.query(TodoModel).filter(TodoModel.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 key, value in update_data.items(): + setattr(db_todo, key, value) + + db.add(db_todo) + 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) +): + """ + Delete a todo item. + """ + db_todo = db.query(TodoModel).filter(TodoModel.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 \ No newline at end of file diff --git a/app/core/__init__.py b/app/core/__init__.py new file mode 100644 index 0000000..b9a7cf7 --- /dev/null +++ b/app/core/__init__.py @@ -0,0 +1 @@ +# Core package initialization \ No newline at end of file diff --git a/app/core/config.py b/app/core/config.py new file mode 100644 index 0000000..ccbd77d --- /dev/null +++ b/app/core/config.py @@ -0,0 +1,28 @@ +from pathlib import Path +from pydantic import field_validator +from pydantic_settings import BaseSettings + +# Build paths +BASE_DIR = Path(__file__).resolve().parent.parent.parent + +class Settings(BaseSettings): + PROJECT_NAME: str = "Barebones Todo API" + API_V1_STR: str = "/api/v1" + + # SQLite Database settings + DB_DIR: Path = BASE_DIR / "storage" / "db" + SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite" + + @field_validator("SQLALCHEMY_DATABASE_URL") + def validate_db_url(cls, v, values): + # Ensure directory exists + db_dir = values.data.get("DB_DIR") + if db_dir: + db_dir.mkdir(parents=True, exist_ok=True) + return v + + class Config: + env_file = ".env" + case_sensitive = True + +settings = Settings() \ No newline at end of file diff --git a/app/db/__init__.py b/app/db/__init__.py new file mode 100644 index 0000000..7e91e76 --- /dev/null +++ b/app/db/__init__.py @@ -0,0 +1 @@ +# Database package initialization \ No newline at end of file diff --git a/app/db/base.py b/app/db/base.py new file mode 100644 index 0000000..379f09b --- /dev/null +++ b/app/db/base.py @@ -0,0 +1,4 @@ +# Import all the models, so that Base has them before being +# imported by Alembic +from app.db.base_class import Base # noqa +from app.models.todo import Todo # noqa \ No newline at end of file diff --git a/app/db/base_class.py b/app/db/base_class.py new file mode 100644 index 0000000..5f54016 --- /dev/null +++ b/app/db/base_class.py @@ -0,0 +1,12 @@ +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() \ No newline at end of file diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..7862695 --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,24 @@ +from pathlib import Path +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + + +# Ensure directory exists +DB_DIR = Path("/app") / "storage" / "db" +DB_DIR.mkdir(parents=True, exist_ok=True) + +SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite" + +engine = create_engine( + SQLALCHEMY_DATABASE_URL, + connect_args={"check_same_thread": False} +) +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + +# Dependency to get DB session +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() \ No newline at end of file diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000..3c51364 --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1 @@ +# Models package initialization \ No newline at end of file diff --git a/app/models/todo.py b/app/models/todo.py new file mode 100644 index 0000000..bdd1f53 --- /dev/null +++ b/app/models/todo.py @@ -0,0 +1,12 @@ +from datetime import datetime +from sqlalchemy import Boolean, Column, Integer, String, DateTime + +from app.db.base_class import Base + +class Todo(Base): + 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, default=datetime.utcnow) + updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) \ No newline at end of file diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..79518f7 --- /dev/null +++ b/app/schemas/__init__.py @@ -0,0 +1,6 @@ +# Schemas package initialization +from app.schemas.todo import Todo as Todo +from app.schemas.todo import TodoCreate as TodoCreate +from app.schemas.todo import TodoUpdate as TodoUpdate + +__all__ = ["Todo", "TodoCreate", "TodoUpdate"] \ No newline at end of file diff --git a/app/schemas/todo.py b/app/schemas/todo.py new file mode 100644 index 0000000..12b43e2 --- /dev/null +++ b/app/schemas/todo.py @@ -0,0 +1,32 @@ +from datetime import datetime +from typing import Optional + +from pydantic import BaseModel + +# Shared properties +class TodoBase(BaseModel): + title: str + description: Optional[str] = None + completed: bool = False + +# Properties to receive on todo creation +class TodoCreate(TodoBase): + pass + +# Properties to receive on todo update +class TodoUpdate(TodoBase): + title: Optional[str] = None + completed: Optional[bool] = None + +# Properties shared by models stored in DB +class TodoInDBBase(TodoBase): + id: int + created_at: datetime + updated_at: datetime + + class Config: + from_attributes = True + +# Properties to return to client +class Todo(TodoInDBBase): + pass \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..89fa9ff --- /dev/null +++ b/main.py @@ -0,0 +1,40 @@ +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, + openapi_url="/openapi.json", + version="0.1.0", +) + +# Set up CORS middleware +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# Include API router +app.include_router(api_router) + +# Root endpoint +@app.get("/") +async def root(): + return { + "title": settings.PROJECT_NAME, + "docs": "/docs", + "health": "/health" + } + +# Health check endpoint +@app.get("/health") +async def health_check(): + return {"status": "healthy"} + +if __name__ == "__main__": + uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) \ No newline at end of file diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000..3542e0e --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration with SQLite. \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..beeabb1 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,74 @@ +import os +import sys +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + +# Add the project root directory to the Python path so we can import app +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +# Import Base from the app +from app.db.base import Base # noqa + +# This is the Alembic Config object +config = context.config + +# Interpret the config file for Python logging +fileConfig(config.config_file_name) + +# Import all models for Alembic to detect +target_metadata = Base.metadata + +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. + + """ + 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 to handle ALTER TABLE operations properly + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() \ No newline at end of file diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..1e4564e --- /dev/null +++ b/migrations/script.py.mako @@ -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"} \ No newline at end of file diff --git a/migrations/versions/01_initial_todos_table.py b/migrations/versions/01_initial_todos_table.py new file mode 100644 index 0000000..9fec33e --- /dev/null +++ b/migrations/versions/01_initial_todos_table.py @@ -0,0 +1,39 @@ +"""Initial todos table + +Revision ID: 001 +Revises: +Create Date: 2023-09-20 + +""" +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(): + # Create todos table + op.create_table( + 'todo', + 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(), default=False, nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_todo_id'), 'todo', ['id'], unique=False) + op.create_index(op.f('ix_todo_title'), 'todo', ['title'], unique=False) + + +def downgrade(): + # Drop todos table + op.drop_index(op.f('ix_todo_title'), table_name='todo') + op.drop_index(op.f('ix_todo_id'), table_name='todo') + op.drop_table('todo') \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..aaaf94b --- /dev/null +++ b/requirements.txt @@ -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.290 \ No newline at end of file