Google News
logo
FastAPI - Interview Questions
Explain the difference between path parameters and query parameters in FastAPI.
In FastAPI, both path parameters and query parameters are used to extract information from the URL, but they serve different purposes and have distinct syntax. Here's an explanation of the differences between path parameters and query parameters:

Path Parameters :

1. Positional in the URL : 
Path parameters are part of the URL path itself and are specified by enclosing them in curly braces {} within the route path. They are positional and must be included in the order they appear in the route definition.
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}?

In this example, the item_id is a path parameter that is part of the URL path /items/{item_id}.


2. Required by Default :
Path parameters are required by default. If a path parameter is defined in the route, it must be provided in the URL, and its type is automatically validated based on the type hint in the route function.


Query Parameters :

1. Appended to the URL : Query parameters are appended to the URL after a question mark ? and are usually in the form of key=value pairs. They are optional and can be provided in any order.
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/")
def read_item(query_param: str):
    return {"query_param": query_param}?

In this example, query_param is a query parameter that can be provided in the URL, e.g., /items/?query_param=value.

2. Optional and Specified with Defaults : Query parameters are optional by default. You can provide default values for query parameters in the route function to indicate a default value if the parameter is not provided in the URL.
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/")
def read_item(query_param: str = "default_value"):
    return {"query_param": query_param}?

If the client does not provide a value for query_param, the default value "default_value" will be used.

Example :
from fastapi import FastAPI

app = FastAPI()

# Path parameter
@app.get("/items/{item_id}")
def read_item_by_id(item_id: int):
    return {"item_id": item_id}

# Query parameter with a default value
@app.get("/items/")
def read_items_with_query_param(query_param: str = "default_value"):
    return {"query_param": query_param}?

In the example above, /items/{item_id} expects a path parameter (item_id) in the URL path, while /items/ expects an optional query parameter (query_param) with a default value.
Advertisement