| 1 |
.. _api_tutorial: |
| 2 |
|
| 3 |
Tutorial: Building a RESTful API |
| 4 |
================================ |
| 5 |
|
| 6 |
In this tutorial we will build a RESTful JSON API. It will |
| 7 |
automatically generate OpenAPI documentation and validate request and |
| 8 |
response data. |
| 9 |
|
| 10 |
This tutorial is meant to serve as an introduction to building APIs in |
| 11 |
Quart. If you want to skip to the end the code is on `Github |
| 12 |
<https://github.com/pallets/quart/tree/main/examples/api>`_. |
| 13 |
|
| 14 |
1: Creating the project |
| 15 |
----------------------- |
| 16 |
|
| 17 |
We need to create a project for our api server, I like to use |
| 18 |
`Poetry <https://python-poetry.org>`_ to do this. Poetry is installed |
| 19 |
via pip (or via `Brew <https://brew.sh/>`_): |
| 20 |
|
| 21 |
.. code-block:: console |
| 22 |
|
| 23 |
pip install poetry |
| 24 |
|
| 25 |
We can then use Poetry to create a new api project: |
| 26 |
|
| 27 |
.. code-block:: console |
| 28 |
|
| 29 |
poetry new --src api |
| 30 |
|
| 31 |
Our project can now be developed in the *api* directory, and all |
| 32 |
subsequent commands should be in run the *api* directory. |
| 33 |
|
| 34 |
2: Adding the dependencies |
| 35 |
-------------------------- |
| 36 |
|
| 37 |
To start we only need Quart to build the api server, which we can |
| 38 |
install as a dependency of the project by running the following: |
| 39 |
|
| 40 |
.. code-block:: console |
| 41 |
|
| 42 |
poetry add quart |
| 43 |
|
| 44 |
Poetry will ensure that this dependency is present and the paths are |
| 45 |
correct by running: |
| 46 |
|
| 47 |
.. code-block:: console |
| 48 |
|
| 49 |
poetry install |
| 50 |
|
| 51 |
3: Creating the app |
| 52 |
------------------- |
| 53 |
|
| 54 |
We need a Quart app to be our web server, which is created by the |
| 55 |
following addition to *src/api/__init__.py*: |
| 56 |
|
| 57 |
.. code-block:: python |
| 58 |
:caption: src/api/__init__.py |
| 59 |
|
| 60 |
from quart import Quart |
| 61 |
|
| 62 |
app = Quart(__name__) |
| 63 |
|
| 64 |
def run() -> None: |
| 65 |
app.run() |
| 66 |
|
| 67 |
To make the app easy to run we can call the run method from a poetry |
| 68 |
script, by adding the following to *pyproject.toml*: |
| 69 |
|
| 70 |
.. code-block:: toml |
| 71 |
:caption: pyproject.toml |
| 72 |
|
| 73 |
[tool.poetry.scripts] |
| 74 |
start = "api:run" |
| 75 |
|
| 76 |
Which allows the following command to start the app: |
| 77 |
|
| 78 |
.. code-block:: console |
| 79 |
|
| 80 |
poetry run start |
| 81 |
|
| 82 |
4: Adding simple JSON API |
| 83 |
------------------------- |
| 84 |
|
| 85 |
To start we can add a route that reads the JSON sent to it and echos |
| 86 |
it back in a response by adding the following to |
| 87 |
*src/api/__init__.py*: |
| 88 |
|
| 89 |
.. code-block:: python |
| 90 |
:caption: src/api/__init__.py |
| 91 |
|
| 92 |
from quart import request |
| 93 |
|
| 94 |
@app.post("/echo") |
| 95 |
async def echo(): |
| 96 |
data = await request.get_json() |
| 97 |
return {"input": data, "extra": True} |
| 98 |
|
| 99 |
We can test this using curl: |
| 100 |
|
| 101 |
.. code-block:: console |
| 102 |
|
| 103 |
curl --json '{"hello": "world"}' http://localhost:5000/echo |
| 104 |
|
| 105 |
Which gives the following result: |
| 106 |
|
| 107 |
.. code-block:: console |
| 108 |
|
| 109 |
{"extra":true,"input":{"hello":"world"}} |
| 110 |
|
| 111 |
To be explicit any dictionary returned from a route handler will be |
| 112 |
returned in the response as JSON with the correct Content-Type |
| 113 |
header. If you want to return a top level array as the JSON response |
| 114 |
the ``jsonify`` function can be used as so: |
| 115 |
|
| 116 |
.. code-block:: python |
| 117 |
|
| 118 |
from quart import jsonify |
| 119 |
|
| 120 |
@app.get("/example") |
| 121 |
async def example(): |
| 122 |
return jsonify(["a", "b"]) |
| 123 |
|
| 124 |
5: Adding schemas |
| 125 |
----------------- |
| 126 |
|
| 127 |
Using the `Quart-Schema <https://github.com/pgjones/quart-schema>`_ |
| 128 |
extension we can define schemas to validate the request and response |
| 129 |
data. In addition Quart-Schema will then utilise these schemas to |
| 130 |
auto-generate OpenAPI (Swagger) documentation. To start we need to |
| 131 |
install quart-schema: |
| 132 |
|
| 133 |
.. code-block:: console |
| 134 |
|
| 135 |
poetry add quart-schema |
| 136 |
|
| 137 |
We can then add schemas for a Todo object by adding the following to |
| 138 |
*src/api/__init__.py*: |
| 139 |
|
| 140 |
.. code-block:: python |
| 141 |
:caption: src/api/__init__.py |
| 142 |
|
| 143 |
from dataclasses import dataclass |
| 144 |
from datetime import datetime |
| 145 |
|
| 146 |
from quart import Quart |
| 147 |
from quart_schema import QuartSchema, validate_request, validate_response |
| 148 |
|
| 149 |
app = Quart(__name__) |
| 150 |
|
| 151 |
QuartSchema(app) |
| 152 |
|
| 153 |
@dataclass |
| 154 |
class TodoIn: |
| 155 |
task: str |
| 156 |
due: datetime | None |
| 157 |
|
| 158 |
@dataclass |
| 159 |
class Todo(TodoIn): |
| 160 |
id: int |
| 161 |
|
| 162 |
@app.post("/todos/") |
| 163 |
@validate_request(TodoIn) |
| 164 |
@validate_response(Todo) |
| 165 |
async def create_todo(data: TodoIn) -> Todo: |
| 166 |
return Todo(id=1, task=data.task, due=data.due) |
| 167 |
|
| 168 |
The OpenAPI schema is then available at |
| 169 |
http://localhost:5000/openapi.json and the docs themselves at |
| 170 |
http://localhost:5000/docs. |
| 171 |
|
| 172 |
6: Testing |
| 173 |
---------- |
| 174 |
|
| 175 |
To test our app we need to check that the echo route returns the JSON |
| 176 |
data sent to it and the create_todo route creates a todo. This is done |
| 177 |
by adding the following to *tests/test_api.py*: |
| 178 |
|
| 179 |
.. code-block:: python |
| 180 |
:caption: tests/test_api.py |
| 181 |
|
| 182 |
from api import app, TodoIn |
| 183 |
|
| 184 |
async def test_echo() -> None: |
| 185 |
test_client = app.test_client() |
| 186 |
response = await test_client.post("/echo", json={"a": "b"}) |
| 187 |
data = await response.get_json() |
| 188 |
assert data == {"extra":True,"input":{"a":"b"}} |
| 189 |
|
| 190 |
async def test_create_todo() -> None: |
| 191 |
test_client = app.test_client() |
| 192 |
response = await test_client.post("/todos/", json=TodoIn(task="Abc", due=None)) |
| 193 |
data = await response.get_json() |
| 194 |
assert data == {"id": 1, "task": "Abc", "due": None} |
| 195 |
|
| 196 |
As the test is an async function we need to install `pytest-asyncio |
| 197 |
<https://github.com/pytest-dev/pytest-asyncio>`_ by running the |
| 198 |
following: |
| 199 |
|
| 200 |
.. code-block:: console |
| 201 |
|
| 202 |
poetry add --dev pytest-asyncio |
| 203 |
|
| 204 |
Once installed it needs to be configured by adding the following to |
| 205 |
*pyproject.toml*: |
| 206 |
|
| 207 |
.. code-block:: toml |
| 208 |
|
| 209 |
[tool.pytest.ini_options] |
| 210 |
asyncio_mode = "auto" |
| 211 |
|
| 212 |
Finally we can run the tests via this command: |
| 213 |
|
| 214 |
.. code-block:: console |
| 215 |
|
| 216 |
poetry run pytest tests/ |
| 217 |
|
| 218 |
If you are running this in the Quart example folder you'll need to add |
| 219 |
a ``-c pyproject.toml`` option to prevent pytest from using the Quart |
| 220 |
pytest configuration. |
| 221 |
|
| 222 |
7: Summary |
| 223 |
---------- |
| 224 |
|
| 225 |
We've built a RESTful API server with autogenerated OpenAPI docs and |
| 226 |
validation. You can now take this code and build any API. |