'How to access fastapi.Request.state when using Pydantic.BaseModel

I'm trying to create a pydantic BaseModel that will be able to map some data from the request body and also from the request.state.

How can this be accomplished?



Solution 1:[1]

Request metadata shouldn't be part of your model - the model should only be concerned with the actual request (i.e. the data submitted by the user).

To access metadata about the request, add a Request object to your view definition:

def my_method(item: Item, request: Request):

This will magically give you all the metadata (including the .state entry) under the request variable in your view function.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MatsLindh