diff --git a/README.md b/README.md index e8acfba..03d7602 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,107 @@ -# FastAPI Application +# REST API Service -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A REST API service built with FastAPI and SQLite. + +## Features + +- FastAPI for high-performance API endpoints +- SQLite database for simple data storage +- Alembic for database migrations +- Pydantic for data validation +- CORS middleware configured +- Health check endpoint +- API documentation with OpenAPI + +## Project Structure + +``` +. +├── alembic.ini # Alembic configuration +├── app # Application code +│ ├── api # API endpoints +│ │ ├── v1 # API version 1 +│ │ │ ├── api.py # API router +│ │ │ └── endpoints # API endpoint modules +│ │ │ └── items.py # Items endpoints +│ │ └── health.py # Health check endpoint +│ ├── core # Core modules +│ │ └── config.py # Application configuration +│ ├── db # Database code +│ │ └── base.py # Database connection code +│ ├── models # SQLAlchemy models +│ │ └── item.py # Item model +│ └── schemas # Pydantic schemas +│ └── item.py # Item schemas +├── main.py # Application entry point +├── migrations # Alembic migrations +│ ├── env.py # Alembic environment +│ ├── script.py.mako # Alembic script template +│ └── versions # Migration versions +│ └── 01_create_items_table.py # Initial migration +└── requirements.txt # Python dependencies +``` + +## Installation + +1. Clone the repository: + +```bash +git clone +cd +``` + +2. Create a virtual environment: + +```bash +python -m venv venv +source venv/bin/activate # On Windows: venv\Scripts\activate +``` + +3. Install dependencies: + +```bash +pip install -r requirements.txt +``` + +4. Configure environment variables: + +Create a `.env` file based on `.env.example`. + +## Database Migrations + +Initialize the database: + +```bash +alembic upgrade head +``` + +## Running the API + +Start the API server: + +```bash +uvicorn main:app --reload +``` + +The API will be available at http://localhost:8000. + +- API documentation: http://localhost:8000/docs +- ReDoc documentation: http://localhost:8000/redoc +- OpenAPI schema: http://localhost:8000/openapi.json +- Health check: http://localhost:8000/health + +## API Endpoints + +### Items + +- `GET /api/v1/items/`: List all items +- `POST /api/v1/items/`: Create a new item +- `GET /api/v1/items/{item_id}`: Get a specific item +- `PUT /api/v1/items/{item_id}`: Update a specific item +- `DELETE /api/v1/items/{item_id}`: Delete a specific item + +## Environment Variables + +- `APP_NAME`: Application name +- `API_V1_STR`: API v1 path prefix +- `CORS_ORIGINS`: CORS allowed origins \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..c75ad2f --- /dev/null +++ b/alembic.ini @@ -0,0 +1,86 @@ +# 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 + +# SQLite URL using absolute path +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/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/health.py b/app/api/health.py new file mode 100644 index 0000000..71e33ca --- /dev/null +++ b/app/api/health.py @@ -0,0 +1,28 @@ +from fastapi import APIRouter, Depends +from sqlalchemy.orm import Session +from typing import Dict + +from app.db.base import get_db + +router = APIRouter() + + +@router.get("/") +def health_check(db: Session = Depends(get_db)) -> Dict[str, str]: + """ + Perform a health check on the API. + + Checks database connection and returns status information. + """ + # Check database connection + try: + # Try to execute a simple query + db.execute("SELECT 1").first() + db_status = "healthy" + except Exception: + db_status = "unhealthy" + + return { + "status": "ok" if db_status == "healthy" else "error", + "database": db_status, + } \ No newline at end of file diff --git a/app/api/v1/__init__.py b/app/api/v1/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/v1/api.py b/app/api/v1/api.py new file mode 100644 index 0000000..b903694 --- /dev/null +++ b/app/api/v1/api.py @@ -0,0 +1,7 @@ +from fastapi import APIRouter + +from app.api.v1.endpoints import items + +api_router = APIRouter() + +api_router.include_router(items.router, prefix="/items", tags=["items"]) \ No newline at end of file diff --git a/app/api/v1/endpoints/__init__.py b/app/api/v1/endpoints/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/v1/endpoints/items.py b/app/api/v1/endpoints/items.py new file mode 100644 index 0000000..be1531a --- /dev/null +++ b/app/api/v1/endpoints/items.py @@ -0,0 +1,108 @@ +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session +from typing import Any, List + +from app.db.base import get_db +from app.models.item import Item as ItemModel +from app.schemas.item import Item, ItemCreate, ItemUpdate + +router = APIRouter() + + +@router.get("/", response_model=List[Item]) +def read_items( + skip: int = 0, + limit: int = 100, + db: Session = Depends(get_db), +) -> Any: + """ + Retrieve items. + """ + items = db.query(ItemModel).offset(skip).limit(limit).all() + return items + + +@router.post("/", response_model=Item, status_code=status.HTTP_201_CREATED) +def create_item( + *, + item_in: ItemCreate, + db: Session = Depends(get_db), +) -> Any: + """ + Create new item. + """ + db_item = ItemModel( + name=item_in.name, + description=item_in.description, + is_active=item_in.is_active, + ) + db.add(db_item) + db.commit() + db.refresh(db_item) + return db_item + + +@router.get("/{item_id}", response_model=Item) +def read_item( + *, + item_id: int, + db: Session = Depends(get_db), +) -> Any: + """ + Get item by ID. + """ + item = db.query(ItemModel).filter(ItemModel.id == item_id).first() + if not item: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Item not found", + ) + return item + + +@router.put("/{item_id}", response_model=Item) +def update_item( + *, + item_id: int, + item_in: ItemUpdate, + db: Session = Depends(get_db), +) -> Any: + """ + Update an item. + """ + item = db.query(ItemModel).filter(ItemModel.id == item_id).first() + if not item: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Item not found", + ) + + update_data = item_in.model_dump(exclude_unset=True) + for field, value in update_data.items(): + setattr(item, field, value) + + db.add(item) + db.commit() + db.refresh(item) + return item + + +@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None) +def delete_item( + *, + item_id: int, + db: Session = Depends(get_db), +) -> Any: + """ + Delete an item. + """ + item = db.query(ItemModel).filter(ItemModel.id == item_id).first() + if not item: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Item not found", + ) + + db.delete(item) + db.commit() + return None \ No newline at end of file diff --git a/app/core/config.py b/app/core/config.py new file mode 100644 index 0000000..4119cc6 --- /dev/null +++ b/app/core/config.py @@ -0,0 +1,33 @@ +from pathlib import Path +from pydantic_settings import BaseSettings +from typing import List + + +class Settings(BaseSettings): + """Application settings.""" + + # Base + APP_NAME: str = "REST API Service" + API_V1_STR: str = "/api/v1" + + # CORS + CORS_ORIGINS: List[str] = ["*"] + + # Database + DB_DIR: Path = Path("/app") / "storage" / "db" + SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite" + + class Config: + env_file = ".env" + case_sensitive = True + + +# Create DB directory if it doesn't exist +def create_db_dir(): + """Create database directory if it doesn't exist.""" + settings = Settings() + settings.DB_DIR.mkdir(parents=True, exist_ok=True) + + +# Get settings instance +settings = Settings() \ No newline at end of file diff --git a/app/db/__init__.py b/app/db/__init__.py new file mode 100644 index 0000000..c73520c --- /dev/null +++ b/app/db/__init__.py @@ -0,0 +1,2 @@ +# Import all models here so alembic can detect them +from app.db.base import Base # noqa: F401 \ No newline at end of file diff --git a/app/db/base.py b/app/db/base.py new file mode 100644 index 0000000..7407488 --- /dev/null +++ b/app/db/base.py @@ -0,0 +1,35 @@ +from sqlalchemy import create_engine +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker + +from app.core.config import settings, create_db_dir + +# Create database directory +create_db_dir() + +# Create SQLAlchemy engine +engine = create_engine( + settings.SQLALCHEMY_DATABASE_URL, + connect_args={"check_same_thread": False} # only needed for SQLite +) + +# Create SessionLocal class +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + +# Create Base class +Base = declarative_base() + + +# Dependency to get DB session +def get_db(): + """ + Dependency function to get a database session. + + Yields: + Session: SQLAlchemy database session + """ + db = SessionLocal() + try: + yield db + finally: + db.close() \ No newline at end of file diff --git a/app/db/base_class.py b/app/db/base_class.py new file mode 100644 index 0000000..a955f37 --- /dev/null +++ b/app/db/base_class.py @@ -0,0 +1,18 @@ +from sqlalchemy.ext.declarative import declared_attr +from sqlalchemy import Column, Integer, DateTime +from sqlalchemy.sql import func + + +class Base: + """Base class for all database models.""" + + # Generate __tablename__ automatically + @declared_attr + def __tablename__(cls) -> str: + return cls.__name__.lower() + + # Common columns for all models + id = Column(Integer, primary_key=True, index=True) + created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False) + updated_at = Column(DateTime(timezone=True), server_default=func.now(), + onupdate=func.now(), nullable=False) \ No newline at end of file diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000..4285ac0 --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1,3 @@ +from app.models.item import Item # noqa: F401 + +# Import all models here to ensure they are registered with SQLAlchemy \ No newline at end of file diff --git a/app/models/item.py b/app/models/item.py new file mode 100644 index 0000000..6067526 --- /dev/null +++ b/app/models/item.py @@ -0,0 +1,11 @@ +from sqlalchemy import Column, String, Boolean, Text + +from app.db.base import Base + + +class Item(Base): + """Item model.""" + + name = Column(String(255), index=True, nullable=False) + description = Column(Text, nullable=True) + is_active = Column(Boolean, default=True) \ No newline at end of file diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..e4c160f --- /dev/null +++ b/app/schemas/__init__.py @@ -0,0 +1,6 @@ +from app.schemas.item import ( # noqa: F401 + Item, + ItemCreate, + ItemUpdate, + ItemInDB, +) \ No newline at end of file diff --git a/app/schemas/item.py b/app/schemas/item.py new file mode 100644 index 0000000..ba33848 --- /dev/null +++ b/app/schemas/item.py @@ -0,0 +1,45 @@ +from pydantic import BaseModel, Field +from typing import Optional +from datetime import datetime + + +class ItemBase(BaseModel): + """Base schema for Item.""" + + name: str = Field(..., min_length=1, max_length=255, description="Name of the item") + description: Optional[str] = Field(None, description="Description of the item") + is_active: bool = Field(True, description="Whether the item is active") + + +class ItemCreate(ItemBase): + """Schema for creating a new Item.""" + pass + + +class ItemUpdate(BaseModel): + """Schema for updating an Item.""" + + name: Optional[str] = Field(None, min_length=1, max_length=255, description="Name of the item") + description: Optional[str] = Field(None, description="Description of the item") + is_active: Optional[bool] = Field(None, description="Whether the item is active") + + +class ItemInDBBase(ItemBase): + """Base schema for Item in DB.""" + + id: int + created_at: datetime + updated_at: datetime + + class Config: + from_attributes = True + + +class Item(ItemInDBBase): + """Schema for Item with all fields.""" + pass + + +class ItemInDB(ItemInDBBase): + """Schema for Item in DB (internal use).""" + pass \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..034939d --- /dev/null +++ b/main.py @@ -0,0 +1,52 @@ +import uvicorn +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from fastapi.openapi.utils import get_openapi + +from app.api.v1.api import api_router +from app.api.health import router as health_router +from app.core.config import settings + +# Create FastAPI app +app = FastAPI( + title=settings.APP_NAME, + openapi_url="/openapi.json", + docs_url="/docs", + redoc_url="/redoc", +) + +# Set up CORS middleware +app.add_middleware( + CORSMiddleware, + allow_origins=settings.CORS_ORIGINS, + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# Include routers +app.include_router(api_router, prefix=settings.API_V1_STR) +app.include_router(health_router, prefix="/health", tags=["health"]) + + +# Custom OpenAPI schema +def custom_openapi(): + if app.openapi_schema: + return app.openapi_schema + + openapi_schema = get_openapi( + title=settings.APP_NAME, + version="1.0.0", + description="REST API service with FastAPI and SQLite", + routes=app.routes, + ) + + app.openapi_schema = openapi_schema + return app.openapi_schema + + +app.openapi = custom_openapi + + +if __name__ == "__main__": + 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..5fc8b1e --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,83 @@ +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: + # Check if we're using SQLite and configure batch mode if needed + is_sqlite = connection.dialect.name == 'sqlite' + + context.configure( + connection=connection, + target_metadata=target_metadata, + render_as_batch=is_sqlite, # Enable batch mode for SQLite + ) + + 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/01_create_items_table.py b/migrations/versions/01_create_items_table.py new file mode 100644 index 0000000..b0e6909 --- /dev/null +++ b/migrations/versions/01_create_items_table.py @@ -0,0 +1,41 @@ +"""Create items table + +Revision ID: 01_create_items_table +Revises: +Create Date: 2023-06-02 10:00:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '01_create_items_table' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # Create items table + op.create_table( + 'item', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(length=255), nullable=False), + sa.Column('description', sa.Text(), 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=False), + sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + # Create index on name column + op.create_index(op.f('ix_item_name'), 'item', ['name'], unique=False) + op.create_index(op.f('ix_item_id'), 'item', ['id'], unique=False) + + +def downgrade(): + # Drop the indices first + op.drop_index(op.f('ix_item_name'), table_name='item') + op.drop_index(op.f('ix_item_id'), table_name='item') + # Drop the table + op.drop_table('item') \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..9c2a609 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,8 @@ +fastapi>=0.104.0 +uvicorn>=0.23.2 +sqlalchemy>=2.0.23 +alembic>=1.12.1 +pydantic>=2.4.2 +python-dotenv>=1.0.0 +ruff>=0.1.3 +httpx>=0.25.0 \ No newline at end of file