feat: enhance books endpoint to return specific book by ID

This commit is contained in:
Backend IM Bot 2025-04-29 19:40:47 +00:00
parent 7c9d752ac2
commit d2e18dd528

View File

@ -1,27 +1,32 @@
from fastapi import APIRouter, Depends, status from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from typing import List from typing import List, Optional, Union
from uuid import UUID
from core.database import get_db from core.database import get_db
from helpers.book_helpers import get_all_books, get_book_by_id
from schemas.book import BookSchema from schemas.book import BookSchema
from helpers.book_helpers import get_all_books
router = APIRouter() router = APIRouter()
@router.get("/books", response_model=List[BookSchema], status_code=status.HTTP_200_OK) @router.get("/books", response_model=Union[List[BookSchema], BookSchema])
def get_all_books_endpoint( async def get_books(
skip: int = 0, book_id: Optional[UUID] = Query(None, description="ID of the book to retrieve"),
limit: int = 100, 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) db: Session = Depends(get_db)
): ):
""" """
Retrieve all books from the database with pagination. Get books with optional filtering by ID.
Parameters: If book_id is provided, returns a single book.
- skip: Number of records to skip (for pagination) Otherwise, returns a list of books with pagination.
- limit: Maximum number of records to return (for pagination)
Returns:
- List of books
""" """
books = get_all_books(db=db, skip=skip, limit=limit) 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 return books