HTTP POST Request Method

 HTTP POST Request Method

  • Used to create data
  • POST can have a body that has additional information that GET does not have
  • Example of Body:
    • {"title": "Title Seven", "author": "Author Two", "category": "math"}

POST request need body as additional information to create data by using API.
So we need to import Body from Fastapi package.

from fastapi import Body, FastAPI

As get cannot have body but post will have body which is the information it need to create by using API endpoint in a database or in any variable for usage.

Note: Do remember at the time of passing body to api-end point for post request give strings in double quotation not in single quotation. As body need to be of json format.

If you will give body as input parameter to GET method it will compile but will give error at the time of API run as body is not permitted for GET request.

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 Body, 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


@app.post("/books/create_book") # This is a POST request to create a new book.
async def create_book(new_book=Body()):
    """
    This function creates a new book and adds it to the list of books.
    """
    BOOKS.append(new_book)
    return {"message": "Book created successfully!", "book": new_book, "total_books":
len(BOOKS), "all_books": BOOKS}




Comments

Popular posts from this blog

Post Request with Pydantic usage (input validator)

Code Scalability and Routing

CRUD Assignment