
- Set up FastAPI application with SQLite database - Implement User and Item models with relationships - Add CRUD operations for users and items - Configure Alembic for database migrations - Include API documentation at /docs and /redoc - Add health check endpoint at /health - Enable CORS for all origins - Structure code with proper separation of concerns
75 lines
2.0 KiB
Python
75 lines
2.0 KiB
Python
from typing import Any, List
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
from app import crud, schemas
|
|
from app.db.session import get_db
|
|
|
|
router = APIRouter()
|
|
|
|
@router.get("/", response_model=List[schemas.Item])
|
|
def read_items(
|
|
db: Session = Depends(get_db),
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
) -> Any:
|
|
items = crud.item.get_multi(db, skip=skip, limit=limit)
|
|
return items
|
|
|
|
@router.post("/", response_model=schemas.Item)
|
|
def create_item(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
item_in: schemas.ItemCreate,
|
|
owner_id: int,
|
|
) -> Any:
|
|
item = crud.item.create_with_owner(db, obj_in=item_in, owner_id=owner_id)
|
|
return item
|
|
|
|
@router.get("/{item_id}", response_model=schemas.Item)
|
|
def read_item(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
item_id: int,
|
|
) -> Any:
|
|
item = crud.item.get(db, id=item_id)
|
|
if not item:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
return item
|
|
|
|
@router.put("/{item_id}", response_model=schemas.Item)
|
|
def update_item(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
item_id: int,
|
|
item_in: schemas.ItemUpdate,
|
|
) -> Any:
|
|
item = crud.item.get(db, id=item_id)
|
|
if not item:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
item = crud.item.update(db, db_obj=item, obj_in=item_in)
|
|
return item
|
|
|
|
@router.delete("/{item_id}")
|
|
def delete_item(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
item_id: int,
|
|
) -> Any:
|
|
item = crud.item.get(db, id=item_id)
|
|
if not item:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
item = crud.item.remove(db, id=item_id)
|
|
return {"message": "Item deleted successfully"}
|
|
|
|
@router.get("/users/{user_id}/items", response_model=List[schemas.Item])
|
|
def read_user_items(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
user_id: int,
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
) -> Any:
|
|
items = crud.item.get_multi_by_owner(
|
|
db, owner_id=user_id, skip=skip, limit=limit
|
|
)
|
|
return items |