From 667ac548e1e2fd0cecea1ec2abd4e13a2c01f9fa Mon Sep 17 00:00:00 2001 From: Automated Action Date: Mon, 21 Jul 2025 19:29:24 +0000 Subject: [PATCH] Build complete FastAPI inventory management application - Created FastAPI application structure with SQLAlchemy and Alembic - Implemented full CRUD operations for inventory items - Added search, filtering, and pagination capabilities - Configured CORS, API documentation, and health endpoints - Set up SQLite database with proper migrations - Added comprehensive API documentation and README --- README.md | 126 +++++++++++++++++- alembic.ini | 41 ++++++ app/__init__.py | 0 app/api/__init__.py | 0 app/api/inventory.py | 106 +++++++++++++++ app/db/__init__.py | 0 app/db/base.py | 3 + app/db/session.py | 23 ++++ app/models/__init__.py | 3 + app/models/inventory.py | 19 +++ app/schemas/__init__.py | 3 + app/schemas/inventory.py | 38 ++++++ main.py | 40 ++++++ migrations/env.py | 55 ++++++++ migrations/script.py.mako | 23 ++++ .../001_create_inventory_items_table.py | 44 ++++++ pyproject.toml | 11 ++ requirements.txt | 7 + 18 files changed, 540 insertions(+), 2 deletions(-) create mode 100644 alembic.ini create mode 100644 app/__init__.py create mode 100644 app/api/__init__.py create mode 100644 app/api/inventory.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/inventory.py create mode 100644 app/schemas/__init__.py create mode 100644 app/schemas/inventory.py create mode 100644 main.py create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/001_create_inventory_items_table.py create mode 100644 pyproject.toml create mode 100644 requirements.txt diff --git a/README.md b/README.md index e8acfba..a70d870 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,125 @@ -# FastAPI Application +# Inventory Management API -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A comprehensive FastAPI-based inventory management system for tracking and managing inventory items. + +## Features + +- **CRUD Operations**: Create, read, update, and delete inventory items +- **Search & Filter**: Search by name, description, or SKU and filter by category +- **Quantity Management**: Update item quantities with dedicated endpoint +- **RESTful API**: Clean REST API endpoints with proper HTTP status codes +- **Data Validation**: Pydantic models for request/response validation +- **Database Migrations**: Alembic integration for database schema management +- **API Documentation**: Auto-generated OpenAPI/Swagger documentation + +## Technology Stack + +- **Framework**: FastAPI +- **Database**: SQLite with SQLAlchemy ORM +- **Migrations**: Alembic +- **Validation**: Pydantic +- **Code Quality**: Ruff for linting and formatting + +## Project Structure + +``` +├── app/ +│ ├── api/ +│ │ └── inventory.py # Inventory API endpoints +│ ├── db/ +│ │ ├── base.py # SQLAlchemy base model +│ │ └── session.py # Database session configuration +│ ├── models/ +│ │ └── inventory.py # SQLAlchemy models +│ └── schemas/ +│ └── inventory.py # Pydantic schemas +├── migrations/ # Alembic migration files +├── main.py # FastAPI application entry point +├── requirements.txt # Python dependencies +└── alembic.ini # Alembic configuration +``` + +## Installation + +1. Install dependencies: +```bash +pip install -r requirements.txt +``` + +2. Run database migrations: +```bash +alembic upgrade head +``` + +3. Start the development server: +```bash +uvicorn main:app --reload +``` + +The API will be available at `http://localhost:8000` + +## API Endpoints + +### Base Endpoints +- `GET /` - API information and links +- `GET /health` - Health check endpoint + +### Inventory Management +- `GET /api/v1/inventory/` - List all inventory items (with pagination, search, and filtering) +- `GET /api/v1/inventory/{item_id}` - Get specific inventory item +- `POST /api/v1/inventory/` - Create new inventory item +- `PUT /api/v1/inventory/{item_id}` - Update inventory item +- `DELETE /api/v1/inventory/{item_id}` - Delete inventory item +- `PATCH /api/v1/inventory/{item_id}/quantity` - Update item quantity + +### Query Parameters +- `skip` - Number of records to skip (pagination) +- `limit` - Maximum number of records to return +- `category` - Filter by category +- `search` - Search in name, description, or SKU + +## API Documentation + +Once the server is running, you can access: +- Swagger UI: `http://localhost:8000/docs` +- ReDoc: `http://localhost:8000/redoc` +- OpenAPI JSON: `http://localhost:8000/openapi.json` + +## Data Model + +### Inventory Item +```json +{ + "id": 1, + "name": "Product Name", + "description": "Product description", + "sku": "UNIQUE-SKU-123", + "quantity": 50, + "price": 29.99, + "category": "Electronics", + "supplier": "Supplier Name", + "location": "Warehouse A", + "created_at": "2024-01-01T00:00:00Z", + "updated_at": "2024-01-01T00:00:00Z" +} +``` + +## Development + +### Code Quality +The project uses Ruff for code formatting and linting: +```bash +ruff check . +ruff format . +``` + +### Database Migrations +To create a new migration after model changes: +```bash +alembic revision --autogenerate -m "Description of changes" +alembic upgrade head +``` + +## Storage + +The application uses `/app/storage/db/` as the database storage directory with SQLite. The database file will be created automatically at `/app/storage/db/db.sqlite`. diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..16a05db --- /dev/null +++ b/alembic.ini @@ -0,0 +1,41 @@ +[alembic] +script_location = migrations +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/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/inventory.py b/app/api/inventory.py new file mode 100644 index 0000000..7cbd4f2 --- /dev/null +++ b/app/api/inventory.py @@ -0,0 +1,106 @@ +from typing import List, Optional +from fastapi import APIRouter, Depends, HTTPException, Query +from sqlalchemy.orm import Session +from app.db.session import get_db +from app.models.inventory import InventoryItem +from app.schemas.inventory import ( + InventoryItem as InventoryItemSchema, + InventoryItemCreate, + InventoryItemUpdate, +) + +router = APIRouter() + + +@router.get("/", response_model=List[InventoryItemSchema]) +def get_inventory_items( + skip: int = Query(0, ge=0), + limit: int = Query(100, ge=1, le=1000), + category: Optional[str] = Query(None), + search: Optional[str] = Query(None), + db: Session = Depends(get_db), +): + query = db.query(InventoryItem) + + if category: + query = query.filter(InventoryItem.category == category) + + if search: + query = query.filter( + (InventoryItem.name.contains(search)) | + (InventoryItem.description.contains(search)) | + (InventoryItem.sku.contains(search)) + ) + + items = query.offset(skip).limit(limit).all() + return items + + +@router.get("/{item_id}", response_model=InventoryItemSchema) +def get_inventory_item(item_id: int, db: Session = Depends(get_db)): + item = db.query(InventoryItem).filter(InventoryItem.id == item_id).first() + if not item: + raise HTTPException(status_code=404, detail="Inventory item not found") + return item + + +@router.post("/", response_model=InventoryItemSchema) +def create_inventory_item(item: InventoryItemCreate, db: Session = Depends(get_db)): + existing_item = db.query(InventoryItem).filter(InventoryItem.sku == item.sku).first() + if existing_item: + raise HTTPException(status_code=400, detail="SKU already exists") + + db_item = InventoryItem(**item.model_dump()) + db.add(db_item) + db.commit() + db.refresh(db_item) + return db_item + + +@router.put("/{item_id}", response_model=InventoryItemSchema) +def update_inventory_item( + item_id: int, item_update: InventoryItemUpdate, db: Session = Depends(get_db) +): + db_item = db.query(InventoryItem).filter(InventoryItem.id == item_id).first() + if not db_item: + raise HTTPException(status_code=404, detail="Inventory item not found") + + if item_update.sku and item_update.sku != db_item.sku: + existing_item = db.query(InventoryItem).filter(InventoryItem.sku == item_update.sku).first() + if existing_item: + raise HTTPException(status_code=400, detail="SKU already exists") + + update_data = item_update.model_dump(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_inventory_item(item_id: int, db: Session = Depends(get_db)): + db_item = db.query(InventoryItem).filter(InventoryItem.id == item_id).first() + if not db_item: + raise HTTPException(status_code=404, detail="Inventory item not found") + + db.delete(db_item) + db.commit() + return {"message": "Inventory item deleted successfully"} + + +@router.patch("/{item_id}/quantity") +def update_item_quantity( + item_id: int, + quantity: int = Query(..., ge=0), + db: Session = Depends(get_db) +): + db_item = db.query(InventoryItem).filter(InventoryItem.id == item_id).first() + if not db_item: + raise HTTPException(status_code=404, detail="Inventory item not found") + + db_item.quantity = quantity + db.commit() + db.refresh(db_item) + return {"message": f"Quantity updated to {quantity}", "item": db_item} \ 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..e77d375 --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,23 @@ +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) + + +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..6e5afa7 --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1,3 @@ +from .inventory import InventoryItem + +__all__ = ["InventoryItem"] \ No newline at end of file diff --git a/app/models/inventory.py b/app/models/inventory.py new file mode 100644 index 0000000..6b9f4a0 --- /dev/null +++ b/app/models/inventory.py @@ -0,0 +1,19 @@ +from sqlalchemy import Column, Integer, String, Float, DateTime, Text +from sqlalchemy.sql import func +from app.db.base import Base + + +class InventoryItem(Base): + __tablename__ = "inventory_items" + + id = Column(Integer, primary_key=True, index=True) + name = Column(String(255), nullable=False, index=True) + description = Column(Text, nullable=True) + sku = Column(String(100), unique=True, nullable=False, index=True) + quantity = Column(Integer, nullable=False, default=0) + price = Column(Float, nullable=False) + category = Column(String(100), nullable=True, index=True) + supplier = Column(String(255), nullable=True) + location = Column(String(255), nullable=True) + created_at = Column(DateTime(timezone=True), server_default=func.now()) + updated_at = Column(DateTime(timezone=True), server_default=func.now(), 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..3428933 --- /dev/null +++ b/app/schemas/__init__.py @@ -0,0 +1,3 @@ +from .inventory import InventoryItem, InventoryItemCreate, InventoryItemUpdate, InventoryItemBase + +__all__ = ["InventoryItem", "InventoryItemCreate", "InventoryItemUpdate", "InventoryItemBase"] \ No newline at end of file diff --git a/app/schemas/inventory.py b/app/schemas/inventory.py new file mode 100644 index 0000000..f2ce15f --- /dev/null +++ b/app/schemas/inventory.py @@ -0,0 +1,38 @@ +from datetime import datetime +from typing import Optional +from pydantic import BaseModel, Field + + +class InventoryItemBase(BaseModel): + name: str = Field(..., min_length=1, max_length=255) + description: Optional[str] = None + sku: str = Field(..., min_length=1, max_length=100) + quantity: int = Field(..., ge=0) + price: float = Field(..., gt=0) + category: Optional[str] = Field(None, max_length=100) + supplier: Optional[str] = Field(None, max_length=255) + location: Optional[str] = Field(None, max_length=255) + + +class InventoryItemCreate(InventoryItemBase): + pass + + +class InventoryItemUpdate(BaseModel): + name: Optional[str] = Field(None, min_length=1, max_length=255) + description: Optional[str] = None + sku: Optional[str] = Field(None, min_length=1, max_length=100) + quantity: Optional[int] = Field(None, ge=0) + price: Optional[float] = Field(None, gt=0) + category: Optional[str] = Field(None, max_length=100) + supplier: Optional[str] = Field(None, max_length=255) + location: Optional[str] = Field(None, max_length=255) + + +class InventoryItem(InventoryItemBase): + id: int + created_at: datetime + updated_at: datetime + + 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..40dad50 --- /dev/null +++ b/main.py @@ -0,0 +1,40 @@ +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import JSONResponse +from app.api.inventory import router as inventory_router + +app = FastAPI( + title="Inventory Management API", + description="A comprehensive inventory management system", + version="1.0.0", + openapi_url="/openapi.json", +) + +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +app.include_router(inventory_router, prefix="/api/v1/inventory", tags=["inventory"]) + + +@app.get("/") +async def root(): + return { + "title": "Inventory Management API", + "description": "A comprehensive inventory management system", + "version": "1.0.0", + "documentation": "/docs", + "health_check": "/health" + } + + +@app.get("/health") +async def health_check(): + return { + "status": "healthy", + "message": "Inventory Management API is running properly" + } \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..b5a2d12 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,55 @@ +import os +import sys +from logging.config import fileConfig +from sqlalchemy import engine_from_config +from sqlalchemy import pool +from alembic import context + +sys.path.append(os.path.dirname(os.path.dirname(__file__))) + +from app.db.base import Base +from app.models import * + +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: + """Run migrations in 'offline' mode.""" + 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: + """Run migrations in 'online' mode.""" + 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/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..4a32725 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,23 @@ +"""${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 = ${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/migrations/versions/001_create_inventory_items_table.py b/migrations/versions/001_create_inventory_items_table.py new file mode 100644 index 0000000..e08a5ee --- /dev/null +++ b/migrations/versions/001_create_inventory_items_table.py @@ -0,0 +1,44 @@ +"""Create inventory items table + +Revision ID: 001 +Revises: +Create Date: 2024-01-01 00:00:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + +revision = '001' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + 'inventory_items', + 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('sku', sa.String(length=100), nullable=False), + sa.Column('quantity', sa.Integer(), nullable=False), + sa.Column('price', sa.Float(), nullable=False), + sa.Column('category', sa.String(length=100), nullable=True), + sa.Column('supplier', sa.String(length=255), nullable=True), + sa.Column('location', sa.String(length=255), 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), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_inventory_items_id'), 'inventory_items', ['id'], unique=False) + op.create_index(op.f('ix_inventory_items_name'), 'inventory_items', ['name'], unique=False) + op.create_index(op.f('ix_inventory_items_sku'), 'inventory_items', ['sku'], unique=True) + op.create_index(op.f('ix_inventory_items_category'), 'inventory_items', ['category'], unique=False) + + +def downgrade() -> None: + op.drop_index(op.f('ix_inventory_items_category'), table_name='inventory_items') + op.drop_index(op.f('ix_inventory_items_sku'), table_name='inventory_items') + op.drop_index(op.f('ix_inventory_items_name'), table_name='inventory_items') + op.drop_index(op.f('ix_inventory_items_id'), table_name='inventory_items') + op.drop_table('inventory_items') \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..eda429b --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,11 @@ +[tool.ruff] +line-length = 88 +target-version = "py39" + +[tool.ruff.lint] +select = ["E", "F", "W", "C", "I"] +ignore = ["E501"] + +[tool.ruff.format] +quote-style = "double" +indent-style = "space" \ 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