
- Set up project structure with FastAPI - Configure SQLite database with SQLAlchemy - Set up Alembic for migrations - Create Item model and schema - Implement CRUD operations - Add health endpoint generated with BackendIM... (backend.im)
97 lines
2.2 KiB
Python
97 lines
2.2 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
|
|
from app.crud.crud_item import item
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("/", response_model=List[schemas.item.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 = item.get_active_items(db, skip=skip, limit=limit)
|
|
else:
|
|
items = item.get_multi(db, skip=skip, limit=limit)
|
|
return items
|
|
|
|
|
|
@router.post("/", response_model=schemas.item.Item, status_code=status.HTTP_201_CREATED)
|
|
def create_item(
|
|
*,
|
|
db: Session = Depends(deps.get_db),
|
|
item_in: schemas.item.ItemCreate,
|
|
) -> Any:
|
|
"""
|
|
Create new item.
|
|
"""
|
|
item_obj = item.create(db=db, obj_in=item_in)
|
|
return item_obj
|
|
|
|
|
|
@router.get("/{id}", response_model=schemas.item.Item)
|
|
def read_item(
|
|
*,
|
|
db: Session = Depends(deps.get_db),
|
|
id: int,
|
|
) -> Any:
|
|
"""
|
|
Get item by ID.
|
|
"""
|
|
item_obj = item.get(db=db, id=id)
|
|
if not item_obj:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Item not found",
|
|
)
|
|
return item_obj
|
|
|
|
|
|
@router.put("/{id}", response_model=schemas.item.Item)
|
|
def update_item(
|
|
*,
|
|
db: Session = Depends(deps.get_db),
|
|
id: int,
|
|
item_in: schemas.item.ItemUpdate,
|
|
) -> Any:
|
|
"""
|
|
Update an item.
|
|
"""
|
|
item_obj = item.get(db=db, id=id)
|
|
if not item_obj:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Item not found",
|
|
)
|
|
item_obj = item.update(db=db, db_obj=item_obj, obj_in=item_in)
|
|
return item_obj
|
|
|
|
|
|
@router.delete("/{id}", response_model=schemas.item.Item)
|
|
def delete_item(
|
|
*,
|
|
db: Session = Depends(deps.get_db),
|
|
id: int,
|
|
) -> Any:
|
|
"""
|
|
Delete an item.
|
|
"""
|
|
item_obj = item.get(db=db, id=id)
|
|
if not item_obj:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Item not found",
|
|
)
|
|
item_obj = item.remove(db=db, id=id)
|
|
return item_obj |