Please follow these instructions, fill every question, and do every step. 🙏
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'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.
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.
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 😅).
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.
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. 😎
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. 🤓
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
label:Commit to Help
description:|
description:|
After submitting this, I commit to one of:
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.
*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.
*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. 🙏
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'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.
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.
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 😅).
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.
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. 😎
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. 🤓
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
label:Commit to Help
description:|
description:|
After submitting this, I commit to one of:
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.
*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.
*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.
<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/3PjOZqc"target="_blank"title="DiscoArt: Create compelling Disco Diffusion artworks in just one line"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/jina-ai.png"></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://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://classiq.link/n4s"target="_blank"title="Join the team building a new SaaS platform that will change the computing world"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/classiq.png"></a>
<ahref="https://app.imgwhale.xyz/"target="_blank"title="The ultimate solution to unlimited and forever cloud storage."><imgsrc="https://fastapi.tiangolo.com/img/sponsors/imgwhale.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.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.investsuite.com/jobs"target="_blank"title="Wealthtech jobs with FastAPI"><imgsrc="https://fastapi.tiangolo.com/img/sponsors/investsuite.svg"></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://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://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://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.
* <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.
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}.
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
### 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 sinnvolle **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
### Validierung
@ -109,7 +109,7 @@ Aber standartmäßig, **"funktioniert einfach"** alles.
* Zeichenketten (`str`), mit definierter minimaler und maximaler Länge.
* Zeichenketten (`str`), mit definierter minimaler und maximaler Länge.
* Zahlen (`int`, `float`) mit minimaler und maximaler Größe, usw.
* 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.
* URL.
* Email.
* Email.
* UUID.
* UUID.
@ -142,8 +142,8 @@ FastAPI enthält ein extrem einfaches, aber extrem mächtiges <abbr title='oft v
* **Automatische Umsetzung** durch FastAPI.
* **Automatische Umsetzung** durch FastAPI.
* Alle abhängigen Komponenten könnten Daten von Anfragen, **Erweiterungen der Pfadoperations-**Einschränkungen und der automatisierten Dokumentation benötigen.
* 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.
* **Automatische Validierung** selbst für *Pfadoperationen*-Parameter, die in den Abhängigkeiten definiert wurden.
* Unterstütz komplexe Benutzerauthentifizierungssysteme, mit **Datenbankverbindungen**, usw.
* Unterstützt komplexe Benutzerauthentifizierungssysteme, mit **Datenbankverbindungen**, usw.
* **Keine Kompromisse** bei Datenbanken, Eingabemasken, usw. Sondern einfache Integration von allen.
* **Keine Kompromisse** bei Datenbanken, Eingabemasken, usw., sondern einfache Integration von allen.
### Unbegrenzte Erweiterungen
### Unbegrenzte Erweiterungen
@ -159,9 +159,9 @@ Jede Integration wurde so entworfen, dass sie einfach zu nutzen ist (mit Abhäng
## Starlette's Merkmale
## 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):
Mit **FastAPI** bekommen Sie viele von **Starlette**'s Funktionen (da FastAPI nur Starlette auf Steroiden ist):
@ -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**:
* 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.
* Weil Datenstrukturen von Pydantic einfach nur Instanzen ihrer definierten Klassen sind, sollten Autovervollständigung, Linting, mypy und ihre Intuition einwandfrei funktionieren.
* **Schnell**:
* **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**:
* Validierung von **komplexen Strukturen**:
* Benutzung von hierachischen Pydantic Schemata, Python `typing`’s `List` und `Dict`, etc.
* 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 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.
* Sie können stark **verschachtelte JSON** Objekte haben und diese sind trotzdem validiert und annotiert.
* **Erweiterbar**:
* **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
### 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.
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.
* 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`).
* 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:
* 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 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.
* 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.
* All this would also work for deeply nested JSON objects.
@ -446,7 +446,6 @@ Used by Pydantic:
Used by Starlette:
Used by Starlette:
* <ahref="https://requests.readthedocs.io"target="_blank"><code>requests</code></a> - Required if you want to use the `TestClient`.
* <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://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://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.
* <ahref="https://pythonhosted.org/itsdangerous/"target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support.
@ -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.
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).
These Pydantic models define more or less a "schema" (a valid data shape).
So this will help us avoiding confusion while using both.
So this will help us avoiding confusion while using both.
@ -333,7 +333,7 @@ Now APIStar is a set of tools to validate OpenAPI specifications, not a web fram
Exist.
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.
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.
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**.
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.
Handle all the core web parts. Adding features on top.
The class `FastAPI` itself inherits directly from the class `Starlette`.
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.
So, anything that you can do with Starlette, you can do it directly with **FastAPI**, as it is basically Starlette on steroids.
@ -116,7 +116,7 @@ The cashier 💁 gives you the number of your turn.
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 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 ✨😍✨.
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 ✨😍✨.
While waiting and talking to your crush 😍, from time to time, you check the number displayed on the counter to see if it's your turn already.
While waiting and talking to your crush 😍, from time to time, you check the number displayed on the counter to see if it's your turn already.
@ -134,7 +134,7 @@ Then, when it's your turn, you do actual "productive" work 🤓, you process the
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.
@ -190,7 +190,7 @@ 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**:
* 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.
* 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**:
* **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**:
* Validate **complex structures**:
* Use of hierarchical Pydantic models, Python `typing`’s `List` and `Dict`, etc.
* 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.
* And validators allow complex data schemas to be clearly and easily defined, checked and documented as JSON Schema.
If you are using a Python version below 3.10, here's a tip from my very **subjective** point of view:
* 🚨 Avoid using `Optional[SomeType]`
* Instead ✨ **use `Union[SomeType, None]`** ✨.
Both are equivalent and underneath they are the same, but I would recommend `Union` instead of `Optional` because the word "**optional**" would seem to imply that the value is optional, and it actually means "it can be `None`", even if it's not optional and is still required.
I think `Union[str, SomeType]` is more explicit about what it means.
It's just about the words and names. But those words can affect how you and your teammates think about the code.
And then you won't have to worry about names like `Optional` and `Union`. 😎
#### Generic types
#### Generic types
These types that take type parameters in square brackets are called **Generic types** or **Generics**, for example:
These types that take type parameters in square brackets are called **Generic types** or **Generics**, for example:
@ -334,14 +373,14 @@ These types that take type parameters in square brackets are called **Generic ty
=== "Python 3.9 and above"
=== "Python 3.9 and above"
You can use the same builtin types as generics (with square brakets and types inside):
You can use the same builtin types as generics (with square brakets and types inside):
* `list`
* `list`
* `tuple`
* `tuple`
* `set`
* `set`
* `dict`
* `dict`
And the same as with Python 3.6, from the `typing` module:
And the same as with Python 3.6, from the `typing` module:
* `Union`
* `Union`
* `Optional`
* `Optional`
* ...and others.
* ...and others.
@ -354,7 +393,7 @@ These types that take type parameters in square brackets are called **Generic ty
* `tuple`
* `tuple`
* `set`
* `set`
* `dict`
* `dict`
And the same as with Python 3.6, from the `typing` module:
And the same as with Python 3.6, from the `typing` module:
* `Union`
* `Union`
@ -422,6 +461,9 @@ An example from the official Pydantic docs:
You will see a lot more of all this in practice in the [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}.
You will see a lot more of all this in practice in the [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}.
!!! tip
Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <ahref="https://pydantic-docs.helpmanual.io/usage/models/#required-optional-fields"class="external-link"target="_blank">Required Optional fields</a>.
## Type hints in **FastAPI**
## Type hints in **FastAPI**
**FastAPI** takes advantage of these type hints to do several things.
**FastAPI** takes advantage of these type hints to do several things.
* 🐛 Fix removing body from status codes that do not support it. PR [#5145](https://github.com/tiangolo/fastapi/pull/5145) by [@tiangolo](https://github.com/tiangolo).
* Setting `status_code` to `204`, `304`, or any code below `200` (1xx) will remove the body from the response.
* This fixes an error in Uvicorn that otherwise would be thrown: `RuntimeError: Response content longer than Content-Length`.
* This removes `fastapi.openapi.constants.STATUS_CODES_WITH_NO_BODY`, it is replaced by a function in utils.
### Translations
* 🌐 Start of Hebrew translation. PR [#5050](https://github.com/tiangolo/fastapi/pull/5050) by [@itay-raveh](https://github.com/itay-raveh).
* 🔧 Add config for Swedish translations notification. PR [#5147](https://github.com/tiangolo/fastapi/pull/5147) by [@tiangolo](https://github.com/tiangolo).
* 🌐 Start of Swedish translation. PR [#5062](https://github.com/tiangolo/fastapi/pull/5062) by [@MrRawbin](https://github.com/MrRawbin).
* 🌐 Add Japanese translation for `docs/ja/docs/advanced/index.md`. PR [#5043](https://github.com/tiangolo/fastapi/pull/5043) by [@wakabame](https://github.com/wakabame).
* 🌐🇵🇱 Add Polish translation for `docs/pl/docs/tutorial/first-steps.md`. PR [#5024](https://github.com/tiangolo/fastapi/pull/5024) by [@Valaraucoo](https://github.com/Valaraucoo).
### Internal
* 🔧 Update translations notification for Hebrew. PR [#5158](https://github.com/tiangolo/fastapi/pull/5158) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update Dependabot commit message. PR [#5156](https://github.com/tiangolo/fastapi/pull/5156) by [@tiangolo](https://github.com/tiangolo).
* ⬆ Bump actions/upload-artifact from 2 to 3. PR [#5148](https://github.com/tiangolo/fastapi/pull/5148) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump actions/cache from 2 to 3. PR [#5149](https://github.com/tiangolo/fastapi/pull/5149) by [@dependabot[bot]](https://github.com/apps/dependabot).
* 🔧 Update sponsors badge configs. PR [#5155](https://github.com/tiangolo/fastapi/pull/5155) by [@tiangolo](https://github.com/tiangolo).
* 👥 Update FastAPI People. PR [#5154](https://github.com/tiangolo/fastapi/pull/5154) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update Jina sponsor badges. PR [#5151](https://github.com/tiangolo/fastapi/pull/5151) by [@tiangolo](https://github.com/tiangolo).
* ⬆ Bump actions/checkout from 2 to 3. PR [#5133](https://github.com/tiangolo/fastapi/pull/5133) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#5030](https://github.com/tiangolo/fastapi/pull/5030) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
* ⬆ Bump nwtgck/actions-netlify from 1.1.5 to 1.2.3. PR [#5132](https://github.com/tiangolo/fastapi/pull/5132) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump codecov/codecov-action from 2 to 3. PR [#5131](https://github.com/tiangolo/fastapi/pull/5131) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump dawidd6/action-download-artifact from 2.9.0 to 2.21.1. PR [#5130](https://github.com/tiangolo/fastapi/pull/5130) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump actions/setup-python from 2 to 4. PR [#5129](https://github.com/tiangolo/fastapi/pull/5129) by [@dependabot[bot]](https://github.com/apps/dependabot).
* 👷 Add Dependabot. PR [#5128](https://github.com/tiangolo/fastapi/pull/5128) by [@tiangolo](https://github.com/tiangolo).
* ♻️ Move from `Optional[X]` to `Union[X, None]` for internal utils. PR [#5124](https://github.com/tiangolo/fastapi/pull/5124) by [@tiangolo](https://github.com/tiangolo).
* ✨ Add support for omitting `...` as default value when declaring required parameters with:
* `Path()`
* `Query()`
* `Header()`
* `Cookie()`
* `Body()`
* `Form()`
* `File()`
New docs at [Tutorial - Query Parameters and String Validations - Make it required](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#make-it-required). PR [#4906](https://github.com/tiangolo/fastapi/pull/4906) by [@tiangolo](https://github.com/tiangolo).
Up to now, declaring a required parameter while adding additional validation or metadata needed using `...` (Ellipsis).
For example:
```Python
from fastapi import Cookie, FastAPI, Header, Path, Query
* 📝 Add docs recommending `Union` over `Optional` and migrate source examples. New docs at [Python Types Intro - Using `Union` or `Optional`](https://fastapi.tiangolo.com/python-types/#using-union-or-optional). PR [#4908](https://github.com/tiangolo/fastapi/pull/4908) by [@tiangolo](https://github.com/tiangolo).
* 🎨 Fix default value as set in tutorial for Path Operations Advanced Configurations. PR [#4899](https://github.com/tiangolo/fastapi/pull/4899) by [@tiangolo](https://github.com/tiangolo).
* 📝 Add documentation for redefined path operations. PR [#4864](https://github.com/tiangolo/fastapi/pull/4864) by [@madkinsz](https://github.com/madkinsz).
* 📝 Updates links for Celery documentation. PR [#4736](https://github.com/tiangolo/fastapi/pull/4736) by [@sammyzord](https://github.com/sammyzord).
* ✏ Fix example code with sets in tutorial for body nested models. PR [#3030](https://github.com/tiangolo/fastapi/pull/3030) by [@hitrust](https://github.com/hitrust).
* ✏ Fix links to Pydantic docs. PR [#4670](https://github.com/tiangolo/fastapi/pull/4670) by [@kinuax](https://github.com/kinuax).
* 📝 Update docs about Swagger UI self-hosting with newer source links. PR [#4813](https://github.com/tiangolo/fastapi/pull/4813) by [@Kastakin](https://github.com/Kastakin).
* 📝 Add link to external article: Building the Poll App From Django Tutorial With FastAPI And React. PR [#4778](https://github.com/tiangolo/fastapi/pull/4778) by [@jbrocher](https://github.com/jbrocher).
* 📝 Add OpenAPI warning to "Body - Fields" docs with extra schema extensions. PR [#4846](https://github.com/tiangolo/fastapi/pull/4846) by [@ml-evs](https://github.com/ml-evs).
### Translations
* 🌐 Fix code examples in Japanese translation for `docs/ja/docs/tutorial/testing.md`. PR [#4623](https://github.com/tiangolo/fastapi/pull/4623) by [@hirotoKirimaru](https://github.com/hirotoKirimaru).
### Internal
* ♻ Refactor dict value extraction to minimize key lookups `fastapi/utils.py`. PR [#3139](https://github.com/tiangolo/fastapi/pull/3139) by [@ShahriyarR](https://github.com/ShahriyarR).
* ✅ Add tests for required nonable parameters and body fields. PR [#4907](https://github.com/tiangolo/fastapi/pull/4907) by [@tiangolo](https://github.com/tiangolo).
* 👷 Fix installing Material for MkDocs Insiders in CI. PR [#4897](https://github.com/tiangolo/fastapi/pull/4897) by [@tiangolo](https://github.com/tiangolo).
* 👷 Add pre-commit CI instead of custom GitHub Action. PR [#4896](https://github.com/tiangolo/fastapi/pull/4896) by [@tiangolo](https://github.com/tiangolo).
* 📝 Add dark mode auto switch to docs based on OS preference. PR [#4869](https://github.com/tiangolo/fastapi/pull/4869) by [@ComicShrimp](https://github.com/ComicShrimp).
* 🔥 Remove un-used old pending tests, already covered in other places. PR [#4891](https://github.com/tiangolo/fastapi/pull/4891) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Add Python formatting hooks to pre-commit. PR [#4890](https://github.com/tiangolo/fastapi/pull/4890) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Add pre-commit with first config and first formatting pass. PR [#4888](https://github.com/tiangolo/fastapi/pull/4888) by [@tiangolo](https://github.com/tiangolo).
* 👷 Disable CI installing Material for MkDocs in forks. PR [#4410](https://github.com/tiangolo/fastapi/pull/4410) by [@dolfinus](https://github.com/dolfinus).
## 0.77.1
### Upgrades
* ⬆ Upgrade Starlette from 0.19.0 to 0.19.1. PR [#4819](https://github.com/tiangolo/fastapi/pull/4819) by [@Kludex](https://github.com/Kludex).
### Docs
* 📝 Add link to german article: REST-API Programmieren mittels Python und dem FastAPI Modul. PR [#4624](https://github.com/tiangolo/fastapi/pull/4624) by [@fschuermeyer](https://github.com/fschuermeyer).
* 📝 Add external link: PyCharm Guide to FastAPI. PR [#4512](https://github.com/tiangolo/fastapi/pull/4512) by [@mukulmantosh](https://github.com/mukulmantosh).
* 📝 Add external link to article: Building an API with FastAPI and Supabase and Deploying on Deta. PR [#4440](https://github.com/tiangolo/fastapi/pull/4440) by [@aUnicornDev](https://github.com/aUnicornDev).
* ✏ Fix small typo in `docs/en/docs/tutorial/security/first-steps.md`. PR [#4515](https://github.com/tiangolo/fastapi/pull/4515) by [@KikoIlievski](https://github.com/KikoIlievski).
### Translations
* 🌐 Add Polish translation for `docs/pl/docs/tutorial/index.md`. PR [#4516](https://github.com/tiangolo/fastapi/pull/4516) by [@MKaczkow](https://github.com/MKaczkow).
* ✏ Fix typo in deployment. PR [#4629](https://github.com/tiangolo/fastapi/pull/4629) by [@raisulislam541](https://github.com/raisulislam541).
* 🌐 Add Portuguese translation for `docs/pt/docs/help-fastapi.md`. PR [#4583](https://github.com/tiangolo/fastapi/pull/4583) by [@mateusjs](https://github.com/mateusjs).
### Internal
* 🔧 Add notifications in issue for Uzbek translations. PR [#4884](https://github.com/tiangolo/fastapi/pull/4884) by [@tiangolo](https://github.com/tiangolo).
## 0.77.0
### Upgrades
* ⬆ Upgrade Starlette from 0.18.0 to 0.19.0. PR [#4488](https://github.com/tiangolo/fastapi/pull/4488) by [@Kludex](https://github.com/Kludex).
* When creating an explicit `JSONResponse` the `content` argument is now required.
### Docs
* 📝 Add external link to article: Seamless FastAPI Configuration with ConfZ. PR [#4414](https://github.com/tiangolo/fastapi/pull/4414) by [@silvanmelchior](https://github.com/silvanmelchior).
* 📝 Add external link to article: 5 Advanced Features of FastAPI You Should Try. PR [#4436](https://github.com/tiangolo/fastapi/pull/4436) by [@kaustubhgupta](https://github.com/kaustubhgupta).
* ✏ Reword to improve legibility of docs about `TestClient`. PR [#4389](https://github.com/tiangolo/fastapi/pull/4389) by [@rgilton](https://github.com/rgilton).
* 📝 Add external link to blog post about Kafka, FastAPI, and Ably. PR [#4044](https://github.com/tiangolo/fastapi/pull/4044) by [@Ugbot](https://github.com/Ugbot).
* ✏ Fix typo in `docs/en/docs/tutorial/sql-databases.md`. PR [#4875](https://github.com/tiangolo/fastapi/pull/4875) by [@wpyoga](https://github.com/wpyoga).
* ✏ Fix typo in `docs/en/docs/async.md`. PR [#4726](https://github.com/tiangolo/fastapi/pull/4726) by [@Prezu](https://github.com/Prezu).
### Translations
* 🌐 Update source example highlights for `docs/zh/docs/tutorial/query-params-str-validations.md`. PR [#4237](https://github.com/tiangolo/fastapi/pull/4237) by [@caimaoy](https://github.com/caimaoy).
* 🌐 Remove translation docs references to aiofiles as it's no longer needed since AnyIO. PR [#3594](https://github.com/tiangolo/fastapi/pull/3594) by [@alonme](https://github.com/alonme).
* ✏ 🌐 Fix typo in Portuguese translation for `docs/pt/docs/tutorial/path-params.md`. PR [#4722](https://github.com/tiangolo/fastapi/pull/4722) by [@CleoMenezesJr](https://github.com/CleoMenezesJr).
* 🌐 Fix live docs server for translations for some languages. PR [#4729](https://github.com/tiangolo/fastapi/pull/4729) by [@wakabame](https://github.com/wakabame).
* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/cookie-params.md`. PR [#4112](https://github.com/tiangolo/fastapi/pull/4112) by [@lbmendes](https://github.com/lbmendes).
* 🌐 Fix French translation for `docs/tutorial/body.md`. PR [#4332](https://github.com/tiangolo/fastapi/pull/4332) by [@Smlep](https://github.com/Smlep).
* 🌐 Add Japanese translation for `docs/ja/docs/advanced/conditional-openapi.md`. PR [#2631](https://github.com/tiangolo/fastapi/pull/2631) by [@sh0nk](https://github.com/sh0nk).
* 🌐 Fix Japanese translation of `docs/ja/docs/tutorial/body.md`. PR [#3062](https://github.com/tiangolo/fastapi/pull/3062) by [@a-takahashi223](https://github.com/a-takahashi223).
* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/background-tasks.md`. PR [#2170](https://github.com/tiangolo/fastapi/pull/2170) by [@izaguerreiro](https://github.com/izaguerreiro).
* 🌐 Add Portuguese translation for `docs/deployment/deta.md`. PR [#4442](https://github.com/tiangolo/fastapi/pull/4442) by [@lsglucas](https://github.com/lsglucas).
* 🌐 Add Russian translation for `docs/async.md`. PR [#4036](https://github.com/tiangolo/fastapi/pull/4036) by [@Winand](https://github.com/Winand).
* 🌐 Add Portuguese translation for `docs/tutorial/body.md`. PR [#3960](https://github.com/tiangolo/fastapi/pull/3960) by [@leandrodesouzadev](https://github.com/leandrodesouzadev).
* 🌐 Add Portuguese translation of `tutorial/extra-data-types.md`. PR [#4077](https://github.com/tiangolo/fastapi/pull/4077) by [@luccasmmg](https://github.com/luccasmmg).
* 🌐 Update German translation for `docs/features.md`. PR [#3905](https://github.com/tiangolo/fastapi/pull/3905) by [@jomue](https://github.com/jomue).
## 0.76.0
### Upgrades
* ⬆ Upgrade Starlette from 0.17.1 to 0.18.0. PR [#4483](https://github.com/tiangolo/fastapi/pull/4483) by [@Kludex](https://github.com/Kludex).
### Internal
* 👥 Update FastAPI People. PR [#4847](https://github.com/tiangolo/fastapi/pull/4847) by [@github-actions[bot]](https://github.com/apps/github-actions).
* 🔧 Add Budget Insight sponsor. PR [#4824](https://github.com/tiangolo/fastapi/pull/4824) by [@tiangolo](https://github.com/tiangolo).
* 🍱 Update sponsor, ExoFlare badge. PR [#4822](https://github.com/tiangolo/fastapi/pull/4822) by [@tiangolo](https://github.com/tiangolo).
This release includes upgrades to third-party packages that handle security issues. Although there's a chance these issues don't affect you in particular, please upgrade as soon as possible.
This release includes upgrades to third-party packages that handle security issues. Although there's a chance these issues don't affect you in particular, please upgrade as soon as possible.
@ -89,7 +89,7 @@ You can see more details in <a href="https://www.starlette.io/background/" class
## Caveat
## Caveat
If you need to perform heavy background computation and you don't necessarily need it to be run by the same process (for example, you don't need to share memory, variables, etc), you might benefit from using other bigger tools like <ahref="https://docs.celeryproject.org"class="external-link"target="_blank">Celery</a>.
If you need to perform heavy background computation and you don't necessarily need it to be run by the same process (for example, you don't need to share memory, variables, etc), you might benefit from using other bigger tools like <ahref="https://docs.celeryq.dev"class="external-link"target="_blank">Celery</a>.
They tend to require more complex configurations, a message/job queue manager, like RabbitMQ or Redis, but they allow you to run background tasks in multiple processes, and especially, in multiple servers.
They tend to require more complex configurations, a message/job queue manager, like RabbitMQ or Redis, but they allow you to run background tasks in multiple processes, and especially, in multiple servers.
@ -57,6 +57,10 @@ You can declare extra information in `Field`, `Query`, `Body`, etc. And it will
You will learn more about adding extra information later in the docs, when learning to declare examples.
You will learn more about adding extra information later in the docs, when learning to declare examples.
!!! warning
Extra keys passed to `Field` will also be present in the resulting OpenAPI schema for your application.
As these keys may not necessarily be part of the OpenAPI specification, some OpenAPI tools, for example [the OpenAPI validator](https://validator.swagger.io/), may not work with your generated schema.
## Recap
## Recap
You can use Pydantic's `Field` to declare extra validations and metadata for model attributes.
You can use Pydantic's `Field` to declare extra validations and metadata for model attributes.
`Body` also has all the same extra validation and metadata parameters as `Query`,`Path` and others you will see later.
`Body` also has all the same extra validation and metadata parameters as `Query`,`Path` and others you will see later.
## Embed a single body parameter
## Embed a single body parameter
Let's say you only have a single `item` body parameter from a Pydantic model `Item`.
Let's say you only have a single `item` body parameter from a Pydantic model `Item`.
@ -162,7 +161,7 @@ By default, **FastAPI** will then expect its body directly.
But if you want it to expect a JSON with a key `item` and inside of it the model contents, as it does when you declare extra body parameters, you can use the special `Body` parameter `embed`:
But if you want it to expect a JSON with a key `item` and inside of it the model contents, as it does when you declare extra body parameters, you can use the special `Body` parameter `embed`:
@ -366,7 +366,7 @@ In this case, you would accept any `dict` as long as it has `int` keys with `flo
But Pydantic has automatic data conversion.
But Pydantic has automatic data conversion.
This means that, even though your API clients can only send strings as keys, as long as those strings contain pure integers, Pydantic will convert them and validate them.
This means that, even though your API clients can only send strings as keys, as long as those strings contain pure integers, Pydantic will convert them and validate them.
And the `dict` you receive as `weights` will actually have `int` keys and `float` values.
And the `dict` you receive as `weights` will actually have `int` keys and `float` values.
@ -138,7 +138,7 @@ But you would get the same editor support with <a href="https://www.jetbrains.co
If you use <ahref="https://www.jetbrains.com/pycharm/"class="external-link"target="_blank">PyCharm</a> as your editor, you can use the <ahref="https://github.com/koxudaxi/pydantic-pycharm-plugin/"class="external-link"target="_blank">Pydantic PyCharm Plugin</a>.
If you use <ahref="https://www.jetbrains.com/pycharm/"class="external-link"target="_blank">PyCharm</a> as your editor, you can use the <ahref="https://github.com/koxudaxi/pydantic-pycharm-plugin/"class="external-link"target="_blank">Pydantic PyCharm Plugin</a>.
It improves editor support for Pydantic models, with:
It improves editor support for Pydantic models, with:
* auto-completion
* auto-completion
* type checks
* type checks
* refactoring
* refactoring
@ -206,7 +206,7 @@ The function parameters will be recognized as follows:
!!! note
!!! note
FastAPI will know that the value of `q` is not required because of the default value `= None`.
FastAPI will know that the value of `q` is not required because of the default value `= None`.
The `Optional` in `Optional[str]` is not used by FastAPI, but will allow your editor to give you better support and detect errors.
The `Union` in `Union[str, None]` is not used by FastAPI, but will allow your editor to give you better support and detect errors.
@ -10,7 +10,7 @@ To do this, use `yield` instead of `return`, and write the extra steps after.
!!! note "Technical Details"
!!! note "Technical Details"
Any function that is valid to use with:
Any function that is valid to use with:
* <ahref="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager"class="external-link"target="_blank">`@contextlib.contextmanager`</a> or
* <ahref="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager"class="external-link"target="_blank">`@contextlib.contextmanager`</a> or
would be valid to use as a **FastAPI** dependency.
would be valid to use as a **FastAPI** dependency.
@ -207,7 +207,7 @@ You can also use them inside of **FastAPI** dependencies with `yield` by using
!!! tip
!!! tip
Another way to create a context manager is with:
Another way to create a context manager is with:
* <ahref="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager"class="external-link"target="_blank">`@contextlib.contextmanager`</a> or
* <ahref="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager"class="external-link"target="_blank">`@contextlib.contextmanager`</a> or
@ -36,7 +36,7 @@ Here are some of the additional data types you can use:
* `datetime.timedelta`:
* `datetime.timedelta`:
* A Python `datetime.timedelta`.
* A Python `datetime.timedelta`.
* In requests and responses will be represented as a `float` of total seconds.
* In requests and responses will be represented as a `float` of total seconds.
* Pydantic also allows representing it as a "ISO 8601 time diff encoding", <ahref="https://pydantic-docs.helpmanual.io/#json-serialisation"class="external-link"target="_blank">see the docs for more info</a>.
* Pydantic also allows representing it as a "ISO 8601 time diff encoding", <ahref="https://pydantic-docs.helpmanual.io/usage/exporting_models/#json_encoders"class="external-link"target="_blank">see the docs for more info</a>.
* `frozenset`:
* `frozenset`:
* In requests and responses, treated the same as a `set`:
* In requests and responses, treated the same as a `set`:
* In requests, a list will be read, eliminating duplicates and converting it to a `set`.
* In requests, a list will be read, eliminating duplicates and converting it to a `set`.
These are technical details that you might skip if it's not important for you now.
These are technical details that you might skip if it's not important for you now.
`RequestValidationError` is a sub-class of Pydantic's <ahref="https://pydantic-docs.helpmanual.io/#error-handling"class="external-link"target="_blank">`ValidationError`</a>.
`RequestValidationError` is a sub-class of Pydantic's <ahref="https://pydantic-docs.helpmanual.io/usage/models/#error-handling"class="external-link"target="_blank">`ValidationError`</a>.
**FastAPI** uses it so that, if you use a Pydantic model in `response_model`, and your data has an error, you will see the error in your log.
**FastAPI** uses it so that, if you use a Pydantic model in `response_model`, and your data has an error, you will see the error in your log.
@ -71,7 +71,7 @@ Pass `*`, as the first parameter of the function.
Python won't do anything with that `*`, but it will know that all the following parameters should be called as keyword arguments (key-value pairs), also known as <abbrtitle="From: K-ey W-ord Arg-uments"><code>kwargs</code></abbr>. Even if they don't have a default value.
Python won't do anything with that `*`, but it will know that all the following parameters should be called as keyword arguments (key-value pairs), also known as <abbrtitle="From: K-ey W-ord Arg-uments"><code>kwargs</code></abbr>. Even if they don't have a default value.
@ -115,6 +115,14 @@ Because *path operations* are evaluated in order, you need to make sure that the
Otherwise, the path for `/users/{user_id}` would match also for `/users/me`, "thinking" that it's receiving a parameter `user_id` with a value of `"me"`.
Otherwise, the path for `/users/{user_id}` would match also for `/users/me`, "thinking" that it's receiving a parameter `user_id` with a value of `"me"`.
Similarly, you cannot redefine a path operation:
```Python hl_lines="6 11"
{!../../../docs_src/path_params/tutorial003b.py!}
```
The first one will always be used since the path matches first.
## Predefined values
## Predefined values
If you have a *path operation* that receives a *path parameter*, but you want the possible valid *path parameter* values to be predefined, you can use a standard Python <abbrtitle="Enumeration">`Enum`</abbr>.
If you have a *path operation* that receives a *path parameter*, but you want the possible valid *path parameter* values to be predefined, you can use a standard Python <abbrtitle="Enumeration">`Enum`</abbr>.
The query parameter `q` is of type `Optional[str]` (or `str | None` in Python 3.10), that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required.
The query parameter `q` is of type `Union[str, None]` (or `str | None` in Python 3.10), that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required.
!!! note
!!! note
FastAPI will know that the value of `q` is not required because of the default value `= None`.
FastAPI will know that the value of `q` is not required because of the default value `= None`.
The `Optional` in `Optional[str]` is not used by FastAPI, but will allow your editor to give you better support and detect errors.
The `Union` in `Union[str, None]` will allow your editor to give you better support and detect errors.
## Additional validation
## Additional validation
@ -59,24 +59,24 @@ And now use it as the default value of your parameter, setting the parameter `ma
As we have to replace the default value `None`with `Query(None)`, the first parameter to `Query` serves the same purpose of defining that default value.
As we have to replace the default value `None`in the function with `Query()`, we can now set the default value with the parameter `Query(default=None)`, it serves the same purpose of defining that default value.
So:
So:
```Python
```Python
q: Optional[str] = Query(None)
q: Union[str, None] = Query(default=None)
```
```
...makes the parameter optional, the same as:
...makes the parameter optional, the same as:
```Python
```Python
q: Optional[str] = None
q: Union[str, None] = None
```
```
And in Python 3.10 and above:
And in Python 3.10 and above:
```Python
```Python
q: str | None = Query(None)
q: str | None = Query(default=None)
```
```
...makes the parameter optional, the same as:
...makes the parameter optional, the same as:
@ -97,17 +97,17 @@ But it declares it explicitly as being a query parameter.
or the:
or the:
```Python
```Python
= Query(None)
= Query(default=None)
```
```
as it will use that `None` as the default value, and that way make the parameter **not required**.
as it will use that `None` as the default value, and that way make the parameter **not required**.
The `Optional` part allows your editor to provide better support, but it is not what tells FastAPI that this parameter is not required.
The `Union[str, None]` part allows your editor to provide better support, but it is not what tells FastAPI that this parameter is not required.
Then, we can pass more parameters to `Query`. In this case, the `max_length` parameter that applies to strings:
Then, we can pass more parameters to `Query`. In this case, the `max_length` parameter that applies to strings:
If you hadn't seen that `...` before: it is a special single value, it is <ahref="https://docs.python.org/3/library/constants.html#Ellipsis"class="external-link"target="_blank">part of Python and is called "Ellipsis"</a>.
If you hadn't seen that `...` before: it is a special single value, it is <ahref="https://docs.python.org/3/library/constants.html#Ellipsis"class="external-link"target="_blank">part of Python and is called "Ellipsis"</a>.
It is used by Pydantic and FastAPI to explicitly declare that a value is required.
This will let **FastAPI** know that this parameter is required.
This will let **FastAPI** know that this parameter is required.
### Required with `None`
You can declare that a parameter can accept `None`, but that it's still required. This would force clients to send a value, even if the value is `None`.
To do that, you can declare that `None` is a valid type but still use `default=...`:
Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <ahref="https://pydantic-docs.helpmanual.io/usage/models/#required-optional-fields"class="external-link"target="_blank">Required Optional fields</a>.
### Use Pydantic's `Required` instead of Ellipsis (`...`)
If you feel uncomfortable using `...`, you can also import and use `Required` from Pydantic:
Remember that in most of the cases, when something is required, you can simply omit the `default` parameter, so you normally don't have to use `...` nor `Required`.
## Query parameter list / multiple values
## Query parameter list / multiple values
When you define a query parameter explicitly with `Query` you can also declare it to receive a list of values, or said in other way, to receive multiple values.
When you define a query parameter explicitly with `Query` you can also declare it to receive a list of values, or said in other way, to receive multiple values.
@ -106,7 +106,7 @@ The way HTML forms (`<form></form>`) sends the data to the server normally uses
Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded` when it doesn't include files.
Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded` when it doesn't include files.
But when the form includes files, it is encoded as `multipart/form-data`. If you use `File`, **FastAPI** will know it has to get the files from the correct part of the body.
But when the form includes files, it is encoded as `multipart/form-data`. If you use `File`, **FastAPI** will know it has to get the files from the correct part of the body.
If you want to read more about these encodings and form fields, head to the <ahref="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST"class="external-link"target="_blank"><abbrtitle="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a>.
If you want to read more about these encodings and form fields, head to the <ahref="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST"class="external-link"target="_blank"><abbrtitle="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a>.
@ -45,7 +45,7 @@ The way HTML forms (`<form></form>`) sends the data to the server normally uses
Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded`.
Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded`.
But when the form includes files, it is encoded as `multipart/form-data`. You'll read about handling files in the next chapter.
But when the form includes files, it is encoded as `multipart/form-data`. You'll read about handling files in the next chapter.
If you want to read more about these encodings and form fields, head to the <ahref="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST"class="external-link"target="_blank"><abbrtitle="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a>.
If you want to read more about these encodings and form fields, head to the <ahref="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST"class="external-link"target="_blank"><abbrtitle="Mozilla Developer Network">MDN</abbr> web docs for <code>POST</code></a>.
@ -121,7 +121,7 @@ When we create an instance of the `OAuth2PasswordBearer` class we pass in the `t
```
```
!!! tip
!!! tip
here `tokenUrl="token"` refers to a relative URL `token` that we haven't created yet. As it's a relative URL, it's equivalent to `./token`.
Here `tokenUrl="token"` refers to a relative URL `token` that we haven't created yet. As it's a relative URL, it's equivalent to `./token`.
Because we are using a relative URL, if your API was located at `https://example.com/`, then it would refer to `https://example.com/token`. But if your API was located at `https://example.com/api/v1/`, then it would refer to `https://example.com/api/v1/token`.
Because we are using a relative URL, if your API was located at `https://example.com/`, then it would refer to `https://example.com/token`. But if your API was located at `https://example.com/api/v1/`, then it would refer to `https://example.com/api/v1/token`.
@ -317,7 +317,7 @@ Not only the IDs of those items, but all the data that we defined in the Pydanti
Now, in the Pydantic *models* for reading, `Item` and `User`, add an internal `Config` class.
Now, in the Pydantic *models* for reading, `Item` and `User`, add an internal `Config` class.
This <ahref="https://pydantic-docs.helpmanual.io/#config"class="external-link"target="_blank">`Config`</a> class is used to provide configurations to Pydantic.
This <ahref="https://pydantic-docs.helpmanual.io/usage/model_config/"class="external-link"target="_blank">`Config`</a> class is used to provide configurations to Pydantic.
In the `Config` class, set the attribute `orm_mode = True`.
In the `Config` class, set the attribute `orm_mode = True`.
@ -491,7 +491,7 @@ You can find an example of Alembic in a FastAPI project in the templates from [P
### Create a dependency
### Create a dependency
Now use the `SessionLocal` class we created in the `sql_app/databases.py` file to create a dependency.
Now use the `SessionLocal` class we created in the `sql_app/database.py` file to create a dependency.
We need to have an independent database session/connection (`SessionLocal`) per request, use the same session through all the request and then close it after the request is finished.
We need to have an independent database session/connection (`SessionLocal`) per request, use the same session through all the request and then close it after the request is finished.
@ -616,7 +616,7 @@ And as the code related to SQLAlchemy and the SQLAlchemy models lives in separat
The same way, you would be able to use the same SQLAlchemy models and utilities in other parts of your code that are not related to **FastAPI**.
The same way, you would be able to use the same SQLAlchemy models and utilities in other parts of your code that are not related to **FastAPI**.
For example, in a background task worker with <ahref="https://docs.celeryproject.org"class="external-link"target="_blank">Celery</a>, <ahref="https://python-rq.org/"class="external-link"target="_blank">RQ</a>, or <ahref="https://arq-docs.helpmanual.io/"class="external-link"target="_blank">ARQ</a>.
For example, in a background task worker with <ahref="https://docs.celeryq.dev"class="external-link"target="_blank">Celery</a>, <ahref="https://python-rq.org/"class="external-link"target="_blank">RQ</a>, or <ahref="https://arq-docs.helpmanual.io/"class="external-link"target="_blank">ARQ</a>.
<atitle="Jina: build neural search-as-a-service for any kind of data in just minutes."style="display: block; position: relative;"href="https://bit.ly/2QSouzH"target="_blank">
<atitle="DiscoArt: Create compelling Disco Diffusion artworks in just one line"style="display: block; position: relative;"href="https://bit.ly/3PjOZqc"target="_blank">
<atitle="Join the team building a new SaaS platform that will change the computing world"style="display: block; position: relative;"href="https://classiq.link/mzg"target="_blank">
<atitle="The ultimate solution to unlimited and forever cloud storage."style="display: block; position: relative;"href="https://app.imgwhale.xyz/"target="_blank">
<atitle="Help us migrate doist to FastAPI"style="display: block; position: relative;"href="https://doist.com/careers/9B437B1615-wa-senior-backend-engineer-python"target="_blank">
@ -191,7 +191,7 @@ Con **FastAPI** obtienes todas las características de **Pydantic** (dado que Fa
* Interactúa bien con tu **<abbrtitle="en inglés: Integrated Development Environment, similar a editor de código">IDE</abbr>/<abbrtitle="Un programa que chequea errores en el código">linter</abbr>/cerebro**:
* Interactúa bien con tu **<abbrtitle="en inglés: Integrated Development Environment, similar a editor de código">IDE</abbr>/<abbrtitle="Un programa que chequea errores en el código">linter</abbr>/cerebro**:
* Porque las estructuras de datos de Pydantic son solo <abbrtitle='En español: ejemplares. Aunque a veces los llaman incorrectamente "instancias"'>instances</abbr> de clases que tu defines, el auto-completado, el linting, mypy y tu intuición deberían funcionar bien con tus datos validados.
* Porque las estructuras de datos de Pydantic son solo <abbrtitle='En español: ejemplares. Aunque a veces los llaman incorrectamente "instancias"'>instances</abbr> de clases que tu defines, el auto-completado, el linting, mypy y tu intuición deberían funcionar bien con tus datos validados.
* **Rápido**:
* **Rápido**:
* En <ahref="https://pydantic-docs.helpmanual.io/#benchmarks-tag"class="external-link"target="_blank">benchmarks</a> Pydantic es más rápido que todas las otras <abbrtitle='Herramienta, paquete. A veces llamado "librería"'>libraries</abbr> probadas.
* En <ahref="https://pydantic-docs.helpmanual.io/benchmarks/"class="external-link"target="_blank">benchmarks</a> Pydantic es más rápido que todas las otras <abbrtitle='Herramienta, paquete. A veces llamado "librería"'>libraries</abbr> probadas.
* Valida **estructuras complejas**:
* Valida **estructuras complejas**:
* Usa modelos jerárquicos de modelos de Pydantic, `typing` de Python, `List` y `Dict`, etc.
* Usa modelos jerárquicos de modelos de Pydantic, `typing` de Python, `List` y `Dict`, etc.
* Los validadores también permiten que se definan fácil y claramente schemas complejos de datos. Estos son chequeados y documentados como JSON Schema.
* Los validadores también permiten que se definan fácil y claramente schemas complejos de datos. Estos son chequeados y documentados como JSON Schema.
* <ahref="https://requests.readthedocs.io"target="_blank"><code>requests</code></a> - Requerido si quieres usar el `TestClient`.
* <ahref="https://requests.readthedocs.io"target="_blank"><code>requests</code></a> - Requerido si quieres usar el `TestClient`.
* <ahref="https://github.com/Tinche/aiofiles"target="_blank"><code>aiofiles</code></a> - Requerido si quieres usar `FileResponse` o `StaticFiles`.
* <ahref="https://jinja.palletsprojects.com"target="_blank"><code>jinja2</code></a> - Requerido si quieres usar la configuración por defecto de templates.
* <ahref="https://jinja.palletsprojects.com"target="_blank"><code>jinja2</code></a> - Requerido si quieres usar la configuración por defecto de templates.
* <ahref="https://andrew-d.github.io/python-multipart/"target="_blank"><code>python-multipart</code></a> - Requerido si quieres dar soporte a <abbrtitle="convertir el string que viene de un HTTP request a datos de Python">"parsing"</abbr> de formularios, con `request.form()`.
* <ahref="https://andrew-d.github.io/python-multipart/"target="_blank"><code>python-multipart</code></a> - Requerido si quieres dar soporte a <abbrtitle="convertir el string que viene de un HTTP request a datos de Python">"parsing"</abbr> de formularios, con `request.form()`.
* <ahref="https://pythonhosted.org/itsdangerous/"target="_blank"><code>itsdangerous</code></a> - Requerido para dar soporte a `SessionMiddleware`.
* <ahref="https://pythonhosted.org/itsdangerous/"target="_blank"><code>itsdangerous</code></a> - Requerido para dar soporte a `SessionMiddleware`.
Some files were not shown because too many files changed in this diff