| 1 |
Accessing the list |
| 2 |
==================== |
| 3 |
|
| 4 |
Intro |
| 5 |
----- |
| 6 |
|
| 7 |
The first thing you'll be setting up for our app is a route handler that returns a |
| 8 |
single TODO list. A TODO list in this case will be a list of dictionaries representing |
| 9 |
the items on that TODO list. |
| 10 |
|
| 11 |
.. literalinclude:: /examples/todo_app/get_list/dict.py |
| 12 |
:language: python |
| 13 |
:caption: ``app.py`` |
| 14 |
:linenos: |
| 15 |
|
| 16 |
|
| 17 |
If you run the app and visit http://127.0.0.1:8000/ in your browser you'll see the |
| 18 |
following output: |
| 19 |
|
| 20 |
.. figure:: images/get_todo_list.png |
| 21 |
|
| 22 |
Suddenly, JSON |
| 23 |
|
| 24 |
|
| 25 |
Because the ``get_list`` function has been annotated with |
| 26 |
``List[Dict[str, Union[str, bool]]]``, Litestar infers that you want the data returned |
| 27 |
from it to be serialized as JSON: |
| 28 |
|
| 29 |
.. literalinclude:: /examples/todo_app/get_list/dict.py |
| 30 |
:language: python |
| 31 |
:lineno-start: 13 |
| 32 |
:lines: 13 |
| 33 |
|
| 34 |
|
| 35 |
Cleaning up the example with dataclasses |
| 36 |
++++++++++++++++++++++++++++++++++++++++ |
| 37 |
|
| 38 |
To make your life a little easier, you can transform this example by using :py:mod:`dataclasses` instead of plain dictionaries: |
| 39 |
|
| 40 |
.. tip:: For an in-depth explanation of dataclasses, you can read this excellent Real Python |
| 41 |
article: `Data Classes in Python 3.7+ <https://realpython.com/python-data-classes/>`_ |
| 42 |
|
| 43 |
.. literalinclude:: /examples/todo_app/get_list/dataclass.py |
| 44 |
:caption: ``app.py`` |
| 45 |
:language: python |
| 46 |
:linenos: |
| 47 |
|
| 48 |
|
| 49 |
This looks a lot cleaner and has the added benefit of being able to work with |
| 50 |
dataclasses instead of plain dictionaries. The result will still be the same: Litestar |
| 51 |
knows how to turn these dataclasses into JSON and will do so for you automatically. |
| 52 |
|
| 53 |
.. tip:: |
| 54 |
In addition to dataclasses, Litestar supports many more types such as |
| 55 |
:class:`TypedDict <typing.TypedDict>`, :class:`NamedTuple <typing.NamedTuple>`, |
| 56 |
`Pydantic models <https://docs.pydantic.dev/usage/models/>`_, or |
| 57 |
`attrs classes <https://www.attrs.org/en/stable/>`_. |
| 58 |
|
| 59 |
|
| 60 |
Filtering the list using query parameters |
| 61 |
----------------------------------------- |
| 62 |
|
| 63 |
Currently ``get_list`` will always return all items on the list, but what if you |
| 64 |
are interested in only those items with a specific status, for example all items that |
| 65 |
are not yet marked as *done*? |
| 66 |
|
| 67 |
For this you can employ query parameters; to define a query parameter, add a parameter |
| 68 |
to the handler function and annotate it with :data:`~.params.FromQuery`, parameterised |
| 69 |
by the type you expect the value to have. When a request is being made, the query |
| 70 |
parameter will be extracted from the URL, converted to the declared type, and passed to |
| 71 |
the function parameter of the same name. |
| 72 |
|
| 73 |
.. literalinclude:: /examples/todo_app/get_list/query_param.py |
| 74 |
:caption: ``app.py`` |
| 75 |
:language: python |
| 76 |
:linenos: |
| 77 |
|
| 78 |
|
| 79 |
.. figure:: images/todos-done.png |
| 80 |
|
| 81 |
Visiting http://127.0.0.1:8000?done=1 will give you all the TODOs that have been |
| 82 |
marked as *done* |
| 83 |
|
| 84 |
|
| 85 |
.. figure:: images/todos-not-done.png |
| 86 |
|
| 87 |
while http://127.0.0.1:8000?done=0 will return only those not yet done |
| 88 |
|
| 89 |
|
| 90 |
At first glance this seems to work just fine, but you might be able to spot a problem: |
| 91 |
If you input anything other than ``?done=1``, it would still return items not yet marked |
| 92 |
as done. For example, ``?done=john`` gives the same result as ``?done=0``. |
| 93 |
|
| 94 |
An easy solution for this would be to simply check if the query parameter is either |
| 95 |
``1`` or ``0``, and return a response with an HTTP status code that indicates an |
| 96 |
error if it's something else: |
| 97 |
|
| 98 |
.. literalinclude:: /examples/todo_app/get_list/query_param_validate_manually.py |
| 99 |
:caption: ``app.py`` |
| 100 |
:language: python |
| 101 |
:linenos: |
| 102 |
|
| 103 |
If the query parameter equals ``1``, return all items that have ``done=True``: |
| 104 |
|
| 105 |
.. literalinclude:: /examples/todo_app/get_list/query_param_validate_manually.py |
| 106 |
:language: python |
| 107 |
:caption: ``app.py`` |
| 108 |
:lines: 24-25 |
| 109 |
:dedent: |
| 110 |
:linenos: |
| 111 |
:lineno-start: 24 |
| 112 |
|
| 113 |
|
| 114 |
If the query parameter equals ``0``, return all items that have ``done=False``: |
| 115 |
|
| 116 |
.. literalinclude:: /examples/todo_app/get_list/query_param_validate_manually.py |
| 117 |
:language: python |
| 118 |
:caption: ``app.py`` |
| 119 |
:lines: 26-27 |
| 120 |
:dedent: |
| 121 |
:linenos: |
| 122 |
:lineno-start: 26 |
| 123 |
|
| 124 |
Finally, if the query parameter has any other value, an :exc:`HTTPException` will be raised. |
| 125 |
Raising an ``HTTPException`` tells Litestar that something went wrong, and instead of |
| 126 |
returning a normal response, it will send a response with the HTTP status code given |
| 127 |
(``400`` in this case) and the error message supplied. |
| 128 |
|
| 129 |
.. literalinclude:: /examples/todo_app/get_list/query_param_validate_manually.py |
| 130 |
:language: python |
| 131 |
:caption: ``app.py`` |
| 132 |
:lines: 28 |
| 133 |
:dedent: |
| 134 |
:linenos: |
| 135 |
:lineno-start: 28 |
| 136 |
|
| 137 |
|
| 138 |
.. figure:: images/done-john.png |
| 139 |
|
| 140 |
Try to access http://127.0.0.1:8000?done=john now and you will get this error message |
| 141 |
|
| 142 |
|
| 143 |
Now we've got that out of the way, but your code has grown to be quite complex for such |
| 144 |
a simple task. You're probably thinking |
| 145 |
`"there must be a better way!" <https://www.youtube.com/watch?t=566&v=p33CVV29OG8>`_, |
| 146 |
and there is! Instead of doing these things manually, you can also just let Litestar |
| 147 |
handle them for you! |
| 148 |
|
| 149 |
|
| 150 |
Converting and validating query parameters |
| 151 |
++++++++++++++++++++++++++++++++++++++++++ |
| 152 |
|
| 153 |
As mentioned earlier, type annotations can be used for more than static type checking |
| 154 |
in Litestar; they can also define and configure behaviour. In this case, you can get |
| 155 |
Litestar to convert the query parameter to a boolean value, matching the values of the |
| 156 |
``TodoItem.done`` attribute, and in the same step validate it, returning error responses |
| 157 |
for you should the supplied value not be a valid boolean. |
| 158 |
|
| 159 |
.. literalinclude:: /examples/todo_app/get_list/query_param_validate.py |
| 160 |
:language: python |
| 161 |
:caption: ``app.py`` |
| 162 |
:linenos: |
| 163 |
|
| 164 |
|
| 165 |
.. figure:: images/done-john-2.png |
| 166 |
|
| 167 |
Browse to http://127.0.0.1:8000?done=john from our earlier example, and you will see it now |
| 168 |
results in this descriptive error message |
| 169 |
|
| 170 |
|
| 171 |
**What's happening here?** |
| 172 |
|
| 173 |
The parameter is now declared as ``done: FromQuery[bool]``. The ``bool`` inside the |
| 174 |
brackets tells Litestar to convert the incoming string into a :class:`bool` before |
| 175 |
passing it to the handler. Since ``john`` (arguably) is not a representation of a |
| 176 |
boolean value, it will return an error response instead. |
| 177 |
|
| 178 |
.. literalinclude:: /examples/todo_app/get_list/query_param_validate.py |
| 179 |
:language: python |
| 180 |
:caption: ``app.py`` |
| 181 |
:lines: 22 |
| 182 |
:linenos: |
| 183 |
:lineno-start: 22 |
| 184 |
|
| 185 |
.. tip:: |
| 186 |
It is important to note that this conversion is not the result of calling |
| 187 |
:class:`bool` on the raw value. ``bool("john")`` would be :obj:`True`, since Python |
| 188 |
considers all non-empty strings to be truthy. |
| 189 |
|
| 190 |
Litestar however supports customary boolean representation commonly used in the HTTP |
| 191 |
world; ``true`` and ``1`` are both converted to :obj:`True`, while ``false`` |
| 192 |
and ``0`` are converted to be :obj:`False`. |
| 193 |
|
| 194 |
|
| 195 |
If the conversion is successful however, ``done`` is now a :class:`bool` (extracted from the ``FromQuery[bool]`` |
| 196 |
declaration), which can then be compared against the ``TodoItem.done`` attribute: |
| 197 |
|
| 198 |
.. literalinclude:: /examples/todo_app/get_list/query_param_validate.py |
| 199 |
:language: python |
| 200 |
:caption: ``app.py`` |
| 201 |
:lines: 23 |
| 202 |
:dedent: |
| 203 |
:linenos: |
| 204 |
:lineno-start: 23 |
| 205 |
|
| 206 |
|
| 207 |
.. seealso:: |
| 208 |
|
| 209 |
* :ref:`Routing - Parameters - Type coercion <usage/routing/parameters:type coercion>` |
| 210 |
|
| 211 |
|
| 212 |
Making the query parameter optional |
| 213 |
+++++++++++++++++++++++++++++++++++ |
| 214 |
|
| 215 |
There is one problem left to solve though, and that is, what happens when you want to |
| 216 |
get **all** items, done or not, and omit the query parameter? |
| 217 |
|
| 218 |
.. figure:: images/missing-query.png |
| 219 |
|
| 220 |
Omitting the ``?done`` query parameter will result in an error |
| 221 |
|
| 222 |
Because the query parameter has been defined as ``done: FromQuery[bool]`` without giving |
| 223 |
it a default value, it will be treated as a required parameter - just like a regular |
| 224 |
function parameter. If instead you want this to be optional, a default value needs to |
| 225 |
be supplied (e.g. ``done: FromQuery[Optional[bool]] = None``). |
| 226 |
|
| 227 |
|
| 228 |
.. literalinclude:: /examples/todo_app/get_list/query_param_default.py |
| 229 |
:language: python |
| 230 |
:caption: ``app.py`` |
| 231 |
:linenos: |
| 232 |
|
| 233 |
|
| 234 |
.. figure:: images/get_todo_list.png |
| 235 |
|
| 236 |
Browsing to http://localhost:8000 once more, you will now see it does not return an error if the |
| 237 |
query parameter is omitted |
| 238 |
|
| 239 |
|
| 240 |
.. tip:: |
| 241 |
In this instance, the default has been set to :obj:`None`, since we don't want to do |
| 242 |
any filtering if no ``done`` status is specified. If instead you wanted to only |
| 243 |
display not-done items by default, you could set the value to :obj:`False` instead. |
| 244 |
|
| 245 |
|
| 246 |
.. seealso:: |
| 247 |
|
| 248 |
* :ref:`Routing - Parameters - Query Parameters <usage/routing/parameters:query parameters>` |
| 249 |
|
| 250 |
|
| 251 |
Interactive documentation |
| 252 |
-------------------------- |
| 253 |
|
| 254 |
So far we have explored our TODO application by navigating to it manually, but there is |
| 255 |
another way: Litestar comes with interactive API documentation, which is generated for |
| 256 |
you automatically. All you need to do is run your app (``litestar run``) and visit |
| 257 |
http://127.0.0.1:8000/schema/swagger |
| 258 |
|
| 259 |
.. figure:: images/swagger-get.png |
| 260 |
|
| 261 |
The route handler set up earlier will show up in the interactive documentation |
| 262 |
|
| 263 |
|
| 264 |
This documentation not only gives an overview of the API you have constructed, but also |
| 265 |
allows you to send requests to it. |
| 266 |
|
| 267 |
.. figure:: images/swagger-get-example-request.png |
| 268 |
|
| 269 |
Executing the same requests we did earlier |
| 270 |
|
| 271 |
|
| 272 |
.. note:: |
| 273 |
This is made possible by `Swagger <https://swagger.io/>`_ and |
| 274 |
`OpenAPI <https://www.openapis.org/>`_. Litestar generates an OpenAPI schema based |
| 275 |
on the route handlers, which can then be used by Swagger to set up the interactive |
| 276 |
documentation. |
| 277 |
|
| 278 |
.. tip:: |
| 279 |
In addition to Swagger, Litestar serves the documentation from the generated |
| 280 |
OpenAPI schema with `ReDoc <https://redocly.com/>`_ and |
| 281 |
`Stoplight Elements <https://stoplight.io/open-source/elements/>`_. You can browse |
| 282 |
to http://127.0.0.1:8000/schema/redoc and http://127.0.0.1:8000/schema/elements to |
| 283 |
view each, respectively. |