From 4c0d7531acaf4835af633ede12b815b338db28e9 Mon Sep 17 00:00:00 2001 From: Automated Action Date: Thu, 19 Jun 2025 22:46:52 +0000 Subject: [PATCH] Create simple FastAPI todo app with SQLite database --- README.md | 56 +++++++++++++++++- alembic.ini | 41 +++++++++++++ alembic/env.py | 50 ++++++++++++++++ alembic/script.py.mako | 23 ++++++++ alembic/versions/001_create_todos_table.py | 41 +++++++++++++ app/crud.py | 42 +++++++++++++ app/db/base.py | 3 + app/db/session.py | 22 +++++++ app/models.py | 14 +++++ app/schemas.py | 28 +++++++++ main.py | 69 ++++++++++++++++++++++ requirements.txt | 7 +++ 12 files changed, 394 insertions(+), 2 deletions(-) create mode 100644 alembic.ini create mode 100644 alembic/env.py create mode 100644 alembic/script.py.mako create mode 100644 alembic/versions/001_create_todos_table.py create mode 100644 app/crud.py create mode 100644 app/db/base.py create mode 100644 app/db/session.py create mode 100644 app/models.py create mode 100644 app/schemas.py create mode 100644 main.py create mode 100644 requirements.txt diff --git a/README.md b/README.md index e8acfba..56d05f0 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,55 @@ -# FastAPI Application +# Todo App API -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A simple FastAPI-based Todo application with SQLite database. + +## Features + +- Create, read, update, and delete todos +- SQLite database with SQLAlchemy ORM +- Database migrations with Alembic +- CORS enabled for all origins +- Health check endpoint +- Interactive API documentation + +## API Endpoints + +- `GET /` - Root endpoint with app information +- `GET /health` - Health check endpoint +- `GET /todos/` - Get all todos (with pagination) +- `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 + +## Documentation + +- API documentation: `/docs` +- Alternative documentation: `/redoc` +- OpenAPI schema: `/openapi.json` + +## Setup and Running + +1. Install dependencies: + ```bash + pip install -r requirements.txt + ``` + +2. Run the application: + ```bash + uvicorn main:app --reload + ``` + +The application will be available at `http://localhost:8000`. + +## Database + +The application uses SQLite database stored at `/app/storage/db/db.sqlite`. + +## Todo Schema + +- `id`: Integer (auto-generated) +- `title`: String (required) +- `description`: String (optional) +- `completed`: Boolean (default: false) +- `created_at`: DateTime (auto-generated) +- `updated_at`: DateTime (auto-updated) diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..017f263 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,41 @@ +[alembic] +script_location = alembic +prepend_sys_path = . +version_path_separator = os +sqlalchemy.url = sqlite:////app/storage/db/db.sqlite + +[post_write_hooks] + +[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/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000..a274b6c --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,50 @@ +from logging.config import fileConfig +from sqlalchemy import engine_from_config +from sqlalchemy import pool +from alembic import context +import sys +import os + +sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) + +from app.db.base import Base + +config = context.config + +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +target_metadata = Base.metadata + + +def run_migrations_offline() -> None: + 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: + 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() diff --git a/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 0000000..30bbf8d --- /dev/null +++ b/alembic/script.py.mako @@ -0,0 +1,23 @@ +"""${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 = '${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/alembic/versions/001_create_todos_table.py b/alembic/versions/001_create_todos_table.py new file mode 100644 index 0000000..0185a4f --- /dev/null +++ b/alembic/versions/001_create_todos_table.py @@ -0,0 +1,41 @@ +"""Create todos table + +Revision ID: 001 +Revises: +Create Date: 2024-01-01 00:00:00.000000 + +""" + +from alembic import op +import sqlalchemy as sa + +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=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) + 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") diff --git a/app/crud.py b/app/crud.py new file mode 100644 index 0000000..cc49ddd --- /dev/null +++ b/app/crud.py @@ -0,0 +1,42 @@ +from typing import List, Optional +from sqlalchemy.orm import Session +from app.models import Todo +from app.schemas import TodoCreate, TodoUpdate + + +def get_todo(db: Session, todo_id: int) -> Optional[Todo]: + return db.query(Todo).filter(Todo.id == todo_id).first() + + +def get_todos(db: Session, skip: int = 0, limit: int = 100) -> List[Todo]: + return db.query(Todo).offset(skip).limit(limit).all() + + +def create_todo(db: Session, todo: TodoCreate) -> Todo: + 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 + + +def update_todo(db: Session, todo_id: int, todo_update: TodoUpdate) -> Optional[Todo]: + db_todo = db.query(Todo).filter(Todo.id == todo_id).first() + if db_todo: + update_data = todo_update.dict(exclude_unset=True) + for field, value in update_data.items(): + setattr(db_todo, field, value) + db.commit() + db.refresh(db_todo) + return db_todo + + +def delete_todo(db: Session, todo_id: int) -> bool: + db_todo = db.query(Todo).filter(Todo.id == todo_id).first() + if db_todo: + db.delete(db_todo) + db.commit() + return True + return False diff --git a/app/db/base.py b/app/db/base.py new file mode 100644 index 0000000..860e542 --- /dev/null +++ b/app/db/base.py @@ -0,0 +1,3 @@ +from sqlalchemy.ext.declarative import declarative_base + +Base = declarative_base() diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..fbff7a0 --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,22 @@ +from pathlib import Path +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +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) + + +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() diff --git a/app/models.py b/app/models.py new file mode 100644 index 0000000..2d1aad9 --- /dev/null +++ b/app/models.py @@ -0,0 +1,14 @@ +from sqlalchemy import Boolean, Column, Integer, String, DateTime +from sqlalchemy.sql import func +from app.db.base import Base + + +class Todo(Base): + __tablename__ = "todos" + + id = Column(Integer, primary_key=True, index=True) + title = Column(String, index=True, nullable=False) + description = Column(String, nullable=True) + completed = Column(Boolean, default=False, nullable=False) + created_at = Column(DateTime(timezone=True), server_default=func.now()) + updated_at = Column(DateTime(timezone=True), onupdate=func.now()) diff --git a/app/schemas.py b/app/schemas.py new file mode 100644 index 0000000..269edc7 --- /dev/null +++ b/app/schemas.py @@ -0,0 +1,28 @@ +from datetime import datetime +from typing import Optional +from pydantic import BaseModel + + +class TodoBase(BaseModel): + title: str + description: Optional[str] = None + completed: 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: Optional[datetime] = None + + class Config: + from_attributes = True diff --git a/main.py b/main.py new file mode 100644 index 0000000..0576472 --- /dev/null +++ b/main.py @@ -0,0 +1,69 @@ +from typing import List +from fastapi import FastAPI, Depends, HTTPException +from fastapi.middleware.cors import CORSMiddleware +from sqlalchemy.orm import Session + +from app.db.session import get_db, engine +from app.db.base import Base +from app import crud, schemas + +Base.metadata.create_all(bind=engine) + +app = FastAPI( + title="Todo App API", + description="A simple Todo application API", + version="1.0.0", + openapi_url="/openapi.json", +) + +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + + +@app.get("/") +def read_root(): + return {"title": "Todo App API", "documentation": "/docs", "health": "/health"} + + +@app.get("/health") +def health_check(): + return {"status": "healthy", "service": "Todo App API"} + + +@app.get("/todos/", response_model=List[schemas.Todo]) +def read_todos(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): + todos = crud.get_todos(db, skip=skip, limit=limit) + return todos + + +@app.post("/todos/", response_model=schemas.Todo) +def create_todo(todo: schemas.TodoCreate, db: Session = Depends(get_db)): + return crud.create_todo(db=db, todo=todo) + + +@app.get("/todos/{todo_id}", response_model=schemas.Todo) +def read_todo(todo_id: int, db: Session = Depends(get_db)): + db_todo = crud.get_todo(db, todo_id=todo_id) + if db_todo is None: + raise HTTPException(status_code=404, detail="Todo not found") + return db_todo + + +@app.put("/todos/{todo_id}", response_model=schemas.Todo) +def update_todo(todo_id: int, todo: schemas.TodoUpdate, db: Session = Depends(get_db)): + db_todo = crud.update_todo(db, todo_id=todo_id, todo_update=todo) + if db_todo is None: + raise HTTPException(status_code=404, detail="Todo not found") + return db_todo + + +@app.delete("/todos/{todo_id}") +def delete_todo(todo_id: int, db: Session = Depends(get_db)): + if not crud.delete_todo(db, todo_id=todo_id): + raise HTTPException(status_code=404, detail="Todo not found") + return {"message": "Todo deleted successfully"} diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..98f9e19 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,7 @@ +fastapi==0.104.1 +uvicorn[standard]==0.24.0 +sqlalchemy==2.0.23 +alembic==1.12.1 +pydantic==2.5.0 +python-multipart==0.0.6 +ruff==0.1.6 \ No newline at end of file