CRUD Assignment

 CRUD Assignment

1. Create a new API Endpoint that can fetch all books from a specific author using either Path Parameters or Query Parameters.

Code and Result:

As async is implemented by FastAPI itself hence ignored it.
from fastapi import FastAPI

app = FastAPI()

BOOKS = [
        {"title": "Book One", "author": "Author A", "category": "Fiction"},
        {"title": "Book Two", "author": "Author B", "category": "Non-Fiction"},
        {"title": "Book Three", "author": "Author A", "category": "Biography"},
        {"title": "Book Four", "author": "Author A", "category": "Historical"},
        {"title": "Book Five", "author": "Author A", "category": "Romance"},
        {"title": "Book Six", "author": "Author A", "category": "Science Fiction"}
    ]

@app.get("/books/{book_author}") # Dynamic path parameter is used here.
def read_all_books_by_author(book_author: str):
    """
    This function returns the list of books based on the author.
    """
    book_to_return = []
    for book in BOOKS:
        if book.get('author').casefold() == book_author.casefold():
            book_to_return.append(book)
    return book_to_return

@app.get("/books/") # query parameter is used here.
def read_books_by_author(author: str = None):
    """
    This function returns the list of books based on the category.
    """
    book_to_return = []
    for book in BOOKS:
        if book.get('author').casefold() == author.casefold():
            book_to_return.append(book)
    return book_to_return





Comments

Popular posts from this blog

Python Variables

API Request Method - Post Todos (create and save todo)