Debian Codegraph @

docs/tutorials/todo-app/2-interacting-with-the-list.rst

raw
1 Making the list interactive
2 ============================
3
4 So far, our TODO list application is not very useful, since it's static. You can't update items,
5 nor add or remove them.
6
7 Receiving incoming data
8 -----------------------
9
10 Let's start by implementing a route handler that handles the creation of new items.
11 In the previous step you used the ``get`` decorator, which responds to the ``GET``
12 HTTP method. In this case we want to react to ``POST`` requests, so we are going to use
13 the corresponding ``post`` decorator.
14
15 .. literalinclude:: /examples/todo_app/create/dict.py
16 :language: python
17 :linenos:
18
19 Request data can be received via the ``data`` keyword. Litestar will recognize this, and
20 supply the data being sent with the request via this parameter. As with the query
21 parameters in the previous chapter, we use the type annotations to configure what type
22 of data we expect to receive, and set up validation. In this case, Litestar will expect
23 request data in the form of JSON and use the type annotation we gave it to convert it
24 into the correct format.
25
26 .. seealso::
27
28 * :doc:`/usage/requests`
29
30
31 Using the interactive documentation to test a route
32 ++++++++++++++++++++++++++++++++++++++++++++++++++++
33
34 Since our example now uses the ``POST`` HTTP method, you can no longer simply visit the
35 URL in our browser and get a response. Instead, you can use the interactive
36 documentation to send a ``POST`` request. Because of the OpenAPI schema generated by
37 Litestar, Swagger will know exactly what kind of data to send. In this example, it will
38 send a simple JSON object.
39
40 .. figure:: images/swagger-post-dict-response.png
41
42 Sending a sample request to our ``add_item`` route reveals a successful response
43
44
45 Improving the example with dataclasses
46 ++++++++++++++++++++++++++++++++++++++
47
48 As in the previous chapter, this too can be improved by using
49 :doc:`dataclasses <python:library/dataclasses>` instead of plain dicts.
50
51 .. literalinclude:: /examples/todo_app/create/dataclass.py
52 :language: python
53 :linenos:
54
55
56 This is not only easier on the eyes and adds more structure to the code, but also gives
57 better interactive documentation; it will now present us with the field names and
58 default values for the dataclass we have defined:
59
60 .. figure:: images/swagger-dict-vs-dataclass.png
61
62 Documentation for the ``add_item`` route with ``data`` typed as a ``dict`` vs
63 ``dataclass``
64
65 Using a dataclass also gives you better validation: omitting a key such as ``title``
66 will result in a useful error response:
67
68
69 .. figure:: images/swagger-dataclass-bad-body.png
70
71 Sending a request without a ``title`` key fails
72
73
74 Create dynamic routes using path parameters
75 -------------------------------------------
76
77 The next task on the list is updating an item's status. For this, a way to refer to a
78 specific item on the list is needed. This could be done using query parameters, but
79 there's an easier, and more semantically coherent way of expressing this: path
80 parameters.
81
82 .. code-block:: python
83
84 @get("/{name:str}")
85 async def greeter(name: FromPath[str]) -> str:
86 return "Hello, " + name
87
88
89 So far all the paths in your application are static, meaning they are expressed by a
90 constant string which does not change. In fact, the only path used so far is ``/``.
91
92 Path parameters allow you to construct dynamic paths and later refer to the dynamically
93 captured parts. This may sound complex at first, but it's actually quite simple; you can
94 think of it as a regular expression that's being used on the requested path.
95
96 Path parameters consist of two parts: an expression inside the route's path describing
97 the slot (e.g. ``{name:str}``), and a matching function parameter on the route handler
98 annotated with :data:`~.params.FromPath` (e.g. ``name: FromPath[str]``), which will
99 receive the captured value.
100
101 In the above example, a path parameter ``name:str`` is declared, which means that now,
102 a request to the path ``/john`` can be made, and the ``greeter`` function will be called
103 as ``greeter(name="john")``, similar to how query parameters are injected.
104
105
106 .. tip::
107 Just like query parameters, path parameters can convert and validate their values as
108 well. This is configured using the ``:type`` colon annotation in the URL pattern.
109 For example, ``value:str`` will receive values as a string, while ``value:int`` will
110 try to convert it into an integer.
111
112 A full list of supported types can be found here:
113 :ref:`usage/routing/parameters:supported path parameter types`
114
115
116 By using this pattern and combining it with those from the earlier section about
117 receiving data you can now set up a route handler that takes in the title of a
118 TODO item, an updated item in form of a dataclass instance, and updates the item in the
119 list.
120
121
122 .. literalinclude:: /examples/todo_app/update.py
123 :language: python
124
125
126 .. seealso::
127
128 * :ref:`usage/routing/parameters:path parameters`