
Features: - Project structure setup - Database configuration with SQLAlchemy - Item model and CRUD operations - API endpoints for items - Alembic migrations - Health check endpoint - Comprehensive documentation generated with BackendIM... (backend.im)
72 lines
2.2 KiB
Python
72 lines
2.2 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
from typing import List
|
|
from app.database import get_db
|
|
from app.models.item import Item
|
|
from app.schemas.item import ItemCreate, ItemUpdate, ItemResponse
|
|
|
|
router = APIRouter(tags=["Items"])
|
|
|
|
@router.post("/items", response_model=ItemResponse, status_code=status.HTTP_201_CREATED)
|
|
def create_item(item: ItemCreate, db: Session = Depends(get_db)):
|
|
"""
|
|
Create a new item.
|
|
"""
|
|
db_item = Item(
|
|
name=item.name,
|
|
description=item.description,
|
|
price=item.price,
|
|
is_active=item.is_active
|
|
)
|
|
db.add(db_item)
|
|
db.commit()
|
|
db.refresh(db_item)
|
|
return db_item
|
|
|
|
@router.get("/items", response_model=List[ItemResponse])
|
|
def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
|
"""
|
|
Retrieve items.
|
|
"""
|
|
items = db.query(Item).offset(skip).limit(limit).all()
|
|
return items
|
|
|
|
@router.get("/items/{item_id}", response_model=ItemResponse)
|
|
def read_item(item_id: int, db: Session = Depends(get_db)):
|
|
"""
|
|
Get a specific item by ID.
|
|
"""
|
|
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")
|
|
return db_item
|
|
|
|
@router.put("/items/{item_id}", response_model=ItemResponse)
|
|
def update_item(item_id: int, item: ItemUpdate, db: Session = Depends(get_db)):
|
|
"""
|
|
Update an item.
|
|
"""
|
|
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.dict(exclude_unset=True)
|
|
for key, value in update_data.items():
|
|
setattr(db_item, key, value)
|
|
|
|
db.commit()
|
|
db.refresh(db_item)
|
|
return db_item
|
|
|
|
@router.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
def delete_item(item_id: int, db: Session = Depends(get_db)):
|
|
"""
|
|
Delete an item.
|
|
"""
|
|
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 None |