Skip to main content

Parameters and Request Handling

To define path, query, header, and cookie parameters in this project, you use high-level parameter functions that map to OpenAPI-compliant models in fastapi.openapi.models.

Defining Parameters and Request Bodies

The following example demonstrates how to declare various parameter types and a request body using Annotated and the parameter functions from fastapi.

from typing import Annotated
from fastapi import Body, Cookie, FastAPI, Header, Path, Query
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
data: str

@app.post("/items/{item_id}")
def create_item(
item_id: Annotated[str, Path(
description="The ID of the item",
openapi_examples={
"Example One": {
"summary": "A standard ID",
"value": "item_1",
}
}
)],
q: Annotated[str | None, Query(max_length=50)] = None,
user_agent: Annotated[str | None, Header()] = None,
session_id: Annotated[str | None, Cookie()] = None,
item: Item = Body(
openapi_examples={
"Normal": {
"summary": "A normal item",
"value": {"data": "some data"},
}
}
),
):
return {"item_id": item_id, "item": item}

Parameter Mapping and Models

When you use functions like Path(), Query(), or Header(), the project internally converts these into the Parameter model defined in fastapi/openapi/models.py.

The Parameter Model

The Parameter class represents an OpenAPI Parameter Object. It requires a name and a location (in_), which is defined by the ParameterInType enum:

  • ParameterInType.path: Extracted from the URL path.
  • ParameterInType.query: Extracted from the URL query string.
  • ParameterInType.header: Extracted from HTTP headers.
  • ParameterInType.cookie: Extracted from cookies.
# From fastapi/openapi/models.py
class Parameter(ParameterBase):
name: str
in_: ParameterInType = Field(alias="in")

Shared Attributes via ParameterBase

Both Parameter and Header (used for response headers) inherit from ParameterBase. This class provides the standard OpenAPI fields for validation and documentation:

  • description: A string describing the parameter.
  • required: A boolean indicating if the parameter is mandatory.
  • deprecated: A boolean to mark the parameter as deprecated in the UI.
  • examples: A dictionary of Example objects for the OpenAPI documentation.

Configuring Request Bodies

Request bodies are represented by the RequestBody model. Unlike parameters, a request body is a single object that maps media types (like application/json) to their respective schemas.

# From fastapi/openapi/models.py
class RequestBody(BaseModelWithConfig):
description: str | None = None
content: dict[str, MediaType]
required: bool | None = None

In your route functions, you use fastapi.params.Body to configure this. The openapi_examples you provide are populated into the content field of the generated RequestBody during OpenAPI generation in fastapi/openapi/utils.py.

Variations

Path Parameters

Path parameters are always required. In fastapi/params.py, the Path class enforces this by asserting that no default value is provided.

# From fastapi/params.py
class Path(Param):
in_ = ParamTypes.path
def __init__(self, default: Any = ..., **kwargs):
assert default is ..., "Path parameters cannot have a default value"
super().__init__(default=default, **kwargs)

Header Parameters and Hyphenation

By default, Header parameters convert underscores to hyphens. For example, a parameter named user_agent will look for the User-Agent HTTP header. This logic is implemented in _get_openapi_operation_parameters within fastapi/openapi/utils.py:

# From fastapi/openapi/utils.py
if (
param_type == ParamTypes.header
and name == param.name
and convert_underscores
):
name = param.name.replace("_", "-")

OpenAPI Examples

To provide rich documentation, use the openapi_examples argument. This accepts a dictionary where keys are example names and values are fastapi.openapi.models.Example structures.

item_id: str = Path(
openapi_examples={
"InternalID": {
"summary": "Internal System ID",
"value": "ID-12345",
}
}
)

Troubleshooting

  • example vs examples: The example field is deprecated in OpenAPI 3.1.0. While this codebase still supports it for backward compatibility, it issues a FastAPIDeprecationWarning. You should use examples (for JSON Schema) or openapi_examples (for OpenAPI-specific metadata) instead.
  • Required Query Parameters: To make a Query parameter required, do not provide a default value, or use ... (Ellipsis) as the first argument.
  • Path Parameter Defaults: If you attempt to provide a default value to a Path parameter, the Path class in fastapi/params.py will raise an AssertionError.