32 lines
1.1 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional, Union
from uuid import UUID
from core.database import get_db
from helpers.book_helpers import get_all_books, get_book_by_id
from schemas.book import BookSchema
router = APIRouter()
@router.get("/books", response_model=Union[List[BookSchema], BookSchema])
async def get_books(
book_id: Optional[UUID] = Query(None, description="ID of the book to retrieve"),
skip: int = Query(0, description="Number of records to skip"),
limit: int = Query(100, description="Maximum number of records to return"),
db: Session = Depends(get_db)
):
"""
Get books with optional filtering by ID.
If book_id is provided, returns a single book.
Otherwise, returns a list of books with pagination.
"""
if book_id:
book = get_book_by_id(db, book_id)
if not book:
raise HTTPException(status_code=404, detail="Book not found")
return book
books = get_all_books(db, skip=skip, limit=limit)
return books