Implement FastAPI inventory management system for small businesses

- Set up FastAPI application with CORS and health check endpoint
- Create SQLite database models for inventory items, categories, and suppliers
- Implement complete CRUD API endpoints for all entities
- Add low-stock monitoring functionality
- Configure Alembic for database migrations
- Set up Ruff for code linting and formatting
- Include comprehensive API documentation and README
This commit is contained in:
Automated Action 2025-06-18 16:50:29 +00:00
parent 4826d2f4df
commit cda1825688
19 changed files with 704 additions and 2 deletions

113
README.md
View File

@ -1,3 +1,112 @@
# FastAPI Application
# Small Business Inventory System
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A comprehensive FastAPI-based inventory management system designed for small businesses.
## Features
- **Inventory Management**: Full CRUD operations for inventory items
- **Category Management**: Organize products by categories
- **Supplier Management**: Track supplier information and relationships
- **Stock Monitoring**: Automated low-stock alerts
- **RESTful API**: Complete API with automatic documentation
- **SQLite Database**: Lightweight database with migration support
## API Endpoints
### Inventory Items
- `GET /api/v1/inventory/` - List all inventory items
- `POST /api/v1/inventory/` - Create new inventory item
- `GET /api/v1/inventory/{item_id}` - Get specific inventory item
- `PUT /api/v1/inventory/{item_id}` - Update inventory item
- `DELETE /api/v1/inventory/{item_id}` - Delete inventory item
- `GET /api/v1/inventory/low-stock/` - Get low stock items
### Categories
- `GET /api/v1/categories/` - List all categories
- `POST /api/v1/categories/` - Create new category
- `GET /api/v1/categories/{category_id}` - Get specific category
- `PUT /api/v1/categories/{category_id}` - Update category
- `DELETE /api/v1/categories/{category_id}` - Delete category
### Suppliers
- `GET /api/v1/suppliers/` - List all suppliers
- `POST /api/v1/suppliers/` - Create new supplier
- `GET /api/v1/suppliers/{supplier_id}` - Get specific supplier
- `PUT /api/v1/suppliers/{supplier_id}` - Update supplier
- `DELETE /api/v1/suppliers/{supplier_id}` - Delete supplier
### System
- `GET /` - API information and documentation links
- `GET /health` - Health check endpoint
- `GET /docs` - Interactive API documentation (Swagger UI)
- `GET /redoc` - Alternative API documentation
## Installation
1. Install dependencies:
```bash
pip install -r requirements.txt
```
2. Run database migrations:
```bash
alembic upgrade head
```
3. Start the server:
```bash
uvicorn main:app --host 0.0.0.0 --port 8000
```
## Development
### Linting
```bash
ruff check --fix .
```
### Database Migrations
- Create new migration: `alembic revision --autogenerate -m "description"`
- Apply migrations: `alembic upgrade head`
- Rollback migration: `alembic downgrade -1`
## Database Schema
### InventoryItem
- `id`: Primary key
- `name`: Product name
- `sku`: Unique stock keeping unit
- `description`: Product description
- `quantity`: Current stock quantity
- `unit_price`: Price per unit
- `minimum_stock`: Minimum stock level for alerts
- `category_id`: Foreign key to Category
- `supplier_id`: Foreign key to Supplier
- `created_at`: Creation timestamp
- `updated_at`: Last update timestamp
### Category
- `id`: Primary key
- `name`: Category name (unique)
- `description`: Category description
- `created_at`: Creation timestamp
### Supplier
- `id`: Primary key
- `name`: Supplier name (unique)
- `contact_person`: Contact person name
- `email`: Contact email
- `phone`: Contact phone number
- `address`: Supplier address
- `created_at`: Creation timestamp
## Configuration
The application uses SQLite database stored at `/app/storage/db/db.sqlite`.
## API Documentation
Once the server is running, visit:
- http://localhost:8000/docs for Swagger UI documentation
- http://localhost:8000/redoc for ReDoc documentation
- http://localhost:8000/openapi.json for OpenAPI schema

41
alembic.ini Normal file
View File

@ -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

51
alembic/env.py Normal file
View File

@ -0,0 +1,51 @@
import os
import sys
from logging.config import fileConfig
from sqlalchemy import engine_from_config, pool
from alembic import context
# Add the project root to the Python path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__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()

24
alembic/script.py.mako Normal file
View File

@ -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"}

View File

@ -0,0 +1,75 @@
"""Initial migration
Revision ID: 001
Revises:
Create Date: 2024-01-01 00:00:00.000000
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '001'
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
# Create categories table
op.create_table('categories',
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(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_categories_id'), 'categories', ['id'], unique=False)
op.create_index(op.f('ix_categories_name'), 'categories', ['name'], unique=True)
# Create suppliers table
op.create_table('suppliers',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=200), nullable=False),
sa.Column('contact_person', sa.String(length=100), nullable=True),
sa.Column('email', sa.String(length=100), nullable=True),
sa.Column('phone', sa.String(length=20), nullable=True),
sa.Column('address', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_suppliers_id'), 'suppliers', ['id'], unique=False)
op.create_index(op.f('ix_suppliers_name'), 'suppliers', ['name'], unique=True)
# Create inventory_items table
op.create_table('inventory_items',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=200), nullable=False),
sa.Column('sku', sa.String(length=50), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('quantity', sa.Integer(), nullable=True),
sa.Column('unit_price', sa.Float(), nullable=False),
sa.Column('minimum_stock', sa.Integer(), nullable=True),
sa.Column('category_id', sa.Integer(), nullable=True),
sa.Column('supplier_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['category_id'], ['categories.id'], ),
sa.ForeignKeyConstraint(['supplier_id'], ['suppliers.id'], ),
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_sku'), 'inventory_items', ['sku'], unique=True)
def downgrade() -> None:
op.drop_index(op.f('ix_inventory_items_sku'), table_name='inventory_items')
op.drop_index(op.f('ix_inventory_items_id'), table_name='inventory_items')
op.drop_table('inventory_items')
op.drop_index(op.f('ix_suppliers_name'), table_name='suppliers')
op.drop_index(op.f('ix_suppliers_id'), table_name='suppliers')
op.drop_table('suppliers')
op.drop_index(op.f('ix_categories_name'), table_name='categories')
op.drop_index(op.f('ix_categories_id'), table_name='categories')
op.drop_table('categories')

0
app/__init__.py Normal file
View File

0
app/db/__init__.py Normal file
View File

3
app/db/base.py Normal file
View File

@ -0,0 +1,3 @@
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

48
app/db/models.py Normal file
View File

@ -0,0 +1,48 @@
from datetime import datetime
from sqlalchemy import Column, DateTime, Float, ForeignKey, Integer, String, Text
from sqlalchemy.orm import relationship
from .base import Base
class Category(Base):
__tablename__ = "categories"
id = Column(Integer, primary_key=True, index=True)
name = Column(String(100), unique=True, index=True, nullable=False)
description = Column(Text, nullable=True)
created_at = Column(DateTime, default=datetime.utcnow)
items = relationship("InventoryItem", back_populates="category")
class Supplier(Base):
__tablename__ = "suppliers"
id = Column(Integer, primary_key=True, index=True)
name = Column(String(200), unique=True, index=True, nullable=False)
contact_person = Column(String(100), nullable=True)
email = Column(String(100), nullable=True)
phone = Column(String(20), nullable=True)
address = Column(Text, nullable=True)
created_at = Column(DateTime, default=datetime.utcnow)
items = relationship("InventoryItem", back_populates="supplier")
class InventoryItem(Base):
__tablename__ = "inventory_items"
id = Column(Integer, primary_key=True, index=True)
name = Column(String(200), nullable=False)
sku = Column(String(50), unique=True, index=True, nullable=False)
description = Column(Text, nullable=True)
quantity = Column(Integer, default=0)
unit_price = Column(Float, nullable=False)
minimum_stock = Column(Integer, default=0)
category_id = Column(Integer, ForeignKey("categories.id"), nullable=True)
supplier_id = Column(Integer, ForeignKey("suppliers.id"), nullable=True)
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
category = relationship("Category", back_populates="items")
supplier = relationship("Supplier", back_populates="items")

23
app/db/session.py Normal file
View 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()

0
app/routers/__init__.py Normal file
View File

59
app/routers/categories.py Normal file
View File

@ -0,0 +1,59 @@
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.db.models import Category
from app.db.session import get_db
from app.schemas.inventory import Category as CategorySchema
from app.schemas.inventory import CategoryCreate, CategoryUpdate
router = APIRouter()
@router.get("/", response_model=List[CategorySchema])
def get_categories(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
categories = db.query(Category).offset(skip).limit(limit).all()
return categories
@router.get("/{category_id}", response_model=CategorySchema)
def get_category(category_id: int, db: Session = Depends(get_db)):
category = db.query(Category).filter(Category.id == category_id).first()
if not category:
raise HTTPException(status_code=404, detail="Category not found")
return category
@router.post("/", response_model=CategorySchema)
def create_category(category: CategoryCreate, db: Session = Depends(get_db)):
existing_category = db.query(Category).filter(Category.name == category.name).first()
if existing_category:
raise HTTPException(status_code=400, detail="Category name already exists")
db_category = Category(**category.dict())
db.add(db_category)
db.commit()
db.refresh(db_category)
return db_category
@router.put("/{category_id}", response_model=CategorySchema)
def update_category(category_id: int, category: CategoryUpdate, db: Session = Depends(get_db)):
db_category = db.query(Category).filter(Category.id == category_id).first()
if not db_category:
raise HTTPException(status_code=404, detail="Category not found")
update_data = category.dict(exclude_unset=True)
for field, value in update_data.items():
setattr(db_category, field, value)
db.commit()
db.refresh(db_category)
return db_category
@router.delete("/{category_id}")
def delete_category(category_id: int, db: Session = Depends(get_db)):
db_category = db.query(Category).filter(Category.id == category_id).first()
if not db_category:
raise HTTPException(status_code=404, detail="Category not found")
db.delete(db_category)
db.commit()
return {"message": "Category deleted successfully"}

64
app/routers/inventory.py Normal file
View File

@ -0,0 +1,64 @@
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.db.models import InventoryItem
from app.db.session import get_db
from app.schemas.inventory import InventoryItem as InventoryItemSchema
from app.schemas.inventory import InventoryItemCreate, InventoryItemUpdate
router = APIRouter()
@router.get("/", response_model=List[InventoryItemSchema])
def get_inventory_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
items = db.query(InventoryItem).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="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.dict())
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: 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="Item not found")
update_data = item.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_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="Item not found")
db.delete(db_item)
db.commit()
return {"message": "Item deleted successfully"}
@router.get("/low-stock/", response_model=List[InventoryItemSchema])
def get_low_stock_items(db: Session = Depends(get_db)):
items = db.query(InventoryItem).filter(InventoryItem.quantity <= InventoryItem.minimum_stock).all()
return items

59
app/routers/suppliers.py Normal file
View File

@ -0,0 +1,59 @@
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.db.models import Supplier
from app.db.session import get_db
from app.schemas.inventory import Supplier as SupplierSchema
from app.schemas.inventory import SupplierCreate, SupplierUpdate
router = APIRouter()
@router.get("/", response_model=List[SupplierSchema])
def get_suppliers(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
suppliers = db.query(Supplier).offset(skip).limit(limit).all()
return suppliers
@router.get("/{supplier_id}", response_model=SupplierSchema)
def get_supplier(supplier_id: int, db: Session = Depends(get_db)):
supplier = db.query(Supplier).filter(Supplier.id == supplier_id).first()
if not supplier:
raise HTTPException(status_code=404, detail="Supplier not found")
return supplier
@router.post("/", response_model=SupplierSchema)
def create_supplier(supplier: SupplierCreate, db: Session = Depends(get_db)):
existing_supplier = db.query(Supplier).filter(Supplier.name == supplier.name).first()
if existing_supplier:
raise HTTPException(status_code=400, detail="Supplier name already exists")
db_supplier = Supplier(**supplier.dict())
db.add(db_supplier)
db.commit()
db.refresh(db_supplier)
return db_supplier
@router.put("/{supplier_id}", response_model=SupplierSchema)
def update_supplier(supplier_id: int, supplier: SupplierUpdate, db: Session = Depends(get_db)):
db_supplier = db.query(Supplier).filter(Supplier.id == supplier_id).first()
if not db_supplier:
raise HTTPException(status_code=404, detail="Supplier not found")
update_data = supplier.dict(exclude_unset=True)
for field, value in update_data.items():
setattr(db_supplier, field, value)
db.commit()
db.refresh(db_supplier)
return db_supplier
@router.delete("/{supplier_id}")
def delete_supplier(supplier_id: int, db: Session = Depends(get_db)):
db_supplier = db.query(Supplier).filter(Supplier.id == supplier_id).first()
if not db_supplier:
raise HTTPException(status_code=404, detail="Supplier not found")
db.delete(db_supplier)
db.commit()
return {"message": "Supplier deleted successfully"}

0
app/schemas/__init__.py Normal file
View File

79
app/schemas/inventory.py Normal file
View File

@ -0,0 +1,79 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel
class CategoryBase(BaseModel):
name: str
description: Optional[str] = None
class CategoryCreate(CategoryBase):
pass
class CategoryUpdate(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
class Category(CategoryBase):
id: int
created_at: datetime
class Config:
from_attributes = True
class SupplierBase(BaseModel):
name: str
contact_person: Optional[str] = None
email: Optional[str] = None
phone: Optional[str] = None
address: Optional[str] = None
class SupplierCreate(SupplierBase):
pass
class SupplierUpdate(BaseModel):
name: Optional[str] = None
contact_person: Optional[str] = None
email: Optional[str] = None
phone: Optional[str] = None
address: Optional[str] = None
class Supplier(SupplierBase):
id: int
created_at: datetime
class Config:
from_attributes = True
class InventoryItemBase(BaseModel):
name: str
sku: str
description: Optional[str] = None
quantity: int = 0
unit_price: float
minimum_stock: int = 0
category_id: Optional[int] = None
supplier_id: Optional[int] = None
class InventoryItemCreate(InventoryItemBase):
pass
class InventoryItemUpdate(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
quantity: Optional[int] = None
unit_price: Optional[float] = None
minimum_stock: Optional[int] = None
category_id: Optional[int] = None
supplier_id: Optional[int] = None
class InventoryItem(InventoryItemBase):
id: int
created_at: datetime
updated_at: datetime
category: Optional[Category] = None
supplier: Optional[Supplier] = None
class Config:
from_attributes = True

38
main.py Normal file
View File

@ -0,0 +1,38 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.routers import categories, inventory, suppliers
app = FastAPI(
title="Small Business Inventory System",
description="A comprehensive inventory management system for small businesses",
version="1.0.0"
)
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.include_router(suppliers.router, prefix="/api/v1/suppliers", tags=["suppliers"])
app.include_router(categories.router, prefix="/api/v1/categories", tags=["categories"])
@app.get("/")
async def root():
return {
"title": "Small Business Inventory System",
"documentation": "/docs",
"health": "/health"
}
@app.get("/health")
async def health_check():
return {"status": "healthy", "service": "inventory-system"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)

22
pyproject.toml Normal file
View File

@ -0,0 +1,22 @@
[tool.ruff]
target-version = "py38"
line-length = 88
[tool.ruff.lint]
select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
"F", # pyflakes
"I", # isort
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"UP", # pyupgrade
]
ignore = [
"E501", # line too long, handled by black
"B008", # do not perform function calls in argument defaults
"C901", # too complex
]
[tool.ruff.lint.isort]
known-third-party = ["fastapi", "pydantic", "starlette", "sqlalchemy"]

7
requirements.txt Normal file
View File

@ -0,0 +1,7 @@
fastapi==0.104.1
uvicorn==0.24.0
sqlalchemy==2.0.23
alembic==1.12.1
pydantic==2.5.0
python-multipart==0.0.6
ruff==0.1.6