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
This commit is contained in:
parent
78f26a5e72
commit
667ac548e1
126
README.md
126
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`.
|
||||
|
41
alembic.ini
Normal file
41
alembic.ini
Normal file
@ -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
|
0
app/__init__.py
Normal file
0
app/__init__.py
Normal file
0
app/api/__init__.py
Normal file
0
app/api/__init__.py
Normal file
106
app/api/inventory.py
Normal file
106
app/api/inventory.py
Normal file
@ -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}
|
0
app/db/__init__.py
Normal file
0
app/db/__init__.py
Normal file
3
app/db/base.py
Normal file
3
app/db/base.py
Normal file
@ -0,0 +1,3 @@
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
|
||||
Base = declarative_base()
|
23
app/db/session.py
Normal file
23
app/db/session.py
Normal file
@ -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()
|
3
app/models/__init__.py
Normal file
3
app/models/__init__.py
Normal file
@ -0,0 +1,3 @@
|
||||
from .inventory import InventoryItem
|
||||
|
||||
__all__ = ["InventoryItem"]
|
19
app/models/inventory.py
Normal file
19
app/models/inventory.py
Normal file
@ -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())
|
3
app/schemas/__init__.py
Normal file
3
app/schemas/__init__.py
Normal file
@ -0,0 +1,3 @@
|
||||
from .inventory import InventoryItem, InventoryItemCreate, InventoryItemUpdate, InventoryItemBase
|
||||
|
||||
__all__ = ["InventoryItem", "InventoryItemCreate", "InventoryItemUpdate", "InventoryItemBase"]
|
38
app/schemas/inventory.py
Normal file
38
app/schemas/inventory.py
Normal file
@ -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
|
40
main.py
Normal file
40
main.py
Normal file
@ -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"
|
||||
}
|
55
migrations/env.py
Normal file
55
migrations/env.py
Normal file
@ -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()
|
23
migrations/script.py.mako
Normal file
23
migrations/script.py.mako
Normal file
@ -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"}
|
44
migrations/versions/001_create_inventory_items_table.py
Normal file
44
migrations/versions/001_create_inventory_items_table.py
Normal file
@ -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')
|
11
pyproject.toml
Normal file
11
pyproject.toml
Normal file
@ -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"
|
7
requirements.txt
Normal file
7
requirements.txt
Normal file
@ -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
|
Loading…
x
Reference in New Issue
Block a user