Add GET endpoint for api/v1/books

This commit is contained in:
Backend IM Bot 2025-03-25 16:19:34 +01:00
parent e5e268c85b
commit 0dcdec6156

43
endpoints/books.get.py Normal file
View File

@ -0,0 +1,43 @@
# Entity: Book
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.api.db.database import get_db
router = APIRouter()
@router.get("/api/v1/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.
"""
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 [
{
"id": book.id,
"title": book.title,
"author": book.author,
# Add other book fields as needed
}
for book in books
]
```
In this implementation, the `get_books` function accepts two optional query parameters: `author` and `title`. It then constructs a SQLAlchemy query on the `Book` model and applies filters based on the provided parameters using the `ilike` operator for case-insensitive pattern matching.
The filtered query is executed, and the results are returned as a list of dictionaries containing the book details. You can adjust the fields included in the dictionary based on your requirements.
Note that this implementation assumes the existence of a `Book` model and the necessary database setup with SQLAlchemy. You'll need to import the `Book` model and any required schemas in the actual implementation.