From 02cc12cad8e1f68ada352542ca34ab940480e091 Mon Sep 17 00:00:00 2001 From: Automated Action Date: Fri, 20 Jun 2025 10:55:10 +0000 Subject: [PATCH] Add FastAPI REST API service with CRUD operations - Created main FastAPI application with CORS middleware - Added SQLite database configuration with SQLAlchemy - Implemented Items model with create, read, update, delete operations - Set up Alembic migrations for database schema management - Added comprehensive API endpoints at /api/v1/items/ - Included health check endpoint at /health - Added proper Pydantic schemas for request/response validation - Updated README with complete documentation and usage instructions - Configured Ruff for code linting and formatting --- README.md | 86 +++++++++++++++++++++- alembic.ini | 41 +++++++++++ alembic/env.py | 50 +++++++++++++ alembic/script.py.mako | 24 ++++++ alembic/versions/001_create_items_table.py | 41 +++++++++++ app/__init__.py | 0 app/api/__init__.py | 0 app/api/items.py | 57 ++++++++++++++ app/db/__init__.py | 0 app/db/base.py | 17 +++++ app/db/session.py | 9 +++ app/models/__init__.py | 0 app/models/item.py | 13 ++++ app/schemas/__init__.py | 0 app/schemas/item.py | 26 +++++++ main.py | 42 +++++++++++ requirements.txt | 7 ++ 17 files changed, 411 insertions(+), 2 deletions(-) create mode 100644 alembic.ini create mode 100644 alembic/env.py create mode 100644 alembic/script.py.mako create mode 100644 alembic/versions/001_create_items_table.py create mode 100644 app/__init__.py create mode 100644 app/api/__init__.py create mode 100644 app/api/items.py create mode 100644 app/db/__init__.py create mode 100644 app/db/base.py create mode 100644 app/db/session.py create mode 100644 app/models/__init__.py create mode 100644 app/models/item.py create mode 100644 app/schemas/__init__.py create mode 100644 app/schemas/item.py create mode 100644 main.py create mode 100644 requirements.txt diff --git a/README.md b/README.md index e8acfba..ce682e3 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,85 @@ -# 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 with CRUD operations, SQLite database, and Alembic migrations. + +## Features + +- FastAPI framework with automatic API documentation +- SQLite database with SQLAlchemy ORM +- Database migrations with Alembic +- CRUD operations for Items +- CORS enabled for all origins +- Health check endpoint +- Automatic OpenAPI documentation + +## Installation + +1. Install dependencies: +```bash +pip install -r requirements.txt +``` + +## Running the Application + +Start the development server: +```bash +uvicorn main:app --reload +``` + +The API 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` + +## API Endpoints + +### Root +- `GET /` - Service information + +### Health Check +- `GET /health` - Health status + +### Items (CRUD) +- `POST /api/v1/items/` - Create a new item +- `GET /api/v1/items/` - List all items (with pagination) +- `GET /api/v1/items/{item_id}` - Get specific item +- `PUT /api/v1/items/{item_id}` - Update specific item +- `DELETE /api/v1/items/{item_id}` - Delete specific item + +## Database + +The application uses SQLite with the database file stored at `/app/storage/db/db.sqlite`. + +### Migrations + +Database migrations are managed with Alembic. The migration files are in the `alembic/versions/` directory. + +## Project Structure + +``` +├── main.py # FastAPI application entry point +├── requirements.txt # Python dependencies +├── alembic.ini # Alembic configuration +├── alembic/ # Database migrations +│ ├── env.py +│ ├── script.py.mako +│ └── versions/ +│ └── 001_create_items_table.py +└── app/ + ├── api/ # API routes + │ └── items.py + ├── db/ # Database configuration + │ ├── base.py + │ └── session.py + ├── models/ # SQLAlchemy models + │ └── item.py + └── schemas/ # Pydantic schemas + └── item.py +``` + +## Environment Variables + +No environment variables are required for basic operation. The application uses SQLite with a file-based database. diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..017f263 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,41 @@ +[alembic] +script_location = alembic +prepend_sys_path = . +version_path_separator = os +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..d1fb6d1 --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,50 @@ +from logging.config import fileConfig +from sqlalchemy import engine_from_config +from sqlalchemy import pool +from alembic import context +import sys +import os + +sys.path.append(os.path.dirname(os.path.dirname(__file__))) + +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() 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/001_create_items_table.py b/alembic/versions/001_create_items_table.py new file mode 100644 index 0000000..60c81bf --- /dev/null +++ b/alembic/versions/001_create_items_table.py @@ -0,0 +1,41 @@ +"""create items table + +Revision ID: 001 +Revises: +Create Date: 2024-01-01 00: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(length=100), nullable=False), + sa.Column("description", sa.Text(), 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") 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..058d94b --- /dev/null +++ b/app/api/items.py @@ -0,0 +1,57 @@ +from fastapi import APIRouter, Depends, HTTPException, status +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("/items/", response_model=ItemSchema, status_code=status.HTTP_201_CREATED) +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("/items/", 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("/items/{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("/items/{item_id}", response_model=ItemSchema) +def update_item(item_id: int, item_update: ItemUpdate, 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") + + update_data = item_update.dict(exclude_unset=True) + for field, value in update_data.items(): + setattr(item, field, value) + + db.commit() + db.refresh(item) + return item + + +@router.delete("/items/{item_id}") +def delete_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") + + db.delete(item) + db.commit() + return {"message": "Item deleted successfully"} 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..532d9bd --- /dev/null +++ b/app/db/base.py @@ -0,0 +1,17 @@ +from sqlalchemy import create_engine +from sqlalchemy.ext.declarative import declarative_base +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) + +Base = declarative_base() diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..a46af1f --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,9 @@ +from .base import SessionLocal + + +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/models/item.py b/app/models/item.py new file mode 100644 index 0000000..2af1584 --- /dev/null +++ b/app/models/item.py @@ -0,0 +1,13 @@ +from sqlalchemy import Column, Integer, String, Text, 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(100), nullable=False, index=True) + description = Column(Text, nullable=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..e69de29 diff --git a/app/schemas/item.py b/app/schemas/item.py new file mode 100644 index 0000000..2e7d46b --- /dev/null +++ b/app/schemas/item.py @@ -0,0 +1,26 @@ +from pydantic import BaseModel +from datetime import datetime +from typing import Optional + + +class ItemBase(BaseModel): + name: str + description: Optional[str] = None + + +class ItemCreate(ItemBase): + pass + + +class ItemUpdate(BaseModel): + name: Optional[str] = None + description: Optional[str] = None + + +class Item(ItemBase): + id: int + created_at: datetime + updated_at: Optional[datetime] = None + + class Config: + from_attributes = True diff --git a/main.py b/main.py new file mode 100644 index 0000000..ddd5357 --- /dev/null +++ b/main.py @@ -0,0 +1,42 @@ +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +import uvicorn +from app.api.items import router as items_router +from app.db.base import engine, Base + +Base.metadata.create_all(bind=engine) + +app = FastAPI( + title="REST API Service", + description="A FastAPI REST API service", + version="1.0.0", + openapi_url="/openapi.json", +) + +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +app.include_router(items_router, prefix="/api/v1", tags=["items"]) + + +@app.get("/") +async def root(): + return { + "title": "REST API Service", + "documentation": "/docs", + "health_check": "/health", + } + + +@app.get("/health") +async def health_check(): + return {"status": "healthy", "service": "REST API Service"} + + +if __name__ == "__main__": + uvicorn.run(app, host="0.0.0.0", port=8000) 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