
- Set up project structure and dependencies - Create database models with SQLAlchemy - Implement API endpoints for CRUD operations - Set up Alembic for database migrations - Add health check endpoint - Configure Ruff for linting - Update documentation in README
75 lines
2.1 KiB
Python
75 lines
2.1 KiB
Python
from typing import List
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app import models, schemas
|
|
from app.db.session import get_db
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("/", response_model=List[schemas.Item])
|
|
def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
|
"""
|
|
Retrieve items with pagination.
|
|
"""
|
|
items = db.query(models.Item).offset(skip).limit(limit).all()
|
|
return items
|
|
|
|
|
|
@router.post("/", response_model=schemas.Item, status_code=status.HTTP_201_CREATED)
|
|
def create_item(item_in: schemas.ItemCreate, db: Session = Depends(get_db)):
|
|
"""
|
|
Create new item.
|
|
"""
|
|
item = models.Item(**item_in.model_dump())
|
|
db.add(item)
|
|
db.commit()
|
|
db.refresh(item)
|
|
return item
|
|
|
|
|
|
@router.get("/{item_id}", response_model=schemas.Item)
|
|
def read_item(item_id: int, db: Session = Depends(get_db)):
|
|
"""
|
|
Get item by ID.
|
|
"""
|
|
item = db.query(models.Item).filter(models.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=schemas.Item)
|
|
def update_item(item_id: int, item_in: schemas.ItemUpdate, db: Session = Depends(get_db)):
|
|
"""
|
|
Update an item.
|
|
"""
|
|
item = db.query(models.Item).filter(models.Item.id == item_id).first()
|
|
if item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
|
|
update_data = item_in.model_dump(exclude_unset=True)
|
|
for field, value in update_data.items():
|
|
setattr(item, field, value)
|
|
|
|
db.add(item)
|
|
db.commit()
|
|
db.refresh(item)
|
|
return item
|
|
|
|
|
|
@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
|
def delete_item(item_id: int, db: Session = Depends(get_db)):
|
|
"""
|
|
Delete an item.
|
|
"""
|
|
item = db.query(models.Item).filter(models.Item.id == item_id).first()
|
|
if item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
|
|
db.delete(item)
|
|
db.commit()
|
|
return None
|