diff --git a/README.md b/README.md index e8acfba..b312f6b 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,48 @@ -# FastAPI Application +# REST API Service -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A FastAPI-based REST API service. + +## Project Structure + +``` +/projects/restapiservice-12nbts/ +├── alembic.ini # Alembic configuration +├── app # Application package +│ ├── api # API endpoints +│ │ └── endpoints # Route handlers +│ ├── core # Core modules +│ │ └── config.py # Application settings +│ ├── db # Database modules +│ │ ├── base.py # Import all models for Alembic +│ │ ├── base_class.py # SQLAlchemy Base class +│ │ └── session.py # Database session management +│ ├── models # SQLAlchemy models +│ ├── schemas # Pydantic schemas for request/response +│ └── services # Business logic +├── main.py # Application entry point +├── migrations # Alembic migrations +│ └── versions # Migration scripts +├── requirements.txt # Project dependencies +└── tests # Test modules +``` + +## Getting Started + +1. Clone the repository +2. Install dependencies: + ``` + pip install -r requirements.txt + ``` +3. Run the application: + ``` + uvicorn main:app --reload + ``` + +## API Documentation + +- Swagger UI: [http://localhost:8000/docs](http://localhost:8000/docs) +- ReDoc: [http://localhost:8000/redoc](http://localhost:8000/redoc) + +## Health Check + +- GET `/health`: Returns a health status of the application \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..94b9968 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,84 @@ +# 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 + +# timezone to use when rendering the date +# within the migration file as well as the filename. +# 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 +# version_locations = %(here)s/bar %(here)s/bat migrations/versions + +# 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 + +# 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 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..6236f88 --- /dev/null +++ b/app/api/endpoints/__init__.py @@ -0,0 +1,7 @@ +from fastapi import APIRouter + +router = APIRouter() + +# Import and include routers from endpoint modules +# Example: from .items import router as items_router +# router.include_router(items_router, prefix="/items", tags=["items"]) diff --git a/app/core/__init__.py b/app/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/core/config.py b/app/core/config.py new file mode 100644 index 0000000..8757f6f --- /dev/null +++ b/app/core/config.py @@ -0,0 +1,21 @@ +import secrets +from pathlib import Path +from pydantic import BaseSettings + +class Settings(BaseSettings): + PROJECT_NAME: str = "REST API Service" + API_V1_STR: str = "/api/v1" + VERSION: str = "0.1.0" + SECRET_KEY: str = secrets.token_urlsafe(32) + ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8 # 8 days + + # Database + DB_DIR = Path("/app") / "storage" / "db" + DB_DIR.mkdir(parents=True, exist_ok=True) + SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite" + + class Config: + env_file = ".env" + case_sensitive = True + +settings = Settings() 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..2e642c0 --- /dev/null +++ b/app/db/base.py @@ -0,0 +1,3 @@ +# Import all models here for Alembic to detect +from app.db.base_class import Base +# Example: from app.models.item import Item diff --git a/app/db/base_class.py b/app/db/base_class.py new file mode 100644 index 0000000..db99348 --- /dev/null +++ b/app/db/base_class.py @@ -0,0 +1,11 @@ +from typing import Any +from sqlalchemy.ext.declarative import as_declarative, declared_attr + +@as_declarative() +class Base: + id: Any + __name__: str + + @declared_attr + def __tablename__(cls) -> str: + return cls.__name__.lower() diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..ad2026a --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,19 @@ +from sqlalchemy import create_engine +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker + +from app.core.config import settings + +engine = create_engine( + settings.SQLALCHEMY_DATABASE_URL, + connect_args={"check_same_thread": False} # Only needed for SQLite +) +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) +Base = declarative_base() + +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/services/__init__.py b/app/services/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/main.py b/main.py new file mode 100644 index 0000000..9ae88b2 --- /dev/null +++ b/main.py @@ -0,0 +1,15 @@ +import uvicorn +from fastapi import FastAPI +from app.api.endpoints import router as api_router +from app.core.config import settings + +app = FastAPI(title=settings.PROJECT_NAME, version=settings.VERSION) + +app.include_router(api_router, prefix=settings.API_V1_STR) + +@app.get('/health', tags=['Health']) +async def health_check(): + return {"status": "healthy"} + +if __name__ == "__main__": + uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000..9c7febd --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration with Alembic. diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..5e286d1 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,78 @@ +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.db.base import Base # noqa +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() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..2c01563 --- /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"} diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..a9159ac --- /dev/null +++ b/requirements.txt @@ -0,0 +1,11 @@ +fastapi>=0.68.0 +pydantic>=1.8.2 +uvicorn>=0.15.0 +sqlalchemy>=1.4.23 +alembic>=1.7.1 +python-dotenv>=0.19.0 +python-jose>=3.3.0 +passlib>=1.7.4 +python-multipart>=0.0.5 +email-validator>=1.1.3 +ruff>=0.0.290 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29