
Implemented a complete FastAPI backend with: - Project structure with FastAPI and SQLAlchemy - SQLite database with proper configuration - Alembic for database migrations - Generic Item resource with CRUD operations - REST API endpoints with proper validation - Health check endpoint - Documentation and setup instructions
88 lines
2.0 KiB
Python
88 lines
2.0 KiB
Python
from typing import Any, List
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app import crud, schemas
|
|
from app.api import deps
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("/", response_model=List[schemas.Item])
|
|
def read_items(
|
|
db: Session = Depends(deps.get_db),
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
active_only: bool = False,
|
|
) -> Any:
|
|
"""
|
|
Retrieve items.
|
|
"""
|
|
if active_only:
|
|
items = crud.item.get_active_items(db, skip=skip, limit=limit)
|
|
else:
|
|
items = crud.item.get_multi(db, skip=skip, limit=limit)
|
|
return items
|
|
|
|
|
|
@router.post("/", response_model=schemas.Item, status_code=status.HTTP_201_CREATED)
|
|
def create_item(
|
|
*,
|
|
db: Session = Depends(deps.get_db),
|
|
item_in: schemas.ItemCreate,
|
|
) -> Any:
|
|
"""
|
|
Create new item.
|
|
"""
|
|
item = crud.item.create(db=db, obj_in=item_in)
|
|
return item
|
|
|
|
|
|
@router.get("/{id}", response_model=schemas.Item)
|
|
def read_item(
|
|
*,
|
|
db: Session = Depends(deps.get_db),
|
|
id: int,
|
|
) -> Any:
|
|
"""
|
|
Get item by ID.
|
|
"""
|
|
item = crud.item.get(db=db, id=id)
|
|
if not item:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
return item
|
|
|
|
|
|
@router.put("/{id}", response_model=schemas.Item)
|
|
def update_item(
|
|
*,
|
|
db: Session = Depends(deps.get_db),
|
|
id: int,
|
|
item_in: schemas.ItemUpdate,
|
|
) -> Any:
|
|
"""
|
|
Update an item.
|
|
"""
|
|
item = crud.item.get(db=db, id=id)
|
|
if not item:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
item = crud.item.update(db=db, db_obj=item, obj_in=item_in)
|
|
return item
|
|
|
|
|
|
@router.delete("/{id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
|
def delete_item(
|
|
*,
|
|
db: Session = Depends(deps.get_db),
|
|
id: int,
|
|
) -> Any:
|
|
"""
|
|
Delete an item.
|
|
"""
|
|
item = crud.item.get(db=db, id=id)
|
|
if not item:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
item = crud.item.remove(db=db, id=id)
|
|
return None
|