From 10ef945a25cb280fcc310293d5e582cd08e1fb14 Mon Sep 17 00:00:00 2001 From: Automated Action Date: Tue, 13 May 2025 06:22:39 +0000 Subject: [PATCH] Build simple Todo application with FastAPI and SQLite - Created REST API for managing todo items - Implemented SQLite database with SQLAlchemy ORM - Added Alembic for database migrations - Added health check endpoint generated with BackendIM... (backend.im) --- README.md | 84 ++++++++++++++++++++++- alembic.ini | 40 +++++++++++ app/api/routes/health.py | 23 +++++++ app/api/routes/todos.py | 56 +++++++++++++++ app/db/database.py | 26 +++++++ app/db/init_db.py | 5 ++ app/models/todo.py | 13 ++++ app/schemas/todo.py | 24 +++++++ main.py | 20 ++++++ migrations/README | 1 + migrations/env.py | 86 ++++++++++++++++++++++++ migrations/script.py.mako | 24 +++++++ migrations/versions/initial_migration.py | 36 ++++++++++ requirements.txt | 6 ++ 14 files changed, 442 insertions(+), 2 deletions(-) create mode 100644 alembic.ini create mode 100644 app/api/routes/health.py create mode 100644 app/api/routes/todos.py create mode 100644 app/db/database.py create mode 100644 app/db/init_db.py create mode 100644 app/models/todo.py create mode 100644 app/schemas/todo.py create mode 100644 main.py create mode 100644 migrations/README create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/initial_migration.py create mode 100644 requirements.txt diff --git a/README.md b/README.md index e8acfba..a3d3cbb 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,83 @@ -# FastAPI Application +# Simple Todo Application -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A simple Todo API application built with FastAPI and SQLite. + +## Features + +- RESTful API for managing todo items +- SQLite database with SQLAlchemy ORM +- Alembic migrations for database versioning +- Health check endpoint +- Swagger UI documentation + +## Project Structure + +``` +. +├── alembic.ini +├── app +│ ├── api +│ │ └── routes +│ │ ├── health.py +│ │ └── todos.py +│ ├── db +│ │ ├── database.py +│ │ └── init_db.py +│ ├── models +│ │ └── todo.py +│ └── schemas +│ └── todo.py +├── main.py +├── migrations +│ ├── README +│ ├── env.py +│ ├── script.py.mako +│ └── versions +│ └── initial_migration.py +└── requirements.txt +``` + +## Installation + +1. Clone the repository +2. Install the dependencies: + +```bash +pip install -r requirements.txt +``` + +## Running the Application + +```bash +uvicorn main:app --reload +``` + +The application will be available at http://localhost:8000. + +API Documentation is available at: +- Swagger UI: http://localhost:8000/docs +- ReDoc: http://localhost:8000/redoc + +## API Endpoints + +### Health Check +- `GET /health` - Check API health + +### Todo Operations +- `GET /todos` - List all todos +- `POST /todos` - Create a new todo +- `GET /todos/{todo_id}` - Get a specific todo +- `PUT /todos/{todo_id}` - Update a todo +- `DELETE /todos/{todo_id}` - Delete a todo + +## Database + +The application uses SQLite with SQLAlchemy ORM. The database file is stored at `/app/storage/db/db.sqlite`. + +## Migrations + +This project uses Alembic for database migrations. To run 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..66903f9 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,40 @@ +[alembic] +script_location = migrations +prepend_sys_path = . +version_path_separator = os + +sqlalchemy.url = driver://user:pass@localhost/dbname + +[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/api/routes/health.py b/app/api/routes/health.py new file mode 100644 index 0000000..a3f4047 --- /dev/null +++ b/app/api/routes/health.py @@ -0,0 +1,23 @@ +from fastapi import APIRouter, Depends +from sqlalchemy.orm import Session +from app.db.database import get_db + +router = APIRouter( + prefix="/health", + tags=["health"] +) + +@router.get("/") +def health_check(db: Session = Depends(get_db)): + # Check if database connection is working by executing a simple query + try: + db.execute("SELECT 1") + db_status = "healthy" + except Exception: + db_status = "unhealthy" + + return { + "status": "ok", + "database": db_status, + "api_version": "0.1.0" + } \ No newline at end of file diff --git a/app/api/routes/todos.py b/app/api/routes/todos.py new file mode 100644 index 0000000..20f4c8b --- /dev/null +++ b/app/api/routes/todos.py @@ -0,0 +1,56 @@ +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session +from typing import List + +from app.db.database import get_db +from app.models.todo import Todo as TodoModel +from app.schemas.todo import Todo, TodoCreate, TodoUpdate + +router = APIRouter( + prefix="/todos", + tags=["todos"] +) + +@router.post("/", response_model=Todo, status_code=status.HTTP_201_CREATED) +def create_todo(todo: TodoCreate, db: Session = Depends(get_db)): + db_todo = TodoModel(**todo.dict()) + db.add(db_todo) + db.commit() + db.refresh(db_todo) + return db_todo + +@router.get("/", response_model=List[Todo]) +def read_todos(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): + todos = db.query(TodoModel).offset(skip).limit(limit).all() + return todos + +@router.get("/{todo_id}", response_model=Todo) +def read_todo(todo_id: int, db: Session = Depends(get_db)): + 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)): + 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.dict(exclude_unset=True) + for key, value in update_data.items(): + setattr(db_todo, key, value) + + db.commit() + db.refresh(db_todo) + return db_todo + +@router.delete("/{todo_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_todo(todo_id: int, db: Session = Depends(get_db)): + 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/db/database.py b/app/db/database.py new file mode 100644 index 0000000..bde256d --- /dev/null +++ b/app/db/database.py @@ -0,0 +1,26 @@ +from pathlib import Path +from sqlalchemy import create_engine +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker + +# Create database directory if it doesn't exist +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) + +Base = declarative_base() + +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() \ No newline at end of file diff --git a/app/db/init_db.py b/app/db/init_db.py new file mode 100644 index 0000000..2ac53e4 --- /dev/null +++ b/app/db/init_db.py @@ -0,0 +1,5 @@ +from app.db.database import engine, Base +from app.models.todo import Todo + +def create_tables(): + Base.metadata.create_all(bind=engine) \ No newline at end of file diff --git a/app/models/todo.py b/app/models/todo.py new file mode 100644 index 0000000..9bfbd20 --- /dev/null +++ b/app/models/todo.py @@ -0,0 +1,13 @@ +from sqlalchemy import Column, Integer, String, Boolean, DateTime +from sqlalchemy.sql import func +from app.db.database import Base + +class Todo(Base): + __tablename__ = "todos" + + id = Column(Integer, primary_key=True, index=True) + title = Column(String, index=True) + description = Column(String) + completed = Column(Boolean, default=False) + created_at = Column(DateTime, default=func.now()) + updated_at = Column(DateTime, default=func.now(), onupdate=func.now()) \ No newline at end of file diff --git a/app/schemas/todo.py b/app/schemas/todo.py new file mode 100644 index 0000000..7c784fe --- /dev/null +++ b/app/schemas/todo.py @@ -0,0 +1,24 @@ +from pydantic import BaseModel +from datetime import datetime +from typing import Optional + +class TodoBase(BaseModel): + title: str + description: Optional[str] = None + completed: Optional[bool] = False + +class TodoCreate(TodoBase): + pass + +class TodoUpdate(BaseModel): + title: Optional[str] = None + description: Optional[str] = None + completed: Optional[bool] = None + +class Todo(TodoBase): + id: int + created_at: datetime + updated_at: datetime + + class Config: + from_attributes = True \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..cd27a73 --- /dev/null +++ b/main.py @@ -0,0 +1,20 @@ +from fastapi import FastAPI +from app.api.routes import todos, health +from app.db.init_db import create_tables + +app = FastAPI( + title="Todo API", + description="A simple Todo API built with FastAPI and SQLite", + version="0.1.0" +) + +@app.on_event("startup") +async def startup(): + create_tables() + +app.include_router(todos.router) +app.include_router(health.router) + +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/README b/migrations/README new file mode 100644 index 0000000..fae95fd --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration with Alembic. \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..cec6fca --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,86 @@ +from logging.config import fileConfig +from pathlib import Path + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + +from app.db.database 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 + +# Override sqlalchemy.url with our database URL +DB_DIR = Path("/app") / "storage" / "db" +DB_DIR.mkdir(parents=True, exist_ok=True) +SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite" +config.set_main_option("sqlalchemy.url", SQLALCHEMY_DATABASE_URL) + +# 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() \ No newline at end of file diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..37d0cac --- /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() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} \ No newline at end of file diff --git a/migrations/versions/initial_migration.py b/migrations/versions/initial_migration.py new file mode 100644 index 0000000..c2e6531 --- /dev/null +++ b/migrations/versions/initial_migration.py @@ -0,0 +1,36 @@ +"""initial_migration + +Revision ID: 001 +Revises: +Create Date: 2025-05-13 + +""" +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: + op.create_table('todos', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.Column('completed', sa.Boolean(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=True), + 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() -> None: + 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') \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..b307dc0 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +fastapi==0.104.0 +uvicorn==0.23.2 +sqlalchemy==2.0.22 +pydantic==2.4.2 +alembic==1.12.1 +python-dotenv==1.0.0 \ No newline at end of file