34 lines
1.4 KiB
Python
34 lines
1.4 KiB
Python
from fastapi import APIRouter, Depends, Query, status
|
|
from sqlalchemy.orm import Session
|
|
from typing import List, Optional
|
|
|
|
from core.database import get_db
|
|
from helpers.book_helpers import get_all_books, get_books_by_author, get_books_by_title
|
|
from schemas.book import BookSchema
|
|
|
|
router = APIRouter()
|
|
|
|
@router.get("/books", response_model=List[BookSchema], status_code=status.HTTP_200_OK)
|
|
async def get_books(
|
|
author: Optional[str] = Query(None, description="Filter books by author name"),
|
|
title: Optional[str] = Query(None, description="Filter books by title or partial title match"),
|
|
skip: int = Query(0, description="Number of records to skip for pagination"),
|
|
limit: int = Query(100, description="Maximum number of records to return"),
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""
|
|
Get all books with optional filtering by author or title.
|
|
|
|
- If author is provided, returns all books by that author
|
|
- If title is provided, returns all books with matching title (partial match)
|
|
- If both are provided, returns books matching both criteria
|
|
- If neither is provided, returns all books
|
|
"""
|
|
if author and not title:
|
|
books = get_books_by_author(db, author=author, skip=skip, limit=limit)
|
|
elif title and not author:
|
|
books = get_books_by_title(db, title=title, skip=skip, limit=limit)
|
|
else:
|
|
books = get_all_books(db, author=author, title=title, skip=skip, limit=limit)
|
|
|
|
return books |