Please follow these instructions, fill every question, and do every step. 🙏
I'm asking this because answering questions and solving problems in GitHub issues is what consumes most of the time.
I end up not being able to add new features, fix bugs, review pull requests, etc. as fast as I wish because I have to spend too much time handling issues.
All that, on top of all the incredible help provided by a bunch of community members, the [FastAPI Experts](https://fastapi.tiangolo.com/fastapi-people/#experts), that give a lot of their time to come here and help others.
@ -18,7 +18,7 @@ body:
That's a lot of work they are doing, but if more FastAPI users came to help others like them just a little bit more, it would be much less effort for them (and you and me 😅).
By asking questions in a structured way (following this) it will be much easier to help you.
And there's a high chance that you will find the solution along the way and you won't even have to submit it and wait for an answer. 😎
As there are too many issues with questions, I'll have to close the incomplete ones. That will allow me (and others) to focus on helping people like you that follow the whole process and help us help you. 🤓
@ -50,7 +50,7 @@ body:
label:Commit to Help
description:|
After submitting this, I commit to one of:
*Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
*I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
Please follow these instructions, fill every question, and do every step. 🙏
I'm asking this because answering questions and solving problems in GitHub issues is what consumes most of the time.
I end up not being able to add new features, fix bugs, review pull requests, etc. as fast as I wish because I have to spend too much time handling issues.
All that, on top of all the incredible help provided by a bunch of community members, the [FastAPI Experts](https://fastapi.tiangolo.com/fastapi-people/#experts), that give a lot of their time to come here and help others.
@ -18,7 +18,7 @@ body:
That's a lot of work they are doing, but if more FastAPI users came to help others like them just a little bit more, it would be much less effort for them (and you and me 😅).
By asking questions in a structured way (following this) it will be much easier to help you.
And there's a high chance that you will find the solution along the way and you won't even have to submit it and wait for an answer. 😎
As there are too many issues with questions, I'll have to close the incomplete ones. That will allow me (and others) to focus on helping people like you that follow the whole process and help us help you. 🤓
@ -50,7 +50,7 @@ body:
label:Commit to Help
description:|
After submitting this, I commit to one of:
*Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
*I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
@ -32,7 +32,6 @@ FastAPI is a modern, fast (high-performance), web framework for building APIs wi
The key features are:
* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).
* **Fast to code**: Increase the speed to develop features by about 200% to 300%. *
* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *
* **Intuitive**: Great editor support. <abbrtitle="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging.
@ -47,15 +46,17 @@ The key features are:
<!-- sponsors -->
<ahref="https://bit.ly/2QSouzH"target="_blank"title="Jina: build neural search-as-a-service for any kind of data in just minutes."><imgsrc="https://fastapi.tiangolo.com/img/sponsors/jina.svg"></a>
<ahref="https://bit.ly/3dmXC5S"target="_blank"title="The data structure for unstructured multimodal data"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/docarray.svg"></a>
<ahref="https://bit.ly/3JJ7y5C"target="_blank"title="Build cross-modal and multimodal applications on the cloud"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/jina2.svg"></a>
<ahref="https://cryptapi.io/"target="_blank"title="CryptAPI: Your easy to use, secure and privacy oriented payment gateway."><imgsrc="https://fastapi.tiangolo.com/img/sponsors/cryptapi.svg"></a>
<ahref="https://www.dropbase.io/careers"target="_blank"title="Dropbase - seamlessly collect, clean, and centralize data."><imgsrc="https://fastapi.tiangolo.com/img/sponsors/dropbase.svg"></a>
<ahref="https://doist.com/careers/9B437B1615-wa-senior-backend-engineer-python"target="_blank"title="Help us migrate doist to FastAPI"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/doist.svg"></a>
<ahref="https://www.deta.sh/?ref=fastapi"target="_blank"title="The launchpad for all your (team's) ideas"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/deta.svg"></a>
<ahref="https://www.investsuite.com/jobs"target="_blank"title="Wealthtech jobs with FastAPI"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/investsuite.svg"></a>
<ahref="https://www.vim.so/?utm_source=FastAPI"target="_blank"title="We help you master vim with interactive exercises"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/vimso.png"></a>
<ahref="https://talkpython.fm/fastapi-sponsor"target="_blank"title="FastAPI video courses on demand from people you trust"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/talkpython.png"></a>
<ahref="https://training.talkpython.fm/fastapi-courses"target="_blank"title="FastAPI video courses on demand from people you trust"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/talkpython.png"></a>
<ahref="https://testdriven.io/courses/tdd-fastapi/"target="_blank"title="Learn to build high-quality web apps with best practices"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/testdriven.svg"></a>
<ahref="https://github.com/deepset-ai/haystack/"target="_blank"title="Build powerful search from composable, open source building blocks"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/haystack-fastapi.svg"></a>
<ahref="https://www.udemy.com/course/fastapi-rest/"target="_blank"title="Learn FastAPI by building a complete project. Extend your knowledge on advanced web development-AWS, Payments, Emails."><imgsrc="https://fastapi.tiangolo.com/img/sponsors/ines-course.jpg"></a>
<ahref="https://careers.budget-insight.com/"target="_blank"title="Budget Insight is hiring!"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/budget-insight.svg"></a>
Mit einer interaktiven API-Dokumentation und explorativen webbasierten Benutzerschnittstellen. Da FastAPI auf OpenAPI basiert, gibt es hierzu mehrere Optionen, wobei zwei standartmäßig vorhanden sind.
Mit einer interaktiven API-Dokumentation und explorativen webbasierten Benutzerschnittstellen. Da FastAPI auf OpenAPI basiert, gibt es hierzu mehrere Optionen, wobei zwei standardmäßig vorhanden sind.
* <ahref="https://github.com/swagger-api/swagger-ui"class="external-link"target="_blank"><strong>Swagger UI</strong></a>, bietet interaktive Exploration: testen und rufen Sie ihre API direkt vom Webbrowser auf.
@ -27,7 +27,7 @@ Mit einer interaktiven API-Dokumentation und explorativen webbasierten Benutzers
Alles basiert auf **Python 3.6 Typ**-Deklarationen (dank Pydantic). Es muss keine neue Syntax gelernt werden, nur standardisiertes modernes Python.
Wenn Sie eine kurze, zweiminütige, Auffrischung in der Benutzung von Python Typ-Deklarationen benötigen (auch wenn Sie FastAPI nicht nutzen), schauen Sie sich diese kurze Einführung an (Englisch): Python Types{.internal-link target=_blank}.
@ -97,9 +97,9 @@ Hierdurch werden Sie nie wieder einen falschen Schlüsselnamen benutzen und spar
### Kompakt
FastAPI nutzt für alles sensible **Standard-Einstellungen**, welche optional überall konfiguriert werden können. Alle Parameter können ganz genau an Ihre Bedürfnisse angepasst werden, sodass sie genau die API definieren können, die sie brachen.
FastAPI nutzt für alles sensible **Standard-Einstellungen**, welche optional überall konfiguriert werden können. Alle Parameter können ganz genau an Ihre Bedürfnisse angepasst werden, sodass sie genau die API definieren können, die sie brauchen.
Aber standartmäßig, **"funktioniert einfach"** alles.
Aber standardmäßig, **"funktioniert einfach"** alles.
### Validierung
@ -109,7 +109,7 @@ Aber standartmäßig, **"funktioniert einfach"** alles.
* Zeichenketten (`str`), mit definierter minimaler und maximaler Länge.
* Zahlen (`int`, `float`) mit minimaler und maximaler Größe, usw.
* Validierung für ungewögnliche Typen, wie:
* Validierung für ungewöhnliche Typen, wie:
* URL.
* Email.
* UUID.
@ -119,9 +119,9 @@ Die gesamte Validierung übernimmt das etablierte und robuste **Pydantic**.
### Sicherheit und Authentifizierung
Sicherheit und Authentifizierung integriert. Ohne einen Kompromiss aufgrund einer Datenbank oder den Datenentitäten.
Integrierte Sicherheit und Authentifizierung. Ohne Kompromisse bei Datenbanken oder Datenmodellen.
Unterstützt alle von OpenAPI definierten Sicherheitsschemata, hierzu gehören:
Unterstützt werden alle von OpenAPI definierten Sicherheitsschemata, hierzu gehören:
* HTTP Basis Authentifizierung.
* **OAuth2** (auch mit **JWT Zugriffstokens**). Schauen Sie sich hierzu dieses Tutorial an: [OAuth2 mit JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}.
@ -142,7 +142,7 @@ FastAPI enthält ein extrem einfaches, aber extrem mächtiges <abbr title='oft v
* **Automatische Umsetzung** durch FastAPI.
* Alle abhängigen Komponenten könnten Daten von Anfragen, **Erweiterungen der Pfadoperations-**Einschränkungen und der automatisierten Dokumentation benötigen.
* **Automatische Validierung** selbst für *Pfadoperationen*-Parameter, die in den Abhängigkeiten definiert wurden.
* **Keine Kompromisse** bei Datenbanken, Eingabemasken, usw. Sondern einfache Integration von allen.
### Unbegrenzte Erweiterungen
@ -159,13 +159,13 @@ Jede Integration wurde so entworfen, dass sie einfach zu nutzen ist (mit Abhäng
## Starlette's Merkmale
**FastAPI** ist vollkommen kompatibel (und basiert auf) <ahref="https://www.starlette.io/"class="external-link"target="_blank"><strong>Starlette</strong></a>. Das bedeutet, auch ihr eigner Starlett Quellcode funktioniert.
**FastAPI** ist vollkommen kompatibel (und basiert auf) <ahref="https://www.starlette.io/"class="external-link"target="_blank"><strong>Starlette</strong></a>. Das bedeutet, auch ihr eigener Starlette Quellcode funktioniert.
`FastAPI` ist eigentlich eine Unterklasse von `Starlette`. Wenn sie also bereits Starlette kennen oder benutzen, können Sie das meiste Ihres Wissen direkt anwenden.
`FastAPI` ist eigentlich eine Unterklasse von `Starlette`. Wenn Sie also bereits Starlette kennen oder benutzen, können Sie das meiste Ihres Wissens direkt anwenden.
Mit **FastAPI** bekommen Sie viele von **Starlette**'s Funktionen (da FastAPI nur Starlette auf Steroiden ist):
* Stark beeindruckende Performanz. Es ist <ahref="https://github.com/encode/starlette#performance"class="external-link"target="_blank">eines der schnellsten Python frameworks, auf Augenhöhe mit **NodeJS** und **Go**</a>.
* Stark beeindruckende Performanz. Es ist <ahref="https://github.com/encode/starlette#performance"class="external-link"target="_blank">eines der schnellsten Python Frameworks, auf Augenhöhe mit **NodeJS** und **Go**</a>.
* **WebSocket**-Unterstützung.
* Hintergrundaufgaben im selben Prozess.
* Ereignisse für das Starten und Herunterfahren.
@ -193,11 +193,11 @@ Mit **FastAPI** bekommen Sie alle Funktionen von **Pydantic** (da FastAPI für d
* Gutes Zusammenspiel mit Ihrer/Ihrem **<abbrtitle="Integrierten Entwicklungsumgebung, ähnlich zu (Quellcode-)Editor">IDE</abbr>/<abbrtitle="Ein Programm, was Fehler im Quellcode sucht">linter</abbr>/Gehirn**:
* Weil Datenstrukturen von Pydantic einfach nur Instanzen ihrer definierten Klassen sind, sollten Autovervollständigung, Linting, mypy und ihre Intuition einwandfrei funktionieren.
* **Schnell**:
* In <ahref="https://pydantic-docs.helpmanual.io/#benchmarks-tag"class="external-link"target="_blank">Vergleichen</a> ist Pydantic schneller als jede andere getestete Bibliothek.
* In <ahref="https://pydantic-docs.helpmanual.io/benchmarks/"class="external-link"target="_blank">Vergleichen</a> ist Pydantic schneller als jede andere getestete Bibliothek.
* Validierung von **komplexen Strukturen**:
* Benutzung von hierachischen Pydantic Schemata, Python `typing`’s `List` und `Dict`, etc.
* Validierungen erlauben klare und einfache Datenschemadefinition, überprüft und dokumentiert als JSON Schema.
* Validierungen erlauben eine klare und einfache Datenschemadefinition, überprüft und dokumentiert als JSON Schema.
* Sie können stark **verschachtelte JSON** Objekte haben und diese sind trotzdem validiert und annotiert.
* **Erweiterbar**:
* Pydantic erlaubt die Definition von eigenen Datentypen oder sie können die Validierung mit einer `validator` dekorierten Methode erweitern..
* Pydantic erlaubt die Definition von eigenen Datentypen oder sie können die Validierung mit einer `validator` dekorierten Methode erweitern.
@ -321,7 +321,7 @@ And now, go to <a href="http://127.0.0.1:8000/redoc" class="external-link" targe
### Recap
In summary, you declare **once** the types of parameters, body, etc. as function parameters.
In summary, you declare **once** the types of parameters, body, etc. as function parameters.
You do that with standard modern Python types.
@ -378,7 +378,7 @@ Coming back to the previous code example, **FastAPI** will:
* As the `q` parameter is declared with `= None`, it is optional.
* Without the `None` it would be required (as is the body in the case with `PUT`).
* For `PUT` requests to `/items/{item_id}`, Read the body as JSON:
* Check that it has a required attribute `name` that should be a `str`.
* Check that it has a required attribute `name` that should be a `str`.
* Check that it has a required attribute `price` that has to be a `float`.
* Check that it has an optional attribute `is_offer`, that should be a `bool`, if present.
* All this would also work for deeply nested JSON objects.
@ -446,7 +446,6 @@ Used by Pydantic:
Used by Starlette:
* <ahref="https://requests.readthedocs.io"target="_blank"><code>requests</code></a> - Required if you want to use the `TestClient`.
* <ahref="https://github.com/Tinche/aiofiles"target="_blank"><code>aiofiles</code></a> - Required if you want to use `FileResponse` or `StaticFiles`.
* <ahref="https://jinja.palletsprojects.com"target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration.
* <ahref="https://andrew-d.github.io/python-multipart/"target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbrtitle="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`.
* <ahref="https://pythonhosted.org/itsdangerous/"target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support.
@ -26,13 +26,23 @@ The important difference for us is that with HTTPX we are not limited to synchro
## Example
For a simple example, let's consider the following `main.py` module:
For a simple example, let's consider a file structure similar to the one described in [Bigger Applications](../tutorial/bigger-applications.md){.internal-link target=_blank} and [Testing](../tutorial/testing.md){.internal-link target=_blank}:
```
.
├── app
│ ├── __init__.py
│ ├── main.py
│ └── test_main.py
```
The file `main.py` would have:
```Python
{!../../../docs_src/async_tests/main.py!}
```
The `test_main.py` module that contains the tests for `main.py` could look like this now:
The file `test_main.py` would have the tests for `main.py`, it could look like this now:
@ -21,6 +21,12 @@ For example, if you are squeezing performance, you can install and use <a href="
Import the `Response` class (sub-class) you want to use and declare it in the *path operation decorator*.
For large responses, returning a `Response` directly is much faster than returning a dictionary.
This is because by default, FastAPI will inspect every item inside and make sure it is serializable with JSON, using the same [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank} explained in the tutorial. This is what allows you to return **arbitrary objects**, for example database models.
But if you are certain that the content that you are returning is **serializable with JSON**, you can pass it directly to the response class and avoid the extra overhead that FastAPI would have by passing your return content through the `jsonable_encoder` before passing it to the response class.
@ -244,6 +250,36 @@ You can also use the `response_class` parameter:
In this case, you can return the file path directly from your *path operation* function.
## Custom response class
You can create your own custom response class, inheriting from `Response` and using it.
For example, let's say that you want to use <ahref="https://github.com/ijl/orjson"class="external-link"target="_blank">`orjson`</a>, but with some custom settings not used in the included `ORJSONResponse` class.
Let's say you want it to return indented and formatted JSON, so you want to use the orjson option `orjson.OPT_INDENT_2`.
You could create a `CustomORJSONResponse`. The main thing you have to do is create a `Response.render(content)` method that returns the content as `bytes`:
As **FastAPI** is based on the OpenAPI specification, you get automatic compatibility with many tools, including the automatic API docs (provided by Swagger UI).
One particular advantage that is not necessarily obvious is that you can **generate clients** (sometimes called <abbrtitle="Software Development Kits">**SDKs**</abbr> ) for your API, for many different **programming languages**.
## OpenAPI Client Generators
There are many tools to generate clients from **OpenAPI**.
A common tool is <ahref="https://openapi-generator.tech/"class="external-link"target="_blank">OpenAPI Generator</a>.
If you are building a **frontend**, a very interesting alternative is <ahref="https://github.com/ferdikoomen/openapi-typescript-codegen"class="external-link"target="_blank">openapi-typescript-codegen</a>.
To generate the client code you can use the command line application `openapi` that would now be installed.
Because it is installed in the local project, you probably wouldn't be able to call that command directly, but you would put it on your `package.json` file.
...that's because the client generator uses the OpenAPI internal **operation ID** for each *path operation*.
OpenAPI requires that each operation ID is unique across all the *path operations*, so FastAPI uses the **function name**, the **path**, and the **HTTP method/operation** to generate that operation ID, because that way it can make sure that the operation IDs are unique.
But I'll show you how to improve that next. 🤓
## Custom Operation IDs and Better Method Names
You can **modify** the way these operation IDs are **generated** to make them simpler and have **simpler method names** in the clients.
In this case you will have to ensure that each operation ID is **unique** in some other way.
For example, you could make sure that each *path operation* has a tag, and then generate the operation ID based on the **tag** and the *path operation***name** (the function name).
### Custom Generate Unique ID Function
FastAPI uses a **unique ID** for each *path operation*, it is used for the **operation ID** and also for the names of any needed custom models, for requests or responses.
You can customize that function. It takes an `APIRoute` and outputs a string.
For example, here it is using the first tag (you will probably have only one tag) and the *path operation* name (the function name).
You can then pass that custom function to **FastAPI** as the `generate_unique_id_function` parameter:
As you see, the method names now have the tag and then the function name, now they don't include information from the URL path and the HTTP operation.
### Preprocess the OpenAPI Specification for the Client Generator
The generated code still has some **duplicated information**.
We already know that this method is related to the **items** because that word is in the `ItemsService` (taken from the tag), but we still have the tag name prefixed in the method name too. 😕
We will probably still want to keep it for OpenAPI in general, as that will ensure that the operation IDs are **unique**.
But for the generated client we could **modify** the OpenAPI operation IDs right before generating the clients, just to make those method names nicer and **cleaner**.
We could download the OpenAPI JSON to a file `openapi.json` and then we could **remove that prefixed tag** with a script like this:
With that, the operation IDs would be renamed from things like `items-get_items` to just `get_items`, that way the client generator can generate simpler method names.
### Generate a TypeScript Client with the Preprocessed OpenAPI
Now as the end result is in a file `openapi.json`, you would modify the `package.json` to use that local file, for example:
When using the automatically generated clients you would **autocompletion** for:
* Methods.
* Request payloads in the body, query parameters, etc.
* Response payloads.
You would also have **inline errors** for everything.
And whenever you update the backend code, and **regenerate** the frontend, it would have any new *path operations* available as methods, the old ones removed, and any other change would be reflected on the generated code. 🤓
This also means that if something changed it will be **reflected** on the client code automatically. And if you **build** the client it will error out if you have any **mismatch** in the data used.
So, you would **detect many errors** very early in the development cycle instead of having to wait for the errors to show up to your final users in production and then trying to debug where the problem is. ✨
@ -163,7 +163,7 @@ At this point you have the *callback path operation(s)* needed (the one(s) that
Now use the parameter `callbacks` in *your API's path operation decorator* to pass the attribute `.routes` (that's actually just a `list` of routes/*path operations*) from that callback router:
@ -34,13 +34,19 @@ Here's a more complete example.
Use a dependency to check if the username and password are correct.
For this, use the Python standard module <ahref="https://docs.python.org/3/library/secrets.html"class="external-link"target="_blank">`secrets`</a> to check the username and password:
For this, use the Python standard module <ahref="https://docs.python.org/3/library/secrets.html"class="external-link"target="_blank">`secrets`</a> to check the username and password.
```Python hl_lines="1 11-13"
`secrets.compare_digest()` needs to take `bytes` or a `str` that only contains ASCII characters (the ones in English), this means it wouldn't work with characters like `á`, as in `Sebastián`.
To handle that, we first convert the `username` and `password` to `bytes` encoding them with UTF-8.
Then we can use `secrets.compare_digest()` to ensure that `credentials.username` is `"stanleyjobson"`, and that `credentials.password` is `"swordfish"`.
```Python hl_lines="1 11-21"
{!../../../docs_src/security/tutorial007.py!}
```
This will ensure that `credentials.username` is `"stanleyjobson"`, and that `credentials.password` is `"swordfish"`. This would be similar to:
This would be similar to:
```Python
if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
@ -102,6 +108,6 @@ That way, using `secrets.compare_digest()` in your application code, it will be
After detecting that the credentials are incorrect, return an `HTTPException` with a status code 401 (the same returned when no credentials are provided) and add the header `WWW-Authenticate` to make the browser show the login prompt again:
@ -182,7 +182,7 @@ Now let's check the file `sql_app/schemas.py`.
To avoid confusion between the Peewee *models* and the Pydantic *models*, we will have the file `models.py` with the Peewee models, and the file `schemas.py` with the Pydantic models.
These Pydantic models define more or less a "schema" (a valid data shape).
So this will help us avoiding confusion while using both.
You can use <ahref="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API"class="external-link"target="_blank">WebSockets</a> with **FastAPI**.
@ -333,7 +333,7 @@ Now APIStar is a set of tools to validate OpenAPI specifications, not a web fram
Exist.
The idea of declaring multiple things (data validation, serialization and documentation) with the same Python types, that at the same time provided great editor support, was something I considered a brilliant idea.
And after searching for a long time for a similar framework and testing many different alternatives, APIStar was the best option available.
Then APIStar stopped to exist as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**.
@ -391,7 +391,7 @@ That's one of the main things that **FastAPI** adds on top, all based on Python
Handle all the core web parts. Adding features on top.
The class `FastAPI` itself inherits directly from the class `Starlette`.
So, anything that you can do with Starlette, you can do it directly with **FastAPI**, as it is basically Starlette on steroids.
If you are using a third party library that communicates with something (a database, an API, the file system, etc) and doesn't have support for using `await`, (this is currently the case for most database libraries), then declare your *path operation functions* as normally, with just `def`, like:
If you are using a third party library that communicates with something (a database, an API, the file system, etc.) and doesn't have support for using `await`, (this is currently the case for most database libraries), then declare your *path operation functions* as normally, with just `def`, like:
```Python hl_lines="2"
@app.get('/')
@ -45,7 +45,7 @@ If you just don't know, use normal `def`.
---
**Note**: you can mix `def` and `async def` in your *path operation functions* as much as you need and define each one using the best option for you. FastAPI will do the right thing with them.
**Note**: You can mix `def` and `async def` in your *path operation functions* as much as you need and define each one using the best option for you. FastAPI will do the right thing with them.
Anyway, in any of the cases above, FastAPI will still work asynchronously and be extremely fast.
@ -102,87 +102,117 @@ To see the difference, imagine the following story about burgers:
### Concurrent Burgers
<!-- The gender neutral cook emoji "🧑🍳" does not render well in browsers. In the meantime, I'm using a mix of male "👨🍳" and female "👩🍳" cooks. -->
You go with your crush to get fast food, you stand in line while the cashier takes the orders from the people in front of you. 😍
You go with your crush 😍 to get fast food 🍔, you stand in line while the cashier 💁 takes the orders from the people in front of you.
The cashier says something to the cook in the kitchen so they know they have to prepare your burgers (even though they are currently preparing the ones for the previous clients).
The cashier 💁 says something to the cook in the kitchen 👨🍳 so they know they have to prepare your burgers 🍔 (even though they are currently preparing the ones for the previous clients).
While you are waiting, you go with your crush and pick a table, you sit and talk with your crush for a long time (as your burgers are very fancy and take some time to prepare).
While you are waiting, you go with your crush 😍 and pick a table, you sit and talk with your crush 😍 for a long time (as your burgers are very fancy and take some time to prepare ✨🍔✨).
As you are sitting at the table with your crush, while you wait for the burgers, you can spend that time admiring how awesome, cute and smart your crush is ✨😍✨.
As you are sitting on the table with your crush 😍, while you wait for the burgers 🍔, you can spend that time admiring how awesome, cute and smart your crush is ✨😍✨.
Beautiful illustrations by <ahref="https://www.instagram.com/ketrinadrawsalot"class="external-link"target="_blank">Ketrina Thompson</a>. 🎨
---
Imagine you are the computer / program 🤖 in that story.
While you are at the line, you are just idle 😴, waiting for your turn, not doing anything very "productive". But the line is fast because the cashier 💁 is only taking the orders (not preparing them), so that's fine.
While you are at the line, you are just idle 😴, waiting for your turn, not doing anything very "productive". But the line is fast because the cashier is only taking the orders (not preparing them), so that's fine.
Then, when it's your turn, you do actual "productive" work 🤓, you process the menu, decide what you want, get your crush's 😍 choice, pay 💸, check that you give the correct bill or card, check that you are charged correctly, check that the order has the correct items, etc.
Then, when it's your turn, you do actual "productive" work, you process the menu, decide what you want, get your crush's choice, pay, check that you give the correct bill or card, check that you are charged correctly, check that the order has the correct items, etc.
But then, even though you still don't have your burgers 🍔, your work with the cashier 💁 is "on pause" ⏸, because you have to wait 🕙 for your burgers to be ready.
But then, even though you still don't have your burgers, your work with the cashier is "on pause" ⏸, because you have to wait 🕙 for your burgers to be ready.
But as you go away from the counter and sit on the table with a number for your turn, you can switch 🔀 your attention to your crush 😍, and "work" ⏯ 🤓 on that. Then you are again doing something very "productive" 🤓, as is flirting with your crush 😍.
But as you go away from the counter and sit at the table with a number for your turn, you can switch 🔀 your attention to your crush, and "work" ⏯ 🤓 on that. Then you are again doing something very "productive" as is flirting with your crush 😍.
Then the cashier 💁 says "I'm finished with doing the burgers" 🍔 by putting your number on the counter's display, but you don't jump like crazy immediately when the displayed number changes to your turn number. You know no one will steal your burgers 🍔 because you have the number of your turn, and they have theirs.
Then the cashier 💁 says "I'm finished with doing the burgers" by putting your number on the counter's display, but you don't jump like crazy immediately when the displayed number changes to your turn number. You know no one will steal your burgers because you have the number of your turn, and they have theirs.
So you wait for your crush 😍 to finish the story (finish the current work ⏯ / task being processed 🤓), smile gently and say that you are going for the burgers ⏸.
So you wait for your crush to finish the story (finish the current work ⏯ / task being processed 🤓), smile gently and say that you are going for the burgers ⏸.
Then you go to the counter 🔀, to the initial task that is now finished ⏯, pick the burgers 🍔, say thanks and take them to the table. That finishes that step / task of interaction with the counter ⏹. That in turn, creates a new task, of "eating burgers" 🔀 ⏯, but the previous one of "getting burgers" is finished ⏹.
Then you go to the counter 🔀, to the initial task that is now finished ⏯, pick the burgers, say thanks and take them to the table. That finishes that step / task of interaction with the counter ⏹. That in turn, creates a new task, of "eating burgers" 🔀 ⏯, but the previous one of "getting burgers" is finished ⏹.
### Parallel Burgers
Now let's imagine these aren't "Concurrent Burgers", but "Parallel Burgers".
You go with your crush 😍 to get parallel fast food 🍔.
You go with your crush to get parallel fast food.
You stand in line while several (let's say 8) cashiers that at the same time are cooks take the orders from the people in front of you.
You stand in line while several (let's say 8) cashiers that at the same time are cooks 👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳 take the orders from the people in front of you.
Everyone before you is waiting for their burgers to be ready before leaving the counter because each of the 8 cashiers goes and prepares the burger right away before getting the next order.
Everyone before you is waiting 🕙 for their burgers 🍔 to be ready before leaving the counter because each of the 8 cashiers goes and prepares the burger right away before getting the next order.
You wait, standing in front of the counter 🕙, so that no one else takes your burgers 🍔 before you do, as there are no numbers for turns.
The cashier goes to the kitchen.
As you and your crush 😍 are busy not letting anyone get in front of you and take your burgers whenever they arrive 🕙, you cannot pay attention to your crush 😞.
You wait, standing in front of the counter 🕙, so that no one else takes your burgers before you do, as there are no numbers for turns.
This is "synchronous" work, you are "synchronized" with the cashier/cook 👨🍳. You have to wait 🕙 and be there at the exact moment that the cashier/cook 👨🍳 finishes the burgers 🍔 and gives them to you, or otherwise, someone else might take them.
Then your cashier/cook 👨🍳 finally comes back with your burgers 🍔, after a long time waiting 🕙 there in front of the counter.
As you and your crush are busy not letting anyone get in front of you and take your burgers whenever they arrive, you cannot pay attention to your crush. 😞
You take your burgers 🍔 and go to the table with your crush 😍.
This is "synchronous" work, you are "synchronized" with the cashier/cook 👨🍳. You have to wait 🕙 and be there at the exact moment that the cashier/cook 👨🍳 finishes the burgers and gives them to you, or otherwise, someone else might take them.
There was not much talk or flirting as most of the time was spent waiting 🕙 in front of the counter. 😞
!!! info
Beautiful illustrations by <ahref="https://www.instagram.com/ketrinadrawsalot"class="external-link"target="_blank">Ketrina Thompson</a>. 🎨
---
In this scenario of the parallel burgers, you are a computer / program 🤖 with two processors (you and your crush 😍), both waiting 🕙 and dedicating their attention ⏯ to be "waiting on the counter" 🕙 for a long time.
In this scenario of the parallel burgers, you are a computer / program 🤖 with two processors (you and your crush), both waiting 🕙 and dedicating their attention ⏯ to be "waiting on the counter" 🕙 for a long time.
The fast food store has 8 processors (cashiers/cooks) 👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳. While the concurrent burgers store might have had only 2 (one cashier and one cook) 💁 👨🍳.
The fast food store has 8 processors (cashiers/cooks). While the concurrent burgers store might have had only 2 (one cashier and one cook).
But still, the final experience is not the best 😞.
But still, the final experience is not the best. 😞
---
This would be the parallel equivalent story for burgers 🍔.
This would be the parallel equivalent story for burgers. 🍔
For a more "real life" example of this, imagine a bank.
@ -208,11 +238,7 @@ This "waiting" 🕙 is measured in microseconds, but still, summing it all, it's
That's why it makes a lot of sense to use asynchronous ⏸🔀⏯ code for web APIs.
Most of the existing popular Python frameworks (including Flask and Django) were created before the new asynchronous features in Python existed. So, the ways they can be deployed support parallel execution and an older form of asynchronous execution that is not as powerful as the new capabilities.
Even though the main specification for asynchronous web Python (ASGI) was developed at Django, to add support for WebSockets.
That kind of asynchronicity is what made NodeJS popular (even though NodeJS is not parallel) and that's the strength of Go as a programming language.
This kind of asynchronicity is what made NodeJS popular (even though NodeJS is not parallel) and that's the strength of Go as a programming language.
And that's the same level of performance you get with **FastAPI**.
@ -238,7 +264,7 @@ You could have turns as in the burgers example, first the living room, then the
It would take the same amount of time to finish with or without turns (concurrency) and you would have done the same amount of work.
But in this case, if you could bring the 8 ex-cashier/cooks/now-cleaners 👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳, and each one of them (plus you) could take a zone of the house to clean it, you could do all the work in **parallel**, with the extra help, and finish much sooner.
But in this case, if you could bring the 8 ex-cashier/cooks/now-cleaners, and each one of them (plus you) could take a zone of the house to clean it, you could do all the work in **parallel**, with the extra help, and finish much sooner.
In this scenario, each one of the cleaners (including you) would be a processor, doing their part of the job.
@ -371,7 +397,7 @@ All that is what powers FastAPI (through Starlette) and what makes it have such
These are very technical details of how **FastAPI** works underneath.
If you have quite some technical knowledge (co-routines, threads, blocking, etc) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead.
If you have quite some technical knowledge (co-routines, threads, blocking, etc.) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead.
@ -190,11 +190,11 @@ With **FastAPI** you get all of **Pydantic**'s features (as FastAPI is based on
* Plays nicely with your **<abbrtitle="Integrated Development Environment, similar to a code editor">IDE</abbr>/<abbrtitle="A program that checks for code errors">linter</abbr>/brain**:
* Because pydantic data structures are just instances of classes you define; auto-completion, linting, mypy and your intuition should all work properly with your validated data.
* **Fast**:
* in <ahref="https://pydantic-docs.helpmanual.io/#benchmarks-tag"class="external-link"target="_blank">benchmarks</a> Pydantic is faster than all other tested libraries.
* in <ahref="https://pydantic-docs.helpmanual.io/benchmarks/"class="external-link"target="_blank">benchmarks</a> Pydantic is faster than all other tested libraries.
* Validate **complex structures**:
* Use of hierarchical Pydantic models, Python `typing`’s `List` and `Dict`, etc.
* And validators allow complex data schemas to be clearly and easily defined, checked and documented as JSON Schema.
* You can have deeply **nested JSON** objects and have them all validated and annotated.
* **Extendible**:
* **Extensible**:
* Pydantic allows custom data types to be defined or you can extend validation with methods on a model decorated with the validator decorator.