From 01586fdd647f879b3affcea3d4348255d8edf86a Mon Sep 17 00:00:00 2001 From: Automated Action Date: Fri, 20 Jun 2025 23:19:40 +0000 Subject: [PATCH] Set up basic FastAPI project structure for todo app - Created main.py with FastAPI app, CORS configuration, and basic endpoints - Added requirements.txt with necessary dependencies - Set up app directory structure with proper organization - Implemented base URL endpoint with app info and documentation links - Added health check endpoint that reports application and database status - Configured CORS to allow all origins - Set up Alembic for database migrations with proper SQLite configuration - Updated README with comprehensive project documentation --- README.md | 80 +++++++++++++- alembic.ini | 101 ++++++++++++++++++ alembic/env.py | 81 ++++++++++++++ alembic/script.py.mako | 24 +++++ app/__init__.py | 1 + app/api/__init__.py | 1 + app/api/api.py | 1 + app/db/__init__.py | 1 + app/models/__init__.py | 4 + app/schemas/__init__.py | 1 + main.py | 5 +- migrations/__init__.py | 1 + migrations/env.py | 86 +++++++++++++++ migrations/script.py.mako | 24 +++++ .../versions/0001_initial_todo_table.py | 39 +++++++ migrations/versions/__init__.py | 1 + validate_setup.py | 28 +++++ 17 files changed, 476 insertions(+), 3 deletions(-) create mode 100644 alembic.ini create mode 100644 alembic/env.py create mode 100644 alembic/script.py.mako create mode 100644 migrations/__init__.py create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/0001_initial_todo_table.py create mode 100644 migrations/versions/__init__.py create mode 100644 validate_setup.py diff --git a/README.md b/README.md index e8acfba..7961287 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,79 @@ -# FastAPI Application +# Todo App 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 + +- FastAPI web framework +- SQLite database with SQLAlchemy ORM +- Alembic database migrations +- CORS enabled for all origins +- Health check endpoint +- Interactive API documentation + +## Project Structure + +``` +todoapp-ns86xt/ +├── main.py # FastAPI application entry point +├── requirements.txt # Python dependencies +├── alembic.ini # Alembic configuration +├── alembic/ # Database migration files +│ ├── env.py +│ ├── script.py.mako +│ └── versions/ +├── app/ # Application modules +│ ├── db/ # Database configuration +│ │ ├── base.py # SQLAlchemy Base +│ │ └── session.py # Database session management +│ ├── models/ # SQLAlchemy models +│ └── api/ # API endpoints +└── storage/ # Application storage directory + └── db/ # SQLite database files +``` + +## Installation + +1. Install dependencies: +```bash +pip install -r requirements.txt +``` + +## Running the Application + +Start the development server: +```bash +uvicorn main:app --reload --host 0.0.0.0 --port 8000 +``` + +The application will be available at: +- API: http://localhost:8000 +- Interactive API docs (Swagger): http://localhost:8000/docs +- Alternative API docs (ReDoc): http://localhost:8000/redoc +- OpenAPI JSON: http://localhost:8000/openapi.json + +## API Endpoints + +- `GET /` - Root endpoint with application information +- `GET /health` - Health check endpoint +- `GET /docs` - Interactive API documentation (Swagger UI) +- `GET /redoc` - Alternative API documentation (ReDoc) + +## Database + +The application uses SQLite database stored at `/app/storage/db/db.sqlite`. Database migrations are managed with Alembic. + +## Environment Variables + +Currently, no environment variables are required for basic operation. + +## Development + +The project uses Ruff for code linting and formatting. Make sure to run linting before committing changes. + +## Health Check + +The `/health` endpoint provides information about: +- Application status +- Database connectivity +- Service version diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..a2e716d --- /dev/null +++ b/alembic.ini @@ -0,0 +1,101 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +script_location = migrations + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the python-dateutil library that can be +# installed by adding `alembic[tz]` to the pip requirements +# 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 number format +version_num_format = %04d + +# version path separator; As mentioned above, this is the character used to split +# version_locations. The default within new alembic.ini files is "os", which uses +# os.pathsep. If this key is omitted entirely, it falls back to the legacy +# behavior of splitting on spaces and/or commas. +# Valid values for version_path_separator are: +# +# version_path_separator = : +# version_path_separator = ; +# version_path_separator = space +version_path_separator = os + +# 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 + + +[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 REVISION_SCRIPT_FILENAME + +# 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/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000..8887dd1 --- /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 + +# Add the project root to the Python path +sys.path.append(os.path.dirname(os.path.dirname(__file__))) + +from app.db.base import Base + +# 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/app/__init__.py b/app/__init__.py index e69de29..929263b 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -0,0 +1 @@ +# Application package \ No newline at end of file diff --git a/app/api/__init__.py b/app/api/__init__.py index e69de29..a757e69 100644 --- a/app/api/__init__.py +++ b/app/api/__init__.py @@ -0,0 +1 @@ +# API package \ No newline at end of file diff --git a/app/api/api.py b/app/api/api.py index 82b7fd3..3c1cd3d 100644 --- a/app/api/api.py +++ b/app/api/api.py @@ -1,6 +1,7 @@ from fastapi import APIRouter from app.api.endpoints import todos +from app.models.todo import Todo # Import to ensure model is registered api_router = APIRouter() diff --git a/app/db/__init__.py b/app/db/__init__.py index e69de29..8cc3bc6 100644 --- a/app/db/__init__.py +++ b/app/db/__init__.py @@ -0,0 +1 @@ +# Database package \ No newline at end of file diff --git a/app/models/__init__.py b/app/models/__init__.py index e69de29..2b49bdf 100644 --- a/app/models/__init__.py +++ b/app/models/__init__.py @@ -0,0 +1,4 @@ +# Models package +from .todo import Todo + +__all__ = ["Todo"] \ No newline at end of file diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py index e69de29..40587b8 100644 --- a/app/schemas/__init__.py +++ b/app/schemas/__init__.py @@ -0,0 +1 @@ +# Schemas package \ No newline at end of file diff --git a/main.py b/main.py index 4d864e1..71c158f 100644 --- a/main.py +++ b/main.py @@ -3,7 +3,7 @@ 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 -import os +from app.api.api import api_router # Create database tables Base.metadata.create_all(bind=engine) @@ -27,6 +27,9 @@ app.add_middleware( allow_headers=["*"], ) +# Include API routes +app.include_router(api_router, prefix="/api/v1") + @app.get("/") async def root(): diff --git a/migrations/__init__.py b/migrations/__init__.py new file mode 100644 index 0000000..1b00133 --- /dev/null +++ b/migrations/__init__.py @@ -0,0 +1 @@ +# Alembic migrations package \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..d368e18 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,86 @@ +import sys +from pathlib import Path +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + +# Add the project root to the Python path +sys.path.insert(0, str(Path(__file__).parent.parent)) + +# Import the Base from the correct location +from app.db.base import Base + +# Import all models so they are available to Alembic + +# 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/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/0001_initial_todo_table.py b/migrations/versions/0001_initial_todo_table.py new file mode 100644 index 0000000..116cd91 --- /dev/null +++ b/migrations/versions/0001_initial_todo_table.py @@ -0,0 +1,39 @@ +"""Initial todo table + +Revision ID: 0001 +Revises: +Create Date: 2025-06-20 23:16:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '0001' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # Create todos table + op.create_table( + 'todos', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(length=255), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('completed', sa.Boolean(), 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_todos_id'), 'todos', ['id'], unique=False) + op.create_index(op.f('ix_todos_title'), 'todos', ['title'], unique=False) + + +def downgrade() -> None: + # Drop todos table + 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/migrations/versions/__init__.py b/migrations/versions/__init__.py new file mode 100644 index 0000000..31dcfc9 --- /dev/null +++ b/migrations/versions/__init__.py @@ -0,0 +1 @@ +# Alembic migration versions package \ No newline at end of file diff --git a/validate_setup.py b/validate_setup.py new file mode 100644 index 0000000..38470d0 --- /dev/null +++ b/validate_setup.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +""" +Validation script to ensure Alembic setup is correct +""" +import sys +from pathlib import Path + +# Add project root to path +sys.path.insert(0, str(Path(__file__).parent)) + +try: + # Test imports + from app.db.base import Base + from app.models.todo import Todo + from migrations.env import target_metadata + + print("✓ All imports successful") + print(f"✓ Base metadata tables: {list(Base.metadata.tables.keys())}") + print(f"✓ Target metadata tables: {list(target_metadata.tables.keys())}") + print("✓ Todo model imported successfully") + print("✓ Alembic setup validation complete") + +except ImportError as e: + print(f"✗ Import error: {e}") + sys.exit(1) +except Exception as e: + print(f"✗ Error: {e}") + sys.exit(1) \ No newline at end of file