| 1 |
Parameters |
| 2 |
========== |
| 3 |
|
| 4 |
.. _parameter-types: |
| 5 |
|
| 6 |
|
| 7 |
Request parameters are parts of the request that can be injected into a handler function |
| 8 |
or dependency. They allow type-coercion, validation, and will show up in the generated |
| 9 |
OpenAPI schema. |
| 10 |
|
| 11 |
There are for request parameter types supported, which can be specified in two different |
| 12 |
forms: |
| 13 |
|
| 14 |
+--------+----------------------------+---------------------------------------------------------------------------+ |
| 15 |
| Type | Short form | :class:`~typing.Annotated` Form | |
| 16 |
+========+============================+===========================================================================+ |
| 17 |
| query | :data:`.params.FromQuery` | :class:`Annotated[\<type\>, QueryParameter()] <.params.QueryParameter>` | |
| 18 |
+--------+----------------------------+---------------------------------------------------------------------------+ |
| 19 |
| path | :data:`.params.FromPath` | :class:`Annotated[\<type\>, PathParameter()] <.params.PathParameter>` | |
| 20 |
+--------+----------------------------+---------------------------------------------------------------------------+ |
| 21 |
| header | :data:`.params.FromHeader` | :class:`Annotated[\<type\>, HeaderParameter()] <.params.HeaderParameter>` | |
| 22 |
+--------+----------------------------+---------------------------------------------------------------------------+ |
| 23 |
| cookie | :data:`.params.FromCookie` | :class:`Annotated[\<type\>, CookieParameter()] <.params.CookieParameter>` | |
| 24 |
+--------+----------------------------+---------------------------------------------------------------------------+ |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
Parameter declarations |
| 29 |
---------------------- |
| 30 |
|
| 31 |
Each parameter source has two equivalent declaration forms: a marker type alias for the |
| 32 |
common case, and an :class:`~typing.Annotated` form for when extra configuration is |
| 33 |
needed: |
| 34 |
|
| 35 |
.. tab-set:: |
| 36 |
|
| 37 |
.. tab-item:: Marker form |
| 38 |
|
| 39 |
.. code-block:: python |
| 40 |
|
| 41 |
from litestar import get |
| 42 |
from litestar.params import FromCookie, FromHeader, FromPath, FromQuery |
| 43 |
|
| 44 |
@get("/{user_id:int}") |
| 45 |
async def handler( |
| 46 |
user_id: FromPath[int], |
| 47 |
limit: FromQuery[int], |
| 48 |
token: FromHeader[str], |
| 49 |
session: FromCookie[str], |
| 50 |
) -> None: ... |
| 51 |
|
| 52 |
.. tab-item:: Annotated form |
| 53 |
|
| 54 |
.. code-block:: python |
| 55 |
|
| 56 |
from typing_extensions import Annotated |
| 57 |
|
| 58 |
from litestar import get |
| 59 |
from litestar.params import ( |
| 60 |
CookieParameter, |
| 61 |
HeaderParameter, |
| 62 |
PathParameter, |
| 63 |
QueryParameter, |
| 64 |
) |
| 65 |
|
| 66 |
@get("/{user_id:int}") |
| 67 |
async def handler( |
| 68 |
user_id: Annotated[int, PathParameter(ge=1)], |
| 69 |
limit: Annotated[int, QueryParameter(gt=0, le=100)], |
| 70 |
token: Annotated[str, HeaderParameter(name="X-API-KEY")], |
| 71 |
session: Annotated[str, CookieParameter(name="session-id")], |
| 72 |
) -> None: ... |
| 73 |
|
| 74 |
The two forms are equivalent: ``FromQuery[T]`` is just an alias for |
| 75 |
``Annotated[T, QueryParameter()]``. Prefer the marker form when no extra configuration |
| 76 |
is needed. |
| 77 |
|
| 78 |
.. admonition:: Technical details |
| 79 |
:class: info |
| 80 |
|
| 81 |
These :term:`parameters <parameter>` will be parsed from the function signature and |
| 82 |
used to generate an internal data model. This model in turn will be used to validate |
| 83 |
the parameters and generate the OpenAPI schema |
| 84 |
|
| 85 |
|
| 86 |
.. seealso:: |
| 87 |
:doc:`/topics/explicit_declarations` |
| 88 |
|
| 89 |
|
| 90 |
Optional, required and nullable |
| 91 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 92 |
|
| 93 |
Just like function parameters in Python, request parameters can be required, optional or |
| 94 |
have a default value. |
| 95 |
|
| 96 |
- Parameters declared without any default are required |
| 97 |
- Parameters declared with a default are optional |
| 98 |
- Parameters declared with ``| None`` are *nullable*, i.e. the may take a ``None`` |
| 99 |
value; they are still required, unless they are given a default value |
| 100 |
|
| 101 |
Defaults work exactly like defaults in regular function parameters: If the value is |
| 102 |
missing from the request, the handler is called with the default: |
| 103 |
|
| 104 |
.. literalinclude:: /examples/parameters/query_params_default.py |
| 105 |
:language: python |
| 106 |
:caption: Defining a default value for a query parameter |
| 107 |
|
| 108 |
Marking a parameter optional means the type itself permits :obj:`None`: |
| 109 |
|
| 110 |
.. literalinclude:: /examples/parameters/query_params_optional.py |
| 111 |
:language: python |
| 112 |
:caption: Defining an optional query parameter |
| 113 |
|
| 114 |
|
| 115 |
.. important:: |
| 116 |
Path parameters are always required because they are part of the URL itself. You can |
| 117 |
only get a "missing" path parameter when the same handler is registered against |
| 118 |
:ref:`multiple paths <usage/routing/parameters:path parameters>` |
| 119 |
(e.g. ``["/items", "/items/{id:int}"]``), in which case the handler-side default |
| 120 |
fills in for the path without the slot. |
| 121 |
|
| 122 |
|
| 123 |
Parameter types |
| 124 |
--------------- |
| 125 |
|
| 126 |
Path parameters |
| 127 |
~~~~~~~~~~~~~~~ |
| 128 |
|
| 129 |
Path :term:`parameters <parameter>` are declared as part of the ``path`` component of |
| 130 |
the URL using the syntax ``{param_name:param_type}``. The handler function receives the |
| 131 |
value via a parameter of the same name, declared with :data:`~.params.FromPath`: |
| 132 |
|
| 133 |
.. literalinclude:: /examples/parameters/path_parameters_1.py |
| 134 |
:language: python |
| 135 |
:caption: Defining a path parameter in a route handler |
| 136 |
|
| 137 |
There are two components to declaring a path parameter: |
| 138 |
|
| 139 |
1. In the :class:`@get() <.handlers.get>` :term:`decorator`, the path component |
| 140 |
declares both the parameter's name (``user_id``) and type (:class:`int`) |
| 141 |
2. In the handler signature, ``user_id`` is declared as |
| 142 |
:data:`FromPath[int] <.params.FromPath>`, which tells Litestar to inject the matching |
| 143 |
path value |
| 144 |
|
| 145 |
Two characteristics are unique to path parameters: |
| 146 |
|
| 147 |
- The URL slot defines the structurally required type via the ``:type`` suffix (see |
| 148 |
:ref:`usage/routing/parameters:supported path parameter types` below). Litestar |
| 149 |
coerces the captured string into this type before passing it to the handler, and the |
| 150 |
handler-side type annotation can request a further coercion |
| 151 |
(see :ref:`usage/routing/parameters:type coercion`). |
| 152 |
- Path parameters cannot be declared on application |
| 153 |
:ref:`layers <usage/applications:layered architecture>` |
| 154 |
|
| 155 |
.. tip:: |
| 156 |
You only need to declare the path :term:`parameter` in the function signature if the |
| 157 |
handler actually uses it. If the path parameter is part of the path but the function |
| 158 |
does not consume it, you can omit it from the signature; it will still be validated |
| 159 |
and added to the OpenAPI schema. |
| 160 |
|
| 161 |
|
| 162 |
Supported path parameter types |
| 163 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 164 |
|
| 165 |
The following types are supported in the ``{name:type}`` slot: |
| 166 |
|
| 167 |
* ``date``: Accepts date strings and time stamps. |
| 168 |
* ``datetime``: Accepts date-time strings and time stamps. |
| 169 |
* ``decimal``: Accepts decimal values and floats. |
| 170 |
* :class:`float`: Accepts ints and floats. |
| 171 |
* :class:`int`: Accepts ints and floats. |
| 172 |
* :class:`path`: Accepts valid POSIX paths. |
| 173 |
* :class:`str`: Accepts all string values. |
| 174 |
* ``time``: Accepts time strings with optional timezone compatible with standard (Pydantic/Msgspec) datetime formats. |
| 175 |
* ``timedelta``: Accepts duration strings compatible with the standard (Pydantic/Msgspec) timedelta formats. |
| 176 |
* ``uuid``: Accepts all uuid values. |
| 177 |
|
| 178 |
Query parameters |
| 179 |
~~~~~~~~~~~~~~~~ |
| 180 |
|
| 181 |
Query :term:`parameters <parameter>` are declared as :term:`parameters <argument>` on |
| 182 |
the handler function, typed with :data:`~.params.FromQuery` or |
| 183 |
``Annotated[<type>, QueryParameter()]``. |
| 184 |
|
| 185 |
.. literalinclude:: /examples/parameters/query_params.py |
| 186 |
:language: python |
| 187 |
:caption: Defining a query parameter in a route handler |
| 188 |
|
| 189 |
|
| 190 |
Header parameters |
| 191 |
~~~~~~~~~~~~~~~~~ |
| 192 |
|
| 193 |
Header :term:`parameters <parameter>` are declared with :data:`~.params.FromHeader` or |
| 194 |
``Annotated[<type>, HeaderParameter()]``. The handler-side parameter name is used as the |
| 195 |
header name by default; HTTP headers are matched case-insensitively, so |
| 196 |
``token: FromHeader[str]`` matches both ``Token`` and ``token`` on the wire. |
| 197 |
|
| 198 |
In practice, most headers you care about have names that are not valid Python |
| 199 |
identifiers (e.g. ``X-API-KEY``, ``Content-Type``). In those cases, switch to |
| 200 |
:class:`~typing.Annotated` and set ``name=`` on :class:`~.params.HeaderParameter`: |
| 201 |
|
| 202 |
.. code-block:: python |
| 203 |
|
| 204 |
from typing_extensions import Annotated |
| 205 |
|
| 206 |
from litestar.params import HeaderParameter |
| 207 |
|
| 208 |
|
| 209 |
async def handler(token: Annotated[str, HeaderParameter(name="X-API-KEY")]) -> None: ... |
| 210 |
|
| 211 |
Cookie parameters |
| 212 |
~~~~~~~~~~~~~~~~~ |
| 213 |
|
| 214 |
Cookie :term:`parameters <parameter>` are declared with |
| 215 |
:data:`~.params.FromCookie` or ``Annotated[<type>, CookieParameter()]``. The handler-side |
| 216 |
parameter name is used as the cookie name by default: |
| 217 |
|
| 218 |
.. code-block:: python |
| 219 |
|
| 220 |
from typing_extensions import Annotated |
| 221 |
|
| 222 |
from litestar.params import CookieParameter |
| 223 |
|
| 224 |
|
| 225 |
async def handler(session: Annotated[str, CookieParameter(name="session-id")]) -> None: ... |
| 226 |
|
| 227 |
A combined example showing both header and cookie parameters alongside a path parameter: |
| 228 |
|
| 229 |
.. literalinclude:: /examples/parameters/header_and_cookie_parameters.py |
| 230 |
:language: python |
| 231 |
:caption: Defining header and cookie parameters |
| 232 |
|
| 233 |
|
| 234 |
Type coercion |
| 235 |
------------- |
| 236 |
|
| 237 |
Every parameter starts life on the wire as a string (or for path parameters, a string captured by the URL slot). |
| 238 |
Litestar coerces that raw value into the inner type of the marker (``FromQuery[int]``, ``FromHeader[float]``, |
| 239 |
``FromPath[datetime]``, …) before passing it to the handler: |
| 240 |
|
| 241 |
.. literalinclude:: /examples/parameters/query_params_types.py |
| 242 |
:language: python |
| 243 |
:caption: Coercing query parameters into different types |
| 244 |
|
| 245 |
Path parameters additionally support coercion via the path-slot type itself. The handler-side type does not need to |
| 246 |
match the slot type one-to-one — if the slot captures an :class:`int` and the handler asks for a |
| 247 |
:class:`~datetime.datetime`, Litestar applies the second conversion: |
| 248 |
|
| 249 |
.. literalinclude:: /examples/parameters/path_parameters_2.py |
| 250 |
:language: python |
| 251 |
:caption: Coercing a path parameter into a different type |
| 252 |
|
| 253 |
The same conversion rules apply to header and cookie parameters: ``FromHeader[int]`` will parse the header value as |
| 254 |
an integer, ``FromCookie[datetime]`` will parse the cookie as a datetime, and so on. |
| 255 |
|
| 256 |
|
| 257 |
Aliasing |
| 258 |
-------- |
| 259 |
|
| 260 |
By default, the name of the function parameter is used to retrieve the parameter data |
| 261 |
from the request. To decouple the two, for example to receive ``camelCase`` query keys |
| 262 |
while keeping ``snake_case`` Python parameter names, or to declare an ``X-``-prefixed |
| 263 |
header, pass ``name="..."`` to the matching specifier class: |
| 264 |
|
| 265 |
.. literalinclude:: /examples/parameters/query_params_remap.py |
| 266 |
:language: python |
| 267 |
:caption: Remapping a query parameter to a different URL name |
| 268 |
|
| 269 |
A request to ``http://127.0.0.1:8000?camelCase=foo`` will be received as |
| 270 |
``snake_case="foo"`` inside the handler. |
| 271 |
|
| 272 |
The same pattern applies to |
| 273 |
:class:`~.params.HeaderParameter`,:class:`~.params.CookieParameter` and |
| 274 |
:class:`~.params.PathParameter`. |
| 275 |
|
| 276 |
|
| 277 |
Validation constraints |
| 278 |
---------------------- |
| 279 |
|
| 280 |
All parameters can be given certain validation constraints, that will be validated when |
| 281 |
a request is received, and represented in the OpenAPI schema. |
| 282 |
|
| 283 |
Currently supported constraints are: ``gt``, ``ge``, ``lt``, ``le``, ``multiple_of``, |
| 284 |
``min_length``, ``max_length``, ``min_items``, ``max_items``, and ``pattern``. A |
| 285 |
value that does not satisfy the constraint raises |
| 286 |
:exc:`~.exceptions.http_exceptions.ValidationException`: |
| 287 |
|
| 288 |
.. literalinclude:: /examples/parameters/query_params_constraints.py |
| 289 |
:language: python |
| 290 |
:caption: Constraining a query parameter to integers larger than 5 |
| 291 |
|
| 292 |
|
| 293 |
OpenAPI metadata |
| 294 |
---------------- |
| 295 |
|
| 296 |
Parameters can extend or alter their OpenAPI schema, e.g. to customize their title, add |
| 297 |
a description or examples: |
| 298 |
|
| 299 |
.. literalinclude:: /examples/parameters/path_parameters_3.py |
| 300 |
:language: python |
| 301 |
:caption: Adding OpenAPI metadata to a path parameter |
| 302 |
|
| 303 |
|
| 304 |
Customizing enum schemas |
| 305 |
------------------------ |
| 306 |
|
| 307 |
By default, the OpenAPI schema generated for an enum-typed parameter uses the enum's |
| 308 |
docstring for the description section of the schema. Overriding the description via |
| 309 |
:attr:`~.params.KwargDefinition.description` would change it for every parameter sharing |
| 310 |
that enum, because only one schema is generated per enum. To get distinct descriptions, |
| 311 |
also pass :attr:`~.params.KwargDefinition.schema_component_key` so a separate schema |
| 312 |
component is generated per parameter: |
| 313 |
|
| 314 |
.. literalinclude:: /examples/parameters/query_params_enum.py |
| 315 |
:language: python |
| 316 |
:caption: Distinct OpenAPI components for parameters sharing the same enum type |
| 317 |
|
| 318 |
In the above example, the schema for ``q1`` references a "q1" schema component with |
| 319 |
description "This is q1"; the schema for ``q2`` references the shared "MyEnum" component |
| 320 |
with description "My enum accepts two values"; and the schema for ``q3`` references a |
| 321 |
"q3" component with description "This is q3". |
| 322 |
|
| 323 |
Without the :attr:`~.params.KwargDefinition.schema_component_key` arguments on |
| 324 |
``q1`` and ``q3``, all three would share the same "MyEnum" component with description |
| 325 |
"This is q1" — whichever description was processed first wins. |
| 326 |
|
| 327 |
|
| 328 |
Layered Parameters |
| 329 |
------------------ |
| 330 |
|
| 331 |
As part of Litestar's :ref:`layered architecture <usage/applications:layered architecture>`, you can declare |
| 332 |
:term:`parameters <parameter>` not only on individual route handler functions, but also on other layers of the |
| 333 |
application: |
| 334 |
|
| 335 |
.. literalinclude:: /examples/parameters/layered_parameters.py |
| 336 |
:language: python |
| 337 |
:caption: Declaring parameters on different layers of the application |
| 338 |
|
| 339 |
In the above we declare :term:`parameters <parameter>` on the :class:`Litestar app <.app.Litestar>`, |
| 340 |
:class:`router <.router.Router>`, and :class:`controller <.controller.Controller>` layers in addition to those |
| 341 |
declared in the route handler. Examine these more closely: |
| 342 |
|
| 343 |
* ``app_param`` is a cookie parameter with the key ``special-cookie``, declared via |
| 344 |
:class:`~.params.CookieParameter` on the :class:`Litestar app <.app.Litestar>` with ``annotation=str``. |
| 345 |
``required=False`` makes it optional; without that argument it would be required by default. |
| 346 |
|
| 347 |
Because the route handler function does not declare ``app_param`` at all, the parameter is still extracted and |
| 348 |
validated at the application level even though the handler never sees it. |
| 349 |
|
| 350 |
* ``router_param`` is a header parameter with the key ``MyHeader``, declared via :class:`~.params.HeaderParameter` |
| 351 |
on the router. It is declared ``required=False`` on the router, so it does not fail validation if absent — unless |
| 352 |
the handler explicitly opts in by re-declaring it (as this one does). |
| 353 |
|
| 354 |
The handler types it as :class:`FromHeader[str] <.params.FromHeader>` (rather than ``str | None``), making it |
| 355 |
required at the handler level. If a value *is* provided, it is also tested against the router-declared regex. |
| 356 |
|
| 357 |
* ``controller_param`` is a query parameter with the key ``controller_param``, declared via |
| 358 |
:class:`~.params.QueryParameter` on the controller with ``lt=100`` (value must be less than 100). The handler |
| 359 |
redeclares it with ``Annotated[int, QueryParameter(lt=50)]``, tightening the constraint to less than 50 for this |
| 360 |
particular route. |
| 361 |
|
| 362 |
* ``local_param`` is a route-handler-local :ref:`query parameter <usage/routing/parameters:query parameters>` |
| 363 |
(``FromQuery[str]``), and ``path_param`` is a :ref:`path parameter <usage/routing/parameters:path parameters>` |
| 364 |
(``FromPath[int]``). |
| 365 |
|
| 366 |
|
| 367 |
.. _deprecated-parameter-styles: |
| 368 |
|
| 369 |
Deprecated declaration styles |
| 370 |
----------------------------- |
| 371 |
|
| 372 |
Earlier 2.x releases accepted several other ways of declaring handler parameters. These continue to work for the |
| 373 |
remainder of the 2.x line, but they now emit a :class:`~.exceptions.LitestarDeprecationWarning` and will be removed |
| 374 |
in 3.0. |
| 375 |
|
| 376 |
.. list-table:: |
| 377 |
:header-rows: 1 |
| 378 |
:widths: 45 55 |
| 379 |
|
| 380 |
* - Deprecated |
| 381 |
- Use instead |
| 382 |
* - ``def h(name: str)`` *(implicit query parameter)* |
| 383 |
- ``def h(name: FromQuery[str])`` |
| 384 |
* - ``def h(user_id: int)`` *(implicit path parameter)* |
| 385 |
- ``def h(user_id: FromPath[int])`` |
| 386 |
* - ``Annotated[str, Parameter(query="alias")]`` |
| 387 |
- ``Annotated[str, QueryParameter(name="alias")]`` |
| 388 |
* - ``Annotated[str, Parameter(header="X-API-KEY")]`` |
| 389 |
- ``Annotated[str, HeaderParameter(name="X-API-KEY")]`` |
| 390 |
* - ``Annotated[str, Parameter(cookie="session")]`` |
| 391 |
- ``Annotated[str, CookieParameter(name="session")]`` |
| 392 |
* - ``name: str = Parameter(...)`` *(default-value style)* |
| 393 |
- ``name: Annotated[str, QueryParameter(...)]`` |
| 394 |
|
| 395 |
The :func:`~.params.Parameter` function itself is **not** removed and can still be used to attach pure metadata |
| 396 |
(``description``, ``gt``, etc.) when wrapped in :class:`~typing.Annotated`. Only its ``header``, ``cookie``, and |
| 397 |
``query`` keyword arguments are deprecated — passing any of those emits a :exc:`DeprecationWarning` independently of |
| 398 |
the handler-level warning. |