
- Set up project structure with FastAPI framework - Implement database models using SQLAlchemy - Create Alembic migrations for database schema - Build CRUD endpoints for Items resource - Add health check endpoint - Include API documentation with Swagger and ReDoc - Update README with project documentation
56 lines
1.4 KiB
Python
56 lines
1.4 KiB
Python
from typing import List, Optional, Dict, Any
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.models.item import Item
|
|
from app.schemas.item import ItemCreate, ItemUpdate
|
|
|
|
|
|
def get_item(db: Session, item_id: int) -> Optional[Item]:
|
|
return db.query(Item).filter(Item.id == item_id).first()
|
|
|
|
|
|
def get_items(
|
|
db: Session, skip: int = 0, limit: int = 100, filter_dict: Optional[Dict[str, Any]] = None
|
|
) -> List[Item]:
|
|
query = db.query(Item)
|
|
|
|
if filter_dict:
|
|
for field, value in filter_dict.items():
|
|
if hasattr(Item, field):
|
|
query = query.filter(getattr(Item, field) == value)
|
|
|
|
return query.offset(skip).limit(limit).all()
|
|
|
|
|
|
def create_item(db: Session, item: ItemCreate) -> Item:
|
|
db_item = Item(**item.model_dump())
|
|
db.add(db_item)
|
|
db.commit()
|
|
db.refresh(db_item)
|
|
return db_item
|
|
|
|
|
|
def update_item(db: Session, item_id: int, item: ItemUpdate) -> Optional[Item]:
|
|
db_item = get_item(db, item_id)
|
|
if not db_item:
|
|
return None
|
|
|
|
update_data = item.model_dump(exclude_unset=True)
|
|
for field, value in update_data.items():
|
|
setattr(db_item, field, value)
|
|
|
|
db.add(db_item)
|
|
db.commit()
|
|
db.refresh(db_item)
|
|
return db_item
|
|
|
|
|
|
def delete_item(db: Session, item_id: int) -> bool:
|
|
db_item = get_item(db, item_id)
|
|
if not db_item:
|
|
return False
|
|
|
|
db.delete(db_item)
|
|
db.commit()
|
|
return True |