Insights

Handling Parameters as Headers, Query or Path Parameters in FastAPI

Handling Parameters as Headers, Query or Path Parameters in FastAPI

Handling Parameters as Headers, Query or Path Parameters in FastAPI

Saurabh Jain

Sep 5, 2024

When building a FastAPI application, handling parameters correctly is crucial to ensure that your endpoints function as expected. FastAPI makes it easy to work with both request headers and query parameters, allowing you to create flexible and powerful APIs. In this article, we'll explore how to handle parameters as headers or query parameters in FastAPI, and when you might want to use each method.

What are Query Parameters and Headers?

Before diving into the code, let's clarify some key terms:

- Query Parameters: These are part of the URL in a request. They typically follow the "?" symbol in the query string and are used to filter or modify the response from the server. For example, in the URL `https://example.com/items?category=books&limit=10`, `category` and `limit` are query parameters.

- Headers: Request headers are key-value pairs sent with the HTTP request or response, carrying information like content type, authentication tokens, and more. Unlike query parameters, headers are not visible in the URL and are instead part of the HTTP request metadata, also known as HTTP headers.

Handling Query Parameters in FastAPI

Query parameters are straightforward to handle in FastAPI. Let's say you want to create an endpoint in your FastAPI application that retrieves items, and you want to filter these items based on a `category` query parameter and limit the number of items returned with a `limit` query parameter.

Here's how you can do it:

from fastapi import FastAPI
from typing import Optional
app = FastAPI()

@app.get("/items/")
async def get_items(category: Optional[str] = None, limit: int = 10):
    items = [{"item_id": 1, "category": "books"}, {"item_id": 2, "category": "electronics"}]
    if category:
        items = [item for item in items if item["category"] == category]
    return items[:limit]

In this example:

- category is an optional query parameter. If it’s not provided, it defaults to `None`.

- limit is another query parameter with a default value of `10`.

When you make a request to /items?category=books&limit=2, FastAPI will filter the items by the `books` category and return only 2 items. This demonstrates how you can handle request parameters that come through the query string.

Handling Headers in FastAPI

Sometimes, you need to extract information from the request headers. FastAPI makes this easy as well. Let’s modify our previous example to require an X-Token HTTP header, which might be used for simple authentication.

from fastapi import FastAPI, Header, HTTPException
app = FastAPI()

@app.get("/items/")
async def get_items(category: Optional[str] = None, limit: int = 10, x_token: str = Header(...)):
    if x_token != "supersecrettoken":
        raise HTTPException(status_code=400, detail="Invalid X-Token header")
    items = [{"item_id": 1, "category": "books"}, {"item_id": 2, "category": "electronics"}]
    if category:
        items = [item for item in items if item["category"] == category]
    return items[:limit]

In this case:

- The x_token HTTP header is required for the request. If it doesn’t match the expected value, FastAPI returns an error.

- The Header function is used to extract the X-Token header from the incoming request.

When a request is made to /items with the header X-Token: supersecrettoken, the server processes the request normally. Otherwise, it raises an HTTP exception.

When to Use Query Parameters vs. Headers

- Use Query Parameters when you want to filter or sort data. Query parameters are ideal for optional query parameters that modify the response, like search filters, pagination limits, or sorting criteria.

- Use Headers for metadata that affects how the request is processed but doesn’t directly modify the resource being fetched. Request headers are commonly used for passing authentication tokens, content type, and custom user agents.

Combining Query Parameters and Headers

In many cases, you’ll need to handle both query parameters and headers in the same endpoint. FastAPI allows you to do this seamlessly. Here’s an example that combines both:

from fastapi import FastAPI, Header, HTTPException, Query
from typing import Optional
app = FastAPI()

@app.get("/items/")
async def get_items(
    category: Optional[str] = Query(None), 
    limit: int = Query(10),
    x_token: str = Header(...)
):
    if x_token != "supersecrettoken":
        raise HTTPException(status_code=400, detail="Invalid X-Token header")
    
    items = [{"item_id": 1, "category": "books"}, {"item_id": 2, "category": "electronics"}]
    
    if category:
        items = [item for item in items if item["category"] == category]
    
    return items[:limit]

Here, we use Query to define query parameters and Header to handle the header. This method allows you to have clean, readable code while ensuring that your API handles requests securely and efficiently.

Handling Path Parameters in FastAPI

Along with query parameters and headers, FastAPI also allows you to work with path parameters. Path parameters are part of the URL path and are often used to identify specific resources. For example, in the URL /items/{item_id}, item_id is a path parameter.

Here's how you can handle path parameters along with query parameters and headers:

from fastapi import FastAPI, Header, HTTPException, Query, Path
app = FastAPI()

@app.get("/items/{item_id}")
async def get_item(
    item_id: int = Path(..., title="The ID of the item to get"),
    category: Optional[str] = Query(None), 
    limit: int = Query(10),
    x_token: str = Header(...)
):
    if x_token != "supersecrettoken":
        raise HTTPException(status_code=400, detail="Invalid X-Token header")
    
    items = [{"item_id": item_id, "category": "books"}]
    
    if category:
        items = [item for item in items if item["category"] == category]
    
    return items[:limit]

In this example:

- The item_id is a path parameter that identifies the specific item.

- The query parameters and headers are handled similarly to the previous examples, but now they are combined with a path parameter.

Conclusion

FastAPI makes it simple to work with query parameters, request headers, and path parameters, offering flexibility and clarity in your code. Whether you're filtering results with query parameters, securing requests with headers, or identifying resources with path parameters, FastAPI provides the tools you need to build robust and flexible APIs. By understanding when and how to use these components, you can create cleaner, more effective endpoints for your FastAPI application.

Saurabh Jain

Share this post