From 2f75e43b7f5b66e93fe4ca25fdde3abe8e5b9ac9 Mon Sep 17 00:00:00 2001 From: Automated Action Date: Sat, 24 May 2025 22:41:36 +0000 Subject: [PATCH] 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 --- README.md | 104 ++++++++++++++++++- alembic.ini | 73 +++++++++++++ app/__init__.py | 0 app/api/__init__.py | 0 app/api/deps.py | 2 + app/api/routers.py | 7 ++ app/api/v1/__init__.py | 0 app/api/v1/health.py | 28 +++++ app/api/v1/todos.py | 99 ++++++++++++++++++ app/core/__init__.py | 0 app/core/config.py | 30 ++++++ app/crud/__init__.py | 0 app/crud/base.py | 65 ++++++++++++ app/crud/todo.py | 24 +++++ app/db/__init__.py | 0 app/db/base.py | 1 + app/db/base_class.py | 14 +++ app/db/session.py | 25 +++++ app/models/__init__.py | 0 app/models/todo.py | 14 +++ app/schemas/__init__.py | 0 app/schemas/todo.py | 37 +++++++ main.py | 37 +++++++ migrations/env.py | 62 +++++++++++ migrations/script.py.mako | 24 +++++ migrations/versions/01_initial_todo_table.py | 35 +++++++ requirements.txt | 7 ++ 27 files changed, 686 insertions(+), 2 deletions(-) create mode 100644 alembic.ini create mode 100644 app/__init__.py create mode 100644 app/api/__init__.py create mode 100644 app/api/deps.py create mode 100644 app/api/routers.py create mode 100644 app/api/v1/__init__.py create mode 100644 app/api/v1/health.py create mode 100644 app/api/v1/todos.py create mode 100644 app/core/__init__.py create mode 100644 app/core/config.py create mode 100644 app/crud/__init__.py create mode 100644 app/crud/base.py create mode 100644 app/crud/todo.py create mode 100644 app/db/__init__.py create mode 100644 app/db/base.py create mode 100644 app/db/base_class.py create mode 100644 app/db/session.py create mode 100644 app/models/__init__.py create mode 100644 app/models/todo.py create mode 100644 app/schemas/__init__.py create mode 100644 app/schemas/todo.py create mode 100644 main.py create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/01_initial_todo_table.py create mode 100644 requirements.txt diff --git a/README.md b/README.md index e8acfba..25dff32 100644 --- a/README.md +++ b/README.md @@ -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) \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..c359295 --- /dev/null +++ b/alembic.ini @@ -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 \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/deps.py b/app/api/deps.py new file mode 100644 index 0000000..139597f --- /dev/null +++ b/app/api/deps.py @@ -0,0 +1,2 @@ + + diff --git a/app/api/routers.py b/app/api/routers.py new file mode 100644 index 0000000..3a7d8a4 --- /dev/null +++ b/app/api/routers.py @@ -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"]) \ 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..e69de29 diff --git a/app/api/v1/health.py b/app/api/v1/health.py new file mode 100644 index 0000000..68dad2a --- /dev/null +++ b/app/api/v1/health.py @@ -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) + } \ No newline at end of file diff --git a/app/api/v1/todos.py b/app/api/v1/todos.py new file mode 100644 index 0000000..131ed7d --- /dev/null +++ b/app/api/v1/todos.py @@ -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 \ No newline at end of file diff --git a/app/core/__init__.py b/app/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/core/config.py b/app/core/config.py new file mode 100644 index 0000000..62cb456 --- /dev/null +++ b/app/core/config.py @@ -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) \ No newline at end of file diff --git a/app/crud/__init__.py b/app/crud/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/crud/base.py b/app/crud/base.py new file mode 100644 index 0000000..3e2577a --- /dev/null +++ b/app/crud/base.py @@ -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 \ No newline at end of file diff --git a/app/crud/todo.py b/app/crud/todo.py new file mode 100644 index 0000000..c5d6b58 --- /dev/null +++ b/app/crud/todo.py @@ -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) \ No newline at end of file diff --git a/app/db/__init__.py b/app/db/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/db/base.py b/app/db/base.py new file mode 100644 index 0000000..8b9a4cd --- /dev/null +++ b/app/db/base.py @@ -0,0 +1 @@ +# Import all models for Alembic to detect diff --git a/app/db/base_class.py b/app/db/base_class.py new file mode 100644 index 0000000..16d816c --- /dev/null +++ b/app/db/base_class.py @@ -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() \ No newline at end of file diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..c4b7696 --- /dev/null +++ b/app/db/session.py @@ -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() \ No newline at end of file diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/models/todo.py b/app/models/todo.py new file mode 100644 index 0000000..2ef5e97 --- /dev/null +++ b/app/models/todo.py @@ -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) \ No newline at end of file diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/schemas/todo.py b/app/schemas/todo.py new file mode 100644 index 0000000..8d1ff0d --- /dev/null +++ b/app/schemas/todo.py @@ -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 \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..edc0a93 --- /dev/null +++ b/main.py @@ -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) \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..ad9fe76 --- /dev/null +++ b/migrations/env.py @@ -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() \ 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_todo_table.py b/migrations/versions/01_initial_todo_table.py new file mode 100644 index 0000000..2e0cb5b --- /dev/null +++ b/migrations/versions/01_initial_todo_table.py @@ -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') \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..8faaf53 --- /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.287 \ No newline at end of file