
- Implemented project structure with FastAPI framework - Set up SQLite database with SQLAlchemy ORM - Created Alembic for database migrations - Implemented Item model and CRUD operations - Added health check endpoint - Added error handling - Configured API documentation with Swagger UI generated with BackendIM... (backend.im)
70 lines
2.2 KiB
Python
70 lines
2.2 KiB
Python
from typing import List, Optional
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.database import get_db
|
|
from app import models, schemas
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.post("/", response_model=schemas.Item, status_code=status.HTTP_201_CREATED)
|
|
def create_item(item: schemas.ItemCreate, db: Session = Depends(get_db)):
|
|
db_item = models.Item(**item.model_dump())
|
|
db.add(db_item)
|
|
db.commit()
|
|
db.refresh(db_item)
|
|
return db_item
|
|
|
|
|
|
@router.get("/", response_model=List[schemas.Item])
|
|
def read_items(
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
name: Optional[str] = None,
|
|
is_active: Optional[bool] = None,
|
|
db: Session = Depends(get_db),
|
|
):
|
|
query = db.query(models.Item)
|
|
|
|
if name:
|
|
query = query.filter(models.Item.name.contains(name))
|
|
if is_active is not None:
|
|
query = query.filter(models.Item.is_active == is_active)
|
|
|
|
items = query.offset(skip).limit(limit).all()
|
|
return items
|
|
|
|
|
|
@router.get("/{item_id}", response_model=schemas.Item)
|
|
def read_item(item_id: int, db: Session = Depends(get_db)):
|
|
db_item = db.query(models.Item).filter(models.Item.id == item_id).first()
|
|
if db_item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
return db_item
|
|
|
|
|
|
@router.put("/{item_id}", response_model=schemas.Item)
|
|
def update_item(item_id: int, item: schemas.ItemUpdate, db: Session = Depends(get_db)):
|
|
db_item = db.query(models.Item).filter(models.Item.id == item_id).first()
|
|
if db_item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
|
|
update_data = item.model_dump(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("/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
def delete_item(item_id: int, db: Session = Depends(get_db)):
|
|
db_item = db.query(models.Item).filter(models.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 |