diff --git a/README.md b/README.md index e8acfba..1d46a21 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,120 @@ -# FastAPI Application +# Generic REST API Service -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +This is a FastAPI application that provides a simple generic REST API service with CRUD operations for an "Item" resource. + +## Features + +- FastAPI-based RESTful API +- SQLite database with SQLAlchemy ORM +- Alembic for database migrations +- Pydantic for data validation +- Comprehensive CRUD operations +- Health check endpoint +- Automatic OpenAPI documentation + +## Project Structure + +``` +├── alembic/ # Database migration files +│ ├── versions/ # Migration version scripts +│ ├── env.py # Alembic environment configuration +│ └── script.py.mako # Migration script template +├── app/ # Application package +│ ├── api/ # API routes +│ │ ├── endpoints/ # API endpoint modules +│ │ ├── api.py # API router setup +│ │ └── deps.py # Dependency injection functions +│ ├── core/ # Core application modules +│ │ └── config.py # Application configuration +│ ├── crud/ # CRUD operation modules +│ │ ├── base.py # Base CRUD operations +│ │ └── crud_item.py # Item-specific CRUD operations +│ ├── db/ # Database modules +│ │ ├── base.py # Import all models +│ │ ├── base_class.py # Base model class +│ │ ├── init_db.py # Database initialization +│ │ └── session.py # DB session setup +│ ├── models/ # SQLAlchemy models +│ │ └── item.py # Item model +│ └── schemas/ # Pydantic schemas +│ └── item.py # Item schema +├── alembic.ini # Alembic configuration +├── main.py # Application entry point +└── requirements.txt # Project dependencies +``` + +## Setup and Installation + +1. Clone the repository: + +```bash +git clone +cd generic-rest-api-service +``` + +2. Create and activate a virtual environment (optional, but recommended): + +```bash +python -m venv venv +source venv/bin/activate # On Windows: venv\\Scripts\\activate +``` + +3. Install dependencies: + +```bash +pip install -r requirements.txt +``` + +4. Run database migrations: + +```bash +alembic upgrade head +``` + +5. Start the application: + +```bash +uvicorn main:app --reload +``` + +The application will be available at http://127.0.0.1:8000. + +## API Documentation + +Once the application is running, you can access the automatically generated API documentation: + +- Swagger UI: http://127.0.0.1:8000/docs +- ReDoc: http://127.0.0.1:8000/redoc + +## API Endpoints + +### Health Check + +- GET `/api/v1/health`: Check if the service is healthy + +### Items + +- GET `/api/v1/items`: List all items + - Query parameters: + - `skip`: Number of items to skip (default: 0) + - `limit`: Maximum number of items to return (default: 100) + - `active_only`: If true, return only active items (default: false) +- POST `/api/v1/items`: Create a new item +- GET `/api/v1/items/{id}`: Get a specific item by ID +- PUT `/api/v1/items/{id}`: Update a specific item +- DELETE `/api/v1/items/{id}`: Delete a specific item (returns 204 No Content) + +## Development + +### Running Tests + +```bash +# Add test command here +``` + +### Linting with Ruff + +```bash +ruff check . +ruff format . +``` \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..44ae6d0 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,85 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +script_location = alembic + +# 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 alembic/versions. When using multiple version +# directories, initial revisions must be specified with --version-path +# version_locations = %(here)s/bar %(here)s/bat alembic/versions + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +# SQLite URL - using absolute path for reliability +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 \ No newline at end of file diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000..15701d9 --- /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 +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. +fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +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: + is_sqlite = connection.dialect.name == "sqlite" + context.configure( + connection=connection, + target_metadata=target_metadata, + render_as_batch=is_sqlite, # Key configuration for SQLite + ) + + 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..1e4564e --- /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(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} \ No newline at end of file diff --git a/alembic/versions/01_create_item_table.py b/alembic/versions/01_create_item_table.py new file mode 100644 index 0000000..d3d22b2 --- /dev/null +++ b/alembic/versions/01_create_item_table.py @@ -0,0 +1,45 @@ +"""create item table + +Revision ID: 01_create_item_table +Revises: +Create Date: 2023-10-01 + +""" + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = "01_create_item_table" +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + "item", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("title", sa.String(), nullable=True), + sa.Column("description", sa.String(), nullable=True), + sa.Column("is_active", sa.Boolean(), nullable=True, default=True), + 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_item_id"), "item", ["id"], unique=False) + op.create_index(op.f("ix_item_title"), "item", ["title"], unique=False) + op.create_index(op.f("ix_item_description"), "item", ["description"], unique=False) + + +def downgrade(): + op.drop_index(op.f("ix_item_description"), table_name="item") + op.drop_index(op.f("ix_item_title"), table_name="item") + op.drop_index(op.f("ix_item_id"), table_name="item") + op.drop_table("item") diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..42df631 --- /dev/null +++ b/app/__init__.py @@ -0,0 +1 @@ +# Required for package discovery diff --git a/app/api/api.py b/app/api/api.py new file mode 100644 index 0000000..8bb492d --- /dev/null +++ b/app/api/api.py @@ -0,0 +1,7 @@ +from fastapi import APIRouter + +from app.api.endpoints import items, health + +api_router = APIRouter() +api_router.include_router(health.router, tags=["health"]) +api_router.include_router(items.router, prefix="/items", tags=["items"]) diff --git a/app/api/deps.py b/app/api/deps.py new file mode 100644 index 0000000..b7f3844 --- /dev/null +++ b/app/api/deps.py @@ -0,0 +1,12 @@ +from typing import Generator + + +from app.db.session import SessionLocal + + +def get_db() -> Generator: + try: + db = SessionLocal() + yield db + finally: + db.close() diff --git a/app/api/endpoints/__init__.py b/app/api/endpoints/__init__.py new file mode 100644 index 0000000..42df631 --- /dev/null +++ b/app/api/endpoints/__init__.py @@ -0,0 +1 @@ +# Required for package discovery diff --git a/app/api/endpoints/health.py b/app/api/endpoints/health.py new file mode 100644 index 0000000..045e505 --- /dev/null +++ b/app/api/endpoints/health.py @@ -0,0 +1,19 @@ +from fastapi import APIRouter, Depends +from sqlalchemy.orm import Session + +from app.api import deps + +router = APIRouter() + + +@router.get("/health", summary="Check service health") +def health_check(db: Session = Depends(deps.get_db)): + """ + Check service health: + - Database connection is active + - API is responding + """ + # Try to execute a simple query to check DB connection + db.execute("SELECT 1") + + return {"status": "ok", "message": "Service is healthy"} diff --git a/app/api/endpoints/items.py b/app/api/endpoints/items.py new file mode 100644 index 0000000..d0ece04 --- /dev/null +++ b/app/api/endpoints/items.py @@ -0,0 +1,87 @@ +from typing import Any, List + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app import crud, schemas +from app.api import deps + +router = APIRouter() + + +@router.get("/", response_model=List[schemas.Item]) +def read_items( + db: Session = Depends(deps.get_db), + skip: int = 0, + limit: int = 100, + active_only: bool = False, +) -> Any: + """ + Retrieve items. + """ + if active_only: + items = crud.item.get_active_items(db, skip=skip, limit=limit) + else: + items = crud.item.get_multi(db, skip=skip, limit=limit) + return items + + +@router.post("/", response_model=schemas.Item, status_code=status.HTTP_201_CREATED) +def create_item( + *, + db: Session = Depends(deps.get_db), + item_in: schemas.ItemCreate, +) -> Any: + """ + Create new item. + """ + item = crud.item.create(db=db, obj_in=item_in) + return item + + +@router.get("/{id}", response_model=schemas.Item) +def read_item( + *, + db: Session = Depends(deps.get_db), + id: int, +) -> Any: + """ + Get item by ID. + """ + item = crud.item.get(db=db, id=id) + if not item: + raise HTTPException(status_code=404, detail="Item not found") + return item + + +@router.put("/{id}", response_model=schemas.Item) +def update_item( + *, + db: Session = Depends(deps.get_db), + id: int, + item_in: schemas.ItemUpdate, +) -> Any: + """ + Update an item. + """ + item = crud.item.get(db=db, id=id) + if not item: + raise HTTPException(status_code=404, detail="Item not found") + item = crud.item.update(db=db, db_obj=item, obj_in=item_in) + return item + + +@router.delete("/{id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None) +def delete_item( + *, + db: Session = Depends(deps.get_db), + id: int, +) -> Any: + """ + Delete an item. + """ + item = crud.item.get(db=db, id=id) + if not item: + raise HTTPException(status_code=404, detail="Item not found") + item = crud.item.remove(db=db, id=id) + return None diff --git a/app/core/__init__.py b/app/core/__init__.py new file mode 100644 index 0000000..42df631 --- /dev/null +++ b/app/core/__init__.py @@ -0,0 +1 @@ +# Required for package discovery diff --git a/app/core/config.py b/app/core/config.py new file mode 100644 index 0000000..07d29cc --- /dev/null +++ b/app/core/config.py @@ -0,0 +1,30 @@ +import secrets + +from pydantic import AnyHttpUrl, BaseSettings, validator + + +class Settings(BaseSettings): + API_V1_STR: str = "/api/v1" + SECRET_KEY: str = secrets.token_urlsafe(32) + # 60 minutes * 24 hours * 8 days = 8 days + ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8 + # BACKEND_CORS_ORIGINS is a JSON-formatted list of origins + # e.g: '["http://localhost", "http://localhost:4200", "http://localhost:3000", \ + # "http://localhost:8080", "http://local.dockertoolbox.tiangolo.com"]' + BACKEND_CORS_ORIGINS: list[AnyHttpUrl] = [] + + @validator("BACKEND_CORS_ORIGINS", pre=True) + def assemble_cors_origins(cls, v: str | list[str]) -> list[str] | str: + if isinstance(v, str) and not v.startswith("["): + return [i.strip() for i in v.split(",")] + elif isinstance(v, (list, str)): + return v + raise ValueError(v) + + PROJECT_NAME: str = "Generic REST API Service" + + class Config: + case_sensitive = True + + +settings = Settings() diff --git a/app/crud/__init__.py b/app/crud/__init__.py new file mode 100644 index 0000000..9904741 --- /dev/null +++ b/app/crud/__init__.py @@ -0,0 +1,5 @@ +from app.crud.crud_item import item as item + +# For easy import in API routes +# Import all CRUD operations here +# Example: from app.crud import item diff --git a/app/crud/base.py b/app/crud/base.py new file mode 100644 index 0000000..1dcee01 --- /dev/null +++ b/app/crud/base.py @@ -0,0 +1,66 @@ +from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union + +from fastapi.encoders import jsonable_encoder +from pydantic import BaseModel +from sqlalchemy.orm import Session + +from app.db.base_class import Base + +ModelType = TypeVar("ModelType", bound=Base) +CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel) +UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel) + + +class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): + def __init__(self, model: Type[ModelType]): + """ + CRUD object with default methods to Create, Read, Update, Delete (CRUD). + + **Parameters** + + * `model`: A SQLAlchemy model class + * `schema`: A Pydantic model (schema) class + """ + self.model = model + + def get(self, db: Session, id: Any) -> Optional[ModelType]: + return db.query(self.model).filter(self.model.id == id).first() + + def get_multi( + self, db: Session, *, skip: int = 0, limit: int = 100 + ) -> List[ModelType]: + return db.query(self.model).offset(skip).limit(limit).all() + + def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType: + obj_in_data = jsonable_encoder(obj_in) + db_obj = self.model(**obj_in_data) # type: ignore + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + def update( + self, + db: Session, + *, + db_obj: ModelType, + obj_in: Union[UpdateSchemaType, Dict[str, Any]], + ) -> ModelType: + obj_data = jsonable_encoder(db_obj) + if isinstance(obj_in, dict): + update_data = obj_in + else: + update_data = obj_in.dict(exclude_unset=True) + for field in obj_data: + if field in update_data: + setattr(db_obj, field, update_data[field]) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + def remove(self, db: Session, *, id: int) -> ModelType: + obj = db.query(self.model).get(id) + db.delete(obj) + db.commit() + return obj diff --git a/app/crud/crud_item.py b/app/crud/crud_item.py new file mode 100644 index 0000000..f301718 --- /dev/null +++ b/app/crud/crud_item.py @@ -0,0 +1,20 @@ +from typing import List, Optional + +from sqlalchemy.orm import Session + +from app.crud.base import CRUDBase +from app.models.item import Item +from app.schemas.item import ItemCreate, ItemUpdate + + +class CRUDItem(CRUDBase[Item, ItemCreate, ItemUpdate]): + def get_by_title(self, db: Session, *, title: str) -> Optional[Item]: + return db.query(Item).filter(Item.title == title).first() + + def get_active_items( + self, db: Session, *, skip: int = 0, limit: int = 100 + ) -> List[Item]: + return db.query(Item).filter(Item.is_active).offset(skip).limit(limit).all() + + +item = CRUDItem(Item) diff --git a/app/db/base.py b/app/db/base.py new file mode 100644 index 0000000..dcf5649 --- /dev/null +++ b/app/db/base.py @@ -0,0 +1,4 @@ +# Import all the models, so that Base has them before being +# imported by Alembic +from app.db.base_class import Base # noqa +from app.models.item import Item # noqa diff --git a/app/db/base_class.py b/app/db/base_class.py new file mode 100644 index 0000000..1e2aabe --- /dev/null +++ b/app/db/base_class.py @@ -0,0 +1,14 @@ +from typing import Any + +from sqlalchemy.ext.declarative import as_declarative, declared_attr + + +@as_declarative() +class Base: + id: Any + __name__: str + + # Generate __tablename__ automatically + @declared_attr + def __tablename__(cls) -> str: + return cls.__name__.lower() diff --git a/app/db/init_db.py b/app/db/init_db.py new file mode 100644 index 0000000..03a1c14 --- /dev/null +++ b/app/db/init_db.py @@ -0,0 +1,7 @@ +from app.db.base import Base +from app.db.session import engine + + +# Create tables if they don't exist +def init_db() -> None: + Base.metadata.create_all(bind=engine) diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..2308d43 --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,13 @@ +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) diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000..6633541 --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1 @@ +from app.models.item import Item as Item diff --git a/app/models/item.py b/app/models/item.py new file mode 100644 index 0000000..a6e54d6 --- /dev/null +++ b/app/models/item.py @@ -0,0 +1,13 @@ +from sqlalchemy import Column, Integer, String, Boolean, DateTime +from sqlalchemy.sql import func + +from app.db.base_class import Base + + +class Item(Base): + id = Column(Integer, primary_key=True, index=True) + title = Column(String, index=True) + description = Column(String, index=True) + is_active = Column(Boolean(), default=True) + created_at = Column(DateTime(timezone=True), server_default=func.now()) + updated_at = Column(DateTime(timezone=True), onupdate=func.now()) diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..746fd5a --- /dev/null +++ b/app/schemas/__init__.py @@ -0,0 +1,5 @@ +# Import all schemas here to expose them +from app.schemas.item import Item as Item +from app.schemas.item import ItemCreate as ItemCreate +from app.schemas.item import ItemInDB as ItemInDB +from app.schemas.item import ItemUpdate as ItemUpdate diff --git a/app/schemas/item.py b/app/schemas/item.py new file mode 100644 index 0000000..b1be420 --- /dev/null +++ b/app/schemas/item.py @@ -0,0 +1,44 @@ +from datetime import datetime +from typing import Optional + +from pydantic import BaseModel, Field + + +# Shared properties +class ItemBase(BaseModel): + title: Optional[str] = None + description: Optional[str] = None + is_active: Optional[bool] = True + + +# Properties to receive on item creation +class ItemCreate(ItemBase): + title: str = Field(..., min_length=1, max_length=100) + + +# Properties to receive on item update +class ItemUpdate(ItemBase): + pass + + +# Properties shared by models stored in DB +class ItemInDBBase(ItemBase): + id: int + title: str + description: Optional[str] = None + is_active: bool + created_at: datetime + updated_at: Optional[datetime] = None + + class Config: + orm_mode = True + + +# Properties to return to client +class Item(ItemInDBBase): + pass + + +# Properties stored in DB +class ItemInDB(ItemInDBBase): + pass diff --git a/main.py b/main.py new file mode 100644 index 0000000..8ece19c --- /dev/null +++ b/main.py @@ -0,0 +1,16 @@ +import uvicorn +from fastapi import FastAPI +from app.api.api import api_router +from app.core.config import settings + +app = FastAPI( + title=settings.PROJECT_NAME, + openapi_url=f"{settings.API_V1_STR}/openapi.json", + description="A simple generic REST API service", + version="0.1.0", +) + +app.include_router(api_router, prefix=settings.API_V1_STR) + +if __name__ == "__main__": + uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..9d45151 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,10 @@ +fastapi>=0.103.1,<0.104.0 +uvicorn>=0.23.2,<0.24.0 +sqlalchemy>=2.0.20,<2.1.0 +alembic>=1.12.0,<1.13.0 +pydantic>=2.3.0,<2.4.0 +python-dotenv>=1.0.0,<1.1.0 +python-multipart>=0.0.6,<0.0.7 +email-validator>=2.0.0,<2.1.0 +ruff>=0.0.291 +pathlib>=1.0.1,<1.1.0 \ No newline at end of file