From 9a45e804e0b138db1ee643e9b9fb6f9a5e4fa0fa Mon Sep 17 00:00:00 2001 From: Backend IM Bot Date: Tue, 25 Mar 2025 16:28:48 +0100 Subject: [PATCH] Add GET endpoint for books --- endpoints/books.get.py | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/endpoints/books.get.py b/endpoints/books.get.py index 7cb71ae..1eaf7a6 100644 --- a/endpoints/books.get.py +++ b/endpoints/books.get.py @@ -3,10 +3,11 @@ 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("/api/v1/books") +@router.get("/books") async def get_books( author: str = None, title: str = None, @@ -14,30 +15,34 @@ async def get_books( ): """ 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 [ - { - "id": book.id, - "title": book.title, - "author": book.author, - # Add other book fields as needed - } - for book in books - ] + return 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. +This endpoint implements the following: -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. +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 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. \ No newline at end of file +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. \ No newline at end of file