PUT HTTP Request Method

 PUT HTTP Request Method

  • Used to update data
  • PUT can have a body that has additional information (like POST) that GET does not have
  • Example of body:
    • {"title": "Title Six", "author": "Author Two", "category": "science"}

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}


@app.put("/books/update_book") # This is a PUT request to update an existing book.
async def update_book(updated_book=Body()):
    """
    This function updates an existing book in the list of books.
    """
    for i in range(len(BOOKS)):
        if BOOKS[i].get('title').casefold() == updated_book.get('title').casefold():
            BOOKS[i] = updated_book
            return {"message": "Book updated successfully!", "book": updated_book, "total_books": len(BOOKS), "all_books": BOOKS}
    return {"message": "Book not found!"}




Comments

Popular posts from this blog

Post Request with Pydantic usage (input validator)

Code Scalability and Routing

CRUD Assignment