Fastapi: [FEATURE] Headers should be typed as Optional

Created on 23 Apr 2019  路  4Comments  路  Source: tiangolo/fastapi

Is your feature request related to a problem? Please describe.
Setting headers for routes requires adding invalid type information because while headers are optional, they cannot be typed as optional.

Describe the solution you'd like
Headers that are typed as str should error if they are not provided. Otherwise, headers should be typed as Optional if they are so.

Describe alternatives you've considered
N/A

Additional context

x_custom_header will not be str if the request doesn't include it.

async def example_route(
    payload: dict, *, x_custom_header: str = Header(None)
):
    assert x_custom_header is not None
    return {"msg": "ok"}

Changing the type hint to typing.Optional[str] raises an assertion error: AssertionError('Parameters for Query and Header must be of type str, int, float, bool, list, tuple or set...

enhancement

Most helpful comment

This should be fixed now in the (just released), FastAPI version 0.27.0.

All 4 comments

Good point. I'll check it.

I think it's the same situation for query parameters. The documentation on optional query parameters says:

The same way, you can declare optional query parameters, by setting their default to None:

But then the type should technically be Optional[...]. The example in the Optional parameters section should not type-check:

async def read_item(item_id: str, q: str = None):

Because q: str = None is invalid: q is declared as str but None is not a str, it is an Optional.

Just hit what @Victor-Savu describes. Looks like being able to use Optional[] in headers/query_param definitions is a must to support mypy --strict-optional feature.

This should be fixed now in the (just released), FastAPI version 0.27.0.

Was this page helpful?
0 / 5 - 0 ratings