Browse Source

Merge branch 'master' into feat/exception-on-duplicate-path

pull/5595/head
Irfanuddin Shafi Ahmed 1 year ago
committed by GitHub
parent
commit
33e9b50dd0
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 6
      .github/dependabot.yml
  2. 4
      .github/workflows/build-docs.yml
  3. 2
      .github/workflows/deploy-docs.yml
  4. 4
      .github/workflows/issue-manager.yml
  5. 4
      .github/workflows/publish.yml
  6. 4
      .github/workflows/smokeshow.yml
  7. 6
      .github/workflows/test.yml
  8. 126
      docs/de/docs/tutorial/background-tasks.md
  9. 10
      docs/de/docs/tutorial/first-steps.md
  10. 80
      docs/de/docs/tutorial/index.md
  11. 6
      docs/em/docs/advanced/security/oauth2-scopes.md
  12. 4
      docs/em/docs/tutorial/security/oauth2-jwt.md
  13. 2
      docs/em/docs/tutorial/sql-databases.md
  14. 36
      docs/en/data/external_links.yml
  15. 2
      docs/en/docs/advanced/additional-responses.md
  16. 2
      docs/en/docs/advanced/async-tests.md
  17. 4
      docs/en/docs/advanced/behind-a-proxy.md
  18. 2
      docs/en/docs/advanced/custom-response.md
  19. 2
      docs/en/docs/advanced/dataclasses.md
  20. 4
      docs/en/docs/advanced/events.md
  21. 2
      docs/en/docs/advanced/path-operation-advanced-configuration.md
  22. 2
      docs/en/docs/advanced/response-change-status-code.md
  23. 2
      docs/en/docs/advanced/response-cookies.md
  24. 2
      docs/en/docs/advanced/response-headers.md
  25. 18
      docs/en/docs/advanced/security/oauth2-scopes.md
  26. 48
      docs/en/docs/advanced/templates.md
  27. 2
      docs/en/docs/advanced/websockets.md
  28. 2
      docs/en/docs/benchmarks.md
  29. 71
      docs/en/docs/contributing.md
  30. 4
      docs/en/docs/deployment/concepts.md
  31. 2
      docs/en/docs/deployment/https.md
  32. 4
      docs/en/docs/deployment/index.md
  33. 4
      docs/en/docs/deployment/manually.md
  34. 6
      docs/en/docs/help-fastapi.md
  35. 5
      docs/en/docs/how-to/async-sql-encode-databases.md
  36. 5
      docs/en/docs/how-to/nosql-databases-couchbase.md
  37. 9
      docs/en/docs/how-to/sql-databases-peewee.md
  38. 67
      docs/en/docs/release-notes.md
  39. 2
      docs/en/docs/tutorial/bigger-applications.md
  40. 2
      docs/en/docs/tutorial/body-nested-models.md
  41. 4
      docs/en/docs/tutorial/handling-errors.md
  42. 2
      docs/en/docs/tutorial/middleware.md
  43. 4
      docs/en/docs/tutorial/path-params-numeric-validations.md
  44. 8
      docs/en/docs/tutorial/query-params-str-validations.md
  45. 2
      docs/en/docs/tutorial/request-files.md
  46. 2
      docs/en/docs/tutorial/security/get-current-user.md
  47. 6
      docs/en/docs/tutorial/security/oauth2-jwt.md
  48. 4
      docs/en/docs/tutorial/sql-databases.md
  49. 2
      docs/en/docs/tutorial/static-files.md
  50. 7
      docs/en/mkdocs.yml
  51. 2
      docs/es/docs/advanced/additional-status-codes.md
  52. 2
      docs/es/docs/advanced/response-directly.md
  53. 14
      docs/es/docs/features.md
  54. 8
      docs/es/docs/index.md
  55. 16
      docs/es/docs/python-types.md
  56. 2
      docs/es/docs/tutorial/first-steps.md
  57. 2
      docs/es/docs/tutorial/index.md
  58. 6
      docs/es/docs/tutorial/path-params.md
  59. 315
      docs/ja/docs/python-types.md
  60. 94
      docs/ja/docs/tutorial/background-tasks.md
  61. 48
      docs/ja/docs/tutorial/body-fields.md
  62. 169
      docs/ja/docs/tutorial/body-multiple-params.md
  63. 244
      docs/ja/docs/tutorial/body-nested-models.md
  64. 191
      docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md
  65. 62
      docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
  66. 225
      docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md
  67. 209
      docs/ja/docs/tutorial/dependencies/index.md
  68. 86
      docs/ja/docs/tutorial/dependencies/sub-dependencies.md
  69. 195
      docs/ja/docs/tutorial/extra-models.md
  70. 265
      docs/ja/docs/tutorial/handling-errors.md
  71. 122
      docs/ja/docs/tutorial/path-params-numeric-validations.md
  72. 208
      docs/ja/docs/tutorial/response-model.md
  73. 89
      docs/ja/docs/tutorial/response-status-code.md
  74. 58
      docs/ja/docs/tutorial/schema-extra-example.md
  75. 2
      docs/ja/docs/tutorial/security/oauth2-jwt.md
  76. 2
      docs/ko/docs/tutorial/path-params.md
  77. 1
      docs/language_names.yml
  78. 2
      docs/ru/docs/index.md
  79. 478
      docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md
  80. 4
      docs/zh/docs/tutorial/extra-data-types.md
  81. 2
      docs/zh/docs/tutorial/security/oauth2-jwt.md
  82. 2
      docs/zh/docs/tutorial/sql-databases.md
  83. 8
      docs_src/security/tutorial004.py
  84. 6
      docs_src/security/tutorial004_an.py
  85. 6
      docs_src/security/tutorial004_an_py310.py
  86. 6
      docs_src/security/tutorial004_an_py39.py
  87. 8
      docs_src/security/tutorial004_py310.py
  88. 8
      docs_src/security/tutorial005.py
  89. 6
      docs_src/security/tutorial005_an.py
  90. 6
      docs_src/security/tutorial005_an_py310.py
  91. 6
      docs_src/security/tutorial005_an_py39.py
  92. 8
      docs_src/security/tutorial005_py310.py
  93. 8
      docs_src/security/tutorial005_py39.py
  94. 2
      docs_src/templates/templates/item.html
  95. 2
      fastapi/security/oauth2.py
  96. 10
      fastapi/utils.py
  97. 5
      pyproject.toml
  98. 9
      scripts/docs.py
  99. 9
      tests/test_generate_unique_id_function.py
  100. 8
      tests/test_tutorial/test_header_params/test_tutorial003.py

6
.github/dependabot.yml

@ -11,6 +11,10 @@ updates:
- package-ecosystem: "pip"
directory: "/"
schedule:
interval: "daily"
interval: "monthly"
groups:
python-packages:
patterns:
- "*"
commit-message:
prefix:

4
.github/workflows/build-docs.yml

@ -39,7 +39,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: "3.11"
- uses: actions/cache@v3
@ -80,7 +80,7 @@ jobs:
run: echo "$GITHUB_CONTEXT"
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: "3.11"
- uses: actions/cache@v3

2
.github/workflows/deploy-docs.yml

@ -21,7 +21,7 @@ jobs:
mkdir ./site
- name: Download Artifact Docs
id: download
uses: dawidd6/action-download-artifact@v2.28.0
uses: dawidd6/action-download-artifact@v3.0.0
with:
if_no_artifact_found: ignore
github_token: ${{ secrets.FASTAPI_PREVIEW_DOCS_DOWNLOAD_ARTIFACTS }}

4
.github/workflows/issue-manager.yml

@ -31,5 +31,9 @@ jobs:
"answered": {
"delay": 864000,
"message": "Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs."
},
"changes-requested": {
"delay": 2628000,
"message": "As this PR had requested changes to be applied but has been inactive for a while, it's now going to be closed. But if there's anyone interested, feel free to create a new PR."
}
}

4
.github/workflows/publish.yml

@ -15,7 +15,7 @@ jobs:
run: echo "$GITHUB_CONTEXT"
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: "3.10"
# Issue ref: https://github.com/actions/setup-python/issues/436
@ -32,7 +32,7 @@ jobs:
- name: Build distribution
run: python -m build
- name: Publish
uses: pypa/[email protected]0
uses: pypa/[email protected]1
with:
password: ${{ secrets.PYPI_API_TOKEN }}
- name: Dump GitHub context

4
.github/workflows/smokeshow.yml

@ -18,13 +18,13 @@ jobs:
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- uses: actions/setup-python@v4
- uses: actions/setup-python@v5
with:
python-version: '3.9'
- run: pip install smokeshow
- uses: dawidd6/action-download-artifact@v2.28.0
- uses: dawidd6/action-download-artifact@v3.0.0
with:
github_token: ${{ secrets.FASTAPI_SMOKESHOW_DOWNLOAD_ARTIFACTS }}
workflow: test.yml

6
.github/workflows/test.yml

@ -19,7 +19,7 @@ jobs:
run: echo "$GITHUB_CONTEXT"
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: "3.11"
# Issue ref: https://github.com/actions/setup-python/issues/436
@ -57,7 +57,7 @@ jobs:
run: echo "$GITHUB_CONTEXT"
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
# Issue ref: https://github.com/actions/setup-python/issues/436
@ -98,7 +98,7 @@ jobs:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- uses: actions/checkout@v4
- uses: actions/setup-python@v4
- uses: actions/setup-python@v5
with:
python-version: '3.8'
# Issue ref: https://github.com/actions/setup-python/issues/436

126
docs/de/docs/tutorial/background-tasks.md

@ -0,0 +1,126 @@
# Hintergrundtasks
Sie können Hintergrundtasks (Hintergrund-Aufgaben) definieren, die *nach* der Rückgabe einer Response ausgeführt werden sollen.
Das ist nützlich für Vorgänge, die nach einem Request ausgeführt werden müssen, bei denen der Client jedoch nicht unbedingt auf den Abschluss des Vorgangs warten muss, bevor er die Response erhält.
Hierzu zählen beispielsweise:
* E-Mail-Benachrichtigungen, die nach dem Ausführen einer Aktion gesendet werden:
* Da die Verbindung zu einem E-Mail-Server und das Senden einer E-Mail in der Regel „langsam“ ist (einige Sekunden), können Sie die Response sofort zurücksenden und die E-Mail-Benachrichtigung im Hintergrund senden.
* Daten verarbeiten:
* Angenommen, Sie erhalten eine Datei, die einen langsamen Prozess durchlaufen muss. Sie können als Response „Accepted“ (HTTP 202) zurückgeben und die Datei im Hintergrund verarbeiten.
## `BackgroundTasks` verwenden
Importieren Sie zunächst `BackgroundTasks` und definieren Sie einen Parameter in Ihrer *Pfadoperation-Funktion* mit der Typdeklaration `BackgroundTasks`:
```Python hl_lines="1 13"
{!../../../docs_src/background_tasks/tutorial001.py!}
```
**FastAPI** erstellt für Sie das Objekt vom Typ `BackgroundTasks` und übergibt es als diesen Parameter.
## Eine Taskfunktion erstellen
Erstellen Sie eine Funktion, die als Hintergrundtask ausgeführt werden soll.
Es handelt sich schlicht um eine Standard-Funktion, die Parameter empfangen kann.
Es kann sich um eine `async def`- oder normale `def`-Funktion handeln. **FastAPI** weiß, wie damit zu verfahren ist.
In diesem Fall schreibt die Taskfunktion in eine Datei (den Versand einer E-Mail simulierend).
Und da der Schreibvorgang nicht `async` und `await` verwendet, definieren wir die Funktion mit normalem `def`:
```Python hl_lines="6-9"
{!../../../docs_src/background_tasks/tutorial001.py!}
```
## Den Hintergrundtask hinzufügen
Übergeben Sie innerhalb Ihrer *Pfadoperation-Funktion* Ihre Taskfunktion mit der Methode `.add_task()` an das *Hintergrundtasks*-Objekt:
```Python hl_lines="14"
{!../../../docs_src/background_tasks/tutorial001.py!}
```
`.add_task()` erhält als Argumente:
* Eine Taskfunktion, die im Hintergrund ausgeführt wird (`write_notification`).
* Eine beliebige Folge von Argumenten, die der Reihe nach an die Taskfunktion übergeben werden sollen (`email`).
* Alle Schlüsselwort-Argumente, die an die Taskfunktion übergeben werden sollen (`message="some notification"`).
## Dependency Injection
Die Verwendung von `BackgroundTasks` funktioniert auch mit dem <abbr title="Einbringen von Abhängigkeiten">Dependency Injection</abbr> System. Sie können einen Parameter vom Typ `BackgroundTasks` auf mehreren Ebenen deklarieren: in einer *Pfadoperation-Funktion*, in einer Abhängigkeit (Dependable), in einer Unterabhängigkeit usw.
**FastAPI** weiß, was jeweils zu tun ist und wie dasselbe Objekt wiederverwendet werden kann, sodass alle Hintergrundtasks zusammengeführt und anschließend im Hintergrund ausgeführt werden:
=== "Python 3.10+"
```Python hl_lines="13 15 22 25"
{!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!}
```
=== "Python 3.9+"
```Python hl_lines="13 15 22 25"
{!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!}
```
=== "Python 3.8+"
```Python hl_lines="14 16 23 26"
{!> ../../../docs_src/background_tasks/tutorial002_an.py!}
```
=== "Python 3.10+ nicht annotiert"
!!! tip "Tipp"
Bevorzugen Sie die `Annotated`-Version, falls möglich.
```Python hl_lines="11 13 20 23"
{!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
```
=== "Python 3.8+ nicht annotiert"
!!! tip "Tipp"
Bevorzugen Sie die `Annotated`-Version, falls möglich.
```Python hl_lines="13 15 22 25"
{!> ../../../docs_src/background_tasks/tutorial002.py!}
```
In obigem Beispiel werden die Nachrichten, *nachdem* die Response gesendet wurde, in die Datei `log.txt` geschrieben.
Wenn im Request ein Query-Parameter enthalten war, wird dieser in einem Hintergrundtask in das Log geschrieben.
Und dann schreibt ein weiterer Hintergrundtask, der in der *Pfadoperation-Funktion* erstellt wird, eine Nachricht unter Verwendung des Pfad-Parameters `email`.
## Technische Details
Die Klasse `BackgroundTasks` stammt direkt von <a href="https://www.starlette.io/background/" class="external-link" target="_blank">`starlette.background`</a>.
Sie wird direkt in FastAPI importiert/inkludiert, sodass Sie sie von `fastapi` importieren können und vermeiden, versehentlich das alternative `BackgroundTask` (ohne das `s` am Ende) von `starlette.background` zu importieren.
Indem Sie nur `BackgroundTasks` (und nicht `BackgroundTask`) verwenden, ist es dann möglich, es als *Pfadoperation-Funktion*-Parameter zu verwenden und **FastAPI** den Rest für Sie erledigen zu lassen, genau wie bei der direkten Verwendung des `Request`-Objekts.
Es ist immer noch möglich, `BackgroundTask` allein in FastAPI zu verwenden, aber Sie müssen das Objekt in Ihrem Code erstellen und eine Starlette-`Response` zurückgeben, die es enthält.
Weitere Details finden Sie in der <a href="https://www.starlette.io/background/" class="external-link" target="_blank">offiziellen Starlette-Dokumentation für Hintergrundtasks</a>.
## Vorbehalt
Wenn Sie umfangreiche Hintergrundberechnungen durchführen müssen und diese nicht unbedingt vom selben Prozess ausgeführt werden müssen (z. B. müssen Sie Speicher, Variablen, usw. nicht gemeinsam nutzen), könnte die Verwendung anderer größerer Tools wie z. B. <a href="https://docs.celeryq.dev" class="external-link" target="_blank">Celery</a> von Vorteil sein.
Sie erfordern in der Regel komplexere Konfigurationen und einen Nachrichten-/Job-Queue-Manager wie RabbitMQ oder Redis, ermöglichen Ihnen jedoch die Ausführung von Hintergrundtasks in mehreren Prozessen und insbesondere auf mehreren Servern.
Um ein Beispiel zu sehen, sehen Sie sich die [Projektgeneratoren](../project-generation.md){.internal-link target=_blank} an. Sie alle enthalten Celery, bereits konfiguriert.
Wenn Sie jedoch über dieselbe **FastAPI**-Anwendung auf Variablen und Objekte zugreifen oder kleine Hintergrundtasks ausführen müssen (z. B. das Senden einer E-Mail-Benachrichtigung), können Sie einfach `BackgroundTasks` verwenden.
## Zusammenfassung
Importieren und verwenden Sie `BackgroundTasks` mit Parametern in *Pfadoperation-Funktionen* und Abhängigkeiten, um Hintergrundtasks hinzuzufügen.

10
docs/de/docs/tutorial/first-steps.md

@ -43,7 +43,7 @@ Diese Zeile zeigt die URL, unter der Ihre Anwendung auf Ihrem lokalen Computer b
Öffnen Sie Ihren Browser unter <a href="http://127.0.0.1:8000" class="external-link" target="_blank">http://127.0.0.1:8000.</a>
Sie werden folgende JSON-Antwort sehen:
Sie werden folgende JSON-Response sehen:
```JSON
{"message": "Hello World"}
@ -81,7 +81,7 @@ Diese Schemadefinition enthält Ihre API-Pfade, die möglichen Parameter, welche
#### Daten-„Schema“
Der Begriff „Schema“ kann sich auch auf die Form von Daten beziehen, wie z.B. einen JSON-Inhalt.
Der Begriff „Schema“ kann sich auch auf die Form von Daten beziehen, wie z. B. einen JSON-Inhalt.
In diesem Fall sind die JSON-Attribute und deren Datentypen, usw. gemeint.
@ -328,6 +328,6 @@ Es gibt viele andere Objekte und Modelle, die automatisch zu JSON konvertiert we
* Importieren Sie `FastAPI`.
* Erstellen Sie eine `app` Instanz.
* Schreiben Sie einen **Pfadoperation-Dekorator** (wie z.B. `@app.get("/")`).
* Schreiben Sie eine **Pfadoperation-Funktion** (wie z.B. oben `def root(): ...`).
* Starten Sie den Entwicklungsserver (z.B. `uvicorn main:app --reload`).
* Schreiben Sie einen **Pfadoperation-Dekorator** (wie z. B. `@app.get("/")`).
* Schreiben Sie eine **Pfadoperation-Funktion** (wie z. B. oben `def root(): ...`).
* Starten Sie den Entwicklungsserver (z. B. `uvicorn main:app --reload`).

80
docs/de/docs/tutorial/index.md

@ -0,0 +1,80 @@
# Tutorial – Benutzerhandbuch
Dieses Tutorial zeigt Ihnen Schritt für Schritt, wie Sie **FastAPI** und die meisten seiner Funktionen verwenden können.
Jeder Abschnitt baut schrittweise auf den vorhergehenden auf. Diese Abschnitte sind aber nach einzelnen Themen gegliedert, sodass Sie direkt zu einem bestimmten Thema übergehen können, um Ihre speziellen API-Anforderungen zu lösen.
Außerdem dienen diese als zukünftige Referenz.
Dadurch können Sie jederzeit zurückkommen und sehen genau das, was Sie benötigen.
## Den Code ausführen
Alle Codeblöcke können kopiert und direkt verwendet werden (da es sich um getestete Python-Dateien handelt).
Um eines der Beispiele auszuführen, kopieren Sie den Code in eine Datei `main.py`, und starten Sie `uvicorn` mit:
<div class="termy">
```console
$ uvicorn main:app --reload
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
<span style="color: green;">INFO</span>: Started reloader process [28720]
<span style="color: green;">INFO</span>: Started server process [28722]
<span style="color: green;">INFO</span>: Waiting for application startup.
<span style="color: green;">INFO</span>: Application startup complete.
```
</div>
Es wird **ausdrücklich empfohlen**, dass Sie den Code schreiben oder kopieren, ihn bearbeiten und lokal ausführen.
Die Verwendung in Ihrem eigenen Editor zeigt Ihnen die Vorteile von FastAPI am besten, wenn Sie sehen, wie wenig Code Sie schreiben müssen, all die Typprüfungen, die automatische Vervollständigung usw.
---
## FastAPI installieren
Der erste Schritt besteht aus der Installation von FastAPI.
Für dieses Tutorial empfiehlt es sich, FastAPI mit allen optionalen Abhängigkeiten und Funktionen zu installieren:
<div class="termy">
```console
$ pip install "fastapi[all]"
---> 100%
```
</div>
... das beinhaltet auch `uvicorn`, welchen Sie als Server verwenden können, der ihren Code ausführt.
!!! note "Hinweis"
Sie können die einzelnen Teile auch separat installieren.
Das folgende würden Sie wahrscheinlich tun, wenn Sie Ihre Anwendung in der Produktion einsetzen:
```
pip install fastapi
```
Installieren Sie auch `uvicorn` als Server:
```
pip install "uvicorn[standard]"
```
Das gleiche gilt für jede der optionalen Abhängigkeiten, die Sie verwenden möchten.
## Handbuch für fortgeschrittene Benutzer
Es gibt auch ein **Handbuch für fortgeschrittene Benutzer**, welches Sie später nach diesem **Tutorial – Benutzerhandbuch** lesen können.
Das **Handbuch für fortgeschrittene Benutzer** baut auf diesem Tutorial auf, verwendet dieselben Konzepte und bringt Ihnen einige zusätzliche Funktionen bei.
Allerdings sollten Sie zuerst das **Tutorial – Benutzerhandbuch** lesen (was Sie hier gerade tun).
Die Dokumentation ist so konzipiert, dass Sie mit dem **Tutorial – Benutzerhandbuch** eine vollständige Anwendung erstellen können und diese dann je nach Bedarf mit einigen der zusätzlichen Ideen aus dem **Handbuch für fortgeschrittene Benutzer** vervollständigen können.

6
docs/em/docs/advanced/security/oauth2-scopes.md

@ -56,7 +56,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
🥇, ➡️ 🔜 👀 🍕 👈 🔀 ⚪️➡️ 🖼 👑 **🔰 - 👩‍💻 🦮** [Oauth2️⃣ ⏮️ 🔐 (&amp; 🔁), 📨 ⏮️ 🥙 🤝](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. 🔜 ⚙️ Oauth2️⃣ ↔:
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153"
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
{!../../../docs_src/security/tutorial005.py!}
```
@ -93,7 +93,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
✋️ 👆 🈸, 💂‍♂, 👆 🔜 ⚒ 💭 👆 🕴 🚮 ↔ 👈 👩‍💻 🤙 💪 ✔️, ⚖️ 🕐 👆 ✔️ 🔁.
```Python hl_lines="153"
```Python hl_lines="155"
{!../../../docs_src/security/tutorial005.py!}
```
@ -118,7 +118,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
👥 🔨 ⚫️ 📥 🎦 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚.
```Python hl_lines="4 139 166"
```Python hl_lines="4 139 168"
{!../../../docs_src/security/tutorial005.py!}
```

4
docs/em/docs/tutorial/security/oauth2-jwt.md

@ -192,13 +192,13 @@ $ openssl rand -hex 32
=== "🐍 3️⃣.6️⃣ &amp; 🔛"
```Python hl_lines="115-128"
```Python hl_lines="115-130"
{!> ../../../docs_src/security/tutorial004.py!}
```
=== "🐍 3️⃣.1️⃣0️⃣ &amp; 🔛"
```Python hl_lines="114-127"
```Python hl_lines="114-129"
{!> ../../../docs_src/security/tutorial004_py310.py!}
```

2
docs/em/docs/tutorial/sql-databases.md

@ -501,7 +501,7 @@ current_user.items
"🛠️" ⚒ 🔁 💪 🕐❔ 👆 🔀 📊 👆 🇸🇲 🏷, 🚮 🆕 🔢, ♒️. 🔁 👈 🔀 💽, 🚮 🆕 🏓, 🆕 🏓, ♒️.
👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/%7B%7Bcookiecutter.project_slug%7D%7D/backend/app/alembic/" class="external-link" target="_blank"> `alembic` 📁 ℹ 📟</a>.
👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/src/backend/app/alembic/" class="external-link" target="_blank"> `alembic` 📁 ℹ 📟</a>.
### ✍ 🔗

36
docs/en/data/external_links.yml

@ -1,5 +1,17 @@
Articles:
English:
- author: Ankit Anchlia
author_link: https://linkedin.com/in/aanchlia21
link: https://hackernoon.com/explore-how-to-effectively-use-jwt-with-fastapi
title: Explore How to Effectively Use JWT With FastAPI
- author: Nicoló Lino
author_link: https://www.nlino.com
link: https://github.com/softwarebloat/python-tracing-demo
title: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo
- author: Mikhail Rozhkov, Elena Samuylova
author_link: https://www.linkedin.com/in/mnrozhkov/
link: https://www.evidentlyai.com/blog/fastapi-tutorial
title: ML serving and monitoring with FastAPI and Evidently
- author: Visual Studio Code Team
author_link: https://code.visualstudio.com/
link: https://code.visualstudio.com/docs/python/tutorial-fastapi
@ -28,10 +40,6 @@ Articles:
author_link: https://dev.to/
link: https://dev.to/teresafds/authorization-on-fastapi-with-casbin-41og
title: Authorization on FastAPI with Casbin
- author: WayScript
author_link: https://www.wayscript.com
link: https://blog.wayscript.com/fast-api-quickstart/
title: Quickstart Guide to Build and Host Responsive APIs with Fast API and WayScript
- author: New Relic
author_link: https://newrelic.com
link: https://newrelic.com/instant-observability/fastapi/e559ec64-f765-4470-a15f-1901fcebb468
@ -84,10 +92,6 @@ Articles:
author_link: https://dev.to/factorlive
link: https://dev.to/factorlive/python-facebook-messenger-webhook-with-fastapi-on-glitch-4n90
title: Python Facebook messenger webhook with FastAPI on Glitch
- author: Dom Patmore
author_link: https://twitter.com/dompatmore
link: https://dompatmore.com/blog/authenticate-your-fastapi-app-with-auth0
title: Authenticate Your FastAPI App with auth0
- author: Valon Januzaj
author_link: https://www.linkedin.com/in/valon-januzaj-b02692187/
link: https://valonjanuzaj.medium.com/deploy-a-dockerized-fastapi-application-to-aws-cc757830ba1b
@ -100,10 +104,6 @@ Articles:
author_link: https://twitter.com/louis_guitton
link: https://guitton.co/posts/fastapi-monitoring/
title: How to monitor your FastAPI service
- author: Julien Harbulot
author_link: https://julienharbulot.com/
link: https://julienharbulot.com/notification-server.html
title: HTTP server to display desktop notifications
- author: Precious Ndubueze
author_link: https://medium.com/@gabbyprecious2000
link: https://medium.com/@gabbyprecious2000/creating-a-crud-app-with-fastapi-part-one-7c049292ad37
@ -152,18 +152,10 @@ Articles:
author_link: https://wuilly.com/
link: https://wuilly.com/2019/10/real-time-notifications-with-python-and-postgres/
title: Real-time Notifications with Python and Postgres
- author: Benjamin Ramser
author_link: https://iwpnd.pw
link: https://iwpnd.pw/articles/2020-03/apache-kafka-fastapi-geostream
title: Apache Kafka producer and consumer with FastAPI and aiokafka
- author: Navule Pavan Kumar Rao
author_link: https://www.linkedin.com/in/navule/
link: https://www.tutlinks.com/create-and-deploy-fastapi-app-to-heroku/
title: Create and Deploy FastAPI app to Heroku without using Docker
- author: Benjamin Ramser
author_link: https://iwpnd.pw
link: https://iwpnd.pw/articles/2020-01/deploy-fastapi-to-aws-lambda
title: How to continuously deploy a FastAPI to AWS Lambda with AWS SAM
- author: Arthur Henrique
author_link: https://twitter.com/arthurheinrique
link: https://medium.com/@arthur393/another-boilerplate-to-fastapi-azure-pipeline-ci-pytest-3c8d9a4be0bb
@ -188,10 +180,6 @@ Articles:
author_link: https://dev.to/dbanty
link: https://dev.to/dbanty/why-i-m-leaving-flask-3ki6
title: Why I'm Leaving Flask
- author: Rob Wagner
author_link: https://robwagner.dev/
link: https://robwagner.dev/tortoise-fastapi-setup/
title: Setting up Tortoise ORM with FastAPI
- author: Mike Moritz
author_link: https://medium.com/@mike.p.moritz
link: https://medium.com/@mike.p.moritz/using-docker-compose-to-deploy-a-lightweight-python-rest-api-with-a-job-queue-37e6072a209b

2
docs/en/docs/advanced/additional-responses.md

@ -28,7 +28,7 @@ For example, to declare another response with a status code `404` and a Pydantic
```
!!! note
Have in mind that you have to return the `JSONResponse` directly.
Keep in mind that you have to return the `JSONResponse` directly.
!!! info
The `model` key is not part of OpenAPI.

2
docs/en/docs/advanced/async-tests.md

@ -85,7 +85,7 @@ response = client.get('/')
Note that we're using async/await with the new `AsyncClient` - the request is asynchronous.
!!! warning
If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from <a href="florimondmanca/asgi-lifespan" class="external-link" target="_blank">https://github.com/florimondmanca/asgi-lifespan#usage</a>.
If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from <a href="https://github.com/florimondmanca/asgi-lifespan#usage" class="external-link" target="_blank">florimondmanca/asgi-lifespan</a>.
## Other Asynchronous Function Calls

4
docs/en/docs/advanced/behind-a-proxy.md

@ -125,7 +125,7 @@ Passing the `root_path` to `FastAPI` would be the equivalent of passing the `--r
### About `root_path`
Have in mind that the server (Uvicorn) won't use that `root_path` for anything else than passing it to the app.
Keep in mind that the server (Uvicorn) won't use that `root_path` for anything else than passing it to the app.
But if you go with your browser to <a href="http://127.0.0.1:8000" class="external-link" target="_blank">http://127.0.0.1:8000/app</a> you will see the normal response:
@ -142,7 +142,7 @@ Uvicorn will expect the proxy to access Uvicorn at `http://127.0.0.1:8000/app`,
## About proxies with a stripped path prefix
Have in mind that a proxy with stripped path prefix is only one of the ways to configure it.
Keep in mind that a proxy with stripped path prefix is only one of the ways to configure it.
Probably in many cases the default will be that the proxy doesn't have a stripped path prefix.

2
docs/en/docs/advanced/custom-response.md

@ -101,7 +101,7 @@ But as you passed the `HTMLResponse` in the `response_class` too, **FastAPI** wi
Here are some of the available responses.
Have in mind that you can use `Response` to return anything else, or even create a custom sub-class.
Keep in mind that you can use `Response` to return anything else, or even create a custom sub-class.
!!! note "Technical Details"
You could also use `from starlette.responses import HTMLResponse`.

2
docs/en/docs/advanced/dataclasses.md

@ -21,7 +21,7 @@ And of course, it supports the same:
This works the same way as with Pydantic models. And it is actually achieved in the same way underneath, using Pydantic.
!!! info
Have in mind that dataclasses can't do everything Pydantic models can do.
Keep in mind that dataclasses can't do everything Pydantic models can do.
So, you might still need to use Pydantic models.

4
docs/en/docs/advanced/events.md

@ -92,7 +92,7 @@ The `lifespan` parameter of the `FastAPI` app takes an **async context manager**
## Alternative Events (deprecated)
!!! warning
The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above.
The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. If you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called. It's all `lifespan` or all events, not both.
You can probably skip this part.
@ -159,4 +159,4 @@ Underneath, in the ASGI technical specification, this is part of the <a href="ht
## Sub Applications
🚨 Have in mind that these lifespan events (startup and shutdown) will only be executed for the main application, not for [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}.
🚨 Keep in mind that these lifespan events (startup and shutdown) will only be executed for the main application, not for [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}.

2
docs/en/docs/advanced/path-operation-advanced-configuration.md

@ -163,7 +163,7 @@ For example, in this application we don't use FastAPI's integrated functionality
```
!!! info
In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_schema_json()`.
In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_json_schema()`.
Nevertheless, although we are not using the default integrated functionality, we are still using a Pydantic model to manually generate the JSON Schema for the data that we want to receive in YAML.

2
docs/en/docs/advanced/response-change-status-code.md

@ -30,4 +30,4 @@ And if you declared a `response_model`, it will still be used to filter and conv
**FastAPI** will use that *temporal* response to extract the status code (also cookies and headers), and will put them in the final response that contains the value you returned, filtered by any `response_model`.
You can also declare the `Response` parameter in dependencies, and set the status code in them. But have in mind that the last one to be set will win.
You can also declare the `Response` parameter in dependencies, and set the status code in them. But keep in mind that the last one to be set will win.

2
docs/en/docs/advanced/response-cookies.md

@ -31,7 +31,7 @@ Then set Cookies in it, and then return it:
```
!!! tip
Have in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly.
Keep in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly.
So, you will have to make sure your data is of the correct type. E.g. it is compatible with JSON, if you are returning a `JSONResponse`.

2
docs/en/docs/advanced/response-headers.md

@ -37,6 +37,6 @@ Create a response as described in [Return a Response Directly](response-directly
## Custom Headers
Have in mind that custom proprietary headers can be added <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">using the 'X-' prefix</a>.
Keep in mind that custom proprietary headers can be added <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">using the 'X-' prefix</a>.
But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations (read more in [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}), using the parameter `expose_headers` documented in <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette's CORS docs</a>.

18
docs/en/docs/advanced/security/oauth2-scopes.md

@ -79,7 +79,7 @@ First, let's quickly see the parts that change from the examples in the main **T
!!! tip
Prefer to use the `Annotated` version if possible.
```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 152"
```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154"
{!> ../../../docs_src/security/tutorial005_py310.py!}
```
@ -88,7 +88,7 @@ First, let's quickly see the parts that change from the examples in the main **T
!!! tip
Prefer to use the `Annotated` version if possible.
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153"
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
{!> ../../../docs_src/security/tutorial005_py39.py!}
```
@ -97,7 +97,7 @@ First, let's quickly see the parts that change from the examples in the main **T
!!! tip
Prefer to use the `Annotated` version if possible.
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153"
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
{!> ../../../docs_src/security/tutorial005.py!}
```
@ -199,7 +199,7 @@ And we return the scopes as part of the JWT token.
!!! tip
Prefer to use the `Annotated` version if possible.
```Python hl_lines="152"
```Python hl_lines="154"
{!> ../../../docs_src/security/tutorial005_py310.py!}
```
@ -208,7 +208,7 @@ And we return the scopes as part of the JWT token.
!!! tip
Prefer to use the `Annotated` version if possible.
```Python hl_lines="153"
```Python hl_lines="155"
{!> ../../../docs_src/security/tutorial005_py39.py!}
```
@ -217,7 +217,7 @@ And we return the scopes as part of the JWT token.
!!! tip
Prefer to use the `Annotated` version if possible.
```Python hl_lines="153"
```Python hl_lines="155"
{!> ../../../docs_src/security/tutorial005.py!}
```
@ -265,7 +265,7 @@ In this case, it requires the scope `me` (it could require more than one scope).
!!! tip
Prefer to use the `Annotated` version if possible.
```Python hl_lines="3 138 165"
```Python hl_lines="3 138 167"
{!> ../../../docs_src/security/tutorial005_py310.py!}
```
@ -274,7 +274,7 @@ In this case, it requires the scope `me` (it could require more than one scope).
!!! tip
Prefer to use the `Annotated` version if possible.
```Python hl_lines="4 139 166"
```Python hl_lines="4 139 168"
{!> ../../../docs_src/security/tutorial005_py39.py!}
```
@ -283,7 +283,7 @@ In this case, it requires the scope `me` (it could require more than one scope).
!!! tip
Prefer to use the `Annotated` version if possible.
```Python hl_lines="4 139 166"
```Python hl_lines="4 139 168"
{!> ../../../docs_src/security/tutorial005.py!}
```

48
docs/en/docs/advanced/templates.md

@ -46,21 +46,61 @@ $ pip install jinja2
## Writing templates
Then you can write a template at `templates/item.html` with:
Then you can write a template at `templates/item.html` with, for example:
```jinja hl_lines="7"
{!../../../docs_src/templates/templates/item.html!}
```
It will show the `id` taken from the "context" `dict` you passed:
### Template Context Values
In the HTML that contains:
{% raw %}
```jinja
Item ID: {{ id }}
```
{% endraw %}
...it will show the `id` taken from the "context" `dict` you passed:
```Python
{"request": request, "id": id}
{"id": id}
```
For example, with an ID of `42`, this would render:
```html
Item ID: 42
```
### Template `url_for` Arguments
You can also use `url_for()` inside of the template, it takes as arguments the same arguments that would be used by your *path operation function*.
So, the section with:
{% raw %}
```jinja
<a href="{{ url_for('read_item', id=id) }}">
```
{% endraw %}
...will generate a link to the same URL that would be handled by the *path operation function* `read_item(id=id)`.
For example, with an ID of `42`, this would render:
```html
<a href="/items/42">
```
## Templates and static files
You can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted.
You can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted with the `name="static"`.
```jinja hl_lines="4"
{!../../../docs_src/templates/templates/item.html!}

2
docs/en/docs/advanced/websockets.md

@ -212,7 +212,7 @@ Client #1596980209979 left the chat
!!! tip
The app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections.
But have in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process.
But keep in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process.
If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check <a href="https://github.com/encode/broadcaster" class="external-link" target="_blank">encode/broadcaster</a>.

2
docs/en/docs/benchmarks.md

@ -2,7 +2,7 @@
Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">one of the fastest Python frameworks available</a>, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)
But when checking benchmarks and comparisons you should have the following in mind.
But when checking benchmarks and comparisons you should keep the following in mind.
## Benchmarks and speed

71
docs/en/docs/contributing.md

@ -4,11 +4,11 @@ First, you might want to see the basic ways to [help FastAPI and get help](help-
## Developing
If you already cloned the repository and you know that you need to deep dive in the code, here are some guidelines to set up your environment.
If you already cloned the <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">fastapi repository</a> and you want to deep dive in the code, here are some guidelines to set up your environment.
### Virtual environment with `venv`
You can create a virtual environment in a directory using Python's `venv` module:
You can create an isolated virtual local environment in a directory using Python's `venv` module. Let's do this in the cloned repository (where the `requirements.txt` is):
<div class="termy">
@ -18,7 +18,7 @@ $ python -m venv env
</div>
That will create a directory `./env/` with the Python binaries and then you will be able to install packages for that isolated environment.
That will create a directory `./env/` with the Python binaries, and then you will be able to install packages for that local environment.
### Activate the environment
@ -84,7 +84,7 @@ To check it worked, use:
If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉
Make sure you have the latest pip version on your virtual environment to avoid errors on the next steps:
Make sure you have the latest pip version on your local environment to avoid errors on the next steps:
<div class="termy">
@ -101,7 +101,7 @@ $ python -m pip install --upgrade pip
This makes sure that if you use a terminal program installed by that package, you use the one from your local environment and not any other that could be installed globally.
### pip
### Install requirements using pip
After activating the environment as described above:
@ -117,20 +117,20 @@ $ pip install -r requirements.txt
It will install all the dependencies and your local FastAPI in your local environment.
#### Using your local FastAPI
### Using your local FastAPI
If you create a Python file that imports and uses FastAPI, and run it with the Python from your local environment, it will use your local FastAPI source code.
If you create a Python file that imports and uses FastAPI, and run it with the Python from your local environment, it will use your cloned local FastAPI source code.
And if you update that local FastAPI source code when you run that Python file again, it will use the fresh version of FastAPI you just edited.
That way, you don't have to "install" your local version to be able to test every change.
!!! note "Technical Details"
This only happens when you install using this included `requirements.txt` instead of installing `pip install fastapi` directly.
This only happens when you install using this included `requirements.txt` instead of running `pip install fastapi` directly.
That is because inside of the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option.
That is because inside the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option.
### Format
### Format the code
There is a script that you can run that will format and clean all your code:
@ -227,15 +227,13 @@ And those Python files are included/injected in the documentation when generatin
Most of the tests actually run against the example source files in the documentation.
This helps making sure that:
This helps to make sure that:
* The documentation is up to date.
* The documentation is up-to-date.
* The documentation examples can be run as is.
* Most of the features are covered by the documentation, ensured by test coverage.
### Apps and docs at the same time
#### Apps and docs at the same time
If you run the examples with, e.g.:
@ -259,7 +257,9 @@ Here are the steps to help with translations.
#### Tips and guidelines
* Check the currently <a href="https://github.com/tiangolo/fastapi/pulls" class="external-link" target="_blank">existing pull requests</a> for your language and add reviews requesting changes or approving them.
* Check the currently <a href="https://github.com/tiangolo/fastapi/pulls" class="external-link" target="_blank">existing pull requests</a> for your language. You can filter the pull requests by the ones with the label for your language. For example, for Spanish, the label is <a href="https://github.com/tiangolo/fastapi/pulls?q=is%3Aopen+sort%3Aupdated-desc+label%3Alang-es+label%3Aawaiting-review" class="external-link" target="_blank">`lang-es`</a>.
* Review those pull requests, requesting changes or approving them. For the languages I don't speak, I'll wait for several others to review the translation before merging.
!!! tip
You can <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">add comments with change suggestions</a> to existing pull requests.
@ -268,19 +268,9 @@ Here are the steps to help with translations.
* Check if there's a <a href="https://github.com/tiangolo/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub Discussion</a> to coordinate translations for your language. You can subscribe to it, and when there's a new pull request to review, an automatic comment will be added to the discussion.
* Add a single pull request per page translated. That will make it much easier for others to review it.
For the languages I don't speak, I'll wait for several others to review the translation before merging.
* If you translate pages, add a single pull request per page translated. That will make it much easier for others to review it.
* You can also check if there are translations for your language and add a review to them, that will help me know that the translation is correct and I can merge it.
* You could check in the <a href="https://github.com/tiangolo/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub Discussions</a> for your language.
* Or you can filter the existing PRs by the ones with the label for your language, for example, for Spanish, the label is <a href="https://github.com/tiangolo/fastapi/pulls?q=is%3Apr+is%3Aopen+sort%3Aupdated-desc+label%3Alang-es+label%3A%22awaiting+review%22" class="external-link" target="_blank">`lang-es`</a>.
* Use the same Python examples and only translate the text in the docs. You don't have to change anything for this to work.
* Use the same images, file names, and links. You don't have to change anything for it to work.
* To check the 2-letter code for the language you want to translate you can use the table <a href="https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes" class="external-link" target="_blank">List of ISO 639-1 codes</a>.
* To check the 2-letter code for the language you want to translate, you can use the table <a href="https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes" class="external-link" target="_blank">List of ISO 639-1 codes</a>.
#### Existing language
@ -323,7 +313,7 @@ $ python ./scripts/docs.py live es
Now you can go to <a href="http://127.0.0.1:8008" class="external-link" target="_blank">http://127.0.0.1:8008</a> and see your changes live.
You will see that every language has all the pages. But some pages are not translated and have a notification about the missing translation.
You will see that every language has all the pages. But some pages are not translated and have an info box at the top, about the missing translation.
Now let's say that you want to add a translation for the section [Features](features.md){.internal-link target=_blank}.
@ -342,7 +332,7 @@ docs/es/docs/features.md
!!! tip
Notice that the only change in the path and file name is the language code, from `en` to `es`.
If you go to your browser you will see that now the docs show your new section. 🎉
If you go to your browser you will see that now the docs show your new section (the info box at the top is gone). 🎉
Now you can translate it all and see how it looks as you save the file.
@ -386,7 +376,7 @@ You can make the first pull request with those two files, `docs/ht/mkdocs.yml` a
#### Preview the result
You can use the `./scripts/docs.py` with the `live` command to preview the results (or `mkdocs serve`).
As already mentioned above, you can use the `./scripts/docs.py` with the `live` command to preview the results (or `mkdocs serve`).
Once you are done, you can also test it all as it would look online, including all the other languages.
@ -423,6 +413,25 @@ Serving at: http://127.0.0.1:8008
</div>
#### Translation specific tips and guidelines
* Translate only the Markdown documents (`.md`). Do not translate the code examples at `./docs_src`.
* In code blocks within the Markdown document, translate comments (`# a comment`), but leave the rest unchanged.
* Do not change anything enclosed in "``" (inline code).
* In lines starting with `===` or `!!!`, translate only the ` "... Text ..."` part. Leave the rest unchanged.
* You can translate info boxes like `!!! warning` with for example `!!! warning "Achtung"`. But do not change the word immediately after the `!!!`, it determines the color of the info box.
* Do not change the paths in links to images, code files, Markdown documents.
* However, when a Markdown document is translated, the `#hash-parts` in links to its headings may change. Update these links if possible.
* Search for such links in the translated document using the regex `#[^# ]`.
* Search in all documents already translated into your language for `your-translated-document.md`. For example VS Code has an option "Edit" -> "Find in Files".
* When translating a document, do not "pre-translate" `#hash-parts` that link to headings in untranslated documents.
## Tests
There is a script that you can run locally to test all the code and generate coverage reports in HTML:

4
docs/en/docs/deployment/concepts.md

@ -258,7 +258,7 @@ And you will have to make sure that it's a single process running those previous
Of course, there are some cases where there's no problem in running the previous steps multiple times, in that case, it's a lot easier to handle.
!!! tip
Also, have in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application.
Also, keep in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application.
In that case, you wouldn't have to worry about any of this. 🤷
@ -297,7 +297,7 @@ You can use simple tools like `htop` to see the CPU and RAM used in your server
## Recap
You have been reading here some of the main concepts that you would probably need to have in mind when deciding how to deploy your application:
You have been reading here some of the main concepts that you would probably need to keep in mind when deciding how to deploy your application:
* Security - HTTPS
* Running on startup

2
docs/en/docs/deployment/https.md

@ -9,7 +9,7 @@ But it is way more complex than that.
To **learn the basics of HTTPS**, from a consumer perspective, check <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a>.
Now, from a **developer's perspective**, here are several things to have in mind while thinking about HTTPS:
Now, from a **developer's perspective**, here are several things to keep in mind while thinking about HTTPS:
* For HTTPS, **the server** needs to **have "certificates"** generated by a **third party**.
* Those certificates are actually **acquired** from the third party, not "generated".

4
docs/en/docs/deployment/index.md

@ -16,6 +16,6 @@ There are several ways to do it depending on your specific use case and the tool
You could **deploy a server** yourself using a combination of tools, you could use a **cloud service** that does part of the work for you, or other possible options.
I will show you some of the main concepts you should probably have in mind when deploying a **FastAPI** application (although most of it applies to any other type of web application).
I will show you some of the main concepts you should probably keep in mind when deploying a **FastAPI** application (although most of it applies to any other type of web application).
You will see more details to have in mind and some of the techniques to do it in the next sections. ✨
You will see more details to keep in mind and some of the techniques to do it in the next sections. ✨

4
docs/en/docs/deployment/manually.md

@ -10,11 +10,11 @@ There are 3 main alternatives:
## Server Machine and Server Program
There's a small detail about names to have in mind. 💡
There's a small detail about names to keep in mind. 💡
The word "**server**" is commonly used to refer to both the remote/cloud computer (the physical or virtual machine) and also the program that is running on that machine (e.g. Uvicorn).
Just have that in mind when you read "server" in general, it could refer to one of those two things.
Just keep in mind that when you read "server" in general, it could refer to one of those two things.
When referring to the remote machine, it's common to call it **server**, but also **machine**, **VM** (virtual machine), **node**. Those all refer to some type of remote machine, normally running Linux, where you run programs.

6
docs/en/docs/help-fastapi.md

@ -106,7 +106,7 @@ In many cases they will only copy a fragment of the code, but that's not enough
* You can ask them to provide a <a href="https://stackoverflow.com/help/minimal-reproducible-example" class="external-link" target="_blank">minimal, reproducible, example</a>, that you can **copy-paste** and run locally to see the same error or behavior they are seeing, or to understand their use case better.
* If you are feeling too generous, you can try to **create an example** like that yourself, just based on the description of the problem. Just have in mind that this might take a lot of time and it might be better to ask them to clarify the problem first.
* If you are feeling too generous, you can try to **create an example** like that yourself, just based on the description of the problem. Just keep in mind that this might take a lot of time and it might be better to ask them to clarify the problem first.
### Suggest solutions
@ -148,7 +148,7 @@ Again, please try your best to be kind. 🤗
---
Here's what to have in mind and how to review a pull request:
Here's what to keep in mind and how to review a pull request:
### Understand the problem
@ -233,7 +233,7 @@ Join the 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" targ
### Don't use the chat for questions
Have in mind that as chats allow more "free conversation", it's easy to ask questions that are too general and more difficult to answer, so, you might not receive answers.
Keep in mind that as chats allow more "free conversation", it's easy to ask questions that are too general and more difficult to answer, so, you might not receive answers.
In GitHub, the template will guide you to write the right question so that you can more easily get a good answer, or even solve the problem yourself even before asking. And in GitHub I can make sure I always answer everything, even if it takes some time. I can't personally do that with the chat systems. 😅

5
docs/en/docs/how-to/async-sql-encode-databases.md

@ -1,4 +1,4 @@
# Async SQL (Relational) Databases with Encode/Databases
# ~~Async SQL (Relational) Databases with Encode/Databases~~ (deprecated)
!!! info
These docs are about to be updated. 🎉
@ -7,6 +7,9 @@
The new docs will include Pydantic v2 and will use <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a> once it is updated to use Pydantic v2 as well.
!!! warning "Deprecated"
This tutorial is deprecated and will be removed in a future version.
You can also use <a href="https://github.com/encode/databases" class="external-link" target="_blank">`encode/databases`</a> with **FastAPI** to connect to databases using `async` and `await`.
It is compatible with:

5
docs/en/docs/how-to/nosql-databases-couchbase.md

@ -1,4 +1,4 @@
# NoSQL (Distributed / Big Data) Databases with Couchbase
# ~~NoSQL (Distributed / Big Data) Databases with Couchbase~~ (deprecated)
!!! info
These docs are about to be updated. 🎉
@ -7,6 +7,9 @@
The new docs will hopefully use Pydantic v2 and will use <a href="https://art049.github.io/odmantic/" class="external-link" target="_blank">ODMantic</a> with MongoDB.
!!! warning "Deprecated"
This tutorial is deprecated and will be removed in a future version.
**FastAPI** can also be integrated with any <abbr title="Distributed database (Big Data), also 'Not Only SQL'">NoSQL</abbr>.
Here we'll see an example using **<a href="https://www.couchbase.com/" class="external-link" target="_blank">Couchbase</a>**, a <abbr title="Document here refers to a JSON object (a dict), with keys and values, and those values can also be other JSON objects, arrays (lists), numbers, strings, booleans, etc.">document</abbr> based NoSQL database.

9
docs/en/docs/how-to/sql-databases-peewee.md

@ -1,4 +1,7 @@
# SQL (Relational) Databases with Peewee
# ~~SQL (Relational) Databases with Peewee~~ (deprecated)
!!! warning "Deprecated"
This tutorial is deprecated and will be removed in a future version.
!!! warning
If you are just starting, the tutorial [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} that uses SQLAlchemy should be enough.
@ -75,7 +78,7 @@ Let's first check all the normal Peewee code, create a Peewee database:
```
!!! tip
Have in mind that if you wanted to use a different database, like PostgreSQL, you couldn't just change the string. You would need to use a different Peewee database class.
Keep in mind that if you wanted to use a different database, like PostgreSQL, you couldn't just change the string. You would need to use a different Peewee database class.
#### Note
@ -493,7 +496,7 @@ This means that, with Peewee's current implementation, multiple tasks could be u
Python 3.7 has <a href="https://docs.python.org/3/library/contextvars.html" class="external-link" target="_blank">`contextvars`</a> that can create a local variable very similar to `threading.local`, but also supporting these async features.
There are several things to have in mind.
There are several things to keep in mind.
The `ContextVar` has to be created at the top of the module, like:

67
docs/en/docs/release-notes.md

@ -7,11 +7,76 @@ hide:
## Latest Changes
* ✏️ Fix Pydantic method name in `docs/en/docs/advanced/path-operation-advanced-configuration.md`. PR [#10826](https://github.com/tiangolo/fastapi/pull/10826) by [@ahmedabdou14](https://github.com/ahmedabdou14).
### Features
* ✨ Include HTTP 205 in status codes with no body. PR [#10969](https://github.com/tiangolo/fastapi/pull/10969) by [@tiangolo](https://github.com/tiangolo).
### Refactors
* ✅ Refactor tests for duplicate operation ID generation for compatibility with other tools running the FastAPI test suite. PR [#10876](https://github.com/tiangolo/fastapi/pull/10876) by [@emmettbutler](https://github.com/emmettbutler).
* ♻️ Simplify string format with f-strings in `fastapi/utils.py`. PR [#10576](https://github.com/tiangolo/fastapi/pull/10576) by [@eukub](https://github.com/eukub).
* 🔧 Fix Ruff configuration unintentionally enabling and re-disabling mccabe complexity check. PR [#10893](https://github.com/tiangolo/fastapi/pull/10893) by [@jiridanek](https://github.com/jiridanek).
* ✅ Re-enable test in `tests/test_tutorial/test_header_params/test_tutorial003.py` after fix in Starlette. PR [#10904](https://github.com/tiangolo/fastapi/pull/10904) by [@ooknimm](https://github.com/ooknimm).
### Docs
* 📝 Deprecate old tutorials: Peewee, Couchbase, encode/databases. PR [#10979](https://github.com/tiangolo/fastapi/pull/10979) by [@tiangolo](https://github.com/tiangolo).
* ✏️ Fix typo in `fastapi/security/oauth2.py`. PR [#10972](https://github.com/tiangolo/fastapi/pull/10972) by [@RafalSkolasinski](https://github.com/RafalSkolasinski).
* 📝 Update `HTTPException` details in `docs/en/docs/tutorial/handling-errors.md`. PR [#5418](https://github.com/tiangolo/fastapi/pull/5418) by [@papb](https://github.com/papb).
* ✏️ A few tweaks in `docs/de/docs/tutorial/first-steps.md`. PR [#10959](https://github.com/tiangolo/fastapi/pull/10959) by [@nilslindemann](https://github.com/nilslindemann).
* ✏️ Fix link in `docs/en/docs/advanced/async-tests.md`. PR [#10960](https://github.com/tiangolo/fastapi/pull/10960) by [@nilslindemann](https://github.com/nilslindemann).
* ✏️ Fix typos for Spanish documentation. PR [#10957](https://github.com/tiangolo/fastapi/pull/10957) by [@jlopezlira](https://github.com/jlopezlira).
* 📝 Add warning about lifespan functions and backwards compatibility with events. PR [#10734](https://github.com/tiangolo/fastapi/pull/10734) by [@jacob-indigo](https://github.com/jacob-indigo).
* ✏️ Fix broken link in `docs/tutorial/sql-databases.md` in several languages. PR [#10716](https://github.com/tiangolo/fastapi/pull/10716) by [@theoohoho](https://github.com/theoohoho).
* ✏️ Remove broken links from `external_links.yml`. PR [#10943](https://github.com/tiangolo/fastapi/pull/10943) by [@Torabek](https://github.com/Torabek).
* 📝 Update template docs with more info about `url_for`. PR [#5937](https://github.com/tiangolo/fastapi/pull/5937) by [@EzzEddin](https://github.com/EzzEddin).
* 📝 Update usage of Token model in security docs. PR [#9313](https://github.com/tiangolo/fastapi/pull/9313) by [@piotrszacilowski](https://github.com/piotrszacilowski).
* ✏️ Update highlighted line in `docs/en/docs/tutorial/bigger-applications.md`. PR [#5490](https://github.com/tiangolo/fastapi/pull/5490) by [@papb](https://github.com/papb).
* 📝 Add External Link: Explore How to Effectively Use JWT With FastAPI. PR [#10212](https://github.com/tiangolo/fastapi/pull/10212) by [@aanchlia](https://github.com/aanchlia).
* 📝 Add hyperlink to `docs/en/docs/tutorial/static-files.md`. PR [#10243](https://github.com/tiangolo/fastapi/pull/10243) by [@hungtsetse](https://github.com/hungtsetse).
* 📝 Add External Link: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo. PR [#9440](https://github.com/tiangolo/fastapi/pull/9440) by [@softwarebloat](https://github.com/softwarebloat).
* 📝 Review and rewording of `en/docs/contributing.md`. PR [#10480](https://github.com/tiangolo/fastapi/pull/10480) by [@nilslindemann](https://github.com/nilslindemann).
* 📝 Add External Link: ML serving and monitoring with FastAPI and Evidently. PR [#9701](https://github.com/tiangolo/fastapi/pull/9701) by [@mnrozhkov](https://github.com/mnrozhkov).
* 📝 Reword in docs, from "have in mind" to "keep in mind". PR [#10376](https://github.com/tiangolo/fastapi/pull/10376) by [@malicious](https://github.com/malicious).
* 📝 Add External Link: Talk by Jeny Sadadia. PR [#10265](https://github.com/tiangolo/fastapi/pull/10265) by [@JenySadadia](https://github.com/JenySadadia).
* 📝 Add location info to `tutorial/bigger-applications.md`. PR [#10552](https://github.com/tiangolo/fastapi/pull/10552) by [@nilslindemann](https://github.com/nilslindemann).
### Translations
* ✏️ Tweak the german translation of `docs/de/docs/tutorial/index.md`. PR [#10962](https://github.com/tiangolo/fastapi/pull/10962) by [@nilslindemann](https://github.com/nilslindemann).
* ✏️ Fix typo error in `docs/ko/docs/tutorial/path-params.md`. PR [#10758](https://github.com/tiangolo/fastapi/pull/10758) by [@2chanhaeng](https://github.com/2chanhaeng).
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#1961](https://github.com/tiangolo/fastapi/pull/1961) by [@SwftAlpc](https://github.com/SwftAlpc).
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#1960](https://github.com/tiangolo/fastapi/pull/1960) by [@SwftAlpc](https://github.com/SwftAlpc).
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/sub-dependencies.md`. PR [#1959](https://github.com/tiangolo/fastapi/pull/1959) by [@SwftAlpc](https://github.com/SwftAlpc).
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/background-tasks.md`. PR [#2668](https://github.com/tiangolo/fastapi/pull/2668) by [@tokusumi](https://github.com/tokusumi).
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/index.md` and `docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#1958](https://github.com/tiangolo/fastapi/pull/1958) by [@SwftAlpc](https://github.com/SwftAlpc).
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-model.md`. PR [#1938](https://github.com/tiangolo/fastapi/pull/1938) by [@SwftAlpc](https://github.com/SwftAlpc).
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-multiple-params.md`. PR [#1903](https://github.com/tiangolo/fastapi/pull/1903) by [@SwftAlpc](https://github.com/SwftAlpc).
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/path-params-numeric-validations.md`. PR [#1902](https://github.com/tiangolo/fastapi/pull/1902) by [@SwftAlpc](https://github.com/SwftAlpc).
* 🌐 Add Japanese translation for `docs/ja/docs/python-types.md`. PR [#1899](https://github.com/tiangolo/fastapi/pull/1899) by [@SwftAlpc](https://github.com/SwftAlpc).
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/handling-errors.md`. PR [#1953](https://github.com/tiangolo/fastapi/pull/1953) by [@SwftAlpc](https://github.com/SwftAlpc).
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-status-code.md`. PR [#1942](https://github.com/tiangolo/fastapi/pull/1942) by [@SwftAlpc](https://github.com/SwftAlpc).
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/extra-models.md`. PR [#1941](https://github.com/tiangolo/fastapi/pull/1941) by [@SwftAlpc](https://github.com/SwftAlpc).
* 🌐 Add Japanese tranlsation for `docs/ja/docs/tutorial/schema-extra-example.md`. PR [#1931](https://github.com/tiangolo/fastapi/pull/1931) by [@SwftAlpc](https://github.com/SwftAlpc).
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-nested-models.md`. PR [#1930](https://github.com/tiangolo/fastapi/pull/1930) by [@SwftAlpc](https://github.com/SwftAlpc).
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-fields.md`. PR [#1923](https://github.com/tiangolo/fastapi/pull/1923) by [@SwftAlpc](https://github.com/SwftAlpc).
* 🌐 Add German translation for `docs/de/docs/tutorial/index.md`. PR [#9502](https://github.com/tiangolo/fastapi/pull/9502) by [@fhabers21](https://github.com/fhabers21).
* 🌐 Add German translation for `docs/de/docs/tutorial/background-tasks.md`. PR [#10566](https://github.com/tiangolo/fastapi/pull/10566) by [@nilslindemann](https://github.com/nilslindemann).
* ✏️ Fix typo in `docs/ru/docs/index.md`. PR [#10672](https://github.com/tiangolo/fastapi/pull/10672) by [@Delitel-WEB](https://github.com/Delitel-WEB).
* ✏️ Fix typos in `docs/zh/docs/tutorial/extra-data-types.md`. PR [#10727](https://github.com/tiangolo/fastapi/pull/10727) by [@HiemalBeryl](https://github.com/HiemalBeryl).
* 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10410](https://github.com/tiangolo/fastapi/pull/10410) by [@AlertRED](https://github.com/AlertRED).
### Internal
* 👷 Add changes-requested handling in GitHub Action issue manager. PR [#10971](https://github.com/tiangolo/fastapi/pull/10971) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Group dependencies on dependabot updates. PR [#10952](https://github.com/tiangolo/fastapi/pull/10952) by [@Kludex](https://github.com/Kludex).
* ⬆ Bump actions/setup-python from 4 to 5. PR [#10764](https://github.com/tiangolo/fastapi/pull/10764) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump pypa/gh-action-pypi-publish from 1.8.10 to 1.8.11. PR [#10731](https://github.com/tiangolo/fastapi/pull/10731) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump dawidd6/action-download-artifact from 2.28.0 to 3.0.0. PR [#10777](https://github.com/tiangolo/fastapi/pull/10777) by [@dependabot[bot]](https://github.com/apps/dependabot).
* 🔧 Add support for translations to languages with a longer code name, like `zh-hant`. PR [#10950](https://github.com/tiangolo/fastapi/pull/10950) by [@tiangolo](https://github.com/tiangolo).
## 0.109.0
### Features
@ -3379,7 +3444,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Add OAuth2 redirect page for Swagger UI. This allows having delegated authentication in the Swagger UI docs. For this to work, you need to add `{your_origin}/docs/oauth2-redirect` to the allowed callbacks in your OAuth2 provider (in Auth0, Facebook, Google, etc).
* For example, during development, it could be `http://localhost:8000/docs/oauth2-redirect`.
* Have in mind that this callback URL is independent of whichever one is used by your frontend. You might also have another callback at `https://yourdomain.com/login/callback`.
* Keep in mind that this callback URL is independent of whichever one is used by your frontend. You might also have another callback at `https://yourdomain.com/login/callback`.
* This is only to allow delegated authentication in the API docs with Swagger UI.
* PR [#198](https://github.com/tiangolo/fastapi/pull/198) by [@steinitzu](https://github.com/steinitzu).

2
docs/en/docs/tutorial/bigger-applications.md

@ -315,7 +315,7 @@ And we can even declare [global dependencies](dependencies/global-dependencies.m
Now we import the other submodules that have `APIRouter`s:
```Python hl_lines="5" title="app/main.py"
```Python hl_lines="4-5" title="app/main.py"
{!../../../docs_src/bigger_applications/app/main.py!}
```

2
docs/en/docs/tutorial/body-nested-models.md

@ -361,7 +361,7 @@ In this case, you would accept any `dict` as long as it has `int` keys with `flo
```
!!! tip
Have in mind that JSON only supports `str` as keys.
Keep in mind that JSON only supports `str` as keys.
But Pydantic has automatic data conversion.

4
docs/en/docs/tutorial/handling-errors.md

@ -234,9 +234,7 @@ You will receive a response telling you that the data is invalid containing the
And **FastAPI**'s `HTTPException` error class inherits from Starlette's `HTTPException` error class.
The only difference, is that **FastAPI**'s `HTTPException` allows you to add headers to be included in the response.
This is needed/used internally for OAuth 2.0 and some security utilities.
The only difference is that **FastAPI**'s `HTTPException` accepts any JSON-able data for the `detail` field, while Starlette's `HTTPException` only accepts strings for it.
So, you can keep raising **FastAPI**'s `HTTPException` as normally in your code.

2
docs/en/docs/tutorial/middleware.md

@ -33,7 +33,7 @@ The middleware function receives:
```
!!! tip
Have in mind that custom proprietary headers can be added <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">using the 'X-' prefix</a>.
Keep in mind that custom proprietary headers can be added <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">using the 'X-' prefix</a>.
But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) using the parameter `expose_headers` documented in <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette's CORS docs</a>.

4
docs/en/docs/tutorial/path-params-numeric-validations.md

@ -126,7 +126,7 @@ So, you can declare your function as:
{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
```
But have in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`.
But keep in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`.
=== "Python 3.9+"
@ -166,7 +166,7 @@ Python won't do anything with that `*`, but it will know that all the following
### Better with `Annotated`
Have in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`.
Keep in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`.
=== "Python 3.9+"

8
docs/en/docs/tutorial/query-params-str-validations.md

@ -173,7 +173,7 @@ q: str | None = None
But it declares it explicitly as being a query parameter.
!!! info
Have in mind that the most important part to make a parameter optional is the part:
Keep in mind that the most important part to make a parameter optional is the part:
```Python
= None
@ -199,7 +199,7 @@ This will validate the data, show a clear error when the data is not valid, and
### `Query` as the default value or in `Annotated`
Have in mind that when using `Query` inside of `Annotated` you cannot use the `default` parameter for `Query`.
Keep in mind that when using `Query` inside of `Annotated` you cannot use the `default` parameter for `Query`.
Instead use the actual default value of the function parameter. Otherwise, it would be inconsistent.
@ -659,7 +659,7 @@ You can also use `list` directly instead of `List[str]` (or `list[str]` in Pytho
```
!!! note
Have in mind that in this case, FastAPI won't check the contents of the list.
Keep in mind that in this case, FastAPI won't check the contents of the list.
For example, `List[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't.
@ -670,7 +670,7 @@ You can add more information about the parameter.
That information will be included in the generated OpenAPI and used by the documentation user interfaces and external tools.
!!! note
Have in mind that different tools might have different levels of OpenAPI support.
Keep in mind that different tools might have different levels of OpenAPI support.
Some of them might not show all the extra information declared yet, although in most of the cases, the missing feature is already planned for development.

2
docs/en/docs/tutorial/request-files.md

@ -71,7 +71,7 @@ The files will be uploaded as "form data".
If you declare the type of your *path operation function* parameter as `bytes`, **FastAPI** will read the file for you and you will receive the contents as `bytes`.
Have in mind that this means that the whole contents will be stored in memory. This will work well for small files.
Keep in mind that this means that the whole contents will be stored in memory. This will work well for small files.
But there are several cases in which you might benefit from using `UploadFile`.

2
docs/en/docs/tutorial/security/get-current-user.md

@ -227,7 +227,7 @@ Just use any kind of model, any kind of class, any kind of database that you nee
## Code size
This example might seem verbose. Have in mind that we are mixing security, data models, utility functions and *path operations* in the same file.
This example might seem verbose. Keep in mind that we are mixing security, data models, utility functions and *path operations* in the same file.
But here's the key point.

6
docs/en/docs/tutorial/security/oauth2-jwt.md

@ -285,7 +285,7 @@ Create a real JWT access token and return it
!!! tip
Prefer to use the `Annotated` version if possible.
```Python hl_lines="114-127"
```Python hl_lines="114-129"
{!> ../../../docs_src/security/tutorial004_py310.py!}
```
@ -294,7 +294,7 @@ Create a real JWT access token and return it
!!! tip
Prefer to use the `Annotated` version if possible.
```Python hl_lines="115-128"
```Python hl_lines="115-130"
{!> ../../../docs_src/security/tutorial004.py!}
```
@ -318,7 +318,7 @@ In those cases, several of those entities could have the same ID, let's say `foo
So, to avoid ID collisions, when creating the JWT token for the user, you could prefix the value of the `sub` key, e.g. with `username:`. So, in this example, the value of `sub` could have been: `username:johndoe`.
The important thing to have in mind is that the `sub` key should have a unique identifier across the entire application, and it should be a string.
The important thing to keep in mind is that the `sub` key should have a unique identifier across the entire application, and it should be a string.
## Check it

4
docs/en/docs/tutorial/sql-databases.md

@ -301,7 +301,7 @@ while Pydantic *models* declare the types using `:`, the new type annotation syn
name: str
```
Have it in mind, so you don't get confused when using `=` and `:` with them.
Keep these in mind, so you don't get confused when using `=` and `:` with them.
### Create Pydantic *models* / schemas for reading / returning
@ -513,7 +513,7 @@ And you would also use Alembic for "migrations" (that's its main job).
A "migration" is the set of steps needed whenever you change the structure of your SQLAlchemy models, add a new attribute, etc. to replicate those changes in the database, add a new column, a new table, etc.
You can find an example of Alembic in a FastAPI project in the templates from [Project Generation - Template](../project-generation.md){.internal-link target=_blank}. Specifically in <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/%7B%7Bcookiecutter.project_slug%7D%7D/backend/app/alembic/" class="external-link" target="_blank">the `alembic` directory in the source code</a>.
You can find an example of Alembic in a FastAPI project in the templates from [Project Generation - Template](../project-generation.md){.internal-link target=_blank}. Specifically in <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/src/backend/app/alembic" class="external-link" target="_blank">the `alembic` directory in the source code</a>.
### Create a dependency

2
docs/en/docs/tutorial/static-files.md

@ -22,7 +22,7 @@ You can serve static files automatically from a directory using `StaticFiles`.
This is different from using an `APIRouter` as a mounted application is completely independent. The OpenAPI and docs from your main application won't include anything from the mounted application, etc.
You can read more about this in the **Advanced User Guide**.
You can read more about this in the [Advanced User Guide](../advanced/index.md){.internal-link target=_blank}.
## Details

7
docs/en/mkdocs.yml

@ -174,9 +174,6 @@ nav:
- How To - Recipes:
- how-to/index.md
- how-to/general.md
- how-to/sql-databases-peewee.md
- how-to/async-sql-encode-databases.md
- how-to/nosql-databases-couchbase.md
- how-to/graphql.md
- how-to/custom-request-and-route.md
- how-to/conditional-openapi.md
@ -184,6 +181,9 @@ nav:
- how-to/separate-openapi-schemas.md
- how-to/custom-docs-ui-assets.md
- how-to/configure-swagger-ui.md
- how-to/sql-databases-peewee.md
- how-to/async-sql-encode-databases.md
- how-to/nosql-databases-couchbase.md
- Reference (Code API):
- reference/index.md
- reference/fastapi.md
@ -242,6 +242,7 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
pymdownx.tabbed:
alternate_style: true
pymdownx.tilde:
attr_list: null
md_in_html: null
extra:

2
docs/es/docs/advanced/additional-status-codes.md

@ -23,7 +23,7 @@ Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu conte
No será serializado con el modelo, etc.
Asegurate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`).
Asegúrate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`).
!!! note "Detalles Técnicos"
También podrías utilizar `from starlette.responses import JSONResponse`.

2
docs/es/docs/advanced/response-directly.md

@ -21,7 +21,7 @@ Y cuando devuelves una `Response`, **FastAPI** la pasará directamente.
No hará ninguna conversión de datos con modelos Pydantic, no convertirá el contenido a ningún tipo, etc.
Esto te da mucha flexibilidad. Puedes devolver cualquier tipo de dato, sobrescribir cualquer declaración de datos o validación, etc.
Esto te da mucha flexibilidad. Puedes devolver cualquier tipo de dato, sobrescribir cualquier declaración de datos o validación, etc.
## Usando el `jsonable_encoder` en una `Response`

14
docs/es/docs/features.md

@ -13,7 +13,7 @@
### Documentación automática
Documentación interactiva de la API e interfaces web de exploración. Hay múltiples opciones, dos incluídas por defecto, porque el framework está basado en OpenAPI.
Documentación interactiva de la API e interfaces web de exploración. Hay múltiples opciones, dos incluidas por defecto, porque el framework está basado en OpenAPI.
* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank"><strong>Swagger UI</strong></a>, con exploración interactiva, llama y prueba tu API directamente desde tu navegador.
@ -25,7 +25,7 @@ Documentación interactiva de la API e interfaces web de exploración. Hay múlt
### Simplemente Python moderno
Todo está basado en las declaraciones de tipo de **Python 3.8** estándar (gracias a Pydantic). No necesitas aprender una sintáxis nueva, solo Python moderno.
Todo está basado en las declaraciones de tipo de **Python 3.8** estándar (gracias a Pydantic). No necesitas aprender una sintaxis nueva, solo Python moderno.
Si necesitas un repaso de 2 minutos de cómo usar los tipos de Python (así no uses FastAPI) prueba el tutorial corto: [Python Types](python-types.md){.internal-link target=_blank}.
@ -72,9 +72,9 @@ my_second_user: User = User(**second_user_data)
El framework fue diseñado en su totalidad para ser fácil e intuitivo de usar. Todas las decisiones fueron probadas en múltiples editores antes de comenzar el desarrollo para asegurar la mejor experiencia de desarrollo.
En la última encuesta a desarrolladores de Python fue claro que <a href="https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features" class="external-link" target="_blank">la característica más usada es el "autocompletado"</a>.
En la última encuesta a desarrolladores de Python fue claro que <a href="https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features" class="external-link" target="_blank">la característica más usada es el "auto-completado"</a>.
El framework **FastAPI** está creado para satisfacer eso. El autocompletado funciona en todas partes.
El framework **FastAPI** está creado para satisfacer eso. El auto-completado funciona en todas partes.
No vas a tener que volver a la documentación seguido.
@ -140,13 +140,13 @@ FastAPI incluye un sistema de <abbr title='En español: Inyección de Dependenci
* Todas las dependencias pueden requerir datos de los requests y aumentar las restricciones del *path operation* y la documentación automática.
* **Validación automática** inclusive para parámetros del *path operation* definidos en las dependencias.
* Soporte para sistemas complejos de autenticación de usuarios, **conexiones con bases de datos**, etc.
* **Sin comprometerse** con bases de datos, frontends, etc. Pero permitiendo integración fácil con todos ellos.
* **Sin comprometerse** con bases de datos, frontend, etc. Pero permitiendo integración fácil con todos ellos.
### "Plug-ins" ilimitados
O dicho de otra manera, no hay necesidad para "plug-ins". Importa y usa el código que necesites.
Cualquier integración está diseñada para que sea tan sencilla de usar (con dependencias) que puedas crear un "plug-in" para tu aplicación en dos líneas de código usando la misma estructura y sintáxis que usaste para tus *path operations*.
Cualquier integración está diseñada para que sea tan sencilla de usar (con dependencias) que puedas crear un "plug-in" para tu aplicación en dos líneas de código usando la misma estructura y sintaxis que usaste para tus *path operations*.
### Probado
@ -181,7 +181,7 @@ Esto incluye a librerías externas basadas en Pydantic como <abbr title="Object-
Esto también significa que en muchos casos puedes pasar el mismo objeto que obtuviste de un request **directamente a la base de datos**, dado que todo es validado automáticamente.
Lo mismo aplica para el sentido contrario. En muchos casos puedes pasarle el objeto que obtienes de la base de datos **directamente al cliente**.
Lo mismo aplica para el sentido contrario. En muchos casos puedes pasar el objeto que obtienes de la base de datos **directamente al cliente**.
Con **FastAPI** obtienes todas las características de **Pydantic** (dado que FastAPI está basado en Pydantic para todo el manejo de datos):

8
docs/es/docs/index.md

@ -37,7 +37,7 @@ Sus características principales son:
* **Robusto**: Crea código listo para producción con documentación automática interactiva.
* **Basado en estándares**: Basado y totalmente compatible con los estándares abiertos para APIs: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> (conocido previamente como Swagger) y <a href="https://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>.
<small>* Esta estimación está basada en pruebas con un equipo de desarrollo interno contruyendo aplicaciones listas para producción.</small>
<small>* Esta estimación está basada en pruebas con un equipo de desarrollo interno construyendo aplicaciones listas para producción.</small>
## Sponsors
@ -295,11 +295,11 @@ Ahora ve a <a href="http://127.0.0.1:8000/docs" class="external-link" target="_b
![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)
* Haz clíck en el botón de "Try it out" que te permite llenar los parámetros e interactuar directamente con la API:
* Haz click en el botón de "Try it out" que te permite llenar los parámetros e interactuar directamente con la API:
![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png)
* Luego haz clíck en el botón de "Execute". La interfaz de usuario se comunicará con tu API, enviará los parámetros y recibirá los resultados para mostrarlos en pantalla:
* Luego haz click en el botón de "Execute". La interfaz de usuario se comunicará con tu API, enviará los parámetros y recibirá los resultados para mostrarlos en pantalla:
![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png)
@ -317,7 +317,7 @@ En resumen, declaras los tipos de parámetros, body, etc. **una vez** como pará
Lo haces con tipos modernos estándar de Python.
No tienes que aprender una sintáxis nueva, los métodos o clases de una library específica, etc.
No tienes que aprender una sintaxis nueva, los métodos o clases de una library específica, etc.
Solo **Python 3.8+** estándar.

16
docs/es/docs/python-types.md

@ -2,7 +2,7 @@
**Python 3.6+** tiene soporte para <abbr title="en español, anotaciones de tipo. En inglés también se conocen como: type annotations">"type hints"</abbr> opcionales.
Estos **type hints** son una nueva sintáxis, desde Python 3.6+, que permite declarar el <abbr title="por ejemplo: str, int, float, bool">tipo</abbr> de una variable.
Estos **type hints** son una nueva sintaxis, desde Python 3.6+, que permite declarar el <abbr title="por ejemplo: str, int, float, bool">tipo</abbr> de una variable.
Usando las declaraciones de tipos para tus variables, los editores y otras herramientas pueden proveerte un soporte mejor.
@ -33,7 +33,7 @@ La función hace lo siguiente:
* Toma un `first_name` y un `last_name`.
* Convierte la primera letra de cada uno en una letra mayúscula con `title()`.
* Las <abbr title="las junta como si fuesen una. Con el contenido de una después de la otra. En inlgés: concatenate.">concatena</abbr> con un espacio en la mitad.
* Las <abbr title="las junta como si fuesen una. Con el contenido de una después de la otra. En inglés: concatenate.">concatena</abbr> con un espacio en la mitad.
```Python hl_lines="2"
{!../../../docs_src/python_types/tutorial001.py!}
@ -51,9 +51,9 @@ Pero, luego tienes que llamar "ese método que convierte la primera letra en una
Era `upper`? O era `uppercase`? `first_uppercase`? `capitalize`?
Luego lo intentas con el viejo amigo de los programadores, el autocompletado del editor.
Luego lo intentas con el viejo amigo de los programadores, el auto-completado del editor.
Escribes el primer parámetro de la función `first_name`, luego un punto (`.`) y luego presionas `Ctrl+Space` para iniciar el autocompletado.
Escribes el primer parámetro de la función `first_name`, luego un punto (`.`) y luego presionas `Ctrl+Space` para iniciar el auto-completado.
Tristemente, no obtienes nada útil:
@ -97,7 +97,7 @@ Añadir los type hints normalmente no cambia lo que sucedería si ellos no estuv
Pero ahora imagina que nuevamente estás creando la función, pero con los type hints.
En el mismo punto intentas iniciar el autocompletado con `Ctrl+Space` y ves:
En el mismo punto intentas iniciar el auto-completado con `Ctrl+Space` y ves:
<img src="https://fastapi.tiangolo.com/img/python-types/image02.png">
@ -113,7 +113,7 @@ Mira esta función que ya tiene type hints:
{!../../../docs_src/python_types/tutorial003.py!}
```
Como el editor conoce el tipo de las variables no solo obtienes autocompletado, si no que también obtienes chequeo de errores:
Como el editor conoce el tipo de las variables no solo obtienes auto-completado, si no que también obtienes chequeo de errores:
<img src="https://fastapi.tiangolo.com/img/python-types/image04.png">
@ -162,7 +162,7 @@ De `typing`, importa `List` (con una `L` mayúscula):
{!../../../docs_src/python_types/tutorial006.py!}
```
Declara la variable con la misma sintáxis de los dos puntos (`:`).
Declara la variable con la misma sintaxis de los dos puntos (`:`).
Pon `List` como el tipo.
@ -176,7 +176,7 @@ Esto significa: la variable `items` es una `list` y cada uno de los ítems en es
Con esta declaración tu editor puede proveerte soporte inclusive mientras está procesando ítems de la lista.
Sin tipos el autocompletado en este tipo de estructura es casi imposible de lograr:
Sin tipos el auto-completado en este tipo de estructura es casi imposible de lograr:
<img src="https://fastapi.tiangolo.com/img/python-types/image05.png">

2
docs/es/docs/tutorial/first-steps.md

@ -303,7 +303,7 @@ En este caso es una función `async`.
---
También podrías definirla como una función normal, en vez de `async def`:
También podrías definirla como una función estándar en lugar de `async def`:
```Python hl_lines="7"
{!../../../docs_src/first_steps/tutorial003.py!}

2
docs/es/docs/tutorial/index.md

@ -28,7 +28,7 @@ $ uvicorn main:app --reload
Se **RECOMIENDA** que escribas o copies el código, lo edites y lo ejecutes localmente.
Usarlo en tu editor de código es lo que realmente te muestra los beneficios de FastAPI, al ver la poca cantidad de código que tienes que escribir, todas las verificaciones de tipo, autocompletado, etc.
Usarlo en tu editor de código es lo que realmente te muestra los beneficios de FastAPI, al ver la poca cantidad de código que tienes que escribir, todas las verificaciones de tipo, auto-completado, etc.
---

6
docs/es/docs/tutorial/path-params.md

@ -25,7 +25,7 @@ Puedes declarar el tipo de un parámetro de path en la función usando las anota
En este caso, `item_id` es declarado como un `int`.
!!! check "Revisa"
Esto te dará soporte en el editor dentro de tu función, con chequeos de errores, autocompletado, etc.
Esto te dará soporte en el editor dentro de tu función, con chequeo de errores, auto-completado, etc.
## <abbr title="también conocido en inglés como: serialization, parsing, marshalling">Conversión</abbr> de datos
@ -135,7 +135,7 @@ Luego crea atributos de clase con valores fijos, que serán los valores disponib
Las <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (o enums) están disponibles en Python</a> desde la versión 3.4.
!!! tip "Consejo"
Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de <abbr title="Tecnicamente, arquitecturas de modelos de Deep Learning">modelos</abbr> de Machine Learning.
Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de <abbr title="Técnicamente, arquitecturas de modelos de Deep Learning">modelos</abbr> de Machine Learning.
### Declara un *parámetro de path*
@ -234,7 +234,7 @@ Entonces lo puedes usar con:
Con **FastAPI**, usando declaraciones de tipo de Python intuitivas y estándares, obtienes:
* Soporte en el editor: chequeos de errores, auto-completado, etc.
* Soporte en el editor: chequeo de errores, auto-completado, etc.
* "<abbr title="convertir el string que viene de un HTTP request a datos de Python">Parsing</abbr>" de datos
* Validación de datos
* Anotación de la API y documentación automática

315
docs/ja/docs/python-types.md

@ -0,0 +1,315 @@
# Pythonの型の紹介
**Python 3.6以降** では「型ヒント」オプションがサポートされています。
これらの **"型ヒント"** は変数の<abbr title="例: str, int, float, bool"></abbr>を宣言することができる新しい構文です。(Python 3.6以降)
変数に型を宣言することでエディターやツールがより良いサポートを提供することができます。
ここではPythonの型ヒントについての **クイックチュートリアル/リフレッシュ** で、**FastAPI**でそれらを使用するために必要な最低限のことだけをカバーしています。...実際には本当に少ないです。
**FastAPI** はすべてこれらの型ヒントに基づいており、多くの強みと利点を与えてくれます。
しかしたとえまったく **FastAPI** を使用しない場合でも、それらについて少し学ぶことで利点を得ることができるでしょう。
!!! note "備考"
もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。
## 動機
簡単な例から始めてみましょう:
```Python
{!../../../docs_src/python_types/tutorial001.py!}
```
このプログラムを実行すると以下が出力されます:
```
John Doe
```
この関数は以下のようなことを行います:
* `first_name`と`last_name`を取得します。
* `title()`を用いて、それぞれの最初の文字を大文字に変換します。
* 真ん中にスペースを入れて<abbr title="次から次へと中身を入れて一つにまとめる">連結</abbr>します。
```Python hl_lines="2"
{!../../../docs_src/python_types/tutorial001.py!}
```
### 編集
これはとても簡単なプログラムです。
しかし、今、あなたがそれを一から書いていたと想像してみてください。
パラメータの準備ができていたら、そのとき、関数の定義を始めていたことでしょう...
しかし、そうすると「最初の文字を大文字に変換するあのメソッド」を呼び出す必要があります。
それは`upper`でしたか?`uppercase`でしたか?それとも`first_uppercase`?または`capitalize`?
そして、古くからプログラマーの友人であるエディタで自動補完を試してみます。
関数の最初のパラメータ`first_name`を入力し、ドット(`.`)を入力してから、`Ctrl+Space`を押すと補完が実行されます。
しかし、悲しいことに、これはなんの役にも立ちません:
<img src="https://fastapi.tiangolo.com/img/python-types/image01.png">
### 型の追加
先ほどのコードから一行変更してみましょう。
以下の関数のパラメータ部分を:
```Python
first_name, last_name
```
以下へ変更します:
```Python
first_name: str, last_name: str
```
これだけです。
それが「型ヒント」です:
```Python hl_lines="1"
{!../../../docs_src/python_types/tutorial002.py!}
```
これは、以下のようにデフォルト値を宣言するのと同じではありません:
```Python
first_name="john", last_name="doe"
```
それとは別物です。
イコール(`=`)ではなく、コロン(`:`)を使用します。
そして、通常、型ヒントを追加しても、それらがない状態と起こることは何も変わりません。
しかし今、あなたが再びその関数を作成している最中に、型ヒントを使っていると想像してみて下さい。
同じタイミングで`Ctrl+Space`で自動補完を実行すると、以下のようになります:
<img src="https://fastapi.tiangolo.com/img/python-types/image02.png">
これであれば、あなたは「ベルを鳴らす」一つを見つけるまで、オプションを見て、スクロールすることができます:
<img src="https://fastapi.tiangolo.com/img/python-types/image03.png">
## より強い動機
この関数を見てください。すでに型ヒントを持っています:
```Python hl_lines="1"
{!../../../docs_src/python_types/tutorial003.py!}
```
エディタは変数の型を知っているので、補完だけでなく、エラーチェックをすることもできます。
<img src="https://fastapi.tiangolo.com/img/python-types/image04.png">
これで`age`を`str(age)`で文字列に変換して修正する必要があることがわかります:
```Python hl_lines="2"
{!../../../docs_src/python_types/tutorial004.py!}
```
## 型の宣言
関数のパラメータとして、型ヒントを宣言している主な場所を確認しました。
これは **FastAPI** で使用する主な場所でもあります。
### 単純な型
`str`だけでなく、Pythonの標準的な型すべてを宣言することができます。
例えば、以下を使用可能です:
* `int`
* `float`
* `bool`
* `bytes`
```Python hl_lines="1"
{!../../../docs_src/python_types/tutorial005.py!}
```
### 型パラメータを持つジェネリック型
データ構造の中には、`dict`、`list`、`set`、そして`tuple`のように他の値を含むことができるものがあります。また内部の値も独自の型を持つことができます。
これらの型や内部の型を宣言するには、Pythonの標準モジュール`typing`を使用します。
これらの型ヒントをサポートするために特別に存在しています。
#### `List`
例えば、`str`の`list`の変数を定義してみましょう。
`typing`から`List`をインポートします(大文字の`L`を含む):
```Python hl_lines="1"
{!../../../docs_src/python_types/tutorial006.py!}
```
同じようにコロン(`:`)の構文で変数を宣言します。
型として、`List`を入力します。
リストはいくつかの内部の型を含む型なので、それらを角括弧で囲んでいます。
```Python hl_lines="4"
{!../../../docs_src/python_types/tutorial006.py!}
```
!!! tip "豆知識"
角括弧内の内部の型は「型パラメータ」と呼ばれています。
この場合、`str`は`List`に渡される型パラメータです。
つまり: 変数`items`は`list`であり、このリストの各項目は`str`です。
そうすることで、エディタはリストの項目を処理している間にもサポートを提供できます。
<img src="https://fastapi.tiangolo.com/img/python-types/image05.png">
タイプがなければ、それはほぼ不可能です。
変数`item`はリスト`items`の要素の一つであることに注意してください。
それでも、エディタはそれが`str`であることを知っていて、そのためのサポートを提供しています。
#### `Tuple``Set`
`tuple`と`set`の宣言も同様です:
```Python hl_lines="1 4"
{!../../../docs_src/python_types/tutorial007.py!}
```
つまり:
* 変数`items_t`は`int`、`int`、`str`の3つの項目を持つ`tuple`です
* 変数`items_s`はそれぞれの項目が`bytes`型である`set`です。
#### `Dict`
`dict`を宣言するためには、カンマ区切りで2つの型パラメータを渡します。
最初の型パラメータは`dict`のキーです。
2番目の型パラメータは`dict`の値です。
```Python hl_lines="1 4"
{!../../../docs_src/python_types/tutorial008.py!}
```
つまり:
* 変数`prices`は`dict`であり:
* この`dict`のキーは`str`型です。(つまり、各項目の名前)
* この`dict`の値は`float`型です。(つまり、各項目の価格)
#### `Optional`
また、`Optional`を使用して、変数が`str`のような型を持つことを宣言することもできますが、それは「オプション」であり、`None`にすることもできます。
```Python hl_lines="1 4"
{!../../../docs_src/python_types/tutorial009.py!}
```
ただの`str`の代わりに`Optional[str]`を使用することで、エディタは値が常に`str`であると仮定している場合に実際には`None`である可能性があるエラーを検出するのに役立ちます。
#### ジェネリック型
以下のように角括弧で型パラメータを取る型を:
* `List`
* `Tuple`
* `Set`
* `Dict`
* `Optional`
* ...など
**ジェネリック型** または **ジェネリクス** と呼びます。
### 型としてのクラス
変数の型としてクラスを宣言することもできます。
例えば、`Person`クラスという名前のクラスがあるとしましょう:
```Python hl_lines="1 2 3"
{!../../../docs_src/python_types/tutorial010.py!}
```
変数の型を`Person`として宣言することができます:
```Python hl_lines="6"
{!../../../docs_src/python_types/tutorial010.py!}
```
そして、再び、すべてのエディタのサポートを得ることができます:
<img src="https://fastapi.tiangolo.com/img/python-types/image06.png">
## Pydanticのモデル
<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> はデータ検証を行うためのPythonライブラリです。
データの「形」を属性付きのクラスとして宣言します。
そして、それぞれの属性は型を持ちます。
さらに、いくつかの値を持つクラスのインスタンスを作成すると、その値を検証し、適切な型に変換して(もしそうであれば)全てのデータを持つオブジェクトを提供してくれます。
また、その結果のオブジェクトですべてのエディタのサポートを受けることができます。
Pydanticの公式ドキュメントから引用:
```Python
{!../../../docs_src/python_types/tutorial011.py!}
```
!!! info "情報"
Pydanticについてより学びたい方は<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">ドキュメントを参照してください</a>.
**FastAPI** はすべてPydanticをベースにしています。
すべてのことは[チュートリアル - ユーザーガイド](tutorial/index.md){.internal-link target=_blank}で実際に見ることができます。
## **FastAPI**での型ヒント
**FastAPI** はこれらの型ヒントを利用していくつかのことを行います。
**FastAPI** では型ヒントを使って型パラメータを宣言すると以下のものが得られます:
* **エディタサポート**.
* **型チェック**.
...そして **FastAPI** は同じように宣言をすると、以下のことを行います:
* **要件の定義**: リクエストパスパラメータ、クエリパラメータ、ヘッダー、ボディ、依存関係などから要件を定義します。
* **データの変換**: リクエストのデータを必要な型に変換します。
* **データの検証**: リクエストごとに:
* データが無効な場合にクライアントに返される **自動エラー** を生成します。
* **ドキュメント** OpenAPIを使用したAPI:
* 自動的に対話型ドキュメントのユーザーインターフェイスで使用されます。
すべてが抽象的に聞こえるかもしれません。心配しないでください。 この全ての動作は [チュートリアル - ユーザーガイド](tutorial/index.md){.internal-link target=_blank}で見ることができます。
重要なのは、Pythonの標準的な型を使うことで、(クラスやデコレータなどを追加するのではなく)1つの場所で **FastAPI** が多くの作業を代わりにやってくれているということです。
!!! info "情報"
すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、<a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">`mypy`のチートシートを参照してください</a>

94
docs/ja/docs/tutorial/background-tasks.md

@ -0,0 +1,94 @@
# バックグラウンドタスク
レスポンスを返した *後に* 実行されるバックグラウンドタスクを定義できます。
これは、リクエスト後に処理を開始する必要があるが、クライアントがレスポンスを受け取る前に処理を終える必要のない操作に役立ちます。
これには、たとえば次のものが含まれます。
* 作業実行後のメール通知:
* メールサーバーへの接続とメールの送信は「遅い」(数秒) 傾向があるため、すぐにレスポンスを返し、バックグラウンドでメール通知ができます。
* データ処理:
* たとえば、時間のかかる処理を必要とするファイル受信時には、「受信済み」(HTTP 202) のレスポンスを返し、バックグラウンドで処理できます。
## `BackgroundTasks` の使用
まず初めに、`BackgroundTasks` をインポートし、` BackgroundTasks` の型宣言と共に、*path operation 関数* のパラメーターを定義します:
```Python hl_lines="1 13"
{!../../../docs_src/background_tasks/tutorial001.py!}
```
**FastAPI** は、`BackgroundTasks` 型のオブジェクトを作成し、そのパラメーターに渡します。
## タスク関数の作成
バックグラウンドタスクとして実行される関数を作成します。
これは、パラメーターを受け取ることができる単なる標準的な関数です。
これは `async def` または通常の `def` 関数であり、**FastAPI** はこれを正しく処理します。
ここで、タスク関数はファイル書き込みを実行します (メール送信のシミュレーション)。
また、書き込み操作では `async``await` を使用しないため、通常の `def` で関数を定義します。
```Python hl_lines="6-9"
{!../../../docs_src/background_tasks/tutorial001.py!}
```
## バックグラウンドタスクの追加
*path operations 関数* 内で、`.add_task()` メソッドを使用してタスク関数を *background tasks* オブジェクトに渡します。
```Python hl_lines="14"
{!../../../docs_src/background_tasks/tutorial001.py!}
```
`.add_task()` は以下の引数を受け取ります:
* バックグラウンドで実行されるタスク関数 (`write_notification`)。
* タスク関数に順番に渡す必要のある引数の列 (`email`)。
* タスク関数に渡す必要のあるキーワード引数 (`message="some notification"`)。
## 依存性注入
`BackgroundTasks` の使用は依存性注入システムでも機能し、様々な階層 (*path operations 関数*、依存性 (依存可能性)、サブ依存性など) で `BackgroundTasks` 型のパラメーターを宣言できます。
**FastAPI** は、それぞれの場合の処理​​方法と同じオブジェクトの再利用方法を知っているため、すべてのバックグラウンドタスクがマージされ、バックグラウンドで後で実行されます。
```Python hl_lines="13 15 22 25"
{!../../../docs_src/background_tasks/tutorial002.py!}
```
この例では、レスポンスが送信された *後* にメッセージが `log.txt` ファイルに書き込まれます。
リクエストにクエリがあった場合、バックグラウンドタスクでログに書き込まれます。
そして、*path operations 関数* で生成された別のバックグラウンドタスクは、`email` パスパラメータを使用してメッセージを書き込みます。
## 技術的な詳細
`BackgroundTasks` クラスは、<a href="https://www.starlette.io/background/" class="external-link" target="_blank">`starlette.background`</a>から直接取得されます。
これは、FastAPI に直接インポート/インクルードされるため、`fastapi` からインポートできる上に、`starlette.background`から別の `BackgroundTask` (末尾に `s` がない) を誤ってインポートすることを回避できます。
`BackgroundTasks`のみを使用することで (`BackgroundTask` ではなく)、`Request` オブジェクトを直接使用する場合と同様に、それを *path operations 関数* パラメーターとして使用し、**FastAPI** に残りの処理を任せることができます。
それでも、FastAPI で `BackgroundTask` を単独で使用することは可能ですが、コード内でオブジェクトを作成し、それを含むStarlette `Response` を返す必要があります。
詳細については、<a href="https://www.starlette.io/background/" class="external-link" target="_blank">バックグラウンドタスクに関する Starlette の公式ドキュメント</a>を参照して下さい。
## 警告
大量のバックグラウンド計算が必要であり、必ずしも同じプロセスで実行する必要がない場合 (たとえば、メモリや変数などを共有する必要がない場合)、<a href="https://www.celeryproject.org/" class="external-link" target="_blank">Celery</a> のようなより大きな他のツールを使用するとメリットがあるかもしれません。
これらは、より複雑な構成、RabbitMQ や Redis などのメッセージ/ジョブキューマネージャーを必要とする傾向がありますが、複数のプロセス、特に複数のサーバーでバックグラウンドタスクを実行できます。
例を確認するには、[Project Generators](../project-generation.md){.internal-link target=_blank} を参照してください。これらにはすべて、Celery が構築済みです。
ただし、同じ **FastAPI** アプリから変数とオブジェクトにアクセスする必要がある場合、または小さなバックグラウンドタスク (電子メール通知の送信など) を実行する必要がある場合は、単に `BackgroundTasks` を使用できます。
## まとめ
`BackgroundTasks` をインポートして、*path operations 関数* や依存関係のパラメータに `BackgroundTasks`を使用し、バックグラウンドタスクを追加して下さい。

48
docs/ja/docs/tutorial/body-fields.md

@ -0,0 +1,48 @@
# ボディ - フィールド
`Query`や`Path`、`Body`を使って *path operation関数* のパラメータに追加のバリデーションやメタデータを宣言するのと同じように、Pydanticの`Field`を使ってPydanticモデルの内部でバリデーションやメタデータを宣言することができます。
## `Field`のインポート
まず、以下のようにインポートします:
```Python hl_lines="4"
{!../../../docs_src/body_fields/tutorial001.py!}
```
!!! warning "注意"
`Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。
## モデルの属性の宣言
以下のように`Field`をモデルの属性として使用することができます:
```Python hl_lines="11 12 13 14"
{!../../../docs_src/body_fields/tutorial001.py!}
```
`Field`は`Query`や`Path`、`Body`と同じように動作し、全く同様のパラメータなどを持ちます。
!!! note "技術詳細"
実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。
また、Pydanticの`Field`は`FieldInfo`のインスタンスも返します。
`Body`は`FieldInfo`のサブクラスのオブジェクトを直接返すこともできます。そして、他にも`Body`クラスのサブクラスであるものがあります。
`fastapi`から`Query`や`Path`などをインポートする場合、これらは実際には特殊なクラスを返す関数であることに注意してください。
!!! tip "豆知識"
型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。
## 追加情報の追加
追加情報は`Field`や`Query`、`Body`などで宣言することができます。そしてそれは生成されたJSONスキーマに含まれます。
後に例を用いて宣言を学ぶ際に、追加情報を句悪方法を学べます。
## まとめ
Pydanticの`Field`を使用して、モデルの属性に追加のバリデーションやメタデータを宣言することができます。
追加のキーワード引数を使用して、追加のJSONスキーマのメタデータを渡すこともできます。

169
docs/ja/docs/tutorial/body-multiple-params.md

@ -0,0 +1,169 @@
# ボディ - 複数のパラメータ
これまで`Path`と`Query`をどう使うかを見てきましたが、リクエストボディの宣言のより高度な使い方を見てみましょう。
## `Path`、`Query`とボディパラメータを混ぜる
まず、もちろん、`Path`と`Query`とリクエストボディのパラメータの宣言は自由に混ぜることができ、 **FastAPI** は何をするべきかを知っています。
また、デフォルトの`None`を設定することで、ボディパラメータをオプションとして宣言することもできます:
```Python hl_lines="19 20 21"
{!../../../docs_src/body_multiple_params/tutorial001.py!}
```
!!! note "備考"
この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値は`None`です。
## 複数のボディパラメータ
上述の例では、*path operations*は`item`の属性を持つ以下のようなJSONボディを期待していました:
```JSON
{
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
}
```
しかし、`item`と`user`のように複数のボディパラメータを宣言することもできます:
```Python hl_lines="22"
{!../../../docs_src/body_multiple_params/tutorial002.py!}
```
この場合、**FastAPI**は関数内に複数のボディパラメータ(Pydanticモデルである2つのパラメータ)があることに気付きます。
そのため、パラメータ名をボディのキー(フィールド名)として使用し、以下のようなボディを期待しています:
```JSON
{
"item": {
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
},
"user": {
"username": "dave",
"full_name": "Dave Grohl"
}
}
```
!!! note "備考"
以前と同じように`item`が宣言されていたにもかかわらず、`item`はキー`item`を持つボディの内部にあることが期待されていることに注意してください。
**FastAPI** はリクエストから自動で変換を行い、パラメータ`item`が特定の内容を受け取り、`user`も同じように特定の内容を受け取ります。
複合データの検証を行い、OpenAPIスキーマや自動ドキュメントのように文書化してくれます。
## ボディ内の単数値
クエリとパスパラメータの追加データを定義するための `Query``Path` があるのと同じように、 **FastAPI** は同等の `Body` を提供します。
例えば、前のモデルを拡張して、同じボディに `item``user` の他にもう一つのキー `importance` を入れたいと決めることができます。
単数値なのでそのまま宣言すると、**FastAPI** はそれがクエリパラメータであるとみなします。
しかし、`Body`を使用して、**FastAPI** に別のボディキーとして扱うように指示することができます:
```Python hl_lines="23"
{!../../../docs_src/body_multiple_params/tutorial003.py!}
```
この場合、**FastAPI** は以下のようなボディを期待します:
```JSON
{
"item": {
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
},
"user": {
"username": "dave",
"full_name": "Dave Grohl"
},
"importance": 5
}
```
繰り返しになりますが、データ型の変換、検証、文書化などを行います。
## 複数のボディパラメータとクエリ
もちろん、ボディパラメータに加えて、必要に応じて追加のクエリパラメータを宣言することもできます。
デフォルトでは、単数値はクエリパラメータとして解釈されるので、明示的に `Query` を追加する必要はありません。
```Python
q: str = None
```
以下において:
```Python hl_lines="27"
{!../../../docs_src/body_multiple_params/tutorial004.py!}
```
!!! info "情報"
`Body`もまた、後述する `Query``Path` などと同様に、すべての検証パラメータとメタデータパラメータを持っています。
## 単一のボディパラメータの埋め込み
Pydanticモデル`Item`のボディパラメータ`item`を1つだけ持っているとしましょう。
デフォルトでは、**FastAPI**はそのボディを直接期待します。
しかし、追加のボディパラメータを宣言したときのように、キー `item` を持つ JSON とその中のモデルの内容を期待したい場合は、特別な `Body` パラメータ `embed` を使うことができます:
```Python
item: Item = Body(..., embed=True)
```
以下において:
```Python hl_lines="17"
{!../../../docs_src/body_multiple_params/tutorial005.py!}
```
この場合、**FastAPI** は以下のようなボディを期待します:
```JSON hl_lines="2"
{
"item": {
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
}
}
```
以下の代わりに:
```JSON
{
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
}
```
## まとめ
リクエストが単一のボディしか持てない場合でも、*path operation関数*に複数のボディパラメータを追加することができます。
しかし、**FastAPI** はそれを処理し、関数内の正しいデータを与え、*path operation*内の正しいスキーマを検証し、文書化します。
また、ボディの一部として受け取る単数値を宣言することもできます。
また、単一のパラメータしか宣言されていない場合でも、ボディをキーに埋め込むように **FastAPI** に指示することができます。

244
docs/ja/docs/tutorial/body-nested-models.md

@ -0,0 +1,244 @@
# ボディ - ネストされたモデル
**FastAPI** を使用すると、深くネストされた任意のモデルを定義、検証、文書化、使用することができます(Pydanticのおかげです)。
## リストのフィールド
属性をサブタイプとして定義することができます。例えば、Pythonの`list`は以下のように定義できます:
```Python hl_lines="12"
{!../../../docs_src/body_nested_models/tutorial001.py!}
```
これにより、各項目の型は宣言されていませんが、`tags`はある項目のリストになります。
## タイプパラメータを持つリストのフィールド
しかし、Pythonには型や「タイプパラメータ」を使ってリストを宣言する方法があります:
### typingの`List`をインポート
まず、Pythonの標準の`typing`モジュールから`List`をインポートします:
```Python hl_lines="1"
{!../../../docs_src/body_nested_models/tutorial002.py!}
```
### タイプパラメータを持つ`List`の宣言
`list`や`dict`、`tuple`のようなタイプパラメータ(内部の型)を持つ型を宣言するには:
* `typing`モジュールからそれらをインストールします。
* 角括弧(`[`と`]`)を使って「タイプパラメータ」として内部の型を渡します:
```Python
from typing import List
my_list: List[str]
```
型宣言の標準的なPythonの構文はこれだけです。
内部の型を持つモデルの属性にも同じ標準の構文を使用してください。
そのため、以下の例では`tags`を具体的な「文字列のリスト」にすることができます:
```Python hl_lines="14"
{!../../../docs_src/body_nested_models/tutorial002.py!}
```
## セット型
しかし、よく考えてみると、タグは繰り返すべきではなく、おそらくユニークな文字列になるのではないかと気付いたとします。
そして、Pythonにはユニークな項目のセットのための特別なデータ型`set`があります。
そのため、以下のように、`Set`をインポートして`str`の`set`として`tags`を宣言することができます:
```Python hl_lines="1 14"
{!../../../docs_src/body_nested_models/tutorial003.py!}
```
これを使えば、データが重複しているリクエストを受けた場合でも、ユニークな項目のセットに変換されます。
そして、そのデータを出力すると、たとえソースに重複があったとしても、固有の項目のセットとして出力されます。
また、それに応じて注釈をつけたり、文書化したりします。
## ネストされたモデル
Pydanticモデルの各属性には型があります。
しかし、その型はそれ自体が別のPydanticモデルである可能性があります。
そのため、特定の属性名、型、バリデーションを指定して、深くネストしたJSON`object`を宣言することができます。
すべては、任意のネストにされています。
### サブモデルの定義
例えば、`Image`モデルを定義することができます:
```Python hl_lines="9 10 11"
{!../../../docs_src/body_nested_models/tutorial004.py!}
```
### サブモデルを型として使用
そして、それを属性の型として使用することができます:
```Python hl_lines="20"
{!../../../docs_src/body_nested_models/tutorial004.py!}
```
これは **FastAPI** が以下のようなボディを期待することを意味します:
```JSON
{
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2,
"tags": ["rock", "metal", "bar"],
"image": {
"url": "http://example.com/baz.jpg",
"name": "The Foo live"
}
}
```
繰り返しになりますが、**FastAPI** を使用して、その宣言を行うだけで以下のような恩恵を受けられます:
* ネストされたモデルでも対応可能なエディタのサポート(補完など)
* データ変換
* データの検証
* 自動文書化
## 特殊な型とバリデーション
`str`や`int`、`float`のような通常の単数型の他にも、`str`を継承したより複雑な単数型を使うこともできます。
すべてのオプションをみるには、<a href="https://pydantic-docs.helpmanual.io/usage/types/" class="external-link" target="_blank">Pydanticのエキゾチック な型</a>のドキュメントを確認してください。次の章でいくつかの例をみることができます。
例えば、`Image`モデルのように`url`フィールドがある場合、`str`の代わりにPydanticの`HttpUrl`を指定することができます:
```Python hl_lines="4 10"
{!../../../docs_src/body_nested_models/tutorial005.py!}
```
文字列は有効なURLであることが確認され、そのようにJSONスキーマ・OpenAPIで文書化されます。
## サブモデルのリストを持つ属性
Pydanticモデルを`list`や`set`などのサブタイプとして使用することもできます:
```Python hl_lines="20"
{!../../../docs_src/body_nested_models/tutorial006.py!}
```
これは、次のようなJSONボディを期待します(変換、検証、ドキュメントなど):
```JSON hl_lines="11"
{
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2,
"tags": [
"rock",
"metal",
"bar"
],
"images": [
{
"url": "http://example.com/baz.jpg",
"name": "The Foo live"
},
{
"url": "http://example.com/dave.jpg",
"name": "The Baz"
}
]
}
```
!!! info "情報"
`images`キーが画像オブジェクトのリストを持つようになったことに注目してください。
## 深くネストされたモデル
深くネストされた任意のモデルを定義することができます:
```Python hl_lines="9 14 20 23 27"
{!../../../docs_src/body_nested_models/tutorial007.py!}
```
!!! info "情報"
`Offer`は`Item`のリストであり、オプションの`Image`のリストを持っていることに注目してください。
## 純粋なリストのボディ
期待するJSONボディのトップレベルの値がJSON`array`(Pythonの`list`)であれば、Pydanticモデルと同じように、関数のパラメータで型を宣言することができます:
```Python
images: List[Image]
```
以下のように:
```Python hl_lines="15"
{!../../../docs_src/body_nested_models/tutorial008.py!}
```
## あらゆる場所でのエディタサポート
エディタのサポートもどこでも受けることができます。
以下のようにリストの中の項目でも:
<img src="https://fastapi.tiangolo.com/img/tutorial/body-nested-models/image01.png">
Pydanticモデルではなく、`dict`を直接使用している場合はこのようなエディタのサポートは得られません。
しかし、それらについて心配する必要はありません。入力された辞書は自動的に変換され、出力も自動的にJSONに変換されます。
## 任意の`dict`のボディ
また、ある型のキーと別の型の値を持つ`dict`としてボディを宣言することもできます。
有効なフィールド・属性名を事前に知る必要がありません(Pydanticモデルの場合のように)。
これは、まだ知らないキーを受け取りたいときに便利だと思います。
---
他にも、`int`のように他の型のキーを持ちたい場合などに便利です。
それをここで見ていきましょう。
この場合、`int`のキーと`float`の値を持つものであれば、どんな`dict`でも受け入れることができます:
```Python hl_lines="15"
{!../../../docs_src/body_nested_models/tutorial009.py!}
```
!!! tip "豆知識"
JSONはキーとして`str`しかサポートしていないことに注意してください。
しかしPydanticには自動データ変換機能があります。
これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。
そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。
## まとめ
**FastAPI** を使用すると、Pydanticモデルが提供する最大限の柔軟性を持ちながら、コードをシンプルに短く、エレガントに保つことができます。
以下のような利点があります:
* エディタのサポート(どこでも補完!)
* データ変換(別名:構文解析・シリアライズ)
* データの検証
* スキーマ文書
* 自動文書化

191
docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md

@ -0,0 +1,191 @@
# 依存関係としてのクラス
**依存性注入** システムを深く掘り下げる前に、先ほどの例をアップグレードしてみましょう。
## 前の例の`dict`
前の例では、依存関係("dependable")から`dict`を返していました:
```Python hl_lines="9"
{!../../../docs_src/dependencies/tutorial001.py!}
```
しかし、*path operation関数*のパラメータ`commons`に`dict`が含まれています。
また、エディタは`dict`のキーと値の型を知ることができないため、多くのサポート(補完のような)を提供することができません。
もっとうまくやれるはずです...。
## 依存関係を作るもの
これまでは、依存関係が関数として宣言されているのを見てきました。
しかし、依存関係を定義する方法はそれだけではありません(その方が一般的かもしれませんが)。
重要なのは、依存関係が「呼び出し可能」なものであることです。
Pythonにおける「**呼び出し可能**」とは、Pythonが関数のように「呼び出す」ことができるものを指します。
そのため、`something`オブジェクト(関数ではないかもしれませんが)を持っていて、それを次のように「呼び出す」(実行する)ことができるとします:
```Python
something()
```
または
```Python
something(some_argument, some_keyword_argument="foo")
```
これを「呼び出し可能」なものと呼びます。
## 依存関係としてのクラス
Pythonのクラスのインスタンスを作成する際に、同じ構文を使用していることに気づくかもしれません。
例えば:
```Python
class Cat:
def __init__(self, name: str):
self.name = name
fluffy = Cat(name="Mr Fluffy")
```
この場合、`fluffy`は`Cat`クラスのインスタンスです。
そして`fluffy`を作成するために、`Cat`を「呼び出している」ことになります。
そのため、Pythonのクラスもまた「呼び出し可能」です。
そして、**FastAPI** では、Pythonのクラスを依存関係として使用することができます。
FastAPIが実際にチェックしているのは、それが「呼び出し可能」(関数、クラス、その他なんでも)であり、パラメータが定義されているかどうかということです。
**FastAPI** の依存関係として「呼び出し可能なもの」を渡すと、その「呼び出し可能なもの」のパラメータを解析し、サブ依存関係も含めて、*path operation関数*のパラメータと同じように処理します。
それは、パラメータが全くない呼び出し可能なものにも適用されます。パラメータのない*path operation関数*と同じように。
そこで、上で紹介した依存関係の`common_parameters`を`CommonQueryParams`クラスに変更します:
```Python hl_lines="11 12 13 14 15"
{!../../../docs_src/dependencies/tutorial002.py!}
```
クラスのインスタンスを作成するために使用される`__init__`メソッドに注目してください:
```Python hl_lines="12"
{!../../../docs_src/dependencies/tutorial002.py!}
```
...以前の`common_parameters`と同じパラメータを持っています:
```Python hl_lines="8"
{!../../../docs_src/dependencies/tutorial001.py!}
```
これらのパラメータは **FastAPI** が依存関係を「解決」するために使用するものです。
どちらの場合も以下を持っています:
* オプショナルの`q`クエリパラメータ。
* `skip`クエリパラメータ、デフォルトは`0`。
* `limit`クエリパラメータ、デフォルトは`100`。
どちらの場合も、データは変換され、検証され、OpenAPIスキーマなどで文書化されます。
## 使用
これで、このクラスを使用して依存関係を宣言することができます。
```Python hl_lines="19"
{!../../../docs_src/dependencies/tutorial002.py!}
```
**FastAPI** は`CommonQueryParams`クラスを呼び出します。これにより、そのクラスの「インスタンス」が作成され、インスタンスはパラメータ`commons`として関数に渡されます。
## 型注釈と`Depends`
上のコードでは`CommonQueryParams`を2回書いていることに注目してください:
```Python
commons: CommonQueryParams = Depends(CommonQueryParams)
```
以下にある最後の`CommonQueryParams`:
```Python
... = Depends(CommonQueryParams)
```
...は、**FastAPI** が依存関係を知るために実際に使用するものです。
そこからFastAPIが宣言されたパラメータを抽出し、それが実際にFastAPIが呼び出すものです。
---
この場合、以下にある最初の`CommonQueryParams`:
```Python
commons: CommonQueryParams ...
```
...は **FastAPI** に対して特別な意味をもちません。FastAPIはデータ変換や検証などには使用しません(それらのためには`= Depends(CommonQueryParams)`を使用しています)。
実際には以下のように書けばいいだけです:
```Python
commons = Depends(CommonQueryParams)
```
以下にあるように:
```Python hl_lines="19"
{!../../../docs_src/dependencies/tutorial003.py!}
```
しかし、型を宣言することは推奨されています。そうすれば、エディタは`commons`のパラメータとして何が渡されるかを知ることができ、コードの補完や型チェックなどを行うのに役立ちます:
<img src="https://fastapi.tiangolo.com/img/tutorial/dependencies/image02.png">
## ショートカット
しかし、ここでは`CommonQueryParams`を2回書くというコードの繰り返しが発生していることがわかります:
```Python
commons: CommonQueryParams = Depends(CommonQueryParams)
```
依存関係が、クラス自体のインスタンスを作成するために**FastAPI**が「呼び出す」*特定の*クラスである場合、**FastAPI** はこれらのケースのショートカットを提供しています。
それらの具体的なケースについては以下のようにします:
以下のように書く代わりに:
```Python
commons: CommonQueryParams = Depends(CommonQueryParams)
```
...以下のように書きます:
```Python
commons: CommonQueryParams = Depends()
```
パラメータの型として依存関係を宣言し、`Depends()`の中でパラメータを指定せず、`Depends()`をその関数のパラメータの「デフォルト」値(`=`のあとの値)として使用することで、`Depends(CommonQueryParams)`の中でクラス全体を*もう一度*書かなくてもよくなります。
同じ例では以下のようになります:
```Python hl_lines="19"
{!../../../docs_src/dependencies/tutorial004.py!}
```
...そして **FastAPI** は何をすべきか知っています。
!!! tip "豆知識"
役に立つというよりも、混乱するようであれば無視してください。それをする*必要*はありません。
それは単なるショートカットです。なぜなら **FastAPI** はコードの繰り返しを最小限に抑えることに気を使っているからです。

62
docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md

@ -0,0 +1,62 @@
# path operationデコレータの依存関係
場合によっては*path operation関数*の中で依存関係の戻り値を本当に必要としないこともあります。
もしくは、依存関係が値を返さない場合もあります。
しかし、それでも実行・解決する必要があります。
このような場合、*path operation関数*のパラメータを`Depends`で宣言する代わりに、*path operation decorator*に`dependencies`の`list`を追加することができます。
## *path operationデコレータ*への`dependencies`の追加
*path operationデコレータ*はオプショナルの引数`dependencies`を受け取ります。
それは`Depends()`の`list`であるべきです:
```Python hl_lines="17"
{!../../../docs_src/dependencies/tutorial006.py!}
```
これらの依存関係は、通常の依存関係と同様に実行・解決されます。しかし、それらの値(何かを返す場合)は*path operation関数*には渡されません。
!!! tip "豆知識"
エディタによっては、未使用の関数パラメータをチェックしてエラーとして表示するものもあります。
`dependencies`を`path operationデコレータ`で使用することで、エディタやツールのエラーを回避しながら確実に実行することができます。
また、コードの未使用のパラメータがあるのを見て、それが不要だと思ってしまうような新しい開発者の混乱を避けるのにも役立つかもしれません。
## 依存関係のエラーと戻り値
通常使用している依存関係の*関数*と同じものを使用することができます。
### 依存関係の要件
これらはリクエストの要件(ヘッダのようなもの)やその他のサブ依存関係を宣言することができます:
```Python hl_lines="6 11"
{!../../../docs_src/dependencies/tutorial006.py!}
```
### 例外の発生
これらの依存関係は通常の依存関係と同じように、例外を`raise`発生させることができます:
```Python hl_lines="8 13"
{!../../../docs_src/dependencies/tutorial006.py!}
```
### 戻り値
そして、値を返すことも返さないこともできますが、値は使われません。
つまり、すでにどこかで使っている通常の依存関係(値を返すもの)を再利用することができ、値は使われなくても依存関係は実行されます:
```Python hl_lines="9 14"
{!../../../docs_src/dependencies/tutorial006.py!}
```
## *path operations*のグループに対する依存関係
後で、より大きなアプリケーションの構造([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank})について読む時に、おそらく複数のファイルを使用して、*path operations*のグループに対して単一の`dependencies`パラメータを宣言する方法を学ぶでしょう。

225
docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md

@ -0,0 +1,225 @@
# yieldを持つ依存関係
FastAPIは、いくつかの<abbr title='時々"exit"、"cleanup"、"teardown"、"close"、"context managers"、 ...のように呼ばれる'>終了後の追加のステップ</abbr>を行う依存関係をサポートしています。
これを行うには、`return`の代わりに`yield`を使い、その後に追加のステップを書きます。
!!! tip "豆知識"
`yield`は必ず一度だけ使用するようにしてください。
!!! info "情報"
これを動作させるには、**Python 3.7** 以上を使用するか、**Python 3.6** では"backports"をインストールする必要があります:
```
pip install async-exit-stack async-generator
```
これにより<a href="https://github.com/sorcio/async_exit_stack" class="external-link" target="_blank">async-exit-stack</a><a href="https://github.com/python-trio/async_generator" class="external-link" target="_blank">async-generator</a>がインストールされます。
!!! note "技術詳細"
以下と一緒に使用できる関数なら何でも有効です:
* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a>または
* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
これらは **FastAPI** の依存関係として使用するのに有効です。
実際、FastAPIは内部的にこれら2つのデコレータを使用しています。
## `yield`を持つデータベースの依存関係
例えば、これを使ってデータベースセッションを作成し、終了後にそれを閉じることができます。
レスポンスを送信する前に`yield`文を含む前のコードのみが実行されます。
```Python hl_lines="2 3 4"
{!../../../docs_src/dependencies/tutorial007.py!}
```
生成された値は、*path operations*や他の依存関係に注入されるものです:
```Python hl_lines="4"
{!../../../docs_src/dependencies/tutorial007.py!}
```
`yield`文に続くコードは、レスポンスが送信された後に実行されます:
```Python hl_lines="5 6"
{!../../../docs_src/dependencies/tutorial007.py!}
```
!!! tip "豆知識"
`async`や通常の関数を使用することができます。
**FastAPI** は、通常の依存関係と同じように、それぞれで正しいことを行います。
## `yield`と`try`を持つ依存関係
`yield`を持つ依存関係で`try`ブロックを使用した場合、その依存関係を使用した際に発生した例外を受け取ることになります。
例えば、途中のどこかの時点で、別の依存関係や*path operation*の中で、データベーストランザクションを「ロールバック」したり、その他のエラーを作成したりするコードがあった場合、依存関係の中で例外を受け取ることになります。
そのため、依存関係の中にある特定の例外を`except SomeException`で探すことができます。
同様に、`finally`を用いて例外があったかどうかにかかわらず、終了ステップを確実に実行することができます。
```Python hl_lines="3 5"
{!../../../docs_src/dependencies/tutorial007.py!}
```
## `yield`を持つサブ依存関係
任意の大きさや形のサブ依存関係やサブ依存関係の「ツリー」を持つことができ、その中で`yield`を使用することができます。
**FastAPI** は、`yield`を持つ各依存関係の「終了コード」が正しい順番で実行されていることを確認します。
例えば、`dependency_c`は`dependency_b`と`dependency_b`に依存する`dependency_a`に、依存することができます:
```Python hl_lines="4 12 20"
{!../../../docs_src/dependencies/tutorial008.py!}
```
そして、それらはすべて`yield`を使用することができます。
この場合、`dependency_c`は終了コードを実行するために、`dependency_b`(ここでは`dep_b`という名前)の値がまだ利用可能である必要があります。
そして、`dependency_b`は`dependency_a`(ここでは`dep_a`という名前)の値を終了コードで利用できるようにする必要があります。
```Python hl_lines="16 17 24 25"
{!../../../docs_src/dependencies/tutorial008.py!}
```
同様に、`yield`と`return`が混在した依存関係を持つこともできます。
また、単一の依存関係を持っていて、`yield`などの他の依存関係をいくつか必要とすることもできます。
依存関係の組み合わせは自由です。
**FastAPI** は、全てが正しい順序で実行されていることを確認します。
!!! note "技術詳細"
これはPythonの<a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Context Managers</a>のおかげで動作します。
**FastAPI** はこれを実現するために内部的に使用しています。
## `yield`と`HTTPException`を持つ依存関係
`yield`と例外をキャッチする`try`ブロックを持つことができる依存関係を使用することができることがわかりました。
`yield`の後の終了コードで`HTTPException`などを発生させたくなるかもしれません。しかし**それはうまくいきません**
`yield`を持つ依存関係の終了コードは[例外ハンドラ](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}の*後に*実行されます。依存関係によって投げられた例外を終了コード(`yield`の後)でキャッチするものはなにもありません。
つまり、`yield`の後に`HTTPException`を発生させた場合、`HTTTPException`をキャッチしてHTTP 400のレスポンスを返すデフォルトの(あるいは任意のカスタムの)例外ハンドラは、その例外をキャッチすることができなくなります。
これは、依存関係に設定されているもの(例えば、DBセッション)を、例えば、バックグラウンドタスクで使用できるようにするものです。
バックグラウンドタスクはレスポンスが送信された*後*に実行されます。そのため、*すでに送信されている*レスポンスを変更する方法すらないので、`HTTPException`を発生させる方法はありません。
しかし、バックグラウンドタスクがDBエラーを発生させた場合、少なくとも`yield`で依存関係のセッションをロールバックしたり、きれいに閉じたりすることができ、エラーをログに記録したり、リモートのトラッキングシステムに報告したりすることができます。
例外が発生する可能性があるコードがある場合は、最も普通の「Python流」なことをして、コードのその部分に`try`ブロックを追加してください。
レスポンスを返したり、レスポンスを変更したり、`HTTPException`を発生させたりする*前に*処理したいカスタム例外がある場合は、[カスタム例外ハンドラ](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}を作成してください。
!!! tip "豆知識"
`HTTPException`を含む例外は、`yield`の*前*でも発生させることができます。ただし、後ではできません。
実行の順序は多かれ少なかれ以下の図のようになります。時間は上から下へと流れていきます。そして、各列はコードを相互作用させたり、実行したりしている部分の一つです。
```mermaid
sequenceDiagram
participant client as Client
participant handler as Exception handler
participant dep as Dep with yield
participant operation as Path Operation
participant tasks as Background tasks
Note over client,tasks: Can raise exception for dependency, handled after response is sent
Note over client,operation: Can raise HTTPException and can change the response
client ->> dep: Start request
Note over dep: Run code up to yield
opt raise
dep -->> handler: Raise HTTPException
handler -->> client: HTTP error response
dep -->> dep: Raise other exception
end
dep ->> operation: Run dependency, e.g. DB session
opt raise
operation -->> handler: Raise HTTPException
handler -->> client: HTTP error response
operation -->> dep: Raise other exception
end
operation ->> client: Return response to client
Note over client,operation: Response is already sent, can't change it anymore
opt Tasks
operation -->> tasks: Send background tasks
end
opt Raise other exception
tasks -->> dep: Raise other exception
end
Note over dep: After yield
opt Handle other exception
dep -->> dep: Handle exception, can't change response. E.g. close DB session.
end
```
!!! info "情報"
**1つのレスポンス** だけがクライアントに送信されます。それはエラーレスポンスの一つかもしれませんし、*path operation*からのレスポンスかもしれません。
いずれかのレスポンスが送信された後、他のレスポンスを送信することはできません。
!!! tip "豆知識"
この図は`HTTPException`を示していますが、[カスタム例外ハンドラ](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}を作成することで、他の例外を発生させることもできます。そして、その例外は依存関係の終了コードではなく、そのカスタム例外ハンドラによって処理されます。
しかし例外ハンドラで処理されない例外を発生させた場合は、依存関係の終了コードで処理されます。
## コンテキストマネージャ
### 「コンテキストマネージャ」とは
「コンテキストマネージャ」とは、`with`文の中で使用できるPythonオブジェクトのことです。
例えば、<a href="https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files" class="external-link" target="_blank">ファイルを読み込むには`with`を使用することができます</a>:
```Python
with open("./somefile.txt") as f:
contents = f.read()
print(contents)
```
その後の`open("./somefile.txt")`は「コンテキストマネージャ」と呼ばれるオブジェクトを作成します。
`with`ブロックが終了すると、例外があったとしてもファイルを確かに閉じます。
`yield`を依存関係を作成すると、**FastAPI** は内部的にそれをコンテキストマネージャに変換し、他の関連ツールと組み合わせます。
### `yield`を持つ依存関係でのコンテキストマネージャの使用
!!! warning "注意"
これは多かれ少なかれ、「高度な」発想です。
**FastAPI** を使い始めたばかりの方は、とりあえずスキップした方がよいかもしれません。
Pythonでは、<a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank">以下の2つのメソッドを持つクラスを作成する: `__enter__()`と`__exit__()`</a>ことでコンテキストマネージャを作成することができます。
また、依存関数の中で`with`や`async with`文を使用することによって`yield`を持つ **FastAPI** の依存関係の中でそれらを使用することができます:
```Python hl_lines="1 2 3 4 5 6 7 8 9 13"
{!../../../docs_src/dependencies/tutorial010.py!}
```
!!! tip "豆知識"
コンテキストマネージャを作成するもう一つの方法はwithです:
* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> または
* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
これらを使って、関数を単一の`yield`でデコレートすることができます。
これは **FastAPI** が内部的に`yield`を持つ依存関係のために使用しているものです。
しかし、FastAPIの依存関係にデコレータを使う必要はありません(そして使うべきではありません)。
FastAPIが内部的にやってくれます。

209
docs/ja/docs/tutorial/dependencies/index.md

@ -0,0 +1,209 @@
# 依存関係 - 最初のステップ
** FastAPI** は非常に強力でありながら直感的な **<abbr title="コンポーネント、リソース、プロバイダ、サービス、インジェクタブルとしても知られている">依存性注入</abbr>** システムを持っています。
それは非常にシンプルに使用できるように設計されており、開発者が他のコンポーネント **FastAPI** と統合するのが非常に簡単になるように設計されています。
## 「依存性注入」とは
**「依存性注入」** とは、プログラミングにおいて、コード(この場合は、*path operation関数*)が動作したり使用したりするために必要なもの(「依存関係」)を宣言する方法があることを意味します:
そして、そのシステム(この場合は、**FastAPI**)は、必要な依存関係をコードに提供するために必要なことは何でも行います(依存関係を「注入」します)。
これは以下のようなことが必要な時にとても便利です:
* ロジックを共有している。(同じコードロジックを何度も繰り返している)。
* データベース接続を共有する。
* セキュリティ、認証、ロール要件などを強制する。
* そのほかにも多くのこと...
これらすべてを、コードの繰り返しを最小限に抑えながら行います。
## 最初のステップ
非常にシンプルな例を見てみましょう。あまりにもシンプルなので、今のところはあまり参考にならないでしょう。
しかし、この方法では **依存性注入** システムがどのように機能するかに焦点を当てることができます。
### 依存関係の作成
まずは依存関係に注目してみましょう。
以下のように、*path operation関数*と同じパラメータを全て取ることができる関数にすぎません:
```Python hl_lines="8 9"
{!../../../docs_src/dependencies/tutorial001.py!}
```
これだけです。
**2行**。
そして、それはすべての*path operation関数*が持っているのと同じ形と構造を持っています。
「デコレータ」を含まない(`@app.get("/some-path")`を含まない)*path operation関数*と考えることもできます。
そして何でも返すことができます。
この場合、この依存関係は以下を期待しています:
* オプショナルのクエリパラメータ`q`は`str`です。
* オプショナルのクエリパラメータ`skip`は`int`で、デフォルトは`0`です。
* オプショナルのクエリパラメータ`limit`は`int`で、デフォルトは`100`です。
そして、これらの値を含む`dict`を返します。
### `Depends`のインポート
```Python hl_lines="3"
{!../../../docs_src/dependencies/tutorial001.py!}
```
### "dependant"での依存関係の宣言
*path operation関数*のパラメータに`Body`や`Query`などを使用するのと同じように、新しいパラメータに`Depends`を使用することができます:
```Python hl_lines="13 18"
{!../../../docs_src/dependencies/tutorial001.py!}
```
関数のパラメータに`Depends`を使用するのは`Body`や`Query`などと同じですが、`Depends`の動作は少し異なります。
`Depends`は1つのパラメータしか与えられません。
このパラメータは関数のようなものである必要があります。
そして、その関数は、*path operation関数*が行うのと同じ方法でパラメータを取ります。
!!! tip "豆知識"
次の章では、関数以外の「もの」が依存関係として使用できるものを見ていきます。
新しいリクエストが到着するたびに、**FastAPI** が以下のような処理を行います:
* 依存関係("dependable")関数を正しいパラメータで呼び出します。
* 関数の結果を取得します。
* *path operation関数*のパラメータにその結果を代入してください。
```mermaid
graph TB
common_parameters(["common_parameters"])
read_items["/items/"]
read_users["/users/"]
common_parameters --> read_items
common_parameters --> read_users
```
この方法では、共有されるコードを一度書き、**FastAPI** が*path operations*のための呼び出しを行います。
!!! check "確認"
特別なクラスを作成してどこかで **FastAPI** に渡して「登録」する必要はないことに注意してください。
`Depends`を渡すだけで、**FastAPI** が残りの処理をしてくれます。
## `async`にするかどうか
依存関係は **FastAPI**(*path operation関数*と同じ)からも呼び出されるため、関数を定義する際にも同じルールが適用されます。
`async def`や通常の`def`を使用することができます。
また、通常の`def`*path operation関数*の中に`async def`を入れて依存関係を宣言したり、`async def`*path operation関数*の中に`def`を入れて依存関係を宣言したりすることなどができます。
それは重要ではありません。**FastAPI** は何をすべきかを知っています。
!!! note "備考"
わからない場合は、ドキュメントの[Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank}の中の`async`と`await`についてのセクションを確認してください。
## OpenAPIとの統合
依存関係(およびサブ依存関係)のすべてのリクエスト宣言、検証、および要件は、同じOpenAPIスキーマに統合されます。
つまり、対話型ドキュメントにはこれらの依存関係から得られる全ての情報も含まれているということです:
<img src="https://fastapi.tiangolo.com/img/tutorial/dependencies/image01.png">
## 簡単な使い方
見てみると、*path*と*operation*が一致した時に*path operation関数*が宣言されていて、**FastAPI** が正しいパラメータで関数を呼び出してリクエストからデータを抽出する処理をしています。
実は、すべての(あるいはほとんどの)Webフレームワークは、このように動作します。
これらの関数を直接呼び出すことはありません。これらの関数はフレームワーク(この場合は、**FastAPI**)によって呼び出されます。
依存性注入システムでは、**FastAPI** に*path operation*もまた、*path operation関数*の前に実行されるべき他の何かに「依存」していることを伝えることができ、**FastAPI** がそれを実行し、結果を「注入」することを引き受けます。
他にも、「依存性注入」と同じような考えの一般的な用語があります:
* リソース
* プロバイダ
* サービス
* インジェクタブル
* コンポーネント
## **FastAPI** プラグイン
統合や「プラグイン」は **依存性注入** システムを使って構築することができます。しかし、実際には、**「プラグイン」を作成する必要はありません**。依存関係を使用することで、無限の数の統合やインタラクションを宣言することができ、それが**path operation関数*で利用可能になるからです。
依存関係は非常にシンプルで直感的な方法で作成することができ、必要なPythonパッケージをインポートするだけで、*文字通り*数行のコードでAPI関数と統合することができます。
次の章では、リレーショナルデータベースやNoSQLデータベース、セキュリティなどについて、その例を見ていきます。
## **FastAPI** 互換性
依存性注入システムがシンプルなので、**FastAPI** は以下のようなものと互換性があります:
* すべてのリレーショナルデータベース
* NoSQLデータベース
* 外部パッケージ
* 外部API
* 認証・認可システム
* API利用状況監視システム
* レスポンスデータ注入システム
* など。
## シンプルでパワフル
階層依存性注入システムは、定義や使用方法が非常にシンプルであるにもかかわらず、非常に強力なものとなっています。
依存関係事態を定義する依存関係を定義することができます。
最終的には、依存関係の階層ツリーが構築され、**依存性注入**システムが、これらの依存関係(およびそのサブ依存関係)をすべて解決し、各ステップで結果を提供(注入)します。
例えば、4つのAPIエンドポイント(*path operations*)があるとします:
* `/items/public/`
* `/items/private/`
* `/users/{user_id}/activate`
* `/items/pro/`
そして、依存関係とサブ依存関係だけで、それぞれに異なるパーミッション要件を追加することができます:
```mermaid
graph TB
current_user(["current_user"])
active_user(["active_user"])
admin_user(["admin_user"])
paying_user(["paying_user"])
public["/items/public/"]
private["/items/private/"]
activate_user["/users/{user_id}/activate"]
pro_items["/items/pro/"]
current_user --> active_user
active_user --> admin_user
active_user --> paying_user
current_user --> public
active_user --> private
admin_user --> activate_user
paying_user --> pro_items
```
## **OpenAPI** との統合
これら全ての依存関係は、要件を宣言すると同時に、*path operations*にパラメータやバリデーションを追加します。
**FastAPI** はそれをすべてOpenAPIスキーマに追加して、対話型のドキュメントシステムに表示されるようにします。

86
docs/ja/docs/tutorial/dependencies/sub-dependencies.md

@ -0,0 +1,86 @@
# サブ依存関係
**サブ依存関係** を持つ依存関係を作成することができます。
それらは必要なだけ **深く** することができます。
**FastAPI** はそれらを解決してくれます。
### 最初の依存関係「依存可能なもの」
以下のような最初の依存関係(「依存可能なもの」)を作成することができます:
```Python hl_lines="8 9"
{!../../../docs_src/dependencies/tutorial005.py!}
```
これはオプショナルのクエリパラメータ`q`を`str`として宣言し、それを返すだけです。
これは非常にシンプルです(あまり便利ではありません)が、サブ依存関係がどのように機能するかに焦点を当てるのに役立ちます。
### 第二の依存関係 「依存可能なもの」と「依存」
そして、別の依存関数(「依存可能なもの」)を作成して、同時にそれ自身の依存関係を宣言することができます(つまりそれ自身も「依存」です):
```Python hl_lines="13"
{!../../../docs_src/dependencies/tutorial005.py!}
```
宣言されたパラメータに注目してみましょう:
* この関数は依存関係(「依存可能なもの」)そのものであるにもかかわらず、別の依存関係を宣言しています(何か他のものに「依存」しています)。
* これは`query_extractor`に依存しており、それが返す値をパラメータ`q`に代入します。
* また、オプショナルの`last_query`クッキーを`str`として宣言します。
* ユーザーがクエリ`q`を提供しなかった場合、クッキーに保存していた最後に使用したクエリを使用します。
### 依存関係の使用
以下のように依存関係を使用することができます:
```Python hl_lines="21"
{!../../../docs_src/dependencies/tutorial005.py!}
```
!!! info "情報"
*path operation関数*の中で宣言している依存関係は`query_or_cookie_extractor`の1つだけであることに注意してください。
しかし、**FastAPI** は`query_extractor`を最初に解決し、その結果を`query_or_cookie_extractor`を呼び出す時に渡す必要があることを知っています。
```mermaid
graph TB
query_extractor(["query_extractor"])
query_or_cookie_extractor(["query_or_cookie_extractor"])
read_query["/items/"]
query_extractor --> query_or_cookie_extractor --> read_query
```
## 同じ依存関係の複数回の使用
依存関係の1つが同じ*path operation*に対して複数回宣言されている場合、例えば、複数の依存関係が共通のサブ依存関係を持っている場合、**FastAPI** はリクエストごとに1回だけそのサブ依存関係を呼び出します。
そして、返された値を<abbr title="計算された値・生成された値を保存するユーティリティまたはシステム、再計算する代わりに再利用するためのもの">「キャッシュ」</abbr>に保存し、同じリクエストに対して依存関係を何度も呼び出す代わりに、特定のリクエストでそれを必要とする全ての「依存関係」に渡すことになります。
高度なシナリオでは、「キャッシュされた」値を使うのではなく、同じリクエストの各ステップ(おそらく複数回)で依存関係を呼び出す必要があることがわかっている場合、`Depens`を使用する際に、`use_cache=False`というパラメータを設定することができます。
```Python hl_lines="1"
async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
return {"fresh_value": fresh_value}
```
## まとめ
ここで使われている派手な言葉は別にして、**依存性注入** システムは非常にシンプルです。
*path operation関数*と同じように見えるただの関数です。
しかし、それでも非常に強力で、任意の深くネストされた依存関係「グラフ」(ツリー)を宣言することができます。
!!! tip "豆知識"
これらの単純な例では、全てが役に立つとは言えないかもしれません。
しかし、**security** についての章で、それがどれほど有用であるかがわかるでしょう。
そして、あなたを救うコードの量もみることになるでしょう。

195
docs/ja/docs/tutorial/extra-models.md

@ -0,0 +1,195 @@
# モデル - より詳しく
先ほどの例に続き、複数の関連モデルを持つことが一般的です。
これはユーザーモデルの場合は特にそうです。なぜなら:
* **入力モデル** にはパスワードが必要です。
* **出力モデル**はパスワードをもつべきではありません。
* **データベースモデル**はおそらくハッシュ化されたパスワードが必要になるでしょう。
!!! danger "危険"
ユーザーの平文のパスワードは絶対に保存しないでください。常に認証に利用可能な「安全なハッシュ」を保存してください。
知らない方は、[セキュリティの章](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}で「パスワードハッシュ」とは何かを学ぶことができます。
## 複数のモデル
ここでは、パスワードフィールドをもつモデルがどのように見えるのか、また、どこで使われるのか、大まかなイメージを紹介します:
```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
{!../../../docs_src/extra_models/tutorial001.py!}
```
### `**user_in.dict()`について
#### Pydanticの`.dict()`
`user_in`は`UserIn`クラスのPydanticモデルです。
Pydanticモデルには、モデルのデータを含む`dict`を返す`.dict()`メソッドがあります。
そこで、以下のようなPydanticオブジェクト`user_in`を作成すると:
```Python
user_in = UserIn(username="john", password="secret", email="[email protected]")
```
そして呼び出すと:
```Python
user_dict = user_in.dict()
```
これで変数`user_dict`のデータを持つ`dict`ができました。(これはPydanticモデルのオブジェクトの代わりに`dict`です)。
そして呼び出すと:
```Python
print(user_dict)
```
以下のようなPythonの`dict`を得ることができます:
```Python
{
'username': 'john',
'password': 'secret',
'email': '[email protected]',
'full_name': None,
}
```
#### `dict`の展開
`user_dict`のような`dict`を受け取り、それを`**user_dict`を持つ関数(またはクラス)に渡すと、Pythonはそれを「展開」します。これは`user_dict`のキーと値を直接キー・バリューの引数として渡します。
そこで上述の`user_dict`の続きを以下のように書くと:
```Python
UserInDB(**user_dict)
```
以下と同等の結果になります:
```Python
UserInDB(
username="john",
password="secret",
email="[email protected]",
full_name=None,
)
```
もっと正確に言えば、`user_dict`を将来的にどんな内容であっても直接使用することになります:
```Python
UserInDB(
username = user_dict["username"],
password = user_dict["password"],
email = user_dict["email"],
full_name = user_dict["full_name"],
)
```
#### 別のモデルからつくるPydanticモデル
上述の例では`user_in.dict()`から`user_dict`をこのコードのように取得していますが:
```Python
user_dict = user_in.dict()
UserInDB(**user_dict)
```
これは以下と同等です:
```Python
UserInDB(**user_in.dict())
```
...なぜなら`user_in.dict()`は`dict`であり、`**`を付与して`UserInDB`を渡してPythonに「展開」させているからです。
そこで、別のPydanticモデルのデータからPydanticモデルを取得します。
#### `dict`の展開と追加引数
そして、追加のキーワード引数`hashed_password=hashed_password`を以下のように追加すると:
```Python
UserInDB(**user_in.dict(), hashed_password=hashed_password)
```
...以下のようになります:
```Python
UserInDB(
username = user_dict["username"],
password = user_dict["password"],
email = user_dict["email"],
full_name = user_dict["full_name"],
hashed_password = hashed_password,
)
```
!!! warning "注意"
サポートしている追加機能は、データの可能な流れをデモするだけであり、もちろん本当のセキュリティを提供しているわけではありません。
## 重複の削減
コードの重複を減らすことは、**FastAPI**の中核的なアイデアの1つです。
コードの重複が増えると、バグやセキュリティの問題、コードの非同期化問題(ある場所では更新しても他の場所では更新されない場合)などが発生する可能性が高くなります。
そして、これらのモデルは全てのデータを共有し、属性名や型を重複させています。
もっと良い方法があります。
他のモデルのベースとなる`UserBase`モデルを宣言することができます。そして、そのモデルの属性(型宣言、検証など)を継承するサブクラスを作ることができます。
データの変換、検証、文書化などはすべて通常通りに動作します。
このようにして、モデル間の違いだけを宣言することができます:
```Python hl_lines="9 15 16 19 20 23 24"
{!../../../docs_src/extra_models/tutorial002.py!}
```
## `Union`または`anyOf`
レスポンスを2つの型の`Union`として宣言することができます。
OpenAPIでは`anyOf`で定義されます。
そのためには、標準的なPythonの型ヒント<a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>を使用します:
```Python hl_lines="1 14 15 18 19 20 33"
{!../../../docs_src/extra_models/tutorial003.py!}
```
## モデルのリスト
同じように、オブジェクトのリストのレスポンスを宣言することができます。
そのためには、標準のPythonの`typing.List`を使用する:
```Python hl_lines="1 20"
{!../../../docs_src/extra_models/tutorial004.py!}
```
## 任意の`dict`を持つレスポンス
また、Pydanticモデルを使用せずに、キーと値の型だけを定義した任意の`dict`を使ってレスポンスを宣言することもできます。
これは、有効なフィールド・属性名(Pydanticモデルに必要なもの)を事前に知らない場合に便利です。
この場合、`typing.Dict`を使用することができます:
```Python hl_lines="1 8"
{!../../../docs_src/extra_models/tutorial005.py!}
```
## まとめ
複数のPydanticモデルを使用し、ケースごとに自由に継承します。
エンティティが異なる「状態」を持たなければならない場合は、エンティティごとに単一のデータモデルを持つ必要はありません。`password` や `password_hash` やパスワードなしなどのいくつかの「状態」をもつユーザー「エンティティ」の場合の様にすれば良いです。

265
docs/ja/docs/tutorial/handling-errors.md

@ -0,0 +1,265 @@
# エラーハンドリング
APIを使用しているクライアントにエラーを通知する必要がある状況はたくさんあります。
このクライアントは、フロントエンドを持つブラウザ、誰かのコード、IoTデバイスなどが考えられます。
クライアントに以下のようなことを伝える必要があるかもしれません:
* クライアントにはその操作のための十分な権限がありません。
* クライアントはそのリソースにアクセスできません。
* クライアントがアクセスしようとしていた項目が存在しません。
* など
これらの場合、通常は **400**(400から499)の範囲内の **HTTPステータスコード** を返すことになります。
これは200のHTTPステータスコード(200から299)に似ています。これらの「200」ステータスコードは、何らかの形でリクエスト「成功」であったことを意味します。
400の範囲にあるステータスコードは、クライアントからのエラーがあったことを意味します。
**"404 Not Found"** のエラー(およびジョーク)を覚えていますか?
## `HTTPException`の使用
HTTPレスポンスをエラーでクライアントに返すには、`HTTPException`を使用します。
### `HTTPException`のインポート
```Python hl_lines="1"
{!../../../docs_src/handling_errors/tutorial001.py!}
```
### コード内での`HTTPException`の発生
`HTTPException`は通常のPythonの例外であり、APIに関連するデータを追加したものです。
Pythonの例外なので、`return`ではなく、`raise`です。
これはまた、*path operation関数*の内部で呼び出しているユーティリティ関数の内部から`HTTPException`を発生させた場合、*path operation関数*の残りのコードは実行されず、そのリクエストを直ちに終了させ、`HTTPException`からのHTTPエラーをクライアントに送信することを意味します。
値を返す`return`よりも例外を発生させることの利点は、「依存関係とセキュリティ」のセクションでより明確になります。
この例では、クライアントが存在しないIDでアイテムを要求した場合、`404`のステータスコードを持つ例外を発生させます:
```Python hl_lines="11"
{!../../../docs_src/handling_errors/tutorial001.py!}
```
### レスポンス結果
クライアントが`http://example.com/items/foo`(`item_id` `"foo"`)をリクエストすると、HTTPステータスコードが200で、以下のJSONレスポンスが返されます:
```JSON
{
"item": "The Foo Wrestlers"
}
```
しかし、クライアントが`http://example.com/items/bar`(存在しない`item_id` `"bar"`)をリクエストした場合、HTTPステータスコード404("not found"エラー)と以下のJSONレスポンスが返されます:
```JSON
{
"detail": "Item not found"
}
```
!!! tip "豆知識"
`HTTPException`を発生させる際には、`str`だけでなく、JSONに変換できる任意の値を`detail`パラメータとして渡すことができます。
`dist`や`list`などを渡すことができます。
これらは **FastAPI** によって自動的に処理され、JSONに変換されます。
## カスタムヘッダーの追加
例えば、いくつかのタイプのセキュリティのために、HTTPエラーにカスタムヘッダを追加できると便利な状況がいくつかあります。
おそらくコードの中で直接使用する必要はないでしょう。
しかし、高度なシナリオのために必要な場合には、カスタムヘッダーを追加することができます:
```Python hl_lines="14"
{!../../../docs_src/handling_errors/tutorial002.py!}
```
## カスタム例外ハンドラのインストール
カスタム例外ハンドラは<a href="https://www.starlette.io/exceptions/" class="external-link" target="_blank">Starletteと同じ例外ユーティリティ</a>を使用して追加することができます。
あなた(または使用しているライブラリ)が`raise`するかもしれないカスタム例外`UnicornException`があるとしましょう。
そして、この例外をFastAPIでグローバルに処理したいと思います。
カスタム例外ハンドラを`@app.exception_handler()`で追加することができます:
```Python hl_lines="5 6 7 13 14 15 16 17 18 24"
{!../../../docs_src/handling_errors/tutorial003.py!}
```
ここで、`/unicorns/yolo`をリクエストすると、*path operation*は`UnicornException`を`raise`します。
しかし、これは`unicorn_exception_handler`で処理されます。
そのため、HTTPステータスコードが`418`で、JSONの内容が以下のような明確なエラーを受け取ることになります:
```JSON
{"message": "Oops! yolo did something. There goes a rainbow..."}
```
!!! note "技術詳細"
また、`from starlette.requests import Request`と`from starlette.responses import JSONResponse`を使用することもできます。
**FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。これは`Request`と同じです。
## デフォルトの例外ハンドラのオーバーライド
**FastAPI** にはいくつかのデフォルトの例外ハンドラがあります。
これらのハンドラは、`HTTPException`を`raise`させた場合や、リクエストに無効なデータが含まれている場合にデフォルトのJSONレスポンスを返す役割を担っています。
これらの例外ハンドラを独自のものでオーバーライドすることができます。
### リクエスト検証の例外のオーバーライド
リクエストに無効なデータが含まれている場合、**FastAPI** は内部的に`RequestValidationError`を発生させます。
また、そのためのデフォルトの例外ハンドラも含まれています。
これをオーバーライドするには`RequestValidationError`をインポートして`@app.exception_handler(RequestValidationError)`と一緒に使用して例外ハンドラをデコレートします。
この例外ハンドラは`Requset`と例外を受け取ります。
```Python hl_lines="2 14 15 16"
{!../../../docs_src/handling_errors/tutorial004.py!}
```
これで、`/items/foo`にアクセスすると、デフォルトのJSONエラーの代わりに以下が返されます:
```JSON
{
"detail": [
{
"loc": [
"path",
"item_id"
],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
]
}
```
以下のようなテキスト版を取得します:
```
1 validation error
path -> item_id
value is not a valid integer (type=type_error.integer)
```
#### `RequestValidationError`と`ValidationError`
!!! warning "注意"
これらは今のあなたにとって重要でない場合は省略しても良い技術的な詳細です。
`RequestValidationError`はPydanticの<a href="https://pydantic-docs.helpmanual.io/#error-handling" class="external-link" target="_blank">`ValidationError`</a>のサブクラスです。
**FastAPI** は`response_model`でPydanticモデルを使用していて、データにエラーがあった場合、ログにエラーが表示されるようにこれを使用しています。
しかし、クライアントやユーザーはそれを見ることはありません。その代わりに、クライアントはHTTPステータスコード`500`の「Internal Server Error」を受け取ります。
*レスポンス*やコードのどこか(クライアントの*リクエスト*ではなく)にPydanticの`ValidationError`がある場合、それは実際にはコードのバグなのでこのようにすべきです。
また、あなたがそれを修正している間は、セキュリティの脆弱性が露呈する場合があるため、クライアントやユーザーがエラーに関する内部情報にアクセスできないようにしてください。
### エラーハンドラ`HTTPException`のオーバーライド
同様に、`HTTPException`ハンドラをオーバーライドすることもできます。
例えば、これらのエラーに対しては、JSONではなくプレーンテキストを返すようにすることができます:
```Python hl_lines="3 4 9 10 11 22"
{!../../../docs_src/handling_errors/tutorial004.py!}
```
!!! note "技術詳細"
また、`from starlette.responses import PlainTextResponse`を使用することもできます。
**FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
### `RequestValidationError`のボディの使用
`RequestValidationError`には無効なデータを含む`body`が含まれています。
アプリ開発中に本体のログを取ってデバッグしたり、ユーザーに返したりなどに使用することができます。
```Python hl_lines="14"
{!../../../docs_src/handling_errors/tutorial005.py!}
```
ここで、以下のような無効な項目を送信してみてください:
```JSON
{
"title": "towel",
"size": "XL"
}
```
受信したボディを含むデータが無効であることを示すレスポンスが表示されます:
```JSON hl_lines="12 13 14 15"
{
"detail": [
{
"loc": [
"body",
"size"
],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
],
"body": {
"title": "towel",
"size": "XL"
}
}
```
#### FastAPIの`HTTPException`とStarletteの`HTTPException`
**FastAPI**は独自の`HTTPException`を持っています。
また、 **FastAPI**のエラークラス`HTTPException`はStarletteのエラークラス`HTTPException`を継承しています。
唯一の違いは、**FastAPI** の`HTTPException`はレスポンスに含まれるヘッダを追加できることです。
これはOAuth 2.0といくつかのセキュリティユーティリティのために内部的に必要とされ、使用されています。
そのため、コード内では通常通り **FastAPI** の`HTTPException`を発生させ続けることができます。
しかし、例外ハンドラを登録する際には、Starletteの`HTTPException`を登録しておく必要があります。
これにより、Starletteの内部コードやStarletteの拡張機能やプラグインの一部が`HTTPException`を発生させた場合、ハンドラがそれをキャッチして処理することができるようになります。
以下の例では、同じコード内で両方の`HTTPException`を使用できるようにするために、Starletteの例外の名前を`StarletteHTTPException`に変更しています:
```Python
from starlette.exceptions import HTTPException as StarletteHTTPException
```
### **FastAPI** の例外ハンドラの再利用
また、何らかの方法で例外を使用することもできますが、**FastAPI** から同じデフォルトの例外ハンドラを使用することもできます。
デフォルトの例外ハンドラを`fastapi.exception_handlers`からインポートして再利用することができます:
```Python hl_lines="2 3 4 5 15 21"
{!../../../docs_src/handling_errors/tutorial006.py!}
```
この例では、非常に表現力のあるメッセージでエラーを`print`しています。
しかし、例外を使用して、デフォルトの例外ハンドラを再利用することができるということが理解できます。

122
docs/ja/docs/tutorial/path-params-numeric-validations.md

@ -0,0 +1,122 @@
# パスパラメータと数値の検証
クエリパラメータに対して`Query`でより多くのバリデーションとメタデータを宣言できるのと同じように、パスパラメータに対しても`Path`で同じ種類のバリデーションとメタデータを宣言することができます。
## Pathのインポート
まず初めに、`fastapi`から`Path`をインポートします:
```Python hl_lines="1"
{!../../../docs_src/path_params_numeric_validations/tutorial001.py!}
```
## メタデータの宣言
パラメータは`Query`と同じものを宣言することができます。
例えば、パスパラメータ`item_id`に対して`title`のメタデータを宣言するには以下のようにします:
```Python hl_lines="8"
{!../../../docs_src/path_params_numeric_validations/tutorial001.py!}
```
!!! note "備考"
パスの一部でなければならないので、パスパラメータは常に必須です。
そのため、`...`を使用して必須と示す必要があります。
それでも、`None`で宣言しても、デフォルト値を設定しても、何の影響もなく、常に必要とされていることに変わりはありません。
## 必要に応じてパラメータを並び替える
クエリパラメータ`q`を必須の`str`として宣言したいとしましょう。
また、このパラメータには何も宣言する必要がないので、`Query`を使う必要はありません。
しかし、パスパラメータ`item_id`のために`Path`を使用する必要があります。
Pythonは「デフォルト」を持たない値の前に「デフォルト」を持つ値を置くことができません。
しかし、それらを並び替えることができ、デフォルト値を持たない値(クエリパラメータ`q`)を最初に持つことができます。
**FastAPI**では関係ありません。パラメータは名前、型、デフォルトの宣言(`Query`、`Path`など)で検出され、順番は気にしません。
そのため、以下のように関数を宣言することができます:
```Python hl_lines="8"
{!../../../docs_src/path_params_numeric_validations/tutorial002.py!}
```
## 必要に応じてパラメータを並び替えるトリック
クエリパラメータ`q`を`Query`やデフォルト値なしで宣言し、パスパラメータ`item_id`を`Path`を用いて宣言し、それらを別の順番に並びたい場合、Pythonには少し特殊な構文が用意されています。
関数の最初のパラメータとして`*`を渡します。
Pythonはその`*`で何かをすることはありませんが、それ以降のすべてのパラメータがキーワード引数(キーと値のペア)として呼ばれるべきものであると知っているでしょう。それは<abbr title="From: K-ey W-ord Arg-uments"><code>kwargs</code></abbr>としても知られています。たとえデフォルト値がなくても。
```Python hl_lines="8"
{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
```
## 数値の検証: 以上
`Query`と`Path`(、そして後述する他のもの)を用いて、文字列の制約を宣言することができますが、数値の制約も同様に宣言できます。
ここで、`ge=1`の場合、`item_id`は`1`「より大きい`g`か、同じ`e`」整数でなれけばなりません。
```Python hl_lines="8"
{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
```
## 数値の検証: より大きいと小なりイコール
以下も同様です:
* `gt`: より大きい(`g`reater `t`han)
* `le`: 小なりイコール(`l`ess than or `e`qual)
```Python hl_lines="9"
{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
```
## 数値の検証: 浮動小数点、 大なり小なり
数値のバリデーションは`float`の値に対しても有効です。
ここで重要になってくるのは<abbr title="より大きい"><code>gt</code></abbr>だけでなく<abbr title="以下"><code>ge</code></abbr>も宣言できることです。これと同様に、例えば、値が`1`より小さくても`0`より大きくなければならないことを要求することができます。
したがって、`0.5`は有効な値ですが、`0.0`や`0`はそうではありません。
これは<abbr title="未満"><code>lt</code></abbr>も同じです。
```Python hl_lines="11"
{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
```
## まとめ
`Query`と`Path`(そしてまだ見たことない他のもの)では、[クエリパラメータと文字列の検証](query-params-str-validations.md){.internal-link target=_blank}と同じようにメタデータと文字列の検証を宣言することができます。
また、数値のバリデーションを宣言することもできます:
* `gt`: より大きい(`g`reater `t`han)
* `ge`: 以上(`g`reater than or `e`qual)
* `lt`: より小さい(`l`ess `t`han)
* `le`: 以下(`l`ess than or `e`qual)
!!! info "情報"
`Query`、`Path`などは後に共通の`Param`クラスのサブクラスを見ることになります。(使う必要はありません)
そして、それらすべては、これまで見てきた追加のバリデーションとメタデータと同じパラメータを共有しています。
!!! note "技術詳細"
`fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。
呼び出されると、同じ名前のクラスのインスタンスを返します。
そのため、関数である`Query`をインポートし、それを呼び出すと、`Query`という名前のクラスのインスタンスが返されます。
これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。
この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。

208
docs/ja/docs/tutorial/response-model.md

@ -0,0 +1,208 @@
# レスポンスモデル
*path operations* のいずれにおいても、`response_model`パラメータを使用して、レスポンスのモデルを宣言することができます:
* `@app.get()`
* `@app.post()`
* `@app.put()`
* `@app.delete()`
* など。
```Python hl_lines="17"
{!../../../docs_src/response_model/tutorial001.py!}
```
!!! note "備考"
`response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数* のパラメータではありません。
Pydanticモデルの属性に対して宣言するのと同じ型を受け取るので、Pydanticモデルになることもできますが、例えば、`List[Item]`のようなPydanticモデルの`list`になることもできます。
FastAPIは`response_model`を使って以下のことをします:
* 出力データを型宣言に変換します。
* データを検証します。
* OpenAPIの *path operation* で、レスポンス用のJSON Schemaを追加します。
* 自動ドキュメントシステムで使用されます。
しかし、最も重要なのは:
* 出力データをモデルのデータに限定します。これがどのように重要なのか以下で見ていきましょう。
!!! note "技術詳細"
レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。
## 同じ入力データの返却
ここでは`UserIn`モデルを宣言しています。それには平文のパスワードが含まれています:
```Python hl_lines="9 11"
{!../../../docs_src/response_model/tutorial002.py!}
```
そして、このモデルを使用して入力を宣言し、同じモデルを使って出力を宣言しています:
```Python hl_lines="17 18"
{!../../../docs_src/response_model/tutorial002.py!}
```
これで、ブラウザがパスワードを使ってユーザーを作成する際に、APIがレスポンスで同じパスワードを返すようになりました。
この場合、ユーザー自身がパスワードを送信しているので問題ないかもしれません。
しかし、同じモデルを別の*path operation*に使用すると、すべてのクライアントにユーザーのパスワードを送信してしまうことになります。
!!! danger "危険"
ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。
## 出力モデルの追加
代わりに、平文のパスワードを持つ入力モデルと、パスワードを持たない出力モデルを作成することができます:
```Python hl_lines="9 11 16"
{!../../../docs_src/response_model/tutorial003.py!}
```
ここでは、*path operation関数*がパスワードを含む同じ入力ユーザーを返しているにもかかわらず:
```Python hl_lines="24"
{!../../../docs_src/response_model/tutorial003.py!}
```
...`response_model`を`UserOut`と宣言したことで、パスワードが含まれていません:
```Python hl_lines="22"
{!../../../docs_src/response_model/tutorial003.py!}
```
そのため、**FastAPI** は出力モデルで宣言されていない全てのデータをフィルタリングしてくれます(Pydanticを使用)。
## ドキュメントを見る
自動ドキュメントを見ると、入力モデルと出力モデルがそれぞれ独自のJSON Schemaを持っていることが確認できます。
<img src="https://fastapi.tiangolo.com/img/tutorial/response-model/image01.png">
そして、両方のモデルは、対話型のAPIドキュメントに使用されます:
<img src="https://fastapi.tiangolo.com/img/tutorial/response-model/image02.png">
## レスポンスモデルのエンコーディングパラメータ
レスポンスモデルにはデフォルト値を設定することができます:
```Python hl_lines="11 13 14"
{!../../../docs_src/response_model/tutorial004.py!}
```
* `description: str = None`は`None`がデフォルト値です。
* `tax: float = 10.5`は`10.5`がデフォルト値です。
* `tags: List[str] = []` は空のリスト(`[]`)がデフォルト値です。
しかし、実際に保存されていない場合には結果からそれらを省略した方が良いかもしれません。
例えば、NoSQLデータベースに多くのオプション属性を持つモデルがあるが、デフォルト値でいっぱいの非常に長いJSONレスポンスを送信したくない場合です。
### `response_model_exclude_unset`パラメータの使用
*path operation デコレータ*に`response_model_exclude_unset=True`パラメータを設定することができます:
```Python hl_lines="24"
{!../../../docs_src/response_model/tutorial004.py!}
```
そして、これらのデフォルト値はレスポンスに含まれず、実際に設定された値のみが含まれます。
そのため、*path operation*にID`foo`が設定されたitemのリクエストを送ると、レスポンスは以下のようになります(デフォルト値を含まない):
```JSON
{
"name": "Foo",
"price": 50.2
}
```
!!! info "情報"
FastAPIはこれをするために、Pydanticモデルの`.dict()`を<a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict" class="external-link" target="_blank">その`exclude_unset`パラメータ</a>で使用しています。
!!! info "情報"
以下も使用することができます:
* `response_model_exclude_defaults=True`
* `response_model_exclude_none=True`
`exclude_defaults`と`exclude_none`については、<a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict" class="external-link" target="_blank">Pydanticのドキュメント</a>で説明されている通りです。
#### デフォルト値を持つフィールドの値を持つデータ
しかし、ID`bar`のitemのように、デフォルト値が設定されているモデルのフィールドに値が設定されている場合:
```Python hl_lines="3 5"
{
"name": "Bar",
"description": "The bartenders",
"price": 62,
"tax": 20.2
}
```
それらはレスポンスに含まれます。
#### デフォルト値と同じ値を持つデータ
ID`baz`のitemのようにデフォルト値と同じ値を持つデータの場合:
```Python hl_lines="3 5 6"
{
"name": "Baz",
"description": None,
"price": 50.2,
"tax": 10.5,
"tags": []
}
```
FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`description`や`tax`、`tags`はデフォルト値と同じ値を持っているにもかかわらず、明示的に設定されていることを理解しています。(デフォルトから取得するのではなく)
そのため、それらはJSONレスポンスに含まれることになります。
!!! tip "豆知識"
デフォルト値は`None`だけでなく、なんでも良いことに注意してください。
例えば、リスト(`[]`)や`10.5`の`float`などです。
### `response_model_include`と`response_model_exclude`
*path operationデコレータ*として`response_model_include`と`response_model_exclude`も使用することができます。
属性名を持つ`str`の`set`を受け取り、含める(残りを省略する)か、除外(残りを含む)します。
これは、Pydanticモデルが1つしかなく、出力からいくつかのデータを削除したい場合のクイックショートカットとして使用することができます。
!!! tip "豆知識"
それでも、これらのパラメータではなく、複数のクラスを使用して、上記のようなアイデアを使うことをおすすめします。
これは`response_model_include`や`response_mode_exclude`を使用していくつかの属性を省略しても、アプリケーションのOpenAPI(とドキュメント)で生成されたJSON Schemaが完全なモデルになるからです。
同様に動作する`response_model_by_alias`にも当てはまります。
```Python hl_lines="31 37"
{!../../../docs_src/response_model/tutorial005.py!}
```
!!! tip "豆知識"
`{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。
これは`set(["name", "description"])`と同等です。
#### `set`の代わりに`list`を使用する
もし`set`を使用することを忘れて、代わりに`list`や`tuple`を使用しても、FastAPIはそれを`set`に変換して正しく動作します:
```Python hl_lines="31 37"
{!../../../docs_src/response_model/tutorial006.py!}
```
## まとめ
*path operationデコレータの*`response_model`パラメータを使用して、レスポンスモデルを定義し、特にプライベートデータがフィルタリングされていることを保証します。
明示的に設定された値のみを返すには、`response_model_exclude_unset`を使用します。

89
docs/ja/docs/tutorial/response-status-code.md

@ -0,0 +1,89 @@
# レスポンスステータスコード
レスポンスモデルを指定するのと同じ方法で、レスポンスに使用されるHTTPステータスコードを以下の*path operations*のいずれかの`status_code`パラメータで宣言することもできます。
* `@app.get()`
* `@app.post()`
* `@app.put()`
* `@app.delete()`
* など。
```Python hl_lines="6"
{!../../../docs_src/response_status_code/tutorial001.py!}
```
!!! note "備考"
`status_code`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数*のものではありません。
`status_code`パラメータはHTTPステータスコードを含む数値を受け取ります。
!!! info "情報"
`status_code`は代わりに、Pythonの<a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>のように、`IntEnum`を受け取ることもできます。
これは:
* レスポンスでステータスコードを返します。
* OpenAPIスキーマ(およびユーザーインターフェース)に以下のように文書化します:
<img src="https://fastapi.tiangolo.com/img/tutorial/response-status-code/image01.png">
!!! note "備考"
いくつかのレスポンスコード(次のセクションを参照)は、レスポンスにボディがないことを示しています。
FastAPIはこれを知っていて、レスポンスボディがないというOpenAPIドキュメントを生成します。
## HTTPステータスコードについて
!!! note "備考"
すでにHTTPステータスコードが何であるかを知っている場合は、次のセクションにスキップしてください。
HTTPでは、レスポンスの一部として3桁の数字のステータスコードを送信します。
これらのステータスコードは、それらを認識するために関連付けられた名前を持っていますが、重要な部分は番号です。
つまり:
* `100`以上は「情報」のためのものです。。直接使うことはほとんどありません。これらのステータスコードを持つレスポンスはボディを持つことができません。
* **`200`** 以上は「成功」のレスポンスのためのものです。これらは最も利用するであろうものです。
* `200`はデフォルトのステータスコードで、すべてが「OK」であったことを意味します。
* 別の例としては、`201`(Created)があります。これはデータベースに新しいレコードを作成した後によく使用されます。
* 特殊なケースとして、`204`(No Content)があります。このレスポンスはクライアントに返すコンテンツがない場合に使用されます。そしてこのレスポンスはボディを持つことはできません。
* **`300`** 以上は「リダイレクト」のためのものです。これらのステータスコードを持つレスポンスは`304`(Not Modified)を除き、ボディを持つことも持たないこともできます。
* **`400`** 以上は「クライアントエラー」のレスポンスのためのものです。これらは、おそらく最も多用するであろう2番目のタイプです。
* 例えば、`404`は「Not Found」レスポンスです。
* クライアントからの一般的なエラーについては、`400`を使用することができます。
* `500`以上はサーバーエラーのためのものです。これらを直接使うことはほとんどありません。アプリケーションコードやサーバーのどこかで何か問題が発生した場合、これらのステータスコードのいずれかが自動的に返されます。
!!! tip "豆知識"
それぞれのステータスコードとどのコードが何のためのコードなのかについて詳細は<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> HTTP レスポンスステータスコードについてのドキュメント</a>を参照してください。
## 名前を覚えるための近道
先ほどの例をもう一度見てみましょう:
```Python hl_lines="6"
{!../../../docs_src/response_status_code/tutorial001.py!}
```
`201`は「作成完了」のためのステータスコードです。
しかし、それぞれのコードの意味を暗記する必要はありません。
`fastapi.status`の便利な変数を利用することができます。
```Python hl_lines="1 6"
{!../../../docs_src/response_status_code/tutorial002.py!}
```
それらは便利です。それらは同じ番号を保持しており、その方法ではエディタの自動補完を使用してそれらを見つけることができます。
<img src="https://fastapi.tiangolo.com/img/tutorial/response-status-code/image02.png">
!!! note "技術詳細"
また、`from starlette import status`を使うこともできます。
**FastAPI** は、`開発者の利便性を考慮して、fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。
## デフォルトの変更
後に、[高度なユーザーガイド](../advanced/response-change-status-code.md){.internal-link target=_blank}で、ここで宣言しているデフォルトとは異なるステータスコードを返す方法を見ていきます。

58
docs/ja/docs/tutorial/schema-extra-example.md

@ -0,0 +1,58 @@
# スキーマの追加 - 例
JSON Schemaに追加する情報を定義することができます。
一般的なユースケースはこのドキュメントで示されているように`example`を追加することです。
JSON Schemaの追加情報を宣言する方法はいくつかあります。
## Pydanticの`schema_extra`
<a href="https://pydantic-docs.helpmanual.io/usage/schema/#schema-customization" class="external-link" target="_blank">Pydanticのドキュメント: スキーマのカスタマイズ</a>で説明されているように、`Config`と`schema_extra`を使ってPydanticモデルの例を宣言することができます:
```Python hl_lines="15 16 17 18 19 20 21 22 23"
{!../../../docs_src/schema_extra_example/tutorial001.py!}
```
その追加情報はそのまま出力され、JSON Schemaに追加されます。
## `Field`の追加引数
後述する`Field`、`Path`、`Query`、`Body`などでは、任意の引数を関数に渡すことでJSON Schemaの追加情報を宣言することもできます:
```Python hl_lines="4 10 11 12 13"
{!../../../docs_src/schema_extra_example/tutorial002.py!}
```
!!! warning "注意"
これらの追加引数が渡されても、文書化のためのバリデーションは追加されず、注釈だけが追加されることを覚えておいてください。
## `Body`の追加引数
追加情報を`Field`に渡すのと同じように、`Path`、`Query`、`Body`などでも同じことができます。
例えば、`Body`にボディリクエストの`example`を渡すことができます:
```Python hl_lines="21 22 23 24 25 26"
{!../../../docs_src/schema_extra_example/tutorial003.py!}
```
## ドキュメントのUIの例
上記のいずれの方法でも、`/docs`の中では以下のようになります:
<img src="https://fastapi.tiangolo.com/img/tutorial/body-fields/image01.png">
## 技術詳細
`example``examples`について...
JSON Schemaの最新バージョンでは<a href="https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.9.5" class="external-link" target="_blank">`examples`</a>というフィールドを定義していますが、OpenAPIは`examples`を持たない古いバージョンのJSON Schemaをベースにしています。
そのため、OpenAPIでは同じ目的のために<a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#fixed-fields-20" class="external-link" target="_blank">`example`</a>を独自に定義しており(`examples`ではなく`example`として)、それがdocs UI(Swagger UIを使用)で使用されています。
つまり、`example`はJSON Schemaの一部ではありませんが、OpenAPIの一部であり、それがdocs UIで使用されることになります。
## その他の情報
同じように、フロントエンドのユーザーインターフェースなどをカスタマイズするために、各モデルのJSON Schemaに追加される独自の追加情報を追加することができます。

2
docs/ja/docs/tutorial/security/oauth2-jwt.md

@ -167,7 +167,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し
JWTアクセストークンを作成し、それを返します。
```Python hl_lines="115-128"
```Python hl_lines="115-130"
{!../../../docs_src/security/tutorial004.py!}
```

2
docs/ko/docs/tutorial/path-params.md

@ -101,7 +101,7 @@
## 순서 문제
*경로 동작*을 만들때 고정 경로를 갖고 있는 상황들을 맞뜨릴 수 있습니다.
*경로 동작*을 만들때 고정 경로를 갖고 있는 상황들을 맞뜨릴 수 있습니다.
`/users/me`처럼, 현재 사용자의 데이터를 가져온다고 합시다.

1
docs/language_names.yml

@ -179,4 +179,5 @@ yi: ייִדיש
yo: Yorùbá
za: Saɯ cueŋƅ
zh: 汉语
zh-hant: 繁體中文
zu: isiZulu

2
docs/ru/docs/index.md

@ -321,7 +321,7 @@ def update_item(item_id: int, item: Item):
Таким образом, вы объявляете **один раз** типы параметров, тело и т. д. в качестве параметров функции.
Вы делаете это испльзуя стандартную современную типизацию Python.
Вы делаете это используя стандартную современную типизацию Python.
Вам не нужно изучать новый синтаксис, методы или классы конкретной библиотеки и т. д.

478
docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md

@ -0,0 +1,478 @@
# Классы как зависимости
Прежде чем углубиться в систему **Внедрения Зависимостей**, давайте обновим предыдущий пример.
## `Словарь` из предыдущего примера
В предыдущем примере мы возвращали `словарь` из нашей зависимости:
=== "Python 3.10+"
```Python hl_lines="9"
{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
```
=== "Python 3.9+"
```Python hl_lines="11"
{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
```
=== "Python 3.6+"
```Python hl_lines="12"
{!> ../../../docs_src/dependencies/tutorial001_an.py!}
```
=== "Python 3.10+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python hl_lines="7"
{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
```
=== "Python 3.6+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python hl_lines="11"
{!> ../../../docs_src/dependencies/tutorial001.py!}
```
Но затем мы получаем `словарь` в параметре `commons` *функции операции пути*. И мы знаем, что редакторы не могут обеспечить достаточную поддержку для `словаря`, поскольку они не могут знать их ключи и типы значений.
Мы можем сделать лучше...
## Что делает зависимость
До сих пор вы видели зависимости, объявленные как функции.
Но это не единственный способ объявления зависимостей (хотя, вероятно, более распространенный).
Ключевым фактором является то, что зависимость должна быть "вызываемой".
В Python "**вызываемый**" - это все, что Python может "вызвать", как функцию.
Так, если у вас есть объект `something` (который может _не_ быть функцией) и вы можете "вызвать" его (выполнить) как:
```Python
something()
```
или
```Python
something(some_argument, some_keyword_argument="foo")
```
в таком случае он является "вызываемым".
## Классы как зависимости
Вы можете заметить, что для создания экземпляра класса в Python используется тот же синтаксис.
Например:
```Python
class Cat:
def __init__(self, name: str):
self.name = name
fluffy = Cat(name="Mr Fluffy")
```
В данном случае `fluffy` является экземпляром класса `Cat`.
А чтобы создать `fluffy`, вы "вызываете" `Cat`.
Таким образом, класс в Python также является **вызываемым**.
Тогда в **FastAPI** в качестве зависимости можно использовать класс Python.
На самом деле FastAPI проверяет, что переданный объект является "вызываемым" (функция, класс или что-либо еще) и указаны необходимые для его вызова параметры.
Если вы передаёте что-то, что можно "вызывать" в качестве зависимости в **FastAPI**, то он будет анализировать параметры, необходимые для "вызова" этого объекта и обрабатывать их так же, как параметры *функции операции пути*. Включая подзависимости.
Это относится и к вызываемым объектам без параметров. Работа с ними происходит точно так же, как и для *функций операции пути* без параметров.
Теперь мы можем изменить зависимость `common_parameters`, указанную выше, на класс `CommonQueryParams`:
=== "Python 3.10+"
```Python hl_lines="11-15"
{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
```
=== "Python 3.9+"
```Python hl_lines="11-15"
{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
```
=== "Python 3.6+"
```Python hl_lines="12-16"
{!> ../../../docs_src/dependencies/tutorial002_an.py!}
```
=== "Python 3.10+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python hl_lines="9-13"
{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
```
=== "Python 3.6+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python hl_lines="11-15"
{!> ../../../docs_src/dependencies/tutorial002.py!}
```
Обратите внимание на метод `__init__`, используемый для создания экземпляра класса:
=== "Python 3.10+"
```Python hl_lines="12"
{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
```
=== "Python 3.9+"
```Python hl_lines="12"
{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
```
=== "Python 3.6+"
```Python hl_lines="13"
{!> ../../../docs_src/dependencies/tutorial002_an.py!}
```
=== "Python 3.10+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python hl_lines="10"
{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
```
=== "Python 3.6+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python hl_lines="12"
{!> ../../../docs_src/dependencies/tutorial002.py!}
```
...имеет те же параметры, что и ранее используемая функция `common_parameters`:
=== "Python 3.10+"
```Python hl_lines="8"
{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
```
=== "Python 3.9+"
```Python hl_lines="9"
{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
```
=== "Python 3.6+"
```Python hl_lines="10"
{!> ../../../docs_src/dependencies/tutorial001_an.py!}
```
=== "Python 3.10+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python hl_lines="6"
{!> ../../../docs_src/dependencies/tutorial001_py310.py!}
```
=== "Python 3.6+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python hl_lines="9"
{!> ../../../docs_src/dependencies/tutorial001.py!}
```
Эти параметры и будут использоваться **FastAPI** для "решения" зависимости.
В обоих случаях она будет иметь:
* Необязательный параметр запроса `q`, представляющий собой `str`.
* Параметр запроса `skip`, представляющий собой `int`, по умолчанию `0`.
* Параметр запроса `limit`, представляющий собой `int`, по умолчанию равный `100`.
В обоих случаях данные будут конвертированы, валидированы, документированы по схеме OpenAPI и т.д.
## Как это использовать
Теперь вы можете объявить свою зависимость, используя этот класс.
=== "Python 3.10+"
```Python hl_lines="19"
{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!}
```
=== "Python 3.9+"
```Python hl_lines="19"
{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!}
```
=== "Python 3.6+"
```Python hl_lines="20"
{!> ../../../docs_src/dependencies/tutorial002_an.py!}
```
=== "Python 3.10+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python hl_lines="17"
{!> ../../../docs_src/dependencies/tutorial002_py310.py!}
```
=== "Python 3.6+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python hl_lines="19"
{!> ../../../docs_src/dependencies/tutorial002.py!}
```
**FastAPI** вызывает класс `CommonQueryParams`. При этом создается "экземпляр" этого класса, который будет передан в качестве параметра `commons` в вашу функцию.
## Аннотация типа или `Depends`
Обратите внимание, что в приведенном выше коде мы два раза пишем `CommonQueryParams`:
=== "Python 3.6+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python
commons: CommonQueryParams = Depends(CommonQueryParams)
```
=== "Python 3.6+"
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
```
Последний параметр `CommonQueryParams`, в:
```Python
... Depends(CommonQueryParams)
```
...это то, что **FastAPI** будет использовать, чтобы узнать, что является зависимостью.
Из него FastAPI извлечёт объявленные параметры и именно их будет вызывать.
---
В этом случае первый `CommonQueryParams`, в:
=== "Python 3.6+"
```Python
commons: Annotated[CommonQueryParams, ...
```
=== "Python 3.6+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python
commons: CommonQueryParams ...
```
...не имеет никакого специального значения для **FastAPI**. FastAPI не будет использовать его для преобразования данных, валидации и т.д. (поскольку для этого используется `Depends(CommonQueryParams)`).
На самом деле можно написать просто:
=== "Python 3.6+"
```Python
commons: Annotated[Any, Depends(CommonQueryParams)]
```
=== "Python 3.6+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python
commons = Depends(CommonQueryParams)
```
...как тут:
=== "Python 3.10+"
```Python hl_lines="19"
{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!}
```
=== "Python 3.9+"
```Python hl_lines="19"
{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!}
```
=== "Python 3.6+"
```Python hl_lines="20"
{!> ../../../docs_src/dependencies/tutorial003_an.py!}
```
=== "Python 3.10+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python hl_lines="17"
{!> ../../../docs_src/dependencies/tutorial003_py310.py!}
```
=== "Python 3.6+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python hl_lines="19"
{!> ../../../docs_src/dependencies/tutorial003.py!}
```
Но объявление типа приветствуется, так как в этом случае ваш редактор будет знать, что будет передано в качестве параметра `commons`, и тогда он сможет помочь вам с автодополнением, проверкой типов и т.д:
<img src="/img/tutorial/dependencies/image02.png">
## Сокращение
Но вы видите, что здесь мы имеем некоторое повторение кода, дважды написав `CommonQueryParams`:
=== "Python 3.6+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python
commons: CommonQueryParams = Depends(CommonQueryParams)
```
=== "Python 3.6+"
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
```
Для случаев, когда зависимостью является *конкретный* класс, который **FastAPI** "вызовет" для создания экземпляра этого класса, можно использовать укороченную запись.
Вместо того чтобы писать:
=== "Python 3.6+"
```Python
commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
```
=== "Python 3.6+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python
commons: CommonQueryParams = Depends(CommonQueryParams)
```
...следует написать:
=== "Python 3.6+"
```Python
commons: Annotated[CommonQueryParams, Depends()]
```
=== "Python 3.6 без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python
commons: CommonQueryParams = Depends()
```
Вы объявляете зависимость как тип параметра и используете `Depends()` без какого-либо параметра, вместо того чтобы *снова* писать полный класс внутри `Depends(CommonQueryParams)`.
Аналогичный пример будет выглядеть следующим образом:
=== "Python 3.10+"
```Python hl_lines="19"
{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!}
```
=== "Python 3.9+"
```Python hl_lines="19"
{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!}
```
=== "Python 3.6+"
```Python hl_lines="20"
{!> ../../../docs_src/dependencies/tutorial004_an.py!}
```
=== "Python 3.10+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python hl_lines="17"
{!> ../../../docs_src/dependencies/tutorial004_py310.py!}
```
=== "Python 3.6+ без Annotated"
!!! tip "Подсказка"
Рекомендуется использовать версию с `Annotated` если возможно.
```Python hl_lines="19"
{!> ../../../docs_src/dependencies/tutorial004.py!}
```
...и **FastAPI** будет знать, что делать.
!!! tip "Подсказка"
Если это покажется вам более запутанным, чем полезным, не обращайте внимания, это вам не *нужно*.
Это просто сокращение. Потому что **FastAPI** заботится о том, чтобы помочь вам свести к минимуму повторение кода.

4
docs/zh/docs/tutorial/extra-data-types.md

@ -44,11 +44,11 @@
* 产生的模式将指定那些 `set` 的值是唯一的 (使用 JSON 模式的 `uniqueItems`)。
* `bytes`:
* 标准的 Python `bytes`
* 在请求和应中被当作 `str` 处理。
* 在请求和应中被当作 `str` 处理。
* 生成的模式将指定这个 `str``binary` "格式"。
* `Decimal`:
* 标准的 Python `Decimal`
* 在请求和应中被当做 `float` 一样处理。
* 在请求和应中被当做 `float` 一样处理。
* 您可以在这里检查所有有效的pydantic数据类型: <a href="https://pydantic-docs.helpmanual.io/usage/types" class="external-link" target="_blank">Pydantic data types</a>.
## 例子

2
docs/zh/docs/tutorial/security/oauth2-jwt.md

@ -170,7 +170,7 @@ $ openssl rand -hex 32
创建并返回真正的 JWT 访问令牌。
```Python hl_lines="115-128"
```Python hl_lines="115-130"
{!../../../docs_src/security/tutorial004.py!}
```

2
docs/zh/docs/tutorial/sql-databases.md

@ -499,7 +499,7 @@ current_user.items
“迁移”是每当您更改 SQLAlchemy 模型的结构、添加新属性等以在数据库中复制这些更改、添加新列、新表等时所需的一组步骤。
您可以在[Project Generation - Template](https://fastapi.tiangolo.com/zh/project-generation/)的模板中找到一个 FastAPI 项目中的 Alembic 示例。具体在[`alembic`代码目录中](https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/%7B%7Bcookiecutter.project_slug%7D%7D/backend/app/alembic/)。
您可以在[Project Generation - Template](https://fastapi.tiangolo.com/zh/project-generation/)的模板中找到一个 FastAPI 项目中的 Alembic 示例。具体在[`alembic`代码目录中](https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/src/backend/app/alembic/)。
### 创建依赖项

8
docs_src/security/tutorial004.py

@ -112,8 +112,10 @@ async def get_current_active_user(current_user: User = Depends(get_current_user)
return current_user
@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
@app.post("/token")
async def login_for_access_token(
form_data: OAuth2PasswordRequestForm = Depends()
) -> Token:
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(
@ -125,7 +127,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(
access_token = create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
return Token(access_token=access_token, token_type="bearer")
@app.get("/users/me/", response_model=User)

6
docs_src/security/tutorial004_an.py

@ -115,10 +115,10 @@ async def get_current_active_user(
return current_user
@app.post("/token", response_model=Token)
@app.post("/token")
async def login_for_access_token(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
):
) -> Token:
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(
@ -130,7 +130,7 @@ async def login_for_access_token(
access_token = create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
return Token(access_token=access_token, token_type="bearer")
@app.get("/users/me/", response_model=User)

6
docs_src/security/tutorial004_an_py310.py

@ -114,10 +114,10 @@ async def get_current_active_user(
return current_user
@app.post("/token", response_model=Token)
@app.post("/token")
async def login_for_access_token(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
):
) -> Token:
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(
@ -129,7 +129,7 @@ async def login_for_access_token(
access_token = create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
return Token(access_token=access_token, token_type="bearer")
@app.get("/users/me/", response_model=User)

6
docs_src/security/tutorial004_an_py39.py

@ -114,10 +114,10 @@ async def get_current_active_user(
return current_user
@app.post("/token", response_model=Token)
@app.post("/token")
async def login_for_access_token(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
):
) -> Token:
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(
@ -129,7 +129,7 @@ async def login_for_access_token(
access_token = create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
return Token(access_token=access_token, token_type="bearer")
@app.get("/users/me/", response_model=User)

8
docs_src/security/tutorial004_py310.py

@ -111,8 +111,10 @@ async def get_current_active_user(current_user: User = Depends(get_current_user)
return current_user
@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
@app.post("/token")
async def login_for_access_token(
form_data: OAuth2PasswordRequestForm = Depends()
) -> Token:
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(
@ -124,7 +126,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(
access_token = create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
return Token(access_token=access_token, token_type="bearer")
@app.get("/users/me/", response_model=User)

8
docs_src/security/tutorial005.py

@ -143,8 +143,10 @@ async def get_current_active_user(
return current_user
@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
@app.post("/token")
async def login_for_access_token(
form_data: OAuth2PasswordRequestForm = Depends()
) -> Token:
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(status_code=400, detail="Incorrect username or password")
@ -153,7 +155,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(
data={"sub": user.username, "scopes": form_data.scopes},
expires_delta=access_token_expires,
)
return {"access_token": access_token, "token_type": "bearer"}
return Token(access_token=access_token, token_type="bearer")
@app.get("/users/me/", response_model=User)

6
docs_src/security/tutorial005_an.py

@ -144,10 +144,10 @@ async def get_current_active_user(
return current_user
@app.post("/token", response_model=Token)
@app.post("/token")
async def login_for_access_token(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
):
) -> Token:
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(status_code=400, detail="Incorrect username or password")
@ -156,7 +156,7 @@ async def login_for_access_token(
data={"sub": user.username, "scopes": form_data.scopes},
expires_delta=access_token_expires,
)
return {"access_token": access_token, "token_type": "bearer"}
return Token(access_token=access_token, token_type="bearer")
@app.get("/users/me/", response_model=User)

6
docs_src/security/tutorial005_an_py310.py

@ -143,10 +143,10 @@ async def get_current_active_user(
return current_user
@app.post("/token", response_model=Token)
@app.post("/token")
async def login_for_access_token(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
):
) -> Token:
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(status_code=400, detail="Incorrect username or password")
@ -155,7 +155,7 @@ async def login_for_access_token(
data={"sub": user.username, "scopes": form_data.scopes},
expires_delta=access_token_expires,
)
return {"access_token": access_token, "token_type": "bearer"}
return Token(access_token=access_token, token_type="bearer")
@app.get("/users/me/", response_model=User)

6
docs_src/security/tutorial005_an_py39.py

@ -143,10 +143,10 @@ async def get_current_active_user(
return current_user
@app.post("/token", response_model=Token)
@app.post("/token")
async def login_for_access_token(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
):
) -> Token:
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(status_code=400, detail="Incorrect username or password")
@ -155,7 +155,7 @@ async def login_for_access_token(
data={"sub": user.username, "scopes": form_data.scopes},
expires_delta=access_token_expires,
)
return {"access_token": access_token, "token_type": "bearer"}
return Token(access_token=access_token, token_type="bearer")
@app.get("/users/me/", response_model=User)

8
docs_src/security/tutorial005_py310.py

@ -142,8 +142,10 @@ async def get_current_active_user(
return current_user
@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
@app.post("/token")
async def login_for_access_token(
form_data: OAuth2PasswordRequestForm = Depends()
) -> Token:
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(status_code=400, detail="Incorrect username or password")
@ -152,7 +154,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(
data={"sub": user.username, "scopes": form_data.scopes},
expires_delta=access_token_expires,
)
return {"access_token": access_token, "token_type": "bearer"}
return Token(access_token=access_token, token_type="bearer")
@app.get("/users/me/", response_model=User)

8
docs_src/security/tutorial005_py39.py

@ -143,8 +143,10 @@ async def get_current_active_user(
return current_user
@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
@app.post("/token")
async def login_for_access_token(
form_data: OAuth2PasswordRequestForm = Depends()
) -> Token:
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(status_code=400, detail="Incorrect username or password")
@ -153,7 +155,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(
data={"sub": user.username, "scopes": form_data.scopes},
expires_delta=access_token_expires,
)
return {"access_token": access_token, "token_type": "bearer"}
return Token(access_token=access_token, token_type="bearer")
@app.get("/users/me/", response_model=User)

2
docs_src/templates/templates/item.html

@ -4,6 +4,6 @@
<link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet">
</head>
<body>
<h1>Item ID: {{ id }}</h1>
<h1><a href="{{ url_for('read_item', id=id) }}">Item ID: {{ id }}</a></h1>
</body>
</html>

2
fastapi/security/oauth2.py

@ -353,7 +353,7 @@ class OAuth2(SecurityBase):
bool,
Doc(
"""
By default, if no HTTP Auhtorization header is provided, required for
By default, if no HTTP Authorization header is provided, required for
OAuth2 authentication, it will automatically cancel the request and
send the client an error.

10
fastapi/utils.py

@ -53,7 +53,7 @@ def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool:
}:
return True
current_status_code = int(status_code)
return not (current_status_code < 200 or current_status_code in {204, 304})
return not (current_status_code < 200 or current_status_code in {204, 205, 304})
def get_path_param_names(path: str) -> Set[str]:
@ -173,17 +173,17 @@ def generate_operation_id_for_path(
DeprecationWarning,
stacklevel=2,
)
operation_id = name + path
operation_id = f"{name}{path}"
operation_id = re.sub(r"\W", "_", operation_id)
operation_id = operation_id + "_" + method.lower()
operation_id = f"{operation_id}_{method.lower()}"
return operation_id
def generate_unique_id(route: "APIRoute") -> str:
operation_id = route.name + route.path_format
operation_id = f"{route.name}{route.path_format}"
operation_id = re.sub(r"\W", "_", operation_id)
assert route.methods
operation_id = operation_id + "_" + list(route.methods)[0].lower()
operation_id = f"{operation_id}_{list(route.methods)[0].lower()}"
return operation_id

5
pyproject.toml

@ -145,15 +145,14 @@ select = [
"W", # pycodestyle warnings
"F", # pyflakes
"I", # isort
"C", # flake8-comprehensions
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"UP", # pyupgrade
]
ignore = [
"E501", # line too long, handled by black
"B008", # do not perform function calls in argument defaults
"C901", # too complex
"W191", # indentation contains tabs
"W191", # indentation contains tabs
]
[tool.ruff.per-file-ignores]

9
scripts/docs.py

@ -53,9 +53,6 @@ def get_lang_paths() -> List[Path]:
def lang_callback(lang: Optional[str]) -> Union[str, None]:
if lang is None:
return None
if not lang.isalpha() or len(lang) != 2:
typer.echo("Use a 2 letter language code, like: es")
raise typer.Abort()
lang = lang.lower()
return lang
@ -289,6 +286,12 @@ def update_config() -> None:
for lang_dict in languages:
code = list(lang_dict.keys())[0]
url = lang_dict[code]
if code not in local_language_names:
print(
f"Missing language name for: {code}, "
"update it in docs/language_names.yml"
)
raise typer.Abort()
use_name = f"{code} - {local_language_names[code]}"
new_alternate.append({"link": url, "name": use_name})
new_alternate.append({"link": "/em/", "name": "😉"})

9
tests/test_generate_unique_id_function.py

@ -1626,6 +1626,9 @@ def test_warn_duplicate_operation_id():
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
client.get("/openapi.json")
assert len(w) == 2
assert issubclass(w[-1].category, UserWarning)
assert "Duplicate Operation ID" in str(w[-1].message)
assert len(w) >= 2
duplicate_warnings = [
warning for warning in w if issubclass(warning.category, UserWarning)
]
assert len(duplicate_warnings) > 0
assert "Duplicate Operation ID" in str(duplicate_warnings[0].message)

8
tests/test_tutorial/test_header_params/test_tutorial003.py

@ -12,8 +12,12 @@ client = TestClient(app)
[
("/items", None, 200, {"X-Token values": None}),
("/items", {"x-token": "foo"}, 200, {"X-Token values": ["foo"]}),
# TODO: fix this, is it a bug?
# ("/items", [("x-token", "foo"), ("x-token", "bar")], 200, {"X-Token values": ["foo", "bar"]}),
(
"/items",
[("x-token", "foo"), ("x-token", "bar")],
200,
{"X-Token values": ["foo", "bar"]},
),
],
)
def test(path, headers, expected_status, expected_response):

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save