diff --git a/README.md b/README.md index e8acfba..f3fb354 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,69 @@ -# FastAPI Application +# Todo Application -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A simple Todo application built with FastAPI and SQLite. + +## Features + +- Create, read, update, and delete todos +- Filter todos by completion status +- Health endpoint for application monitoring + +## Project Structure + +``` +/ +├── app/ +│ ├── api/ +│ │ ├── endpoints/ +│ │ │ ├── health.py # Health check endpoint +│ │ │ └── todos.py # Todo CRUD operations +│ ├── db/ +│ │ ├── base.py # SQLAlchemy Base +│ │ └── session.py # Database session management +│ ├── models/ +│ │ └── todo.py # SQLAlchemy Todo model +│ └── schemas/ +│ └── todo.py # Pydantic schemas for Todo +├── alembic/ # Database migrations +├── main.py # FastAPI application +└── requirements.txt # Project dependencies +``` + +## Setup + +1. Install dependencies: + +```bash +pip install -r requirements.txt +``` + +2. Run migrations: + +```bash +alembic upgrade head +``` + +3. Start the application: + +```bash +uvicorn main:app --reload +``` + +## API Endpoints + +### Todos + +- `GET /api/todos`: List all todos +- `POST /api/todos`: Create a new todo +- `GET /api/todos/{todo_id}`: Get a specific todo +- `PUT /api/todos/{todo_id}`: Update a todo +- `DELETE /api/todos/{todo_id}`: Delete a todo + +### Health + +- `GET /health`: Check application health + +## API Documentation + +- Swagger UI: `/docs` +- ReDoc: `/redoc` \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..91f0690 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,40 @@ +[alembic] +script_location = alembic +prepend_sys_path = . +version_path_separator = os + +sqlalchemy.url = sqlite:////app/storage/db/db.sqlite + +[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/README b/alembic/README new file mode 100644 index 0000000..f3a049c --- /dev/null +++ b/alembic/README @@ -0,0 +1 @@ +Generic single-database configuration with SQLAlchemy. \ No newline at end of file diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000..22f2ae6 --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,81 @@ +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.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +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() \ No newline at end of file diff --git a/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 0000000..37d0cac --- /dev/null +++ b/alembic/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/alembic/versions/initial_migration.py b/alembic/versions/initial_migration.py new file mode 100644 index 0000000..e3e2c32 --- /dev/null +++ b/alembic/versions/initial_migration.py @@ -0,0 +1,36 @@ +"""initial migration + +Revision ID: initial +Revises: +Create Date: 2023-11-01 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'initial' +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, default=False), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + 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') \ 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/endpoints/__init__.py b/app/api/endpoints/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/endpoints/health.py b/app/api/endpoints/health.py new file mode 100644 index 0000000..8f176ad --- /dev/null +++ b/app/api/endpoints/health.py @@ -0,0 +1,23 @@ +from fastapi import APIRouter, Depends +from sqlalchemy.orm import Session +from app.db.session import get_db + +router = APIRouter( + prefix="/health", + tags=["health"], +) + + +@router.get("/") +def health_check(db: Session = Depends(get_db)): + try: + # Check if database is accessible + db.execute("SELECT 1") + db_status = "ok" + except Exception as e: + db_status = f"error: {str(e)}" + + return { + "status": "ok", + "database": db_status + } \ No newline at end of file diff --git a/app/api/endpoints/todos.py b/app/api/endpoints/todos.py new file mode 100644 index 0000000..aa78b53 --- /dev/null +++ b/app/api/endpoints/todos.py @@ -0,0 +1,70 @@ +from typing import List, Optional +from fastapi import APIRouter, Depends, HTTPException, Query, status +from sqlalchemy.orm import Session + +from app.db.session import get_db +from app.models.todo import Todo +from app.schemas.todo import TodoCreate, TodoUpdate, Todo as TodoSchema + +router = APIRouter( + prefix="/todos", + tags=["todos"], + responses={404: {"description": "Not found"}}, +) + + +@router.post("/", response_model=TodoSchema, status_code=status.HTTP_201_CREATED) +def create_todo(todo: TodoCreate, db: Session = Depends(get_db)): + db_todo = Todo(**todo.dict()) + db.add(db_todo) + db.commit() + db.refresh(db_todo) + return db_todo + + +@router.get("/", response_model=List[TodoSchema]) +def read_todos( + skip: int = 0, + limit: int = 100, + completed: Optional[bool] = None, + db: Session = Depends(get_db) +): + query = db.query(Todo) + if completed is not None: + query = query.filter(Todo.completed == completed) + todos = query.offset(skip).limit(limit).all() + return todos + + +@router.get("/{todo_id}", response_model=TodoSchema) +def read_todo(todo_id: int, db: Session = Depends(get_db)): + db_todo = db.query(Todo).filter(Todo.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=TodoSchema) +def update_todo(todo_id: int, todo: TodoUpdate, db: Session = Depends(get_db)): + db_todo = db.query(Todo).filter(Todo.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(Todo).filter(Todo.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/__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..7c2377a --- /dev/null +++ b/app/db/base.py @@ -0,0 +1,3 @@ +from sqlalchemy.ext.declarative import declarative_base + +Base = declarative_base() \ No newline at end of file diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..e77d375 --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,23 @@ +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() \ 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..13b1203 --- /dev/null +++ b/app/models/todo.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) + description = Column(String, nullable=True) + completed = Column(Boolean, default=False) + created_at = Column(DateTime(timezone=True), server_default=func.now()) + updated_at = Column(DateTime(timezone=True), onupdate=func.now()) \ 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..5cb0ca6 --- /dev/null +++ b/app/schemas/todo.py @@ -0,0 +1,32 @@ +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 TodoInDB(TodoBase): + id: int + created_at: datetime + updated_at: Optional[datetime] = None + + class Config: + orm_mode = True + + +class Todo(TodoInDB): + pass \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..b17a0d2 --- /dev/null +++ b/main.py @@ -0,0 +1,13 @@ +from fastapi import FastAPI +from app.api.endpoints import todos, health +from app.db.session import engine +from app.db.base import Base + +# Create database tables +Base.metadata.create_all(bind=engine) + +app = FastAPI(title="Todo Application", description="A simple todo application") + +# Include routers +app.include_router(health.router) +app.include_router(todos.router, prefix="/api") \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..5149f7f --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +fastapi==0.104.1 +uvicorn==0.23.2 +sqlalchemy==2.0.22 +pydantic==2.4.2 +alembic==1.12.1 +ruff==0.1.5 \ No newline at end of file