
- Set up FastAPI application with CORS support - Implement SQLAlchemy models and database session management - Create CRUD API endpoints for items management - Configure Alembic for database migrations - Add health check and service info endpoints - Include comprehensive documentation and project structure - Integrate Ruff for code quality and formatting
53 lines
1.8 KiB
Python
53 lines
1.8 KiB
Python
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
from typing import List
|
|
|
|
from app.db.session import get_db
|
|
from app.models.item import Item
|
|
from app.schemas.item import Item as ItemSchema, ItemCreate, ItemUpdate
|
|
|
|
router = APIRouter()
|
|
|
|
@router.post("/", response_model=ItemSchema)
|
|
def create_item(item: ItemCreate, db: Session = Depends(get_db)):
|
|
db_item = Item(**item.dict())
|
|
db.add(db_item)
|
|
db.commit()
|
|
db.refresh(db_item)
|
|
return db_item
|
|
|
|
@router.get("/", response_model=List[ItemSchema])
|
|
def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
|
items = db.query(Item).offset(skip).limit(limit).all()
|
|
return items
|
|
|
|
@router.get("/{item_id}", response_model=ItemSchema)
|
|
def read_item(item_id: int, db: Session = Depends(get_db)):
|
|
item = db.query(Item).filter(Item.id == item_id).first()
|
|
if item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
return item
|
|
|
|
@router.put("/{item_id}", response_model=ItemSchema)
|
|
def update_item(item_id: int, item_update: ItemUpdate, db: Session = Depends(get_db)):
|
|
db_item = db.query(Item).filter(Item.id == item_id).first()
|
|
if db_item is None:
|
|
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("/{item_id}")
|
|
def delete_item(item_id: int, db: Session = Depends(get_db)):
|
|
db_item = db.query(Item).filter(Item.id == item_id).first()
|
|
if db_item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
|
|
db.delete(db_item)
|
|
db.commit()
|
|
return {"message": "Item deleted successfully"} |