Path Parameters

 Path parameters

  • Path parameters are request parameters that have been attached to the URL.
  • They are usually defined as a way to find information based on location.
  • Think of a computer file system:
    • You can identify the specific resources based on the file you are in
      • /Users/coding/Documents/python/fastapi/section1

Static path parameters:


Dynamic path parameters:

Consider a scenario where you want to see only one book detail from URL:
127.0.0.1:8000/books/book_one

So in place of typing list of books in the URL we can use a dynamic parameter to take care of book_one or another book name in URL.


Order matters in Path Parameters:









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")
async def read_all_books():
    """
    This function returns the list of books.
    """
    return BOOKS

@app.get("/books/{dynamic_param}")
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}



Wrong order of methods and will lead to wrong answer:

# 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")
async def read_all_books():
    """
    This function returns the list of books.
    """
    return BOOKS

@app.get("/books/{dynamic_param}")
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("/books/mybooks")
async def read_all_books():
    """
    This function returns the list of books.
    """
    return {'book_title': 'My Favorite Book!'}

Result:


Right order of code:


# 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")
async def read_all_books():
    """
    This function returns the list of books.
    """
    return BOOKS

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

@app.get("/books/{dynamic_param}")
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}

Result:



Returning only desired book details:

# 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")
async def read_all_books():
    """
    This function returns the list of books.
    """
    return BOOKS

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

@app.get("/books/{book_title}")
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
    return {"message": "Book not found!"}

@app.get("/books/{dynamic_param}")
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}

Result:





Comments

Popular posts from this blog

Post Request with Pydantic usage (input validator)

Code Scalability and Routing

CRUD Assignment