Implement product catalog API with CRUD operations

- Created FastAPI application with product catalog functionality
- Implemented CRUD operations for products
- Added SQLAlchemy models and Pydantic schemas
- Set up SQLite database with Alembic migrations
- Added health check endpoint
- Updated README with project documentation

generated with BackendIM... (backend.im)
This commit is contained in:
Automated Action 2025-05-13 17:21:00 +00:00
parent 979005abe0
commit 0e00013b7f
22 changed files with 634 additions and 2 deletions

View File

@ -1,3 +1,87 @@
# FastAPI Application # Product Catalog API
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. A simple product catalog API with CRUD operations built with FastAPI and SQLite.
## Features
- Product management with CRUD operations
- Product filtering by category
- Health check endpoint
- Database migrations using Alembic
- SQLite database for data storage
## Project Structure
```
.
├── app
│ ├── api
│ │ ├── api.py # API router configuration
│ │ ├── health.py # Health check endpoint
│ │ └── products.py # Product endpoints
│ ├── crud
│ │ └── product.py # CRUD operations for products
│ ├── db
│ │ └── database.py # Database configuration and session
│ ├── models
│ │ └── product.py # SQLAlchemy models
│ └── schemas
│ ├── health.py # Pydantic schemas for health check
│ └── product.py # Pydantic schemas for products
├── migrations # Alembic migration files
│ ├── env.py
│ ├── script.py.mako
│ └── versions
│ └── initial_products_table.py
├── alembic.ini # Alembic configuration
├── main.py # Application entry point
└── requirements.txt # Project dependencies
```
## Installation
1. Clone the repository
2. Install dependencies:
```bash
pip install -r requirements.txt
```
## Running the Application
```bash
uvicorn main:app --reload
```
The API will be available at http://localhost:8000.
API documentation is available at:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
## API Endpoints
### Health Check
- `GET /health` - Get API health status
### Products
- `GET /products` - Get all products (with optional category filter)
- `POST /products` - Create a new product
- `GET /products/{product_id}` - Get a specific product
- `PUT /products/{product_id}` - Update a product
- `DELETE /products/{product_id}` - Delete a product
## Database
The application uses SQLite as database, stored at `/app/storage/db/db.sqlite`.
## Database Migrations
Migrations are managed with Alembic.
```bash
# Apply migrations
alembic upgrade head
```

101
alembic.ini Normal file
View File

@ -0,0 +1,101 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = migrations
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python-dateutil library that can be
# installed by adding `alembic[tz]` to the pip requirements
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to migrations/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# Logging configuration
[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
View File

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

7
app/api/api.py Normal file
View File

@ -0,0 +1,7 @@
from fastapi import APIRouter
from app.api import products, health
api_router = APIRouter()
api_router.include_router(health.router, prefix="/health", tags=["health"])
api_router.include_router(products.router, prefix="/products", tags=["products"])

12
app/api/health.py Normal file
View File

@ -0,0 +1,12 @@
from fastapi import APIRouter
from app.schemas.health import HealthCheck
router = APIRouter()
@router.get("/", response_model=HealthCheck)
def health_check():
"""
Health check endpoint.
"""
return HealthCheck(status="ok", version="0.1.0")

105
app/api/products.py Normal file
View File

@ -0,0 +1,105 @@
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from app.db.database import get_db
from app.models.product import Product as ProductModel
from app.schemas.product import Product, ProductCreate, ProductUpdate
from app.crud import product as product_crud
router = APIRouter()
@router.get("/", response_model=List[Product])
def get_products(
category: Optional[str] = None,
skip: int = Query(0, ge=0),
limit: int = Query(100, ge=1, le=100),
db: Session = Depends(get_db),
):
"""
Retrieve all products with optional filtering by category.
"""
products = product_crud.get_products(db, skip=skip, limit=limit, category=category)
return products
@router.post("/", response_model=Product, status_code=status.HTTP_201_CREATED)
def create_product(
product: ProductCreate,
db: Session = Depends(get_db),
):
"""
Create a new product.
"""
db_product = product_crud.get_product_by_sku(db, sku=product.sku)
if db_product:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Product with SKU {product.sku} already exists",
)
return product_crud.create_product(db=db, product=product)
@router.get("/{product_id}", response_model=Product)
def get_product(
product_id: int,
db: Session = Depends(get_db),
):
"""
Get a specific product by ID.
"""
db_product = product_crud.get_product(db, product_id=product_id)
if db_product is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Product with ID {product_id} not found",
)
return db_product
@router.put("/{product_id}", response_model=Product)
def update_product(
product_id: int,
product_update: ProductUpdate,
db: Session = Depends(get_db),
):
"""
Update a product.
"""
db_product = product_crud.get_product(db, product_id=product_id)
if db_product is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Product with ID {product_id} not found",
)
# If SKU is being updated, check if it already exists
if product_update.sku is not None and product_update.sku != db_product.sku:
existing_product = product_crud.get_product_by_sku(db, sku=product_update.sku)
if existing_product:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Product with SKU {product_update.sku} already exists",
)
return product_crud.update_product(db=db, db_product=db_product, product_update=product_update)
@router.delete("/{product_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_product(
product_id: int,
db: Session = Depends(get_db),
):
"""
Delete a product.
"""
db_product = product_crud.get_product(db, product_id=product_id)
if db_product is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Product with ID {product_id} not found",
)
product_crud.delete_product(db=db, db_product=db_product)
return None

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

60
app/crud/product.py Normal file
View File

@ -0,0 +1,60 @@
from typing import List, Optional
from sqlalchemy.orm import Session
from sqlalchemy import desc
from app.models.product import Product
from app.schemas.product import ProductCreate, ProductUpdate
def get_product(db: Session, product_id: int) -> Optional[Product]:
return db.query(Product).filter(Product.id == product_id).first()
def get_product_by_sku(db: Session, sku: str) -> Optional[Product]:
return db.query(Product).filter(Product.sku == sku).first()
def get_products(
db: Session,
skip: int = 0,
limit: int = 100,
category: Optional[str] = None
) -> List[Product]:
query = db.query(Product)
if category:
query = query.filter(Product.category == category)
return query.order_by(desc(Product.created_at)).offset(skip).limit(limit).all()
def create_product(db: Session, product: ProductCreate) -> Product:
db_product = Product(
name=product.name,
description=product.description,
price=product.price,
sku=product.sku,
stock=product.stock,
category=product.category
)
db.add(db_product)
db.commit()
db.refresh(db_product)
return db_product
def update_product(
db: Session, db_product: Product, product_update: ProductUpdate
) -> Product:
update_data = product_update.model_dump(exclude_unset=True)
for field, value in update_data.items():
setattr(db_product, field, value)
db.commit()
db.refresh(db_product)
return db_product
def delete_product(db: Session, db_product: Product) -> None:
db.delete(db_product)
db.commit()

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

28
app/db/database.py Normal file
View File

@ -0,0 +1,28 @@
from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
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)
Base = declarative_base()
def create_db_and_tables():
Base.metadata.create_all(bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

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

@ -0,0 +1 @@
from app.models.product import Product

16
app/models/product.py Normal file
View File

@ -0,0 +1,16 @@
from sqlalchemy import Column, Integer, String, Float, Text, DateTime
from sqlalchemy.sql import func
from app.db.database import Base
class Product(Base):
__tablename__ = "products"
id = Column(Integer, primary_key=True, index=True)
name = Column(String(100), nullable=False, index=True)
description = Column(Text, nullable=True)
price = Column(Float, nullable=False)
sku = Column(String(50), unique=True, index=True)
stock = Column(Integer, default=0)
category = Column(String(50), nullable=True, index=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())

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

@ -0,0 +1 @@
from app.schemas.product import Product, ProductCreate, ProductUpdate, ProductInDB

6
app/schemas/health.py Normal file
View File

@ -0,0 +1,6 @@
from pydantic import BaseModel
class HealthCheck(BaseModel):
status: str = "ok"
version: str

38
app/schemas/product.py Normal file
View File

@ -0,0 +1,38 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
class ProductBase(BaseModel):
name: str = Field(..., min_length=1, max_length=100, example="Smartphone XYZ")
description: Optional[str] = Field(None, example="Latest model with advanced features")
price: float = Field(..., gt=0, example=799.99)
sku: str = Field(..., min_length=3, max_length=50, example="SM-XYZ-2023")
stock: int = Field(0, ge=0, example=25)
category: Optional[str] = Field(None, example="Electronics")
class ProductCreate(ProductBase):
pass
class ProductUpdate(BaseModel):
name: Optional[str] = Field(None, min_length=1, max_length=100)
description: Optional[str] = None
price: Optional[float] = Field(None, gt=0)
sku: Optional[str] = Field(None, min_length=3, max_length=50)
stock: Optional[int] = Field(None, ge=0)
category: Optional[str] = None
class ProductInDB(ProductBase):
id: int
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True
class Product(ProductInDB):
pass

19
main.py Normal file
View File

@ -0,0 +1,19 @@
from fastapi import FastAPI
from app.api.api import api_router
from app.db.database import create_db_and_tables
app = FastAPI(
title="Product Catalog API",
description="A simple product catalog API with CRUD operations",
version="0.1.0",
)
@app.on_event("startup")
def on_startup():
create_db_and_tables()
app.include_router(api_router)
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

0
migrations/__init__.py Normal file
View File

80
migrations/env.py Normal file
View File

@ -0,0 +1,80 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config, pool
from alembic import context
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
from app.models import Product
from app.db.database import Base
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
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():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
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
migrations/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():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}

View File

@ -0,0 +1,44 @@
"""Initial products table
Revision ID: 001
Revises:
Create Date: 2025-05-13
"""
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():
op.create_table(
'products',
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('price', sa.Float(), nullable=False),
sa.Column('sku', sa.String(length=50), nullable=False),
sa.Column('stock', sa.Integer(), nullable=True, default=0),
sa.Column('category', sa.String(length=50), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_products_id'), 'products', ['id'], unique=False)
op.create_index(op.f('ix_products_name'), 'products', ['name'], unique=False)
op.create_index(op.f('ix_products_sku'), 'products', ['sku'], unique=True)
op.create_index(op.f('ix_products_category'), 'products', ['category'], unique=False)
def downgrade():
op.drop_index(op.f('ix_products_category'), table_name='products')
op.drop_index(op.f('ix_products_sku'), table_name='products')
op.drop_index(op.f('ix_products_name'), table_name='products')
op.drop_index(op.f('ix_products_id'), table_name='products')
op.drop_table('products')

6
requirements.txt Normal file
View File

@ -0,0 +1,6 @@
fastapi==0.110.0
uvicorn==0.27.1
sqlalchemy==2.0.27
pydantic==2.5.3
alembic==1.13.1
python-dotenv==1.0.0