Query parameters

 Query Parameters

  • Query Parameters are parameters that have been attached after a "?".
  • Query Parameters have name=value pairs relationship.
  • Example:
    • 127.0.0.1:8000/books/?category=math
Request:
URL: 127.0.0.1:8000/?category=science

code:
@app.get("/books/")
async def read_category_by_query(category: str):
    books_to_return = []
    for book in BOOKS:
        if book.get('category').casefold() == category.casefold():
            books_to_return.append(book)
    return books_to_return


Queries parameters can be used along with path parameters.
Example:
Request:
URL: 127.0.0.1:8000/books/author%20four/?category=science

code:
@app.get("books/{book_author}/")
async def read_category_by_query(book_author: str, category: str):
    books_to_return = []
    for book in BOOKS:
        if book.get('author').casefold() == book_author.casefold() and 
            book.get('category').casefold() == category.casefold():
                books_to_return.append(book)
    return books_to_return

Code and Result:

# This code is to create the api endpoint for providing list of books as result to user whenever a link is clicked.
from fastapi import FastAPI

app = FastAPI() # allow uvicorn to identify the application is created by using FastAPI and it is the entry point for the application.
# This is the first API endpoint that will be created to return a simple message.


BOOKS = [
    {'title': 'Title one', 'author': 'Author one', 'category': 'science'},
    {'title': 'Title two', 'author': 'Author two', 'category': 'science'},
    {'title': 'Title three', 'author': 'Author three', 'category': 'history'},
    {'title': 'Title four', 'author': 'Author four', 'category': 'math'},
    {'title': 'Title five', 'author': 'Author five', 'category': 'math'}
]
@app.get("/api-endpoint") # It is a decorator that tells FastAPI that this function is an API endpoint and will call the function below when a GET request is made to the specified path.
async def first_api():
    return {"message": "Hello Puneet!"}

@app.get("/books") # Static path parameter is used here.
async def read_all_books():
    """
    This function returns the list of books.
    """
    return BOOKS

@app.get("/books/mybooks") # Static path parameter is used here.
async def read_all_books():
    """
    This function returns the list of books.
    """
    return {'book_title': 'My Favorite Book!'}

@app.get("/books/{book_title}") # Dynamic path parameter is used here.
async def read_book(book_title: str):
    """
    This function returns the book details based on the book title.
    """
    for book in BOOKS:
        if book.get('title').casefold() == book_title.casefold():
            # casefold() is used to make the comparison case-insensitive
            return book


"""
@app.get("/books/{dynamic_param}") # General one to just show what is passed in dynamic path parameter.
async def read_all_books(dynamic_param: str):
"""
"""
    This function returns the list of books based on the dynamic parameter.
"""
"""
    return {"dynamic_param": dynamic_param}
"""


@app.get("/book/") # Here fastapi will understand that this path is not using dynamic parameter but using query parameter.
async def read_category_by_query(category: str):
    """
    This function returns the list of books based on the category.
    """
    book_to_return = []
    for book in BOOKS:
        if book.get('category').casefold() == category.casefold():
            book_to_return.append(book)
    return book_to_return





Dynamic path and Query parameter together:

code and result:

# This code is to create the api endpoint for providing list of books as result to user whenever a link is clicked.
from fastapi import FastAPI

app = FastAPI() # allow uvicorn to identify the application is created by using FastAPI and it is the entry point for the application.
# This is the first API endpoint that will be created to return a simple message.


BOOKS = [
    {'title': 'Title one', 'author': 'Author one', 'category': 'science'},
    {'title': 'Title two', 'author': 'Author two', 'category': 'science'},
    {'title': 'Title three', 'author': 'Author three', 'category': 'history'},
    {'title': 'Title four', 'author': 'Author four', 'category': 'math'},
    {'title': 'Title five', 'author': 'Author five', 'category': 'math'}
]
@app.get("/api-endpoint") # It is a decorator that tells FastAPI that this function is an API endpoint and will call the function below when a GET request is made to the specified path.
async def first_api():
    return {"message": "Hello Puneet!"}

@app.get("/books") # Static path parameter is used here.
async def read_all_books():
    """
    This function returns the list of books.
    """
    return BOOKS

@app.get("/books/mybooks") # Static path parameter is used here.
async def read_all_books():
    """
    This function returns the list of books.
    """
    return {'book_title': 'My Favorite Book!'}

@app.get("/books/{book_title}") # Dynamic path parameter is used here.
async def read_book(book_title: str):
    """
    This function returns the book details based on the book title.
    """
    for book in BOOKS:
        if book.get('title').casefold() == book_title.casefold():
            # casefold() is used to make the comparison case-insensitive
            return book


"""
@app.get("/books/{dynamic_param}") # General one to just show what is passed in dynamic path parameter.
async def read_all_books(dynamic_param: str):
"""
"""
    This function returns the list of books based on the dynamic parameter.
"""
"""
    return {"dynamic_param": dynamic_param}
"""


@app.get("/book/") # Here fastapi will understand that this path is not using dynamic parameter but using query parameter.
async def read_category_by_query(category: str):
    """
    This function returns the list of books based on the category.
    """
    book_to_return = []
    for book in BOOKS:
        if book.get('category').casefold() == category.casefold():
            book_to_return.append(book)
    return book_to_return

@app.get("/book/{book_author}/")
async def read_books_by_author_category_query(book_author: str, category: str = None):
    """
    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()) and (category is None or book.get('category').casefold() == category.casefold()):
            book_to_return.append(book)
    return book_to_return



Comments

Popular posts from this blog

Post Request with Pydantic usage (input validator)

Code Scalability and Routing

CRUD Assignment