48 lines
1.6 KiB
Python
48 lines
1.6 KiB
Python
# Entity: Book
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
from app.api.db.database import get_db
|
|
# You'll need to add correct model and schema imports
|
|
|
|
router = APIRouter()
|
|
|
|
@router.get("/books")
|
|
async def get_books(
|
|
author: str = None,
|
|
title: str = None,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""
|
|
Get all books with optional filtering by author and title.
|
|
|
|
Args:
|
|
author (str, optional): Filter by author name.
|
|
title (str, optional): Filter by book title.
|
|
db (Session, optional): Database session instance.
|
|
|
|
Returns:
|
|
List[Book]: List of Book objects matching the filters.
|
|
"""
|
|
query = db.query(Book)
|
|
|
|
if author:
|
|
query = query.filter(Book.author.ilike(f"%{author}%"))
|
|
|
|
if title:
|
|
query = query.filter(Book.title.ilike(f"%{title}%"))
|
|
|
|
books = query.all()
|
|
|
|
return books
|
|
```
|
|
|
|
This endpoint implements the following:
|
|
|
|
1. It accepts two optional query parameters: `author` and `title`.
|
|
2. It constructs a SQLAlchemy query on the `Book` model and applies filters based on the provided parameters.
|
|
3. If the `author` parameter is provided, it filters the books by the author name using a case-insensitive `LIKE` query.
|
|
4. If the `title` parameter is provided, it filters the books by the title using a case-insensitive `LIKE` query.
|
|
5. It retrieves all the books matching the filters and returns them as a list.
|
|
|
|
Note that you'll need to import the `Book` model and any necessary schemas for the response. Also, you may need to adjust the return type annotation based on your schema definition. |