diff --git a/README.md b/README.md index e8acfba..f859f98 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,109 @@ -# FastAPI Application +# REST API Service -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A comprehensive REST API built with FastAPI, SQLAlchemy, and SQLite. + +## Features + +- **FastAPI**: Modern, fast web framework for building APIs +- **SQLAlchemy**: SQL toolkit and Object-Relational Mapping (ORM) library +- **SQLite**: Lightweight database for data persistence +- **Alembic**: Database migration tool +- **CORS**: Cross-Origin Resource Sharing enabled for all origins +- **Health Check**: Built-in health monitoring endpoint +- **API Documentation**: Automatic interactive API docs via OpenAPI/Swagger + +## Project Structure + +``` +. +├── main.py # Application entry point +├── requirements.txt # Python dependencies +├── alembic.ini # Alembic configuration +├── alembic/ # Database migrations +│ ├── env.py +│ ├── script.py.mako +│ └── versions/ +└── app/ + ├── api/ # API routes + │ ├── items.py # Items CRUD endpoints + │ └── routes.py # Main router + ├── db/ # Database configuration + │ ├── base.py # SQLAlchemy Base + │ └── session.py # Database session + ├── models/ # SQLAlchemy models + │ └── item.py # Item model + └── schemas/ # Pydantic schemas + └── item.py # Item schemas +``` + +## Installation + +1. Install dependencies: +```bash +pip install -r requirements.txt +``` + +2. Run database migrations: +```bash +alembic upgrade head +``` + +## Running the Application + +Start the server with uvicorn: +```bash +uvicorn main:app --host 0.0.0.0 --port 8000 --reload +``` + +The API will be available at: +- **API Base**: http://localhost:8000 +- **Interactive Docs**: http://localhost:8000/docs +- **ReDoc**: http://localhost:8000/redoc +- **OpenAPI Schema**: http://localhost:8000/openapi.json + +## API Endpoints + +### Core Endpoints +- `GET /` - Service information +- `GET /health` - Health check + +### Items API (`/api/v1/items`) +- `POST /` - Create a new item +- `GET /` - List all items (with pagination) +- `GET /{item_id}` - Get item by ID +- `PUT /{item_id}` - Update item by ID +- `DELETE /{item_id}` - Delete item by ID + +## Database + +The application uses SQLite with the database file stored at `/app/storage/db/db.sqlite`. + +### Running Migrations + +Create a new migration: +```bash +alembic revision --autogenerate -m "Description of changes" +``` + +Apply migrations: +```bash +alembic upgrade head +``` + +## Development + +### Code Quality + +The project uses Ruff for code formatting and linting: +```bash +ruff check . +ruff format . +``` + +### Environment Variables + +No environment variables are required for basic operation. The application uses SQLite with a default file path. + +## License + +This project is open source and available under the MIT License. diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..a8e82d9 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,41 @@ +[alembic] +script_location = alembic +file_template = %%(year)d%%(month).2d%%(day).2d_%%(hour).2d%%(minute).2d%%(second).2d_%%(slug)s + +sqlalchemy.url = sqlite:////app/storage/db/db.sqlite + +[post_write_hooks] + +[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..8bb8b3c --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,52 @@ +from logging.config import fileConfig +from sqlalchemy import engine_from_config +from sqlalchemy import pool +from alembic import context +import sys +from pathlib import Path + +# Add the project root to sys.path +sys.path.insert(0, str(Path(__file__).parent.parent)) + +from app.db.base import Base + +config = context.config + +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +target_metadata = Base.metadata + +def run_migrations_offline() -> None: + 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: + 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/alembic/versions/20241219_120000_initial_migration.py b/alembic/versions/20241219_120000_initial_migration.py new file mode 100644 index 0000000..af8e67c --- /dev/null +++ b/alembic/versions/20241219_120000_initial_migration.py @@ -0,0 +1,35 @@ +"""Initial migration + +Revision ID: 001 +Revises: +Create Date: 2024-12-19 12:00:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + +# revision identifiers, used by Alembic. +revision = '001' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table('items', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('description', sa.String(), nullable=True), + sa.Column('is_active', sa.Boolean(), nullable=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_items_id'), 'items', ['id'], unique=False) + op.create_index(op.f('ix_items_name'), 'items', ['name'], unique=False) + + +def downgrade() -> None: + op.drop_index(op.f('ix_items_name'), table_name='items') + op.drop_index(op.f('ix_items_id'), table_name='items') + op.drop_table('items') \ 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/items.py b/app/api/items.py new file mode 100644 index 0000000..9e42742 --- /dev/null +++ b/app/api/items.py @@ -0,0 +1,53 @@ +from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy.orm import Session +from typing import List + +from app.db.session import get_db +from app.models.item import Item +from app.schemas.item import Item as ItemSchema, ItemCreate, ItemUpdate + +router = APIRouter() + +@router.post("/", response_model=ItemSchema) +def create_item(item: ItemCreate, db: Session = Depends(get_db)): + db_item = Item(**item.dict()) + db.add(db_item) + db.commit() + db.refresh(db_item) + return db_item + +@router.get("/", response_model=List[ItemSchema]) +def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): + items = db.query(Item).offset(skip).limit(limit).all() + return items + +@router.get("/{item_id}", response_model=ItemSchema) +def read_item(item_id: int, db: Session = Depends(get_db)): + item = db.query(Item).filter(Item.id == item_id).first() + if item is None: + raise HTTPException(status_code=404, detail="Item not found") + return item + +@router.put("/{item_id}", response_model=ItemSchema) +def update_item(item_id: int, item_update: ItemUpdate, db: Session = Depends(get_db)): + db_item = db.query(Item).filter(Item.id == item_id).first() + if db_item is None: + raise HTTPException(status_code=404, detail="Item not found") + + update_data = item_update.dict(exclude_unset=True) + for field, value in update_data.items(): + setattr(db_item, field, value) + + db.commit() + db.refresh(db_item) + return db_item + +@router.delete("/{item_id}") +def delete_item(item_id: int, db: Session = Depends(get_db)): + db_item = db.query(Item).filter(Item.id == item_id).first() + if db_item is None: + raise HTTPException(status_code=404, detail="Item not found") + + db.delete(db_item) + db.commit() + return {"message": "Item deleted successfully"} \ No newline at end of file diff --git a/app/api/routes.py b/app/api/routes.py new file mode 100644 index 0000000..ef40ea7 --- /dev/null +++ b/app/api/routes.py @@ -0,0 +1,6 @@ +from fastapi import APIRouter +from app.api 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/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..7c2377a --- /dev/null +++ b/app/db/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/db/session.py b/app/db/session.py new file mode 100644 index 0000000..b6f41f1 --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,22 @@ +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker +from pathlib import Path + +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) + +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..e69de29 diff --git a/app/models/item.py b/app/models/item.py new file mode 100644 index 0000000..c0ece9c --- /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 import Base + +class Item(Base): + __tablename__ = "items" + + id = Column(Integer, primary_key=True, index=True) + name = Column(String, index=True, nullable=False) + description = Column(String, nullable=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()) \ 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/app/schemas/item.py b/app/schemas/item.py new file mode 100644 index 0000000..0bd7fbf --- /dev/null +++ b/app/schemas/item.py @@ -0,0 +1,24 @@ +from pydantic import BaseModel +from datetime import datetime +from typing import Optional + +class ItemBase(BaseModel): + name: str + description: Optional[str] = None + is_active: bool = True + +class ItemCreate(ItemBase): + pass + +class ItemUpdate(BaseModel): + name: Optional[str] = None + description: Optional[str] = None + is_active: Optional[bool] = None + +class Item(ItemBase): + id: int + created_at: datetime + updated_at: Optional[datetime] = None + + class Config: + from_attributes = True \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..29d4a1b --- /dev/null +++ b/main.py @@ -0,0 +1,41 @@ +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware + +from app.api.routes import api_router +from app.db.session import engine +from app.db.base import Base + +app = FastAPI( + title="REST API Service", + description="A comprehensive REST API built with FastAPI", + version="1.0.0", + openapi_url="/openapi.json" +) + +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +Base.metadata.create_all(bind=engine) + +app.include_router(api_router, prefix="/api/v1") + +@app.get("/") +async def root(): + return { + "title": "REST API Service", + "documentation": "/docs", + "health": "/health" + } + +@app.get("/health") +async def health_check(): + return {"status": "healthy", "service": "REST API Service"} + +if __name__ == "__main__": + import uvicorn + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..9313193 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,7 @@ +fastapi==0.104.1 +uvicorn[standard]==0.24.0 +sqlalchemy==2.0.23 +alembic==1.12.1 +python-multipart==0.0.6 +pydantic==2.5.0 +ruff==0.1.6 \ No newline at end of file