Create FastAPI inventory management system for small businesses

- Set up FastAPI application with SQLite database
- Implemented CRUD operations for inventory items, categories, and suppliers
- Added Alembic migrations for database schema management
- Configured CORS middleware for cross-origin requests
- Added health check and API documentation endpoints
- Structured project with proper separation of concerns
- Added comprehensive README with API documentation
This commit is contained in:
Automated Action 2025-06-25 10:33:52 +00:00
parent 8af5b11aa1
commit 1badf85dea
17 changed files with 703 additions and 2 deletions

View File

@ -1,3 +1,93 @@
# FastAPI Application # Small Business Inventory Management System
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. A FastAPI-based inventory management system designed for small businesses to track their inventory, suppliers, and product categories.
## Features
- **Inventory Management**: Complete CRUD operations for inventory items
- **Category Management**: Organize products by categories
- **Supplier Management**: Track supplier information and relationships
- **Low Stock Alerts**: Filter items by low stock levels
- **RESTful API**: Full REST API with automatic documentation
- **Database Migrations**: Alembic for database schema management
## API Endpoints
### Inventory Items
- `GET /api/inventory/items` - List all inventory items (with optional filters)
- `GET /api/inventory/items/{item_id}` - Get specific inventory item
- `POST /api/inventory/items` - Create new inventory item
- `PUT /api/inventory/items/{item_id}` - Update inventory item
- `DELETE /api/inventory/items/{item_id}` - Delete inventory item
### Categories
- `GET /api/inventory/categories` - List all categories
- `GET /api/inventory/categories/{category_id}` - Get specific category
- `POST /api/inventory/categories` - Create new category
- `PUT /api/inventory/categories/{category_id}` - Update category
- `DELETE /api/inventory/categories/{category_id}` - Delete category
### Suppliers
- `GET /api/inventory/suppliers` - List all suppliers
- `GET /api/inventory/suppliers/{supplier_id}` - Get specific supplier
- `POST /api/inventory/suppliers` - Create new supplier
- `PUT /api/inventory/suppliers/{supplier_id}` - Update supplier
- `DELETE /api/inventory/suppliers/{supplier_id}` - Delete supplier
### System Endpoints
- `GET /` - API information and links
- `GET /health` - Health check endpoint
- `GET /docs` - Interactive API documentation (Swagger UI)
- `GET /redoc` - Alternative API documentation
## Quick Start
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`
## Documentation
- Interactive API docs: `http://localhost:8000/docs`
- Alternative docs: `http://localhost:8000/redoc`
- OpenAPI JSON: `http://localhost:8000/openapi.json`
## Database
This application uses SQLite as the database backend. The database file is stored at `/app/storage/db/db.sqlite`.
## 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_initial_migration.py
└── app/
├── api/
│ └── inventory.py # API endpoints
├── db/
│ ├── base.py # SQLAlchemy base
│ └── session.py # Database session
├── models/
│ └── inventory.py # Database models
└── schemas/
└── inventory.py # Pydantic schemas
```

43
alembic.ini Normal file
View File

@ -0,0 +1,43 @@
[alembic]
script_location = alembic
prepend_sys_path = .
version_path_separator = os
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
[post_write_hooks]
[alembic:exclude]
[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

53
alembic/env.py Normal file
View File

@ -0,0 +1,53 @@
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(os.path.realpath(__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,102 @@
"""Initial migration
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:
# 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()),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.text("CURRENT_TIMESTAMP"),
),
sa.Column("updated_at", sa.DateTime(timezone=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)),
sa.Column("email", sa.String(length=100)),
sa.Column("phone", sa.String(length=20)),
sa.Column("address", sa.Text()),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.text("CURRENT_TIMESTAMP"),
),
sa.Column("updated_at", sa.DateTime(timezone=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()),
sa.Column("category_id", sa.Integer()),
sa.Column("supplier_id", sa.Integer()),
sa.Column("quantity", sa.Integer(), default=0),
sa.Column("min_quantity", sa.Integer(), default=0),
sa.Column("unit_price", sa.Float(), nullable=False),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.text("CURRENT_TIMESTAMP"),
),
sa.Column("updated_at", sa.DateTime(timezone=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_name"), "inventory_items", ["name"], 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_name"), 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/api/__init__.py Normal file
View File

190
app/api/inventory.py Normal file
View File

@ -0,0 +1,190 @@
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.db.session import SessionLocal
from app.models.inventory import InventoryItem, Category, Supplier
from app.schemas.inventory import (
InventoryItem as InventoryItemSchema,
InventoryItemCreate,
InventoryItemUpdate,
Category as CategorySchema,
CategoryCreate,
CategoryUpdate,
Supplier as SupplierSchema,
SupplierCreate,
SupplierUpdate,
)
router = APIRouter()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@router.get("/items", response_model=List[InventoryItemSchema])
def get_inventory_items(
skip: int = 0,
limit: int = 100,
category_id: Optional[int] = None,
low_stock: bool = False,
db: Session = Depends(get_db),
):
query = db.query(InventoryItem)
if category_id:
query = query.filter(InventoryItem.category_id == category_id)
if low_stock:
query = query.filter(InventoryItem.quantity <= InventoryItem.min_quantity)
return query.offset(skip).limit(limit).all()
@router.get("/items/{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("/items", response_model=InventoryItemSchema)
def create_inventory_item(item: InventoryItemCreate, db: Session = Depends(get_db)):
db_item = InventoryItem(**item.dict())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
@router.put("/items/{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="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("/items/{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("/categories", response_model=List[CategorySchema])
def get_categories(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
return db.query(Category).offset(skip).limit(limit).all()
@router.get("/categories/{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("/categories", response_model=CategorySchema)
def create_category(category: CategoryCreate, db: Session = Depends(get_db)):
db_category = Category(**category.dict())
db.add(db_category)
db.commit()
db.refresh(db_category)
return db_category
@router.put("/categories/{category_id}", response_model=CategorySchema)
def update_category(
category_id: int, category_update: 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_update.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("/categories/{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"}
@router.get("/suppliers", response_model=List[SupplierSchema])
def get_suppliers(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
return db.query(Supplier).offset(skip).limit(limit).all()
@router.get("/suppliers/{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("/suppliers", response_model=SupplierSchema)
def create_supplier(supplier: SupplierCreate, db: Session = Depends(get_db)):
db_supplier = Supplier(**supplier.dict())
db.add(db_supplier)
db.commit()
db.refresh(db_supplier)
return db_supplier
@router.put("/suppliers/{supplier_id}", response_model=SupplierSchema)
def update_supplier(
supplier_id: int, supplier_update: 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_update.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("/suppliers/{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/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()

14
app/db/session.py Normal file
View File

@ -0,0 +1,14 @@
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)

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

50
app/models/inventory.py Normal file
View File

@ -0,0 +1,50 @@
from sqlalchemy import Column, Integer, String, Float, DateTime, ForeignKey, Text
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.db.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)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
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))
email = Column(String(100))
phone = Column(String(20))
address = Column(Text)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
items = relationship("InventoryItem", back_populates="supplier")
class InventoryItem(Base):
__tablename__ = "inventory_items"
id = Column(Integer, primary_key=True, index=True)
name = Column(String(200), index=True, nullable=False)
sku = Column(String(50), unique=True, index=True, nullable=False)
description = Column(Text)
category_id = Column(Integer, ForeignKey("categories.id"))
supplier_id = Column(Integer, ForeignKey("suppliers.id"))
quantity = Column(Integer, default=0)
min_quantity = Column(Integer, default=0)
unit_price = Column(Float, nullable=False)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
category = relationship("Category", back_populates="items")
supplier = relationship("Supplier", back_populates="items")

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

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

@ -0,0 +1,92 @@
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
updated_at: Optional[datetime] = None
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
updated_at: Optional[datetime] = None
class Config:
from_attributes = True
class InventoryItemBase(BaseModel):
name: str
sku: str
description: Optional[str] = None
category_id: Optional[int] = None
supplier_id: Optional[int] = None
quantity: int = 0
min_quantity: int = 0
unit_price: float
class InventoryItemCreate(InventoryItemBase):
pass
class InventoryItemUpdate(BaseModel):
name: Optional[str] = None
sku: Optional[str] = None
description: Optional[str] = None
category_id: Optional[int] = None
supplier_id: Optional[int] = None
quantity: Optional[int] = None
min_quantity: Optional[int] = None
unit_price: Optional[float] = None
class InventoryItem(InventoryItemBase):
id: int
created_at: datetime
updated_at: Optional[datetime] = None
category: Optional[Category] = None
supplier: Optional[Supplier] = None
class Config:
from_attributes = True

33
main.py Normal file
View File

@ -0,0 +1,33 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.inventory import router as inventory_router
app = FastAPI(
title="Small Business Inventory Management System",
description="A FastAPI-based 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/inventory", tags=["inventory"])
@app.get("/")
def read_root():
return {
"title": "Small Business Inventory Management System",
"documentation": "/docs",
"health_check": "/health",
}
@app.get("/health")
def health_check():
return {"status": "healthy", "service": "inventory-management-system"}

7
requirements.txt Normal file
View File

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