Skip to content

Header Parameters

Header parameters are declared the same way as Query and Path parameters:

from typing import Dict, Optional

from xpresso import App, FromHeader, Path


async def read_items(
    accept_language: FromHeader[Optional[str]] = None,
) -> Dict[str, Optional[str]]:
    return {"Accept-Language": accept_language}


app = App(
    routes=[
        Path(
            "/items/",
            get=read_items,
        )
    ]
)

Underscore conversion

Headers names are usually composed of several words separated by hyphens ("-"). But Python veriable names cannot contain hyphens. Since Xpresso automatically derives the header names from the parameter names, this creates a problem. To get around this, Xpresso automatically converts parameter name underscores ("_") to hyphens ("-"). This is controlled using the convert_underscores parameter to HeaderParam(...):

from typing import Dict, Optional

from xpresso import App, HeaderParam, Path
from xpresso.typing import Annotated


async def read_items(
    some_header: Annotated[
        str, HeaderParam(convert_underscores=False)
    ]
) -> Dict[str, Optional[str]]:
    return {"some_header": some_header}


app = App(
    routes=[
        Path(
            "/items/",
            get=read_items,
        )
    ]
)

Tip

The import from Xpresso.typing import Annotated is just a convenience import. All it does is import Annotated from typing if your Python version is >= 3.9 and [typing_extensions] otherwise. But if you are already using Python >= 3.9, you can just replace that with from typing import Annotated.

Warning

It is pretty uncommon to use headers with underscores. You should probably think twice about setting convert_underscores=False and test that it doesn't break your clients, proxies, etc.

Repeated Headers

Serialization and Parsing