From 8e743adf11e087d82723c8916635060e7e38fc8e Mon Sep 17 00:00:00 2001 From: Automated Action Date: Thu, 5 Jun 2025 07:45:16 +0000 Subject: [PATCH] Setup FastAPI project with SQLite integration --- README.md | 89 +++++++++++++++++++- alembic.ini | 102 +++++++++++++++++++++++ app/__init__.py | 0 app/api/__init__.py | 0 app/api/routes/__init__.py | 0 app/api/routes/api.py | 11 +++ app/api/routes/health.py | 25 ++++++ app/db/session.py | 25 ++++++ app/models/__init__.py | 1 + app/models/base.py | 3 + app/schemas/__init__.py | 0 main.py | 51 ++++++++++++ migrations/__init__.py | 0 migrations/env.py | 76 +++++++++++++++++ migrations/script.py.mako | 24 ++++++ migrations/versions/initial_migration.py | 28 +++++++ requirements.txt | 8 ++ 17 files changed, 441 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/routes/__init__.py create mode 100644 app/api/routes/api.py create mode 100644 app/api/routes/health.py create mode 100644 app/db/session.py create mode 100644 app/models/__init__.py create mode 100644 app/models/base.py create mode 100644 app/schemas/__init__.py create mode 100644 main.py create mode 100644 migrations/__init__.py 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..14aa2fb 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,88 @@ -# FastAPI Application +# General Communication Service -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A FastAPI-based general purpose communication service with SQLite integration. + +## Features + +- FastAPI-based REST API +- SQLite database integration +- Alembic migrations +- CORS enabled with all origins allowed +- Health check endpoint +- API documentation at default paths + +## Project Structure + +``` +/ +├── app/ +│ ├── api/ +│ │ ├── routes/ +│ │ │ ├── health.py +│ │ │ └── api.py +│ ├── core/ +│ ├── db/ +│ │ └── session.py +│ ├── models/ +│ │ └── base.py +│ └── schemas/ +├── migrations/ +│ ├── versions/ +│ ├── env.py +│ └── script.py.mako +├── storage/ +│ └── db/ +├── alembic.ini +├── main.py +├── requirements.txt +└── README.md +``` + +## Installation + +1. Clone the repository +2. Install 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 + +- Swagger UI: http://localhost:8000/docs +- ReDoc: http://localhost:8000/redoc +- OpenAPI JSON: http://localhost:8000/openapi.json + +## Database Migrations + +Generate a new migration: + +```bash +alembic revision --autogenerate -m "description" +``` + +Apply migrations: + +```bash +alembic upgrade head +``` + +## Environment Variables + +None required for basic setup, as SQLite database path is configured internally. + +## Database Configuration + +SQLite database is configured to be stored at: + +``` +/app/storage/db/db.sqlite +``` \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..98965b6 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,102 @@ +# 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 + +# 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 location specification; This defaults +# to migrations/versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "version_path_separator" below. +# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions + +# 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 # Use os.pathsep. Default configuration used for new projects. + +# 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/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/routes/__init__.py b/app/api/routes/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/routes/api.py b/app/api/routes/api.py new file mode 100644 index 0000000..7b06223 --- /dev/null +++ b/app/api/routes/api.py @@ -0,0 +1,11 @@ +from fastapi import APIRouter + +router = APIRouter() + + +@router.get("/", tags=["Root"]) +def root(): + """ + Root API endpoint. + """ + return {"message": "Welcome to the General Communication Service API"} \ 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..e35f7df --- /dev/null +++ b/app/api/routes/health.py @@ -0,0 +1,25 @@ +from fastapi import APIRouter, Depends +from sqlalchemy.orm import Session + +from app.db.session import get_db + +router = APIRouter() + + +@router.get("/health", tags=["Health"]) +def health_check(db: Session = Depends(get_db)): + """ + Health check endpoint to verify if the API is up and running. + Also checks database connectivity. + """ + try: + # Verify database connection + db.execute("SELECT 1") + db_status = "healthy" + except Exception: + db_status = "unhealthy" + + return { + "status": "healthy", + "database": db_status + } \ No newline at end of file diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..f784204 --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,25 @@ +from pathlib import Path +from sqlalchemy import create_engine +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker + +# Create DB 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) + +# Database dependency +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..68d5cd5 --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1 @@ +from app.models.base import Base \ No newline at end of file diff --git a/app/models/base.py b/app/models/base.py new file mode 100644 index 0000000..7c2377a --- /dev/null +++ b/app/models/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/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/main.py b/main.py new file mode 100644 index 0000000..b4e6bb0 --- /dev/null +++ b/main.py @@ -0,0 +1,51 @@ +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from fastapi.openapi.utils import get_openapi + +from app.api.routes import health, api +from app.db.session import engine +from app.models import base + +# Create database tables +base.Base.metadata.create_all(bind=engine) + +app = FastAPI( + title="General Communication Service", + description="A general purpose communication service API", + version="0.1.0", +) + +# Enable CORS +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# Include routes +app.include_router(health.router) +app.include_router(api.router, prefix="/api/v1") + + +# Custom OpenAPI schema +def custom_openapi(): + if app.openapi_schema: + return app.openapi_schema + openapi_schema = get_openapi( + title=app.title, + version=app.version, + description=app.description, + routes=app.routes, + ) + app.openapi_schema = openapi_schema + return app.openapi_schema + + +app.openapi = custom_openapi + + +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/__init__.py b/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..32b6706 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,76 @@ +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + +# 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. +fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +from app.models.base import Base +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(): + """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(): + """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..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/initial_migration.py b/migrations/versions/initial_migration.py new file mode 100644 index 0000000..917af97 --- /dev/null +++ b/migrations/versions/initial_migration.py @@ -0,0 +1,28 @@ +"""Initial migration + +Revision ID: initial_migration +Revises: +Create Date: 2025-06-05 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'initial_migration' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + pass + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + pass + # ### end Alembic commands ### \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..55275e9 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,8 @@ +fastapi==0.104.1 +uvicorn==0.24.0 +sqlalchemy==2.0.23 +pydantic==2.4.2 +pydantic-settings==2.0.3 +alembic==1.12.1 +python-dotenv==1.0.0 +ruff==0.1.5 \ No newline at end of file