In FastAPI, how does the framework determine whether a function parameter like 'who' is a path parameter, query parameter, body parameter, or header parameter?
FastAPI checks whether the parameter name appears inside curly braces in the URL pattern of the decorator; if it does, it is a path parameter. If the parameter has a Body() or Header() default, FastAPI reads it from the HTTP body or headers. Otherwise, a plain parameter with no special default is assumed to be a query parameter.
In the examples, when the route is written as @app.get("/hi/{who}") and the function is defined as greet(who), the presence of {who} in the path decorator tells FastAPI to match that URL segment and assign it to the who argument. When the route is just @app.get("/hi") and the function is again greet(who) without {who} in the URL, FastAPI interprets who as a query parameter. For body input, the function must declare who with the Body default, e.g. who: str = Body(embed=True), which tells FastAPI to take who from the JSON request body. For header input, the function declares who: str = Header(), which tells FastAPI to take who from an HTTP header. Thus FastAPI decides based on the combination of the route template and the function parameter's declaration and defaults.
Key points
- A parameter named in the URL curly braces, such as {who}, becomes a path parameter and is bound to that function argument.
- If the parameter is not in the URL and has no special FastAPI default, FastAPI treats it as a query parameter.
- Giving the parameter a Body() default directs FastAPI to read it from the HTTP request body, with Body(embed=True) expecting a JSON object like {"who": "Mom"}.
- Giving the parameter a Header() default directs FastAPI to read it from the HTTP headers.
Related questions
FastAPI: Modern Python Web Development
Bill Lubanovic;
First Edition · O'Reilly Media, Inc.