92 lines
2.2 KiB
Python
92 lines
2.2 KiB
Python
from typing import List
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.db.repositories import item_repository
|
|
from app.db.schemas.item import Item, ItemCreate, ItemUpdate
|
|
from app.db.session import get_db
|
|
|
|
router = APIRouter(tags=["items"])
|
|
|
|
|
|
@router.get("/items/", response_model=List[Item])
|
|
def read_items(
|
|
skip: int = Query(0, ge=0),
|
|
limit: int = Query(100, ge=1, le=100),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""
|
|
Retrieve items with pagination support.
|
|
"""
|
|
items = item_repository.get_multi(db=db, skip=skip, limit=limit)
|
|
return items
|
|
|
|
|
|
@router.post("/items/", response_model=Item, status_code=status.HTTP_201_CREATED)
|
|
def create_item(
|
|
item_in: ItemCreate,
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""
|
|
Create a new item.
|
|
"""
|
|
item = item_repository.create(db=db, obj_in=item_in)
|
|
return item
|
|
|
|
|
|
@router.get("/items/{item_id}", response_model=Item)
|
|
def read_item(
|
|
item_id: int,
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""
|
|
Get item by ID.
|
|
"""
|
|
item = item_repository.get(db=db, id=item_id)
|
|
if item is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Item not found",
|
|
)
|
|
return item
|
|
|
|
|
|
@router.put("/items/{item_id}", response_model=Item)
|
|
def update_item(
|
|
item_id: int,
|
|
item_in: ItemUpdate,
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""
|
|
Update an item.
|
|
"""
|
|
item = item_repository.get(db=db, id=item_id)
|
|
if item is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Item not found",
|
|
)
|
|
item = item_repository.update(db=db, db_obj=item, obj_in=item_in)
|
|
return item
|
|
|
|
|
|
@router.delete(
|
|
"/items/{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 = item_repository.get(db=db, id=item_id)
|
|
if item is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Item not found",
|
|
)
|
|
item_repository.remove(db=db, id=item_id)
|
|
return None
|