diff --git a/.github/DISCUSSION_TEMPLATE/translations.yml b/.github/DISCUSSION_TEMPLATE/translations.yml
new file mode 100644
index 0000000000000..16e304d9981e8
--- /dev/null
+++ b/.github/DISCUSSION_TEMPLATE/translations.yml
@@ -0,0 +1,45 @@
+labels: [lang-all]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Thanks for your interest in helping translate the FastAPI docs! 🌍
+
+ Please follow these instructions carefully to propose a new language translation. 🙏
+
+ This structured process helps ensure translations can be properly maintained long-term.
+ - type: checkboxes
+ id: checks
+ attributes:
+ label: Initial Checks
+ description: Please confirm and check all the following options.
+ options:
+ - label: I checked that this language is not already being translated in FastAPI docs.
+ required: true
+ - label: I searched existing discussions to ensure no one else proposed this language.
+ required: true
+ - label: I am a native speaker of the language I want to help translate.
+ required: true
+ - type: input
+ id: language
+ attributes:
+ label: Target Language
+ description: What language do you want to translate the FastAPI docs into?
+ placeholder: e.g. Latin
+ validations:
+ required: true
+ - type: textarea
+ id: additional_info
+ attributes:
+ label: Additional Information
+ description: Any other relevant information about your translation proposal
+ - type: markdown
+ attributes:
+ value: |
+ Translations are automatized with AI and then reviewed by native speakers. 🤖 🙋
+
+ This allows us to keep them consistent and up-to-date.
+
+ If there are several native speakers commenting on this discussion and
+ committing to help review new translations, the FastAPI team will review it
+ and potentially make it an official translation. 😎
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
index a8f4c4de2de29..fd9f3b11c5830 100644
--- a/.github/ISSUE_TEMPLATE/config.yml
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -4,13 +4,13 @@ contact_links:
about: Please report security vulnerabilities to security@tiangolo.com
- name: Question or Problem
about: Ask a question or ask about a problem in GitHub Discussions.
- url: https://github.com/tiangolo/fastapi/discussions/categories/questions
+ url: https://github.com/fastapi/fastapi/discussions/categories/questions
- name: Feature Request
about: To suggest an idea or ask about a feature, please start with a question saying what you would like to achieve. There might be a way to do it already.
- url: https://github.com/tiangolo/fastapi/discussions/categories/questions
+ url: https://github.com/fastapi/fastapi/discussions/categories/questions
- name: Show and tell
about: Show what you built with FastAPI or to be used with FastAPI.
- url: https://github.com/tiangolo/fastapi/discussions/categories/show-and-tell
+ url: https://github.com/fastapi/fastapi/discussions/categories/show-and-tell
- name: Translations
about: Coordinate translations in GitHub Discussions.
- url: https://github.com/tiangolo/fastapi/discussions/categories/translations
+ url: https://github.com/fastapi/fastapi/discussions/categories/translations
diff --git a/.github/ISSUE_TEMPLATE/privileged.yml b/.github/ISSUE_TEMPLATE/privileged.yml
index c01e34b6dd682..2b85eb310b306 100644
--- a/.github/ISSUE_TEMPLATE/privileged.yml
+++ b/.github/ISSUE_TEMPLATE/privileged.yml
@@ -6,7 +6,7 @@ body:
value: |
Thanks for your interest in FastAPI! 🚀
- If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/tiangolo/fastapi/discussions/categories/questions) instead.
+ If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/fastapi/fastapi/discussions/categories/questions) instead.
- type: checkboxes
id: privileged
attributes:
diff --git a/.github/actions/comment-docs-preview-in-pr/Dockerfile b/.github/actions/comment-docs-preview-in-pr/Dockerfile
deleted file mode 100644
index 14b0d026956fb..0000000000000
--- a/.github/actions/comment-docs-preview-in-pr/Dockerfile
+++ /dev/null
@@ -1,7 +0,0 @@
-FROM python:3.9
-
-RUN pip install httpx "pydantic==1.5.1" pygithub
-
-COPY ./app /app
-
-CMD ["python", "/app/main.py"]
diff --git a/.github/actions/comment-docs-preview-in-pr/action.yml b/.github/actions/comment-docs-preview-in-pr/action.yml
deleted file mode 100644
index 0eb64402d2a1f..0000000000000
--- a/.github/actions/comment-docs-preview-in-pr/action.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-name: Comment Docs Preview in PR
-description: Comment with the docs URL preview in the PR
-author: Sebastián Ramírez
-
-
-
-
-
+### Keystone Sponsor
+
+
+
+### Gold and Silver Sponsors
+
+
+
+
+
+
+
+
+
+
+
+
-Other sponsors
+[Other sponsors](https://fastapi.tiangolo.com/fastapi-people/#sponsors)
## Opinions
"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._"
-
+
## **Typer**, the FastAPI of CLIs
-uvicorn main:app --reload...fastapi dev...email_validator - for email validation.
-* pydantic-settings - for settings management.
-* pydantic-extra-types - for extra types to be used with Pydantic.
+* [`email-validator`](https://github.com/JoshData/python-email-validator) - for email validation.
Used by Starlette:
-* httpx - Required if you want to use the `TestClient`.
-* jinja2 - Required if you want to use the default template configuration.
-* python-multipart - Required if you want to support form "parsing", with `request.form()`.
-* itsdangerous - Required for `SessionMiddleware` support.
-* pyyaml - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
-* ujson - Required if you want to use `UJSONResponse`.
+* [`httpx`](https://www.python-httpx.org) - Required if you want to use the `TestClient`.
+* [`jinja2`](https://jinja.palletsprojects.com) - Required if you want to use the default template configuration.
+* [`python-multipart`](https://github.com/Kludex/python-multipart) - Required if you want to support form "parsing", with `request.form()`.
+
+Used by FastAPI:
+
+* [`uvicorn`](https://www.uvicorn.dev) - for the server that loads and serves your application. This includes `uvicorn[standard]`, which includes some dependencies (e.g. `uvloop`) needed for high performance serving.
+* `fastapi-cli[standard]` - to provide the `fastapi` command.
+ * This includes `fastapi-cloud-cli`, which allows you to deploy your FastAPI application to [FastAPI Cloud](https://fastapicloud.com).
+
+### Without `standard` Dependencies
+
+If you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install "fastapi[standard]"`.
+
+### Without `fastapi-cloud-cli`
+
+If you want to install FastAPI with the standard dependencies but without the `fastapi-cloud-cli`, you can install with `pip install "fastapi[standard-no-fastapi-cloud-cli]"`.
+
+### Additional Optional Dependencies
+
+There are some additional dependencies you might want to install.
+
+Additional optional Pydantic dependencies:
-Used by FastAPI / Starlette:
+* [`pydantic-settings`](https://docs.pydantic.dev/latest/usage/pydantic_settings/) - for settings management.
+* [`pydantic-extra-types`](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/) - for extra types to be used with Pydantic.
-* uvicorn - for the server that loads and serves your application.
-* orjson - Required if you want to use `ORJSONResponse`.
+Additional optional FastAPI dependencies:
-You can install all of these with `pip install "fastapi[all]"`.
+* [`orjson`](https://github.com/ijl/orjson) - Required if you want to use `ORJSONResponse`.
+* [`ujson`](https://github.com/esnme/ultrajson) - Required if you want to use `UJSONResponse`.
## License
diff --git a/SECURITY.md b/SECURITY.md
index db412cf2c8e66..87e87e0ca1c71 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -16,7 +16,7 @@ You can learn more about [FastAPI versions and how to pin and upgrade them](http
If you think you found a vulnerability, and even if you are not sure about it, please report it right away by sending an email to: security@tiangolo.com. Please try to be as explicit as possible, describing all the steps and example code to reproduce the security issue.
-I (the author, [@tiangolo](https://twitter.com/tiangolo)) will review it thoroughly and get back to you.
+I (the author, [@tiangolo](https://x.com/tiangolo)) will review it thoroughly and get back to you.
## Public Discussions
diff --git a/docs/de/docs/_llm-test.md b/docs/de/docs/_llm-test.md
new file mode 100644
index 0000000000000..de1aa1e9fedec
--- /dev/null
+++ b/docs/de/docs/_llm-test.md
@@ -0,0 +1,503 @@
+# LLM-Testdatei { #llm-test-file }
+
+Dieses Dokument testet, ob das LLM, das die Dokumentation übersetzt, den `general_prompt` in `scripts/translate.py` und den sprachspezifischen Prompt in `docs/{language code}/llm-prompt.md` versteht. Der sprachsspezifische Prompt wird an `general_prompt` angehängt.
+
+Hier hinzugefügte Tests werden von allen Erstellern sprachsspezifischer Prompts gesehen.
+
+So verwenden:
+
+* Einen sprachsspezifischen Prompt haben – `docs/{language code}/llm-prompt.md`.
+* Eine frische Übersetzung dieses Dokuments in die gewünschte Zielsprache durchführen (siehe z. B. das Kommando `translate-page` der `translate.py`). Dadurch wird die Übersetzung unter `docs/{language code}/docs/_llm-test.md` erstellt.
+* Prüfen Sie, ob in der Übersetzung alles in Ordnung ist.
+* Verbessern Sie bei Bedarf Ihren sprachsspezifischen Prompt, den allgemeinen Prompt oder das englische Dokument.
+* Beheben Sie anschließend manuell die verbleibenden Probleme in der Übersetzung, sodass es eine gute Übersetzung ist.
+* Übersetzen Sie erneut, nachdem die gute Übersetzung vorliegt. Das ideale Ergebnis wäre, dass das LLM an der Übersetzung keine Änderungen mehr vornimmt. Das bedeutet, dass der allgemeine Prompt und Ihr sprachsspezifischer Prompt so gut sind, wie sie sein können (Es wird manchmal ein paar scheinbar zufällige Änderungen machen, der Grund ist, dass [LLMs keine deterministischen Algorithmen sind](https://doublespeak.chat/#/handbook#deterministic-output)).
+
+Die Tests:
+
+## Codeschnipsel { #code-snippets }
+
+//// tab | Test
+
+Dies ist ein Codeschnipsel: `foo`. Und dies ist ein weiteres Codeschnipsel: `bar`. Und noch eins: `baz quux`.
+
+////
+
+//// tab | Info
+
+Der Inhalt von Codeschnipseln sollte unverändert bleiben.
+
+Siehe Abschnitt `### Content of code snippets` im allgemeinen Prompt in `scripts/translate.py`.
+
+////
+
+## Anführungszeichen { #quotes }
+
+//// tab | Test
+
+Gestern schrieb mein Freund: „Wenn man ‚incorrectly‘ korrekt schreibt, hat man es falsch geschrieben“. Worauf ich antwortete: „Korrekt, aber ‚incorrectly‘ ist inkorrekterweise nicht ‚„incorrectly“‘“.
+
+/// note | Hinweis
+
+Das LLM wird dies wahrscheinlich falsch übersetzen. Interessant ist nur, ob es die korrigierte Übersetzung bei einer erneuten Übersetzung beibehält.
+
+///
+
+////
+
+//// tab | Info
+
+Der Promptdesigner kann entscheiden, ob neutrale Anführungszeichen in typografische Anführungszeichen umgewandelt werden sollen. Es ist in Ordnung, sie unverändert zu lassen.
+
+Siehe zum Beispiel den Abschnitt `### Quotes` in `docs/de/llm-prompt.md`.
+
+////
+
+## Anführungszeichen in Codeschnipseln { #quotes-in-code-snippets }
+
+//// tab | Test
+
+`pip install "foo[bar]"`
+
+Beispiele für Stringliterale in Codeschnipseln: `"this"`, `'that'`.
+
+Ein schwieriges Beispiel für Stringliterale in Codeschnipseln: `f"I like {'oranges' if orange else "apples"}"`
+
+Hardcore: `Yesterday, my friend wrote: "If you spell incorrectly correctly, you have spelled it incorrectly". To which I answered: "Correct, but 'incorrectly' is incorrectly not '"incorrectly"'"`
+
+////
+
+//// tab | Info
+
+... Allerdings müssen Anführungszeichen in Codeschnipseln unverändert bleiben.
+
+////
+
+## Codeblöcke { #code-blocks }
+
+//// tab | Test
+
+Ein Bash-Codebeispiel ...
+
+```bash
+# Eine Begrüßung an das Universum ausgeben
+echo "Hello universe"
+```
+
+... und ein Konsolen-Codebeispiel ...
+
+```console
+$ fastapi run main.py
+ FastAPI Starting server
+ Searching for package file structure
+```
+
+... und noch ein Konsolen-Codebeispiel ...
+
+```console
+// Create a directory "Code"
+$ mkdir code
+// In dieses Verzeichnis wechseln
+$ cd code
+```
+
+... und ein Python-Codebeispiel ...
+
+```Python
+wont_work() # Das wird nicht funktionieren 😱
+works(foo="bar") # Das funktioniert 🎉
+```
+
+... und das war's.
+
+////
+
+//// tab | Info
+
+Code in Codeblöcken sollte nicht verändert werden, mit Ausnahme von Kommentaren.
+
+Siehe Abschnitt `### Content of code blocks` im allgemeinen Prompt in `scripts/translate.py`.
+
+////
+
+## Tabs und farbige Boxen { #tabs-and-colored-boxes }
+
+//// tab | Test
+
+/// info | Info
+Etwas Text
+///
+
+/// note | Hinweis
+Etwas Text
+///
+
+/// note | Technische Details
+Etwas Text
+///
+
+/// check | Testen
+Etwas Text
+///
+
+/// tip | Tipp
+Etwas Text
+///
+
+/// warning | Achtung
+Etwas Text
+///
+
+/// danger | Gefahr
+Etwas Text
+///
+
+////
+
+//// tab | Info
+
+Tabs und `Info`/`Note`/`Warning`/usw. Blöcke sollten die Übersetzung ihres Titels nach einem vertikalen Strich (`|`) erhalten.
+
+Siehe die Abschnitte `### Special blocks` und `### Tab blocks` im allgemeinen Prompt in `scripts/translate.py`.
+
+////
+
+## Web- und interne Links { #web-and-internal-links }
+
+//// tab | Test
+
+Der Linktext sollte übersetzt werden, die Linkadresse sollte unverändert bleiben:
+
+* [Link zur Überschrift oben](#code-snippets)
+* [Interner Link](index.md#installation)
+* [Externer Link](https://sqlmodel.tiangolo.com/)
+* [Link zu einem Stil](https://fastapi.tiangolo.com/css/styles.css)
+* [Link zu einem Skript](https://fastapi.tiangolo.com/js/logic.js)
+* [Link zu einem Bild](https://fastapi.tiangolo.com/img/foo.jpg)
+
+Der Linktext sollte übersetzt werden, die Linkadresse sollte auf die Übersetzung zeigen:
+
+* [FastAPI-Link](https://fastapi.tiangolo.com/de/)
+
+////
+
+//// tab | Info
+
+Links sollten übersetzt werden, aber ihre Adresse soll unverändert bleiben. Eine Ausnahme sind absolute Links zu Seiten der FastAPI-Dokumentation. In diesem Fall sollte auf die Übersetzung verlinkt werden.
+
+Siehe Abschnitt `### Links` im allgemeinen Prompt in `scripts/translate.py`.
+
+////
+
+## HTML-„abbr“-Elemente { #html-abbr-elements }
+
+//// tab | Test
+
+Hier einige Dinge, die in HTML-„abbr“-Elemente gepackt sind (einige sind erfunden):
+
+### Das abbr gibt eine vollständige Phrase { #the-abbr-gives-a-full-phrase }
+
+* GTD
+* lt
+* XWT
+* PSGI
+
+### Das abbr gibt eine vollständige Phrase und eine Erklärung { #the-abbr-gives-a-full-phrase-and-an-explanation }
+
+* MDN
+* I/O.
+
+////
+
+//// tab | Info
+
+„title“-Attribute von „abbr“-Elementen werden nach bestimmten Anweisungen übersetzt.
+
+Übersetzungen können eigene „abbr“-Elemente hinzufügen, die das LLM nicht entfernen soll. Z. B. um englische Wörter zu erklären.
+
+Siehe Abschnitt `### HTML abbr elements` im allgemeinen Prompt in `scripts/translate.py`.
+
+////
+
+## HTML „dfn“-Elemente { #html-dfn-elements }
+
+* Cluster
+* Deep Learning
+
+## Überschriften { #headings }
+
+//// tab | Test
+
+### Eine Webapp entwickeln – ein Tutorial { #develop-a-webapp-a-tutorial }
+
+Hallo.
+
+### Typhinweise und -annotationen { #type-hints-and-annotations }
+
+Hallo wieder.
+
+### Super- und Subklassen { #super-and-subclasses }
+
+Hallo wieder.
+
+////
+
+//// tab | Info
+
+Die einzige strenge Regel für Überschriften ist, dass das LLM den Hash-Teil in geschweiften Klammern unverändert lässt, damit Links nicht kaputtgehen.
+
+Siehe Abschnitt `### Headings` im allgemeinen Prompt in `scripts/translate.py`.
+
+Für einige sprachsspezifische Anweisungen, siehe z. B. den Abschnitt `### Headings` in `docs/de/llm-prompt.md`.
+
+////
+
+## In der Dokumentation verwendete Begriffe { #terms-used-in-the-docs }
+
+//// tab | Test
+
+* Sie
+* Ihr
+
+* z. B.
+* usw.
+
+* `foo` vom Typ `int`
+* `bar` vom Typ `str`
+* `baz` vom Typ `list`
+
+* das Tutorial – Benutzerhandbuch
+* das Handbuch für fortgeschrittene Benutzer
+* die SQLModel-Dokumentation
+* die API-Dokumentation
+* die automatische Dokumentation
+
+* Data Science
+* Deep Learning
+* Machine Learning
+* Dependency Injection
+* HTTP Basic-Authentifizierung
+* HTTP Digest
+* ISO-Format
+* der JSON-Schema-Standard
+* das JSON-Schema
+* die Schema-Definition
+* Password Flow
+* Mobile
+
+* deprecatet
+* designt
+* ungültig
+* on the fly
+* Standard
+* Default
+* Groß-/Kleinschreibung ist relevant
+* Groß-/Kleinschreibung ist nicht relevant
+
+* die Anwendung bereitstellen
+* die Seite ausliefern
+
+* die App
+* die Anwendung
+
+* der Request
+* die Response
+* die Error-Response
+
+* die Pfadoperation
+* der Pfadoperation-Dekorator
+* die Pfadoperation-Funktion
+
+* der Body
+* der Requestbody
+* der Responsebody
+* der JSON-Body
+* der Formularbody
+* der Dateibody
+* der Funktionskörper
+
+* der Parameter
+* der Body-Parameter
+* der Pfad-Parameter
+* der Query-Parameter
+* der Cookie-Parameter
+* der Header-Parameter
+* der Formular-Parameter
+* der Funktionsparameter
+
+* das Event
+* das Startup-Event
+* das Hochfahren des Servers
+* das Shutdown-Event
+* das Lifespan-Event
+
+* der Handler
+* der Eventhandler
+* der Exceptionhandler
+* handhaben
+
+* das Modell
+* das Pydantic-Modell
+* das Datenmodell
+* das Datenbankmodell
+* das Formularmodell
+* das Modellobjekt
+
+* die Klasse
+* die Basisklasse
+* die Elternklasse
+* die Subklasse
+* die Kindklasse
+* die Geschwisterklasse
+* die Klassenmethode
+
+* der Header
+* die Header
+* der Autorisierungsheader
+* der `Authorization`-Header
+* der Forwarded-Header
+
+* das Dependency-Injection-System
+* die Dependency
+* das Dependable
+* der Dependant
+
+* I/O-lastig
+* CPU-lastig
+* Nebenläufigkeit
+* Parallelität
+* Multiprocessing
+
+* die Umgebungsvariable
+* die Umgebungsvariable
+* der `PATH`
+* die `PATH`-Umgebungsvariable
+
+* die Authentifizierung
+* der Authentifizierungsanbieter
+* die Autorisierung
+* das Anmeldeformular
+* der Autorisierungsanbieter
+* der Benutzer authentisiert sich
+* das System authentifiziert den Benutzer
+
+* Das CLI
+* Das Kommandozeileninterface
+
+* der Server
+* der Client
+
+* der Cloudanbieter
+* der Clouddienst
+
+* die Entwicklung
+* die Entwicklungsphasen
+
+* das Dict
+* das Dictionary
+* die Enumeration
+* das Enum
+* das Enum-Member
+
+* der Encoder
+* der Decoder
+* kodieren
+* dekodieren
+
+* die Exception
+* werfen
+
+* der Ausdruck
+* die Anweisung
+
+* das Frontend
+* das Backend
+
+* die GitHub-Diskussion
+* das GitHub-Issue
+
+* die Leistung
+* die Leistungsoptimierung
+
+* der Rückgabetyp
+* der Rückgabewert
+
+* die Sicherheit
+* das Sicherheitsschema
+
+* der Task
+* der Hintergrundtask
+* die Taskfunktion
+
+* das Template
+* die Template-Engine
+
+* die Typannotation
+* der Typhinweis
+
+* der Serverworker
+* der Uvicorn-Worker
+* der Gunicorn-Worker
+* der Workerprozess
+* die Workerklasse
+* die Workload
+
+* das Deployment
+* deployen
+
+* das SDK
+* das Software Development Kit
+
+* der `APIRouter`
+* die `requirements.txt`
+* das Bearer-Token
+* der Breaking Change
+* der Bug
+* der Button
+* das Callable
+* der Code
+* der Commit
+* der Contextmanager
+* die Coroutine
+* die Datenbanksession
+* die Festplatte
+* die Domain
+* die Engine
+* das Fake-X
+* die HTTP-GET-Methode
+* das Item
+* die Bibliothek
+* der Lifespan
+* der Lock
+* die Middleware
+* die Mobile-Anwendung
+* das Modul
+* das Mounten
+* das Netzwerk
+* das Origin
+* Die Überschreibung
+* die Payload
+* der Prozessor
+* die Property
+* der Proxy
+* der Pull Request
+* die Query
+* der RAM
+* der entfernte Rechner
+* der Statuscode
+* der String
+* der Tag
+* das Webframework
+* die Wildcard
+* zurückgeben
+* validieren
+
+////
+
+//// tab | Info
+
+Dies ist eine nicht vollständige und nicht normative Liste von (meist) technischen Begriffen, die in der Dokumentation vorkommen. Sie kann dem Promptdesigner helfen herauszufinden, bei welchen Begriffen das LLM Unterstützung braucht. Zum Beispiel, wenn es eine gute Übersetzung immer wieder auf eine suboptimale Übersetzung zurücksetzt. Oder wenn es Probleme hat, einen Begriff in Ihrer Sprache zu konjugieren/deklinieren.
+
+Siehe z. B. den Abschnitt `### List of English terms and their preferred German translations` in `docs/de/llm-prompt.md`.
+
+////
diff --git a/docs/de/docs/about/index.md b/docs/de/docs/about/index.md
new file mode 100644
index 0000000000000..5e9c6b6a0a069
--- /dev/null
+++ b/docs/de/docs/about/index.md
@@ -0,0 +1,3 @@
+# Über { #about }
+
+Über FastAPI, sein Design, seine Inspiration und mehr. 🤓
diff --git a/docs/de/docs/advanced/additional-responses.md b/docs/de/docs/advanced/additional-responses.md
new file mode 100644
index 0000000000000..bc7c477c86998
--- /dev/null
+++ b/docs/de/docs/advanced/additional-responses.md
@@ -0,0 +1,247 @@
+# Zusätzliche Responses in OpenAPI { #additional-responses-in-openapi }
+
+/// warning | Achtung
+
+Dies ist ein eher fortgeschrittenes Thema.
+
+Wenn Sie mit **FastAPI** beginnen, benötigen Sie dies möglicherweise nicht.
+
+///
+
+Sie können zusätzliche Responses mit zusätzlichen Statuscodes, Medientypen, Beschreibungen, usw. deklarieren.
+
+Diese zusätzlichen Responses werden in das OpenAPI-Schema aufgenommen, sodass sie auch in der API-Dokumentation erscheinen.
+
+Für diese zusätzlichen Responses müssen Sie jedoch sicherstellen, dass Sie eine `Response`, wie etwa `JSONResponse`, direkt zurückgeben, mit Ihrem Statuscode und Inhalt.
+
+## Zusätzliche Response mit `model` { #additional-response-with-model }
+
+Sie können Ihren *Pfadoperation-Dekoratoren* einen Parameter `responses` übergeben.
+
+Der nimmt ein `dict` entgegen, die Schlüssel sind Statuscodes für jede Response, wie etwa `200`, und die Werte sind andere `dict`s mit den Informationen für jede Response.
+
+Jedes dieser Response-`dict`s kann einen Schlüssel `model` haben, welcher ein Pydantic-Modell enthält, genau wie `response_model`.
+
+**FastAPI** nimmt dieses Modell, generiert dessen JSON-Schema und fügt es an der richtigen Stelle in OpenAPI ein.
+
+Um beispielsweise eine weitere Response mit dem Statuscode `404` und einem Pydantic-Modell `Message` zu deklarieren, können Sie schreiben:
+
+{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}
+
+/// note | Hinweis
+
+Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen.
+
+///
+
+/// info | Info
+
+Der `model`-Schlüssel ist nicht Teil von OpenAPI.
+
+**FastAPI** nimmt das Pydantic-Modell von dort, generiert das JSON-Schema und fügt es an der richtigen Stelle ein.
+
+Die richtige Stelle ist:
+
+* Im Schlüssel `content`, der als Wert ein weiteres JSON-Objekt (`dict`) hat, welches Folgendes enthält:
+ * Ein Schlüssel mit dem Medientyp, z. B. `application/json`, der als Wert ein weiteres JSON-Objekt hat, welches Folgendes enthält:
+ * Ein Schlüssel `schema`, der als Wert das JSON-Schema aus dem Modell hat, hier ist die richtige Stelle.
+ * **FastAPI** fügt hier eine Referenz auf die globalen JSON-Schemas an einer anderen Stelle in Ihrer OpenAPI hinzu, anstatt es direkt einzubinden. Auf diese Weise können andere Anwendungen und Clients diese JSON-Schemas direkt verwenden, bessere Tools zur Codegenerierung bereitstellen, usw.
+
+///
+
+Die generierten Responses in der OpenAPI für diese *Pfadoperation* lauten:
+
+```JSON hl_lines="3-12"
+{
+ "responses": {
+ "404": {
+ "description": "Additional Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Message"
+ }
+ }
+ }
+ },
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+Die Schemas werden von einer anderen Stelle innerhalb des OpenAPI-Schemas referenziert:
+
+```JSON hl_lines="4-16"
+{
+ "components": {
+ "schemas": {
+ "Message": {
+ "title": "Message",
+ "required": [
+ "message"
+ ],
+ "type": "object",
+ "properties": {
+ "message": {
+ "title": "Message",
+ "type": "string"
+ }
+ }
+ },
+ "Item": {
+ "title": "Item",
+ "required": [
+ "id",
+ "value"
+ ],
+ "type": "object",
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
+ },
+ "value": {
+ "title": "Value",
+ "type": "string"
+ }
+ }
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": [
+ "loc",
+ "msg",
+ "type"
+ ],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string"
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string"
+ }
+ }
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+## Zusätzliche Medientypen für die Haupt-Response { #additional-media-types-for-the-main-response }
+
+Sie können denselben `responses`-Parameter verwenden, um verschiedene Medientypen für dieselbe Haupt-Response hinzuzufügen.
+
+Sie können beispielsweise einen zusätzlichen Medientyp `image/png` hinzufügen und damit deklarieren, dass Ihre *Pfadoperation* ein JSON-Objekt (mit dem Medientyp `application/json`) oder ein PNG-Bild zurückgeben kann:
+
+{* ../../docs_src/additional_responses/tutorial002_py310.py hl[17:22,26] *}
+
+/// note | Hinweis
+
+Beachten Sie, dass Sie das Bild direkt mit einer `FileResponse` zurückgeben müssen.
+
+///
+
+/// info | Info
+
+Sofern Sie in Ihrem Parameter `responses` nicht explizit einen anderen Medientyp angeben, geht FastAPI davon aus, dass die Response denselben Medientyp wie die Haupt-Response-Klasse hat (Standardmäßig `application/json`).
+
+Wenn Sie jedoch eine benutzerdefinierte Response-Klasse mit `None` als Medientyp angegeben haben, verwendet FastAPI `application/json` für jede zusätzliche Response, die über ein zugehöriges Modell verfügt.
+
+///
+
+## Informationen kombinieren { #combining-information }
+
+Sie können auch Response-Informationen von mehreren Stellen kombinieren, einschließlich der Parameter `response_model`, `status_code` und `responses`.
+
+Sie können ein `response_model` deklarieren, indem Sie den Standardstatuscode `200` (oder bei Bedarf einen benutzerdefinierten) verwenden und dann zusätzliche Informationen für dieselbe Response in `responses` direkt im OpenAPI-Schema deklarieren.
+
+**FastAPI** behält die zusätzlichen Informationen aus `responses` und kombiniert sie mit dem JSON-Schema aus Ihrem Modell.
+
+Sie können beispielsweise eine Response mit dem Statuscode `404` deklarieren, die ein Pydantic-Modell verwendet und über eine benutzerdefinierte Beschreibung (`description`) verfügt.
+
+Und eine Response mit dem Statuscode `200`, die Ihr `response_model` verwendet, aber ein benutzerdefiniertes Beispiel (`example`) enthält:
+
+{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}
+
+Es wird alles kombiniert und in Ihre OpenAPI eingebunden und in der API-Dokumentation angezeigt:
+
+
+
+## Vordefinierte und benutzerdefinierte Responses kombinieren { #combine-predefined-responses-and-custom-ones }
+
+Möglicherweise möchten Sie einige vordefinierte Responses haben, die für viele *Pfadoperationen* gelten, Sie möchten diese jedoch mit benutzerdefinierten Responses kombinieren, die für jede *Pfadoperation* erforderlich sind.
+
+In diesen Fällen können Sie die Python-Technik zum „Entpacken“ eines `dict`s mit `**dict_to_unpack` verwenden:
+
+```Python
+old_dict = {
+ "old key": "old value",
+ "second old key": "second old value",
+}
+new_dict = {**old_dict, "new key": "new value"}
+```
+
+Hier wird `new_dict` alle Schlüssel-Wert-Paare von `old_dict` plus das neue Schlüssel-Wert-Paar enthalten:
+
+```Python
+{
+ "old key": "old value",
+ "second old key": "second old value",
+ "new key": "new value",
+}
+```
+
+Mit dieser Technik können Sie einige vordefinierte Responses in Ihren *Pfadoperationen* wiederverwenden und sie mit zusätzlichen benutzerdefinierten Responses kombinieren.
+
+Zum Beispiel:
+
+{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}
+
+## Weitere Informationen zu OpenAPI-Responses { #more-information-about-openapi-responses }
+
+Um zu sehen, was genau Sie in die Responses aufnehmen können, können Sie die folgenden Abschnitte in der OpenAPI-Spezifikation überprüfen:
+
+* [OpenAPI Responses Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responses-object), enthält das `Response Object`.
+* [OpenAPI Response Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#response-object), Sie können alles davon direkt in jede Response innerhalb Ihres `responses`-Parameter einfügen. Einschließlich `description`, `headers`, `content` (darin deklarieren Sie verschiedene Medientypen und JSON-Schemas) und `links`.
diff --git a/docs/de/docs/advanced/additional-status-codes.md b/docs/de/docs/advanced/additional-status-codes.md
new file mode 100644
index 0000000000000..f1a74a32c4657
--- /dev/null
+++ b/docs/de/docs/advanced/additional-status-codes.md
@@ -0,0 +1,41 @@
+# Zusätzliche Statuscodes { #additional-status-codes }
+
+Standardmäßig liefert **FastAPI** die Responses als `JSONResponse` zurück und fügt den Inhalt, den Sie aus Ihrer *Pfadoperation* zurückgeben, in diese `JSONResponse` ein.
+
+Es wird der Default-Statuscode oder derjenige verwendet, den Sie in Ihrer *Pfadoperation* festgelegt haben.
+
+## Zusätzliche Statuscodes { #additional-status-codes_1 }
+
+Wenn Sie neben dem Hauptstatuscode weitere Statuscodes zurückgeben möchten, können Sie dies tun, indem Sie direkt eine `Response` zurückgeben, wie etwa eine `JSONResponse`, und den zusätzlichen Statuscode direkt festlegen.
+
+Angenommen, Sie möchten eine *Pfadoperation* haben, die das Aktualisieren von Artikeln ermöglicht und bei Erfolg den HTTP-Statuscode 200 „OK“ zurückgibt.
+
+Sie möchten aber auch, dass sie neue Artikel akzeptiert. Und wenn die Artikel vorher nicht vorhanden waren, werden diese Artikel erstellt und der HTTP-Statuscode 201 „Created“ zurückgegeben.
+
+Um dies zu erreichen, importieren Sie `JSONResponse`, und geben Sie Ihren Inhalt direkt zurück, indem Sie den gewünschten `status_code` setzen:
+
+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
+
+/// warning | Achtung
+
+Wenn Sie eine `Response` direkt zurückgeben, wie im obigen Beispiel, wird sie direkt zurückgegeben.
+
+Sie wird nicht mit einem Modell usw. serialisiert.
+
+Stellen Sie sicher, dass sie die gewünschten Daten enthält und dass die Werte gültiges JSON sind (wenn Sie `JSONResponse` verwenden).
+
+///
+
+/// note | Technische Details
+
+Sie können auch `from starlette.responses import JSONResponse` verwenden.
+
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Dasselbe gilt für `status`.
+
+///
+
+## OpenAPI- und API-Dokumentation { #openapi-and-api-docs }
+
+Wenn Sie zusätzliche Statuscodes und Responses direkt zurückgeben, werden diese nicht in das OpenAPI-Schema (die API-Dokumentation) aufgenommen, da FastAPI keine Möglichkeit hat, im Voraus zu wissen, was Sie zurückgeben werden.
+
+Sie können das jedoch in Ihrem Code dokumentieren, indem Sie Folgendes verwenden: [Zusätzliche Responses](additional-responses.md).
diff --git a/docs/de/docs/advanced/advanced-dependencies.md b/docs/de/docs/advanced/advanced-dependencies.md
new file mode 100644
index 0000000000000..ab2cab0713af5
--- /dev/null
+++ b/docs/de/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,163 @@
+# Fortgeschrittene Abhängigkeiten { #advanced-dependencies }
+
+## Parametrisierte Abhängigkeiten { #parameterized-dependencies }
+
+Alle Abhängigkeiten, die wir bisher gesehen haben, waren festgelegte Funktionen oder Klassen.
+
+Es kann jedoch Fälle geben, in denen Sie Parameter für eine Abhängigkeit festlegen möchten, ohne viele verschiedene Funktionen oder Klassen zu deklarieren.
+
+Stellen wir uns vor, wir möchten eine Abhängigkeit haben, die prüft, ob ein Query-Parameter `q` einen vordefinierten Inhalt hat.
+
+Aber wir wollen diesen vordefinierten Inhalt per Parameter festlegen können.
+
+## Eine „aufrufbare“ Instanz { #a-callable-instance }
+
+In Python gibt es eine Möglichkeit, eine Instanz einer Klasse „aufrufbar“ zu machen.
+
+Nicht die Klasse selbst (die bereits aufrufbar ist), sondern eine Instanz dieser Klasse.
+
+Dazu deklarieren wir eine Methode `__call__`:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}
+
+In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zusätzlichen Parametern und Unterabhängigkeiten zu suchen, und das ist es auch, was später aufgerufen wird, um einen Wert an den Parameter in Ihrer *Pfadoperation-Funktion* zu übergeben.
+
+## Die Instanz parametrisieren { #parameterize-the-instance }
+
+Und jetzt können wir `__init__` verwenden, um die Parameter der Instanz zu deklarieren, die wir zum „Parametrisieren“ der Abhängigkeit verwenden können:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}
+
+In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmern, wir werden es direkt in unserem Code verwenden.
+
+## Eine Instanz erstellen { #create-an-instance }
+
+Wir könnten eine Instanz dieser Klasse erstellen mit:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}
+
+Und auf diese Weise können wir unsere Abhängigkeit „parametrisieren“, die jetzt `"bar"` enthält, als das Attribut `checker.fixed_content`.
+
+## Die Instanz als Abhängigkeit verwenden { #use-the-instance-as-a-dependency }
+
+Dann könnten wir diesen `checker` in einem `Depends(checker)` anstelle von `Depends(FixedContentQueryChecker)` verwenden, da die Abhängigkeit die Instanz `checker` und nicht die Klasse selbst ist.
+
+Und beim Auflösen der Abhängigkeit ruft **FastAPI** diesen `checker` wie folgt auf:
+
+```Python
+checker(q="somequery")
+```
+
+... und übergibt, was immer das als Wert dieser Abhängigkeit in unserer *Pfadoperation-Funktion* zurückgibt, als den Parameter `fixed_content_included`:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}
+
+/// tip | Tipp
+
+Das alles mag gekünstelt wirken. Und es ist möglicherweise noch nicht ganz klar, welchen Nutzen das hat.
+
+Diese Beispiele sind bewusst einfach gehalten, zeigen aber, wie alles funktioniert.
+
+In den Kapiteln zum Thema Sicherheit gibt es Hilfsfunktionen, die auf die gleiche Weise implementiert werden.
+
+Wenn Sie das hier alles verstanden haben, wissen Sie bereits, wie diese Sicherheits-Hilfswerkzeuge unter der Haube funktionieren.
+
+///
+
+## Abhängigkeiten mit `yield`, `HTTPException`, `except` und Hintergrundtasks { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+/// warning | Achtung
+
+Sie benötigen diese technischen Details höchstwahrscheinlich nicht.
+
+Diese Details sind hauptsächlich nützlich, wenn Sie eine FastAPI-Anwendung haben, die älter als 0.121.0 ist, und Sie auf Probleme mit Abhängigkeiten mit `yield` stoßen.
+
+///
+
+Abhängigkeiten mit `yield` haben sich im Laufe der Zeit weiterentwickelt, um verschiedene Anwendungsfälle abzudecken und einige Probleme zu beheben, hier ist eine Zusammenfassung der Änderungen.
+
+### Abhängigkeiten mit `yield` und `scope` { #dependencies-with-yield-and-scope }
+
+In Version 0.121.0 hat FastAPI Unterstützung für `Depends(scope="function")` für Abhängigkeiten mit `yield` hinzugefügt.
+
+Mit `Depends(scope="function")` wird der Exit-Code nach `yield` direkt nach dem Ende der *Pfadoperation-Funktion* ausgeführt, bevor die Response an den Client gesendet wird.
+
+Und bei Verwendung von `Depends(scope="request")` (dem Default) wird der Exit-Code nach `yield` ausgeführt, nachdem die Response gesendet wurde.
+
+Mehr dazu finden Sie in der Dokumentation zu [Abhängigkeiten mit `yield` – Frühes Beenden und `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope).
+
+### Abhängigkeiten mit `yield` und `StreamingResponse`, Technische Details { #dependencies-with-yield-and-streamingresponse-technical-details }
+
+Vor FastAPI 0.118.0 wurde bei Verwendung einer Abhängigkeit mit `yield` der Exit-Code nach der *Pfadoperation-Funktion* ausgeführt, aber unmittelbar bevor die Response gesendet wurde.
+
+Die Absicht war, Ressourcen nicht länger als nötig zu halten, während darauf gewartet wird, dass die Response durchs Netzwerk reist.
+
+Diese Änderung bedeutete auch, dass bei Rückgabe einer `StreamingResponse` der Exit-Code der Abhängigkeit mit `yield` bereits ausgeführt worden wäre.
+
+Wenn Sie beispielsweise eine Datenbanksession in einer Abhängigkeit mit `yield` hatten, konnte die `StreamingResponse` diese Session während des Streamens von Daten nicht verwenden, weil die Session im Exit-Code nach `yield` bereits geschlossen worden wäre.
+
+Dieses Verhalten wurde in 0.118.0 zurückgenommen, sodass der Exit-Code nach `yield` ausgeführt wird, nachdem die Response gesendet wurde.
+
+/// info | Info
+
+Wie Sie unten sehen werden, ähnelt dies sehr dem Verhalten vor Version 0.106.0, jedoch mit mehreren Verbesserungen und Bugfixes für Sonderfälle.
+
+///
+
+#### Anwendungsfälle mit frühem Exit-Code { #use-cases-with-early-exit-code }
+
+Es gibt einige Anwendungsfälle mit spezifischen Bedingungen, die vom alten Verhalten profitieren könnten, den Exit-Code von Abhängigkeiten mit `yield` vor dem Senden der Response auszuführen.
+
+Stellen Sie sich zum Beispiel vor, Sie haben Code, der in einer Abhängigkeit mit `yield` eine Datenbanksession verwendet, nur um einen Benutzer zu verifizieren, die Datenbanksession wird aber in der *Pfadoperation-Funktion* nie wieder verwendet, sondern nur in der Abhängigkeit, und die Response benötigt lange, um gesendet zu werden, wie eine `StreamingResponse`, die Daten langsam sendet, aus irgendeinem Grund aber die Datenbank nicht verwendet.
+
+In diesem Fall würde die Datenbanksession gehalten, bis das Senden der Response abgeschlossen ist, aber wenn Sie sie nicht verwenden, wäre es nicht notwendig, sie zu halten.
+
+So könnte es aussehen:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
+
+Der Exit-Code, das automatische Schließen der `Session` in:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
+
+... würde ausgeführt, nachdem die Response das langsame Senden der Daten beendet:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
+
+Da `generate_stream()` die Datenbanksession jedoch nicht verwendet, ist es nicht wirklich notwendig, die Session während des Sendens der Response offen zu halten.
+
+Wenn Sie diesen spezifischen Anwendungsfall mit SQLModel (oder SQLAlchemy) haben, könnten Sie die Session explizit schließen, nachdem Sie sie nicht mehr benötigen:
+
+{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}
+
+Auf diese Weise würde die Session die Datenbankverbindung freigeben, sodass andere Requests sie verwenden könnten.
+
+Wenn Sie einen anderen Anwendungsfall haben, der ein frühes Beenden aus einer Abhängigkeit mit `yield` benötigt, erstellen Sie bitte eine [GitHub-Diskussion-Frage](https://github.com/fastapi/fastapi/discussions/new?category=questions) mit Ihrem spezifischen Anwendungsfall und warum Sie von einem frühen Schließen für Abhängigkeiten mit `yield` profitieren würden.
+
+Wenn es überzeugende Anwendungsfälle für ein frühes Schließen bei Abhängigkeiten mit `yield` gibt, würde ich erwägen, eine neue Möglichkeit hinzuzufügen, um ein frühes Schließen optional zu aktivieren.
+
+### Abhängigkeiten mit `yield` und `except`, Technische Details { #dependencies-with-yield-and-except-technical-details }
+
+Vor FastAPI 0.110.0 war es so, dass wenn Sie eine Abhängigkeit mit `yield` verwendet und dann in dieser Abhängigkeit mit `except` eine Exception abgefangen haben und die Exception nicht erneut geworfen haben, die Exception automatisch an beliebige Exceptionhandler oder den Handler für interne Serverfehler weitergereicht/weitergeworfen wurde.
+
+Dies wurde in Version 0.110.0 geändert, um unbehandelten Speicherverbrauch durch weitergeleitete Exceptions ohne Handler (interne Serverfehler) zu beheben und um es mit dem Verhalten von normalem Python-Code konsistent zu machen.
+
+### Hintergrundtasks und Abhängigkeiten mit `yield`, Technische Details { #background-tasks-and-dependencies-with-yield-technical-details }
+
+Vor FastAPI 0.106.0 war das Werfen von Exceptions nach `yield` nicht möglich, der Exit-Code in Abhängigkeiten mit `yield` wurde ausgeführt, nachdem die Response gesendet wurde, sodass [Exceptionhandler](../tutorial/handling-errors.md#install-custom-exception-handlers) bereits ausgeführt worden wären.
+
+Dies war so designt, hauptsächlich um die Verwendung derselben von Abhängigkeiten „geyieldeten“ Objekte in Hintergrundtasks zu ermöglichen, da der Exit-Code erst ausgeführt wurde, nachdem die Hintergrundtasks abgeschlossen waren.
+
+Dies wurde in FastAPI 0.106.0 geändert mit der Absicht, keine Ressourcen zu halten, während darauf gewartet wird, dass die Response durchs Netzwerk reist.
+
+/// tip | Tipp
+
+Zusätzlich ist ein Hintergrundtask normalerweise ein unabhängiger Logikblock, der separat gehandhabt werden sollte, mit eigenen Ressourcen (z. B. eigener Datenbankverbindung).
+
+So haben Sie wahrscheinlich saubereren Code.
+
+///
+
+Wenn Sie sich bisher auf dieses Verhalten verlassen haben, sollten Sie jetzt die Ressourcen für Hintergrundtasks innerhalb des Hintergrundtasks selbst erstellen und intern nur Daten verwenden, die nicht von den Ressourcen von Abhängigkeiten mit `yield` abhängen.
+
+Anstatt beispielsweise dieselbe Datenbanksession zu verwenden, würden Sie innerhalb des Hintergrundtasks eine neue Datenbanksession erstellen und die Objekte aus der Datenbank mithilfe dieser neuen Session beziehen. Und anstatt das Objekt aus der Datenbank als Parameter an die Hintergrundtask-Funktion zu übergeben, würden Sie die ID dieses Objekts übergeben und das Objekt dann innerhalb der Hintergrundtask-Funktion erneut beziehen.
diff --git a/docs/de/docs/advanced/advanced-python-types.md b/docs/de/docs/advanced/advanced-python-types.md
new file mode 100644
index 0000000000000..aed859ceff525
--- /dev/null
+++ b/docs/de/docs/advanced/advanced-python-types.md
@@ -0,0 +1,61 @@
+# Fortgeschrittene Python-Typen { #advanced-python-types }
+
+Hier sind einige zusätzliche Ideen, die beim Arbeiten mit Python-Typen nützlich sein könnten.
+
+## `Union` oder `Optional` verwenden { #using-union-or-optional }
+
+Wenn Ihr Code aus irgendeinem Grund nicht `|` verwenden kann, z. B. wenn es nicht in einer Typannotation ist, sondern in etwas wie `response_model=`, können Sie anstelle des senkrechten Strichs (`|`) `Union` aus `typing` verwenden.
+
+Zum Beispiel könnten Sie deklarieren, dass etwas ein `str` oder `None` sein könnte:
+
+```python
+from typing import Union
+
+
+def say_hi(name: Union[str, None]):
+ print(f"Hi {name}!")
+```
+
+`typing` hat außerdem eine Abkürzung, um zu deklarieren, dass etwas `None` sein könnte, mit `Optional`.
+
+Hier ist ein Tipp aus meiner sehr **subjektiven** Perspektive:
+
+* 🚨 Vermeiden Sie die Verwendung von `Optional[SomeType]`
+* Verwenden Sie stattdessen ✨ **`Union[SomeType, None]`** ✨.
+
+Beides ist äquivalent und unter der Haube identisch, aber ich würde `Union` statt `Optional` empfehlen, weil das Wort „**optional**“ implizieren könnte, dass der Wert optional ist; tatsächlich bedeutet es jedoch „es kann `None` sein“, selbst wenn es nicht optional ist und weiterhin erforderlich bleibt.
+
+Ich finde, `Union[SomeType, None]` ist expliziter in dem, was es bedeutet.
+
+Es geht nur um Wörter und Namen. Aber diese Wörter können beeinflussen, wie Sie und Ihr Team über den Code denken.
+
+Als Beispiel nehmen wir diese Funktion:
+
+```python
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+ print(f"Hey {name}!")
+```
+
+Der Parameter `name` ist als `Optional[str]` definiert, aber er ist **nicht optional**, Sie können die Funktion nicht ohne den Parameter aufrufen:
+
+```Python
+say_hi() # Oh nein, das löst einen Fehler aus! 😱
+```
+
+Der Parameter `name` ist **weiterhin erforderlich** (nicht *optional*), weil er keinen Defaultwert hat. Dennoch akzeptiert `name` den Wert `None`:
+
+```Python
+say_hi(name=None) # Das funktioniert, None ist gültig 🎉
+```
+
+Die gute Nachricht ist: In den meisten Fällen können Sie einfach `|` verwenden, um Unions von Typen zu definieren:
+
+```python
+def say_hi(name: str | None):
+ print(f"Hey {name}!")
+```
+
+Sie müssen sich also normalerweise keine Gedanken über Namen wie `Optional` und `Union` machen. 😎
diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md
new file mode 100644
index 0000000000000..58c925ae6edfc
--- /dev/null
+++ b/docs/de/docs/advanced/async-tests.md
@@ -0,0 +1,99 @@
+# Asynchrone Tests { #async-tests }
+
+Sie haben bereits gesehen, wie Sie Ihre **FastAPI**-Anwendungen mit dem bereitgestellten `TestClient` testen. Bisher haben Sie nur gesehen, wie man synchrone Tests schreibt, ohne `async`-Funktionen zu verwenden.
+
+Die Möglichkeit, in Ihren Tests asynchrone Funktionen zu verwenden, könnte beispielsweise nützlich sein, wenn Sie Ihre Datenbank asynchron abfragen. Stellen Sie sich vor, Sie möchten das Senden von Requests an Ihre FastAPI-Anwendung testen und dann überprüfen, ob Ihr Backend die richtigen Daten erfolgreich in die Datenbank geschrieben hat, während Sie eine asynchrone Datenbankbibliothek verwenden.
+
+Schauen wir uns an, wie wir das machen können.
+
+## pytest.mark.anyio { #pytest-mark-anyio }
+
+Wenn wir in unseren Tests asynchrone Funktionen aufrufen möchten, müssen unsere Testfunktionen asynchron sein. AnyIO stellt hierfür ein nettes Plugin zur Verfügung, mit dem wir festlegen können, dass einige Testfunktionen asynchron aufgerufen werden sollen.
+
+## HTTPX { #httpx }
+
+Auch wenn Ihre **FastAPI**-Anwendung normale `def`-Funktionen anstelle von `async def` verwendet, handelt es sich darunter immer noch um eine `async`-Anwendung.
+
+Der `TestClient` betreibt unter der Haube etwas Magie, um die asynchrone FastAPI-Anwendung in Ihren normalen `def`-Testfunktionen, mithilfe von Standard-Pytest aufzurufen. Aber diese Magie funktioniert nicht mehr, wenn wir sie in asynchronen Funktionen verwenden. Durch die asynchrone Ausführung unserer Tests können wir den `TestClient` nicht mehr in unseren Testfunktionen verwenden.
+
+Der `TestClient` basiert auf [HTTPX](https://www.python-httpx.org) und glücklicherweise können wir es direkt verwenden, um die API zu testen.
+
+## Beispiel { #example }
+
+Betrachten wir als einfaches Beispiel eine Dateistruktur ähnlich der in [Größere Anwendungen](../tutorial/bigger-applications.md) und [Testen](../tutorial/testing.md):
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+Die Datei `main.py` hätte als Inhalt:
+
+{* ../../docs_src/async_tests/app_a_py310/main.py *}
+
+Die Datei `test_main.py` hätte die Tests für `main.py`, das könnte jetzt so aussehen:
+
+{* ../../docs_src/async_tests/app_a_py310/test_main.py *}
+
+## Es ausführen { #run-it }
+
+Sie können Ihre Tests wie gewohnt ausführen mit:
+
+
+
+Wenn wir jedoch unter der „offiziellen“ URL, über den Proxy mit Port `9999`, unter `/api/v1/docs`, auf die Dokumentationsoberfläche zugreifen, funktioniert es ordnungsgemäß! 🎉
+
+Sie können das unter [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs) testen:
+
+
+
+Genau so, wie wir es wollten. ✔️
+
+Dies liegt daran, dass FastAPI diesen `root_path` verwendet, um den Default-`server` in OpenAPI mit der von `root_path` bereitgestellten URL zu erstellen.
+
+## Zusätzliche Server { #additional-servers }
+
+/// warning | Achtung
+
+Dies ist ein fortgeschrittener Anwendungsfall. Überspringen Sie das gerne.
+
+///
+
+Standardmäßig erstellt **FastAPI** einen `server` im OpenAPI-Schema mit der URL für den `root_path`.
+
+Sie können aber auch andere alternative `servers` bereitstellen, beispielsweise wenn Sie möchten, dass *dieselbe* Dokumentationsoberfläche mit einer Staging- und Produktionsumgebung interagiert.
+
+Wenn Sie eine benutzerdefinierte Liste von Servern (`servers`) übergeben und es einen `root_path` gibt (da Ihre API hinter einem Proxy läuft), fügt **FastAPI** einen „Server“ mit diesem `root_path` am Anfang der Liste ein.
+
+Zum Beispiel:
+
+{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}
+
+Erzeugt ein OpenAPI-Schema, wie:
+
+```JSON hl_lines="5-7"
+{
+ "openapi": "3.1.0",
+ // Hier mehr Einstellungen
+ "servers": [
+ {
+ "url": "/api/v1"
+ },
+ {
+ "url": "https://stag.example.com",
+ "description": "Staging environment"
+ },
+ {
+ "url": "https://prod.example.com",
+ "description": "Production environment"
+ }
+ ],
+ "paths": {
+ // Hier mehr Einstellungen
+ }
+}
+```
+
+/// tip | Tipp
+
+Beachten Sie den automatisch generierten Server mit dem `URL`-Wert `/api/v1`, welcher vom `root_path` stammt.
+
+///
+
+In der Dokumentationsoberfläche unter [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs) würde es so aussehen:
+
+
+
+/// tip | Tipp
+
+Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server.
+
+///
+
+/// note | Technische Details
+
+Die Eigenschaft `servers` in der OpenAPI-Spezifikation ist optional.
+
+Wenn Sie den Parameter `servers` nicht angeben und `root_path` den Wert `/` hat, wird die Eigenschaft `servers` im generierten OpenAPI-Schema standardmäßig vollständig weggelassen, was dem Äquivalent eines einzelnen Servers mit einem `url`-Wert von `/` entspricht.
+
+///
+
+### Den automatischen Server von `root_path` deaktivieren { #disable-automatic-server-from-root-path }
+
+Wenn Sie nicht möchten, dass **FastAPI** einen automatischen Server inkludiert, welcher `root_path` verwendet, können Sie den Parameter `root_path_in_servers=False` verwenden:
+
+{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}
+
+Dann wird er nicht in das OpenAPI-Schema aufgenommen.
+
+## Mounten einer Unteranwendung { #mounting-a-sub-application }
+
+Wenn Sie gleichzeitig eine Unteranwendung mounten (wie beschrieben in [Unteranwendungen – Mounts](sub-applications.md)) und einen Proxy mit `root_path` verwenden wollen, können Sie das normal tun, wie Sie es erwarten würden.
+
+FastAPI verwendet intern den `root_path` auf intelligente Weise, sodass es einfach funktioniert. ✨
diff --git a/docs/de/docs/advanced/custom-response.md b/docs/de/docs/advanced/custom-response.md
new file mode 100644
index 0000000000000..9a11089ad6120
--- /dev/null
+++ b/docs/de/docs/advanced/custom-response.md
@@ -0,0 +1,272 @@
+# Benutzerdefinierte Response – HTML, Stream, Datei, andere { #custom-response-html-stream-file-others }
+
+Standardmäßig gibt **FastAPI** JSON-Responses zurück.
+
+Sie können dies überschreiben, indem Sie direkt eine `Response` zurückgeben, wie in [Eine Response direkt zurückgeben](response-directly.md) gezeigt.
+
+Wenn Sie jedoch direkt eine `Response` (oder eine Unterklasse wie `JSONResponse`) zurückgeben, werden die Daten nicht automatisch konvertiert (selbst wenn Sie ein `response_model` deklarieren), und die Dokumentation wird nicht automatisch generiert (zum Beispiel einschließlich des spezifischen „Medientyps“ im HTTP-Header `Content-Type` als Teil der generierten OpenAPI).
+
+Sie können jedoch auch die `Response`, die Sie verwenden möchten (z. B. jede `Response`-Unterklasse), im *Pfadoperation-Dekorator* mit dem `response_class`-Parameter deklarieren.
+
+Der Inhalt, den Sie von Ihrer *Pfadoperation-Funktion* zurückgeben, wird in diese `Response` eingefügt.
+
+/// note | Hinweis
+
+Wenn Sie eine Response-Klasse ohne Medientyp verwenden, erwartet FastAPI, dass Ihre Response keinen Inhalt hat, und dokumentiert daher das Format der Response nicht in deren generierter OpenAPI-Dokumentation.
+
+///
+
+## JSON-Responses { #json-responses }
+
+Standardmäßig gibt FastAPI JSON-Responses zurück.
+
+Wenn Sie ein [Responsemodell](../tutorial/response-model.md) deklarieren, verwendet FastAPI Pydantic, um die Daten zu JSON zu serialisieren.
+
+Wenn Sie kein Responsemodell deklarieren, verwendet FastAPI den `jsonable_encoder`, wie in [JSON-kompatibler Encoder](../tutorial/encoder.md) erklärt, und packt das Ergebnis in eine `JSONResponse`.
+
+Wenn Sie eine `response_class` mit einem JSON-Medientyp (`application/json`) deklarieren, wie es bei `JSONResponse` der Fall ist, werden die von Ihnen zurückgegebenen Daten automatisch mit jedem Pydantic-`response_model` (das Sie im *Pfadoperation-Dekorator* deklariert haben) konvertiert (und gefiltert). Aber die Daten werden nicht mit Pydantic zu JSON-Bytes serialisiert, stattdessen werden sie mit dem `jsonable_encoder` konvertiert und anschließend an die `JSONResponse`-Klasse übergeben, die sie dann mit der Standard-JSON-Bibliothek in Python in Bytes serialisiert.
+
+### JSON-Leistung { #json-performance }
+
+Kurz gesagt: Wenn Sie die maximale Leistung möchten, verwenden Sie ein [Responsemodell](../tutorial/response-model.md) und deklarieren Sie keine `response_class` im *Pfadoperation-Dekorator*.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py ln[15:17] hl[16] *}
+
+## HTML-Response { #html-response }
+
+Um eine Response mit HTML direkt von **FastAPI** zurückzugeben, verwenden Sie `HTMLResponse`.
+
+* Importieren Sie `HTMLResponse`.
+* Übergeben Sie `HTMLResponse` als den Parameter `response_class` Ihres *Pfadoperation-Dekorators*.
+
+{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}
+
+/// info | Info
+
+Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren.
+
+In diesem Fall wird der HTTP-Header `Content-Type` auf `text/html` gesetzt.
+
+Und er wird als solcher in OpenAPI dokumentiert.
+
+///
+
+### Eine `Response` zurückgeben { #return-a-response }
+
+Wie in [Eine Response direkt zurückgeben](response-directly.md) gezeigt, können Sie die Response auch direkt in Ihrer *Pfadoperation* überschreiben, indem Sie diese zurückgeben.
+
+Das gleiche Beispiel von oben, das eine `HTMLResponse` zurückgibt, könnte so aussehen:
+
+{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}
+
+/// warning | Achtung
+
+Eine `Response`, die direkt von Ihrer *Pfadoperation-Funktion* zurückgegeben wird, wird in OpenAPI nicht dokumentiert (zum Beispiel wird der `Content-Type` nicht dokumentiert) und ist in der automatischen interaktiven Dokumentation nicht sichtbar.
+
+///
+
+/// info | Info
+
+Natürlich stammen der eigentliche `Content-Type`-Header, der Statuscode, usw., aus dem `Response`-Objekt, das Sie zurückgegeben haben.
+
+///
+
+### In OpenAPI dokumentieren und `Response` überschreiben { #document-in-openapi-and-override-response }
+
+Wenn Sie die Response innerhalb der Funktion überschreiben und gleichzeitig den „Medientyp“ in OpenAPI dokumentieren möchten, können Sie den `response_class`-Parameter verwenden UND ein `Response`-Objekt zurückgeben.
+
+Die `response_class` wird dann nur zur Dokumentation der OpenAPI-*Pfadoperation* verwendet, Ihre `Response` wird jedoch unverändert verwendet.
+
+#### Eine `HTMLResponse` direkt zurückgeben { #return-an-htmlresponse-directly }
+
+Es könnte zum Beispiel so etwas sein:
+
+{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}
+
+In diesem Beispiel generiert die Funktion `generate_html_response()` bereits eine `Response` und gibt sie zurück, anstatt das HTML in einem `str` zurückzugeben.
+
+Indem Sie das Ergebnis des Aufrufs von `generate_html_response()` zurückgeben, geben Sie bereits eine `Response` zurück, die das Standardverhalten von **FastAPI** überschreibt.
+
+Aber da Sie die `HTMLResponse` auch in der `response_class` übergeben haben, weiß **FastAPI**, dass sie in OpenAPI und der interaktiven Dokumentation als HTML mit `text/html` zu dokumentieren ist:
+
+
+
+## Verfügbare Responses { #available-responses }
+
+Hier sind einige der verfügbaren Responses.
+
+Bedenken Sie, dass Sie `Response` verwenden können, um alles andere zurückzugeben, oder sogar eine benutzerdefinierte Unterklasse zu erstellen.
+
+/// note | Technische Details
+
+Sie können auch `from starlette.responses import HTMLResponse` verwenden.
+
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+
+///
+
+### `Response` { #response }
+
+Die Hauptklasse `Response`, alle anderen Responses erben von ihr.
+
+Sie können sie direkt zurückgeben.
+
+Sie akzeptiert die folgenden Parameter:
+
+* `content` – Ein `str` oder `bytes`.
+* `status_code` – Ein `int`-HTTP-Statuscode.
+* `headers` – Ein `dict` von Strings.
+* `media_type` – Ein `str`, der den Medientyp angibt. Z. B. `"text/html"`.
+
+FastAPI (eigentlich Starlette) fügt automatisch einen Content-Length-Header ein. Außerdem wird es einen Content-Type-Header einfügen, der auf dem `media_type` basiert, und für Texttypen einen Zeichensatz (charset) anfügen.
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+### `HTMLResponse` { #htmlresponse }
+
+Nimmt Text oder Bytes entgegen und gibt eine HTML-Response zurück, wie Sie oben gelesen haben.
+
+### `PlainTextResponse` { #plaintextresponse }
+
+Nimmt Text oder Bytes entgegen und gibt eine Plain-Text-Response zurück.
+
+{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}
+
+### `JSONResponse` { #jsonresponse }
+
+Nimmt einige Daten entgegen und gibt eine `application/json`-codierte Response zurück.
+
+Dies ist die Standard-Response, die in **FastAPI** verwendet wird, wie Sie oben gelesen haben.
+
+/// note | Technische Details
+
+Wenn Sie jedoch ein Responsemodell oder einen Rückgabetyp deklarieren, wird dieser direkt verwendet, um die Daten zu JSON zu serialisieren, und eine Response mit dem richtigen Medientyp für JSON wird direkt zurückgegeben, ohne die `JSONResponse`-Klasse zu verwenden.
+
+Dies ist der ideale Weg, um die beste Leistung zu erzielen.
+
+///
+
+### `RedirectResponse` { #redirectresponse }
+
+Gibt eine HTTP-Weiterleitung (HTTP-Redirect) zurück. Verwendet standardmäßig den Statuscode 307 – Temporäre Weiterleitung (Temporary Redirect).
+
+Sie können eine `RedirectResponse` direkt zurückgeben:
+
+{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}
+
+---
+
+Oder Sie können sie im Parameter `response_class` verwenden:
+
+{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}
+
+Wenn Sie das tun, können Sie die URL direkt von Ihrer *Pfadoperation*-Funktion zurückgeben.
+
+In diesem Fall ist der verwendete `status_code` der Standardcode für die `RedirectResponse`, also `307`.
+
+---
+
+Sie können den Parameter `status_code` auch in Kombination mit dem Parameter `response_class` verwenden:
+
+{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}
+
+### `StreamingResponse` { #streamingresponse }
+
+Nimmt einen asynchronen Generator oder einen normalen Generator/Iterator (eine Funktion mit `yield`) und streamt den Responsebody.
+
+{* ../../docs_src/custom_response/tutorial007_py310.py hl[3,16] *}
+
+/// note | Technische Details
+
+Ein `async`-Task kann nur abgebrochen werden, wenn er ein `await` erreicht. Wenn es kein `await` gibt, kann der Generator (Funktion mit `yield`) nicht ordnungsgemäß abgebrochen werden und könnte weiterlaufen, selbst nachdem der Abbruch angefordert wurde.
+
+Da dieses kleine Beispiel keine `await`-Anweisungen benötigt, fügen wir ein `await anyio.sleep(0)` hinzu, um dem Event Loop die Chance zu geben, den Abbruch zu verarbeiten.
+
+Dies wäre bei großen oder unendlichen Streams noch wichtiger.
+
+///
+
+/// tip | Tipp
+
+Anstatt eine `StreamingResponse` direkt zurückzugeben, sollten Sie wahrscheinlich dem Stil in [Daten streamen](./stream-data.md) folgen. Das ist wesentlich bequemer und behandelt den Abbruch im Hintergrund für Sie.
+
+Wenn Sie JSON Lines streamen, folgen Sie dem Tutorial [JSON Lines streamen](../tutorial/stream-json-lines.md).
+
+///
+
+### `FileResponse` { #fileresponse }
+
+Streamt eine Datei asynchron als Response.
+
+Nimmt zur Instanziierung einen anderen Satz von Argumenten entgegen als die anderen Response-Typen:
+
+* `path` – Der Dateipfad zur Datei, die gestreamt werden soll.
+* `headers` – Alle benutzerdefinierten Header, die inkludiert werden sollen, als Dictionary.
+* `media_type` – Ein String, der den Medientyp angibt. Wenn nicht gesetzt, wird der Dateiname oder Pfad verwendet, um auf einen Medientyp zu schließen.
+* `filename` – Wenn gesetzt, wird das in der `Content-Disposition` der Response eingefügt.
+
+Datei-Responses enthalten die entsprechenden `Content-Length`-, `Last-Modified`- und `ETag`-Header.
+
+{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}
+
+Sie können auch den Parameter `response_class` verwenden:
+
+{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}
+
+In diesem Fall können Sie den Dateipfad direkt von Ihrer *Pfadoperation*-Funktion zurückgeben.
+
+## Benutzerdefinierte Response-Klasse { #custom-response-class }
+
+Sie können Ihre eigene benutzerdefinierte Response-Klasse erstellen, die von `Response` erbt und diese verwendet.
+
+Nehmen wir zum Beispiel an, dass Sie [`orjson`](https://github.com/ijl/orjson) mit einigen Einstellungen verwenden möchten.
+
+Sie möchten etwa, dass Ihre Response eingerücktes und formatiertes JSON zurückgibt. Dafür möchten Sie die orjson-Option `orjson.OPT_INDENT_2` verwenden.
+
+Sie könnten eine `CustomORJSONResponse` erstellen. Das Wichtigste, was Sie tun müssen, ist, eine `Response.render(content)`-Methode zu erstellen, die den Inhalt als `bytes` zurückgibt:
+
+{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}
+
+Anstatt Folgendes zurückzugeben:
+
+```json
+{"message": "Hello World"}
+```
+
+... wird diese Response Folgendes zurückgeben:
+
+```json
+{
+ "message": "Hello World"
+}
+```
+
+Natürlich werden Sie wahrscheinlich viel bessere Möglichkeiten finden, Vorteil daraus zu ziehen, als JSON zu formatieren. 😉
+
+### `orjson` oder Responsemodell { #orjson-or-response-model }
+
+Wenn es Ihnen um Leistung geht, sind Sie wahrscheinlich mit einem [Responsemodell](../tutorial/response-model.md) besser beraten als mit einer `orjson`-Response.
+
+Mit einem Responsemodell verwendet FastAPI Pydantic, um die Daten ohne Zwischenschritte zu JSON zu serialisieren, also ohne sie z. B. erst mit `jsonable_encoder` zu konvertieren, was sonst der Fall wäre.
+
+Und unter der Haube verwendet Pydantic dieselben Rust-Mechanismen wie `orjson`, um nach JSON zu serialisieren. Sie erhalten mit einem Responsemodell also ohnehin die beste Leistung.
+
+## Standard-Response-Klasse { #default-response-class }
+
+Beim Erstellen einer **FastAPI**-Klasseninstanz oder eines `APIRouter`s können Sie angeben, welche Response-Klasse standardmäßig verwendet werden soll.
+
+Der Parameter, der das definiert, ist `default_response_class`.
+
+Im folgenden Beispiel verwendet **FastAPI** standardmäßig `HTMLResponse` in allen *Pfadoperationen*, anstelle von JSON.
+
+{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}
+
+/// tip | Tipp
+
+Sie können dennoch weiterhin `response_class` in *Pfadoperationen* überschreiben, wie bisher.
+
+///
+
+## Zusätzliche Dokumentation { #additional-documentation }
+
+Sie können auch den Medientyp und viele andere Details in OpenAPI mit `responses` deklarieren: [Zusätzliche Responses in OpenAPI](additional-responses.md).
diff --git a/docs/de/docs/advanced/dataclasses.md b/docs/de/docs/advanced/dataclasses.md
new file mode 100644
index 0000000000000..743aea6999769
--- /dev/null
+++ b/docs/de/docs/advanced/dataclasses.md
@@ -0,0 +1,95 @@
+# Datenklassen verwenden { #using-dataclasses }
+
+FastAPI basiert auf **Pydantic**, und ich habe Ihnen gezeigt, wie Sie Pydantic-Modelle verwenden können, um Requests und Responses zu deklarieren.
+
+Aber FastAPI unterstützt auf die gleiche Weise auch die Verwendung von [`dataclasses`](https://docs.python.org/3/library/dataclasses.html):
+
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
+
+Das ist dank **Pydantic** ebenfalls möglich, da es [„`dataclasses` intern unterstützt“](https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel).
+
+Auch wenn im obigen Code Pydantic nicht explizit vorkommt, verwendet FastAPI Pydantic, um diese Standard-Datenklassen in Pydantics eigene Variante von Datenklassen zu konvertieren.
+
+Und natürlich wird das gleiche unterstützt:
+
+* Datenvalidierung
+* Datenserialisierung
+* Datendokumentation, usw.
+
+Das funktioniert genauso wie mit Pydantic-Modellen. Und tatsächlich wird es unter der Haube mittels Pydantic auf die gleiche Weise bewerkstelligt.
+
+/// info | Info
+
+Bedenken Sie, dass Datenklassen nicht alles können, was Pydantic-Modelle können.
+
+Daher müssen Sie möglicherweise weiterhin Pydantic-Modelle verwenden.
+
+Wenn Sie jedoch eine Menge Datenklassen herumliegen haben, ist dies ein guter Trick, um sie für eine Web-API mithilfe von FastAPI zu verwenden. 🤓
+
+///
+
+## Datenklassen in `response_model` { #dataclasses-in-response-model }
+
+Sie können `dataclasses` auch im Parameter `response_model` verwenden:
+
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
+
+Die Datenklasse wird automatisch in eine Pydantic-Datenklasse konvertiert.
+
+Auf diese Weise wird deren Schema in der Benutzeroberfläche der API-Dokumentation angezeigt:
+
+
+
+## Datenklassen in verschachtelten Datenstrukturen { #dataclasses-in-nested-data-structures }
+
+Sie können `dataclasses` auch mit anderen Typannotationen kombinieren, um verschachtelte Datenstrukturen zu erstellen.
+
+In einigen Fällen müssen Sie möglicherweise immer noch Pydantics Version von `dataclasses` verwenden. Zum Beispiel, wenn Sie Fehler in der automatisch generierten API-Dokumentation haben.
+
+In diesem Fall können Sie einfach die Standard-`dataclasses` durch `pydantic.dataclasses` ersetzen, was einen direkten Ersatz darstellt:
+
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+
+1. Wir importieren `field` weiterhin von Standard-`dataclasses`.
+
+2. `pydantic.dataclasses` ist ein direkter Ersatz für `dataclasses`.
+
+3. Die Datenklasse `Author` enthält eine Liste von `Item`-Datenklassen.
+
+4. Die Datenklasse `Author` wird im `response_model`-Parameter verwendet.
+
+5. Sie können andere Standard-Typannotationen mit Datenklassen als Requestbody verwenden.
+
+ In diesem Fall handelt es sich um eine Liste von `Item`-Datenklassen.
+
+6. Hier geben wir ein Dictionary zurück, das `items` enthält, welches eine Liste von Datenklassen ist.
+
+ FastAPI ist weiterhin in der Lage, die Daten nach JSON zu Serialisieren.
+
+7. Hier verwendet das `response_model` als Typannotation eine Liste von `Author`-Datenklassen.
+
+ Auch hier können Sie `dataclasses` mit Standard-Typannotationen kombinieren.
+
+8. Beachten Sie, dass diese *Pfadoperation-Funktion* reguläres `def` anstelle von `async def` verwendet.
+
+ Wie immer können Sie in FastAPI `def` und `async def` beliebig kombinieren.
+
+ Wenn Sie eine Auffrischung darüber benötigen, wann welche Anwendung sinnvoll ist, lesen Sie den Abschnitt „In Eile?“ in der Dokumentation zu [`async` und `await`](../async.md#in-a-hurry).
+
+9. Diese *Pfadoperation-Funktion* gibt keine Datenklassen zurück (obwohl dies möglich wäre), sondern eine Liste von Dictionarys mit internen Daten.
+
+ FastAPI verwendet den Parameter `response_model` (der Datenklassen enthält), um die Response zu konvertieren.
+
+Sie können `dataclasses` mit anderen Typannotationen auf vielfältige Weise kombinieren, um komplexe Datenstrukturen zu bilden.
+
+Weitere Einzelheiten finden Sie in den Bemerkungen im Quellcode oben.
+
+## Mehr erfahren { #learn-more }
+
+Sie können `dataclasses` auch mit anderen Pydantic-Modellen kombinieren, von ihnen erben, sie in Ihre eigenen Modelle einbinden, usw.
+
+Weitere Informationen finden Sie in der [Pydantic-Dokumentation zu Datenklassen](https://docs.pydantic.dev/latest/concepts/dataclasses/).
+
+## Version { #version }
+
+Dies ist verfügbar seit FastAPI-Version `0.67.0`. 🔖
diff --git a/docs/de/docs/advanced/events.md b/docs/de/docs/advanced/events.md
new file mode 100644
index 0000000000000..ea04e3ebdeed7
--- /dev/null
+++ b/docs/de/docs/advanced/events.md
@@ -0,0 +1,165 @@
+# Lifespan-Events { #lifespan-events }
+
+Sie können Logik (Code) definieren, die ausgeführt werden soll, bevor die Anwendung **hochfährt**. Dies bedeutet, dass dieser Code **einmal** ausgeführt wird, **bevor** die Anwendung **beginnt, Requests entgegenzunehmen**.
+
+Auf die gleiche Weise können Sie Logik (Code) definieren, die ausgeführt werden soll, wenn die Anwendung **heruntergefahren** wird. In diesem Fall wird dieser Code **einmal** ausgeführt, **nachdem** möglicherweise **viele Requests** bearbeitet wurden.
+
+Da dieser Code ausgeführt wird, bevor die Anwendung **beginnt**, Requests entgegenzunehmen, und unmittelbar, nachdem sie die Bearbeitung von Requests **abgeschlossen hat**, deckt er den gesamten Anwendungs-**Lifespan** ab (das Wort „Lifespan“ wird gleich wichtig sein 😉).
+
+Dies kann sehr nützlich sein, um **Ressourcen** einzurichten, die Sie in der gesamten App verwenden wollen und die von Requests **gemeinsam genutzt** werden und/oder die Sie anschließend **aufräumen** müssen. Zum Beispiel ein Pool von Datenbankverbindungen oder das Laden eines gemeinsam genutzten Modells für maschinelles Lernen.
+
+## Anwendungsfall { #use-case }
+
+Beginnen wir mit einem Beispiel-**Anwendungsfall** und schauen uns dann an, wie wir ihn mit dieser Methode implementieren können.
+
+Stellen wir uns vor, Sie verfügen über einige **Modelle für maschinelles Lernen**, die Sie zur Bearbeitung von Requests verwenden möchten. 🤖
+
+Die gleichen Modelle werden von den Requests gemeinsam genutzt, es handelt sich also nicht um ein Modell pro Request, pro Benutzer, oder ähnliches.
+
+Stellen wir uns vor, dass das Laden des Modells **eine ganze Weile dauern** kann, da viele **Daten von der Festplatte** gelesen werden müssen. Sie möchten das also nicht für jeden Request tun.
+
+Sie könnten das auf der obersten Ebene des Moduls/der Datei machen, aber das würde auch bedeuten, dass **das Modell geladen wird**, selbst wenn Sie nur einen einfachen automatisierten Test ausführen, dann wäre dieser Test **langsam**, weil er warten müsste, bis das Modell geladen ist, bevor er einen davon unabhängigen Teil des Codes ausführen könnte.
+
+Das wollen wir besser machen: Laden wir das Modell, bevor die Requests bearbeitet werden, aber unmittelbar bevor die Anwendung beginnt, Requests zu empfangen, und nicht, während der Code geladen wird.
+
+## Lifespan { #lifespan }
+
+Sie können diese Logik beim *Startup* und *Shutdown* mithilfe des `lifespan`-Parameters der `FastAPI`-App und eines „Kontextmanagers“ definieren (ich zeige Ihnen gleich, was das ist).
+
+Beginnen wir mit einem Beispiel und sehen es uns dann im Detail an.
+
+Wir erstellen eine asynchrone Funktion `lifespan()` mit `yield` wie folgt:
+
+{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}
+
+Hier simulieren wir den langsamen *Startup*, das Laden des Modells, indem wir die (Fake-)Modellfunktion vor dem `yield` in das Dictionary mit Modellen für maschinelles Lernen einfügen. Dieser Code wird ausgeführt, **bevor** die Anwendung **beginnt, Requests entgegenzunehmen**, während des *Startups*.
+
+Und dann, direkt nach dem `yield`, entladen wir das Modell. Dieser Code wird ausgeführt, **nachdem** die Anwendung **die Bearbeitung von Requests abgeschlossen hat**, direkt vor dem *Shutdown*. Dadurch könnten beispielsweise Ressourcen wie Arbeitsspeicher oder eine GPU freigegeben werden.
+
+/// tip | Tipp
+
+Das `shutdown` würde erfolgen, wenn Sie die Anwendung **stoppen**.
+
+Möglicherweise müssen Sie eine neue Version starten, oder Sie haben es einfach satt, sie auszuführen. 🤷
+
+///
+
+### Lifespan-Funktion { #lifespan-function }
+
+Das Erste, was auffällt, ist, dass wir eine asynchrone Funktion mit `yield` definieren. Das ist sehr ähnlich zu Abhängigkeiten mit `yield`.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}
+
+Der erste Teil der Funktion, vor dem `yield`, wird ausgeführt **bevor** die Anwendung startet.
+
+Und der Teil nach `yield` wird ausgeführt, **nachdem** die Anwendung beendet ist.
+
+### Asynchroner Kontextmanager { #async-context-manager }
+
+Wie Sie sehen, ist die Funktion mit einem `@asynccontextmanager` versehen.
+
+Dadurch wird die Funktion in einen sogenannten „**asynchronen Kontextmanager**“ umgewandelt.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}
+
+Ein **Kontextmanager** in Python ist etwas, das Sie in einer `with`-Anweisung verwenden können, zum Beispiel kann `open()` als Kontextmanager verwendet werden:
+
+```Python
+with open("file.txt") as file:
+ file.read()
+```
+
+In neueren Versionen von Python gibt es auch einen **asynchronen Kontextmanager**. Sie würden ihn mit `async with` verwenden:
+
+```Python
+async with lifespan(app):
+ await do_stuff()
+```
+
+Wenn Sie wie oben einen Kontextmanager oder einen asynchronen Kontextmanager erstellen, führt dieser vor dem Betreten des `with`-Blocks den Code vor dem `yield` aus, und nach dem Verlassen des `with`-Blocks wird er den Code nach dem `yield` ausführen.
+
+In unserem obigen Codebeispiel verwenden wir ihn nicht direkt, sondern übergeben ihn an FastAPI, damit es ihn verwenden kann.
+
+Der Parameter `lifespan` der `FastAPI`-App benötigt einen **asynchronen Kontextmanager**, wir können ihm also unseren neuen asynchronen Kontextmanager `lifespan` übergeben.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[22] *}
+
+## Alternative Events (deprecatet) { #alternative-events-deprecated }
+
+/// warning | Achtung
+
+Der empfohlene Weg, den *Startup* und *Shutdown* zu handhaben, ist die Verwendung des `lifespan`-Parameters der `FastAPI`-App, wie oben beschrieben. Wenn Sie einen `lifespan`-Parameter übergeben, werden die `startup`- und `shutdown`-Eventhandler nicht mehr aufgerufen. Es ist entweder alles `lifespan` oder alles Events, nicht beides.
+
+Sie können diesen Teil wahrscheinlich überspringen.
+
+///
+
+Es gibt eine alternative Möglichkeit, diese Logik zu definieren, sodass sie beim *Startup* und beim *Shutdown* ausgeführt wird.
+
+Sie können Eventhandler (Funktionen) definieren, die ausgeführt werden sollen, bevor die Anwendung hochgefahren wird oder wenn die Anwendung heruntergefahren wird.
+
+Diese Funktionen können mit `async def` oder normalem `def` deklariert werden.
+
+### `startup`-Event { #startup-event }
+
+Um eine Funktion hinzuzufügen, die vor dem Start der Anwendung ausgeführt werden soll, deklarieren Sie diese mit dem Event `startup`:
+
+{* ../../docs_src/events/tutorial001_py310.py hl[8] *}
+
+In diesem Fall initialisiert die Eventhandler-Funktion `startup` die „Datenbank“ der Items (nur ein `dict`) mit einigen Werten.
+
+Sie können mehr als eine Eventhandler-Funktion hinzufügen.
+
+Und Ihre Anwendung empfängt erst dann Requests, wenn alle `startup`-Eventhandler abgeschlossen sind.
+
+### `shutdown`-Event { #shutdown-event }
+
+Um eine Funktion hinzuzufügen, die beim Shutdown der Anwendung ausgeführt werden soll, deklarieren Sie sie mit dem Event `shutdown`:
+
+{* ../../docs_src/events/tutorial002_py310.py hl[6] *}
+
+Hier schreibt die `shutdown`-Eventhandler-Funktion eine Textzeile `"Application shutdown"` in eine Datei `log.txt`.
+
+/// info | Info
+
+In der Funktion `open()` bedeutet `mode="a"` „append“ („anhängen“), sodass die Zeile nach dem, was sich in dieser Datei befindet, hinzugefügt wird, ohne den vorherigen Inhalt zu überschreiben.
+
+///
+
+/// tip | Tipp
+
+Beachten Sie, dass wir in diesem Fall eine Standard-Python-Funktion `open()` verwenden, die mit einer Datei interagiert.
+
+Es handelt sich also um I/O (Input/Output), welches „Warten“ erfordert, bis Dinge auf die Festplatte geschrieben werden.
+
+Aber `open()` verwendet nicht `async` und `await`.
+
+Daher deklarieren wir die Eventhandler-Funktion mit Standard-`def` statt mit `async def`.
+
+///
+
+### `startup` und `shutdown` zusammen { #startup-and-shutdown-together }
+
+Es besteht eine hohe Wahrscheinlichkeit, dass die Logik für Ihr *Startup* und *Shutdown* miteinander verknüpft ist. Vielleicht möchten Sie etwas beginnen und es dann beenden, eine Ressource laden und sie dann freigeben usw.
+
+Bei getrennten Funktionen, die keine gemeinsame Logik oder Variablen haben, ist dies schwieriger, da Sie Werte in globalen Variablen speichern oder ähnliche Tricks verwenden müssen.
+
+Aus diesem Grund wird jetzt empfohlen, stattdessen `lifespan` wie oben erläutert zu verwenden.
+
+## Technische Details { #technical-details }
+
+Nur ein technisches Detail für die neugierigen Nerds. 🤓
+
+In der technischen ASGI-Spezifikation ist dies Teil des [Lifespan Protokolls](https://asgi.readthedocs.io/en/latest/specs/lifespan.html) und definiert Events namens `startup` und `shutdown`.
+
+/// info | Info
+
+Weitere Informationen zu Starlettes `lifespan`-Handlern finden Sie in [Starlettes Lifespan-Dokumentation](https://www.starlette.dev/lifespan/).
+
+Einschließlich, wie man Lifespan-Zustand handhabt, der in anderen Bereichen Ihres Codes verwendet werden kann.
+
+///
+
+## Unteranwendungen { #sub-applications }
+
+🚨 Beachten Sie, dass diese Lifespan-Events (Startup und Shutdown) nur für die Hauptanwendung ausgeführt werden, nicht für [Unteranwendungen – Mounts](sub-applications.md).
diff --git a/docs/de/docs/advanced/generate-clients.md b/docs/de/docs/advanced/generate-clients.md
new file mode 100644
index 0000000000000..12ba4072c4fc7
--- /dev/null
+++ b/docs/de/docs/advanced/generate-clients.md
@@ -0,0 +1,208 @@
+# SDKs generieren { #generating-sdks }
+
+Da **FastAPI** auf der **OpenAPI**-Spezifikation basiert, können dessen APIs in einem standardisierten Format beschrieben werden, das viele Tools verstehen.
+
+Dies vereinfacht es, aktuelle **Dokumentation** und Client-Bibliotheken (**SDKs**) in verschiedenen Sprachen zu generieren sowie **Test-** oder **Automatisierungs-Workflows**, die mit Ihrem Code synchron bleiben.
+
+In diesem Leitfaden erfahren Sie, wie Sie ein **TypeScript-SDK** für Ihr FastAPI-Backend generieren.
+
+## Open Source SDK-Generatoren { #open-source-sdk-generators }
+
+Eine vielseitige Möglichkeit ist der [OpenAPI Generator](https://openapi-generator.tech/), der **viele Programmiersprachen** unterstützt und SDKs aus Ihrer OpenAPI-Spezifikation generieren kann.
+
+Für **TypeScript-Clients** ist [Hey API](https://heyapi.dev/) eine speziell entwickelte Lösung, die ein optimiertes Erlebnis für das TypeScript-Ökosystem bietet.
+
+Weitere SDK-Generatoren finden Sie auf [OpenAPI.Tools](https://openapi.tools/#sdk).
+
+/// tip | Tipp
+
+FastAPI generiert automatisch **OpenAPI 3.1**-Spezifikationen, daher muss jedes von Ihnen verwendete Tool diese Version unterstützen.
+
+///
+
+## SDK-Generatoren von FastAPI-Sponsoren { #sdk-generators-from-fastapi-sponsors }
+
+Dieser Abschnitt hebt **venture-unterstützte** und **firmengestützte** Lösungen hervor, die von Unternehmen entwickelt werden, welche FastAPI sponsern. Diese Produkte bieten **zusätzliche Funktionen** und **Integrationen** zusätzlich zu hochwertig generierten SDKs.
+
+Durch das ✨ [**Sponsoring von FastAPI**](../help-fastapi.md#sponsor-the-author) ✨ helfen diese Unternehmen sicherzustellen, dass das Framework und sein **Ökosystem** gesund und **nachhaltig** bleiben.
+
+Ihr Sponsoring zeigt auch ein starkes Engagement für die FastAPI-**Community** (Sie), was bedeutet, dass sie nicht nur einen **großartigen Service** bieten möchten, sondern auch ein **robustes und florierendes Framework**, FastAPI, unterstützen möchten. 🙇
+
+Zum Beispiel könnten Sie ausprobieren:
+
+* [Speakeasy](https://speakeasy.com/editor?utm_source=fastapi+repo&utm_medium=github+sponsorship)
+* [Stainless](https://www.stainless.com/?utm_source=fastapi&utm_medium=referral)
+* [liblab](https://developers.liblab.com/tutorials/sdk-for-fastapi?utm_source=fastapi)
+
+Einige dieser Lösungen sind möglicherweise auch Open Source oder bieten kostenlose Tarife an, sodass Sie diese ohne finanzielle Verpflichtung ausprobieren können. Andere kommerzielle SDK-Generatoren sind online verfügbar und können dort gefunden werden. 🤓
+
+## Ein TypeScript-SDK erstellen { #create-a-typescript-sdk }
+
+Beginnen wir mit einer einfachen FastAPI-Anwendung:
+
+{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}
+
+Beachten Sie, dass die *Pfadoperationen* die Modelle definieren, die sie für die Request- und Response-Payload verwenden, indem sie die Modelle `Item` und `ResponseMessage` verwenden.
+
+### API-Dokumentation { #api-docs }
+
+Wenn Sie zu `/docs` gehen, sehen Sie, dass es die **Schemas** für die Daten enthält, die in Requests gesendet und in Responses empfangen werden:
+
+
+
+Sie können diese Schemas sehen, da sie mit den Modellen in der App deklariert wurden.
+
+Diese Informationen sind im **OpenAPI-Schema** der Anwendung verfügbar und werden in der API-Dokumentation angezeigt.
+
+Diese Informationen aus den Modellen, die in OpenAPI enthalten sind, können verwendet werden, um **den Client-Code zu generieren**.
+
+### Hey API { #hey-api }
+
+Sobald wir eine FastAPI-App mit den Modellen haben, können wir Hey API verwenden, um einen TypeScript-Client zu generieren. Der schnellste Weg das zu tun, ist über npx.
+
+```sh
+npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
+```
+
+Dies generiert ein TypeScript-SDK in `./src/client`.
+
+Sie können lernen, wie man [`@hey-api/openapi-ts` installiert](https://heyapi.dev/openapi-ts/get-started) und über die [erzeugte Ausgabe](https://heyapi.dev/openapi-ts/output) auf deren Website lesen.
+
+### Das SDK verwenden { #using-the-sdk }
+
+Jetzt können Sie den Client-Code importieren und verwenden. Er könnte wie folgt aussehen, beachten Sie, dass Sie eine automatische Vervollständigung für die Methoden erhalten:
+
+
+
+Sie werden auch eine automatische Vervollständigung für die zu sendende Payload erhalten:
+
+
+
+/// tip | Tipp
+
+Beachten Sie die automatische Vervollständigung für `name` und `price`, die in der FastAPI-Anwendung im `Item`-Modell definiert wurden.
+
+///
+
+Sie erhalten Inline-Fehlerberichte für die von Ihnen gesendeten Daten:
+
+
+
+Das Response-Objekt hat auch automatische Vervollständigung:
+
+
+
+## FastAPI-Anwendung mit Tags { #fastapi-app-with-tags }
+
+In vielen Fällen wird Ihre FastAPI-App größer sein und Sie werden wahrscheinlich Tags verwenden, um verschiedene Gruppen von *Pfadoperationen* zu separieren.
+
+Zum Beispiel könnten Sie einen Abschnitt für **Items** und einen weiteren Abschnitt für **Users** haben, und diese könnten durch Tags getrennt sein:
+
+{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}
+
+### Einen TypeScript-Client mit Tags generieren { #generate-a-typescript-client-with-tags }
+
+Wenn Sie einen Client für eine FastAPI-App generieren, die Tags verwendet, wird normalerweise der Client-Code auch anhand der Tags getrennt.
+
+Auf diese Weise können Sie die Dinge für den Client-Code richtig ordnen und gruppieren:
+
+
+
+In diesem Fall haben Sie:
+
+* `ItemsService`
+* `UsersService`
+
+### Client-Methodennamen { #client-method-names }
+
+Im Moment sehen die generierten Methodennamen wie `createItemItemsPost` nicht sehr sauber aus:
+
+```TypeScript
+ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
+```
+
+... das liegt daran, dass der Client-Generator für jede *Pfadoperation* die OpenAPI-interne **Operation-ID** verwendet.
+
+OpenAPI erfordert, dass jede Operation-ID innerhalb aller *Pfadoperationen* einzigartig ist. Daher verwendet FastAPI den **Funktionsnamen**, den **Pfad** und die **HTTP-Methode/-Operation**, um diese Operation-ID zu generieren. Denn so kann sichergestellt werden, dass die Operation-IDs einzigartig sind.
+
+Aber ich zeige Ihnen als Nächstes, wie Sie das verbessern können. 🤓
+
+## Benutzerdefinierte Operation-IDs und bessere Methodennamen { #custom-operation-ids-and-better-method-names }
+
+Sie können die Art und Weise, wie diese Operation-IDs **generiert** werden, **ändern**, um sie einfacher zu machen und **einfachere Methodennamen** in den Clients zu haben.
+
+In diesem Fall müssen Sie auf andere Weise sicherstellen, dass jede Operation-ID **einzigartig** ist.
+
+Zum Beispiel könnten Sie sicherstellen, dass jede *Pfadoperation* einen Tag hat, und dann die Operation-ID basierend auf dem **Tag** und dem *Pfadoperation*-**Namen** (dem Funktionsnamen) generieren.
+
+### Eine benutzerdefinierte Funktion zur Erzeugung einer eindeutigen ID erstellen { #custom-generate-unique-id-function }
+
+FastAPI verwendet eine **eindeutige ID** für jede *Pfadoperation*, die für die **Operation-ID** und auch für die Namen aller benötigten benutzerdefinierten Modelle für Requests oder Responses verwendet wird.
+
+Sie können diese Funktion anpassen. Sie nimmt ein `APIRoute` und gibt einen String zurück.
+
+Hier verwendet sie beispielsweise den ersten Tag (Sie werden wahrscheinlich nur einen Tag haben) und den *Pfadoperation*-Namen (den Funktionsnamen).
+
+Anschließend können Sie diese benutzerdefinierte Funktion als `generate_unique_id_function`-Parameter an **FastAPI** übergeben:
+
+{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}
+
+### Einen TypeScript-Client mit benutzerdefinierten Operation-IDs generieren { #generate-a-typescript-client-with-custom-operation-ids }
+
+Wenn Sie nun den Client erneut generieren, werden Sie feststellen, dass er über die verbesserten Methodennamen verfügt:
+
+
+
+Wie Sie sehen, haben die Methodennamen jetzt den Tag und dann den Funktionsnamen, aber keine Informationen aus dem URL-Pfad und der HTTP-Operation.
+
+### Die OpenAPI-Spezifikation für den Client-Generator vorab modifizieren { #preprocess-the-openapi-specification-for-the-client-generator }
+
+Der generierte Code enthält immer noch einige **verdoppelte Informationen**.
+
+Wir wissen bereits, dass diese Methode mit den **Items** zusammenhängt, weil dieses Wort in `ItemsService` enthalten ist (vom Tag übernommen), aber wir haben den Tag-Namen dennoch im Methodennamen vorangestellt. 😕
+
+Wir werden das wahrscheinlich weiterhin für OpenAPI allgemein beibehalten wollen, da dadurch sichergestellt wird, dass die Operation-IDs **einzigartig** sind.
+
+Aber für den generierten Client könnten wir die OpenAPI-Operation-IDs direkt vor der Generierung der Clients **modifizieren**, um diese Methodennamen schöner und **sauberer** zu machen.
+
+Wir könnten das OpenAPI-JSON in eine Datei `openapi.json` herunterladen und dann mit einem Skript wie dem folgenden **den präfixierten Tag entfernen**:
+
+{* ../../docs_src/generate_clients/tutorial004_py310.py *}
+
+//// tab | Node.js
+
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
+```
+
+////
+
+Damit würden die Operation-IDs von Dingen wie `items-get_items` in `get_items` umbenannt, sodass der Client-Generator einfachere Methodennamen generieren kann.
+
+### Einen TypeScript-Client mit der vorverarbeiteten OpenAPI generieren { #generate-a-typescript-client-with-the-preprocessed-openapi }
+
+Da das Endergebnis nun in einer `openapi.json`-Datei vorliegt, müssen Sie Ihren Eingabeort aktualisieren:
+
+```sh
+npx @hey-api/openapi-ts -i ./openapi.json -o src/client
+```
+
+Nach der Generierung des neuen Clients haben Sie jetzt **saubere Methodennamen**, mit allen **Autovervollständigungen**, **Inline-Fehlerberichten**, usw.:
+
+
+
+## Vorteile { #benefits }
+
+Wenn Sie die automatisch generierten Clients verwenden, erhalten Sie **Autovervollständigung** für:
+
+* Methoden.
+* Request-Payloads im Body, Query-Parameter, usw.
+* Response-Payloads.
+
+Sie erhalten auch **Inline-Fehlerberichte** für alles.
+
+Und wann immer Sie den Backend-Code aktualisieren und **das Frontend neu generieren**, stehen alle neuen *Pfadoperationen* als Methoden zur Verfügung, die alten werden entfernt und alle anderen Änderungen werden im generierten Code reflektiert. 🤓
+
+Das bedeutet auch, dass, wenn sich etwas ändert, dies automatisch im Client-Code **reflektiert** wird. Und wenn Sie den Client **erstellen**, wird eine Fehlermeldung ausgegeben, wenn die verwendeten Daten **nicht übereinstimmen**.
+
+Sie würden also **viele Fehler sehr früh** im Entwicklungszyklus erkennen, anstatt darauf warten zu müssen, dass die Fehler Ihren Endbenutzern in der Produktion angezeigt werden, und dann zu versuchen, zu debuggen, wo das Problem liegt. ✨
diff --git a/docs/de/docs/advanced/index.md b/docs/de/docs/advanced/index.md
new file mode 100644
index 0000000000000..3886e963a616d
--- /dev/null
+++ b/docs/de/docs/advanced/index.md
@@ -0,0 +1,21 @@
+# Handbuch für fortgeschrittene Benutzer { #advanced-user-guide }
+
+## Zusatzfunktionen { #additional-features }
+
+Das Haupt-[Tutorial – Benutzerhandbuch](../tutorial/index.md) sollte ausreichen, um Ihnen einen Überblick über alle Hauptfunktionen von **FastAPI** zu geben.
+
+In den nächsten Abschnitten sehen Sie weitere Optionen, Konfigurationen und zusätzliche Funktionen.
+
+/// tip | Tipp
+
+Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**.
+
+Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt.
+
+///
+
+## Das Tutorial zuerst lesen { #read-the-tutorial-first }
+
+Sie können immer noch die meisten Funktionen in **FastAPI** mit den Kenntnissen aus dem Haupt-[Tutorial – Benutzerhandbuch](../tutorial/index.md) nutzen.
+
+Und die nächsten Abschnitte setzen voraus, dass Sie es bereits gelesen haben und dass Sie diese Hauptideen kennen.
diff --git a/docs/de/docs/advanced/json-base64-bytes.md b/docs/de/docs/advanced/json-base64-bytes.md
new file mode 100644
index 0000000000000..26c7e70892f4d
--- /dev/null
+++ b/docs/de/docs/advanced/json-base64-bytes.md
@@ -0,0 +1,63 @@
+# JSON mit Bytes als base64 { #json-with-bytes-as-base64 }
+
+Wenn Ihre App JSON-Daten empfangen und senden muss, Sie darin aber Binärdaten einschließen müssen, können Sie diese als base64 kodieren.
+
+## Base64 vs Dateien { #base64-vs-files }
+
+Prüfen Sie zunächst, ob Sie [Request Files](../tutorial/request-files.md) zum Hochladen von Binärdaten und [Benutzerdefinierte Response – FileResponse](./custom-response.md#fileresponse--fileresponse-) zum Senden von Binärdaten verwenden können, anstatt sie in JSON zu kodieren.
+
+JSON kann nur UTF-8-kodierte Strings enthalten, es kann daher keine rohen Bytes enthalten.
+
+Base64 kann Binärdaten in Strings kodieren, dafür werden jedoch mehr Zeichen benötigt als in den ursprünglichen Binärdaten; es ist daher in der Regel weniger effizient als der Umgang mit normalen Dateien.
+
+Verwenden Sie base64 nur, wenn Sie Binärdaten unbedingt in JSON einbetten müssen und dafür keine Dateien verwenden können.
+
+## Pydantic `bytes` { #pydantic-bytes }
+
+Sie können ein Pydantic-Modell mit `bytes`-Feldern deklarieren und dann in der Modellkonfiguration `val_json_bytes` verwenden, um anzugeben, dass zur *Validierung* von eingehenden JSON-Daten base64 genutzt werden soll; im Rahmen dieser Validierung wird der base64-String in Bytes dekodiert.
+
+{* ../../docs_src/json_base64_bytes/tutorial001_py310.py ln[1:9,29:35] hl[9] *}
+
+Wenn Sie die `/docs` aufrufen, zeigt die Dokumentation, dass das Feld `data` base64-kodierte Bytes erwartet:
+
+
+
diff --git a/docs/de/docs/advanced/openapi-webhooks.md b/docs/de/docs/advanced/openapi-webhooks.md
new file mode 100644
index 0000000000000..e6984de74f5d9
--- /dev/null
+++ b/docs/de/docs/advanced/openapi-webhooks.md
@@ -0,0 +1,55 @@
+# OpenAPI Webhooks { #openapi-webhooks }
+
+Es gibt Fälle, in denen Sie Ihren API-**Benutzern** mitteilen möchten, dass Ihre App *deren* App mit einigen Daten aufrufen (einen Request senden) könnte, normalerweise um über ein bestimmtes **Event** zu **benachrichtigen**.
+
+Das bedeutet, dass anstelle des normalen Prozesses, bei dem Ihre Benutzer Requests an Ihre API senden, **Ihre API** (oder Ihre App) **Requests an deren System** (an deren API, deren App) senden könnte.
+
+Das wird normalerweise als **Webhook** bezeichnet.
+
+## Webhooks-Schritte { #webhooks-steps }
+
+Der Prozess besteht normalerweise darin, dass **Sie in Ihrem Code definieren**, welche Nachricht Sie senden möchten, den **Requestbody**.
+
+Sie definieren auch auf irgendeine Weise, in welchen **Momenten** Ihre App diese Requests oder Events senden wird.
+
+Und **Ihre Benutzer** definieren auf irgendeine Weise (zum Beispiel irgendwo in einem Web-Dashboard) die **URL**, an die Ihre App diese Requests senden soll.
+
+Die gesamte **Logik** zur Registrierung der URLs für Webhooks und der Code zum tatsächlichen Senden dieser Requests liegt bei Ihnen. Sie schreiben es so, wie Sie möchten, in **Ihrem eigenen Code**.
+
+## Webhooks mit **FastAPI** und OpenAPI dokumentieren { #documenting-webhooks-with-fastapi-and-openapi }
+
+Mit **FastAPI**, mithilfe von OpenAPI, können Sie die Namen dieser Webhooks, die Arten von HTTP-Operationen, die Ihre App senden kann (z. B. `POST`, `PUT`, usw.) und die **Requestbodys** definieren, die Ihre App senden würde.
+
+Dies kann es Ihren Benutzern viel einfacher machen, **deren APIs zu implementieren**, um Ihre **Webhook**-Requests zu empfangen. Möglicherweise können diese sogar einen Teil ihres eigenen API-Codes automatisch generieren.
+
+/// info | Info
+
+Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.99.0` und höher unterstützt.
+
+///
+
+## Eine App mit Webhooks { #an-app-with-webhooks }
+
+Wenn Sie eine **FastAPI**-Anwendung erstellen, gibt es ein `webhooks`-Attribut, das Sie verwenden können, um *Webhooks* zu definieren, genauso wie Sie *Pfadoperationen* definieren würden, zum Beispiel mit `@app.webhooks.post()`.
+
+{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}
+
+Die von Ihnen definierten Webhooks landen im **OpenAPI**-Schema und der automatischen **Dokumentations-Oberfläche**.
+
+/// info | Info
+
+Das `app.webhooks`-Objekt ist eigentlich nur ein `APIRouter`, derselbe Typ, den Sie verwenden würden, wenn Sie Ihre App mit mehreren Dateien strukturieren.
+
+///
+
+Beachten Sie, dass Sie bei Webhooks tatsächlich keinen *Pfad* (wie `/items/`) deklarieren, der Text, den Sie dort übergeben, ist lediglich eine **Kennzeichnung** des Webhooks (der Name des Events). Zum Beispiel ist in `@app.webhooks.post("new-subscription")` der Webhook-Name `new-subscription`.
+
+Das liegt daran, dass erwartet wird, dass **Ihre Benutzer** den tatsächlichen **URL-Pfad**, an dem sie den Webhook-Request empfangen möchten, auf andere Weise definieren (z. B. über ein Web-Dashboard).
+
+### Die Dokumentation testen { #check-the-docs }
+
+Jetzt können Sie Ihre App starten und auf [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) gehen.
+
+Sie werden sehen, dass Ihre Dokumentation die normalen *Pfadoperationen* und jetzt auch einige **Webhooks** enthält:
+
+
diff --git a/docs/de/docs/advanced/path-operation-advanced-configuration.md b/docs/de/docs/advanced/path-operation-advanced-configuration.md
new file mode 100644
index 0000000000000..e6ff498eb94d8
--- /dev/null
+++ b/docs/de/docs/advanced/path-operation-advanced-configuration.md
@@ -0,0 +1,172 @@
+# Fortgeschrittene Konfiguration der Pfadoperation { #path-operation-advanced-configuration }
+
+## OpenAPI operationId { #openapi-operationid }
+
+/// warning | Achtung
+
+Wenn Sie kein „Experte“ für OpenAPI sind, brauchen Sie dies wahrscheinlich nicht.
+
+///
+
+Mit dem Parameter `operation_id` können Sie die OpenAPI `operationId` festlegen, die in Ihrer *Pfadoperation* verwendet werden soll.
+
+Sie müssten sicherstellen, dass sie für jede Operation eindeutig ist.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
+
+### Verwendung des Namens der *Pfadoperation-Funktion* als operationId { #using-the-path-operation-function-name-as-the-operationid }
+
+Wenn Sie die Funktionsnamen Ihrer API als `operationId`s verwenden möchten, können Sie über alle iterieren und die `operation_id` jeder *Pfadoperation* mit deren `APIRoute.name` überschreiben.
+
+Sie sollten dies tun, nachdem Sie alle Ihre *Pfadoperationen* hinzugefügt haben.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *}
+
+/// tip | Tipp
+
+Wenn Sie `app.openapi()` manuell aufrufen, sollten Sie vorher die `operationId`s aktualisiert haben.
+
+///
+
+/// warning | Achtung
+
+Wenn Sie dies tun, müssen Sie sicherstellen, dass jede Ihrer *Pfadoperation-Funktionen* einen eindeutigen Namen hat.
+
+Auch wenn diese sich in unterschiedlichen Modulen (Python-Dateien) befinden.
+
+///
+
+## Von OpenAPI ausschließen { #exclude-from-openapi }
+
+Um eine *Pfadoperation* aus dem generierten OpenAPI-Schema (und damit aus den automatischen Dokumentationssystemen) auszuschließen, verwenden Sie den Parameter `include_in_schema` und setzen Sie ihn auf `False`:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}
+
+## Fortgeschrittene Beschreibung mittels Docstring { #advanced-description-from-docstring }
+
+Sie können die verwendeten Zeilen aus dem Docstring einer *Pfadoperation-Funktion* einschränken, die für OpenAPI verwendet werden.
+
+Das Hinzufügen eines `\f` (ein maskiertes „Form Feed“-Zeichen) führt dazu, dass **FastAPI** die für OpenAPI verwendete Ausgabe an dieser Stelle abschneidet.
+
+Sie wird nicht in der Dokumentation angezeigt, aber andere Tools (wie z. B. Sphinx) können den Rest verwenden.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}
+
+## Zusätzliche Responses { #additional-responses }
+
+Sie haben wahrscheinlich gesehen, wie man das `response_model` und den `status_code` für eine *Pfadoperation* deklariert.
+
+Das definiert die Metadaten der Haupt-Response einer *Pfadoperation*.
+
+Sie können auch zusätzliche Responses mit deren Modellen, Statuscodes usw. deklarieren.
+
+Es gibt hier in der Dokumentation ein ganzes Kapitel darüber, Sie können es unter [Zusätzliche Responses in OpenAPI](additional-responses.md) lesen.
+
+## OpenAPI-Extra { #openapi-extra }
+
+Wenn Sie in Ihrer Anwendung eine *Pfadoperation* deklarieren, generiert **FastAPI** automatisch die relevanten Metadaten dieser *Pfadoperation*, die in das OpenAPI-Schema aufgenommen werden sollen.
+
+/// note | Technische Details
+
+In der OpenAPI-Spezifikation wird es das [Operationsobjekt](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object) genannt.
+
+///
+
+Es hat alle Informationen zur *Pfadoperation* und wird zur Erstellung der automatischen Dokumentation verwendet.
+
+Es enthält `tags`, `parameters`, `requestBody`, `responses`, usw.
+
+Dieses *Pfadoperation*-spezifische OpenAPI-Schema wird normalerweise automatisch von **FastAPI** generiert, Sie können es aber auch erweitern.
+
+/// tip | Tipp
+
+Dies ist ein Low-Level-Erweiterungspunkt.
+
+Wenn Sie nur zusätzliche Responses deklarieren müssen, können Sie dies bequemer mit [Zusätzliche Responses in OpenAPI](additional-responses.md) tun.
+
+///
+
+Sie können das OpenAPI-Schema für eine *Pfadoperation* erweitern, indem Sie den Parameter `openapi_extra` verwenden.
+
+### OpenAPI-Erweiterungen { #openapi-extensions }
+
+Dieses `openapi_extra` kann beispielsweise hilfreich sein, um [OpenAPI-Erweiterungen](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) zu deklarieren:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py310.py hl[6] *}
+
+Wenn Sie die automatische API-Dokumentation öffnen, wird Ihre Erweiterung am Ende der spezifischen *Pfadoperation* angezeigt.
+
+
+
+Und wenn Sie die resultierende OpenAPI sehen (unter `/openapi.json` in Ihrer API), sehen Sie Ihre Erweiterung auch als Teil der spezifischen *Pfadoperation*:
+
+```JSON hl_lines="22"
+{
+ "openapi": "3.1.0",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0"
+ },
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ }
+ },
+ "x-aperture-labs-portal": "blue"
+ }
+ }
+ }
+}
+```
+
+### Benutzerdefiniertes OpenAPI-*Pfadoperation*-Schema { #custom-openapi-path-operation-schema }
+
+Das Dictionary in `openapi_extra` wird mit dem automatisch generierten OpenAPI-Schema für die *Pfadoperation* zusammengeführt (mittels Deep Merge).
+
+Sie können dem automatisch generierten Schema also zusätzliche Daten hinzufügen.
+
+Sie könnten sich beispielsweise dafür entscheiden, den Request mit Ihrem eigenen Code zu lesen und zu validieren, ohne FastAPIs automatische Funktionen mit Pydantic zu verwenden, aber Sie könnten den Request trotzdem im OpenAPI-Schema definieren wollen.
+
+Das könnte man mit `openapi_extra` machen:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py310.py hl[19:36, 39:40] *}
+
+In diesem Beispiel haben wir kein Pydantic-Modell deklariert. Tatsächlich wird der Requestbody nicht einmal als JSON geparst, sondern direkt als `bytes` gelesen und die Funktion `magic_data_reader()` wäre dafür verantwortlich, ihn in irgendeiner Weise zu parsen.
+
+Dennoch können wir das zu erwartende Schema für den Requestbody deklarieren.
+
+### Benutzerdefinierter OpenAPI-Content-Type { #custom-openapi-content-type }
+
+Mit demselben Trick könnten Sie ein Pydantic-Modell verwenden, um das JSON-Schema zu definieren, das dann im benutzerdefinierten Abschnitt des OpenAPI-Schemas für die *Pfadoperation* enthalten ist.
+
+Und Sie könnten dies auch tun, wenn der Datentyp im Request nicht JSON ist.
+
+In der folgenden Anwendung verwenden wir beispielsweise weder FastAPIs integrierte Funktionalität zum Extrahieren des JSON-Schemas aus Pydantic-Modellen noch die automatische Validierung für JSON. Tatsächlich deklarieren wir den Request-Content-Type als YAML und nicht als JSON:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[15:20, 22] *}
+
+Obwohl wir nicht die standardmäßig integrierte Funktionalität verwenden, verwenden wir dennoch ein Pydantic-Modell, um das JSON-Schema für die Daten, die wir in YAML empfangen möchten, manuell zu generieren.
+
+Dann verwenden wir den Request direkt und extrahieren den Body als `bytes`. Das bedeutet, dass FastAPI nicht einmal versucht, die Request-Payload als JSON zu parsen.
+
+Und dann parsen wir in unserem Code diesen YAML-Inhalt direkt und verwenden dann wieder dasselbe Pydantic-Modell, um den YAML-Inhalt zu validieren:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *}
+
+/// tip | Tipp
+
+Hier verwenden wir dasselbe Pydantic-Modell wieder.
+
+Aber genauso hätten wir es auch auf andere Weise validieren können.
+
+///
diff --git a/docs/de/docs/advanced/response-change-status-code.md b/docs/de/docs/advanced/response-change-status-code.md
new file mode 100644
index 0000000000000..a0d90fe80de1b
--- /dev/null
+++ b/docs/de/docs/advanced/response-change-status-code.md
@@ -0,0 +1,31 @@
+# Response – Statuscode ändern { #response-change-status-code }
+
+Sie haben wahrscheinlich schon vorher gelesen, dass Sie einen Default-[Response-Statuscode](../tutorial/response-status-code.md) festlegen können.
+
+In manchen Fällen müssen Sie jedoch einen anderen als den Default-Statuscode zurückgeben.
+
+## Anwendungsfall { #use-case }
+
+Stellen Sie sich zum Beispiel vor, Sie möchten standardmäßig den HTTP-Statuscode „OK“ `200` zurückgeben.
+
+Wenn die Daten jedoch nicht vorhanden sind, möchten Sie diese erstellen und den HTTP-Statuscode „CREATED“ `201` zurückgeben.
+
+Sie möchten aber dennoch in der Lage sein, die von Ihnen zurückgegebenen Daten mit einem `response_model` zu filtern und zu konvertieren.
+
+In diesen Fällen können Sie einen `Response`-Parameter verwenden.
+
+## Einen `Response`-Parameter verwenden { #use-a-response-parameter }
+
+Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* deklarieren (wie Sie es auch für Cookies und Header tun können).
+
+Anschließend können Sie den `status_code` in diesem *vorübergehenden* Response-Objekt festlegen.
+
+{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}
+
+Und dann können Sie jedes benötigte Objekt zurückgeben, wie Sie es normalerweise tun würden (ein `dict`, ein Datenbankmodell usw.).
+
+Und wenn Sie ein `response_model` deklariert haben, wird es weiterhin zum Filtern und Konvertieren des von Ihnen zurückgegebenen Objekts verwendet.
+
+**FastAPI** verwendet diese *vorübergehende* Response, um den Statuscode (auch Cookies und Header) zu extrahieren und fügt diese in die endgültige Response ein, die den von Ihnen zurückgegebenen Wert enthält, gefiltert nach einem beliebigen `response_model`.
+
+Sie können den Parameter `Response` auch in Abhängigkeiten deklarieren und den Statuscode darin festlegen. Bedenken Sie jedoch, dass der zuletzt gesetzte gewinnt.
diff --git a/docs/de/docs/advanced/response-cookies.md b/docs/de/docs/advanced/response-cookies.md
new file mode 100644
index 0000000000000..672bbbe78e65e
--- /dev/null
+++ b/docs/de/docs/advanced/response-cookies.md
@@ -0,0 +1,51 @@
+# Response-Cookies { #response-cookies }
+
+## Einen `Response`-Parameter verwenden { #use-a-response-parameter }
+
+Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* deklarieren.
+
+Und dann können Sie Cookies in diesem *vorübergehenden* Response-Objekt setzen.
+
+{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}
+
+Anschließend können Sie wie gewohnt jedes gewünschte Objekt zurückgeben (ein `dict`, ein Datenbankmodell, usw.).
+
+Und wenn Sie ein `response_model` deklariert haben, wird es weiterhin zum Filtern und Konvertieren des von Ihnen zurückgegebenen Objekts verwendet.
+
+**FastAPI** verwendet diese *vorübergehende* Response, um die Cookies (auch Header und Statuscode) zu extrahieren und fügt diese in die endgültige Response ein, die den von Ihnen zurückgegebenen Wert enthält, gefiltert nach einem beliebigen `response_model`.
+
+Sie können den `Response`-Parameter auch in Abhängigkeiten deklarieren und darin Cookies (und Header) setzen.
+
+## Eine `Response` direkt zurückgeben { #return-a-response-directly }
+
+Sie können Cookies auch erstellen, wenn Sie eine `Response` direkt in Ihrem Code zurückgeben.
+
+Dazu können Sie eine Response erstellen, wie unter [Eine Response direkt zurückgeben](response-directly.md) beschrieben.
+
+Setzen Sie dann Cookies darin und geben Sie sie dann zurück:
+
+{* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *}
+
+/// tip | Tipp
+
+Beachten Sie, dass, wenn Sie eine Response direkt zurückgeben, anstatt den `Response`-Parameter zu verwenden, FastAPI diese direkt zurückgibt.
+
+Sie müssen also sicherstellen, dass Ihre Daten vom richtigen Typ sind. Z. B. sollten diese mit JSON kompatibel sein, wenn Sie eine `JSONResponse` zurückgeben.
+
+Und auch, dass Sie keine Daten senden, die durch ein `response_model` hätten gefiltert werden sollen.
+
+///
+
+### Mehr Informationen { #more-info }
+
+/// note | Technische Details
+
+Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden.
+
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+
+Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit.
+
+///
+
+Um alle verfügbaren Parameter und Optionen anzuzeigen, sehen Sie sich deren [Dokumentation in Starlette](https://www.starlette.dev/responses/#set-cookie) an.
diff --git a/docs/de/docs/advanced/response-directly.md b/docs/de/docs/advanced/response-directly.md
new file mode 100644
index 0000000000000..4235e8db0b741
--- /dev/null
+++ b/docs/de/docs/advanced/response-directly.md
@@ -0,0 +1,83 @@
+# Eine Response direkt zurückgeben { #return-a-response-directly }
+
+Wenn Sie eine **FastAPI** *Pfadoperation* erstellen, können Sie normalerweise beliebige Daten davon zurückgeben: ein `dict`, eine `list`, ein Pydantic-Modell, ein Datenbankmodell, usw.
+
+Wenn Sie ein [Responsemodell](../tutorial/response-model.md) deklarieren, wird FastAPI es verwenden, um die Daten mithilfe von Pydantic nach JSON zu serialisieren.
+
+Wenn Sie kein Responsemodell deklarieren, verwendet FastAPI den `jsonable_encoder`, wie in [JSON-kompatibler Encoder](../tutorial/encoder.md) erläutert, und packt die Daten in eine `JSONResponse`.
+
+Sie könnten auch direkt eine `JSONResponse` erstellen und zurückgeben.
+
+/// tip | Tipp
+
+Normalerweise erzielen Sie eine deutlich bessere Leistung, wenn Sie ein [Responsemodell](../tutorial/response-model.md) verwenden, als wenn Sie direkt eine `JSONResponse` zurückgeben, da die Serialisierung der Daten dabei mit Pydantic in Rust erfolgt.
+
+///
+
+## Eine `Response` zurückgeben { #return-a-response }
+
+Tatsächlich können Sie jede `Response` oder jede Unterklasse davon zurückgeben.
+
+/// info | Info
+
+`JSONResponse` selbst ist eine Unterklasse von `Response`.
+
+///
+
+Und wenn Sie eine `Response` zurückgeben, wird **FastAPI** diese direkt weiterleiten.
+
+Es wird keine Datenkonvertierung mit Pydantic-Modellen durchführen, es wird den Inhalt nicht in irgendeinen Typ konvertieren, usw.
+
+Dadurch haben Sie viel Flexibilität. Sie können jeden Datentyp zurückgeben, jede Datendeklaration oder -validierung überschreiben, usw.
+
+Das bringt Ihnen aber auch viel Verantwortung. Sie müssen sicherstellen, dass die von Ihnen zurückgegebenen Daten korrekt sind, das richtige Format haben, serialisierbar sind, usw.
+
+## Verwendung des `jsonable_encoder` in einer `Response` { #using-the-jsonable-encoder-in-a-response }
+
+Da **FastAPI** keine Änderungen an einer von Ihnen zurückgegebenen `Response` vornimmt, müssen Sie sicherstellen, dass deren Inhalt dafür bereit ist.
+
+Sie können beispielsweise kein Pydantic-Modell in eine `JSONResponse` einfügen, ohne es zuvor in ein `dict` zu konvertieren, bei dem alle Datentypen (wie `datetime`, `UUID`, usw.) in JSON-kompatible Typen konvertiert wurden.
+
+In diesen Fällen können Sie den `jsonable_encoder` verwenden, um Ihre Daten zu konvertieren, bevor Sie sie an eine Response übergeben:
+
+{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}
+
+/// note | Technische Details
+
+Sie könnten auch `from starlette.responses import JSONResponse` verwenden.
+
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+
+///
+
+## Eine benutzerdefinierte `Response` zurückgeben { #returning-a-custom-response }
+
+Das obige Beispiel zeigt alle Teile, die Sie benötigen, ist aber noch nicht sehr nützlich, da Sie das `item` einfach direkt hätten zurückgeben können, und **FastAPI** würde es für Sie in eine `JSONResponse` einfügen, es in ein `dict` konvertieren, usw. All das standardmäßig.
+
+Sehen wir uns nun an, wie Sie damit eine benutzerdefinierte Response zurückgeben können.
+
+Nehmen wir an, Sie möchten eine [XML](https://en.wikipedia.org/wiki/XML)-Response zurückgeben.
+
+Sie könnten Ihren XML-Inhalt als String in eine `Response` einfügen und sie zurückgeben:
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+## Funktionsweise eines Responsemodells { #how-a-response-model-works }
+
+Wenn Sie in einer Pfadoperation ein [Responsemodell - Rückgabetyp](../tutorial/response-model.md) deklarieren, wird **FastAPI** es verwenden, um die Daten mithilfe von Pydantic nach JSON zu serialisieren.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+Da dies auf der Rust-Seite geschieht, ist die Leistung deutlich besser, als wenn es mit normalem Python und der Klasse `JSONResponse` erfolgen würde.
+
+Wenn Sie ein `response_model` oder einen Rückgabetyp verwenden, nutzt FastAPI weder den `jsonable_encoder` (was langsamer wäre) zur Konvertierung der Daten noch die Klasse `JSONResponse`.
+
+Stattdessen nimmt es die von Pydantic mithilfe des Responsemodells (oder Rückgabetyps) generierten JSON-Bytes und gibt direkt eine `Response` mit dem richtigen Mediatyp für JSON (`application/json`) zurück.
+
+## Anmerkungen { #notes }
+
+Wenn Sie eine `Response` direkt zurücksenden, werden deren Daten weder validiert, konvertiert (serialisiert), noch automatisch dokumentiert.
+
+Sie können sie aber trotzdem wie unter [Zusätzliche Responses in OpenAPI](additional-responses.md) beschrieben dokumentieren.
+
+In späteren Abschnitten erfahren Sie, wie Sie diese benutzerdefinierten `Response`s verwenden/deklarieren und gleichzeitig über automatische Datenkonvertierung, Dokumentation, usw. verfügen.
diff --git a/docs/de/docs/advanced/response-headers.md b/docs/de/docs/advanced/response-headers.md
new file mode 100644
index 0000000000000..bcec04be8b0fe
--- /dev/null
+++ b/docs/de/docs/advanced/response-headers.md
@@ -0,0 +1,41 @@
+# Response-Header { #response-headers }
+
+## Einen `Response`-Parameter verwenden { #use-a-response-parameter }
+
+Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* deklarieren (wie Sie es auch für Cookies tun können).
+
+Und dann können Sie Header in diesem *vorübergehenden* Response-Objekt festlegen.
+
+{* ../../docs_src/response_headers/tutorial002_py310.py hl[1, 7:8] *}
+
+Anschließend können Sie wie gewohnt jedes gewünschte Objekt zurückgeben (ein `dict`, ein Datenbankmodell, usw.).
+
+Und wenn Sie ein `response_model` deklariert haben, wird es weiterhin zum Filtern und Konvertieren des von Ihnen zurückgegebenen Objekts verwendet.
+
+**FastAPI** verwendet diese *vorübergehende* Response, um die Header (auch Cookies und Statuscode) zu extrahieren und fügt diese in die endgültige Response ein, die den von Ihnen zurückgegebenen Wert enthält, gefiltert nach einem beliebigen `response_model`.
+
+Sie können den Parameter `Response` auch in Abhängigkeiten deklarieren und darin Header (und Cookies) festlegen.
+
+## Eine `Response` direkt zurückgeben { #return-a-response-directly }
+
+Sie können auch Header hinzufügen, wenn Sie eine `Response` direkt zurückgeben.
+
+Erstellen Sie eine Response wie in [Eine Response direkt zurückgeben](response-directly.md) beschrieben und übergeben Sie die Header als zusätzlichen Parameter:
+
+{* ../../docs_src/response_headers/tutorial001_py310.py hl[10:12] *}
+
+/// note | Technische Details
+
+Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden.
+
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+
+Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit.
+
+///
+
+## Benutzerdefinierte Header { #custom-headers }
+
+Beachten Sie, dass benutzerdefinierte proprietäre Header [mit dem Präfix `X-`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) hinzugefügt werden können.
+
+Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser sehen können soll, müssen Sie diese zu Ihrer CORS-Konfiguration hinzufügen (weitere Informationen finden Sie unter [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md)), unter Verwendung des Parameters `expose_headers`, dokumentiert in [Starlettes CORS-Dokumentation](https://www.starlette.dev/middleware/#corsmiddleware).
diff --git a/docs/de/docs/advanced/security/http-basic-auth.md b/docs/de/docs/advanced/security/http-basic-auth.md
new file mode 100644
index 0000000000000..2b4baba309ea8
--- /dev/null
+++ b/docs/de/docs/advanced/security/http-basic-auth.md
@@ -0,0 +1,107 @@
+# HTTP Basic Auth { #http-basic-auth }
+
+Für die einfachsten Fälle können Sie HTTP Basic Auth verwenden.
+
+Bei HTTP Basic Auth erwartet die Anwendung einen Header, der einen Benutzernamen und ein Passwort enthält.
+
+Wenn sie diesen nicht empfängt, gibt sie den HTTP-Error 401 „Unauthorized“ zurück.
+
+Und gibt einen Header `WWW-Authenticate` mit dem Wert `Basic` und einem optionalen `realm`-Parameter zurück.
+
+Dadurch wird der Browser angewiesen, die integrierte Eingabeaufforderung für einen Benutzernamen und ein Passwort anzuzeigen.
+
+Wenn Sie dann den Benutzernamen und das Passwort eingeben, sendet der Browser diese automatisch im Header.
+
+## Einfaches HTTP Basic Auth { #simple-http-basic-auth }
+
+* Importieren Sie `HTTPBasic` und `HTTPBasicCredentials`.
+* Erstellen Sie mit `HTTPBasic` ein „`security`-Schema“.
+* Verwenden Sie dieses `security` mit einer Abhängigkeit in Ihrer *Pfadoperation*.
+* Diese gibt ein Objekt vom Typ `HTTPBasicCredentials` zurück:
+ * Es enthält den gesendeten `username` und das gesendete `password`.
+
+{* ../../docs_src/security/tutorial006_an_py310.py hl[4,8,12] *}
+
+Wenn Sie versuchen, die URL zum ersten Mal zu öffnen (oder in der Dokumentation auf den Button „Execute“ zu klicken), wird der Browser Sie nach Ihrem Benutzernamen und Passwort fragen:
+
+
+
+## Den Benutzernamen überprüfen { #check-the-username }
+
+Hier ist ein vollständigeres Beispiel.
+
+Verwenden Sie eine Abhängigkeit, um zu überprüfen, ob Benutzername und Passwort korrekt sind.
+
+Verwenden Sie dazu das Python-Standardmodul [`secrets`](https://docs.python.org/3/library/secrets.html), um den Benutzernamen und das Passwort zu überprüfen.
+
+`secrets.compare_digest()` benötigt `bytes` oder einen `str`, welcher nur ASCII-Zeichen (solche der englischen Sprache) enthalten darf, das bedeutet, dass es nicht mit Zeichen wie `á`, wie in `Sebastián`, funktionieren würde.
+
+Um dies zu lösen, konvertieren wir zunächst den `username` und das `password` in UTF-8-codierte `bytes`.
+
+Dann können wir `secrets.compare_digest()` verwenden, um sicherzustellen, dass `credentials.username` `"stanleyjobson"` und `credentials.password` `"swordfish"` ist.
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[1,12:24] *}
+
+Dies wäre das gleiche wie:
+
+```Python
+if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
+ # Einen Error zurückgeben
+ ...
+```
+
+Aber durch die Verwendung von `secrets.compare_digest()` ist dieser Code sicher vor einer Art von Angriffen, die „Timing-Angriffe“ genannt werden.
+
+### Timing-Angriffe { #timing-attacks }
+
+Aber was ist ein „Timing-Angriff“?
+
+Stellen wir uns vor, dass einige Angreifer versuchen, den Benutzernamen und das Passwort zu erraten.
+
+Und sie senden einen Request mit dem Benutzernamen `johndoe` und dem Passwort `love123`.
+
+Dann würde der Python-Code in Ihrer Anwendung etwa so aussehen:
+
+```Python
+if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Aber genau in dem Moment, in dem Python das erste `j` in `johndoe` mit dem ersten `s` in `stanleyjobson` vergleicht, gibt es `False` zurück, da es bereits weiß, dass diese beiden Strings nicht identisch sind, und denkt, „Es besteht keine Notwendigkeit, weitere Berechnungen mit dem Vergleich der restlichen Buchstaben zu verschwenden“. Und Ihre Anwendung wird zurückgeben „Incorrect username or password“.
+
+Doch dann versuchen es die Angreifer mit dem Benutzernamen `stanleyjobsox` und dem Passwort `love123`.
+
+Und Ihr Anwendungscode macht etwa Folgendes:
+
+```Python
+if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Python muss das gesamte `stanleyjobso` in `stanleyjobsox` und `stanleyjobson` vergleichen, bevor es erkennt, dass beide Zeichenfolgen nicht gleich sind. Daher wird es einige zusätzliche Mikrosekunden dauern, bis die Response „Incorrect username or password“ erfolgt.
+
+#### Die Zeit zum Antworten hilft den Angreifern { #the-time-to-answer-helps-the-attackers }
+
+Wenn die Angreifer zu diesem Zeitpunkt feststellen, dass der Server einige Mikrosekunden länger braucht, um die Response „Incorrect username or password“ zu senden, wissen sie, dass sie _etwas_ richtig gemacht haben, einige der Anfangsbuchstaben waren richtig.
+
+Und dann können sie es noch einmal versuchen, wohl wissend, dass es wahrscheinlich eher etwas mit `stanleyjobsox` als mit `johndoe` zu tun hat.
+
+#### Ein „professioneller“ Angriff { #a-professional-attack }
+
+Natürlich würden die Angreifer das alles nicht von Hand versuchen, sondern ein Programm dafür schreiben, möglicherweise mit Tausenden oder Millionen Tests pro Sekunde. Und würden jeweils nur einen zusätzlichen richtigen Buchstaben erhalten.
+
+Aber so hätten die Angreifer in wenigen Minuten oder Stunden mit der „Hilfe“ unserer Anwendung den richtigen Benutzernamen und das richtige Passwort erraten, indem sie die Zeitspanne zur Hilfe nehmen, die diese zur Beantwortung benötigt.
+
+#### Das Problem beheben mittels `secrets.compare_digest()` { #fix-it-with-secrets-compare-digest }
+
+Aber in unserem Code verwenden wir tatsächlich `secrets.compare_digest()`.
+
+Damit wird, kurz gesagt, der Vergleich von `stanleyjobsox` mit `stanleyjobson` genauso lange dauern wie der Vergleich von `johndoe` mit `stanleyjobson`. Und das Gleiche gilt für das Passwort.
+
+So ist Ihr Anwendungscode, dank der Verwendung von `secrets.compare_digest()`, vor dieser ganzen Klasse von Sicherheitsangriffen geschützt.
+
+### Den Error zurückgeben { #return-the-error }
+
+Nachdem Sie festgestellt haben, dass die Anmeldeinformationen falsch sind, geben Sie eine `HTTPException` mit dem Statuscode 401 zurück (derselbe, der auch zurückgegeben wird, wenn keine Anmeldeinformationen angegeben werden) und fügen den Header `WWW-Authenticate` hinzu, damit der Browser die Anmeldeaufforderung erneut anzeigt:
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[26:30] *}
diff --git a/docs/de/docs/advanced/security/index.md b/docs/de/docs/advanced/security/index.md
new file mode 100644
index 0000000000000..9884f2c1b76a8
--- /dev/null
+++ b/docs/de/docs/advanced/security/index.md
@@ -0,0 +1,19 @@
+# Fortgeschrittene Sicherheit { #advanced-security }
+
+## Zusatzfunktionen { #additional-features }
+
+Neben den in [Tutorial – Benutzerhandbuch: Sicherheit](../../tutorial/security/index.md) behandelten Funktionen gibt es noch einige zusätzliche Funktionen zur Handhabung der Sicherheit.
+
+/// tip | Tipp
+
+Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**.
+
+Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt.
+
+///
+
+## Das Tutorial zuerst lesen { #read-the-tutorial-first }
+
+Die nächsten Abschnitte setzen voraus, dass Sie das Haupt-[Tutorial – Benutzerhandbuch: Sicherheit](../../tutorial/security/index.md) bereits gelesen haben.
+
+Sie basieren alle auf den gleichen Konzepten, ermöglichen jedoch einige zusätzliche Funktionalitäten.
diff --git a/docs/de/docs/advanced/security/oauth2-scopes.md b/docs/de/docs/advanced/security/oauth2-scopes.md
new file mode 100644
index 0000000000000..a903fbeb96283
--- /dev/null
+++ b/docs/de/docs/advanced/security/oauth2-scopes.md
@@ -0,0 +1,274 @@
+# OAuth2-Scopes { #oauth2-scopes }
+
+Sie können OAuth2-Scopes direkt in **FastAPI** verwenden, sie sind nahtlos integriert.
+
+Das ermöglicht es Ihnen, ein feingranuliertes Berechtigungssystem nach dem OAuth2-Standard in Ihre OpenAPI-Anwendung (und deren API-Dokumentation) zu integrieren.
+
+OAuth2 mit Scopes ist der Mechanismus, der von vielen großen Authentifizierungsanbietern wie Facebook, Google, GitHub, Microsoft, X (Twitter) usw. verwendet wird. Sie verwenden ihn, um Benutzern und Anwendungen spezifische Berechtigungen zu erteilen.
+
+Jedes Mal, wenn Sie sich mit Facebook, Google, GitHub, Microsoft oder X (Twitter) anmelden („log in with“), verwendet die entsprechende Anwendung OAuth2 mit Scopes.
+
+In diesem Abschnitt erfahren Sie, wie Sie Authentifizierung und Autorisierung mit demselben OAuth2, mit Scopes in Ihrer **FastAPI**-Anwendung verwalten.
+
+/// warning | Achtung
+
+Dies ist ein mehr oder weniger fortgeschrittener Abschnitt. Wenn Sie gerade erst anfangen, können Sie ihn überspringen.
+
+Sie benötigen nicht unbedingt OAuth2-Scopes, und Sie können die Authentifizierung und Autorisierung handhaben wie Sie möchten.
+
+Aber OAuth2 mit Scopes kann bequem in Ihre API (mit OpenAPI) und deren API-Dokumentation integriert werden.
+
+Dennoch, verwenden Sie solche Scopes oder andere Sicherheits-/Autorisierungsanforderungen in Ihrem Code so wie Sie es möchten.
+
+In vielen Fällen kann OAuth2 mit Scopes ein Overkill sein.
+
+Aber wenn Sie wissen, dass Sie es brauchen oder neugierig sind, lesen Sie weiter.
+
+///
+
+## OAuth2-Scopes und OpenAPI { #oauth2-scopes-and-openapi }
+
+Die OAuth2-Spezifikation definiert „Scopes“ als eine Liste von durch Leerzeichen getrennten Strings.
+
+Der Inhalt jedes dieser Strings kann ein beliebiges Format haben, sollte jedoch keine Leerzeichen enthalten.
+
+Diese Scopes stellen „Berechtigungen“ dar.
+
+In OpenAPI (z. B. der API-Dokumentation) können Sie „Sicherheitsschemas“ definieren.
+
+Wenn eines dieser Sicherheitsschemas OAuth2 verwendet, können Sie auch Scopes deklarieren und verwenden.
+
+Jeder „Scope“ ist nur ein String (ohne Leerzeichen).
+
+Er wird normalerweise verwendet, um bestimmte Sicherheitsberechtigungen zu deklarieren, zum Beispiel:
+
+* `users:read` oder `users:write` sind gängige Beispiele.
+* `instagram_basic` wird von Facebook / Instagram verwendet.
+* `https://www.googleapis.com/auth/drive` wird von Google verwendet.
+
+/// info | Info
+
+In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert.
+
+Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist.
+
+Diese Details sind implementierungsspezifisch.
+
+Für OAuth2 sind es einfach nur Strings.
+
+///
+
+## Gesamtübersicht { #global-view }
+
+Sehen wir uns zunächst kurz die Teile an, die sich gegenüber den Beispielen im Haupt-**Tutorial – Benutzerhandbuch** für [OAuth2 mit Password (und Hashing), Bearer mit JWT-Tokens](../../tutorial/security/oauth2-jwt.md) ändern. Diesmal verwenden wir OAuth2-Scopes:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}
+
+Sehen wir uns diese Änderungen nun Schritt für Schritt an.
+
+## OAuth2-Sicherheitsschema { #oauth2-security-scheme }
+
+Die erste Änderung ist, dass wir jetzt das OAuth2-Sicherheitsschema mit zwei verfügbaren Scopes deklarieren: `me` und `items`.
+
+Der `scopes`-Parameter erhält ein `dict` mit jedem Scope als Schlüssel und dessen Beschreibung als Wert:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *}
+
+Da wir diese Scopes jetzt deklarieren, werden sie in der API-Dokumentation angezeigt, wenn Sie sich einloggen/autorisieren.
+
+Und Sie können auswählen, auf welche Scopes Sie Zugriff haben möchten: `me` und `items`.
+
+Das ist derselbe Mechanismus, der verwendet wird, wenn Sie beim Anmelden mit Facebook, Google, GitHub, usw. Berechtigungen erteilen:
+
+
+
+## JWT-Token mit Scopes { #jwt-token-with-scopes }
+
+Ändern Sie nun die Token-*Pfadoperation*, um die angeforderten Scopes zurückzugeben.
+
+Wir verwenden immer noch dasselbe `OAuth2PasswordRequestForm`. Es enthält eine Eigenschaft `scopes` mit einer `list`e von `str`s für jeden Scope, den es im Request erhalten hat.
+
+Und wir geben die Scopes als Teil des JWT-Tokens zurück.
+
+/// danger | Gefahr
+
+Der Einfachheit halber fügen wir hier die empfangenen Scopes direkt zum Token hinzu.
+
+Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwendung nur die Scopes hinzufügen, die der Benutzer tatsächlich haben kann, oder die Sie vordefiniert haben.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}
+
+## Scopes in *Pfadoperationen* und Abhängigkeiten deklarieren { #declare-scopes-in-path-operations-and-dependencies }
+
+Jetzt deklarieren wir, dass die *Pfadoperation* für `/users/me/items/` den Scope `items` erfordert.
+
+Dazu importieren und verwenden wir `Security` von `fastapi`.
+
+Sie können `Security` verwenden, um Abhängigkeiten zu deklarieren (genau wie `Depends`), aber `Security` erhält auch einen Parameter `scopes` mit einer Liste von Scopes (Strings).
+
+In diesem Fall übergeben wir eine Abhängigkeitsfunktion `get_current_active_user` an `Security` (genauso wie wir es mit `Depends` tun würden).
+
+Wir übergeben aber auch eine `list`e von Scopes, in diesem Fall mit nur einem Scope: `items` (es könnten mehrere sein).
+
+Und die Abhängigkeitsfunktion `get_current_active_user` kann auch Unterabhängigkeiten deklarieren, nicht nur mit `Depends`, sondern auch mit `Security`. Ihre eigene Unterabhängigkeitsfunktion (`get_current_user`) und weitere Scope-Anforderungen deklarierend.
+
+In diesem Fall erfordert sie den Scope `me` (sie könnte mehr als einen Scope erfordern).
+
+/// note | Hinweis
+
+Sie müssen nicht unbedingt an verschiedenen Stellen verschiedene Scopes hinzufügen.
+
+Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen deklarierte Scopes verarbeitet.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}
+
+/// info | Technische Details
+
+`Security` ist tatsächlich eine Unterklasse von `Depends` und hat nur noch einen zusätzlichen Parameter, den wir später kennenlernen werden.
+
+Durch die Verwendung von `Security` anstelle von `Depends` weiß **FastAPI** jedoch, dass es Sicherheits-Scopes deklarieren, intern verwenden und die API mit OpenAPI dokumentieren kann.
+
+Wenn Sie jedoch `Query`, `Path`, `Depends`, `Security` und andere von `fastapi` importieren, handelt es sich tatsächlich um Funktionen, die spezielle Klassen zurückgeben.
+
+///
+
+## `SecurityScopes` verwenden { #use-securityscopes }
+
+Aktualisieren Sie nun die Abhängigkeit `get_current_user`.
+
+Das ist diejenige, die von den oben genannten Abhängigkeiten verwendet wird.
+
+Hier verwenden wir dasselbe OAuth2-Schema, das wir zuvor erstellt haben, und deklarieren es als Abhängigkeit: `oauth2_scheme`.
+
+Da diese Abhängigkeitsfunktion selbst keine Scope-Anforderungen hat, können wir `Depends` mit `oauth2_scheme` verwenden. Wir müssen `Security` nicht verwenden, wenn wir keine Sicherheits-Scopes angeben müssen.
+
+Wir deklarieren auch einen speziellen Parameter vom Typ `SecurityScopes`, der aus `fastapi.security` importiert wird.
+
+Diese `SecurityScopes`-Klasse ähnelt `Request` (`Request` wurde verwendet, um das Request-Objekt direkt zu erhalten).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}
+
+## Die `scopes` verwenden { #use-the-scopes }
+
+Der Parameter `security_scopes` wird vom Typ `SecurityScopes` sein.
+
+Dieses verfügt über ein Attribut `scopes` mit einer Liste, die alle von ihm selbst benötigten Scopes enthält und ferner alle Abhängigkeiten, die dieses als Unterabhängigkeit verwenden. Sprich, alle „Dependanten“ ... das mag verwirrend klingen, wird aber später noch einmal erklärt.
+
+Das `security_scopes`-Objekt (der Klasse `SecurityScopes`) stellt außerdem ein `scope_str`-Attribut mit einem einzelnen String bereit, der die durch Leerzeichen getrennten Scopes enthält (den werden wir verwenden).
+
+Wir erstellen eine `HTTPException`, die wir später an mehreren Stellen wiederverwenden (`raise`n) können.
+
+In diese Exception fügen wir (falls vorhanden) die erforderlichen Scopes als durch Leerzeichen getrennten String ein (unter Verwendung von `scope_str`). Wir fügen diesen String mit den Scopes in den Header `WWW-Authenticate` ein (das ist Teil der Spezifikation).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}
+
+## Den `username` und das Format der Daten überprüfen { #verify-the-username-and-data-shape }
+
+Wir verifizieren, dass wir einen `username` erhalten, und extrahieren die Scopes.
+
+Und dann validieren wir diese Daten mit dem Pydantic-Modell (wobei wir die `ValidationError`-Exception abfangen), und wenn wir beim Lesen des JWT-Tokens oder beim Validieren der Daten mit Pydantic einen Fehler erhalten, lösen wir die zuvor erstellte `HTTPException` aus.
+
+Dazu aktualisieren wir das Pydantic-Modell `TokenData` mit einem neuen Attribut `scopes`.
+
+Durch die Validierung der Daten mit Pydantic können wir sicherstellen, dass wir beispielsweise präzise eine `list`e von `str`s mit den Scopes und einen `str` mit dem `username` haben.
+
+Anstelle beispielsweise eines `dict`s oder etwas anderem, was später in der Anwendung zu Fehlern führen könnte und darum ein Sicherheitsrisiko darstellt.
+
+Wir verifizieren auch, dass wir einen Benutzer mit diesem Benutzernamen haben, und wenn nicht, lösen wir dieselbe Exception aus, die wir zuvor erstellt haben.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}
+
+## Die `scopes` verifizieren { #verify-the-scopes }
+
+Wir überprüfen nun, ob das empfangene Token alle Scopes enthält, die von dieser Abhängigkeit und deren Verwendern (einschließlich *Pfadoperationen*) gefordert werden. Andernfalls lösen wir eine `HTTPException` aus.
+
+Hierzu verwenden wir `security_scopes.scopes`, das eine `list`e mit allen diesen Scopes als `str` enthält.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}
+
+## Abhängigkeitsbaum und Scopes { #dependency-tree-and-scopes }
+
+Sehen wir uns diesen Abhängigkeitsbaum und die Scopes noch einmal an.
+
+Da die Abhängigkeit `get_current_active_user` von `get_current_user` abhängt, wird der bei `get_current_active_user` deklarierte Scope `"me"` in die Liste der erforderlichen Scopes in `security_scopes.scopes` aufgenommen, das an `get_current_user` übergeben wird.
+
+Die *Pfadoperation* selbst deklariert auch einen Scope, `"items"`, sodass dieser auch in der Liste der `security_scopes.scopes` enthalten ist, die an `get_current_user` übergeben wird.
+
+So sieht die Hierarchie der Abhängigkeiten und Scopes aus:
+
+* Die *Pfadoperation* `read_own_items` hat:
+ * Erforderliche Scopes `["items"]` mit der Abhängigkeit:
+ * `get_current_active_user`:
+ * Die Abhängigkeitsfunktion `get_current_active_user` hat:
+ * Erforderliche Scopes `["me"]` mit der Abhängigkeit:
+ * `get_current_user`:
+ * Die Abhängigkeitsfunktion `get_current_user` hat:
+ * Selbst keine erforderlichen Scopes.
+ * Eine Abhängigkeit, die `oauth2_scheme` verwendet.
+ * Einen `security_scopes`-Parameter vom Typ `SecurityScopes`:
+ * Dieser `security_scopes`-Parameter hat ein Attribut `scopes` mit einer `list`e, die alle oben deklarierten Scopes enthält, sprich:
+ * `security_scopes.scopes` enthält `["me", "items"]` für die *Pfadoperation* `read_own_items`.
+ * `security_scopes.scopes` enthält `["me"]` für die *Pfadoperation* `read_users_me`, da das in der Abhängigkeit `get_current_active_user` deklariert ist.
+ * `security_scopes.scopes` wird `[]` (nichts) für die *Pfadoperation* `read_system_status` enthalten, da diese keine `Security` mit `scopes` deklariert hat, und deren Abhängigkeit `get_current_user` ebenfalls keinerlei `scopes` deklariert.
+
+/// tip | Tipp
+
+Das Wichtige und „Magische“ hier ist, dass `get_current_user` für jede *Pfadoperation* eine andere Liste von `scopes` hat, die überprüft werden.
+
+Alles hängt von den „Scopes“ ab, die in jeder *Pfadoperation* und jeder Abhängigkeit im Abhängigkeitsbaum für diese bestimmte *Pfadoperation* deklariert wurden.
+
+///
+
+## Weitere Details zu `SecurityScopes` { #more-details-about-securityscopes }
+
+Sie können `SecurityScopes` an jeder Stelle und an mehreren Stellen verwenden, es muss sich nicht in der „Wurzel“-Abhängigkeit befinden.
+
+Es wird immer die Sicherheits-Scopes enthalten, die in den aktuellen `Security`-Abhängigkeiten deklariert sind und in allen Abhängigkeiten für **diese spezifische** *Pfadoperation* und **diesen spezifischen** Abhängigkeitsbaum.
+
+Da die `SecurityScopes` alle von den Verwendern der Abhängigkeiten deklarierten Scopes enthalten, können Sie damit überprüfen, ob ein Token in einer zentralen Abhängigkeitsfunktion über die erforderlichen Scopes verfügt, und dann unterschiedliche Scope-Anforderungen in unterschiedlichen *Pfadoperationen* deklarieren.
+
+Diese werden für jede *Pfadoperation* unabhängig überprüft.
+
+## Es testen { #check-it }
+
+Wenn Sie die API-Dokumentation öffnen, können Sie sich authentisieren und angeben, welche Scopes Sie autorisieren möchten.
+
+
+
+Wenn Sie keinen Scope auswählen, werden Sie „authentifiziert“, aber wenn Sie versuchen, auf `/users/me/` oder `/users/me/items/` zuzugreifen, wird eine Fehlermeldung angezeigt, die sagt, dass Sie nicht über genügend Berechtigungen verfügen. Sie können aber auf `/status/` zugreifen.
+
+Und wenn Sie den Scope `me`, aber nicht den Scope `items` auswählen, können Sie auf `/users/me/` zugreifen, aber nicht auf `/users/me/items/`.
+
+Das würde einer Drittanbieteranwendung passieren, die versucht, auf eine dieser *Pfadoperationen* mit einem Token zuzugreifen, das von einem Benutzer bereitgestellt wurde, abhängig davon, wie viele Berechtigungen der Benutzer dieser Anwendung erteilt hat.
+
+## Über Integrationen von Drittanbietern { #about-third-party-integrations }
+
+In diesem Beispiel verwenden wir den OAuth2-Flow „Password“.
+
+Das ist angemessen, wenn wir uns bei unserer eigenen Anwendung anmelden, wahrscheinlich mit unserem eigenen Frontend.
+
+Weil wir darauf vertrauen können, dass es den `username` und das `password` erhält, welche wir kontrollieren.
+
+Wenn Sie jedoch eine OAuth2-Anwendung erstellen, mit der andere eine Verbindung herstellen würden (d.h. wenn Sie einen Authentifizierungsanbieter erstellen, der Facebook, Google, GitHub usw. entspricht), sollten Sie einen der anderen Flows verwenden.
+
+Am häufigsten ist der „Implicit“-Flow.
+
+Am sichersten ist der „Code“-Flow, die Implementierung ist jedoch komplexer, da mehr Schritte erforderlich sind. Da er komplexer ist, schlagen viele Anbieter letztendlich den „Implicit“-Flow vor.
+
+/// note | Hinweis
+
+Es ist üblich, dass jeder Authentifizierungsanbieter seine Flows anders benennt, um sie zu einem Teil seiner Marke zu machen.
+
+Aber am Ende implementieren sie denselben OAuth2-Standard.
+
+///
+
+**FastAPI** enthält Werkzeuge für alle diese OAuth2-Authentifizierungs-Flows in `fastapi.security.oauth2`.
+
+## `Security` in Dekorator-`dependencies` { #security-in-decorator-dependencies }
+
+Auf die gleiche Weise können Sie eine `list`e von `Depends` im Parameter `dependencies` des Dekorators definieren (wie in [Abhängigkeiten in Pfadoperation-Dekoratoren](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md) erläutert), Sie könnten auch dort `Security` mit `scopes` verwenden.
diff --git a/docs/de/docs/advanced/settings.md b/docs/de/docs/advanced/settings.md
new file mode 100644
index 0000000000000..1df74802b32b2
--- /dev/null
+++ b/docs/de/docs/advanced/settings.md
@@ -0,0 +1,302 @@
+# Einstellungen und Umgebungsvariablen { #settings-and-environment-variables }
+
+In vielen Fällen benötigt Ihre Anwendung möglicherweise einige externe Einstellungen oder Konfigurationen, zum Beispiel geheime Schlüssel, Datenbank-Anmeldeinformationen, Anmeldeinformationen für E-Mail-Dienste, usw.
+
+Die meisten dieser Einstellungen sind variabel (können sich ändern), wie z. B. Datenbank-URLs. Und vieles könnten schützenswerte, geheime Daten sein.
+
+Aus diesem Grund werden diese üblicherweise in Umgebungsvariablen bereitgestellt, die von der Anwendung gelesen werden.
+
+/// tip | Tipp
+
+Um Umgebungsvariablen zu verstehen, können Sie [Umgebungsvariablen](../environment-variables.md) lesen.
+
+///
+
+## Typen und Validierung { #types-and-validation }
+
+Diese Umgebungsvariablen können nur Text-Zeichenketten verarbeiten, da sie außerhalb von Python liegen und mit anderen Programmen und dem Rest des Systems (und sogar mit verschiedenen Betriebssystemen wie Linux, Windows, macOS) kompatibel sein müssen.
+
+Das bedeutet, dass jeder in Python aus einer Umgebungsvariablen gelesene Wert ein `str` ist und jede Konvertierung in einen anderen Typ oder jede Validierung im Code erfolgen muss.
+
+## Pydantic `Settings` { #pydantic-settings }
+
+Glücklicherweise bietet Pydantic ein großartiges Werkzeug zur Verarbeitung dieser Einstellungen, die von Umgebungsvariablen stammen, mit [Pydantic: Settings Management](https://docs.pydantic.dev/latest/concepts/pydantic_settings/).
+
+### `pydantic-settings` installieren { #install-pydantic-settings }
+
+Stellen Sie zunächst sicher, dass Sie Ihre [virtuelle Umgebung](../virtual-environments.md) erstellt und aktiviert haben, und installieren Sie dann das Package `pydantic-settings`:
+
+
+
+Öffnen Sie dann die Dokumentation für die Unteranwendung unter [http://127.0.0.1:8000/subapi/docs](http://127.0.0.1:8000/subapi/docs).
+
+Sie sehen die automatische API-Dokumentation für die Unteranwendung, welche nur deren eigene _Pfadoperationen_ anzeigt, alle unter dem korrekten Unterpfad-Präfix `/subapi`:
+
+
+
+Wenn Sie versuchen, mit einer der beiden Benutzeroberflächen zu interagieren, funktionieren diese ordnungsgemäß, da der Browser mit jeder spezifischen Anwendung oder Unteranwendung kommunizieren kann.
+
+### Technische Details: `root_path` { #technical-details-root-path }
+
+Wenn Sie eine Unteranwendung wie oben beschrieben mounten, kümmert sich FastAPI darum, den Mount-Pfad für die Unteranwendung zu kommunizieren, mithilfe eines Mechanismus aus der ASGI-Spezifikation namens `root_path`.
+
+Auf diese Weise weiß die Unteranwendung, dass sie dieses Pfadpräfix für die Benutzeroberfläche der Dokumentation verwenden soll.
+
+Und die Unteranwendung könnte auch ihre eigenen gemounteten Unteranwendungen haben und alles würde korrekt funktionieren, da FastAPI sich um alle diese `root_path`s automatisch kümmert.
+
+Mehr über den `root_path` und dessen explizite Verwendung erfahren Sie im Abschnitt [Hinter einem Proxy](behind-a-proxy.md).
diff --git a/docs/de/docs/advanced/templates.md b/docs/de/docs/advanced/templates.md
new file mode 100644
index 0000000000000..218b0437e436c
--- /dev/null
+++ b/docs/de/docs/advanced/templates.md
@@ -0,0 +1,126 @@
+# Templates { #templates }
+
+Sie können jede gewünschte Template-Engine mit **FastAPI** verwenden.
+
+Eine häufige Wahl ist Jinja2, dasselbe, was auch von Flask und anderen Tools verwendet wird.
+
+Es gibt Werkzeuge zur einfachen Konfiguration, die Sie direkt in Ihrer **FastAPI**-Anwendung verwenden können (bereitgestellt von Starlette).
+
+## Abhängigkeiten installieren { #install-dependencies }
+
+Stellen Sie sicher, dass Sie eine [virtuelle Umgebung](../virtual-environments.md) erstellen, sie aktivieren und `jinja2` installieren:
+
+
+
+Sie können Nachrichten in das Eingabefeld tippen und absenden:
+
+
+
+Und Ihre **FastAPI**-Anwendung mit WebSockets antwortet:
+
+
+
+Sie können viele Nachrichten senden (und empfangen):
+
+
+
+Und alle verwenden dieselbe WebSocket-Verbindung.
+
+## Verwendung von `Depends` und anderen { #using-depends-and-others }
+
+In WebSocket-Endpunkten können Sie Folgendes aus `fastapi` importieren und verwenden:
+
+* `Depends`
+* `Security`
+* `Cookie`
+* `Header`
+* `Path`
+* `Query`
+
+Diese funktionieren auf die gleiche Weise wie für andere FastAPI-Endpunkte/*Pfadoperationen*:
+
+{* ../../docs_src/websockets_/tutorial002_an_py310.py hl[68:69,82] *}
+
+/// info | Info
+
+Da es sich um einen WebSocket handelt, macht es keinen Sinn, eine `HTTPException` auszulösen, stattdessen lösen wir eine `WebSocketException` aus.
+
+Sie können einen „Closing“-Code verwenden, aus den [gültigen Codes, die in der Spezifikation definiert sind](https://tools.ietf.org/html/rfc6455#section-7.4.1).
+
+///
+
+### WebSockets mit Abhängigkeiten ausprobieren { #try-the-websockets-with-dependencies }
+
+Führen Sie Ihre Anwendung aus:
+
+
+
+## Verbindungsabbrüche und mehrere Clients handhaben { #handling-disconnections-and-multiple-clients }
+
+Wenn eine WebSocket-Verbindung geschlossen wird, löst `await websocket.receive_text()` eine `WebSocketDisconnect`-Exception aus, die Sie dann wie in folgendem Beispiel abfangen und behandeln können.
+
+{* ../../docs_src/websockets_/tutorial003_py310.py hl[79:81] *}
+
+Zum Ausprobieren:
+
+* Öffnen Sie die Anwendung mit mehreren Browser-Tabs.
+* Schreiben Sie Nachrichten in den Tabs.
+* Schließen Sie dann einen der Tabs.
+
+Das wird die Ausnahme `WebSocketDisconnect` auslösen und alle anderen Clients erhalten eine Nachricht wie:
+
+```
+Client #1596980209979 left the chat
+```
+
+/// tip | Tipp
+
+Die obige Anwendung ist ein minimales und einfaches Beispiel, das zeigt, wie Nachrichten verarbeitet und an mehrere WebSocket-Verbindungen gesendet werden.
+
+Beachten Sie jedoch, dass, da alles nur im Speicher in einer einzigen Liste verwaltet wird, es nur funktioniert, während der Prozess ausgeführt wird, und nur mit einem einzelnen Prozess.
+
+Wenn Sie etwas benötigen, das sich leicht in FastAPI integrieren lässt, aber robuster ist und von Redis, PostgreSQL und anderen unterstützt wird, sehen Sie sich [encode/broadcaster](https://github.com/encode/broadcaster) an.
+
+///
+
+## Mehr Informationen { #more-info }
+
+Weitere Informationen zu Optionen finden Sie in der Dokumentation von Starlette:
+
+* [Die `WebSocket`-Klasse](https://www.starlette.dev/websockets/).
+* [Klassen-basierte Handhabung von WebSockets](https://www.starlette.dev/endpoints/#websocketendpoint).
diff --git a/docs/de/docs/advanced/wsgi.md b/docs/de/docs/advanced/wsgi.md
new file mode 100644
index 0000000000000..89e513dc08e6b
--- /dev/null
+++ b/docs/de/docs/advanced/wsgi.md
@@ -0,0 +1,51 @@
+# WSGI inkludieren – Flask, Django und andere { #including-wsgi-flask-django-others }
+
+Sie können WSGI-Anwendungen mounten, wie Sie es in [Unteranwendungen – Mounts](sub-applications.md), [Hinter einem Proxy](behind-a-proxy.md) gesehen haben.
+
+Dazu können Sie die `WSGIMiddleware` verwenden und damit Ihre WSGI-Anwendung wrappen, zum Beispiel Flask, Django usw.
+
+## `WSGIMiddleware` verwenden { #using-wsgimiddleware }
+
+/// info | Info
+
+Dafür muss `a2wsgi` installiert sein, z. B. mit `pip install a2wsgi`.
+
+///
+
+Sie müssen `WSGIMiddleware` aus `a2wsgi` importieren.
+
+Wrappen Sie dann die WSGI-Anwendung (z. B. Flask) mit der Middleware.
+
+Und dann mounten Sie das auf einem Pfad.
+
+{* ../../docs_src/wsgi/tutorial001_py310.py hl[1,3,23] *}
+
+/// note | Hinweis
+
+Früher wurde empfohlen, `WSGIMiddleware` aus `fastapi.middleware.wsgi` zu verwenden, dies ist jetzt deprecatet.
+
+Stattdessen wird empfohlen, das Paket `a2wsgi` zu verwenden. Die Nutzung bleibt gleich.
+
+Stellen Sie lediglich sicher, dass das Paket `a2wsgi` installiert ist und importieren Sie `WSGIMiddleware` korrekt aus `a2wsgi`.
+
+///
+
+## Es testen { #check-it }
+
+Jetzt wird jeder Request unter dem Pfad `/v1/` von der Flask-Anwendung verarbeitet.
+
+Und der Rest wird von **FastAPI** gehandhabt.
+
+Wenn Sie das ausführen und auf [http://localhost:8000/v1/](http://localhost:8000/v1/) gehen, sehen Sie die Response von Flask:
+
+```txt
+Hello, World from Flask!
+```
+
+Und wenn Sie auf [http://localhost:8000/v2](http://localhost:8000/v2) gehen, sehen Sie die Response von FastAPI:
+
+```JSON
+{
+ "message": "Hello World"
+}
+```
diff --git a/docs/de/docs/alternatives.md b/docs/de/docs/alternatives.md
new file mode 100644
index 0000000000000..910f3b972bdb6
--- /dev/null
+++ b/docs/de/docs/alternatives.md
@@ -0,0 +1,485 @@
+# Alternativen, Inspiration und Vergleiche { #alternatives-inspiration-and-comparisons }
+
+Was hat **FastAPI** inspiriert, wie es sich im Vergleich zu Alternativen verhält und was es von ihnen gelernt hat.
+
+## Einführung { #intro }
+
+**FastAPI** würde ohne die frühere Arbeit anderer nicht existieren.
+
+Es wurden zuvor viele Tools entwickelt, die als Inspiration für seine Entwicklung dienten.
+
+Ich habe die Schaffung eines neuen Frameworks viele Jahre lang vermieden. Zuerst habe ich versucht, alle von **FastAPI** abgedeckten Funktionen mithilfe vieler verschiedener Frameworks, Plugins und Tools zu lösen.
+
+Aber irgendwann gab es keine andere Möglichkeit, als etwas zu schaffen, das all diese Funktionen bereitstellte, die besten Ideen früherer Tools aufnahm und diese auf die bestmögliche Weise kombinierte, wobei Sprachfunktionen verwendet wurden, die vorher noch nicht einmal verfügbar waren (Python 3.6+ Typhinweise).
+
+## Vorherige Tools { #previous-tools }
+
+### [Django](https://www.djangoproject.com/) { #django }
+
+Es ist das beliebteste Python-Framework und genießt großes Vertrauen. Es wird zum Aufbau von Systemen wie Instagram verwendet.
+
+Es ist relativ eng mit relationalen Datenbanken (wie MySQL oder PostgreSQL) gekoppelt, daher ist es nicht sehr einfach, eine NoSQL-Datenbank (wie Couchbase, MongoDB, Cassandra, usw.) als Hauptspeicherengine zu verwenden.
+
+Es wurde erstellt, um den HTML-Code im Backend zu generieren, nicht um APIs zu erstellen, die von einem modernen Frontend (wie React, Vue.js und Angular) oder von anderen Systemen (wie IoT-Geräten) verwendet werden, um mit ihm zu kommunizieren.
+
+### [Django REST Framework](https://www.django-rest-framework.org/) { #django-rest-framework }
+
+Das Django REST Framework wurde als flexibles Toolkit zum Erstellen von Web-APIs unter Verwendung von Django entwickelt, um dessen API-Möglichkeiten zu verbessern.
+
+Es wird von vielen Unternehmen verwendet, darunter Mozilla, Red Hat und Eventbrite.
+
+Es war eines der ersten Beispiele für **automatische API-Dokumentation**, und dies war insbesondere eine der ersten Ideen, welche „die Suche nach“ **FastAPI** inspirierten.
+
+/// note | Hinweis
+
+Das Django REST Framework wurde von Tom Christie erstellt. Derselbe Schöpfer von Starlette und Uvicorn, auf denen **FastAPI** basiert.
+
+///
+
+/// check | Inspirierte **FastAPI**
+
+Eine automatische API-Dokumentationsoberfläche zu haben.
+
+///
+
+### [Flask](https://flask.palletsprojects.com) { #flask }
+
+Flask ist ein „Mikroframework“, es enthält weder Datenbankintegration noch viele der Dinge, die standardmäßig in Django enthalten sind.
+
+Diese Einfachheit und Flexibilität ermöglichen beispielsweise die Verwendung von NoSQL-Datenbanken als Hauptdatenspeichersystem.
+
+Da es sehr einfach ist, ist es relativ intuitiv zu erlernen, obwohl die Dokumentation an einigen Stellen etwas technisch wird.
+
+Es wird auch häufig für andere Anwendungen verwendet, die nicht unbedingt eine Datenbank, Benutzerverwaltung oder eine der vielen in Django enthaltenen Funktionen benötigen. Obwohl viele dieser Funktionen mit Plugins hinzugefügt werden können.
+
+Diese Entkopplung der Teile und die Tatsache, dass es sich um ein „Mikroframework“ handelt, welches so erweitert werden kann, dass es genau das abdeckt, was benötigt wird, war ein Schlüsselmerkmal, das ich beibehalten wollte.
+
+Angesichts der Einfachheit von Flask schien es eine gute Ergänzung zum Erstellen von APIs zu sein. Als Nächstes musste ein „Django REST Framework“ für Flask gefunden werden.
+
+/// check | Inspirierte **FastAPI**
+
+Ein Mikroframework zu sein. Es einfach zu machen, die benötigten Tools und Teile zu kombinieren.
+
+Über ein einfaches und benutzerfreundliches Routingsystem zu verfügen.
+
+///
+
+### [Requests](https://requests.readthedocs.io) { #requests }
+
+**FastAPI** ist eigentlich keine Alternative zu **Requests**. Der Umfang der beiden ist sehr unterschiedlich.
+
+Es wäre tatsächlich üblich, Requests *innerhalb* einer FastAPI-Anwendung zu verwenden.
+
+Dennoch erhielt FastAPI von Requests einiges an Inspiration.
+
+**Requests** ist eine Bibliothek zur *Interaktion* mit APIs (als Client), während **FastAPI** eine Bibliothek zum *Erstellen* von APIs (als Server) ist.
+
+Die beiden stehen mehr oder weniger an entgegengesetzten Enden und ergänzen sich.
+
+Requests hat ein sehr einfaches und intuitives Design, ist sehr einfach zu bedienen und verfügt über sinnvolle Standardeinstellungen. Aber gleichzeitig ist es sehr leistungsstark und anpassbar.
+
+Aus diesem Grund heißt es auf der offiziellen Website:
+
+> Requests ist eines der am häufigsten heruntergeladenen Python-Packages aller Zeiten
+
+Die Art und Weise, wie Sie es verwenden, ist sehr einfach. Um beispielsweise einen `GET`-Request zu machen, würden Sie schreiben:
+
+```Python
+response = requests.get("http://example.com/some/url")
+```
+
+Die entsprechende *Pfadoperation* der FastAPI-API könnte wie folgt aussehen:
+
+```Python hl_lines="1"
+@app.get("/some/url")
+def read_url():
+ return {"message": "Hello World"}
+```
+
+Sehen Sie sich die Ähnlichkeiten in `requests.get(...)` und `@app.get(...)` an.
+
+/// check | Inspirierte **FastAPI**
+
+* Über eine einfache und intuitive API zu verfügen.
+* HTTP-Methodennamen (Operationen) direkt, auf einfache und intuitive Weise zu verwenden.
+* Vernünftige Standardeinstellungen zu haben, aber auch mächtige Einstellungsmöglichkeiten.
+
+///
+
+### [Swagger](https://swagger.io/) / [OpenAPI](https://github.com/OAI/OpenAPI-Specification/) { #swagger-openapi }
+
+Die Hauptfunktion, die ich vom Django REST Framework haben wollte, war die automatische API-Dokumentation.
+
+Dann fand ich heraus, dass es einen Standard namens Swagger gab, zur Dokumentation von APIs unter Verwendung von JSON (oder YAML, einer Erweiterung von JSON).
+
+Und es gab bereits eine Web-Oberfläche für Swagger-APIs. Die Möglichkeit, Swagger-Dokumentation für eine API zu generieren, würde die automatische Nutzung dieser Web-Oberfläche ermöglichen.
+
+Irgendwann wurde Swagger an die Linux Foundation übergeben und in OpenAPI umbenannt.
+
+Aus diesem Grund spricht man bei Version 2.0 häufig von „Swagger“ und ab Version 3 von „OpenAPI“.
+
+/// check | Inspirierte **FastAPI**
+
+Einen offenen Standard für API-Spezifikationen zu übernehmen und zu verwenden, anstelle eines benutzerdefinierten Schemas.
+
+Und Standard-basierte Tools für die Oberfläche zu integrieren:
+
+* [Swagger UI](https://github.com/swagger-api/swagger-ui)
+* [ReDoc](https://github.com/Rebilly/ReDoc)
+
+Diese beiden wurden ausgewählt, weil sie ziemlich beliebt und stabil sind, aber bei einer schnellen Suche könnten Sie Dutzende alternativer Benutzeroberflächen für OpenAPI finden (welche Sie mit **FastAPI** verwenden können).
+
+///
+
+### Flask REST Frameworks { #flask-rest-frameworks }
+
+Es gibt mehrere Flask REST Frameworks, aber nachdem ich die Zeit und Arbeit investiert habe, sie zu untersuchen, habe ich festgestellt, dass viele nicht mehr unterstützt werden oder abgebrochen wurden und dass mehrere fortbestehende Probleme sie unpassend machten.
+
+### [Marshmallow](https://marshmallow.readthedocs.io/en/stable/) { #marshmallow }
+
+Eine der von API-Systemen benötigten Hauptfunktionen ist die Daten-„Serialisierung“, welche Daten aus dem Code (Python) entnimmt und in etwas umwandelt, was durch das Netzwerk gesendet werden kann. Beispielsweise das Konvertieren eines Objekts, welches Daten aus einer Datenbank enthält, in ein JSON-Objekt. Konvertieren von `datetime`-Objekten in Strings, usw.
+
+Eine weitere wichtige Funktion, benötigt von APIs, ist die Datenvalidierung, welche sicherstellt, dass die Daten unter gegebenen Umständen gültig sind. Zum Beispiel, dass ein Feld ein `int` ist und kein zufälliger String. Das ist besonders nützlich für hereinkommende Daten.
+
+Ohne ein Datenvalidierungssystem müssten Sie alle Prüfungen manuell im Code durchführen.
+
+Für diese Funktionen wurde Marshmallow entwickelt. Es ist eine großartige Bibliothek und ich habe sie schon oft genutzt.
+
+Aber sie wurde erstellt, bevor Typhinweise in Python existierten. Um also ein Schema zu definieren, müssen Sie bestimmte Werkzeuge und Klassen verwenden, die von Marshmallow bereitgestellt werden.
+
+/// check | Inspirierte **FastAPI**
+
+Code zu verwenden, um „Schemas“ zu definieren, welche Datentypen und Validierung automatisch bereitstellen.
+
+///
+
+### [Webargs](https://webargs.readthedocs.io/en/latest/) { #webargs }
+
+Eine weitere wichtige Funktion, die von APIs benötigt wird, ist das Parsen von Daten aus eingehenden Requests.
+
+Webargs wurde entwickelt, um dieses für mehrere Frameworks, einschließlich Flask, bereitzustellen.
+
+Es verwendet unter der Haube Marshmallow, um die Datenvalidierung durchzuführen. Und es wurde von denselben Entwicklern erstellt.
+
+Es ist ein großartiges Tool und ich habe es auch oft verwendet, bevor ich **FastAPI** hatte.
+
+/// info | Info
+
+Webargs wurde von denselben Marshmallow-Entwicklern erstellt.
+
+///
+
+/// check | Inspirierte **FastAPI**
+
+Eingehende Requestdaten automatisch zu validieren.
+
+///
+
+### [APISpec](https://apispec.readthedocs.io/en/stable/) { #apispec }
+
+Marshmallow und Webargs bieten Validierung, Parsen und Serialisierung als Plugins.
+
+Es fehlt jedoch noch die Dokumentation. Dann wurde APISpec erstellt.
+
+Es ist ein Plugin für viele Frameworks (und es gibt auch ein Plugin für Starlette).
+
+Die Funktionsweise besteht darin, dass Sie die Definition des Schemas im YAML-Format im Docstring jeder Funktion schreiben, die eine Route verarbeitet.
+
+Und es generiert OpenAPI-Schemas.
+
+So funktioniert es in Flask, Starlette, Responder, usw.
+
+Aber dann haben wir wieder das Problem einer Mikrosyntax innerhalb eines Python-Strings (eines großen YAML).
+
+Der Texteditor kann dabei nicht viel helfen. Und wenn wir Parameter oder Marshmallow-Schemas ändern und vergessen, auch den YAML-Docstring zu ändern, wäre das generierte Schema veraltet.
+
+/// info | Info
+
+APISpec wurde von denselben Marshmallow-Entwicklern erstellt.
+
+///
+
+/// check | Inspirierte **FastAPI**
+
+Den offenen Standard für APIs, OpenAPI, zu unterstützen.
+
+///
+
+### [Flask-apispec](https://flask-apispec.readthedocs.io/en/latest/) { #flask-apispec }
+
+Hierbei handelt es sich um ein Flask-Plugin, welches Webargs, Marshmallow und APISpec miteinander verbindet.
+
+Es nutzt die Informationen von Webargs und Marshmallow, um mithilfe von APISpec automatisch OpenAPI-Schemas zu generieren.
+
+Ein großartiges Tool, sehr unterbewertet. Es sollte weitaus populärer als viele andere Flask-Plugins sein. Möglicherweise liegt es daran, dass die Dokumentation zu kompakt und abstrakt ist.
+
+Das löste das Problem, YAML (eine andere Syntax) in Python-Docstrings schreiben zu müssen.
+
+Diese Kombination aus Flask, Flask-apispec mit Marshmallow und Webargs war bis zur Entwicklung von **FastAPI** mein Lieblings-Backend-Stack.
+
+Die Verwendung führte zur Entwicklung mehrerer Flask-Full-Stack-Generatoren. Dies sind die Hauptstacks, die ich (und mehrere externe Teams) bisher verwendet haben:
+
+* [https://github.com/tiangolo/full-stack](https://github.com/tiangolo/full-stack)
+* [https://github.com/tiangolo/full-stack-flask-couchbase](https://github.com/tiangolo/full-stack-flask-couchbase)
+* [https://github.com/tiangolo/full-stack-flask-couchdb](https://github.com/tiangolo/full-stack-flask-couchdb)
+
+Und dieselben Full-Stack-Generatoren bildeten die Basis der [**FastAPI**-Projektgeneratoren](project-generation.md).
+
+/// info | Info
+
+Flask-apispec wurde von denselben Marshmallow-Entwicklern erstellt.
+
+///
+
+/// check | Inspirierte **FastAPI**
+
+Das OpenAPI-Schema automatisch zu generieren, aus demselben Code, welcher die Serialisierung und Validierung definiert.
+
+///
+
+### [NestJS](https://nestjs.com/) (und [Angular](https://angular.io/)) { #nestjs-and-angular }
+
+Dies ist nicht einmal Python, NestJS ist ein von Angular inspiriertes JavaScript (TypeScript) NodeJS Framework.
+
+Es erreicht etwas Ähnliches wie Flask-apispec.
+
+Es verfügt über ein integriertes Dependency Injection System, welches von Angular 2 inspiriert ist. Erfordert ein Vorab-Registrieren der „Injectables“ (wie alle anderen Dependency Injection Systeme, welche ich kenne), sodass der Code ausschweifender wird und es mehr Codeverdoppelung gibt.
+
+Da die Parameter mit TypeScript-Typen beschrieben werden (ähnlich den Python-Typhinweisen), ist die Editorunterstützung ziemlich gut.
+
+Da TypeScript-Daten jedoch nach der Kompilierung nach JavaScript nicht erhalten bleiben, können die Typen nicht gleichzeitig die Validierung, Serialisierung und Dokumentation definieren. Aus diesem Grund und aufgrund einiger Designentscheidungen ist es für die Validierung, Serialisierung und automatische Schemagenerierung erforderlich, an vielen Stellen Dekoratoren hinzuzufügen. Es wird also ziemlich ausführlich.
+
+Es kann nicht sehr gut mit verschachtelten Modellen umgehen. Wenn es sich beim JSON-Body im Request also um ein JSON-Objekt mit inneren Feldern handelt, die wiederum verschachtelte JSON-Objekte sind, kann er nicht richtig dokumentiert und validiert werden.
+
+/// check | Inspirierte **FastAPI**
+
+Python-Typen zu verwenden, um eine hervorragende Editorunterstützung zu erhalten.
+
+Über ein leistungsstarkes Dependency Injection System zu verfügen. Eine Möglichkeit zu finden, Codeverdoppelung zu minimieren.
+
+///
+
+### [Sanic](https://sanic.readthedocs.io/en/latest/) { #sanic }
+
+Es war eines der ersten extrem schnellen Python-Frameworks, welches auf `asyncio` basierte. Es wurde so gestaltet, dass es Flask sehr ähnlich ist.
+
+/// note | Technische Details
+
+Es verwendete [`uvloop`](https://github.com/MagicStack/uvloop) anstelle der standardmäßigen Python-`asyncio`-Schleife. Das hat es so schnell gemacht.
+
+Hat eindeutig Uvicorn und Starlette inspiriert, welche derzeit in offenen Benchmarks schneller als Sanic sind.
+
+///
+
+/// check | Inspirierte **FastAPI**
+
+Einen Weg zu finden, eine hervorragende Performanz zu haben.
+
+Aus diesem Grund basiert **FastAPI** auf Starlette, da dieses das schnellste verfügbare Framework ist (getestet in Benchmarks von Dritten).
+
+///
+
+### [Falcon](https://falconframework.org/) { #falcon }
+
+Falcon ist ein weiteres leistungsstarkes Python-Framework. Es ist minimalistisch konzipiert und dient als Grundlage für andere Frameworks wie Hug.
+
+Es ist so konzipiert, dass es über Funktionen verfügt, welche zwei Parameter empfangen, einen „Request“ und eine „Response“. Dann „lesen“ Sie Teile des Requests und „schreiben“ Teile der Response. Aufgrund dieses Designs ist es nicht möglich, Request-Parameter und -Bodys mit Standard-Python-Typhinweisen als Funktionsparameter zu deklarieren.
+
+Daher müssen Datenvalidierung, Serialisierung und Dokumentation im Code und nicht automatisch erfolgen. Oder sie müssen als Framework oberhalb von Falcon implementiert werden, so wie Hug. Dieselbe Unterscheidung findet auch in anderen Frameworks statt, die vom Design von Falcon inspiriert sind und ein Requestobjekt und ein Responseobjekt als Parameter haben.
+
+/// check | Inspirierte **FastAPI**
+
+Wege zu finden, eine großartige Performanz zu erzielen.
+
+Zusammen mit Hug (da Hug auf Falcon basiert), einen `response`-Parameter in Funktionen zu deklarieren.
+
+Obwohl er in FastAPI optional ist und hauptsächlich zum Festlegen von Headern, Cookies und alternativen Statuscodes verwendet wird.
+
+///
+
+### [Molten](https://moltenframework.com/) { #molten }
+
+Ich habe Molten in den ersten Phasen der Entwicklung von **FastAPI** entdeckt. Und es hat ganz ähnliche Ideen:
+
+* Basierend auf Python-Typhinweisen.
+* Validierung und Dokumentation aus diesen Typen.
+* Dependency Injection System.
+
+Es verwendet keine Datenvalidierungs-, Serialisierungs- und Dokumentationsbibliothek eines Dritten wie Pydantic, sondern verfügt über eine eigene. Daher wären diese Datentyp-Definitionen nicht so einfach wiederverwendbar.
+
+Es erfordert eine etwas ausführlichere Konfiguration. Und da es auf WSGI (anstelle von ASGI) basiert, ist es nicht darauf ausgelegt, die hohe Leistung von Tools wie Uvicorn, Starlette und Sanic zu nutzen.
+
+Das Dependency Injection System erfordert eine Vorab-Registrierung der Abhängigkeiten und die Abhängigkeiten werden basierend auf den deklarierten Typen aufgelöst. Daher ist es nicht möglich, mehr als eine „Komponente“ zu deklarieren, welche einen bestimmten Typ bereitstellt.
+
+Routen werden an einer einzigen Stelle deklariert, indem Funktionen verwendet werden, die an anderen Stellen deklariert wurden (anstatt Dekoratoren zu verwenden, welche direkt über der Funktion platziert werden können, welche den Endpunkt verarbeitet). Dies ähnelt eher der Vorgehensweise von Django als der Vorgehensweise von Flask (und Starlette). Es trennt im Code Dinge, die relativ eng miteinander gekoppelt sind.
+
+/// check | Inspirierte **FastAPI**
+
+Zusätzliche Validierungen für Datentypen zu definieren, mithilfe des „Default“-Werts von Modellattributen. Dies verbessert die Editorunterstützung und war zuvor in Pydantic nicht verfügbar.
+
+Das hat tatsächlich dazu geführt, dass Teile von Pydantic aktualisiert wurden, um denselben Validierungsdeklarationsstil zu unterstützen (diese gesamte Funktionalität ist jetzt bereits in Pydantic verfügbar).
+
+///
+
+### [Hug](https://github.com/hugapi/hug) { #hug }
+
+Hug war eines der ersten Frameworks, welches die Deklaration von API-Parametertypen mithilfe von Python-Typhinweisen implementierte. Das war eine großartige Idee, die andere Tools dazu inspirierte, dasselbe zu tun.
+
+Es verwendete benutzerdefinierte Typen in seinen Deklarationen anstelle von Standard-Python-Typen, es war aber dennoch ein großer Fortschritt.
+
+Außerdem war es eines der ersten Frameworks, welches ein benutzerdefiniertes Schema generierte, welches die gesamte API in JSON deklarierte.
+
+Es basierte nicht auf einem Standard wie OpenAPI und JSON Schema. Daher wäre es nicht einfach, es in andere Tools wie Swagger UI zu integrieren. Aber, nochmal, es war eine sehr innovative Idee.
+
+Es verfügt über eine interessante, ungewöhnliche Funktion: Mit demselben Framework ist es möglich, APIs und auch CLIs zu erstellen.
+
+Da es auf dem bisherigen Standard für synchrone Python-Webframeworks (WSGI) basiert, kann es nicht mit Websockets und anderen Dingen umgehen, verfügt aber dennoch über eine hohe Performanz.
+
+/// info | Info
+
+Hug wurde von Timothy Crosley erstellt, demselben Schöpfer von [`isort`](https://github.com/timothycrosley/isort), einem großartigen Tool zum automatischen Sortieren von Importen in Python-Dateien.
+
+///
+
+/// check | Ideen, die **FastAPI** inspiriert haben
+
+Hug inspirierte Teile von APIStar und war eines der Tools, die ich am vielversprechendsten fand, neben APIStar.
+
+Hug hat dazu beigetragen, **FastAPI** dazu zu inspirieren, Python-Typhinweise zum Deklarieren von Parametern zu verwenden und ein Schema zu generieren, das die API automatisch definiert.
+
+Hug inspirierte **FastAPI** dazu, einen `response`-Parameter in Funktionen zu deklarieren, um Header und Cookies zu setzen.
+
+///
+
+### [APIStar](https://github.com/encode/apistar) (≦ 0.5) { #apistar-0-5 }
+
+Kurz bevor ich mich entschied, **FastAPI** zu erstellen, fand ich den **APIStar**-Server. Er hatte fast alles, was ich suchte, und ein tolles Design.
+
+Er war eine der ersten Implementierungen eines Frameworks, die ich je gesehen hatte (vor NestJS und Molten), welches Python-Typhinweise zur Deklaration von Parametern und Requests verwendeten. Ich habe ihn mehr oder weniger zeitgleich mit Hug gefunden. Aber APIStar nutzte den OpenAPI-Standard.
+
+Er verfügte an mehreren Stellen über automatische Datenvalidierung, Datenserialisierung und OpenAPI-Schemagenerierung, basierend auf denselben Typhinweisen.
+
+Body-Schemadefinitionen verwendeten nicht die gleichen Python-Typhinweise wie Pydantic, er war Marshmallow etwas ähnlicher, sodass die Editorunterstützung nicht so gut war, aber dennoch war APIStar die beste verfügbare Option.
+
+Er hatte zu dieser Zeit die besten Leistungsbenchmarks (nur übertroffen von Starlette).
+
+Anfangs gab es keine Web-Oberfläche für die automatische API-Dokumentation, aber ich wusste, dass ich Swagger UI hinzufügen konnte.
+
+Er verfügte über ein Dependency Injection System. Es erforderte eine Vorab-Registrierung der Komponenten, wie auch bei anderen oben besprochenen Tools. Aber dennoch, es war ein tolles Feature.
+
+Ich konnte ihn nie in einem vollständigen Projekt verwenden, da er keine Sicherheitsintegration hatte, sodass ich nicht alle Funktionen, die ich hatte, durch die auf Flask-apispec basierenden Full-Stack-Generatoren ersetzen konnte. Ich hatte in meinem Projekte-Backlog den Eintrag, einen Pull Request zu erstellen, welcher diese Funktionalität hinzufügte.
+
+Doch dann verlagerte sich der Schwerpunkt des Projekts.
+
+Es handelte sich nicht länger um ein API-Webframework, da sich der Entwickler auf Starlette konzentrieren musste.
+
+Jetzt handelt es sich bei APIStar um eine Reihe von Tools zur Validierung von OpenAPI-Spezifikationen, nicht um ein Webframework.
+
+/// info | Info
+
+APIStar wurde von Tom Christie erstellt. Derselbe, welcher Folgendes erstellt hat:
+
+* Django REST Framework
+* Starlette (auf welchem **FastAPI** basiert)
+* Uvicorn (verwendet von Starlette und **FastAPI**)
+
+///
+
+/// check | Inspirierte **FastAPI**
+
+Zu existieren.
+
+Die Idee, mehrere Dinge (Datenvalidierung, Serialisierung und Dokumentation) mit denselben Python-Typen zu deklarieren, welche gleichzeitig eine hervorragende Editorunterstützung bieten, hielt ich für eine brillante Idee.
+
+Und nach einer langen Suche nach einem ähnlichen Framework und dem Testen vieler verschiedener Alternativen, war APIStar die beste verfügbare Option.
+
+Dann hörte APIStar auf, als Server zu existieren, und Starlette wurde geschaffen, welches eine neue, bessere Grundlage für ein solches System bildete. Das war die finale Inspiration für die Entwicklung von **FastAPI**.
+
+Ich betrachte **FastAPI** als einen „spirituellen Nachfolger“ von APIStar, welcher die Funktionen, das Typsystem und andere Teile verbessert und erweitert, basierend auf den Erkenntnissen aus all diesen früheren Tools.
+
+///
+
+## Verwendet von **FastAPI** { #used-by-fastapi }
+
+### [Pydantic](https://docs.pydantic.dev/) { #pydantic }
+
+Pydantic ist eine Bibliothek zum Definieren von Datenvalidierung, Serialisierung und Dokumentation (unter Verwendung von JSON Schema) basierend auf Python-Typhinweisen.
+
+Das macht es äußerst intuitiv.
+
+Es ist vergleichbar mit Marshmallow. Obwohl es in Benchmarks schneller als Marshmallow ist. Und da es auf den gleichen Python-Typhinweisen basiert, ist die Editorunterstützung großartig.
+
+/// check | **FastAPI** verwendet es, um
+
+Die gesamte Datenvalidierung, Datenserialisierung und automatische Modelldokumentation (basierend auf JSON Schema) zu erledigen.
+
+**FastAPI** nimmt dann, abgesehen von all den anderen Dingen, die es tut, dieses JSON-Schema und fügt es in OpenAPI ein.
+
+///
+
+### [Starlette](https://www.starlette.dev/) { #starlette }
+
+Starlette ist ein leichtgewichtiges ASGI-Framework/Toolkit, welches sich ideal für die Erstellung hochperformanter asynchroner Dienste eignet.
+
+Es ist sehr einfach und intuitiv. Es ist so konzipiert, dass es leicht erweiterbar ist und über modulare Komponenten verfügt.
+
+Es bietet:
+
+* Eine sehr beeindruckende Leistung.
+* WebSocket-Unterstützung.
+* Hintergrundtasks im selben Prozess.
+* Startup- und Shutdown-Events.
+* Testclient basierend auf HTTPX.
+* CORS, GZip, statische Dateien, Responses streamen.
+* Session- und Cookie-Unterstützung.
+* 100 % Testabdeckung.
+* 100 % Typannotierte Codebasis.
+* Wenige starke Abhängigkeiten.
+
+Starlette ist derzeit das schnellste getestete Python-Framework. Nur übertroffen von Uvicorn, welches kein Framework, sondern ein Server ist.
+
+Starlette bietet alle grundlegenden Funktionen eines Web-Microframeworks.
+
+Es bietet jedoch keine automatische Datenvalidierung, Serialisierung oder Dokumentation.
+
+Das ist eines der wichtigsten Dinge, welche **FastAPI** hinzufügt, alles basierend auf Python-Typhinweisen (mit Pydantic). Das, plus, das Dependency Injection System, Sicherheitswerkzeuge, OpenAPI-Schemagenerierung, usw.
+
+/// note | Technische Details
+
+ASGI ist ein neuer „Standard“, welcher von Mitgliedern des Django-Kernteams entwickelt wird. Es handelt sich immer noch nicht um einen „Python-Standard“ (ein PEP), obwohl sie gerade dabei sind, das zu tun.
+
+Dennoch wird es bereits von mehreren Tools als „Standard“ verwendet. Das verbessert die Interoperabilität erheblich, da Sie Uvicorn mit jeden anderen ASGI-Server (wie Daphne oder Hypercorn) tauschen oder ASGI-kompatible Tools wie `python-socketio` hinzufügen können.
+
+///
+
+/// check | **FastAPI** verwendet es, um
+
+Alle Kern-Webaspekte zu handhaben. Und fügt Funktionen obenauf.
+
+Die Klasse `FastAPI` selbst erbt direkt von der Klasse `Starlette`.
+
+Alles, was Sie also mit Starlette machen können, können Sie direkt mit **FastAPI** machen, da es sich im Grunde um Starlette auf Steroiden handelt.
+
+///
+
+### [Uvicorn](https://www.uvicorn.dev/) { #uvicorn }
+
+Uvicorn ist ein blitzschneller ASGI-Server, der auf uvloop und httptools basiert.
+
+Es handelt sich nicht um ein Webframework, sondern um einen Server. Beispielsweise werden keine Tools für das Routing von Pfaden bereitgestellt. Das ist etwas, was ein Framework wie Starlette (oder **FastAPI**) zusätzlich bieten würde.
+
+Es ist der empfohlene Server für Starlette und **FastAPI**.
+
+/// check | **FastAPI** empfiehlt es als
+
+Hauptwebserver zum Ausführen von **FastAPI**-Anwendungen.
+
+Sie können auch die Kommandozeilenoption `--workers` verwenden, um einen asynchronen Multiprozess-Server zu erhalten.
+
+Weitere Details finden Sie im Abschnitt [Deployment](deployment/index.md).
+
+///
+
+## Benchmarks und Geschwindigkeit { #benchmarks-and-speed }
+
+Um den Unterschied zwischen Uvicorn, Starlette und FastAPI zu verstehen, zu vergleichen, und zu sehen, lesen Sie den Abschnitt über [Benchmarks](benchmarks.md).
diff --git a/docs/de/docs/async.md b/docs/de/docs/async.md
new file mode 100644
index 0000000000000..066a9d9f6b4ed
--- /dev/null
+++ b/docs/de/docs/async.md
@@ -0,0 +1,444 @@
+# Nebenläufigkeit und async / await { #concurrency-and-async-await }
+
+Details zur `async def`-Syntax für *Pfadoperation-Funktionen* und Hintergrundinformationen zu asynchronem Code, Nebenläufigkeit und Parallelität.
+
+## In Eile? { #in-a-hurry }
+
+TL;DR:
+
+Wenn Sie Bibliotheken von Dritten verwenden, die mit `await` aufgerufen werden müssen, wie zum Beispiel:
+
+```Python
+results = await some_library()
+```
+
+Dann deklarieren Sie Ihre *Pfadoperation-Funktionen* mit `async def`, wie in:
+
+```Python hl_lines="2"
+@app.get('/')
+async def read_results():
+ results = await some_library()
+ return results
+```
+
+/// note | Hinweis
+
+Sie können `await` nur innerhalb von Funktionen verwenden, die mit `async def` erstellt wurden.
+
+///
+
+---
+
+Wenn Sie eine Bibliothek eines Dritten verwenden, die mit etwas kommuniziert (einer Datenbank, einer API, dem Dateisystem, usw.) und welche die Verwendung von `await` nicht unterstützt (dies ist derzeit bei den meisten Datenbankbibliotheken der Fall), dann deklarieren Sie Ihre *Pfadoperation-Funktionen* ganz normal nur mit `def`, wie in:
+
+```Python hl_lines="2"
+@app.get('/')
+def results():
+ results = some_library()
+ return results
+```
+
+---
+
+Wenn Ihre Anwendung (irgendwie) nicht mit etwas anderem kommunizieren und auf dessen Antwort warten muss, verwenden Sie `async def`, auch wenn Sie `await` im Inneren nicht verwenden müssen.
+
+---
+
+Wenn Sie sich unsicher sind, verwenden Sie einfach `def`.
+
+---
+
+**Hinweis**: Sie können `def` und `async def` in Ihren *Pfadoperation-Funktionen* beliebig mischen, so wie Sie es benötigen, und jede einzelne Funktion in der für Sie besten Variante erstellen. FastAPI wird damit das Richtige tun.
+
+Wie dem auch sei, in jedem der oben genannten Fälle wird FastAPI immer noch asynchron arbeiten und extrem schnell sein.
+
+Wenn Sie jedoch den oben genannten Schritten folgen, können einige Performanz-Optimierungen vorgenommen werden.
+
+## Technische Details { #technical-details }
+
+Moderne Versionen von Python unterstützen **„asynchronen Code“** unter Verwendung sogenannter **„Coroutinen“** mithilfe der Syntax **`async` und `await`**.
+
+Nehmen wir obigen Satz in den folgenden Abschnitten Schritt für Schritt unter die Lupe:
+
+* **Asynchroner Code**
+* **`async` und `await`**
+* **Coroutinen**
+
+## Asynchroner Code { #asynchronous-code }
+
+Asynchroner Code bedeutet lediglich, dass die Sprache 💬 eine Möglichkeit hat, dem Computer / Programm 🤖 mitzuteilen, dass es 🤖 an einem bestimmten Punkt im Code darauf warten muss, dass *etwas anderes* irgendwo anders fertig wird. Nehmen wir an, *etwas anderes* ist hier „Langsam-Datei“ 📝.
+
+Während der Zeit, die „Langsam-Datei“ 📝 benötigt, kann das System also andere Aufgaben erledigen.
+
+Dann kommt der Computer / das Programm 🤖 bei jeder Gelegenheit zurück, weil es entweder wieder wartet oder wann immer es 🤖 die ganze Arbeit erledigt hat, die zu diesem Zeitpunkt zu tun war. Und es 🤖 wird nachschauen, ob eine der Aufgaben, auf die es gewartet hat, fertig ist.
+
+Dann nimmt es 🤖 die erste erledigte Aufgabe (sagen wir, unsere „Langsam-Datei“ 📝) und bearbeitet sie weiter.
+
+Das „Warten auf etwas anderes“ bezieht sich normalerweise auf I/O-Operationen, die relativ „langsam“ sind (im Vergleich zur Geschwindigkeit des Prozessors und des Arbeitsspeichers), wie etwa das Warten darauf, dass:
+
+* die Daten des Clients über das Netzwerk empfangen wurden
+* die von Ihrem Programm gesendeten Daten vom Client über das Netzwerk empfangen wurden
+* der Inhalt einer Datei vom System von der Festplatte gelesen und an Ihr Programm übergeben wurde
+* der Inhalt, den Ihr Programm dem System übergeben hat, auf die Festplatte geschrieben wurde
+* eine Remote-API-Operation beendet wurde
+* Eine Datenbankoperation abgeschlossen wurde
+* eine Datenbankabfrage die Ergebnisse zurückgegeben hat
+* usw.
+
+Da die Ausführungszeit hier hauptsächlich durch das Warten auf I/O-Operationen verbraucht wird, nennt man dies auch „I/O-lastige“ („I/O bound“) Operationen.
+
+„Asynchron“, sagt man, weil der Computer / das Programm nicht mit einer langsamen Aufgabe „synchronisiert“ werden muss und nicht auf den genauen Moment warten muss, in dem die Aufgabe beendet ist, ohne dabei etwas zu tun, um schließlich das Ergebnis der Aufgabe zu übernehmen und die Arbeit fortsetzen zu können.
+
+Da es sich stattdessen um ein „asynchrones“ System handelt, kann die Aufgabe nach Abschluss ein wenig (einige Mikrosekunden) in der Schlange warten, bis der Computer / das Programm seine anderen Dinge erledigt hat und zurückkommt, um die Ergebnisse entgegenzunehmen und mit ihnen weiterzuarbeiten.
+
+Für „synchron“ (im Gegensatz zu „asynchron“) wird auch oft der Begriff „sequentiell“ verwendet, da der Computer / das Programm alle Schritte in einer Sequenz („der Reihe nach“) ausführt, bevor es zu einer anderen Aufgabe wechselt, auch wenn diese Schritte mit Warten verbunden sind.
+
+### Nebenläufigkeit und Hamburger { #concurrency-and-burgers }
+
+Diese oben beschriebene Idee von **asynchronem** Code wird manchmal auch **„Nebenläufigkeit“** genannt. Sie unterscheidet sich von **„Parallelität“**.
+
+**Nebenläufigkeit** und **Parallelität** beziehen sich beide auf „verschiedene Dinge, die mehr oder weniger gleichzeitig passieren“.
+
+Aber die Details zwischen *Nebenläufigkeit* und *Parallelität* sind ziemlich unterschiedlich.
+
+Um den Unterschied zu erkennen, stellen Sie sich die folgende Geschichte über Hamburger vor:
+
+### Nebenläufige Hamburger { #concurrent-burgers }
+
+Sie gehen mit Ihrem Schwarm Fastfood holen, stehen in der Schlange, während der Kassierer die Bestellungen der Leute vor Ihnen entgegennimmt. 😍
+
+
+
+Dann sind Sie an der Reihe und Sie bestellen zwei sehr schmackhafte Burger für Ihren Schwarm und Sie. 🍔🍔
+
+
+
+Der Kassierer sagt etwas zum Koch in der Küche, damit dieser weiß, dass er Ihre Burger zubereiten muss (obwohl er gerade die für die vorherigen Kunden zubereitet).
+
+
+
+Sie bezahlen. 💸
+
+Der Kassierer gibt Ihnen die Nummer Ihrer Bestellung.
+
+
+
+Während Sie warten, suchen Sie sich mit Ihrem Schwarm einen Tisch aus, Sie sitzen da und reden lange mit Ihrem Schwarm (da Ihre Burger sehr aufwändig sind und die Zubereitung einige Zeit dauert).
+
+Während Sie mit Ihrem Schwarm am Tisch sitzen und auf die Burger warten, können Sie die Zeit damit verbringen, zu bewundern, wie großartig, süß und klug Ihr Schwarm ist ✨😍✨.
+
+
+
+Während Sie warten und mit Ihrem Schwarm sprechen, überprüfen Sie von Zeit zu Zeit die auf dem Zähler angezeigte Nummer, um zu sehen, ob Sie bereits an der Reihe sind.
+
+Dann, irgendwann, sind Sie endlich an der Reihe. Sie gehen zur Theke, holen sich die Burger und kommen zurück an den Tisch.
+
+
+
+Sie und Ihr Schwarm essen die Burger und haben eine schöne Zeit. ✨
+
+
+
+/// info | Info
+
+Die wunderschönen Illustrationen stammen von [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨
+
+///
+
+---
+
+Stellen Sie sich vor, Sie wären der Computer / das Programm 🤖 in dieser Geschichte.
+
+Während Sie an der Schlange stehen, sind Sie einfach untätig 😴, warten darauf, dass Sie an die Reihe kommen, und tun nichts sehr „Produktives“. Aber die Schlange ist schnell abgearbeitet, weil der Kassierer nur die Bestellungen entgegennimmt (und nicht zubereitet), also ist das vertretbar.
+
+Wenn Sie dann an der Reihe sind, erledigen Sie tatsächliche „produktive“ Arbeit, Sie gehen das Menü durch, entscheiden sich, was Sie möchten, bekunden Ihre und die Wahl Ihres Schwarms, bezahlen, prüfen, ob Sie die richtige Menge Geld oder die richtige Karte geben, prüfen, ob die Rechnung korrekt ist, prüfen, dass die Bestellung die richtigen Artikel enthält, usw.
+
+Aber dann, auch wenn Sie Ihre Burger noch nicht haben, ist Ihre Interaktion mit dem Kassierer erst mal „auf Pause“ ⏸, weil Sie warten müssen 🕙, bis Ihre Burger fertig sind.
+
+Aber wenn Sie sich von der Theke entfernt haben und mit der Nummer für die Bestellung an einem Tisch sitzen, können Sie Ihre Aufmerksamkeit auf Ihren Schwarm lenken und an dieser Aufgabe „arbeiten“ ⏯ 🤓. Sie machen wieder etwas sehr „Produktives“ und flirten mit Ihrem Schwarm 😍.
+
+Dann sagt der Kassierer 💁 „Ich bin mit dem Burger fertig“, indem er Ihre Nummer auf dem Display über der Theke anzeigt, aber Sie springen nicht sofort wie verrückt auf, wenn das Display auf Ihre Nummer springt. Sie wissen, dass niemand Ihnen Ihre Burger wegnimmt, denn Sie haben die Nummer Ihrer Bestellung, und andere Leute haben andere Nummern.
+
+Also warten Sie darauf, dass Ihr Schwarm ihre Geschichte zu Ende erzählt (die aktuelle Arbeit ⏯ / bearbeitete Aufgabe beendet 🤓), lächeln sanft und sagen, dass Sie die Burger holen ⏸.
+
+Dann gehen Sie zur Theke 🔀, zur ursprünglichen Aufgabe, die nun erledigt ist ⏯, nehmen die Burger auf, sagen Danke, und bringen sie zum Tisch. Damit ist dieser Schritt / diese Aufgabe der Interaktion mit der Theke abgeschlossen ⏹. Das wiederum schafft eine neue Aufgabe, „Burger essen“ 🔀 ⏯, aber die vorherige Aufgabe „Burger holen“ ist erledigt ⏹.
+
+### Parallele Hamburger { #parallel-burgers }
+
+Stellen wir uns jetzt vor, dass es sich hierbei nicht um „nebenläufige Hamburger“, sondern um „parallele Hamburger“ handelt.
+
+Sie gehen los mit Ihrem Schwarm, um paralleles Fast Food zu bekommen.
+
+Sie stehen in der Schlange, während mehrere (sagen wir acht) Kassierer, die gleichzeitig Köche sind, die Bestellungen der Leute vor Ihnen entgegennehmen.
+
+Alle vor Ihnen warten darauf, dass ihre Burger fertig sind, bevor sie die Theke verlassen, denn jeder der 8 Kassierer geht los und bereitet den Burger sofort zu, bevor er die nächste Bestellung entgegennimmt.
+
+
+
+Dann sind Sie endlich an der Reihe und bestellen zwei sehr leckere Burger für Ihren Schwarm und Sie.
+
+Sie zahlen 💸.
+
+
+
+Der Kassierer geht in die Küche.
+
+Sie warten, vor der Theke stehend 🕙, damit niemand außer Ihnen Ihre Burger entgegennimmt, da es keine Nummern für die Reihenfolge gibt.
+
+
+
+Da Sie und Ihr Schwarm damit beschäftigt sind, niemanden vor sich zu lassen, der Ihre Burger nimmt, wenn sie ankommen, können Sie Ihrem Schwarm keine Aufmerksamkeit schenken. 😞
+
+Das ist „synchrone“ Arbeit, Sie sind mit dem Kassierer/Koch „synchronisiert“ 👨🍳. Sie müssen warten 🕙 und genau in dem Moment da sein, in dem der Kassierer/Koch 👨🍳 die Burger zubereitet hat und Ihnen gibt, sonst könnte jemand anderes sie nehmen.
+
+
+
+Dann kommt Ihr Kassierer/Koch 👨🍳 endlich mit Ihren Burgern zurück, nachdem Sie lange vor der Theke gewartet 🕙 haben.
+
+
+
+Sie nehmen Ihre Burger und gehen mit Ihrem Schwarm an den Tisch.
+
+Sie essen sie und sind fertig. ⏹
+
+
+
+Es wurde nicht viel geredet oder geflirtet, da die meiste Zeit mit Warten 🕙 vor der Theke verbracht wurde. 😞
+
+/// info | Info
+
+Die wunderschönen Illustrationen stammen von [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨
+
+///
+
+---
+
+In diesem Szenario der parallelen Hamburger sind Sie ein Computersystem / Programm 🤖 mit zwei Prozessoren (Sie und Ihr Schwarm), die beide warten 🕙 und ihre Aufmerksamkeit darauf verwenden, „lange Zeit vor der Theke zu warten“ 🕙.
+
+Der Fast-Food-Laden verfügt über 8 Prozessoren (Kassierer/Köche). Während der nebenläufige Burger-Laden nur zwei hatte (einen Kassierer und einen Koch).
+
+Dennoch ist das schlussendliche Benutzererlebnis nicht das Beste. 😞
+
+---
+
+Dies wäre die parallele äquivalente Geschichte für Hamburger. 🍔
+
+Für ein „realeres“ Beispiel hierfür, stellen Sie sich eine Bank vor.
+
+Bis vor kurzem hatten die meisten Banken mehrere Kassierer 👨💼👨💼👨💼👨💼 und eine große Warteschlange 🕙🕙🕙🕙🕙🕙🕙🕙.
+
+Alle Kassierer erledigen die ganze Arbeit mit einem Kunden nach dem anderen 👨💼⏯.
+
+Und man muss lange in der Schlange warten 🕙 sonst kommt man nicht an die Reihe.
+
+Sie würden Ihren Schwarm 😍 wahrscheinlich nicht mitnehmen wollen, um Besorgungen bei der Bank zu erledigen 🏦.
+
+### Hamburger Schlussfolgerung { #burger-conclusion }
+
+In diesem Szenario „Fastfood-Burger mit Ihrem Schwarm“ ist es viel sinnvoller, ein nebenläufiges System zu haben ⏸🔀⏯, da viel gewartet wird 🕙.
+
+Das ist auch bei den meisten Webanwendungen der Fall.
+
+Viele, viele Benutzer, aber Ihr Server wartet 🕙 darauf, dass deren nicht so gute Internetverbindungen die Requests übermitteln.
+
+Und dann wieder warten 🕙, bis die Responses zurückkommen.
+
+Dieses „Warten“ 🕙 wird in Mikrosekunden gemessen, aber zusammenfassend lässt sich sagen, dass am Ende eine Menge gewartet wird.
+
+Deshalb ist es sehr sinnvoll, asynchronen ⏸🔀⏯ Code für Web-APIs zu verwenden.
+
+Diese Art der Asynchronität hat NodeJS populär gemacht (auch wenn NodeJS nicht parallel ist) und darin liegt die Stärke von Go als Programmiersprache.
+
+Und das ist das gleiche Leistungsniveau, das Sie mit **FastAPI** erhalten.
+
+Und da Sie Parallelität und Asynchronität gleichzeitig haben können, erzielen Sie eine höhere Performanz als die meisten getesteten NodeJS-Frameworks und sind mit Go auf Augenhöhe, einer kompilierten Sprache, die näher an C liegt [(alles dank Starlette)](https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=query&l=zijmkf-1).
+
+### Ist Nebenläufigkeit besser als Parallelität? { #is-concurrency-better-than-parallelism }
+
+Nein! Das ist nicht die Moral der Geschichte.
+
+Nebenläufigkeit unterscheidet sich von Parallelität. Und sie ist besser bei **bestimmten** Szenarien, die viel Warten erfordern. Aus diesem Grund ist sie im Allgemeinen viel besser als Parallelität für die Entwicklung von Webanwendungen. Aber das stimmt nicht für alle Anwendungen.
+
+Um die Dinge auszugleichen, stellen Sie sich die folgende Kurzgeschichte vor:
+
+> Sie müssen ein großes, schmutziges Haus aufräumen.
+
+*Yup, das ist die ganze Geschichte*.
+
+---
+
+Es gibt kein Warten 🕙, nur viel Arbeit an mehreren Stellen im Haus.
+
+Sie könnten wie im Hamburger-Beispiel hin- und herspringen, zuerst das Wohnzimmer, dann die Küche, aber da Sie auf nichts warten 🕙, sondern nur putzen und putzen, hätte das Hin- und Herspringen keine Auswirkungen.
+
+Es würde mit oder ohne Hin- und Herspringen (Nebenläufigkeit) die gleiche Zeit in Anspruch nehmen, um fertig zu werden, und Sie hätten die gleiche Menge an Arbeit erledigt.
+
+Aber wenn Sie in diesem Fall die acht Ex-Kassierer/Köche/jetzt Reinigungskräfte mitbringen würden und jeder von ihnen (plus Sie) würde einen Bereich des Hauses reinigen, könnten Sie die ganze Arbeit **parallel** erledigen, und würden mit dieser zusätzlichen Hilfe viel schneller fertig werden.
+
+In diesem Szenario wäre jede einzelne Reinigungskraft (einschließlich Ihnen) ein Prozessor, der seinen Teil der Arbeit erledigt.
+
+Und da die meiste Ausführungszeit durch tatsächliche Arbeit (anstatt durch Warten) in Anspruch genommen wird und die Arbeit in einem Computer von einer CPU erledigt wird, werden diese Probleme als „CPU-lastig“ („CPU bound“) bezeichnet.
+
+---
+
+Typische Beispiele für CPU-lastige Vorgänge sind Dinge, die komplexe mathematische Berechnungen erfordern.
+
+Zum Beispiel:
+
+* **Audio-** oder **Bildbearbeitung**.
+* **Computer Vision**: Ein Bild besteht aus Millionen von Pixeln, jedes Pixel hat 3 Werte / Farben, die Verarbeitung erfordert normalerweise, Berechnungen mit diesen Pixeln durchzuführen, alles zur gleichen Zeit.
+* **Maschinelles Lernen**: Normalerweise sind viele „Matrix“- und „Vektor“-Multiplikationen erforderlich. Stellen Sie sich eine riesige Tabelle mit Zahlen vor, in der Sie alle Zahlen gleichzeitig multiplizieren.
+* **Deep Learning**: Dies ist ein Teilgebiet des maschinellen Lernens, daher gilt das Gleiche. Es ist nur so, dass es nicht eine einzige Tabelle mit Zahlen zum Multiplizieren gibt, sondern eine riesige Menge davon, und in vielen Fällen verwendet man einen speziellen Prozessor, um diese Modelle zu erstellen und / oder zu verwenden.
+
+### Nebenläufigkeit + Parallelität: Web + maschinelles Lernen { #concurrency-parallelism-web-machine-learning }
+
+Mit **FastAPI** können Sie die Vorteile der Nebenläufigkeit nutzen, die in der Webentwicklung weit verbreitet ist (derselbe Hauptvorteil von NodeJS).
+
+Sie können aber auch die Vorteile von Parallelität und Multiprocessing (mehrere Prozesse werden parallel ausgeführt) für **CPU-lastige** Workloads wie in Systemen für maschinelles Lernen nutzen.
+
+Dies und die einfache Tatsache, dass Python die Hauptsprache für **Data Science**, maschinelles Lernen und insbesondere Deep Learning ist, machen FastAPI zu einem sehr passenden Werkzeug für Web-APIs und Anwendungen für Data Science / maschinelles Lernen (neben vielen anderen).
+
+Wie Sie diese Parallelität in der Produktion erreichen, erfahren Sie im Abschnitt über [Deployment](deployment/index.md).
+
+## `async` und `await` { #async-and-await }
+
+Moderne Versionen von Python verfügen über eine sehr intuitive Möglichkeit, asynchronen Code zu schreiben. Dadurch sieht es wie normaler „sequentieller“ Code aus und übernimmt im richtigen Moment das „Warten“ für Sie.
+
+Wenn es einen Vorgang gibt, der erfordert, dass gewartet wird, bevor die Ergebnisse zurückgegeben werden, und der diese neue Python-Funktionalität unterstützt, können Sie ihn wie folgt schreiben:
+
+```Python
+burgers = await get_burgers(2)
+```
+
+Der Schlüssel hier ist das `await`. Es teilt Python mit, dass es warten ⏸ muss, bis `get_burgers(2)` seine Aufgabe erledigt hat 🕙, bevor die Ergebnisse in `burgers` gespeichert werden. Damit weiß Python, dass es in der Zwischenzeit etwas anderes tun kann 🔀 ⏯ (z. B. einen weiteren Request empfangen).
+
+Damit `await` funktioniert, muss es sich in einer Funktion befinden, die diese Asynchronität unterstützt. Dazu deklarieren Sie sie einfach mit `async def`:
+
+```Python hl_lines="1"
+async def get_burgers(number: int):
+ # Mache hier etwas Asynchrones, um die Burger zu erstellen
+ return burgers
+```
+
+... statt mit `def`:
+
+```Python hl_lines="2"
+# Dies ist nicht asynchron
+def get_sequential_burgers(number: int):
+ # Mache hier etwas Sequentielles, um die Burger zu erstellen
+ return burgers
+```
+
+Mit `async def` weiß Python, dass es innerhalb dieser Funktion auf `await`-Ausdrücke achten muss und dass es die Ausführung dieser Funktion „anhalten“ ⏸ und etwas anderes tun kann 🔀, bevor es zurückkommt.
+
+Wenn Sie eine `async def`-Funktion aufrufen möchten, müssen Sie sie „erwarten“ („await“). Das folgende wird also nicht funktionieren:
+
+```Python
+# Das funktioniert nicht, weil get_burgers definiert wurde mit: async def
+burgers = get_burgers(2)
+```
+
+---
+
+Wenn Sie also eine Bibliothek verwenden, die Ihnen sagt, dass Sie sie mit `await` aufrufen können, müssen Sie die *Pfadoperation-Funktionen*, die diese Bibliothek verwenden, mittels `async def` erstellen, wie in:
+
+```Python hl_lines="2-3"
+@app.get('/burgers')
+async def read_burgers():
+ burgers = await get_burgers(2)
+ return burgers
+```
+
+### Weitere technische Details { #more-technical-details }
+
+Ihnen ist wahrscheinlich aufgefallen, dass `await` nur innerhalb von Funktionen verwendet werden kann, die mit `async def` definiert sind.
+
+Gleichzeitig müssen aber mit `async def` definierte Funktionen „erwartet“ („awaited“) werden. Daher können Funktionen mit `async def` nur innerhalb von Funktionen aufgerufen werden, die auch mit `async def` definiert sind.
+
+Daraus resultiert das Ei-und-Huhn-Problem: Wie ruft man die erste `async` Funktion auf?
+
+Wenn Sie mit **FastAPI** arbeiten, müssen Sie sich darüber keine Sorgen machen, da diese „erste“ Funktion Ihre *Pfadoperation-Funktion* sein wird und FastAPI weiß, was zu tun ist.
+
+Wenn Sie jedoch `async` / `await` ohne FastAPI verwenden möchten, können Sie dies auch tun.
+
+### Schreiben Sie Ihren eigenen asynchronen Code { #write-your-own-async-code }
+
+Starlette (und **FastAPI**) basieren auf [AnyIO](https://anyio.readthedocs.io/en/stable/), was bedeutet, dass es sowohl kompatibel mit der Python-Standardbibliothek [asyncio](https://docs.python.org/3/library/asyncio-task.html) als auch mit [Trio](https://trio.readthedocs.io/en/stable/) ist.
+
+Insbesondere können Sie [AnyIO](https://anyio.readthedocs.io/en/stable/) direkt verwenden für Ihre fortgeschrittenen nebenläufigen Anwendungsfälle, die fortgeschrittenere Muster in Ihrem eigenen Code erfordern.
+
+Und auch wenn Sie FastAPI nicht verwenden würden, könnten Sie Ihre eigenen asynchronen Anwendungen mit [AnyIO](https://anyio.readthedocs.io/en/stable/) schreiben, um hochkompatibel zu sein und dessen Vorteile zu nutzen (z. B. *strukturierte Nebenläufigkeit*).
+
+Ich habe eine weitere Bibliothek auf Basis von AnyIO erstellt, als dünne Schicht obendrauf, um die Typannotationen etwas zu verbessern und bessere **Autovervollständigung**, **Inline-Fehler** usw. zu erhalten. Sie hat auch eine freundliche Einführung und ein Tutorial, um Ihnen zu helfen, **Ihren eigenen asynchronen Code zu verstehen** und zu schreiben: [Asyncer](https://asyncer.tiangolo.com/). Sie ist insbesondere nützlich, wenn Sie **asynchronen Code mit regulärem** (blockierendem/synchronem) Code kombinieren müssen.
+
+### Andere Formen von asynchronem Code { #other-forms-of-asynchronous-code }
+
+Diese Art der Verwendung von `async` und `await` ist in der Sprache relativ neu.
+
+Aber sie erleichtert die Arbeit mit asynchronem Code erheblich.
+
+Die gleiche Syntax (oder fast identisch) wurde kürzlich auch in moderne Versionen von JavaScript (im Browser und in NodeJS) aufgenommen.
+
+Davor war der Umgang mit asynchronem Code jedoch deutlich komplexer und schwieriger.
+
+In früheren Versionen von Python hätten Sie Threads oder [Gevent](https://www.gevent.org/) verwenden können. Der Code ist jedoch viel komplexer zu verstehen, zu debuggen und nachzuvollziehen.
+
+In früheren Versionen von NodeJS / Browser JavaScript hätten Sie „Callbacks“ verwendet. Was zur „Callback-Hölle“ führt.
+
+## Coroutinen { #coroutines }
+
+**Coroutine** ist nur ein schicker Begriff für dasjenige, was von einer `async def`-Funktion zurückgegeben wird. Python weiß, dass es so etwas wie eine Funktion ist, die es starten kann und die irgendwann endet, aber auch dass sie pausiert ⏸ werden kann, wann immer darin ein `await` steht.
+
+Aber all diese Funktionalität der Verwendung von asynchronem Code mit `async` und `await` wird oft als Verwendung von „Coroutinen“ zusammengefasst. Es ist vergleichbar mit dem Hauptmerkmal von Go, den „Goroutinen“.
+
+## Fazit { #conclusion }
+
+Sehen wir uns den gleichen Satz von oben noch mal an:
+
+> Moderne Versionen von Python unterstützen **„asynchronen Code“** unter Verwendung sogenannter **„Coroutinen“** mithilfe der Syntax **`async` und `await`**.
+
+Das sollte jetzt mehr Sinn ergeben. ✨
+
+All das ist es, was FastAPI (via Starlette) befeuert und es eine so beeindruckende Performanz haben lässt.
+
+## Sehr technische Details { #very-technical-details }
+
+/// warning | Achtung
+
+Das folgende können Sie wahrscheinlich überspringen.
+
+Dies sind sehr technische Details darüber, wie **FastAPI** unter der Haube funktioniert.
+
+Wenn Sie über gute technische Kenntnisse verfügen (Coroutinen, Threads, Blocking, usw.) und neugierig sind, wie FastAPI mit `async def`s im Vergleich zu normalen `def`s umgeht, fahren Sie fort.
+
+///
+
+### Pfadoperation-Funktionen { #path-operation-functions }
+
+Wenn Sie eine *Pfadoperation-Funktion* mit normalem `def` anstelle von `async def` deklarieren, wird sie in einem externen Threadpool ausgeführt, der dann `await`et wird, anstatt direkt aufgerufen zu werden (da dies den Server blockieren würde).
+
+Wenn Sie von einem anderen asynchronen Framework kommen, das nicht auf die oben beschriebene Weise funktioniert, und Sie es gewohnt sind, triviale, nur-berechnende *Pfadoperation-Funktionen* mit einfachem `def` zu definieren, um einen geringfügigen Geschwindigkeitsgewinn (etwa 100 Nanosekunden) zu erzielen, beachten Sie bitte, dass der Effekt in **FastAPI** genau gegenteilig wäre. In solchen Fällen ist es besser, `async def` zu verwenden, es sei denn, Ihre *Pfadoperation-Funktionen* verwenden Code, der blockierende I/O-Operationen durchführt.
+
+Dennoch besteht in beiden Fällen eine gute Chance, dass **FastAPI** [immer noch schneller](index.md#performance) als Ihr bisheriges Framework (oder zumindest damit vergleichbar) ist.
+
+### Abhängigkeiten { #dependencies }
+
+Das Gleiche gilt für [Abhängigkeiten](tutorial/dependencies/index.md). Wenn eine Abhängigkeit eine normale `def`-Funktion anstelle einer `async def` ist, wird sie im externen Threadpool ausgeführt.
+
+### Unterabhängigkeiten { #sub-dependencies }
+
+Sie können mehrere Abhängigkeiten und [Unterabhängigkeiten](tutorial/dependencies/sub-dependencies.md) haben, die einander bedingen (als Parameter der Funktionsdefinitionen), einige davon könnten erstellt werden mit `async def` und einige mit normalem `def`. Es würde immer noch funktionieren, und diejenigen, die mit normalem `def` erstellt wurden, würden in einem externen Thread (vom Threadpool stammend) aufgerufen werden, anstatt `await`et zu werden.
+
+### Andere Hilfsfunktionen { #other-utility-functions }
+
+Jede andere Hilfsfunktion, die Sie direkt aufrufen, kann mit normalem `def` oder `async def` erstellt werden, und FastAPI beeinflusst nicht die Art und Weise, wie Sie sie aufrufen.
+
+Dies steht im Gegensatz zu den Funktionen, die FastAPI für Sie aufruft: *Pfadoperation-Funktionen* und Abhängigkeiten.
+
+Wenn Ihre Hilfsfunktion eine normale Funktion mit `def` ist, wird sie direkt aufgerufen (so wie Sie es in Ihrem Code schreiben), nicht in einem Threadpool. Wenn die Funktion mit `async def` erstellt wurde, sollten Sie sie `await`en, wenn Sie sie in Ihrem Code aufrufen.
+
+---
+
+Nochmal, es handelt sich hier um sehr technische Details, die Ihnen helfen, falls Sie danach gesucht haben.
+
+Andernfalls liegen Sie richtig, wenn Sie sich an die Richtlinien aus dem obigen Abschnitt halten: In Eile?.
diff --git a/docs/de/docs/benchmarks.md b/docs/de/docs/benchmarks.md
new file mode 100644
index 0000000000000..9421f80105194
--- /dev/null
+++ b/docs/de/docs/benchmarks.md
@@ -0,0 +1,34 @@
+# Benchmarks { #benchmarks }
+
+Unabhängige TechEmpower-Benchmarks zeigen **FastAPI**-Anwendungen, die unter Uvicorn ausgeführt werden, als [eines der schnellsten verfügbaren Python-Frameworks](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7), nur unterhalb von Starlette und Uvicorn selbst (die intern von FastAPI verwendet werden).
+
+Aber bei der Betrachtung von Benchmarks und Vergleichen sollten Sie Folgendes beachten.
+
+## Benchmarks und Geschwindigkeit { #benchmarks-and-speed }
+
+Wenn Sie die Benchmarks ansehen, ist es üblich, dass mehrere Tools unterschiedlichen Typs als gleichwertig verglichen werden.
+
+Insbesondere dass Uvicorn, Starlette und FastAPI zusammen verglichen werden (neben vielen anderen Tools).
+
+Je einfacher das Problem, das durch das Tool gelöst wird, desto besser wird die Performanz sein. Und die meisten Benchmarks testen nicht die zusätzlichen Funktionen, die das Tool bietet.
+
+Die Hierarchie ist wie folgt:
+
+* **Uvicorn**: ein ASGI-Server
+ * **Starlette**: (verwendet Uvicorn) ein Web-Mikroframework
+ * **FastAPI**: (verwendet Starlette) ein API-Mikroframework mit mehreren zusätzlichen Funktionen zum Erstellen von APIs, mit Datenvalidierung, usw.
+
+* **Uvicorn**:
+ * Wird die beste Performanz haben, da außer dem Server selbst nicht viel zusätzlicher Code vorhanden ist.
+ * Sie würden eine Anwendung nicht direkt in Uvicorn schreiben. Das würde bedeuten, dass Ihr Code zumindest mehr oder weniger den gesamten von Starlette (oder **FastAPI**) bereitgestellten Code enthalten müsste. Und wenn Sie das täten, hätte Ihre endgültige Anwendung den gleichen Overhead wie bei der Verwendung eines Frameworks und der Minimierung Ihres Anwendungscodes und der Fehler.
+ * Wenn Sie Uvicorn vergleichen, vergleichen Sie es mit Anwendungsservern wie Daphne, Hypercorn, uWSGI, usw.
+* **Starlette**:
+ * Wird nach Uvicorn die nächstbeste Performanz erbringen. Tatsächlich verwendet Starlette Uvicorn, um zu laufen. Daher kann es wahrscheinlich nur „langsamer“ als Uvicorn werden, weil mehr Code ausgeführt werden muss.
+ * Aber es bietet Ihnen die Werkzeuge, um einfache Webanwendungen zu erstellen, mit Routing basierend auf Pfaden, usw.
+ * Wenn Sie Starlette vergleichen, vergleichen Sie es mit Webframeworks (oder Mikroframeworks) wie Sanic, Flask, Django, usw.
+* **FastAPI**:
+ * So wie Starlette Uvicorn verwendet und nicht schneller als dieses sein kann, verwendet **FastAPI** Starlette, sodass es nicht schneller als dieses sein kann.
+ * FastAPI bietet zusätzliche Funktionen auf Basis von Starlette. Funktionen, die Sie beim Erstellen von APIs fast immer benötigen, wie Datenvalidierung und Serialisierung. Und wenn Sie es verwenden, erhalten Sie kostenlose automatische Dokumentation (die automatische Dokumentation verursacht nicht einmal zusätzlichen Overhead für laufende Anwendungen, sie wird beim Starten generiert).
+ * Wenn Sie FastAPI nicht verwenden und stattdessen Starlette direkt (oder ein anderes Tool wie Sanic, Flask, Responder, usw.) verwenden würden, müssten Sie die gesamte Datenvalidierung und Serialisierung selbst implementieren. Ihre finale Anwendung hätte also immer noch den gleichen Overhead, als ob sie mit FastAPI erstellt worden wäre. Und in vielen Fällen ist diese Datenvalidierung und Serialisierung der größte Teil des in Anwendungen geschriebenen Codes.
+ * Durch die Verwendung von FastAPI sparen Sie also Entwicklungszeit, Fehler und Codezeilen und würden wahrscheinlich die gleiche Performanz (oder eine bessere) erzielen, die Sie hätten, wenn Sie es nicht verwenden würden (da Sie alles in Ihrem Code implementieren müssten).
+ * Wenn Sie FastAPI vergleichen, vergleichen Sie es mit einem Webanwendungs-Framework (oder einer Reihe von Tools), das Datenvalidierung, Serialisierung und Dokumentation bereitstellt, wie Flask-apispec, NestJS, Molten, usw. – Frameworks mit integrierter automatischer Datenvalidierung, Serialisierung und Dokumentation.
diff --git a/docs/de/docs/deployment/cloud.md b/docs/de/docs/deployment/cloud.md
new file mode 100644
index 0000000000000..2c8fe85c48646
--- /dev/null
+++ b/docs/de/docs/deployment/cloud.md
@@ -0,0 +1,24 @@
+# FastAPI bei Cloudanbietern deployen { #deploy-fastapi-on-cloud-providers }
+
+Sie können praktisch **jeden Cloudanbieter** verwenden, um Ihre FastAPI-Anwendung zu deployen.
+
+In den meisten Fällen bieten die großen Cloudanbieter Anleitungen zum Deployment von FastAPI an.
+
+## FastAPI Cloud { #fastapi-cloud }
+
+**[FastAPI Cloud](https://fastapicloud.com)** wurde vom selben Autor und Team hinter **FastAPI** entwickelt.
+
+Es vereinfacht den Prozess des **Erstellens**, **Deployens** und **Zugreifens** auf eine API mit minimalem Aufwand.
+
+Es bringt die gleiche **Developer-Experience** beim Erstellen von Apps mit FastAPI auch zum **Deployment** in der Cloud. 🎉
+
+FastAPI Cloud ist der Hauptsponsor und Finanzierungsgeber für die *FastAPI and friends* Open-Source-Projekte. ✨
+
+## Cloudanbieter – Sponsoren { #cloud-providers-sponsors }
+
+Einige andere Cloudanbieter ✨ [**sponsern FastAPI**](../help-fastapi.md#sponsor-the-author) ✨ ebenfalls. 🙇
+
+Sie könnten diese ebenfalls in Betracht ziehen, deren Anleitungen folgen und ihre Dienste ausprobieren:
+
+* [Render](https://docs.render.com/deploy-fastapi?utm_source=deploydoc&utm_medium=referral&utm_campaign=fastapi)
+* [Railway](https://docs.railway.com/guides/fastapi?utm_medium=integration&utm_source=docs&utm_campaign=fastapi)
diff --git a/docs/de/docs/deployment/concepts.md b/docs/de/docs/deployment/concepts.md
new file mode 100644
index 0000000000000..be00b2260b62b
--- /dev/null
+++ b/docs/de/docs/deployment/concepts.md
@@ -0,0 +1,321 @@
+# Deployment-Konzepte { #deployments-concepts }
+
+Bei dem Deployment – der Bereitstellung – einer **FastAPI**-Anwendung, oder eigentlich jeder Art von Web-API, gibt es mehrere Konzepte, die Sie wahrscheinlich interessieren, und mithilfe der Sie die **am besten geeignete** Methode zum **Deployment Ihrer Anwendung** finden können.
+
+Einige wichtige Konzepte sind:
+
+* Sicherheit – HTTPS
+* Beim Hochfahren ausführen
+* Neustarts
+* Replikation (die Anzahl der laufenden Prozesse)
+* Arbeitsspeicher
+* Schritte vor dem Start
+
+Wir werden sehen, wie diese sich auf das **Deployment** auswirken.
+
+Letztendlich besteht das ultimative Ziel darin, **Ihre API-Clients** auf **sichere** Weise zu versorgen, um **Unterbrechungen** zu vermeiden und die **Rechenressourcen** (z. B. entfernte Server/virtuelle Maschinen) so effizient wie möglich zu nutzen. 🚀
+
+Ich erzähle Ihnen hier etwas mehr über diese **Konzepte**, was Ihnen hoffentlich die **Intuition** gibt, die Sie benötigen, um zu entscheiden, wie Sie Ihre API in sehr unterschiedlichen Umgebungen deployen, möglicherweise sogar in **zukünftigen**, die jetzt noch nicht existieren.
+
+Durch die Berücksichtigung dieser Konzepte können Sie die beste Variante des Deployments **Ihrer eigenen APIs** **evaluieren und konzipieren**.
+
+In den nächsten Kapiteln werde ich Ihnen mehr **konkrete Rezepte** für das Deployment von FastAPI-Anwendungen geben.
+
+Aber schauen wir uns zunächst einmal diese grundlegenden **konzeptionellen Ideen** an. Diese Konzepte gelten auch für jede andere Art von Web-API. 💡
+
+## Sicherheit – HTTPS { #security-https }
+
+Im [vorherigen Kapitel über HTTPS](https.md) haben wir erfahren, wie HTTPS Verschlüsselung für Ihre API bereitstellt.
+
+Wir haben auch gesehen, dass HTTPS normalerweise von einer Komponente **außerhalb** Ihres Anwendungsservers bereitgestellt wird, einem **TLS-Terminierungsproxy**.
+
+Und es muss etwas geben, das für die **Erneuerung der HTTPS-Zertifikate** zuständig ist, es könnte sich um dieselbe Komponente handeln oder um etwas anderes.
+
+### Beispieltools für HTTPS { #example-tools-for-https }
+
+Einige der Tools, die Sie als TLS-Terminierungsproxy verwenden können, sind:
+
+* Traefik
+ * Handhabt automatisch Zertifikat-Erneuerungen ✨
+* Caddy
+ * Handhabt automatisch Zertifikat-Erneuerungen ✨
+* Nginx
+ * Mit einer externen Komponente wie Certbot für Zertifikat-Erneuerungen
+* HAProxy
+ * Mit einer externen Komponente wie Certbot für Zertifikat-Erneuerungen
+* Kubernetes mit einem Ingress Controller wie Nginx
+ * Mit einer externen Komponente wie cert-manager für Zertifikat-Erneuerungen
+* Es wird intern von einem Cloudanbieter als Teil seiner Dienste verwaltet (siehe unten 👇)
+
+Eine andere Möglichkeit besteht darin, dass Sie einen **Cloud-Dienst** verwenden, der den größten Teil der Arbeit übernimmt, einschließlich der Einrichtung von HTTPS. Er könnte einige Einschränkungen haben oder Ihnen mehr in Rechnung stellen, usw. In diesem Fall müssten Sie jedoch nicht selbst einen TLS-Terminierungsproxy einrichten.
+
+In den nächsten Kapiteln zeige ich Ihnen einige konkrete Beispiele.
+
+---
+
+Die nächsten zu berücksichtigenden Konzepte drehen sich dann um das Programm, das Ihre eigentliche API ausführt (z. B. Uvicorn).
+
+## Programm und Prozess { #program-and-process }
+
+Wir werden viel über den laufenden „**Prozess**“ sprechen, daher ist es nützlich, Klarheit darüber zu haben, was das bedeutet und was der Unterschied zum Wort „**Programm**“ ist.
+
+### Was ist ein Programm { #what-is-a-program }
+
+Das Wort **Programm** wird häufig zur Beschreibung vieler Dinge verwendet:
+
+* Der **Code**, den Sie schreiben, die **Python-Dateien**.
+* Die **Datei**, die vom Betriebssystem **ausgeführt** werden kann, zum Beispiel: `python`, `python.exe` oder `uvicorn`.
+* Ein bestimmtes Programm, während es auf dem Betriebssystem **läuft**, die CPU nutzt und Dinge im Arbeitsspeicher ablegt. Dies wird auch als **Prozess** bezeichnet.
+
+### Was ist ein Prozess { #what-is-a-process }
+
+Das Wort **Prozess** wird normalerweise spezifischer verwendet und bezieht sich nur auf das, was im Betriebssystem ausgeführt wird (wie im letzten Punkt oben):
+
+* Ein bestimmtes Programm, während es auf dem Betriebssystem **ausgeführt** wird.
+ * Dies bezieht sich weder auf die Datei noch auf den Code, sondern **speziell** auf das, was vom Betriebssystem **ausgeführt** und verwaltet wird.
+* Jedes Programm, jeder Code **kann nur dann Dinge tun**, wenn er **ausgeführt** wird, wenn also ein **Prozess läuft**.
+* Der Prozess kann von Ihnen oder vom Betriebssystem **terminiert** („beendet“, „gekillt“) werden. An diesem Punkt hört es auf zu laufen/ausgeführt zu werden und kann **keine Dinge mehr tun**.
+* Hinter jeder Anwendung, die Sie auf Ihrem Computer ausführen, steckt ein Prozess, jedes laufende Programm, jedes Fenster usw. Und normalerweise laufen viele Prozesse **gleichzeitig**, während ein Computer eingeschaltet ist.
+* Es können **mehrere Prozesse** desselben **Programms** gleichzeitig ausgeführt werden.
+
+Wenn Sie sich den „Task-Manager“ oder „Systemmonitor“ (oder ähnliche Tools) in Ihrem Betriebssystem ansehen, können Sie viele dieser laufenden Prozesse sehen.
+
+Und Sie werden beispielsweise wahrscheinlich feststellen, dass mehrere Prozesse dasselbe Browserprogramm ausführen (Firefox, Chrome, Edge, usw.). Normalerweise führen diese einen Prozess pro Browsertab sowie einige andere zusätzliche Prozesse aus.
+
+
+
+---
+
+Nachdem wir nun den Unterschied zwischen den Begriffen **Prozess** und **Programm** kennen, sprechen wir weiter über das Deployment.
+
+## Beim Hochfahren ausführen { #running-on-startup }
+
+Wenn Sie eine Web-API erstellen, möchten Sie in den meisten Fällen, dass diese **immer läuft**, ununterbrochen, damit Ihre Clients immer darauf zugreifen können. Es sei denn natürlich, Sie haben einen bestimmten Grund, warum Sie möchten, dass diese nur in bestimmten Situationen ausgeführt wird. Meistens möchten Sie jedoch, dass sie ständig ausgeführt wird und **verfügbar** ist.
+
+### Auf einem entfernten Server { #in-a-remote-server }
+
+Wenn Sie einen entfernten Server (einen Cloud-Server, eine virtuelle Maschine, usw.) einrichten, können Sie am einfachsten `fastapi run` (welches Uvicorn verwendet) oder etwas Ähnliches manuell ausführen, genau wie bei der lokalen Entwicklung.
+
+Und es wird funktionieren und **während der Entwicklung** nützlich sein.
+
+Wenn Ihre Verbindung zum Server jedoch unterbrochen wird, wird der **laufende Prozess** wahrscheinlich abstürzen.
+
+Und wenn der Server neu gestartet wird (z. B. nach Updates oder Migrationen vom Cloudanbieter), werden Sie das wahrscheinlich **nicht bemerken**. Und deshalb wissen Sie nicht einmal, dass Sie den Prozess manuell neu starten müssen. Ihre API bleibt also einfach tot. 😱
+
+### Beim Hochfahren automatisch ausführen { #run-automatically-on-startup }
+
+Im Allgemeinen möchten Sie wahrscheinlich, dass das Serverprogramm (z. B. Uvicorn) beim Hochfahren des Servers automatisch gestartet wird und kein **menschliches Eingreifen** erforderlich ist, sodass immer ein Prozess mit Ihrer API ausgeführt wird (z. B. Uvicorn, welches Ihre FastAPI-Anwendung ausführt).
+
+### Separates Programm { #separate-program }
+
+Um dies zu erreichen, haben Sie normalerweise ein **separates Programm**, welches sicherstellt, dass Ihre Anwendung beim Hochfahren ausgeführt wird. Und in vielen Fällen würde es auch sicherstellen, dass auch andere Komponenten oder Anwendungen ausgeführt werden, beispielsweise eine Datenbank.
+
+### Beispieltools zur Ausführung beim Hochfahren { #example-tools-to-run-at-startup }
+
+Einige Beispiele für Tools, die diese Aufgabe übernehmen können, sind:
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Docker im Schwarm-Modus
+* Systemd
+* Supervisor
+* Es wird intern von einem Cloudanbieter im Rahmen seiner Dienste verwaltet
+* Andere ...
+
+In den nächsten Kapiteln werde ich Ihnen konkretere Beispiele geben.
+
+## Neustart { #restarts }
+
+Ähnlich wie Sie sicherstellen möchten, dass Ihre Anwendung beim Hochfahren ausgeführt wird, möchten Sie wahrscheinlich auch sicherstellen, dass diese nach Fehlern **neu gestartet** wird.
+
+### Wir machen Fehler { #we-make-mistakes }
+
+Wir, als Menschen, machen ständig **Fehler**. Software hat fast *immer* **Bugs**, die an verschiedenen Stellen versteckt sind. 🐛
+
+Und wir als Entwickler verbessern den Code ständig, wenn wir diese Bugs finden und neue Funktionen implementieren (und möglicherweise auch neue Bugs hinzufügen 😅).
+
+### Kleine Fehler automatisch handhaben { #small-errors-automatically-handled }
+
+Wenn beim Erstellen von Web-APIs mit FastAPI ein Fehler in unserem Code auftritt, wird FastAPI ihn normalerweise dem einzelnen Request zurückgeben, der den Fehler ausgelöst hat. 🛡
+
+Der Client erhält für diesen Request einen **500 Internal Server Error**, aber die Anwendung arbeitet bei den nächsten Requests weiter, anstatt einfach komplett abzustürzen.
+
+### Größere Fehler – Abstürze { #bigger-errors-crashes }
+
+Dennoch kann es vorkommen, dass wir Code schreiben, der **die gesamte Anwendung zum Absturz bringt** und so zum Absturz von Uvicorn und Python führt. 💥
+
+Und dennoch möchten Sie wahrscheinlich nicht, dass die Anwendung tot bleibt, weil an einer Stelle ein Fehler aufgetreten ist. Sie möchten wahrscheinlich, dass sie zumindest für die *Pfadoperationen*, die nicht fehlerhaft sind, **weiterläuft**.
+
+### Neustart nach Absturz { #restart-after-crash }
+
+Aber in den Fällen mit wirklich schwerwiegenden Fehlern, die den laufenden **Prozess** zum Absturz bringen, benötigen Sie eine externe Komponente, die den Prozess **neu startet**, zumindest ein paar Mal ...
+
+/// tip | Tipp
+
+... Obwohl es wahrscheinlich keinen Sinn macht, sie immer wieder neu zu starten, wenn die gesamte Anwendung einfach **sofort abstürzt**. Aber in diesen Fällen werden Sie es wahrscheinlich während der Entwicklung oder zumindest direkt nach dem Deployment bemerken.
+
+Konzentrieren wir uns also auf die Hauptfälle, in denen die Anwendung in bestimmten Fällen **in der Zukunft** völlig abstürzen könnte und es dann dennoch sinnvoll ist, sie neu zu starten.
+
+///
+
+Sie möchten wahrscheinlich, dass eine **externe Komponente** für den Neustart Ihrer Anwendung verantwortlich ist, da zu diesem Zeitpunkt dieselbe Anwendung mit Uvicorn und Python bereits abgestürzt ist und es daher nichts im selben Code derselben Anwendung gibt, was etwas dagegen tun kann.
+
+### Beispieltools zum automatischen Neustart { #example-tools-to-restart-automatically }
+
+In den meisten Fällen wird dasselbe Tool, das zum **Ausführen des Programms beim Hochfahren** verwendet wird, auch für automatische **Neustarts** verwendet.
+
+Dies könnte zum Beispiel erledigt werden durch:
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Docker im Schwarm-Modus
+* Systemd
+* Supervisor
+* Intern von einem Cloudanbieter im Rahmen seiner Dienste
+* Andere ...
+
+## Replikation – Prozesse und Arbeitsspeicher { #replication-processes-and-memory }
+
+Wenn Sie eine FastAPI-Anwendung verwenden und ein Serverprogramm wie den `fastapi`-Befehl, der Uvicorn ausführt, kann **ein einzelner Prozess** an mehrere Clients gleichzeitig ausliefern.
+
+In vielen Fällen möchten Sie jedoch mehrere Workerprozesse gleichzeitig ausführen.
+
+### Mehrere Prozesse – Worker { #multiple-processes-workers }
+
+Wenn Sie mehr Clients haben, als ein einzelner Prozess verarbeiten kann (z. B. wenn die virtuelle Maschine nicht sehr groß ist) und die CPU des Servers **mehrere Kerne** hat, dann könnten **mehrere Prozesse** gleichzeitig mit derselben Anwendung laufen und alle Requests unter sich verteilen.
+
+Wenn Sie mit **mehreren Prozessen** dasselbe API-Programm ausführen, werden diese üblicherweise als **Worker** bezeichnet.
+
+### Workerprozesse und Ports { #worker-processes-and-ports }
+
+Erinnern Sie sich aus der Dokumentation [Über HTTPS](https.md), dass nur ein Prozess auf einer Kombination aus Port und IP-Adresse auf einem Server lauschen kann?
+
+Das ist immer noch wahr.
+
+Um also **mehrere Prozesse** gleichzeitig zu haben, muss es einen **einzelnen Prozess geben, der einen Port überwacht**, welcher dann die Kommunikation auf irgendeine Weise an jeden Workerprozess überträgt.
+
+### Arbeitsspeicher pro Prozess { #memory-per-process }
+
+Wenn das Programm nun Dinge in den Arbeitsspeicher lädt, zum Beispiel ein Modell für maschinelles Lernen in einer Variablen oder den Inhalt einer großen Datei in einer Variablen, verbraucht das alles **einen Teil des Arbeitsspeichers (RAM – Random Access Memory)** des Servers.
+
+Und mehrere Prozesse teilen sich normalerweise keinen Speicher. Das bedeutet, dass jeder laufende Prozess seine eigenen Dinge, eigenen Variablen und eigenen Speicher hat. Und wenn Sie in Ihrem Code viel Speicher verbrauchen, verbraucht **jeder Prozess** die gleiche Menge Speicher.
+
+### Serverspeicher { #server-memory }
+
+Wenn Ihr Code beispielsweise ein Machine-Learning-Modell mit **1 GB Größe** lädt und Sie einen Prozess mit Ihrer API ausführen, verbraucht dieser mindestens 1 GB RAM. Und wenn Sie **4 Prozesse** (4 Worker) starten, verbraucht jeder 1 GB RAM. Insgesamt verbraucht Ihre API also **4 GB RAM**.
+
+Und wenn Ihr entfernter Server oder Ihre virtuelle Maschine nur über 3 GB RAM verfügt, führt der Versuch, mehr als 4 GB RAM zu laden, zu Problemen. 🚨
+
+### Mehrere Prozesse – Ein Beispiel { #multiple-processes-an-example }
+
+Im folgenden Beispiel gibt es einen **Manager-Prozess**, welcher zwei **Workerprozesse** startet und steuert.
+
+Dieser Manager-Prozess wäre wahrscheinlich derjenige, welcher der IP am **Port** lauscht. Und er würde die gesamte Kommunikation an die Workerprozesse weiterleiten.
+
+Diese Workerprozesse würden Ihre Anwendung ausführen, sie würden die Hauptberechnungen durchführen, um einen **Request** entgegenzunehmen und eine **Response** zurückzugeben, und sie würden alles, was Sie in Variablen einfügen, in den RAM laden.
+
++ +**FastAPI** würde ohne die frühere Arbeit anderer nicht existieren. + +Es wurden zuvor viele Tools entwickelt, die als Inspiration für seine Entwicklung dienten. + +Ich habe die Schaffung eines neuen Frameworks viele Jahre lang vermieden. Zuerst habe ich versucht, alle von **FastAPI** abgedeckten Funktionen mithilfe vieler verschiedener Frameworks, Plugins und Tools zu lösen. + +Aber irgendwann gab es keine andere Möglichkeit, als etwas zu schaffen, das all diese Funktionen bereitstellte, die besten Ideen früherer Tools aufnahm und diese auf die bestmögliche Weise kombinierte, wobei Sprachfunktionen verwendet wurden, die vorher noch nicht einmal verfügbar waren (Python 3.6+ Typhinweise). + ++ +## Untersuchung { #investigation } + +Durch die Nutzung all dieser vorherigen Alternativen hatte ich die Möglichkeit, von allen zu lernen, Ideen aufzunehmen und sie auf die beste Weise zu kombinieren, die ich für mich und die Entwicklerteams, mit denen ich zusammengearbeitet habe, finden konnte. + +Es war beispielsweise klar, dass es idealerweise auf Standard-Python-Typhinweisen basieren sollte. + +Der beste Ansatz bestand außerdem darin, bereits bestehende Standards zu nutzen. + +Bevor ich also überhaupt angefangen habe, **FastAPI** zu schreiben, habe ich mehrere Monate damit verbracht, die Spezifikationen für OpenAPI, JSON Schema, OAuth2, usw. zu studieren und deren Beziehungen, Überschneidungen und Unterschiede zu verstehen. + +## Design { #design } + +Dann habe ich einige Zeit damit verbracht, die Entwickler-„API“ zu entwerfen, die ich als Benutzer haben wollte (als Entwickler, welcher FastAPI verwendet). + +Ich habe mehrere Ideen in den beliebtesten Python-Editoren getestet: PyCharm, VS Code, Jedi-basierte Editoren. + +Laut der letzten [Python-Entwickler-Umfrage](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools) deckt das etwa 80 % der Benutzer ab. + +Das bedeutet, dass **FastAPI** speziell mit den Editoren getestet wurde, die von 80 % der Python-Entwickler verwendet werden. Und da die meisten anderen Editoren in der Regel ähnlich funktionieren, sollten alle diese Vorteile für praktisch alle Editoren funktionieren. + +Auf diese Weise konnte ich die besten Möglichkeiten finden, die Codeverdoppelung so weit wie möglich zu reduzieren, überall Autovervollständigung, Typ- und Fehlerprüfungen, usw. zu gewährleisten. + +Alles auf eine Weise, die allen Entwicklern das beste Entwicklungserlebnis bot. + +## Anforderungen { #requirements } + +Nachdem ich mehrere Alternativen getestet hatte, entschied ich, dass ich [**Pydantic**](https://docs.pydantic.dev/) wegen seiner Vorteile verwenden würde. + +Dann habe ich zu dessen Code beigetragen, um es vollständig mit JSON Schema kompatibel zu machen, und so verschiedene Möglichkeiten zum Definieren von einschränkenden Deklarationen (Constraints) zu unterstützen, und die Editorunterstützung (Typprüfungen, Codevervollständigung) zu verbessern, basierend auf den Tests in mehreren Editoren. + +Während der Entwicklung habe ich auch zu [**Starlette**](https://www.starlette.dev/) beigetragen, die andere Schlüsselanforderung. + +## Entwicklung { #development } + +Als ich mit der Erstellung von **FastAPI** selbst begann, waren die meisten Teile bereits vorhanden, das Design definiert, die Anforderungen und Tools bereit und das Wissen über die Standards und Spezifikationen klar und frisch. + +## Zukunft { #future } + +Zu diesem Zeitpunkt ist bereits klar, dass **FastAPI** mit seinen Ideen für viele Menschen nützlich ist. + +Es wird gegenüber früheren Alternativen gewählt, da es für viele Anwendungsfälle besser geeignet ist. + +Viele Entwickler und Teams verlassen sich bei ihren Projekten bereits auf **FastAPI** (einschließlich mir und meinem Team). + +Dennoch stehen uns noch viele Verbesserungen und Funktionen bevor. + +**FastAPI** hat eine große Zukunft vor sich. + +Und [Ihre Hilfe](help-fastapi.md) wird sehr geschätzt. diff --git a/docs/de/docs/how-to/authentication-error-status-code.md b/docs/de/docs/how-to/authentication-error-status-code.md new file mode 100644 index 0000000000000..02acef9f1d112 --- /dev/null +++ b/docs/de/docs/how-to/authentication-error-status-code.md @@ -0,0 +1,17 @@ +# Alte 403-Authentifizierungsfehler-Statuscodes verwenden { #use-old-403-authentication-error-status-codes } + +Vor FastAPI-Version `0.122.0` verwendeten die integrierten Sicherheits-Utilities den HTTP-Statuscode `403 Forbidden`, wenn sie dem Client nach einer fehlgeschlagenen Authentifizierung einen Fehler zurückgaben. + +Ab FastAPI-Version `0.122.0` verwenden sie den passenderen HTTP-Statuscode `401 Unauthorized` und geben in der Response einen sinnvollen `WWW-Authenticate`-Header zurück, gemäß den HTTP-Spezifikationen, [RFC 7235](https://datatracker.ietf.org/doc/html/rfc7235#section-3.1), [RFC 9110](https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized). + +Aber falls Ihre Clients aus irgendeinem Grund vom alten Verhalten abhängen, können Sie darauf zurückgreifen, indem Sie in Ihren Sicherheitsklassen die Methode `make_not_authenticated_error` überschreiben. + +Sie können beispielsweise eine Unterklasse von `HTTPBearer` erstellen, die einen Fehler `403 Forbidden` zurückgibt, statt des Default-`401 Unauthorized`-Fehlers: + +{* ../../docs_src/authentication_error_status_code/tutorial001_an_py310.py hl[9:13] *} + +/// tip | Tipp + +Beachten Sie, dass die Funktion die Exception-Instanz zurückgibt; sie wirft sie nicht. Das Werfen erfolgt im restlichen internen Code. + +/// diff --git a/docs/de/docs/how-to/conditional-openapi.md b/docs/de/docs/how-to/conditional-openapi.md new file mode 100644 index 0000000000000..dc873c9c93913 --- /dev/null +++ b/docs/de/docs/how-to/conditional-openapi.md @@ -0,0 +1,56 @@ +# Bedingte OpenAPI { #conditional-openapi } + +Bei Bedarf können Sie OpenAPI mithilfe von Einstellungen und Umgebungsvariablen abhängig von der Umgebung bedingt konfigurieren und sogar vollständig deaktivieren. + +## Über Sicherheit, APIs und Dokumentation { #about-security-apis-and-docs } + +Das Verstecken Ihrer Dokumentationsoberflächen in der Produktion *sollte nicht* die Methode sein, Ihre API zu schützen. + +Dadurch wird Ihrer API keine zusätzliche Sicherheit hinzugefügt, die *Pfadoperationen* sind weiterhin dort verfügbar, wo sie sich befinden. + +Wenn Ihr Code eine Sicherheitslücke aufweist, ist diese weiterhin vorhanden. + +Das Verstecken der Dokumentation macht es nur schwieriger zu verstehen, wie mit Ihrer API interagiert werden kann, und könnte es auch schwieriger machen, diese in der Produktion zu debuggen. Man könnte es einfach als eine Form von [Sicherheit durch Verschleierung](https://en.wikipedia.org/wiki/Security_through_obscurity) betrachten. + +Wenn Sie Ihre API sichern möchten, gibt es mehrere bessere Dinge, die Sie tun können, zum Beispiel: + +* Stellen Sie sicher, dass Sie über gut definierte Pydantic-Modelle für Ihre Requestbodys und Responses verfügen. +* Konfigurieren Sie alle erforderlichen Berechtigungen und Rollen mithilfe von Abhängigkeiten. +* Speichern Sie niemals Klartext-Passwörter, sondern nur Passwort-Hashes. +* Implementieren und verwenden Sie gängige kryptografische Tools wie pwdlib und JWT-Tokens, usw. +* Fügen Sie bei Bedarf detailliertere Berechtigungskontrollen mit OAuth2-Scopes hinzu. +* ... usw. + +Dennoch kann es sein, dass Sie einen ganz bestimmten Anwendungsfall haben, bei dem Sie die API-Dokumentation für eine bestimmte Umgebung (z. B. für die Produktion) oder abhängig von Konfigurationen aus Umgebungsvariablen wirklich deaktivieren müssen. + +## Bedingte OpenAPI aus Einstellungen und Umgebungsvariablen { #conditional-openapi-from-settings-and-env-vars } + +Sie können problemlos dieselben Pydantic-Einstellungen verwenden, um Ihre generierte OpenAPI und die Dokumentationsoberflächen zu konfigurieren. + +Zum Beispiel: + +{* ../../docs_src/conditional_openapi/tutorial001_py310.py hl[6,11] *} + +Hier deklarieren wir die Einstellung `openapi_url` mit dem gleichen Defaultwert `"/openapi.json"`. + +Und dann verwenden wir es beim Erstellen der `FastAPI`-App. + +Dann könnten Sie OpenAPI (einschließlich der Dokumentationsoberflächen) deaktivieren, indem Sie die Umgebungsvariable `OPENAPI_URL` auf einen leeren String setzen, wie zum Beispiel: + +
+
+Sie können sie jedoch deaktivieren, indem Sie `syntaxHighlight` auf `False` setzen:
+
+{* ../../docs_src/configure_swagger_ui/tutorial001_py310.py hl[3] *}
+
+... und dann zeigt die Swagger-Oberfläche die Syntaxhervorhebung nicht mehr an:
+
+
+
+## Das Theme ändern { #change-the-theme }
+
+Auf die gleiche Weise könnten Sie das Theme der Syntaxhervorhebung mit dem Schlüssel `"syntaxHighlight.theme"` festlegen (beachten Sie, dass er einen Punkt in der Mitte hat):
+
+{* ../../docs_src/configure_swagger_ui/tutorial002_py310.py hl[3] *}
+
+Obige Konfiguration würde das Theme für die Farbe der Syntaxhervorhebung ändern:
+
+
+
+## Defaultparameter der Swagger-Oberfläche ändern { #change-default-swagger-ui-parameters }
+
+FastAPI enthält einige Defaultkonfigurationsparameter, die für die meisten Anwendungsfälle geeignet sind.
+
+Es umfasst die folgenden Defaultkonfigurationen:
+
+{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}
+
+Sie können jede davon überschreiben, indem Sie im Argument `swagger_ui_parameters` einen anderen Wert festlegen.
+
+Um beispielsweise `deepLinking` zu deaktivieren, könnten Sie folgende Einstellungen an `swagger_ui_parameters` übergeben:
+
+{* ../../docs_src/configure_swagger_ui/tutorial003_py310.py hl[3] *}
+
+## Andere Parameter der Swagger-Oberfläche { #other-swagger-ui-parameters }
+
+Um alle anderen möglichen Konfigurationen zu sehen, die Sie verwenden können, lesen Sie die offizielle [Dokumentation für die Parameter der Swagger-Oberfläche](https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/).
+
+## Nur-JavaScript-Einstellungen { #javascript-only-settings }
+
+Die Swagger-Oberfläche erlaubt, dass andere Konfigurationen auch **Nur-JavaScript**-Objekte sein können (z. B. JavaScript-Funktionen).
+
+FastAPI umfasst auch diese Nur-JavaScript-`presets`-Einstellungen:
+
+```JavaScript
+presets: [
+ SwaggerUIBundle.presets.apis,
+ SwaggerUIBundle.SwaggerUIStandalonePreset
+]
+```
+
+Dabei handelt es sich um **JavaScript**-Objekte, nicht um Strings, daher können Sie diese nicht direkt vom Python-Code aus übergeben.
+
+Wenn Sie solche JavaScript-Konfigurationen verwenden müssen, können Sie einen der früher genannten Wege verwenden. Überschreiben Sie alle *Pfadoperationen* der Swagger-Oberfläche und schreiben Sie manuell jedes benötigte JavaScript.
diff --git a/docs/de/docs/how-to/custom-docs-ui-assets.md b/docs/de/docs/how-to/custom-docs-ui-assets.md
new file mode 100644
index 0000000000000..c88b09d06d15c
--- /dev/null
+++ b/docs/de/docs/how-to/custom-docs-ui-assets.md
@@ -0,0 +1,185 @@
+# Statische Assets der Dokumentationsoberfläche (Selbst-Hosting) { #custom-docs-ui-static-assets-self-hosting }
+
+Die API-Dokumentation verwendet **Swagger UI** und **ReDoc**, und jede dieser Dokumentationen benötigt einige JavaScript- und CSS-Dateien.
+
+Standardmäßig werden diese Dateien von einem CDN bereitgestellt.
+
+Es ist jedoch möglich, das anzupassen, ein bestimmtes CDN festzulegen oder die Dateien selbst bereitzustellen.
+
+## Benutzerdefiniertes CDN für JavaScript und CSS { #custom-cdn-for-javascript-and-css }
+
+Nehmen wir an, Sie möchten ein anderes CDN verwenden, zum Beispiel möchten Sie `https://unpkg.com/` verwenden.
+
+Das kann nützlich sein, wenn Sie beispielsweise in einem Land leben, in dem bestimmte URLs eingeschränkt sind.
+
+### Die automatische Dokumentation deaktivieren { #disable-the-automatic-docs }
+
+Der erste Schritt besteht darin, die automatische Dokumentation zu deaktivieren, da sie standardmäßig das Standard-CDN verwendet.
+
+Um sie zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[8] *}
+
+### Die benutzerdefinierte Dokumentation hinzufügen { #include-the-custom-docs }
+
+Jetzt können Sie die *Pfadoperationen* für die benutzerdefinierte Dokumentation erstellen.
+
+Sie können die internen Funktionen von FastAPI wiederverwenden, um die HTML-Seiten für die Dokumentation zu erstellen und ihnen die erforderlichen Argumente zu übergeben:
+
+* `openapi_url`: die URL, unter welcher die HTML-Seite für die Dokumentation das OpenAPI-Schema für Ihre API abrufen kann. Sie können hier das Attribut `app.openapi_url` verwenden.
+* `title`: der Titel Ihrer API.
+* `oauth2_redirect_url`: Sie können hier `app.swagger_ui_oauth2_redirect_url` verwenden, um die Standardeinstellung zu verwenden.
+* `swagger_js_url`: die URL, unter welcher der HTML-Code für Ihre Swagger-UI-Dokumentation die **JavaScript**-Datei abrufen kann. Dies ist die benutzerdefinierte CDN-URL.
+* `swagger_css_url`: die URL, unter welcher der HTML-Code für Ihre Swagger-UI-Dokumentation die **CSS**-Datei abrufen kann. Dies ist die benutzerdefinierte CDN-URL.
+
+Und ähnlich für ReDoc ...
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[2:6,11:19,22:24,27:33] *}
+
+/// tip | Tipp
+
+Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2.
+
+Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend.
+
+Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer.
+
+///
+
+### Eine *Pfadoperation* erstellen, um es zu testen { #create-a-path-operation-to-test-it }
+
+Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[36:38] *}
+
+### Es testen { #test-it }
+
+Jetzt sollten Sie in der Lage sein, zu Ihrer Dokumentation auf [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) zu gehen und die Seite neu zu laden, die Assets werden nun vom neuen CDN geladen.
+
+## JavaScript und CSS für die Dokumentation selbst hosten { #self-hosting-javascript-and-css-for-docs }
+
+Das Selbst-Hosting von JavaScript und CSS kann nützlich sein, wenn Sie beispielsweise möchten, dass Ihre Anwendung auch offline, ohne bestehenden Internetzugang oder in einem lokalen Netzwerk weiter funktioniert.
+
+Hier erfahren Sie, wie Sie diese Dateien selbst in derselben FastAPI-App bereitstellen und die Dokumentation für deren Verwendung konfigurieren.
+
+### Projektdateistruktur { #project-file-structure }
+
+Nehmen wir an, die Dateistruktur Ihres Projekts sieht folgendermaßen aus:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+```
+
+Erstellen Sie jetzt ein Verzeichnis zum Speichern dieser statischen Dateien.
+
+Ihre neue Dateistruktur könnte so aussehen:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static/
+```
+
+### Die Dateien herunterladen { #download-the-files }
+
+Laden Sie die für die Dokumentation benötigten statischen Dateien herunter und legen Sie diese im Verzeichnis `static/` ab.
+
+Sie können wahrscheinlich mit der rechten Maustaste auf jeden Link klicken und eine Option wie etwa „Link speichern unter ...“ auswählen.
+
+**Swagger UI** verwendet folgende Dateien:
+
+* [`swagger-ui-bundle.js`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js)
+* [`swagger-ui.css`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css)
+
+Und **ReDoc** verwendet diese Datei:
+
+* [`redoc.standalone.js`](https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js)
+
+Danach könnte Ihre Dateistruktur wie folgt aussehen:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static
+ ├── redoc.standalone.js
+ ├── swagger-ui-bundle.js
+ └── swagger-ui.css
+```
+
+### Die statischen Dateien bereitstellen { #serve-the-static-files }
+
+* Importieren Sie `StaticFiles`.
+* „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad.
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[7,11] *}
+
+### Die statischen Dateien testen { #test-the-static-files }
+
+Starten Sie Ihre Anwendung und gehen Sie auf [http://127.0.0.1:8000/static/redoc.standalone.js](http://127.0.0.1:8000/static/redoc.standalone.js).
+
+Sie sollten eine sehr lange JavaScript-Datei für **ReDoc** sehen.
+
+Sie könnte beginnen mit etwas wie:
+
+```JavaScript
+/*! For license information please see redoc.standalone.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")):
+...
+```
+
+Das zeigt, dass Sie statische Dateien aus Ihrer Anwendung bereitstellen können und dass Sie die statischen Dateien für die Dokumentation an der richtigen Stelle platziert haben.
+
+Jetzt können wir die Anwendung so konfigurieren, dass sie diese statischen Dateien für die Dokumentation verwendet.
+
+### Die automatische Dokumentation für statische Dateien deaktivieren { #disable-the-automatic-docs-for-static-files }
+
+Wie bei der Verwendung eines benutzerdefinierten CDN besteht der erste Schritt darin, die automatische Dokumentation zu deaktivieren, da sie standardmäßig das CDN verwendet.
+
+Um sie zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[9] *}
+
+### Die benutzerdefinierte Dokumentation für statische Dateien hinzufügen { #include-the-custom-docs-for-static-files }
+
+Und genau wie bei einem benutzerdefinierten CDN können Sie jetzt die *Pfadoperationen* für die benutzerdefinierte Dokumentation erstellen.
+
+Auch hier können Sie die internen Funktionen von FastAPI wiederverwenden, um die HTML-Seiten für die Dokumentation zu erstellen und ihnen die erforderlichen Argumente zu übergeben:
+
+* `openapi_url`: die URL, unter der die HTML-Seite für die Dokumentation das OpenAPI-Schema für Ihre API abrufen kann. Sie können hier das Attribut `app.openapi_url` verwenden.
+* `title`: der Titel Ihrer API.
+* `oauth2_redirect_url`: Sie können hier `app.swagger_ui_oauth2_redirect_url` verwenden, um die Standardeinstellung zu verwenden.
+* `swagger_js_url`: die URL, unter welcher der HTML-Code für Ihre Swagger-UI-Dokumentation die **JavaScript**-Datei abrufen kann. **Das ist die, welche jetzt von Ihrer eigenen Anwendung bereitgestellt wird**.
+* `swagger_css_url`: die URL, unter welcher der HTML-Code für Ihre Swagger-UI-Dokumentation die **CSS**-Datei abrufen kann. **Das ist die, welche jetzt von Ihrer eigenen Anwendung bereitgestellt wird**.
+
+Und ähnlich für ReDoc ...
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[2:6,14:22,25:27,30:36] *}
+
+/// tip | Tipp
+
+Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2.
+
+Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend.
+
+Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer.
+
+///
+
+### Eine *Pfadoperation* erstellen, um statische Dateien zu testen { #create-a-path-operation-to-test-static-files }
+
+Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[39:41] *}
+
+### Benutzeroberfläche mit statischen Dateien testen { #test-static-files-ui }
+
+Jetzt sollten Sie in der Lage sein, Ihr WLAN zu trennen, gehen Sie zu Ihrer Dokumentation unter [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) und laden Sie die Seite neu.
+
+Und selbst ohne Internet können Sie die Dokumentation für Ihre API sehen und mit ihr interagieren.
diff --git a/docs/de/docs/how-to/custom-request-and-route.md b/docs/de/docs/how-to/custom-request-and-route.md
new file mode 100644
index 0000000000000..5e2dee95d3850
--- /dev/null
+++ b/docs/de/docs/how-to/custom-request-and-route.md
@@ -0,0 +1,109 @@
+# Benutzerdefinierte Request- und APIRoute-Klasse { #custom-request-and-apiroute-class }
+
+In einigen Fällen möchten Sie möglicherweise die von den Klassen `Request` und `APIRoute` verwendete Logik überschreiben.
+
+Das kann insbesondere eine gute Alternative zur Logik in einer Middleware sein.
+
+Wenn Sie beispielsweise den Requestbody lesen oder manipulieren möchten, bevor er von Ihrer Anwendung verarbeitet wird.
+
+/// danger | Gefahr
+
+Dies ist eine „fortgeschrittene“ Funktion.
+
+Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie diesen Abschnitt vielleicht überspringen.
+
+///
+
+## Anwendungsfälle { #use-cases }
+
+Einige Anwendungsfälle sind:
+
+* Konvertieren von Nicht-JSON-Requestbodys nach JSON (z. B. [`msgpack`](https://msgpack.org/index.html)).
+* Dekomprimierung gzip-komprimierter Requestbodys.
+* Automatisches Loggen aller Requestbodys.
+
+## Handhaben von benutzerdefinierten Requestbody-Kodierungen { #handling-custom-request-body-encodings }
+
+Sehen wir uns an, wie Sie eine benutzerdefinierte `Request`-Unterklasse verwenden, um gzip-Requests zu dekomprimieren.
+
+Und eine `APIRoute`-Unterklasse zur Verwendung dieser benutzerdefinierten Requestklasse.
+
+### Eine benutzerdefinierte `GzipRequest`-Klasse erstellen { #create-a-custom-gziprequest-class }
+
+/// tip | Tipp
+
+Dies ist nur ein einfaches Beispiel, um zu demonstrieren, wie es funktioniert. Wenn Sie Gzip-Unterstützung benötigen, können Sie die bereitgestellte [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware) verwenden.
+
+///
+
+Zuerst erstellen wir eine `GzipRequest`-Klasse, welche die Methode `Request.body()` überschreibt, um den Body bei Vorhandensein eines entsprechenden Headers zu dekomprimieren.
+
+Wenn der Header kein `gzip` enthält, wird nicht versucht, den Body zu dekomprimieren.
+
+Auf diese Weise kann dieselbe Routenklasse gzip-komprimierte oder unkomprimierte Requests verarbeiten.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[9:16] *}
+
+### Eine benutzerdefinierte `GzipRoute`-Klasse erstellen { #create-a-custom-gziproute-class }
+
+Als Nächstes erstellen wir eine benutzerdefinierte Unterklasse von `fastapi.routing.APIRoute`, welche `GzipRequest` nutzt.
+
+Dieses Mal wird die Methode `APIRoute.get_route_handler()` überschrieben.
+
+Diese Methode gibt eine Funktion zurück. Und diese Funktion empfängt einen Request und gibt eine Response zurück.
+
+Hier verwenden wir sie, um aus dem ursprünglichen Request einen `GzipRequest` zu erstellen.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[19:27] *}
+
+/// note | Technische Details
+
+Ein `Request` hat ein `request.scope`-Attribut, welches einfach ein Python-`dict` ist, welches die mit dem Request verbundenen Metadaten enthält.
+
+Ein `Request` hat auch ein `request.receive`, welches eine Funktion ist, die den Body des Requests empfängt.
+
+Das `scope`-`dict` und die `receive`-Funktion sind beide Teil der ASGI-Spezifikation.
+
+Und diese beiden Dinge, `scope` und `receive`, werden benötigt, um eine neue `Request`-Instanz zu erstellen.
+
+Um mehr über den `Request` zu erfahren, schauen Sie sich [Starlettes Dokumentation zu Requests](https://www.starlette.dev/requests/) an.
+
+///
+
+Das Einzige, was die von `GzipRequest.get_route_handler` zurückgegebene Funktion anders macht, ist die Konvertierung von `Request` in ein `GzipRequest`.
+
+Dabei kümmert sich unser `GzipRequest` um die Dekomprimierung der Daten (falls erforderlich), bevor diese an unsere *Pfadoperationen* weitergegeben werden.
+
+Danach ist die gesamte Verarbeitungslogik dieselbe.
+
+Aufgrund unserer Änderungen in `GzipRequest.body` wird der Requestbody jedoch bei Bedarf automatisch dekomprimiert, wenn er von **FastAPI** geladen wird.
+
+## Zugriff auf den Requestbody in einem Exceptionhandler { #accessing-the-request-body-in-an-exception-handler }
+
+/// tip | Tipp
+
+Um dasselbe Problem zu lösen, ist es wahrscheinlich viel einfacher, den `body` in einem benutzerdefinierten Handler für `RequestValidationError` zu verwenden ([Fehlerbehandlung](../tutorial/handling-errors.md#use-the-requestvalidationerror-body)).
+
+Dieses Beispiel ist jedoch immer noch gültig und zeigt, wie mit den internen Komponenten interagiert wird.
+
+///
+
+Wir können denselben Ansatz auch verwenden, um in einem Exceptionhandler auf den Requestbody zuzugreifen.
+
+Alles, was wir tun müssen, ist, den Request innerhalb eines `try`/`except`-Blocks zu handhaben:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[14,16] *}
+
+Wenn eine Exception auftritt, befindet sich die `Request`-Instanz weiterhin im Gültigkeitsbereich, sodass wir den Requestbody lesen und bei der Fehlerbehandlung verwenden können:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[17:19] *}
+
+## Benutzerdefinierte `APIRoute`-Klasse in einem Router { #custom-apiroute-class-in-a-router }
+
+Sie können auch den Parameter `route_class` eines `APIRouter` festlegen:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[26] *}
+
+In diesem Beispiel verwenden die *Pfadoperationen* unter dem `router` die benutzerdefinierte `TimedRoute`-Klasse und haben in der Response einen zusätzlichen `X-Response-Time`-Header mit der Zeit, die zum Generieren der Response benötigt wurde:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[13:20] *}
diff --git a/docs/de/docs/how-to/extending-openapi.md b/docs/de/docs/how-to/extending-openapi.md
new file mode 100644
index 0000000000000..8005344c8d9fc
--- /dev/null
+++ b/docs/de/docs/how-to/extending-openapi.md
@@ -0,0 +1,80 @@
+# OpenAPI erweitern { #extending-openapi }
+
+Es gibt einige Fälle, in denen Sie das generierte OpenAPI-Schema ändern müssen.
+
+In diesem Abschnitt erfahren Sie, wie.
+
+## Der normale Vorgang { #the-normal-process }
+
+Der normale (Standard-)Prozess ist wie folgt.
+
+Eine `FastAPI`-Anwendung (Instanz) verfügt über eine `.openapi()`-Methode, von der erwartet wird, dass sie das OpenAPI-Schema zurückgibt.
+
+Als Teil der Erstellung des Anwendungsobjekts wird eine *Pfadoperation* für `/openapi.json` (oder welcher Wert für den Parameter `openapi_url` gesetzt wurde) registriert.
+
+Diese gibt lediglich eine JSON-Response zurück, mit dem Ergebnis der Methode `.openapi()` der Anwendung.
+
+Standardmäßig überprüft die Methode `.openapi()` die Eigenschaft `.openapi_schema`, um zu sehen, ob diese Inhalt hat, und gibt diesen zurück.
+
+Ist das nicht der Fall, wird der Inhalt mithilfe der Hilfsfunktion unter `fastapi.openapi.utils.get_openapi` generiert.
+
+Diese Funktion `get_openapi()` erhält als Parameter:
+
+* `title`: Der OpenAPI-Titel, der in der Dokumentation angezeigt wird.
+* `version`: Die Version Ihrer API, z. B. `2.5.0`.
+* `openapi_version`: Die Version der verwendeten OpenAPI-Spezifikation. Standardmäßig die neueste Version: `3.1.0`.
+* `summary`: Eine kurze Zusammenfassung der API.
+* `description`: Die Beschreibung Ihrer API. Dies kann Markdown enthalten und wird in der Dokumentation angezeigt.
+* `routes`: Eine Liste von Routen, dies sind alle registrierten *Pfadoperationen*. Sie stammen von `app.routes`.
+
+/// info | Info
+
+Der Parameter `summary` ist in OpenAPI 3.1.0 und höher verfügbar und wird von FastAPI 0.99.0 und höher unterstützt.
+
+///
+
+## Überschreiben der Standardeinstellungen { #overriding-the-defaults }
+
+Mithilfe der oben genannten Informationen können Sie dieselbe Hilfsfunktion verwenden, um das OpenAPI-Schema zu generieren und jeden benötigten Teil zu überschreiben.
+
+Fügen wir beispielsweise [ReDocs OpenAPI-Erweiterung zum Einbinden eines benutzerdefinierten Logos](https://github.com/Rebilly/ReDoc/blob/master/docs/redoc-vendor-extensions.md#x-logo) hinzu.
+
+### Normales **FastAPI** { #normal-fastapi }
+
+Schreiben Sie zunächst wie gewohnt Ihre ganze **FastAPI**-Anwendung:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[1,4,7:9] *}
+
+### Das OpenAPI-Schema generieren { #generate-the-openapi-schema }
+
+Verwenden Sie dann dieselbe Hilfsfunktion, um das OpenAPI-Schema innerhalb einer `custom_openapi()`-Funktion zu generieren:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[2,15:21] *}
+
+### Das OpenAPI-Schema ändern { #modify-the-openapi-schema }
+
+Jetzt können Sie die ReDoc-Erweiterung hinzufügen und dem `info`-„Objekt“ im OpenAPI-Schema ein benutzerdefiniertes `x-logo` hinzufügen:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[22:24] *}
+
+### Zwischenspeichern des OpenAPI-Schemas { #cache-the-openapi-schema }
+
+Sie können die Eigenschaft `.openapi_schema` als „Cache“ verwenden, um Ihr generiertes Schema zu speichern.
+
+Auf diese Weise muss Ihre Anwendung das Schema nicht jedes Mal generieren, wenn ein Benutzer Ihre API-Dokumentation öffnet.
+
+Es wird nur einmal generiert und dann wird dasselbe zwischengespeicherte Schema für die nächsten Requests verwendet.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[13:14,25:26] *}
+
+### Die Methode überschreiben { #override-the-method }
+
+Jetzt können Sie die Methode `.openapi()` durch Ihre neue Funktion ersetzen.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[29] *}
+
+### Es testen { #check-it }
+
+Sobald Sie auf [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) gehen, werden Sie sehen, dass Ihr benutzerdefiniertes Logo verwendet wird (in diesem Beispiel das Logo von **FastAPI**):
+
+
diff --git a/docs/de/docs/how-to/general.md b/docs/de/docs/how-to/general.md
new file mode 100644
index 0000000000000..593b79d3b4222
--- /dev/null
+++ b/docs/de/docs/how-to/general.md
@@ -0,0 +1,43 @@
+# Allgemeines – How-To – Rezepte { #general-how-to-recipes }
+
+Hier finden Sie mehrere Verweise auf andere Stellen in der Dokumentation, für allgemeine oder häufige Fragen.
+
+## Daten filtern – Sicherheit { #filter-data-security }
+
+Um sicherzustellen, dass Sie nicht mehr Daten zurückgeben, als Sie sollten, lesen Sie die Dokumentation unter [Tutorial – Responsemodell – Rückgabetyp](../tutorial/response-model.md).
+
+## Response-Leistung optimieren – Responsemodell – Rückgabetyp { #optimize-response-performance-response-model-return-type }
+
+Um die Leistung beim Zurückgeben von JSON-Daten zu optimieren, verwenden Sie einen Rückgabetyp oder ein Responsemodell. So übernimmt Pydantic die Serialisierung zu JSON auf der Rust-Seite, ohne den Umweg über Python. Mehr dazu in der Dokumentation unter [Tutorial – Responsemodell – Rückgabetyp](../tutorial/response-model.md).
+
+## Dokumentations-Tags – OpenAPI { #documentation-tags-openapi }
+
+Um Tags zu Ihren *Pfadoperationen* hinzuzufügen und diese in der Oberfläche der Dokumentation zu gruppieren, lesen Sie die Dokumentation unter [Tutorial – Pfadoperation-Konfiguration – Tags](../tutorial/path-operation-configuration.md#tags).
+
+## Zusammenfassung und Beschreibung in der Dokumentation – OpenAPI { #documentation-summary-and-description-openapi }
+
+Um Ihren *Pfadoperationen* eine Zusammenfassung und Beschreibung hinzuzufügen und diese in der Oberfläche der Dokumentation anzuzeigen, lesen Sie die Dokumentation unter [Tutorial – Pfadoperation-Konfiguration – Zusammenfassung und Beschreibung](../tutorial/path-operation-configuration.md#summary-and-description).
+
+## Beschreibung der Response in der Dokumentation – OpenAPI { #documentation-response-description-openapi }
+
+Um die Beschreibung der Response zu definieren, welche in der Oberfläche der Dokumentation angezeigt wird, lesen Sie die Dokumentation unter [Tutorial – Pfadoperation-Konfiguration – Beschreibung der Response](../tutorial/path-operation-configuration.md#response-description).
+
+## *Pfadoperation* in der Dokumentation deprecaten – OpenAPI { #documentation-deprecate-a-path-operation-openapi }
+
+Um eine *Pfadoperation* zu deprecaten und das in der Oberfläche der Dokumentation anzuzeigen, lesen Sie die Dokumentation unter [Tutorial – Pfadoperation-Konfiguration – Deprecaten](../tutorial/path-operation-configuration.md#deprecate-a-path-operation).
+
+## Daten in etwas JSON-kompatibles konvertieren { #convert-any-data-to-json-compatible }
+
+Um Daten in etwas JSON-kompatibles zu konvertieren, lesen Sie die Dokumentation unter [Tutorial – JSON-kompatibler Encoder](../tutorial/encoder.md).
+
+## OpenAPI-Metadaten – Dokumentation { #openapi-metadata-docs }
+
+Um Metadaten zu Ihrem OpenAPI-Schema hinzuzufügen, einschließlich einer Lizenz, Version, Kontakt, usw., lesen Sie die Dokumentation unter [Tutorial – Metadaten und URLs der Dokumentation](../tutorial/metadata.md).
+
+## Benutzerdefinierte OpenAPI-URL { #openapi-custom-url }
+
+Um die OpenAPI-URL anzupassen (oder zu entfernen), lesen Sie die Dokumentation unter [Tutorial – Metadaten und URLs der Dokumentation](../tutorial/metadata.md#openapi-url).
+
+## URLs der OpenAPI-Dokumentationen { #openapi-docs-urls }
+
+Um die URLs zu aktualisieren, die für die automatisch generierten Dokumentations-Oberflächen verwendet werden, lesen Sie die Dokumentation unter [Tutorial – Metadaten und URLs der Dokumentation](../tutorial/metadata.md#docs-urls).
diff --git a/docs/de/docs/how-to/graphql.md b/docs/de/docs/how-to/graphql.md
new file mode 100644
index 0000000000000..bf1490f7075b1
--- /dev/null
+++ b/docs/de/docs/how-to/graphql.md
@@ -0,0 +1,60 @@
+# GraphQL { #graphql }
+
+Da **FastAPI** auf dem **ASGI**-Standard basiert, ist es sehr einfach, jede **GraphQL**-Bibliothek zu integrieren, die auch mit ASGI kompatibel ist.
+
+Sie können normale FastAPI-*Pfadoperationen* mit GraphQL in derselben Anwendung kombinieren.
+
+/// tip | Tipp
+
+**GraphQL** löst einige sehr spezifische Anwendungsfälle.
+
+Es hat **Vorteile** und **Nachteile** im Vergleich zu gängigen **Web-APIs**.
+
+Stellen Sie sicher, dass Sie prüfen, ob die **Vorteile** für Ihren Anwendungsfall die **Nachteile** ausgleichen. 🤓
+
+///
+
+## GraphQL-Bibliotheken { #graphql-libraries }
+
+Hier sind einige der **GraphQL**-Bibliotheken, die **ASGI**-Unterstützung haben. Sie könnten sie mit **FastAPI** verwenden:
+
+* [Strawberry](https://strawberry.rocks/) 🍓
+ * Mit [Dokumentation für FastAPI](https://strawberry.rocks/docs/integrations/fastapi)
+* [Ariadne](https://ariadnegraphql.org/)
+ * Mit [Dokumentation für FastAPI](https://ariadnegraphql.org/docs/fastapi-integration)
+* [Tartiflette](https://tartiflette.io/)
+ * Mit [Tartiflette ASGI](https://tartiflette.github.io/tartiflette-asgi/) für ASGI-Integration
+* [Graphene](https://graphene-python.org/)
+ * Mit [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3)
+
+## GraphQL mit Strawberry { #graphql-with-strawberry }
+
+Wenn Sie mit **GraphQL** arbeiten möchten oder müssen, ist [**Strawberry**](https://strawberry.rocks/) die **empfohlene** Bibliothek, da deren Design **FastAPIs** Design am nächsten kommt und alles auf **Typannotationen** basiert.
+
+Abhängig von Ihrem Anwendungsfall könnten Sie eine andere Bibliothek vorziehen, aber wenn Sie mich fragen würden, würde ich Ihnen wahrscheinlich empfehlen, **Strawberry** auszuprobieren.
+
+Hier ist eine kleine Vorschau, wie Sie Strawberry mit FastAPI integrieren können:
+
+{* ../../docs_src/graphql_/tutorial001_py310.py hl[3,22,25] *}
+
+Weitere Informationen zu Strawberry finden Sie in der [Strawberry-Dokumentation](https://strawberry.rocks/).
+
+Und auch in der Dokumentation zu [Strawberry mit FastAPI](https://strawberry.rocks/docs/integrations/fastapi).
+
+## Ältere `GraphQLApp` von Starlette { #older-graphqlapp-from-starlette }
+
+Frühere Versionen von Starlette enthielten eine `GraphQLApp`-Klasse zur Integration mit [Graphene](https://graphene-python.org/).
+
+Das wurde von Starlette deprecatet, aber wenn Sie Code haben, der das verwendet, können Sie einfach zu [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3) **migrieren**, das denselben Anwendungsfall abdeckt und eine **fast identische Schnittstelle** hat.
+
+/// tip | Tipp
+
+Wenn Sie GraphQL benötigen, würde ich Ihnen trotzdem empfehlen, sich [Strawberry](https://strawberry.rocks/) anzuschauen, da es auf Typannotationen basiert, statt auf benutzerdefinierten Klassen und Typen.
+
+///
+
+## Mehr darüber lernen { #learn-more }
+
+Weitere Informationen zu **GraphQL** finden Sie in der [offiziellen GraphQL-Dokumentation](https://graphql.org/).
+
+Sie können auch mehr über jede der oben beschriebenen Bibliotheken in den jeweiligen Links lesen.
diff --git a/docs/de/docs/how-to/index.md b/docs/de/docs/how-to/index.md
new file mode 100644
index 0000000000000..c46bbfbdce183
--- /dev/null
+++ b/docs/de/docs/how-to/index.md
@@ -0,0 +1,13 @@
+# How-To – Rezepte { #how-to-recipes }
+
+Hier finden Sie verschiedene Rezepte und „How-To“-Anleitungen zu **verschiedenen Themen**.
+
+Die meisten dieser Ideen sind mehr oder weniger **unabhängig**, und in den meisten Fällen müssen Sie diese nur studieren, wenn sie direkt auf **Ihr Projekt** anwendbar sind.
+
+Wenn etwas für Ihr Projekt interessant und nützlich erscheint, lesen Sie es, andernfalls überspringen Sie es einfach.
+
+/// tip | Tipp
+
+Wenn Sie strukturiert **FastAPI lernen** möchten (empfohlen), lesen Sie stattdessen Kapitel für Kapitel das [Tutorial – Benutzerhandbuch](../tutorial/index.md).
+
+///
diff --git a/docs/de/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/de/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
new file mode 100644
index 0000000000000..c252b3e0f2497
--- /dev/null
+++ b/docs/de/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -0,0 +1,135 @@
+# Von Pydantic v1 zu Pydantic v2 migrieren { #migrate-from-pydantic-v1-to-pydantic-v2 }
+
+Wenn Sie eine ältere FastAPI-App haben, nutzen Sie möglicherweise Pydantic Version 1.
+
+FastAPI Version 0.100.0 unterstützte sowohl Pydantic v1 als auch v2. Es verwendete, was auch immer Sie installiert hatten.
+
+FastAPI Version 0.119.0 führte eine teilweise Unterstützung für Pydantic v1 innerhalb von Pydantic v2 (als `pydantic.v1`) ein, um die Migration zu v2 zu erleichtern.
+
+FastAPI 0.126.0 entfernte die Unterstützung für Pydantic v1, während `pydantic.v1` noch eine Weile unterstützt wurde.
+
+/// warning | Achtung
+
+Das Pydantic-Team hat die Unterstützung für Pydantic v1 in den neuesten Python-Versionen eingestellt, beginnend mit **Python 3.14**.
+
+Dies schließt `pydantic.v1` ein, das unter Python 3.14 und höher nicht mehr unterstützt wird.
+
+Wenn Sie die neuesten Features von Python nutzen möchten, müssen Sie sicherstellen, dass Sie Pydantic v2 verwenden.
+
+///
+
+Wenn Sie eine ältere FastAPI-App mit Pydantic v1 haben, zeige ich Ihnen hier, wie Sie sie zu Pydantic v2 migrieren, und die **Features in FastAPI 0.119.0**, die Ihnen bei einer schrittweisen Migration helfen.
+
+## Offizieller Leitfaden { #official-guide }
+
+Pydantic hat einen offiziellen [Migrationsleitfaden](https://docs.pydantic.dev/latest/migration/) von v1 zu v2.
+
+Er enthält auch, was sich geändert hat, wie Validierungen nun korrekter und strikter sind, mögliche Stolpersteine, usw.
+
+Sie können ihn lesen, um besser zu verstehen, was sich geändert hat.
+
+## Tests { #tests }
+
+Stellen Sie sicher, dass Sie [Tests](../tutorial/testing.md) für Ihre App haben und diese in Continuous Integration (CI) ausführen.
+
+Auf diese Weise können Sie das Update durchführen und sicherstellen, dass weiterhin alles wie erwartet funktioniert.
+
+## `bump-pydantic` { #bump-pydantic }
+
+In vielen Fällen, wenn Sie reguläre Pydantic-Modelle ohne Anpassungen verwenden, können Sie den Großteil des Prozesses der Migration von Pydantic v1 auf Pydantic v2 automatisieren.
+
+Sie können [`bump-pydantic`](https://github.com/pydantic/bump-pydantic) vom selben Pydantic-Team verwenden.
+
+Dieses Tool hilft Ihnen, den Großteil des zu ändernden Codes automatisch anzupassen.
+
+Danach können Sie die Tests ausführen und prüfen, ob alles funktioniert. Falls ja, sind Sie fertig. 😎
+
+## Pydantic v1 in v2 { #pydantic-v1-in-v2 }
+
+Pydantic v2 enthält alles aus Pydantic v1 als Untermodul `pydantic.v1`. Dies wird aber in Versionen oberhalb von Python 3.13 nicht mehr unterstützt.
+
+Das bedeutet, Sie können die neueste Version von Pydantic v2 installieren und die alten Pydantic‑v1‑Komponenten aus diesem Untermodul importieren und verwenden, als hätten Sie das alte Pydantic v1 installiert.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}
+
+### FastAPI-Unterstützung für Pydantic v1 in v2 { #fastapi-support-for-pydantic-v1-in-v2 }
+
+Seit FastAPI 0.119.0 gibt es außerdem eine teilweise Unterstützung für Pydantic v1 innerhalb von Pydantic v2, um die Migration auf v2 zu erleichtern.
+
+Sie könnten also Pydantic auf die neueste Version 2 aktualisieren und die Importe so ändern, dass das Untermodul `pydantic.v1` verwendet wird, und in vielen Fällen würde es einfach funktionieren.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py hl[2,5,15] *}
+
+/// warning | Achtung
+
+Beachten Sie, dass, da das Pydantic‑Team Pydantic v1 in neueren Python‑Versionen nicht mehr unterstützt, beginnend mit Python 3.14, auch die Verwendung von `pydantic.v1` unter Python 3.14 und höher nicht unterstützt wird.
+
+///
+
+### Pydantic v1 und v2 in derselben App { #pydantic-v1-and-v2-on-the-same-app }
+
+Es wird von Pydantic **nicht unterstützt**, dass ein Pydantic‑v2‑Modell Felder hat, die als Pydantic‑v1‑Modelle definiert sind, und umgekehrt.
+
+```mermaid
+graph TB
+ subgraph "❌ Nicht unterstützt"
+ direction TB
+ subgraph V2["Pydantic-v2-Modell"]
+ V1Field["Pydantic-v1-Modell"]
+ end
+ subgraph V1["Pydantic-v1-Modell"]
+ V2Field["Pydantic-v2-Modell"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+... aber Sie können getrennte Modelle, die Pydantic v1 bzw. v2 nutzen, in derselben App verwenden.
+
+```mermaid
+graph TB
+ subgraph "✅ Unterstützt"
+ direction TB
+ subgraph V2["Pydantic-v2-Modell"]
+ V2Field["Pydantic-v2-Modell"]
+ end
+ subgraph V1["Pydantic-v1-Modell"]
+ V1Field["Pydantic-v1-Modell"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+In einigen Fällen ist es sogar möglich, sowohl Pydantic‑v1‑ als auch Pydantic‑v2‑Modelle in derselben **Pfadoperation** Ihrer FastAPI‑App zu verwenden:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}
+
+Im obigen Beispiel ist das Eingabemodell ein Pydantic‑v1‑Modell, und das Ausgabemodell (definiert in `response_model=ItemV2`) ist ein Pydantic‑v2‑Modell.
+
+### Pydantic v1 Parameter { #pydantic-v1-parameters }
+
+Wenn Sie einige der FastAPI-spezifischen Tools für Parameter wie `Body`, `Query`, `Form`, usw. zusammen mit Pydantic‑v1‑Modellen verwenden müssen, können Sie die aus `fastapi.temp_pydantic_v1_params` importieren, während Sie die Migration zu Pydantic v2 abschließen:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py hl[4,18] *}
+
+### In Schritten migrieren { #migrate-in-steps }
+
+/// tip | Tipp
+
+Probieren Sie zuerst `bump-pydantic` aus. Wenn Ihre Tests erfolgreich sind und das funktioniert, sind Sie mit einem einzigen Befehl fertig. ✨
+
+///
+
+Wenn `bump-pydantic` für Ihren Anwendungsfall nicht funktioniert, können Sie die Unterstützung für Pydantic‑v1‑ und Pydantic‑v2‑Modelle in derselben App nutzen, um die Migration zu Pydantic v2 schrittweise durchzuführen.
+
+Sie könnten zuerst Pydantic auf die neueste Version 2 aktualisieren und die Importe so ändern, dass für all Ihre Modelle `pydantic.v1` verwendet wird.
+
+Anschließend können Sie beginnen, Ihre Modelle gruppenweise von Pydantic v1 auf v2 zu migrieren – in kleinen, schrittweisen Etappen. 🚶
diff --git a/docs/de/docs/how-to/separate-openapi-schemas.md b/docs/de/docs/how-to/separate-openapi-schemas.md
new file mode 100644
index 0000000000000..16f9c8a144c0f
--- /dev/null
+++ b/docs/de/docs/how-to/separate-openapi-schemas.md
@@ -0,0 +1,102 @@
+# Separate OpenAPI-Schemas für Eingabe und Ausgabe oder nicht { #separate-openapi-schemas-for-input-and-output-or-not }
+
+Seit der Veröffentlichung von **Pydantic v2** ist die generierte OpenAPI etwas genauer und **korrekter** als zuvor. 😎
+
+Tatsächlich gibt es in einigen Fällen sogar **zwei JSON-Schemas** in OpenAPI für dasselbe Pydantic-Modell, für Eingabe und Ausgabe, je nachdem, ob sie **Defaultwerte** haben.
+
+Sehen wir uns an, wie das funktioniert und wie Sie es bei Bedarf ändern können.
+
+## Pydantic-Modelle für Eingabe und Ausgabe { #pydantic-models-for-input-and-output }
+
+Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *}
+
+### Modell für Eingabe { #model-for-input }
+
+Wenn Sie dieses Modell wie hier als Eingabe verwenden:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *}
+
+... dann ist das Feld `description` **nicht erforderlich**. Weil es den Defaultwert `None` hat.
+
+### Eingabemodell in der Dokumentation { #input-model-in-docs }
+
+Sie können überprüfen, dass das Feld `description` in der Dokumentation kein **rotes Sternchen** enthält, es ist nicht als erforderlich markiert:
+
+
+
+
+
+
++ FastAPI-Framework, hohe Performanz, leicht zu lernen, schnell zu entwickeln, produktionsreif +
+ + +--- + +**Dokumentation**: [https://fastapi.tiangolo.com/de](https://fastapi.tiangolo.com/de) + +**Quellcode**: [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi) + +--- + +FastAPI ist ein modernes, schnelles (hoch performantes) Webframework zur Erstellung von APIs mit Python auf Basis von Standard-Python-Typhinweisen. + +Seine Schlüssel-Merkmale sind: + +* **Schnell**: Sehr hohe Performanz, auf Augenhöhe mit **NodeJS** und **Go** (dank Starlette und Pydantic). [Eines der schnellsten verfügbaren Python-Frameworks](#performance). +* **Schnell zu entwickeln**: Erhöhen Sie die Geschwindigkeit bei der Entwicklung von Features um etwa 200 % bis 300 %. * +* **Weniger Bugs**: Verringern Sie die von Menschen (Entwicklern) verursachten Fehler um etwa 40 %. * +* **Intuitiv**: Hervorragende Editor-Unterstützung. Code-Vervollständigung überall. Weniger Zeit mit Debuggen verbringen. +* **Einfach**: So konzipiert, dass es einfach zu benutzen und zu erlernen ist. Weniger Zeit mit dem Lesen von Dokumentation verbringen. +* **Kurz**: Minimieren Sie die Verdoppelung von Code. Mehrere Features aus jeder Parameterdeklaration. Weniger Bugs. +* **Robust**: Erhalten Sie produktionsreifen Code. Mit automatischer, interaktiver Dokumentation. +* **Standards-basiert**: Basierend auf (und vollständig kompatibel mit) den offenen Standards für APIs: [OpenAPI](https://github.com/OAI/OpenAPI-Specification) (früher bekannt als Swagger) und [JSON Schema](https://json-schema.org/). + +* Schätzung basierend auf Tests, die von einem internen Entwicklungsteam durchgeführt wurden, das Produktionsanwendungen erstellt. + +## Sponsoren { #sponsors } + + + +### Keystone-Sponsor { #keystone-sponsor } + +{% for sponsor in sponsors.keystone -%} +
+
+## **Typer**, das FastAPI der CLIs { #typer-the-fastapi-of-clis }
+
+async def ...fastapi dev ...
+
+### Typen hinzufügen { #add-types }
+
+Lassen Sie uns eine einzelne Zeile aus der vorherigen Version ändern.
+
+Wir ändern den folgenden Teil, die Parameter der Funktion, von:
+
+```Python
+ first_name, last_name
+```
+
+zu:
+
+```Python
+ first_name: str, last_name: str
+```
+
+Das war's.
+
+Das sind die „Typhinweise“:
+
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
+
+Das ist nicht das gleiche wie das Deklarieren von Defaultwerten, wie es hier der Fall ist:
+
+```Python
+ first_name="john", last_name="doe"
+```
+
+Das ist eine andere Sache.
+
+Wir verwenden Doppelpunkte (`:`), nicht Gleichheitszeichen (`=`).
+
+Und das Hinzufügen von Typhinweisen ändert normalerweise nichts an dem, was ohne sie passieren würde.
+
+Aber jetzt stellen Sie sich vor, Sie sind wieder mitten in der Erstellung dieser Funktion, aber mit Typhinweisen.
+
+An derselben Stelle versuchen Sie, die Autovervollständigung mit „Strg+Leertaste“ auszulösen, und Sie sehen:
+
+
+
+Hier können Sie durch die Optionen blättern, bis Sie diejenige finden, bei der es „Klick“ macht:
+
+
+
+## Mehr Motivation { #more-motivation }
+
+Sehen Sie sich diese Funktion an, sie hat bereits Typhinweise:
+
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
+
+Da der Editor die Typen der Variablen kennt, erhalten Sie nicht nur Code-Vervollständigung, sondern auch eine Fehlerprüfung:
+
+
+
+Jetzt, da Sie wissen, dass Sie das reparieren müssen, konvertieren Sie `age` mittels `str(age)` in einen String:
+
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
+
+## Deklarieren von Typen { #declaring-types }
+
+Sie haben gerade den Haupt-Einsatzort für die Deklaration von Typhinweisen gesehen. Als Funktionsparameter.
+
+Das ist auch meistens, wie sie in **FastAPI** verwendet werden.
+
+### Einfache Typen { #simple-types }
+
+Sie können alle Standard-Python-Typen deklarieren, nicht nur `str`.
+
+Zum Beispiel diese:
+
+* `int`
+* `float`
+* `bool`
+* `bytes`
+
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
+
+### `typing`-Modul { #typing-module }
+
+Für einige zusätzliche Anwendungsfälle müssen Sie möglicherweise Dinge aus dem Standardmodul `typing` importieren. Zum Beispiel, wenn Sie deklarieren möchten, dass etwas „jeden Typ“ haben kann, können Sie `Any` aus `typing` verwenden:
+
+```python
+from typing import Any
+
+
+def some_function(data: Any):
+ print(data)
+```
+
+### Generische Typen { #generic-types }
+
+Einige Typen können „Typ-Parameter“ in eckigen Klammern annehmen, um ihre inneren Typen zu definieren, z. B. eine „Liste von Strings“ würde als `list[str]` deklariert.
+
+Diese Typen, die Typ-Parameter annehmen können, werden **generische Typen** oder **Generics** genannt.
+
+Sie können dieselben eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin):
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
+
+#### Liste { #list }
+
+Definieren wir zum Beispiel eine Variable, die eine `list` von `str` – eine Liste von Strings – sein soll.
+
+Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`).
+
+Als Typ nehmen Sie `list`.
+
+Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst:
+
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
+
+/// info | Info
+
+Die inneren Typen in den eckigen Klammern werden als „Typ-Parameter“ bezeichnet.
+
+In diesem Fall ist `str` der Typ-Parameter, der an `list` übergeben wird.
+
+///
+
+Das bedeutet: Die Variable `items` ist eine Liste – `list` – und jedes der Elemente in dieser Liste ist ein String – `str`.
+
+Auf diese Weise kann Ihr Editor Sie auch bei der Bearbeitung von Einträgen aus der Liste unterstützen:
+
+
+
+Ohne Typen ist das fast unmöglich zu erreichen.
+
+Beachten Sie, dass die Variable `item` eines der Elemente in der Liste `items` ist.
+
+Und trotzdem weiß der Editor, dass es sich um ein `str` handelt, und bietet entsprechende Unterstützung.
+
+#### Tupel und Menge { #tuple-and-set }
+
+Das Gleiche gilt für die Deklaration eines Tupels – `tuple` – und einer Menge – `set`:
+
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
+
+Das bedeutet:
+
+* Die Variable `items_t` ist ein `tuple` mit 3 Elementen, einem `int`, einem weiteren `int` und einem `str`.
+* Die Variable `items_s` ist ein `set`, und jedes seiner Elemente ist vom Typ `bytes`.
+
+#### Dict { #dict }
+
+Um ein `dict` zu definieren, übergeben Sie zwei Typ-Parameter, getrennt durch Kommas.
+
+Der erste Typ-Parameter ist für die Schlüssel des `dict`.
+
+Der zweite Typ-Parameter ist für die Werte des `dict`:
+
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
+
+Das bedeutet:
+
+* Die Variable `prices` ist ein `dict`:
+ * Die Schlüssel dieses `dict` sind vom Typ `str` (z. B. die Namen der einzelnen Artikel).
+ * Die Werte dieses `dict` sind vom Typ `float` (z. B. der Preis jedes Artikels).
+
+#### Union { #union }
+
+Sie können deklarieren, dass eine Variable einer von **verschiedenen Typen** sein kann, zum Beispiel ein `int` oder ein `str`.
+
+Um das zu definieren, verwenden Sie den vertikalen Balken (`|`), um beide Typen zu trennen.
+
+Das wird „Union“ genannt, weil die Variable etwas aus der Vereinigung dieser beiden Typmengen sein kann.
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
+```
+
+Das bedeutet, dass `item` ein `int` oder ein `str` sein könnte.
+
+#### Vielleicht `None` { #possibly-none }
+
+Sie können deklarieren, dass ein Wert einen Typ haben könnte, wie `str`, dass er aber auch `None` sein könnte.
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
+
+////
+
+Wenn Sie `str | None` anstelle von nur `str` verwenden, wird Ihr Editor Ihnen dabei helfen, Fehler zu erkennen, bei denen Sie annehmen könnten, dass ein Wert immer ein `str` ist, obwohl er auch `None` sein könnte.
+
+### Klassen als Typen { #classes-as-types }
+
+Sie können auch eine Klasse als Typ einer Variablen deklarieren.
+
+Nehmen wir an, Sie haben eine Klasse `Person`, mit einem Namen:
+
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
+
+Dann können Sie eine Variable vom Typ `Person` deklarieren:
+
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
+
+Und wiederum bekommen Sie die volle Editor-Unterstützung:
+
+
+
+Beachten Sie, das bedeutet: „`one_person` ist eine **Instanz** der Klasse `Person`“.
+
+Es bedeutet nicht: „`one_person` ist die **Klasse** genannt `Person`“.
+
+## Pydantic-Modelle { #pydantic-models }
+
+[Pydantic](https://docs.pydantic.dev/) ist eine Python-Bibliothek für die Validierung von Daten.
+
+Sie deklarieren die „Form“ der Daten als Klassen mit Attributen.
+
+Und jedes Attribut hat einen Typ.
+
+Dann erzeugen Sie eine Instanz dieser Klasse mit einigen Werten, und Pydantic validiert die Werte, konvertiert sie in den passenden Typ (falls notwendig) und gibt Ihnen ein Objekt mit allen Daten.
+
+Und Sie erhalten volle Editor-Unterstützung für dieses Objekt.
+
+Ein Beispiel aus der offiziellen Pydantic Dokumentation:
+
+{* ../../docs_src/python_types/tutorial011_py310.py *}
+
+/// info | Info
+
+Um mehr über [Pydantic zu erfahren, schauen Sie sich dessen Dokumentation an](https://docs.pydantic.dev/).
+
+///
+
+**FastAPI** basiert vollständig auf Pydantic.
+
+Viel mehr von all dem werden Sie in praktischer Anwendung im [Tutorial – Benutzerhandbuch](tutorial/index.md) sehen.
+
+## Typhinweise mit Metadaten-Annotationen { #type-hints-with-metadata-annotations }
+
+Python bietet auch die Möglichkeit, **zusätzliche Metadaten** in Typhinweisen unterzubringen, mittels `Annotated`.
+
+Sie können `Annotated` von `typing` importieren.
+
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
+
+Python selbst macht nichts mit `Annotated`. Für Editoren und andere Tools ist der Typ immer noch `str`.
+
+Aber Sie können `Annotated` nutzen, um **FastAPI** mit Metadaten zu versorgen, die ihm sagen, wie sich Ihre Anwendung verhalten soll.
+
+Wichtig ist, dass **der erste *Typ-Parameter***, den Sie `Annotated` übergeben, der **tatsächliche Typ** ist. Der Rest sind Metadaten für andere Tools.
+
+Im Moment müssen Sie nur wissen, dass `Annotated` existiert, und dass es Standard-Python ist. 😎
+
+Später werden Sie sehen, wie **mächtig** es sein kann.
+
+/// tip | Tipp
+
+Der Umstand, dass es **Standard-Python** ist, bedeutet, dass Sie immer noch die **bestmögliche Entwickler-Erfahrung** in Ihrem Editor haben, sowie mit den Tools, die Sie nutzen, um Ihren Code zu analysieren, zu refaktorisieren, usw. ✨
+
+Und ebenfalls, dass Ihr Code sehr kompatibel mit vielen anderen Python-Tools und -Bibliotheken sein wird. 🚀
+
+///
+
+## Typhinweise in **FastAPI** { #type-hints-in-fastapi }
+
+**FastAPI** macht sich diese Typhinweise zunutze, um mehrere Dinge zu tun.
+
+Mit **FastAPI** deklarieren Sie Parameter mit Typhinweisen, und Sie erhalten:
+
+* **Editorunterstützung**.
+* **Typ-Prüfungen**.
+
+... und **FastAPI** verwendet dieselben Deklarationen, um:
+
+* **Anforderungen** zu definieren: aus Request-Pfadparametern, Query-Parametern, Headern, Bodys, Abhängigkeiten, usw.
+* **Daten umzuwandeln**: aus dem Request in den erforderlichen Typ.
+* **Daten zu validieren**: aus jedem Request:
+ * **Automatische Fehler** generieren, die an den Client zurückgegeben werden, wenn die Daten ungültig sind.
+* Die API mit OpenAPI zu **dokumentieren**:
+ * Die dann von den Benutzeroberflächen der automatisch generierten interaktiven Dokumentation verwendet wird.
+
+Das mag alles abstrakt klingen. Machen Sie sich keine Sorgen. Sie werden all das in Aktion sehen im [Tutorial – Benutzerhandbuch](tutorial/index.md).
+
+Das Wichtigste ist, dass **FastAPI** durch die Verwendung von Standard-Python-Typen an einer einzigen Stelle (anstatt weitere Klassen, Dekoratoren usw. hinzuzufügen) einen Großteil der Arbeit für Sie erledigt.
+
+/// info | Info
+
+Wenn Sie bereits das ganze Tutorial durchgearbeitet haben und mehr über Typen erfahren wollen, dann ist eine gute Ressource [der „Cheat Sheet“ von `mypy`](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html).
+
+///
diff --git a/docs/de/docs/resources/index.md b/docs/de/docs/resources/index.md
new file mode 100644
index 0000000000000..52b32b148023e
--- /dev/null
+++ b/docs/de/docs/resources/index.md
@@ -0,0 +1,3 @@
+# Ressourcen { #resources }
+
+Zusätzliche Ressourcen, externe Links und mehr. ✈️
diff --git a/docs/de/docs/translation-banner.md b/docs/de/docs/translation-banner.md
new file mode 100644
index 0000000000000..1801a019046e3
--- /dev/null
+++ b/docs/de/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 Übersetzung durch KI und Menschen
+
+Diese Übersetzung wurde von KI erstellt, angeleitet von Menschen. 🤝
+
+Sie könnte Fehler enthalten, etwa Missverständnisse des ursprünglichen Sinns oder unnatürliche Formulierungen, usw. 🤖
+
+Sie können diese Übersetzung verbessern, indem Sie [uns helfen, die KI-LLM besser anzuleiten](https://fastapi.tiangolo.com/de/contributing/#translations).
+
+[Englische Version](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/de/docs/tutorial/background-tasks.md b/docs/de/docs/tutorial/background-tasks.md
new file mode 100644
index 0000000000000..7d6c35a1c0170
--- /dev/null
+++ b/docs/de/docs/tutorial/background-tasks.md
@@ -0,0 +1,86 @@
+# Hintergrundtasks { #background-tasks }
+
+Sie können Hintergrundtasks 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 { #using-backgroundtasks }
+
+Importieren Sie zunächst `BackgroundTasks` und definieren Sie einen Parameter in Ihrer *Pfadoperation-Funktion* mit der Typdeklaration `BackgroundTasks`:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
+
+**FastAPI** erstellt für Sie das Objekt vom Typ `BackgroundTasks` und übergibt es als diesen Parameter.
+
+## Eine Taskfunktion erstellen { #create-a-task-function }
+
+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`:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
+
+## Den Hintergrundtask hinzufügen { #add-the-background-task }
+
+Übergeben Sie innerhalb Ihrer *Pfadoperation-Funktion* Ihre Taskfunktion mit der Methode `.add_task()` an das *Hintergrundtasks*-Objekt:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
+
+`.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 { #dependency-injection }
+
+Die Verwendung von `BackgroundTasks` funktioniert auch mit dem Dependency Injection 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:
+
+
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
+
+
+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 { #technical-details }
+
+Die Klasse `BackgroundTasks` stammt direkt von [`starlette.background`](https://www.starlette.dev/background/).
+
+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 [Starlettes offizieller Dokumentation für Hintergrundtasks](https://www.starlette.dev/background/).
+
+## Vorbehalt { #caveat }
+
+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. [Celery](https://docs.celeryq.dev) 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.
+
+Wenn Sie jedoch über dieselbe **FastAPI**-App 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 { #recap }
+
+Importieren und verwenden Sie `BackgroundTasks` mit Parametern in *Pfadoperation-Funktionen* und Abhängigkeiten, um Hintergrundtasks hinzuzufügen.
diff --git a/docs/de/docs/tutorial/bigger-applications.md b/docs/de/docs/tutorial/bigger-applications.md
new file mode 100644
index 0000000000000..b74c5ee5a7e8c
--- /dev/null
+++ b/docs/de/docs/tutorial/bigger-applications.md
@@ -0,0 +1,535 @@
+# Größere Anwendungen – mehrere Dateien { #bigger-applications-multiple-files }
+
+Wenn Sie eine Anwendung oder eine Web-API erstellen, ist es selten der Fall, dass Sie alles in einer einzigen Datei unterbringen können.
+
+**FastAPI** bietet ein praktisches Werkzeug zur Strukturierung Ihrer Anwendung bei gleichzeitiger Wahrung der Flexibilität.
+
+/// info | Info
+
+Wenn Sie von Flask kommen, wäre dies das Äquivalent zu Flasks Blueprints.
+
+///
+
+## Eine Beispiel-Dateistruktur { #an-example-file-structure }
+
+Nehmen wir an, Sie haben eine Dateistruktur wie diese:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ ├── dependencies.py
+│ └── routers
+│ │ ├── __init__.py
+│ │ ├── items.py
+│ │ └── users.py
+│ └── internal
+│ ├── __init__.py
+│ └── admin.py
+```
+
+/// tip | Tipp
+
+Es gibt mehrere `__init__.py`-Dateien: eine in jedem Verzeichnis oder Unterverzeichnis.
+
+Das ermöglicht den Import von Code aus einer Datei in eine andere.
+
+In `app/main.py` könnten Sie beispielsweise eine Zeile wie diese haben:
+
+```
+from app.routers import items
+```
+
+///
+
+* Das Verzeichnis `app` enthält alles. Und es hat eine leere Datei `app/__init__.py`, es handelt sich also um ein „Python-Package“ (eine Sammlung von „Python-Modulen“): `app`.
+* Es enthält eine Datei `app/main.py`. Da sie sich in einem Python-Package (einem Verzeichnis mit einer Datei `__init__.py`) befindet, ist sie ein „Modul“ dieses Packages: `app.main`.
+* Es gibt auch eine Datei `app/dependencies.py`, genau wie `app/main.py` ist sie ein „Modul“: `app.dependencies`.
+* Es gibt ein Unterverzeichnis `app/routers/` mit einer weiteren Datei `__init__.py`, es handelt sich also um ein „Python-Subpackage“: `app.routers`.
+* Die Datei `app/routers/items.py` befindet sich in einem Package, `app/routers/`, also ist sie ein Submodul: `app.routers.items`.
+* Das Gleiche gilt für `app/routers/users.py`, es ist ein weiteres Submodul: `app.routers.users`.
+* Es gibt auch ein Unterverzeichnis `app/internal/` mit einer weiteren Datei `__init__.py`, es handelt sich also um ein weiteres „Python-Subpackage“: `app.internal`.
+* Und die Datei `app/internal/admin.py` ist ein weiteres Submodul: `app.internal.admin`.
+
+
+
+## Den gleichen Router mehrmals mit unterschiedlichem `prefix` inkludieren { #include-the-same-router-multiple-times-with-different-prefix }
+
+Sie können `.include_router()` auch mehrmals mit *demselben* Router und unterschiedlichen Präfixen verwenden.
+
+Dies könnte beispielsweise nützlich sein, um dieselbe API unter verschiedenen Präfixen verfügbar zu machen, z. B. `/api/v1` und `/api/latest`.
+
+Dies ist eine fortgeschrittene Verwendung, die Sie möglicherweise nicht wirklich benötigen, aber für den Fall, dass Sie sie benötigen, ist sie vorhanden.
+
+## Einen `APIRouter` in einen anderen einfügen { #include-an-apirouter-in-another }
+
+Auf die gleiche Weise, wie Sie einen `APIRouter` in eine `FastAPI`-Anwendung einbinden können, können Sie einen `APIRouter` in einen anderen `APIRouter` einbinden, indem Sie Folgendes verwenden:
+
+```Python
+router.include_router(other_router)
+```
+
+Stellen Sie sicher, dass Sie dies tun, bevor Sie `router` in die `FastAPI`-App einbinden, damit auch die *Pfadoperationen* von `other_router` inkludiert werden.
diff --git a/docs/de/docs/tutorial/body-fields.md b/docs/de/docs/tutorial/body-fields.md
new file mode 100644
index 0000000000000..4edb22478bd31
--- /dev/null
+++ b/docs/de/docs/tutorial/body-fields.md
@@ -0,0 +1,59 @@
+# Body – Felder { #body-fields }
+
+So wie Sie zusätzliche Validierung und Metadaten in Parametern der *Pfadoperation-Funktion* mittels `Query`, `Path` und `Body` deklarieren, können Sie auch innerhalb von Pydantic-Modellen zusätzliche Validierung und Metadaten deklarieren, mittels Pydantics `Field`.
+
+## `Field` importieren { #import-field }
+
+Importieren Sie es zuerst:
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}
+
+/// warning | Achtung
+
+Beachten Sie, dass `Field` direkt von `pydantic` importiert wird, nicht von `fastapi`, wie die anderen (`Query`, `Path`, `Body`, usw.)
+
+///
+
+## Modellattribute deklarieren { #declare-model-attributes }
+
+Dann können Sie `Field` mit Modellattributen deklarieren:
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}
+
+`Field` funktioniert genauso wie `Query`, `Path` und `Body`, es hat die gleichen Parameter, usw.
+
+/// note | Technische Details
+
+Tatsächlich erstellen `Query`, `Path` und andere, die Sie als nächstes sehen werden, Instanzen von Unterklassen einer allgemeinen Klasse `Param`, welche selbst eine Unterklasse von Pydantics `FieldInfo`-Klasse ist.
+
+Und Pydantics `Field` gibt ebenfalls eine Instanz von `FieldInfo` zurück.
+
+`Body` gibt auch direkt Instanzen einer Unterklasse von `FieldInfo` zurück. Später werden Sie andere sehen, die Unterklassen der `Body`-Klasse sind.
+
+Denken Sie daran, dass `Query`, `Path` und andere, wenn Sie sie von `fastapi` importieren, tatsächlich Funktionen sind, die spezielle Klassen zurückgeben.
+
+///
+
+/// tip | Tipp
+
+Beachten Sie, wie jedes Attribut eines Modells mit einem Typ, Defaultwert und `Field` die gleiche Struktur hat wie ein Parameter einer *Pfadoperation-Funktion*, nur mit `Field` statt `Path`, `Query`, `Body`.
+
+///
+
+## Zusätzliche Information hinzufügen { #add-extra-information }
+
+Sie können zusätzliche Information in `Field`, `Query`, `Body`, usw. deklarieren. Und es wird im generierten JSON-Schema untergebracht.
+
+Sie werden später in der Dokumentation mehr darüber lernen, wie man zusätzliche Information unterbringt, wenn Sie lernen, Beispiele zu deklarieren.
+
+/// warning | Achtung
+
+Extra-Schlüssel, die `Field` überreicht werden, werden auch im resultierenden OpenAPI-Schema Ihrer Anwendung gelistet. Da diese Schlüssel möglicherweise nicht Teil der OpenAPI-Spezifikation sind, könnten einige OpenAPI-Tools, wie etwa [der OpenAPI-Validator](https://validator.swagger.io/), nicht mit Ihrem generierten Schema funktionieren.
+
+///
+
+## Zusammenfassung { #recap }
+
+Sie können Pydantics `Field` verwenden, um zusätzliche Validierungen und Metadaten für Modellattribute zu deklarieren.
+
+Sie können auch die zusätzlichen Schlüsselwortargumente verwenden, um zusätzliche JSON-Schema-Metadaten zu übergeben.
diff --git a/docs/de/docs/tutorial/body-multiple-params.md b/docs/de/docs/tutorial/body-multiple-params.md
new file mode 100644
index 0000000000000..60a0ceefe05b5
--- /dev/null
+++ b/docs/de/docs/tutorial/body-multiple-params.md
@@ -0,0 +1,165 @@
+# Body – Mehrere Parameter { #body-multiple-parameters }
+
+Nun, da wir gesehen haben, wie `Path` und `Query` verwendet werden, schauen wir uns fortgeschrittenere Verwendungsmöglichkeiten von Requestbody-Deklarationen an.
+
+## `Path`-, `Query`- und Body-Parameter vermischen { #mix-path-query-and-body-parameters }
+
+Zuerst einmal, Sie können `Path`-, `Query`- und Requestbody-Parameter-Deklarationen frei mischen und **FastAPI** wird wissen, was zu tun ist.
+
+Und Sie können auch Body-Parameter als optional kennzeichnen, indem Sie den Defaultwert auf `None` setzen:
+
+{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
+
+/// note | Hinweis
+
+Beachten Sie, dass in diesem Fall das `item`, welches vom Body genommen wird, optional ist. Da es `None` als Defaultwert hat.
+
+///
+
+## Mehrere Body-Parameter { #multiple-body-parameters }
+
+Im vorherigen Beispiel erwarteten die *Pfadoperationen* einen JSON-Body mit den Attributen eines `Item`s, etwa:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+
+Aber Sie können auch mehrere Body-Parameter deklarieren, z. B. `item` und `user`:
+
+{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}
+
+In diesem Fall wird **FastAPI** bemerken, dass es mehr als einen Body-Parameter in der Funktion gibt (zwei Parameter, die Pydantic-Modelle sind).
+
+Es wird deshalb die Parameternamen als Schlüssel (Feldnamen) im Body verwenden und erwartet einen Body wie folgt:
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ }
+}
+```
+
+/// note | Hinweis
+
+Beachten Sie, dass, obwohl `item` wie zuvor deklariert wurde, es nun unter einem Schlüssel `item` im Body erwartet wird.
+
+///
+
+**FastAPI** wird die automatische Konvertierung des Requests übernehmen, sodass der Parameter `item` seinen spezifischen Inhalt bekommt, und das Gleiche gilt für den Parameter `user`.
+
+Es wird die Validierung dieser zusammengesetzten Daten übernehmen, und diese im OpenAPI-Schema und der automatischen Dokumentation dokumentieren.
+
+## Einzelne Werte im Body { #singular-values-in-body }
+
+So wie `Query` und `Path` für Query- und Pfad-Parameter, stellt **FastAPI** das Äquivalent `Body` zur Verfügung, um Extra-Daten für Body-Parameter zu definieren.
+
+Zum Beispiel, das vorherige Modell erweiternd, könnten Sie entscheiden, dass Sie einen weiteren Schlüssel `importance` im selben Body haben möchten, neben `item` und `user`.
+
+Wenn Sie diesen Parameter einfach so hinzufügen, wird **FastAPI** annehmen, dass es ein Query-Parameter ist, da er ein einzelner Wert ist.
+
+Aber Sie können **FastAPI** instruieren, ihn als weiteren Body-Schlüssel zu erkennen, indem Sie `Body` verwenden:
+
+{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
+
+In diesem Fall erwartet **FastAPI** einen Body wie:
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ },
+ "importance": 5
+}
+```
+
+Wiederum wird es die Datentypen konvertieren, validieren, dokumentieren, usw.
+
+## Mehrere Body-Parameter und Query-Parameter { #multiple-body-params-and-query }
+
+Natürlich können Sie auch, wann immer Sie das brauchen, weitere Query-Parameter hinzufügen, zusätzlich zu den Body-Parametern.
+
+Da einfache Werte standardmäßig als Query-Parameter interpretiert werden, müssen Sie `Query` nicht explizit hinzufügen, Sie können einfach schreiben:
+
+```Python
+q: str | None = None
+```
+
+Zum Beispiel:
+
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
+
+/// info | Info
+
+`Body` hat die gleichen zusätzlichen Validierungs- und Metadaten-Parameter wie `Query`, `Path` und andere, die Sie später kennenlernen werden.
+
+///
+
+## Einen einzelnen Body-Parameter einbetten { #embed-a-single-body-parameter }
+
+Nehmen wir an, Sie haben nur einen einzelnen `item`-Body-Parameter von einem Pydantic-Modell `Item`.
+
+Standardmäßig wird **FastAPI** dann seinen Body direkt erwarten.
+
+Aber wenn Sie möchten, dass es einen JSON-Body mit einem Schlüssel `item` erwartet, und darin den Inhalt des Modells, so wie es das tut, wenn Sie mehrere Body-Parameter deklarieren, dann können Sie den speziellen `Body`-Parameter `embed` setzen:
+
+```Python
+item: Item = Body(embed=True)
+```
+
+so wie in:
+
+{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}
+
+In diesem Fall erwartet **FastAPI** einen Body wie:
+
+```JSON hl_lines="2"
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ }
+}
+```
+
+statt:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+
+## Zusammenfassung { #recap }
+
+Sie können mehrere Body-Parameter zu Ihrer *Pfadoperation-Funktion* hinzufügen, obwohl ein Request nur einen einzigen Body enthalten kann.
+
+Aber **FastAPI** wird sich darum kümmern, Ihnen korrekte Daten in Ihrer Funktion zu überreichen, und das korrekte Schema in der *Pfadoperation* zu validieren und zu dokumentieren.
+
+Sie können auch einzelne Werte deklarieren, die als Teil des Bodys empfangen werden.
+
+Und Sie können **FastAPI** instruieren, den Body in einem Schlüssel unterzubringen, selbst wenn nur ein einzelner Body-Parameter deklariert ist.
diff --git a/docs/de/docs/tutorial/body-nested-models.md b/docs/de/docs/tutorial/body-nested-models.md
new file mode 100644
index 0000000000000..62f04a37da1e2
--- /dev/null
+++ b/docs/de/docs/tutorial/body-nested-models.md
@@ -0,0 +1,220 @@
+# Body – Verschachtelte Modelle { #body-nested-models }
+
+Mit **FastAPI** können Sie (dank Pydantic) beliebig tief verschachtelte Modelle definieren, validieren, dokumentieren und verwenden.
+
+## Listen als Felder { #list-fields }
+
+Sie können ein Attribut als Kindtyp definieren, zum Beispiel eine Python-`list`.
+
+{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}
+
+Das bewirkt, dass `tags` eine Liste ist, wenngleich es nichts über den Typ der Elemente der Liste aussagt.
+
+## Listen mit Typ-Parametern als Felder { #list-fields-with-type-parameter }
+
+Aber Python erlaubt es, Listen mit inneren Typen, auch „Typ-Parameter“ genannt, zu deklarieren.
+
+### Eine `list` mit einem Typ-Parameter deklarieren { #declare-a-list-with-a-type-parameter }
+
+Um Typen zu deklarieren, die Typ-Parameter (innere Typen) haben, wie `list`, `dict`, `tuple`, übergeben Sie den/die inneren Typ(en) als „Typ-Parameter“ in eckigen Klammern: `[` und `]`
+
+```Python
+my_list: list[str]
+```
+
+Das ist alles Standard-Python-Syntax für Typdeklarationen.
+
+Verwenden Sie dieselbe Standardsyntax für Modellattribute mit inneren Typen.
+
+In unserem Beispiel können wir also bewirken, dass `tags` spezifisch eine „Liste von Strings“ ist:
+
+{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}
+
+## Set-Typen { #set-types }
+
+Aber dann denken wir darüber nach und stellen fest, dass sich die Tags nicht wiederholen sollen, es sollen eindeutige Strings sein.
+
+Python hat einen Datentyp speziell für Mengen eindeutiger Dinge: das `set`.
+
+Deklarieren wir also `tags` als Set von Strings.
+
+{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}
+
+Jetzt, selbst wenn Sie einen Request mit duplizierten Daten erhalten, werden diese zu einem Set eindeutiger Dinge konvertiert.
+
+Und wann immer Sie diese Daten ausgeben, selbst wenn die Quelle Duplikate hatte, wird es als Set von eindeutigen Dingen ausgegeben.
+
+Und es wird entsprechend annotiert/dokumentiert.
+
+## Verschachtelte Modelle { #nested-models }
+
+Jedes Attribut eines Pydantic-Modells hat einen Typ.
+
+Aber dieser Typ kann selbst ein anderes Pydantic-Modell sein.
+
+Sie können also tief verschachtelte JSON-„Objekte“ deklarieren, mit spezifischen Attributnamen, -typen, und -validierungen.
+
+Alles das beliebig tief verschachtelt.
+
+### Ein Kindmodell definieren { #define-a-submodel }
+
+Für ein Beispiel können wir ein `Image`-Modell definieren.
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}
+
+### Das Kindmodell als Typ verwenden { #use-the-submodel-as-a-type }
+
+Und dann können wir es als Typ eines Attributes verwenden:
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}
+
+Das würde bedeuten, dass **FastAPI** einen Body wie folgt erwartet:
+
+```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"
+ }
+}
+```
+
+Wiederum, nur mit dieser Deklaration erhalten Sie von **FastAPI**:
+
+* Editor-Unterstützung (Codevervollständigung, usw.), selbst für verschachtelte Modelle
+* Datenkonvertierung
+* Datenvalidierung
+* Automatische Dokumentation
+
+## Spezielle Typen und Validierungen { #special-types-and-validation }
+
+Abgesehen von normalen einfachen Typen wie `str`, `int`, `float`, usw. können Sie komplexere einfache Typen verwenden, die von `str` erben.
+
+Um alle Optionen kennenzulernen, die Sie haben, schauen Sie sich [Pydantics Typübersicht](https://docs.pydantic.dev/latest/concepts/types/) an. Sie werden einige Beispiele im nächsten Kapitel kennenlernen.
+
+Zum Beispiel, da wir im `Image`-Modell ein Feld `url` haben, können wir deklarieren, dass das eine Instanz von Pydantics `HttpUrl` sein soll, anstelle eines `str`:
+
+{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}
+
+Es wird getestet, ob der String eine gültige URL ist, und als solche wird er in JSON Schema / OpenAPI dokumentiert.
+
+## Attribute mit Listen von Kindmodellen { #attributes-with-lists-of-submodels }
+
+Sie können Pydantic-Modelle auch als Typen innerhalb von `list`, `set`, usw. verwenden:
+
+{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}
+
+Das wird einen JSON-Body erwarten (konvertieren, validieren, dokumentieren, usw.) wie:
+
+```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 | Info
+
+Beachten Sie, dass der `images`-Schlüssel jetzt eine Liste von Bild-Objekten hat.
+
+///
+
+## Tief verschachtelte Modelle { #deeply-nested-models }
+
+Sie können beliebig tief verschachtelte Modelle definieren:
+
+{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}
+
+/// info | Info
+
+Beachten Sie, wie `Offer` eine Liste von `Item`s hat, die ihrerseits eine optionale Liste von `Image`s haben.
+
+///
+
+## Bodys aus reinen Listen { #bodies-of-pure-lists }
+
+Wenn das äußerste Element des JSON-Bodys, das Sie erwarten, ein JSON-`array` (eine Python-`list`) ist, können Sie den Typ im Funktionsparameter deklarieren, mit der gleichen Syntax wie in Pydantic-Modellen:
+
+```Python
+images: list[Image]
+```
+
+so wie in:
+
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
+
+## Editor-Unterstützung überall { #editor-support-everywhere }
+
+Und Sie erhalten Editor-Unterstützung überall.
+
+Selbst für Dinge in Listen:
+
+
+
+Sie würden diese Editor-Unterstützung nicht erhalten, wenn Sie direkt mit `dict`, statt mit Pydantic-Modellen arbeiten würden.
+
+Aber Sie müssen sich auch nicht weiter um die Modelle kümmern, hereinkommende Dicts werden automatisch in sie konvertiert. Und was Sie zurückgeben, wird automatisch nach JSON konvertiert.
+
+## Bodys mit beliebigen `dict`s { #bodies-of-arbitrary-dicts }
+
+Sie können einen Body auch als `dict` deklarieren, mit Schlüsseln eines Typs und Werten eines anderen Typs.
+
+So brauchen Sie vorher nicht zu wissen, wie die Feld-/Attributnamen lauten (wie es bei Pydantic-Modellen der Fall wäre).
+
+Das ist nützlich, wenn Sie Schlüssel empfangen, deren Namen Sie nicht bereits kennen.
+
+---
+
+Ein anderer nützlicher Anwendungsfall ist, wenn Sie Schlüssel eines anderen Typs haben wollen, z. B. `int`.
+
+Das schauen wir uns mal an.
+
+Im folgenden Beispiel akzeptieren Sie irgendein `dict`, solange es `int`-Schlüssel und `float`-Werte hat:
+
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
+
+/// tip | Tipp
+
+Bedenken Sie, dass JSON nur `str` als Schlüssel unterstützt.
+
+Aber Pydantic hat automatische Datenkonvertierung.
+
+Das bedeutet, dass Ihre API-Clients nur Strings senden können, aber solange diese Strings nur Zahlen enthalten, wird Pydantic sie konvertieren und validieren.
+
+Und das `dict`, welches Sie als `weights` erhalten, wird `int`-Schlüssel und `float`-Werte haben.
+
+///
+
+## Zusammenfassung { #recap }
+
+Mit **FastAPI** haben Sie die maximale Flexibilität von Pydantic-Modellen, während Ihr Code einfach, kurz und elegant bleibt.
+
+Aber mit all den Vorzügen:
+
+* Editor-Unterstützung (Codevervollständigung überall)
+* Datenkonvertierung (auch bekannt als Parsen, Serialisierung)
+* Datenvalidierung
+* Schema-Dokumentation
+* Automatische Dokumentation
diff --git a/docs/de/docs/tutorial/body-updates.md b/docs/de/docs/tutorial/body-updates.md
new file mode 100644
index 0000000000000..ef46f19f68e86
--- /dev/null
+++ b/docs/de/docs/tutorial/body-updates.md
@@ -0,0 +1,100 @@
+# Body – Aktualisierungen { #body-updates }
+
+## Ersetzendes Aktualisieren mit `PUT` { #update-replacing-with-put }
+
+Um einen Artikel zu aktualisieren, können Sie die [HTTP `PUT`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) Operation verwenden.
+
+Sie können den `jsonable_encoder` verwenden, um die empfangenen Daten in etwas zu konvertieren, das als JSON gespeichert werden kann (z. B. in einer NoSQL-Datenbank). Zum Beispiel, um ein `datetime` in einen `str` zu konvertieren.
+
+{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}
+
+`PUT` wird verwendet, um Daten zu empfangen, die die existierenden Daten ersetzen sollen.
+
+### Warnung bezüglich des Ersetzens { #warning-about-replacing }
+
+Das bedeutet, dass, wenn Sie den Artikel `bar` aktualisieren wollen, mittels `PUT` und folgendem Body:
+
+```Python
+{
+ "name": "Barz",
+ "price": 3,
+ "description": None,
+}
+```
+
+weil das bereits gespeicherte Attribut `"tax": 20.2` nicht enthalten ist, das Eingabemodell den Defaultwert `"tax": 10.5` erhalten würde.
+
+Und die Daten würden mit diesem „neuen“ `tax` von `10.5` gespeichert werden.
+
+## Teil-Aktualisierungen mit `PATCH` { #partial-updates-with-patch }
+
+Sie können auch die [HTTP `PATCH`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) Operation verwenden, um Daten *teilweise* zu ersetzen.
+
+Das bedeutet, Sie senden nur die Daten, die Sie aktualisieren wollen, der Rest bleibt unverändert.
+
+/// note | Hinweis
+
+`PATCH` wird seltener verwendet und ist weniger bekannt als `PUT`.
+
+Und viele Teams verwenden ausschließlich `PUT`, selbst für nur Teil-Aktualisierungen.
+
+Es steht Ihnen **frei**, das zu verwenden, was Sie möchten, **FastAPI** legt Ihnen keine Einschränkungen auf.
+
+Aber dieser Leitfaden zeigt Ihnen mehr oder weniger, wie die beiden normalerweise verwendet werden.
+
+///
+
+### Pydantics `exclude_unset`-Parameter verwenden { #using-pydantics-exclude-unset-parameter }
+
+Wenn Sie Teil-Aktualisierungen entgegennehmen, ist der `exclude_unset`-Parameter in der `.model_dump()`-Methode von Pydantic-Modellen sehr nützlich.
+
+Wie in `item.model_dump(exclude_unset=True)`.
+
+Das wird ein `dict` erstellen, mit nur den Daten, die gesetzt wurden, als das `item`-Modell erstellt wurde, Defaultwerte ausgeschlossen.
+
+Sie können das verwenden, um ein `dict` zu erstellen, das nur die (im Request) gesendeten Daten enthält, ohne Defaultwerte:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}
+
+### Pydantics `update`-Parameter verwenden { #using-pydantics-update-parameter }
+
+Jetzt können Sie eine Kopie des existierenden Modells mittels `.model_copy()` erstellen, wobei Sie dem `update`-Parameter ein `dict` mit den zu ändernden Daten übergeben.
+
+Wie in `stored_item_model.model_copy(update=update_data)`:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}
+
+### Rekapitulation zu Teil-Aktualisierungen { #partial-updates-recap }
+
+Zusammengefasst, um Teil-Aktualisierungen vorzunehmen:
+
+* (Optional) verwenden Sie `PATCH` statt `PUT`.
+* Lesen Sie die bereits gespeicherten Daten aus.
+* Fügen Sie diese in ein Pydantic-Modell ein.
+* Erzeugen Sie aus dem empfangenen Modell ein `dict` ohne Defaultwerte (mittels `exclude_unset`).
+ * So ersetzen Sie nur die tatsächlich vom Benutzer gesetzten Werte, statt dass bereits gespeicherte Werte mit Defaultwerten des Modells überschrieben werden.
+* Erzeugen Sie eine Kopie ihres gespeicherten Modells, wobei Sie die Attribute mit den empfangenen Teil-Ersetzungen aktualisieren (mittels des `update`-Parameters).
+* Konvertieren Sie das kopierte Modell zu etwas, das in Ihrer Datenbank gespeichert werden kann (indem Sie beispielsweise `jsonable_encoder` verwenden).
+ * Das ist vergleichbar dazu, die `.model_dump()`-Methode des Modells erneut aufzurufen, aber es wird sicherstellen, dass die Werte zu Daten konvertiert werden, die ihrerseits zu JSON konvertiert werden können, zum Beispiel `datetime` zu `str`.
+* Speichern Sie die Daten in Ihrer Datenbank.
+* Geben Sie das aktualisierte Modell zurück.
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *}
+
+/// tip | Tipp
+
+Sie können tatsächlich die gleiche Technik mit einer HTTP `PUT` Operation verwenden.
+
+Aber dieses Beispiel verwendet `PATCH`, da dieses für solche Anwendungsfälle geschaffen wurde.
+
+///
+
+/// note | Hinweis
+
+Beachten Sie, dass das hereinkommende Modell immer noch validiert wird.
+
+Wenn Sie also Teil-Aktualisierungen empfangen wollen, die alle Attribute auslassen können, müssen Sie ein Modell haben, dessen Attribute alle als optional gekennzeichnet sind (mit Defaultwerten oder `None`).
+
+Um zu unterscheiden zwischen Modellen für **Aktualisierungen**, mit lauter optionalen Werten, und solchen für die **Erzeugung**, mit benötigten Werten, können Sie die Techniken verwenden, die in [Extramodelle](extra-models.md) beschrieben wurden.
+
+///
diff --git a/docs/de/docs/tutorial/body.md b/docs/de/docs/tutorial/body.md
new file mode 100644
index 0000000000000..9e87dfccf0f84
--- /dev/null
+++ b/docs/de/docs/tutorial/body.md
@@ -0,0 +1,165 @@
+# Requestbody { #request-body }
+
+Wenn Sie Daten von einem Client (sagen wir, einem Browser) zu Ihrer API senden müssen, senden Sie sie als **Requestbody**.
+
+Ein **Request**body sind Daten, die vom Client zu Ihrer API gesendet werden. Ein **Response**body sind Daten, die Ihre API zum Client sendet.
+
+Ihre API muss fast immer einen **Response**body senden. Aber Clients müssen nicht unbedingt immer **Requestbodys** senden, manchmal fordern sie nur einen Pfad an, vielleicht mit einigen Query-Parametern, aber senden keinen Body.
+
+Um einen **Request**body zu deklarieren, verwenden Sie [Pydantic](https://docs.pydantic.dev/)-Modelle mit all deren Fähigkeiten und Vorzügen.
+
+/// info | Info
+
+Um Daten zu senden, sollten Sie eines von: `POST` (meistverwendet), `PUT`, `DELETE` oder `PATCH` verwenden.
+
+Das Senden eines Bodys mit einem `GET`-Request hat ein undefiniertes Verhalten in den Spezifikationen, wird aber dennoch von FastAPI unterstützt, nur für sehr komplexe/extreme Anwendungsfälle.
+
+Da davon abgeraten wird, zeigt die interaktive Dokumentation mit Swagger-Benutzeroberfläche die Dokumentation für den Body nicht an, wenn `GET` verwendet wird, und zwischengeschaltete Proxys unterstützen es möglicherweise nicht.
+
+///
+
+## Pydantics `BaseModel` importieren { #import-pydantics-basemodel }
+
+Zuerst müssen Sie `BaseModel` von `pydantic` importieren:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[2] *}
+
+## Ihr Datenmodell erstellen { #create-your-data-model }
+
+Dann deklarieren Sie Ihr Datenmodell als eine Klasse, die von `BaseModel` erbt.
+
+Verwenden Sie Standard-Python-Typen für alle Attribute:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}
+
+Wie auch bei der Deklaration von Query-Parametern gilt: Wenn ein Modellattribut einen Defaultwert hat, ist das Attribut nicht erforderlich. Andernfalls ist es erforderlich. Verwenden Sie `None`, um es einfach optional zu machen.
+
+Zum Beispiel deklariert das obige Modell ein JSON „`object`“ (oder Python-`dict`) wie dieses:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "An optional description",
+ "price": 45.2,
+ "tax": 3.5
+}
+```
+
+Da `description` und `tax` optional sind (mit `None` als Defaultwert), wäre folgendes JSON „`object`“ auch gültig:
+
+```JSON
+{
+ "name": "Foo",
+ "price": 45.2
+}
+```
+
+## Als Parameter deklarieren { #declare-it-as-a-parameter }
+
+Um es zu Ihrer *Pfadoperation* hinzuzufügen, deklarieren Sie es auf die gleiche Weise, wie Sie Pfad- und Query-Parameter deklariert haben:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[16] *}
+
+... und deklarieren Sie dessen Typ als das Modell, welches Sie erstellt haben, `Item`.
+
+## Resultate { #results }
+
+Mit nur dieser Python-Typdeklaration wird **FastAPI**:
+
+* Den Requestbody als JSON lesen.
+* Die entsprechenden Typen konvertieren (falls nötig).
+* Diese Daten validieren.
+ * Wenn die Daten ungültig sind, wird ein klar lesbarer Fehler zurückgegeben, der genau anzeigt, wo und was die inkorrekten Daten sind.
+* Ihnen die erhaltenen Daten im Parameter `item` übergeben.
+ * Da Sie ihn in der Funktion als vom Typ `Item` deklariert haben, erhalten Sie auch die volle Unterstützung des Editors (Autovervollständigung, usw.) für alle Attribute und deren Typen.
+* [JSON Schema](https://json-schema.org)-Definitionen für Ihr Modell generieren, die Sie auch überall sonst verwenden können, wenn es für Ihr Projekt Sinn macht.
+* Diese Schemas werden Teil des generierten OpenAPI-Schemas und werden von den UIs der automatischen Dokumentation genutzt.
+
+## Automatische Dokumentation { #automatic-docs }
+
+Die JSON-Schemas Ihrer Modelle werden Teil Ihres OpenAPI-generierten Schemas und in der interaktiven API-Dokumentation angezeigt:
+
+
+
+Und werden auch in der API-Dokumentation innerhalb jeder *Pfadoperation*, die sie benötigt, verwendet:
+
+
+
+## Editor-Unterstützung { #editor-support }
+
+In Ihrem Editor erhalten Sie innerhalb Ihrer Funktion Typhinweise und Code-Vervollständigung überall (was nicht der Fall wäre, wenn Sie ein `dict` anstelle eines Pydantic-Modells erhalten hätten):
+
+
+
+Sie bekommen auch Fehlermeldungen für inkorrekte Typoperationen:
+
+
+
+Das ist nicht zufällig so, das ganze Framework wurde um dieses Design herum aufgebaut.
+
+Und es wurde in der Designphase gründlich getestet, bevor irgendeine Implementierung stattfand, um sicherzustellen, dass es mit allen Editoren funktioniert.
+
+Es gab sogar einige Änderungen an Pydantic selbst, um dies zu unterstützen.
+
+Die vorherigen Screenshots wurden mit [Visual Studio Code](https://code.visualstudio.com) aufgenommen.
+
+Aber Sie würden die gleiche Editor-Unterstützung in [PyCharm](https://www.jetbrains.com/pycharm/) und den meisten anderen Python-Editoren erhalten:
+
+
+
+/// tip | Tipp
+
+Wenn Sie [PyCharm](https://www.jetbrains.com/pycharm/) als Ihren Editor verwenden, können Sie das [Pydantic PyCharm Plugin](https://github.com/koxudaxi/pydantic-pycharm-plugin/) ausprobieren.
+
+Es verbessert die Editor-Unterstützung für Pydantic-Modelle, mit:
+
+* Code-Vervollständigung
+* Typüberprüfungen
+* Refaktorisierung
+* Suche
+* Inspektionen
+
+///
+
+## Das Modell verwenden { #use-the-model }
+
+Innerhalb der Funktion können Sie alle Attribute des Modellobjekts direkt verwenden:
+
+{* ../../docs_src/body/tutorial002_py310.py *}
+
+## Requestbody- + Pfad-Parameter { #request-body-path-parameters }
+
+Sie können Pfad-Parameter und den Requestbody gleichzeitig deklarieren.
+
+**FastAPI** erkennt, dass Funktionsparameter, die mit Pfad-Parametern übereinstimmen, **vom Pfad genommen** werden sollen, und dass Funktionsparameter, welche Pydantic-Modelle sind, **vom Requestbody genommen** werden sollen.
+
+{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}
+
+
+## Requestbody- + Pfad- + Query-Parameter { #request-body-path-query-parameters }
+
+Sie können auch zur gleichen Zeit **Body-**, **Pfad-** und **Query-Parameter** deklarieren.
+
+**FastAPI** wird jeden von ihnen korrekt erkennen und die Daten vom richtigen Ort holen.
+
+{* ../../docs_src/body/tutorial004_py310.py hl[16] *}
+
+Die Funktionsparameter werden wie folgt erkannt:
+
+* Wenn der Parameter auch im **Pfad** deklariert wurde, wird er als Pfad-Parameter verwendet.
+* Wenn der Parameter ein **einfacher Typ** ist (wie `int`, `float`, `str`, `bool`, usw.), wird er als **Query**-Parameter interpretiert.
+* Wenn der Parameter vom Typ eines **Pydantic-Modells** ist, wird er als Request**body** interpretiert.
+
+/// note | Hinweis
+
+FastAPI weiß, dass der Wert von `q` nicht erforderlich ist, aufgrund des definierten Defaultwertes `= None`.
+
+Das `str | None` wird von FastAPI nicht verwendet, um zu bestimmen, dass der Wert nicht erforderlich ist. FastAPI weiß, dass er nicht erforderlich ist, weil er einen Defaultwert von `= None` hat.
+
+Das Hinzufügen der Typannotationen ermöglicht jedoch Ihrem Editor, Ihnen eine bessere Unterstützung zu bieten und Fehler zu erkennen.
+
+///
+
+## Ohne Pydantic { #without-pydantic }
+
+Wenn Sie keine Pydantic-Modelle verwenden möchten, können Sie auch **Body**-Parameter verwenden. Siehe die Dokumentation unter [Body – Mehrere Parameter: Einfache Werte im Body](body-multiple-params.md#singular-values-in-body).
diff --git a/docs/de/docs/tutorial/cookie-param-models.md b/docs/de/docs/tutorial/cookie-param-models.md
new file mode 100644
index 0000000000000..81f7abb7de5c0
--- /dev/null
+++ b/docs/de/docs/tutorial/cookie-param-models.md
@@ -0,0 +1,76 @@
+# Cookie-Parameter-Modelle { #cookie-parameter-models }
+
+Wenn Sie eine Gruppe von **Cookies** haben, die zusammengehören, können Sie ein **Pydantic-Modell** erstellen, um diese zu deklarieren. 🍪
+
+Damit können Sie das Modell an **mehreren Stellen wiederverwenden** und auch Validierungen und Metadaten für alle Parameter gleichzeitig deklarieren. 😎
+
+/// note | Hinweis
+
+Dies wird seit FastAPI Version `0.115.0` unterstützt. 🤓
+
+///
+
+/// tip | Tipp
+
+Diese gleiche Technik gilt für `Query`, `Cookie` und `Header`. 😎
+
+///
+
+## Cookies mit einem Pydantic-Modell { #cookies-with-a-pydantic-model }
+
+Deklarieren Sie die **Cookie**-Parameter, die Sie benötigen, in einem **Pydantic-Modell**, und deklarieren Sie dann den Parameter als `Cookie`:
+
+{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}
+
+**FastAPI** wird die Daten für **jedes Feld** aus den im Request empfangenen **Cookies** **extrahieren** und Ihnen das von Ihnen definierte Pydantic-Modell bereitstellen.
+
+## Die Dokumentation testen { #check-the-docs }
+
+Sie können die definierten Cookies in der Dokumentationsoberfläche unter `/docs` sehen:
+
+
+
+
+---
+
+Wenn Sie Pycharm verwenden, können Sie:
+
+* Das Menü „Run“ öffnen.
+* Die Option „Debug ...“ auswählen.
+* Ein Kontextmenü wird angezeigt.
+* Die zu debuggende Datei auswählen (in diesem Fall `main.py`).
+
+Der Server wird dann mit Ihrem **FastAPI**-Code gestartet, an Ihren Haltepunkten angehalten, usw.
+
+So könnte es aussehen:
+
+
diff --git a/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md
new file mode 100644
index 0000000000000..4fd8d092fc110
--- /dev/null
+++ b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -0,0 +1,288 @@
+# Klassen als Abhängigkeiten { #classes-as-dependencies }
+
+Bevor wir tiefer in das **Dependency Injection** System eintauchen, lassen Sie uns das vorherige Beispiel verbessern.
+
+## Ein `dict` aus dem vorherigen Beispiel { #a-dict-from-the-previous-example }
+
+Im vorherigen Beispiel haben wir ein `dict` von unserer Abhängigkeit („Dependable“) zurückgegeben:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *}
+
+Aber dann haben wir ein `dict` im Parameter `commons` der *Pfadoperation-Funktion*.
+
+Und wir wissen, dass Editoren nicht viel Unterstützung (wie etwa Code-Vervollständigung) für `dict`s bieten können, weil sie ihre Schlüssel- und Werttypen nicht kennen.
+
+Das können wir besser machen ...
+
+## Was macht eine Abhängigkeit aus { #what-makes-a-dependency }
+
+Bisher haben Sie Abhängigkeiten gesehen, die als Funktionen deklariert wurden.
+
+Das ist jedoch nicht die einzige Möglichkeit, Abhängigkeiten zu deklarieren (obwohl es wahrscheinlich die gebräuchlichste ist).
+
+Der springende Punkt ist, dass eine Abhängigkeit aufrufbar („callable“) sein sollte.
+
+Ein „**Callable**“ in Python ist etwas, das wie eine Funktion aufgerufen werden kann („to call“).
+
+Wenn Sie also ein Objekt `something` haben (das möglicherweise _keine_ Funktion ist) und Sie es wie folgt aufrufen (ausführen) können:
+
+```Python
+something()
+```
+
+oder
+
+```Python
+something(some_argument, some_keyword_argument="foo")
+```
+
+dann ist das ein „Callable“ (ein „Aufrufbares“).
+
+## Klassen als Abhängigkeiten { #classes-as-dependencies_1 }
+
+Möglicherweise stellen Sie fest, dass Sie zum Erstellen einer Instanz einer Python-Klasse die gleiche Syntax verwenden.
+
+Zum Beispiel:
+
+```Python
+class Cat:
+ def __init__(self, name: str):
+ self.name = name
+
+
+fluffy = Cat(name="Mr Fluffy")
+```
+
+In diesem Fall ist `fluffy` eine Instanz der Klasse `Cat`.
+
+Und um `fluffy` zu erzeugen, rufen Sie `Cat` auf.
+
+Eine Python-Klasse ist also auch ein **Callable**.
+
+Darum können Sie in **FastAPI** auch eine Python-Klasse als Abhängigkeit verwenden.
+
+Was FastAPI tatsächlich prüft, ist, ob es sich um ein „Callable“ (Funktion, Klasse oder irgendetwas anderes) handelt und ob die Parameter definiert sind.
+
+Wenn Sie **FastAPI** ein „Callable“ als Abhängigkeit übergeben, analysiert es die Parameter dieses „Callables“ und verarbeitet sie auf die gleiche Weise wie die Parameter einer *Pfadoperation-Funktion*. Einschließlich Unterabhängigkeiten.
+
+Das gilt auch für Callables ohne Parameter. So wie es auch für *Pfadoperation-Funktionen* ohne Parameter gilt.
+
+Dann können wir das „Dependable“ `common_parameters` der Abhängigkeit von oben in die Klasse `CommonQueryParams` ändern:
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *}
+
+Achten Sie auf die Methode `__init__`, die zum Erstellen der Instanz der Klasse verwendet wird:
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *}
+
+... sie hat die gleichen Parameter wie unsere vorherige `common_parameters`:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *}
+
+Diese Parameter werden von **FastAPI** verwendet, um die Abhängigkeit „aufzulösen“.
+
+In beiden Fällen wird sie haben:
+
+* Einen optionalen `q`-Query-Parameter, der ein `str` ist.
+* Einen `skip`-Query-Parameter, der ein `int` ist, mit einem Defaultwert `0`.
+* Einen `limit`-Query-Parameter, der ein `int` ist, mit einem Defaultwert `100`.
+
+In beiden Fällen werden die Daten konvertiert, validiert, im OpenAPI-Schema dokumentiert, usw.
+
+## Verwenden { #use-it }
+
+Jetzt können Sie Ihre Abhängigkeit mithilfe dieser Klasse deklarieren.
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *}
+
+**FastAPI** ruft die Klasse `CommonQueryParams` auf. Dadurch wird eine „Instanz“ dieser Klasse erstellt und die Instanz wird als Parameter `commons` an Ihre Funktion überreicht.
+
+## Typannotation vs. `Depends` { #type-annotation-vs-depends }
+
+Beachten Sie, wie wir `CommonQueryParams` im obigen Code zweimal schreiben:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | Tipp
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+Das letzte `CommonQueryParams`, in:
+
+```Python
+... Depends(CommonQueryParams)
+```
+
+... ist das, was **FastAPI** tatsächlich verwendet, um die Abhängigkeit zu ermitteln.
+
+Aus diesem extrahiert FastAPI die deklarierten Parameter, und dieses ist es, was FastAPI auch aufruft.
+
+---
+
+In diesem Fall hat das erste `CommonQueryParams` in:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, ...
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | Tipp
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python
+commons: CommonQueryParams ...
+```
+
+////
+
+... keine besondere Bedeutung für **FastAPI**. FastAPI verwendet es nicht für die Datenkonvertierung, -validierung, usw. (da es dafür `Depends(CommonQueryParams)` verwendet).
+
+Sie könnten tatsächlich einfach schreiben:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[Any, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | Tipp
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python
+commons = Depends(CommonQueryParams)
+```
+
+////
+
+... wie in:
+
+{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *}
+
+Es wird jedoch empfohlen, den Typ zu deklarieren, da Ihr Editor so weiß, was als Parameter `commons` übergeben wird, und Ihnen dann bei der Codevervollständigung, Typprüfungen, usw. helfen kann:
+
+
+
+## Abkürzung { #shortcut }
+
+Aber Sie sehen, dass wir hier etwas Codeduplizierung haben, indem wir `CommonQueryParams` zweimal schreiben:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | Tipp
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+**FastAPI** bietet eine Abkürzung für diese Fälle, wo die Abhängigkeit *speziell* eine Klasse ist, welche **FastAPI** aufruft, um eine Instanz der Klasse selbst zu erstellen.
+
+In diesem speziellen Fall können Sie Folgendes tun:
+
+Anstatt zu schreiben:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | Tipp
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+... schreiben Sie:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | Tipp
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
+
+Sie deklarieren die Abhängigkeit als Typ des Parameters und verwenden `Depends()` ohne Parameter, anstatt die vollständige Klasse *erneut* in `Depends(CommonQueryParams)` schreiben zu müssen.
+
+Dasselbe Beispiel würde dann so aussehen:
+
+{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *}
+
+... und **FastAPI** wird wissen, was zu tun ist.
+
+/// tip | Tipp
+
+Wenn Sie das eher verwirrt, als Ihnen zu helfen, ignorieren Sie es, Sie *brauchen* es nicht.
+
+Es ist nur eine Abkürzung. Es geht **FastAPI** darum, Ihnen dabei zu helfen, Codeverdoppelung zu minimieren.
+
+///
diff --git a/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
new file mode 100644
index 0000000000000..028d280dc7f8f
--- /dev/null
+++ b/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -0,0 +1,69 @@
+# Abhängigkeiten in Pfadoperation-Dekoratoren { #dependencies-in-path-operation-decorators }
+
+Manchmal benötigen Sie den Rückgabewert einer Abhängigkeit innerhalb Ihrer *Pfadoperation-Funktion* nicht wirklich.
+
+Oder die Abhängigkeit gibt keinen Wert zurück.
+
+Aber Sie müssen sie trotzdem ausführen/auflösen.
+
+In diesen Fällen können Sie, anstatt einen Parameter der *Pfadoperation-Funktion* mit `Depends` zu deklarieren, eine `list` von `dependencies` zum *Pfadoperation-Dekorator* hinzufügen.
+
+## `dependencies` zum *Pfadoperation-Dekorator* hinzufügen { #add-dependencies-to-the-path-operation-decorator }
+
+Der *Pfadoperation-Dekorator* erhält ein optionales Argument `dependencies`.
+
+Es sollte eine `list` von `Depends()` sein:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
+
+Diese Abhängigkeiten werden auf die gleiche Weise wie normale Abhängigkeiten ausgeführt/aufgelöst. Aber ihr Wert (falls sie einen zurückgeben) wird nicht an Ihre *Pfadoperation-Funktion* übergeben.
+
+/// tip | Tipp
+
+Einige Editoren prüfen, ob Funktionsparameter nicht verwendet werden, und zeigen das als Fehler an.
+
+Wenn Sie `dependencies` im *Pfadoperation-Dekorator* verwenden, stellen Sie sicher, dass sie ausgeführt werden, während gleichzeitig Ihr Editor/Ihre Tools keine Fehlermeldungen ausgeben.
+
+Damit wird auch vermieden, neue Entwickler möglicherweise zu verwirren, die einen nicht verwendeten Parameter in Ihrem Code sehen und ihn für unnötig halten könnten.
+
+///
+
+/// info | Info
+
+In diesem Beispiel verwenden wir zwei erfundene benutzerdefinierte Header `X-Key` und `X-Token`.
+
+Aber in realen Fällen würden Sie bei der Implementierung von Sicherheit mehr Vorteile durch die Verwendung der integrierten [Sicherheits-Werkzeuge (siehe nächstes Kapitel)](../security/index.md) erzielen.
+
+///
+
+## Abhängigkeitsfehler und -Rückgabewerte { #dependencies-errors-and-return-values }
+
+Sie können dieselben Abhängigkeits-*Funktionen* verwenden, die Sie normalerweise verwenden.
+
+### Abhängigkeitsanforderungen { #dependency-requirements }
+
+Sie können Anforderungen für einen Request (wie Header) oder andere Unterabhängigkeiten deklarieren:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
+
+### Exceptions auslösen { #raise-exceptions }
+
+Die Abhängigkeiten können Exceptions `raise`n, genau wie normale Abhängigkeiten:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
+
+### Rückgabewerte { #return-values }
+
+Und sie können Werte zurückgeben oder nicht, die Werte werden nicht verwendet.
+
+Sie können also eine normale Abhängigkeit (die einen Wert zurückgibt), die Sie bereits an anderer Stelle verwenden, wiederverwenden, und auch wenn der Wert nicht verwendet wird, wird die Abhängigkeit ausgeführt:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
+
+## Abhängigkeiten für eine Gruppe von *Pfadoperationen* { #dependencies-for-a-group-of-path-operations }
+
+Wenn Sie später lesen, wie Sie größere Anwendungen strukturieren ([Größere Anwendungen – Mehrere Dateien](../../tutorial/bigger-applications.md)), möglicherweise mit mehreren Dateien, lernen Sie, wie Sie einen einzelnen `dependencies`-Parameter für eine Gruppe von *Pfadoperationen* deklarieren.
+
+## Globale Abhängigkeiten { #global-dependencies }
+
+Als Nächstes werden wir sehen, wie man Abhängigkeiten zur gesamten `FastAPI`-Anwendung hinzufügt, sodass sie für jede *Pfadoperation* gelten.
diff --git a/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md
new file mode 100644
index 0000000000000..e1eec2350e55f
--- /dev/null
+++ b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -0,0 +1,288 @@
+# Abhängigkeiten mit `yield` { #dependencies-with-yield }
+
+FastAPI unterstützt Abhängigkeiten, die einige zusätzliche Schritte nach Abschluss ausführen.
+
+Verwenden Sie dazu `yield` statt `return` und schreiben Sie die zusätzlichen Schritte / den zusätzlichen Code danach.
+
+/// tip | Tipp
+
+Stellen Sie sicher, dass Sie `yield` nur einmal pro Abhängigkeit verwenden.
+
+///
+
+/// note | Technische Details
+
+Jede Funktion, die dekoriert werden kann mit:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) oder
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+kann auch als gültige **FastAPI**-Abhängigkeit verwendet werden.
+
+Tatsächlich verwendet FastAPI diese beiden Dekoratoren intern.
+
+///
+
+## Eine Datenbank-Abhängigkeit mit `yield` { #a-database-dependency-with-yield }
+
+Sie könnten damit beispielsweise eine Datenbanksession erstellen und diese nach Abschluss schließen.
+
+Nur der Code vor und einschließlich der `yield`-Anweisung wird ausgeführt, bevor eine Response erzeugt wird:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
+
+Der ge`yield`ete Wert ist das, was in *Pfadoperationen* und andere Abhängigkeiten eingefügt wird:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
+
+Der auf die `yield`-Anweisung folgende Code wird nach der Response ausgeführt:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
+
+/// tip | Tipp
+
+Sie können `async`- oder reguläre Funktionen verwenden.
+
+**FastAPI** wird bei jeder das Richtige tun, so wie auch bei normalen Abhängigkeiten.
+
+///
+
+## Eine Abhängigkeit mit `yield` und `try` { #a-dependency-with-yield-and-try }
+
+Wenn Sie einen `try`-Block in einer Abhängigkeit mit `yield` verwenden, empfangen Sie alle Exceptions, die bei Verwendung der Abhängigkeit geworfen wurden.
+
+Wenn beispielsweise ein Code irgendwann in der Mitte, in einer anderen Abhängigkeit oder in einer *Pfadoperation*, ein „Rollback“ einer Datenbanktransaktion macht oder eine andere Exception verursacht, empfangen Sie die Exception in Ihrer Abhängigkeit.
+
+Sie können also mit `except SomeException` diese bestimmte Exception innerhalb der Abhängigkeit handhaben.
+
+Auf die gleiche Weise können Sie `finally` verwenden, um sicherzustellen, dass die Exit-Schritte ausgeführt werden, unabhängig davon, ob eine Exception geworfen wurde oder nicht.
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
+
+## Unterabhängigkeiten mit `yield` { #sub-dependencies-with-yield }
+
+Sie können Unterabhängigkeiten und „Bäume“ von Unterabhängigkeiten beliebiger Größe und Form haben, und einige oder alle davon können `yield` verwenden.
+
+**FastAPI** stellt sicher, dass der „Exit-Code“ in jeder Abhängigkeit mit `yield` in der richtigen Reihenfolge ausgeführt wird.
+
+Beispielsweise kann `dependency_c` von `dependency_b` und `dependency_b` von `dependency_a` abhängen:
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
+
+Und alle können `yield` verwenden.
+
+In diesem Fall benötigt `dependency_c` zum Ausführen seines Exit-Codes, dass der Wert von `dependency_b` (hier `dep_b` genannt) verfügbar ist.
+
+Und wiederum benötigt `dependency_b` den Wert von `dependency_a` (hier `dep_a` genannt) für seinen Exit-Code.
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
+
+Auf die gleiche Weise könnten Sie einige Abhängigkeiten mit `yield` und einige andere Abhängigkeiten mit `return` haben, und alle können beliebig voneinander abhängen.
+
+Und Sie könnten eine einzelne Abhängigkeit haben, die auf mehreren ge`yield`eten Abhängigkeiten basiert, usw.
+
+Sie können beliebige Kombinationen von Abhängigkeiten haben.
+
+**FastAPI** stellt sicher, dass alles in der richtigen Reihenfolge ausgeführt wird.
+
+/// note | Technische Details
+
+Dieses funktioniert dank Pythons [Kontextmanager](https://docs.python.org/3/library/contextlib.html).
+
+**FastAPI** verwendet sie intern, um das zu erreichen.
+
+///
+
+## Abhängigkeiten mit `yield` und `HTTPException` { #dependencies-with-yield-and-httpexception }
+
+Sie haben gesehen, dass Sie Abhängigkeiten mit `yield` verwenden und `try`-Blöcke haben können, die versuchen, irgendeinen Code auszuführen und dann, nach `finally`, Exit-Code ausführen.
+
+Sie können auch `except` verwenden, um die geworfene Exception abzufangen und damit etwas zu tun.
+
+Zum Beispiel können Sie eine andere Exception auslösen, wie `HTTPException`.
+
+/// tip | Tipp
+
+Dies ist eine etwas fortgeschrittene Technik, die Sie in den meisten Fällen nicht wirklich benötigen, da Sie Exceptions (einschließlich `HTTPException`) innerhalb des restlichen Anwendungscodes auslösen können, beispielsweise in der *Pfadoperation-Funktion*.
+
+Aber es ist für Sie da, wenn Sie es brauchen. 🤓
+
+///
+
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
+
+Wenn Sie Exceptions abfangen und darauf basierend eine benutzerdefinierte Response erstellen möchten, erstellen Sie einen [benutzerdefinierten Exceptionhandler](../handling-errors.md#install-custom-exception-handlers).
+
+## Abhängigkeiten mit `yield` und `except` { #dependencies-with-yield-and-except }
+
+Wenn Sie eine Exception mit `except` in einer Abhängigkeit mit `yield` abfangen und sie nicht erneut auslösen (oder eine neue Exception auslösen), kann FastAPI nicht feststellen, dass es eine Exception gab, genau so wie es bei normalem Python der Fall wäre:
+
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
+
+In diesem Fall sieht der Client eine *HTTP 500 Internal Server Error*-Response, wie es sein sollte, da wir keine `HTTPException` oder Ähnliches auslösen, aber der Server hat **keine Logs** oder einen anderen Hinweis darauf, was der Fehler war. 😱
+
+### In Abhängigkeiten mit `yield` und `except` immer `raise` verwenden { #always-raise-in-dependencies-with-yield-and-except }
+
+Wenn Sie eine Exception in einer Abhängigkeit mit `yield` abfangen, sollten Sie – sofern Sie nicht eine andere `HTTPException` oder Ähnliches auslösen – **die ursprüngliche Exception erneut auslösen**.
+
+Sie können dieselbe Exception mit `raise` erneut auslösen:
+
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
+
+Jetzt erhält der Client dieselbe *HTTP 500 Internal Server Error*-Response, aber der Server enthält unseren benutzerdefinierten `InternalError` in den Logs. 😎
+
+## Ausführung von Abhängigkeiten mit `yield` { #execution-of-dependencies-with-yield }
+
+Die Ausführungsreihenfolge ähnelt mehr oder weniger dem folgenden Diagramm. Die Zeit verläuft von oben nach unten. Und jede Spalte ist einer der interagierenden oder Code-ausführenden Teilnehmer.
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant handler as Exceptionhandler
+participant dep as Abhängigkeit mit yield
+participant operation as Pfadoperation
+participant tasks as Hintergrundtasks
+
+ Note over client,operation: Kann Exceptions auslösen, inklusive HTTPException
+ client ->> dep: Startet den Request
+ Note over dep: Führt den Code bis zum yield aus
+ opt Löst Exception aus
+ dep -->> handler: Löst Exception aus
+ handler -->> client: HTTP-Error-Response
+ end
+ dep ->> operation: Führt Abhängigkeit aus, z. B. DB-Session
+ opt Löst aus
+ operation -->> dep: Löst Exception aus (z. B. HTTPException)
+ opt Handhabt
+ dep -->> dep: Kann Exception abfangen, eine neue HTTPException auslösen, andere Exception auslösen
+ end
+ handler -->> client: HTTP-Error-Response
+ end
+
+ operation ->> client: Sendet Response an Client
+ Note over client,operation: Response wurde bereits gesendet, kann nicht mehr geändert werden
+ opt Tasks
+ operation -->> tasks: Sendet Hintergrundtasks
+ end
+ opt Löst andere Exception aus
+ tasks -->> tasks: Handhabt Exceptions im Hintergrundtask-Code
+ end
+```
+
+/// info | Info
+
+Es wird nur **eine Response** an den Client gesendet. Es kann eine Error-Response oder die Response der *Pfadoperation* sein.
+
+Nachdem eine dieser Responses gesendet wurde, kann keine weitere Response gesendet werden.
+
+///
+
+/// tip | Tipp
+
+Wenn Sie in dem Code der *Pfadoperation-Funktion* irgendeine Exception auslösen, wird sie an die Abhängigkeiten mit `yield` weitergegeben, einschließlich `HTTPException`. In den meisten Fällen sollten Sie dieselbe Exception oder eine neue aus der Abhängigkeit mit `yield` erneut auslösen, um sicherzustellen, dass sie korrekt gehandhabt wird.
+
+///
+
+## Frühes Beenden und `scope` { #early-exit-and-scope }
+
+Normalerweise wird der Exit-Code von Abhängigkeiten mit `yield` ausgeführt **nachdem die Response** an den Client gesendet wurde.
+
+Wenn Sie aber wissen, dass Sie die Abhängigkeit nach der Rückkehr aus der *Pfadoperation-Funktion* nicht mehr benötigen, können Sie `Depends(scope="function")` verwenden, um FastAPI mitzuteilen, dass es die Abhängigkeit nach der Rückkehr aus der *Pfadoperation-Funktion* schließen soll, jedoch **bevor** die **Response gesendet wird**.
+
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
+
+`Depends()` erhält einen `scope`-Parameter, der sein kann:
+
+* `"function"`: startet die Abhängigkeit vor der *Pfadoperation-Funktion*, die den Request bearbeitet, beendet die Abhängigkeit nach dem Ende der *Pfadoperation-Funktion*, aber **bevor** die Response an den Client zurückgesendet wird. Die Abhängigkeitsfunktion wird also **um** die *Pfadoperation-**Funktion*** **herum** ausgeführt.
+* `"request"`: startet die Abhängigkeit vor der *Pfadoperation-Funktion*, die den Request bearbeitet (ähnlich wie bei `"function"`), beendet sie jedoch **nachdem** die Response an den Client zurückgesendet wurde. Die Abhängigkeitsfunktion wird also **um** den **Request**- und Response-Zyklus **herum** ausgeführt.
+
+Wenn nicht angegeben und die Abhängigkeit `yield` hat, hat sie standardmäßig einen `scope` von `"request"`.
+
+### `scope` für Unterabhängigkeiten { #scope-for-sub-dependencies }
+
+Wenn Sie eine Abhängigkeit mit `scope="request"` (dem Default) deklarieren, muss jede Unterabhängigkeit ebenfalls einen `scope` von `"request"` haben.
+
+Eine Abhängigkeit mit `scope` von `"function"` kann jedoch Abhängigkeiten mit `scope` von `"function"` und `scope` von `"request"` haben.
+
+Das liegt daran, dass jede Abhängigkeit in der Lage sein muss, ihren Exit-Code vor den Unterabhängigkeiten auszuführen, da sie diese während ihres Exit-Codes möglicherweise noch verwenden muss.
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant dep_req as Abhängigkeit scope="request"
+participant dep_func as Abhängigkeit scope="function"
+participant operation as Pfadoperation
+
+ client ->> dep_req: Startet den Request
+ Note over dep_req: Führt den Code bis zum yield aus
+ dep_req ->> dep_func: Reicht Abhängigkeit weiter
+ Note over dep_func: Führt den Code bis zum yield aus
+ dep_func ->> operation: Führt Pfadoperation mit Abhängigkeit aus
+ operation ->> dep_func: Kehrt aus Pfadoperation zurück
+ Note over dep_func: Führt Code nach yield aus
+ Note over dep_func: ✅ Abhängigkeit geschlossen
+ dep_func ->> client: Sendet Response an Client
+ Note over client: Response gesendet
+ Note over dep_req: Führt Code nach yield aus
+ Note over dep_req: ✅ Abhängigkeit geschlossen
+```
+
+## Abhängigkeiten mit `yield`, `HTTPException`, `except` und Hintergrundtasks { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+Abhängigkeiten mit `yield` haben sich im Laufe der Zeit weiterentwickelt, um verschiedene Anwendungsfälle abzudecken und einige Probleme zu beheben.
+
+Wenn Sie sehen möchten, was sich in verschiedenen Versionen von FastAPI geändert hat, lesen Sie mehr dazu im fortgeschrittenen Teil, unter [Fortgeschrittene Abhängigkeiten – Abhängigkeiten mit `yield`, `HTTPException`, `except` und Hintergrundtasks](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks).
+## Kontextmanager { #context-managers }
+
+### Was sind „Kontextmanager“ { #what-are-context-managers }
+
+„Kontextmanager“ (Englisch „Context Manager“) sind bestimmte Python-Objekte, die Sie in einer `with`-Anweisung verwenden können.
+
+Beispielsweise können Sie [„with“ verwenden, um eine Datei auszulesen](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files):
+
+```Python
+with open("./somefile.txt") as f:
+ contents = f.read()
+ print(contents)
+```
+
+Im Hintergrund erstellt das `open("./somefile.txt")` ein Objekt, das als „Kontextmanager“ bezeichnet wird.
+
+Dieser stellt sicher, dass, wenn der `with`-Block beendet ist, die Datei geschlossen wird, auch wenn Exceptions geworfen wurden.
+
+Wenn Sie eine Abhängigkeit mit `yield` erstellen, erstellt **FastAPI** dafür intern einen Kontextmanager und kombiniert ihn mit einigen anderen zugehörigen Tools.
+
+### Kontextmanager in Abhängigkeiten mit `yield` verwenden { #using-context-managers-in-dependencies-with-yield }
+
+/// warning | Achtung
+
+Dies ist mehr oder weniger eine „fortgeschrittene“ Idee.
+
+Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie das vielleicht vorerst überspringen.
+
+///
+
+In Python können Sie Kontextmanager erstellen, indem Sie [eine Klasse mit zwei Methoden erzeugen: `__enter__()` und `__exit__()`](https://docs.python.org/3/reference/datamodel.html#context-managers).
+
+Sie können solche auch innerhalb von **FastAPI**-Abhängigkeiten mit `yield` verwenden, indem Sie `with`- oder `async with`-Anweisungen innerhalb der Abhängigkeits-Funktion verwenden:
+
+{* ../../docs_src/dependencies/tutorial010_py310.py hl[1:9,13] *}
+
+/// tip | Tipp
+
+Andere Möglichkeiten, einen Kontextmanager zu erstellen, sind:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) oder
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+Verwenden Sie diese, um eine Funktion zu dekorieren, die ein einziges `yield` hat.
+
+Das ist es auch, was **FastAPI** intern für Abhängigkeiten mit `yield` verwendet.
+
+Aber Sie müssen die Dekoratoren nicht für FastAPI-Abhängigkeiten verwenden (und das sollten Sie auch nicht).
+
+FastAPI erledigt das intern für Sie.
+
+///
diff --git a/docs/de/docs/tutorial/dependencies/global-dependencies.md b/docs/de/docs/tutorial/dependencies/global-dependencies.md
new file mode 100644
index 0000000000000..ac52cf0bd280b
--- /dev/null
+++ b/docs/de/docs/tutorial/dependencies/global-dependencies.md
@@ -0,0 +1,16 @@
+# Globale Abhängigkeiten { #global-dependencies }
+
+Bei einigen Anwendungstypen möchten Sie möglicherweise Abhängigkeiten zur gesamten Anwendung hinzufügen.
+
+Ähnlich wie Sie [`dependencies` zu den *Pfadoperation-Dekoratoren* hinzufügen](dependencies-in-path-operation-decorators.md) können, können Sie sie auch zur `FastAPI`-Anwendung hinzufügen.
+
+In diesem Fall werden sie auf alle *Pfadoperationen* in der Anwendung angewendet:
+
+{* ../../docs_src/dependencies/tutorial012_an_py310.py hl[17] *}
+
+
+Und alle Ideen aus dem Abschnitt über das [Hinzufügen von `dependencies` zu den *Pfadoperation-Dekoratoren*](dependencies-in-path-operation-decorators.md) gelten weiterhin, aber in diesem Fall für alle *Pfadoperationen* in der App.
+
+## Abhängigkeiten für Gruppen von *Pfadoperationen* { #dependencies-for-groups-of-path-operations }
+
+Wenn Sie später lesen, wie Sie größere Anwendungen strukturieren ([Größere Anwendungen – mehrere Dateien](../../tutorial/bigger-applications.md)), möglicherweise mit mehreren Dateien, lernen Sie, wie Sie einen einzelnen `dependencies`-Parameter für eine Gruppe von *Pfadoperationen* deklarieren.
diff --git a/docs/de/docs/tutorial/dependencies/index.md b/docs/de/docs/tutorial/dependencies/index.md
new file mode 100644
index 0000000000000..49c65eb37ae0b
--- /dev/null
+++ b/docs/de/docs/tutorial/dependencies/index.md
@@ -0,0 +1,249 @@
+# Abhängigkeiten { #dependencies }
+
+**FastAPI** hat ein sehr mächtiges, aber intuitives **Abhängigkeitsinjektion** System.
+
+Es ist so konzipiert, sehr einfach zu verwenden zu sein und es jedem Entwickler sehr leicht zu machen, andere Komponenten mit **FastAPI** zu integrieren.
+
+## Was ist „Dependency Injection“ { #what-is-dependency-injection }
+
+**„Dependency Injection“** bedeutet in der Programmierung, dass es für Ihren Code (in diesem Fall Ihre *Pfadoperation-Funktionen*) eine Möglichkeit gibt, Dinge zu deklarieren, die er verwenden möchte und die er zum Funktionieren benötigt: „Abhängigkeiten“ – „Dependencies“.
+
+Das System (in diesem Fall **FastAPI**) kümmert sich dann darum, Ihren Code mit den erforderlichen Abhängigkeiten zu versorgen („die Abhängigkeiten einfügen“ – „inject the dependencies“).
+
+Das ist sehr nützlich, wenn Sie:
+
+* Eine gemeinsame Logik haben (die gleiche Code-Logik immer und immer wieder).
+* Datenbankverbindungen teilen.
+* Sicherheit, Authentifizierung, Rollenanforderungen, usw. durchsetzen.
+* Und viele andere Dinge ...
+
+All dies, während Sie Codeverdoppelung minimieren.
+
+## Erste Schritte { #first-steps }
+
+Sehen wir uns ein sehr einfaches Beispiel an. Es ist so einfach, dass es vorerst nicht sehr nützlich ist.
+
+Aber so können wir uns besser auf die Funktionsweise des **Dependency Injection** Systems konzentrieren.
+
+### Eine Abhängigkeit erstellen, oder „Dependable“ { #create-a-dependency-or-dependable }
+
+Konzentrieren wir uns zunächst auf die Abhängigkeit – die Dependency.
+
+Es handelt sich einfach um eine Funktion, die die gleichen Parameter entgegennimmt wie eine *Pfadoperation-Funktion*:
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}
+
+Das war's schon.
+
+**Zwei Zeilen**.
+
+Und sie hat die gleiche Form und Struktur wie alle Ihre *Pfadoperation-Funktionen*.
+
+Sie können sie sich als *Pfadoperation-Funktion* ohne den „Dekorator“ (ohne `@app.get("/some-path")`) vorstellen.
+
+Und sie kann alles zurückgeben, was Sie möchten.
+
+In diesem Fall erwartet diese Abhängigkeit:
+
+* Einen optionalen Query-Parameter `q`, der ein `str` ist.
+* Einen optionalen Query-Parameter `skip`, der ein `int` ist und standardmäßig `0` ist.
+* Einen optionalen Query-Parameter `limit`, der ein `int` ist und standardmäßig `100` ist.
+
+Und dann wird einfach ein `dict` zurückgegeben, welches diese Werte enthält.
+
+/// info | Info
+
+FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0.
+
+Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden.
+
+Bitte [aktualisieren Sie FastAPI](../../deployment/versions.md#upgrading-the-fastapi-versions) daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden.
+
+///
+
+### `Depends` importieren { #import-depends }
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}
+
+### Die Abhängigkeit im „Dependant“ deklarieren { #declare-the-dependency-in-the-dependant }
+
+So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ihrer *Pfadoperation-Funktion*:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}
+
+Obwohl Sie `Depends` in den Parametern Ihrer Funktion genauso verwenden wie `Body`, `Query`, usw., funktioniert `Depends` etwas anders.
+
+Sie übergeben `Depends` nur einen einzigen Parameter.
+
+Dieser Parameter muss so etwas wie eine Funktion sein.
+
+Sie **rufen diese nicht direkt auf** (fügen Sie am Ende keine Klammern hinzu), sondern übergeben sie einfach als Parameter an `Depends()`.
+
+Und diese Funktion akzeptiert Parameter auf die gleiche Weise wie *Pfadoperation-Funktionen*.
+
+/// tip | Tipp
+
+Im nächsten Kapitel erfahren Sie, welche anderen „Dinge“, außer Funktionen, Sie als Abhängigkeiten verwenden können.
+
+///
+
+Immer wenn ein neuer Request eintrifft, kümmert sich **FastAPI** darum:
+
+* Ihre Abhängigkeitsfunktion („Dependable“) mit den richtigen Parametern aufzurufen.
+* Sich das Ergebnis von dieser Funktion zu holen.
+* Dieses Ergebnis dem Parameter Ihrer *Pfadoperation-Funktion* zuzuweisen.
+
+```mermaid
+graph TB
+
+common_parameters(["common_parameters"])
+read_items["/items/"]
+read_users["/users/"]
+
+common_parameters --> read_items
+common_parameters --> read_users
+```
+
+Auf diese Weise schreiben Sie gemeinsam genutzten Code nur einmal, und **FastAPI** kümmert sich darum, ihn für Ihre *Pfadoperationen* aufzurufen.
+
+/// check | Testen
+
+Beachten Sie, dass Sie keine spezielle Klasse erstellen und diese irgendwo an **FastAPI** übergeben müssen, um sie zu „registrieren“ oder so ähnlich.
+
+Sie übergeben es einfach an `Depends` und **FastAPI** weiß, wie der Rest erledigt wird.
+
+///
+
+## `Annotated`-Abhängigkeiten wiederverwenden { #share-annotated-dependencies }
+
+In den Beispielen oben sehen Sie, dass es ein kleines bisschen **Codeverdoppelung** gibt.
+
+Wenn Sie die Abhängigkeit `common_parameters()` verwenden, müssen Sie den gesamten Parameter mit der Typannotation und `Depends()` schreiben:
+
+```Python
+commons: Annotated[dict, Depends(common_parameters)]
+```
+
+Da wir jedoch `Annotated` verwenden, können wir diesen `Annotated`-Wert in einer Variablen speichern und an mehreren Stellen verwenden:
+
+{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}
+
+/// tip | Tipp
+
+Das ist schlicht Standard-Python, es wird als „Typalias“ bezeichnet und ist eigentlich nicht **FastAPI**-spezifisch.
+
+Da **FastAPI** jedoch auf Standard-Python, einschließlich `Annotated`, basiert, können Sie diesen Trick in Ihrem Code verwenden. 😎
+
+///
+
+Die Abhängigkeiten funktionieren weiterhin wie erwartet, und das **Beste daran** ist, dass die **Typinformationen erhalten bleiben**, was bedeutet, dass Ihr Editor Ihnen weiterhin **automatische Vervollständigung**, **Inline-Fehler**, usw. bieten kann. Das Gleiche gilt für andere Tools wie `mypy`.
+
+Das ist besonders nützlich, wenn Sie es in einer **großen Codebasis** verwenden, in der Sie in **vielen *Pfadoperationen*** immer wieder **dieselben Abhängigkeiten** verwenden.
+
+## `async` oder nicht `async` { #to-async-or-not-to-async }
+
+Da Abhängigkeiten auch von **FastAPI** aufgerufen werden (so wie Ihre *Pfadoperation-Funktionen*), gelten beim Definieren Ihrer Funktionen die gleichen Regeln.
+
+Sie können `async def` oder einfach `def` verwenden.
+
+Und Sie können Abhängigkeiten mit `async def` innerhalb normaler `def`-*Pfadoperation-Funktionen* oder `def`-Abhängigkeiten innerhalb von `async def`-*Pfadoperation-Funktionen*, usw. deklarieren.
+
+Es spielt keine Rolle. **FastAPI** weiß, was zu tun ist.
+
+/// note | Hinweis
+
+Wenn Ihnen das nichts sagt, lesen Sie den [Async: *„In Eile?“*](../../async.md#in-a-hurry)-Abschnitt über `async` und `await` in der Dokumentation.
+
+///
+
+## Integriert in OpenAPI { #integrated-with-openapi }
+
+Alle Requestdeklarationen, -validierungen und -anforderungen Ihrer Abhängigkeiten (und Unterabhängigkeiten) werden in dasselbe OpenAPI-Schema integriert.
+
+Die interaktive Dokumentation enthält also auch alle Informationen aus diesen Abhängigkeiten:
+
+
+
+## Einfache Verwendung { #simple-usage }
+
+Näher betrachtet, werden *Pfadoperation-Funktionen* deklariert, um verwendet zu werden, wann immer ein *Pfad* und eine *Operation* übereinstimmen, und dann kümmert sich **FastAPI** darum, die Funktion mit den richtigen Parametern aufzurufen, die Daten aus dem Request extrahierend.
+
+Tatsächlich funktionieren alle (oder die meisten) Webframeworks auf die gleiche Weise.
+
+Sie rufen diese Funktionen niemals direkt auf. Sie werden von Ihrem Framework aufgerufen (in diesem Fall **FastAPI**).
+
+Mit dem Dependency Injection System können Sie **FastAPI** ebenfalls mitteilen, dass Ihre *Pfadoperation-Funktion* von etwas anderem „abhängt“, das vor Ihrer *Pfadoperation-Funktion* ausgeführt werden soll, und **FastAPI** kümmert sich darum, es auszuführen und die Ergebnisse zu „injizieren“.
+
+Andere gebräuchliche Begriffe für dieselbe Idee der „Abhängigkeitsinjektion“ sind:
+
+* Ressourcen
+* Provider
+* Services
+* Injectables
+* Komponenten
+
+## **FastAPI**-Plugins { #fastapi-plug-ins }
+
+Integrationen und „Plugins“ können mit dem **Dependency Injection** System erstellt werden. Aber tatsächlich besteht **keine Notwendigkeit, „Plugins“ zu erstellen**, da es durch die Verwendung von Abhängigkeiten möglich ist, eine unendliche Anzahl von Integrationen und Interaktionen zu deklarieren, die dann für Ihre *Pfadoperation-Funktionen* verfügbar sind.
+
+Und Abhängigkeiten können auf sehr einfache und intuitive Weise erstellt werden, sodass Sie einfach die benötigten Python-Packages importieren und sie in wenigen Codezeilen, *im wahrsten Sinne des Wortes*, mit Ihren API-Funktionen integrieren.
+
+Beispiele hierfür finden Sie in den nächsten Kapiteln zu relationalen und NoSQL-Datenbanken, Sicherheit usw.
+
+## **FastAPI**-Kompatibilität { #fastapi-compatibility }
+
+Die Einfachheit des Dependency Injection Systems macht **FastAPI** kompatibel mit:
+
+* allen relationalen Datenbanken
+* NoSQL-Datenbanken
+* externen Packages
+* externen APIs
+* Authentifizierungs- und Autorisierungssystemen
+* API-Nutzungs-Überwachungssystemen
+* Responsedaten-Injektionssystemen
+* usw.
+
+## Einfach und leistungsstark { #simple-and-powerful }
+
+Obwohl das hierarchische Dependency Injection System sehr einfach zu definieren und zu verwenden ist, ist es dennoch sehr mächtig.
+
+Sie können Abhängigkeiten definieren, die selbst wiederum Abhängigkeiten definieren können.
+
+Am Ende wird ein hierarchischer Baum von Abhängigkeiten erstellt, und das **Dependency Injection** System kümmert sich darum, alle diese Abhängigkeiten (und deren Unterabhängigkeiten) für Sie aufzulösen und die Ergebnisse bei jedem Schritt einzubinden (zu injizieren).
+
+Nehmen wir zum Beispiel an, Sie haben vier API-Endpunkte (*Pfadoperationen*):
+
+* `/items/public/`
+* `/items/private/`
+* `/users/{user_id}/activate`
+* `/items/pro/`
+
+Dann könnten Sie für jeden davon unterschiedliche Berechtigungsanforderungen hinzufügen, nur mit Abhängigkeiten und Unterabhängigkeiten:
+
+```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
+```
+
+## Integriert mit **OpenAPI** { #integrated-with-openapi_1 }
+
+Alle diese Abhängigkeiten, während sie ihre Anforderungen deklarieren, fügen auch Parameter, Validierungen, usw. zu Ihren *Pfadoperationen* hinzu.
+
+**FastAPI** kümmert sich darum, alles zum OpenAPI-Schema hinzuzufügen, damit es in den interaktiven Dokumentationssystemen angezeigt wird.
diff --git a/docs/de/docs/tutorial/dependencies/sub-dependencies.md b/docs/de/docs/tutorial/dependencies/sub-dependencies.md
new file mode 100644
index 0000000000000..b01cc80a76abd
--- /dev/null
+++ b/docs/de/docs/tutorial/dependencies/sub-dependencies.md
@@ -0,0 +1,105 @@
+# Unterabhängigkeiten { #sub-dependencies }
+
+Sie können Abhängigkeiten erstellen, die **Unterabhängigkeiten** haben.
+
+Diese können so **tief** verschachtelt sein, wie nötig.
+
+**FastAPI** kümmert sich darum, sie aufzulösen.
+
+## Erste Abhängigkeit, „Dependable“ { #first-dependency-dependable }
+
+Sie könnten eine erste Abhängigkeit („Dependable“) wie folgt erstellen:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}
+
+Diese deklariert einen optionalen Query-Parameter `q` vom Typ `str` und gibt ihn dann einfach zurück.
+
+Das ist recht einfach (nicht sehr nützlich), hilft uns aber dabei, uns auf die Funktionsweise der Unterabhängigkeiten zu konzentrieren.
+
+## Zweite Abhängigkeit, „Dependable“ und „Dependant“ { #second-dependency-dependable-and-dependant }
+
+Dann können Sie eine weitere Abhängigkeitsfunktion (ein „Dependable“) erstellen, die gleichzeitig eine eigene Abhängigkeit deklariert (also auch ein „Dependant“ ist):
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}
+
+Betrachten wir die deklarierten Parameter:
+
+* Obwohl diese Funktion selbst eine Abhängigkeit ist („Dependable“, etwas hängt von ihr ab), deklariert sie auch eine andere Abhängigkeit („Dependant“, sie hängt von etwas anderem ab).
+ * Sie hängt von `query_extractor` ab und weist den von diesem zurückgegebenen Wert dem Parameter `q` zu.
+* Sie deklariert außerdem ein optionales `last_query`-Cookie, ein `str`.
+ * Wenn der Benutzer keine Query `q` übermittelt hat, verwenden wir die zuletzt übermittelte Query, die wir zuvor in einem Cookie gespeichert haben.
+
+## Die Abhängigkeit verwenden { #use-the-dependency }
+
+Diese Abhängigkeit verwenden wir nun wie folgt:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}
+
+/// info | Info
+
+Beachten Sie, dass wir in der *Pfadoperation-Funktion* nur eine einzige Abhängigkeit deklarieren, den `query_or_cookie_extractor`.
+
+Aber **FastAPI** wird wissen, dass es zuerst `query_extractor` auflösen muss, um dessen Resultat an `query_or_cookie_extractor` zu übergeben, wenn dieses aufgerufen wird.
+
+///
+
+```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
+```
+
+## Dieselbe Abhängigkeit mehrmals verwenden { #using-the-same-dependency-multiple-times }
+
+Wenn eine Ihrer Abhängigkeiten mehrmals für dieselbe *Pfadoperation* deklariert wird, beispielsweise wenn mehrere Abhängigkeiten eine gemeinsame Unterabhängigkeit haben, wird **FastAPI** diese Unterabhängigkeit nur einmal pro Request aufrufen.
+
+Und es speichert den zurückgegebenen Wert in einem „Cache“ und übergibt diesen gecachten Wert an alle „Dependanten“, die ihn in diesem spezifischen Request benötigen, anstatt die Abhängigkeit mehrmals für denselben Request aufzurufen.
+
+In einem fortgeschrittenen Szenario, bei dem Sie wissen, dass die Abhängigkeit bei jedem Schritt (möglicherweise mehrmals) in demselben Request aufgerufen werden muss, anstatt den zwischengespeicherten Wert zu verwenden, können Sie den Parameter `use_cache=False` festlegen, wenn Sie `Depends` verwenden:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+//// tab | Python 3.10+ nicht annotiert
+
+/// tip | Tipp
+
+Bevorzugen Sie die `Annotated`-Version, falls möglich.
+
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+## Zusammenfassung { #recap }
+
+Abgesehen von all den ausgefallenen Wörtern, die hier verwendet werden, ist das **Dependency Injection**-System recht simpel.
+
+Einfach Funktionen, die genauso aussehen wie *Pfadoperation-Funktionen*.
+
+Dennoch ist es sehr mächtig und ermöglicht Ihnen die Deklaration beliebig tief verschachtelter Abhängigkeits-„Graphen“ (Bäume).
+
+/// tip | Tipp
+
+All dies scheint angesichts dieser einfachen Beispiele möglicherweise nicht so nützlich zu sein.
+
+Aber Sie werden in den Kapiteln über **Sicherheit** sehen, wie nützlich das ist.
+
+Und Sie werden auch sehen, wie viel Code Sie dadurch einsparen.
+
+///
diff --git a/docs/de/docs/tutorial/encoder.md b/docs/de/docs/tutorial/encoder.md
new file mode 100644
index 0000000000000..77a87f811c77d
--- /dev/null
+++ b/docs/de/docs/tutorial/encoder.md
@@ -0,0 +1,35 @@
+# JSON-kompatibler Encoder { #json-compatible-encoder }
+
+Es gibt Fälle, da möchten Sie einen Datentyp (etwa ein Pydantic-Modell) in etwas konvertieren, das kompatibel mit JSON ist (etwa ein `dict`, eine `list`, usw.).
+
+Zum Beispiel, wenn Sie es in einer Datenbank speichern möchten.
+
+Dafür bietet **FastAPI** eine Funktion `jsonable_encoder()`.
+
+## `jsonable_encoder` verwenden { #using-the-jsonable-encoder }
+
+Stellen wir uns vor, Sie haben eine Datenbank `fake_db`, die nur JSON-kompatible Daten entgegennimmt.
+
+Sie akzeptiert zum Beispiel keine `datetime`-Objekte, da die nicht kompatibel mit JSON sind.
+
+Ein `datetime`-Objekt müsste also in einen `str` umgewandelt werden, der die Daten im [ISO-Format](https://en.wikipedia.org/wiki/ISO_8601) enthält.
+
+Genauso würde die Datenbank kein Pydantic-Modell (ein Objekt mit Attributen) akzeptieren, sondern nur ein `dict`.
+
+Sie können für diese Fälle `jsonable_encoder` verwenden.
+
+Es nimmt ein Objekt entgegen, wie etwa ein Pydantic-Modell, und gibt eine JSON-kompatible Version zurück:
+
+{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *}
+
+In diesem Beispiel wird das Pydantic-Modell in ein `dict`, und das `datetime`-Objekt in ein `str` konvertiert.
+
+Das Resultat dieses Aufrufs ist etwas, das mit Pythons Standard-[`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps) kodiert werden kann.
+
+Es wird also kein großer `str` zurückgegeben, der die Daten im JSON-Format (als String) enthält. Es wird eine Python-Standarddatenstruktur (z. B. ein `dict`) zurückgegeben, mit Werten und Unterwerten, die alle mit JSON kompatibel sind.
+
+/// note | Hinweis
+
+`jsonable_encoder` wird tatsächlich von **FastAPI** intern verwendet, um Daten zu konvertieren. Aber es ist in vielen anderen Szenarien hilfreich.
+
+///
diff --git a/docs/de/docs/tutorial/extra-data-types.md b/docs/de/docs/tutorial/extra-data-types.md
new file mode 100644
index 0000000000000..92401172b4c03
--- /dev/null
+++ b/docs/de/docs/tutorial/extra-data-types.md
@@ -0,0 +1,62 @@
+# Zusätzliche Datentypen { #extra-data-types }
+
+Bisher haben Sie gängige Datentypen verwendet, wie zum Beispiel:
+
+* `int`
+* `float`
+* `str`
+* `bool`
+
+Sie können aber auch komplexere Datentypen verwenden.
+
+Und Sie haben immer noch dieselbe Funktionalität wie bisher gesehen:
+
+* Großartige Editor-Unterstützung.
+* Datenkonvertierung bei eingehenden Requests.
+* Datenkonvertierung für Response-Daten.
+* Datenvalidierung.
+* Automatische Annotation und Dokumentation.
+
+## Andere Datentypen { #other-data-types }
+
+Hier sind einige der zusätzlichen Datentypen, die Sie verwenden können:
+
+* `UUID`:
+ * Ein standardmäßiger „universell eindeutiger Bezeichner“ („Universally Unique Identifier“), der in vielen Datenbanken und Systemen als ID üblich ist.
+ * Wird in Requests und Responses als `str` dargestellt.
+* `datetime.datetime`:
+ * Ein Python-`datetime.datetime`.
+ * Wird in Requests und Responses als `str` im ISO 8601-Format dargestellt, etwa: `2008-09-15T15:53:00+05:00`.
+* `datetime.date`:
+ * Python-`datetime.date`.
+ * Wird in Requests und Responses als `str` im ISO 8601-Format dargestellt, etwa: `2008-09-15`.
+* `datetime.time`:
+ * Ein Python-`datetime.time`.
+ * Wird in Requests und Responses als `str` im ISO 8601-Format dargestellt, etwa: `14:23:55.003`.
+* `datetime.timedelta`:
+ * Ein Python-`datetime.timedelta`.
+ * Wird in Requests und Responses als `float` der Gesamtsekunden dargestellt.
+ * Pydantic ermöglicht auch die Darstellung als „ISO 8601 Zeitdifferenz-Kodierung“, [siehe die Dokumentation für weitere Informationen](https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers).
+* `frozenset`:
+ * Wird in Requests und Responses wie ein `set` behandelt:
+ * Bei Requests wird eine Liste gelesen, Duplikate entfernt und in ein `set` umgewandelt.
+ * Bei Responses wird das `set` in eine `list` umgewandelt.
+ * Das generierte Schema zeigt an, dass die `set`-Werte eindeutig sind (unter Verwendung von JSON Schemas `uniqueItems`).
+* `bytes`:
+ * Standard-Python-`bytes`.
+ * In Requests und Responses werden sie als `str` behandelt.
+ * Das generierte Schema wird anzeigen, dass es sich um einen `str` mit `binary` „Format“ handelt.
+* `Decimal`:
+ * Standard-Python-`Decimal`.
+ * In Requests und Responses wird es wie ein `float` behandelt.
+* Sie können alle gültigen Pydantic-Datentypen hier überprüfen: [Pydantic-Datentypen](https://docs.pydantic.dev/latest/usage/types/types/).
+
+## Beispiel { #example }
+
+Hier ist ein Beispiel für eine *Pfadoperation* mit Parametern, die einige der oben genannten Typen verwenden.
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *}
+
+Beachten Sie, dass die Parameter innerhalb der Funktion ihren natürlichen Datentyp haben und Sie beispielsweise normale Datumsmanipulationen durchführen können, wie zum Beispiel:
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *}
diff --git a/docs/de/docs/tutorial/extra-models.md b/docs/de/docs/tutorial/extra-models.md
new file mode 100644
index 0000000000000..59580d73afba4
--- /dev/null
+++ b/docs/de/docs/tutorial/extra-models.md
@@ -0,0 +1,211 @@
+# Extramodelle { #extra-models }
+
+Im Anschluss an das vorherige Beispiel ist es üblich, mehr als ein zusammenhängendes Modell zu haben.
+
+Dies gilt insbesondere für Benutzermodelle, denn:
+
+* Das **Eingabemodell** muss ein Passwort enthalten können.
+* Das **Ausgabemodell** sollte kein Passwort haben.
+* Das **Datenbankmodell** müsste wahrscheinlich ein gehashtes Passwort haben.
+
+/// danger | Gefahr
+
+Speichern Sie niemals das Klartextpasswort eines Benutzers. Speichern Sie immer einen „sicheren Hash“, den Sie dann verifizieren können.
+
+Wenn Sie nicht wissen, was das ist, werden Sie in den [Sicherheitskapiteln](security/simple-oauth2.md#password-hashing) lernen, was ein „Passworthash“ ist.
+
+///
+
+## Mehrere Modelle { #multiple-models }
+
+Hier ist eine allgemeine Idee, wie die Modelle mit ihren Passwortfeldern aussehen könnten und an welchen Stellen sie verwendet werden:
+
+{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}
+
+### Über `**user_in.model_dump()` { #about-user-in-model-dump }
+
+#### Pydantics `.model_dump()` { #pydantics-model-dump }
+
+`user_in` ist ein Pydantic-Modell der Klasse `UserIn`.
+
+Pydantic-Modelle haben eine `.model_dump()`-Methode, die ein `dict` mit den Daten des Modells zurückgibt.
+
+Wenn wir also ein Pydantic-Objekt `user_in` erstellen, etwa so:
+
+```Python
+user_in = UserIn(username="john", password="secret", email="john.doe@example.com")
+```
+
+und dann aufrufen:
+
+```Python
+user_dict = user_in.model_dump()
+```
+
+haben wir jetzt ein `dict` mit den Daten in der Variablen `user_dict` (es ist ein `dict` statt eines Pydantic-Modellobjekts).
+
+Und wenn wir aufrufen:
+
+```Python
+print(user_dict)
+```
+
+würden wir ein Python-`dict` erhalten mit:
+
+```Python
+{
+ 'username': 'john',
+ 'password': 'secret',
+ 'email': 'john.doe@example.com',
+ 'full_name': None,
+}
+```
+
+#### Ein `dict` entpacken { #unpacking-a-dict }
+
+Wenn wir ein `dict` wie `user_dict` nehmen und es einer Funktion (oder Klasse) mit `**user_dict` übergeben, wird Python es „entpacken“. Es wird die Schlüssel und Werte von `user_dict` direkt als Schlüsselwort-Argumente übergeben.
+
+Setzen wir also das `user_dict` von oben ein:
+
+```Python
+UserInDB(**user_dict)
+```
+
+so ist das äquivalent zu:
+
+```Python
+UserInDB(
+ username="john",
+ password="secret",
+ email="john.doe@example.com",
+ full_name=None,
+)
+```
+
+Oder genauer gesagt, dazu, `user_dict` direkt zu verwenden, mit welchen Inhalten es auch immer in der Zukunft haben mag:
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ password = user_dict["password"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+)
+```
+
+#### Ein Pydantic-Modell aus dem Inhalt eines anderen { #a-pydantic-model-from-the-contents-of-another }
+
+Da wir im obigen Beispiel `user_dict` von `user_in.model_dump()` bekommen haben, wäre dieser Code:
+
+```Python
+user_dict = user_in.model_dump()
+UserInDB(**user_dict)
+```
+
+gleichwertig zu:
+
+```Python
+UserInDB(**user_in.model_dump())
+```
+
+... weil `user_in.model_dump()` ein `dict` ist, und dann lassen wir Python es „entpacken“, indem wir es an `UserInDB` mit vorangestelltem `**` übergeben.
+
+Auf diese Weise erhalten wir ein Pydantic-Modell aus den Daten eines anderen Pydantic-Modells.
+
+#### Ein `dict` entpacken und zusätzliche Schlüsselwort-Argumente { #unpacking-a-dict-and-extra-keywords }
+
+Und dann fügen wir das zusätzliche Schlüsselwort-Argument `hashed_password=hashed_password` hinzu, wie in:
+
+```Python
+UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
+```
+
+... was so ist wie:
+
+```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 | Achtung
+
+Die unterstützenden zusätzlichen Funktionen `fake_password_hasher` und `fake_save_user` dienen nur zur Demo eines möglichen Datenflusses, bieten jedoch natürlich keine echte Sicherheit.
+
+///
+
+## Verdopplung vermeiden { #reduce-duplication }
+
+Die Reduzierung von Code-Verdoppelung ist eine der Kernideen von **FastAPI**.
+
+Da die Verdopplung von Code die Wahrscheinlichkeit von Fehlern, Sicherheitsproblemen, Problemen mit der Desynchronisation des Codes (wenn Sie an einer Stelle, aber nicht an der anderen aktualisieren) usw. erhöht.
+
+Und diese Modelle teilen alle eine Menge der Daten und verdoppeln Attributnamen und -typen.
+
+Wir könnten es besser machen.
+
+Wir können ein `UserBase`-Modell deklarieren, das als Basis für unsere anderen Modelle dient. Und dann können wir Unterklassen dieses Modells erstellen, die seine Attribute (Typdeklarationen, Validierung usw.) erben.
+
+Die ganze Datenkonvertierung, -validierung, -dokumentation usw. wird immer noch wie gewohnt funktionieren.
+
+Auf diese Weise können wir nur die Unterschiede zwischen den Modellen (mit Klartext-`password`, mit `hashed_password` und ohne Passwort) deklarieren:
+
+{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}
+
+## `Union` oder `anyOf` { #union-or-anyof }
+
+Sie können deklarieren, dass eine Response eine `Union` mehrerer Typen ist, das bedeutet, dass die Response einer von ihnen ist.
+
+Dies wird in OpenAPI mit `anyOf` definiert.
+
+Um das zu tun, verwenden Sie den Standard-Python-Typhinweis [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union):
+
+/// note | Hinweis
+
+Wenn Sie eine [`Union`](https://docs.pydantic.dev/latest/concepts/types/#unions) definieren, listen Sie den spezifischeren Typ zuerst auf, gefolgt vom weniger spezifischen Typ. Im Beispiel unten steht `PlaneItem` vor `CarItem` in `Union[PlaneItem, CarItem]`.
+
+///
+
+{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}
+
+### `Union` in Python 3.10 { #union-in-python-3-10 }
+
+In diesem Beispiel übergeben wir `Union[PlaneItem, CarItem]` als Wert des Arguments `response_model`.
+
+Da wir es als **Wert an ein Argument übergeben**, anstatt es in einer **Typannotation** zu verwenden, müssen wir `Union` verwenden, sogar in Python 3.10.
+
+Wäre es eine Typannotation gewesen, hätten wir den vertikalen Strich verwenden können, wie in:
+
+```Python
+some_variable: PlaneItem | CarItem
+```
+
+Aber wenn wir das in der Zuweisung `response_model=PlaneItem | CarItem` machen, würden wir einen Fehler erhalten, weil Python versuchen würde, eine **ungültige Operation** zwischen `PlaneItem` und `CarItem` auszuführen, anstatt es als Typannotation zu interpretieren.
+
+## Liste von Modellen { #list-of-models }
+
+Auf die gleiche Weise können Sie Responses von Listen von Objekten deklarieren.
+
+Dafür verwenden Sie Pythons Standard-`list`:
+
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
+
+## Response mit beliebigem `dict` { #response-with-arbitrary-dict }
+
+Sie können auch eine Response deklarieren, die ein beliebiges `dict` zurückgibt, indem Sie nur die Typen der Schlüssel und Werte ohne ein Pydantic-Modell deklarieren.
+
+Dies ist nützlich, wenn Sie die gültigen Feld-/Attributnamen nicht im Voraus kennen (die für ein Pydantic-Modell benötigt werden würden).
+
+In diesem Fall können Sie `dict` verwenden:
+
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
+
+## Zusammenfassung { #recap }
+
+Verwenden Sie gerne mehrere Pydantic-Modelle und vererben Sie je nach Bedarf.
+
+Sie brauchen kein einzelnes Datenmodell pro Einheit, wenn diese Einheit in der Lage sein muss, verschiedene „Zustände“ zu haben. Wie im Fall der Benutzer-„Einheit“ mit einem Zustand einschließlich `password`, `password_hash` und ohne Passwort.
diff --git a/docs/de/docs/tutorial/first-steps.md b/docs/de/docs/tutorial/first-steps.md
new file mode 100644
index 0000000000000..0cf3d03a9f9c3
--- /dev/null
+++ b/docs/de/docs/tutorial/first-steps.md
@@ -0,0 +1,429 @@
+# Erste Schritte { #first-steps }
+
+Die einfachste FastAPI-Datei könnte wie folgt aussehen:
+
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
+
+Kopieren Sie das in eine Datei `main.py`.
+
+Starten Sie den Live-Server:
+
+get-Operation gehen
+
+/// info | `@decorator` Info
+
+Diese `@something`-Syntax wird in Python „Dekorator“ genannt.
+
+Sie platzieren ihn über einer Funktion. Wie ein hübscher, dekorativer Hut (daher kommt wohl der Begriff).
+
+Ein „Dekorator“ nimmt die darunter stehende Funktion und macht etwas damit.
+
+In unserem Fall teilt dieser Dekorator **FastAPI** mit, dass die folgende Funktion mit dem **Pfad** `/` und der **Operation** `get` zusammenhängt.
+
+Dies ist der „**Pfadoperation-Dekorator**“.
+
+///
+
+Sie können auch die anderen Operationen verwenden:
+
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+
+Und die exotischeren:
+
+* `@app.options()`
+* `@app.head()`
+* `@app.patch()`
+* `@app.trace()`
+
+/// tip | Tipp
+
+Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten.
+
+**FastAPI** erzwingt keine bestimmte Bedeutung.
+
+Die hier aufgeführten Informationen dienen als Leitfaden und sind nicht verbindlich.
+
+Wenn Sie beispielsweise GraphQL verwenden, führen Sie normalerweise alle Aktionen nur mit „POST“-Operationen durch.
+
+///
+
+### Schritt 4: Definieren der **Pfadoperation-Funktion** { #step-4-define-the-path-operation-function }
+
+Das ist unsere „**Pfadoperation-Funktion**“:
+
+* **Pfad**: ist `/`.
+* **Operation**: ist `get`.
+* **Funktion**: ist die Funktion direkt unter dem „Dekorator“ (unter `@app.get("/")`).
+
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
+
+Dies ist eine Python-Funktion.
+
+Sie wird von **FastAPI** immer dann aufgerufen, wenn sie einen Request an die URL „`/`“ mittels einer `GET`-Operation erhält.
+
+In diesem Fall handelt es sich um eine `async`-Funktion.
+
+---
+
+Sie könnten sie auch als normale Funktion anstelle von `async def` definieren:
+
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
+
+/// note | Hinweis
+
+Wenn Sie den Unterschied nicht kennen, lesen Sie [Async: *„In Eile?“*](../async.md#in-a-hurry).
+
+///
+
+### Schritt 5: den Inhalt zurückgeben { #step-5-return-the-content }
+
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
+
+Sie können ein `dict`, eine `list`, einzelne Werte wie `str`, `int`, usw. zurückgeben.
+
+Sie können auch Pydantic-Modelle zurückgeben (dazu später mehr).
+
+Es gibt viele andere Objekte und Modelle, die automatisch zu JSON konvertiert werden (einschließlich ORMs, usw.). Versuchen Sie, Ihre Lieblingsobjekte zu verwenden. Es ist sehr wahrscheinlich, dass sie bereits unterstützt werden.
+
+### Schritt 6: Deployen { #step-6-deploy-it }
+
+Stellen Sie Ihre App in der **[FastAPI Cloud](https://fastapicloud.com)** mit einem Befehl bereit: `fastapi deploy`. 🎉
+
+#### Über FastAPI Cloud { #about-fastapi-cloud }
+
+**[FastAPI Cloud](https://fastapicloud.com)** wird vom selben Autor und Team hinter **FastAPI** entwickelt.
+
+Es vereinfacht den Prozess des Erstellens, Deployens und des Zugriffs auf eine API mit minimalem Aufwand.
+
+Es bringt die gleiche **Developer-Experience** beim Erstellen von Apps mit FastAPI auch zum **Deployment** in der Cloud. 🎉
+
+FastAPI Cloud ist der Hauptsponsor und Finanzierer der „FastAPI and friends“ Open-Source-Projekte. ✨
+
+#### Zu anderen Cloudanbietern deployen { #deploy-to-other-cloud-providers }
+
+FastAPI ist Open Source und basiert auf Standards. Sie können FastAPI-Apps bei jedem Cloudanbieter Ihrer Wahl deployen.
+
+Folgen Sie den Anleitungen Ihres Cloudanbieters, um dort FastAPI-Apps bereitzustellen. 🤓
+
+## Zusammenfassung { #recap }
+
+* Importieren Sie `FastAPI`.
+* Erstellen Sie eine `app` Instanz.
+* Schreiben Sie einen **Pfadoperation-Dekorator** unter Verwendung von Dekoratoren wie `@app.get("/")`.
+* Definieren Sie eine **Pfadoperation-Funktion**, zum Beispiel `def root(): ...`.
+* Starten Sie den Entwicklungsserver mit dem Befehl `fastapi dev`.
+* Optional: Ihre App mit `fastapi deploy` deployen.
diff --git a/docs/de/docs/tutorial/handling-errors.md b/docs/de/docs/tutorial/handling-errors.md
new file mode 100644
index 0000000000000..261831a8ebd5b
--- /dev/null
+++ b/docs/de/docs/tutorial/handling-errors.md
@@ -0,0 +1,244 @@
+# Fehler behandeln { #handling-errors }
+
+Es gibt viele Situationen, in denen Sie einem Client, der Ihre API nutzt, einen Fehler mitteilen müssen.
+
+Dieser Client könnte ein Browser mit einem Frontend sein, ein Code von jemand anderem, ein IoT-Gerät usw.
+
+Sie könnten dem Client mitteilen müssen, dass:
+
+* Der Client nicht genügend Berechtigungen für diese Operation hat.
+* Der Client keinen Zugriff auf diese Ressource hat.
+* Die Ressource, auf die der Client versucht hat, zuzugreifen, nicht existiert.
+* usw.
+
+In diesen Fällen würden Sie normalerweise einen **HTTP-Statuscode** im Bereich **400** (von 400 bis 499) zurückgeben.
+
+Dies ist vergleichbar mit den HTTP-Statuscodes im Bereich 200 (von 200 bis 299). Diese „200“-Statuscodes bedeuten, dass der Request in irgendeiner Weise erfolgreich war.
+
+Die Statuscodes im Bereich 400 bedeuten hingegen, dass es einen Fehler seitens des Clients gab.
+
+Erinnern Sie sich an all diese **„404 Not Found“** Fehler (und Witze)?
+
+## `HTTPException` verwenden { #use-httpexception }
+
+Um HTTP-Responses mit Fehlern an den Client zurückzugeben, verwenden Sie `HTTPException`.
+
+### `HTTPException` importieren { #import-httpexception }
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
+
+### Eine `HTTPException` in Ihrem Code auslösen { #raise-an-httpexception-in-your-code }
+
+`HTTPException` ist eine normale Python-Exception mit zusätzlichen Daten, die für APIs relevant sind.
+
+Weil es eine Python-Exception ist, geben Sie sie nicht zurück (`return`), sondern lösen sie aus (`raise`).
+
+Das bedeutet auch, wenn Sie sich innerhalb einer Hilfsfunktion befinden, die Sie innerhalb Ihrer *Pfadoperation-Funktion* aufrufen, und Sie die `HTTPException` aus dieser Hilfsfunktion heraus auslösen, wird der restliche Code in der *Pfadoperation-Funktion* nicht ausgeführt. Der Request wird sofort abgebrochen und der HTTP-Error der `HTTPException` wird an den Client gesendet.
+
+Der Vorteil des Auslösens einer Exception gegenüber dem Zurückgeben eines Wertes wird im Abschnitt über Abhängigkeiten und Sicherheit deutlicher werden.
+
+In diesem Beispiel lösen wir eine Exception mit einem Statuscode von `404` aus, wenn der Client einen Artikel mit einer nicht existierenden ID anfordert:
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
+
+### Die resultierende Response { #the-resulting-response }
+
+Wenn der Client `http://example.com/items/foo` anfordert (ein `item_id` `"foo"`), erhält dieser Client einen HTTP-Statuscode 200 und diese JSON-Response:
+
+```JSON
+{
+ "item": "The Foo Wrestlers"
+}
+```
+
+Aber wenn der Client `http://example.com/items/bar` anfordert (ein nicht-existierendes `item_id` `"bar"`), erhält er einen HTTP-Statuscode 404 (der „Not Found“-Error) und eine JSON-Response wie:
+
+```JSON
+{
+ "detail": "Item not found"
+}
+```
+
+/// tip | Tipp
+
+Wenn Sie eine `HTTPException` auslösen, können Sie dem Parameter `detail` jeden Wert übergeben, der in JSON konvertiert werden kann, nicht nur `str`.
+
+Sie könnten ein `dict`, eine `list`, usw. übergeben.
+
+Diese werden von **FastAPI** automatisch gehandhabt und in JSON konvertiert.
+
+///
+
+## Benutzerdefinierte Header hinzufügen { #add-custom-headers }
+
+Es gibt Situationen, in denen es nützlich ist, dem HTTP-Error benutzerdefinierte Header hinzuzufügen. Zum Beispiel in einigen Sicherheitsszenarien.
+
+Sie werden es wahrscheinlich nicht direkt in Ihrem Code verwenden müssen.
+
+Aber falls Sie es für ein fortgeschrittenes Szenario benötigen, können Sie benutzerdefinierte Header hinzufügen:
+
+{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
+
+## Benutzerdefinierte Exceptionhandler installieren { #install-custom-exception-handlers }
+
+Sie können benutzerdefinierte Exceptionhandler mit [denselben Exception-Werkzeugen von Starlette](https://www.starlette.dev/exceptions/) hinzufügen.
+
+Angenommen, Sie haben eine benutzerdefinierte Exception `UnicornException`, die Sie (oder eine Bibliothek, die Sie verwenden) `raise`n könnten.
+
+Und Sie möchten diese Exception global mit FastAPI handhaben.
+
+Sie könnten einen benutzerdefinierten Exceptionhandler mit `@app.exception_handler()` hinzufügen:
+
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
+
+Hier, wenn Sie `/unicorns/yolo` anfordern, wird die *Pfadoperation* eine `UnicornException` `raise`n.
+
+Aber diese wird von `unicorn_exception_handler` gehandhabt.
+
+Sie erhalten also einen sauberen Fehler mit einem HTTP-Statuscode von `418` und dem JSON-Inhalt:
+
+```JSON
+{"message": "Oops! yolo did something. There goes a rainbow..."}
+```
+
+/// note | Technische Details
+
+Sie könnten auch `from starlette.requests import Request` und `from starlette.responses import JSONResponse` verwenden.
+
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, nur als Annehmlichkeit für Sie, den Entwickler. Aber die meisten verfügbaren Responses kommen direkt von Starlette. Dasselbe gilt für `Request`.
+
+///
+
+## Die Default-Exceptionhandler überschreiben { #override-the-default-exception-handlers }
+
+**FastAPI** hat einige Default-Exceptionhandler.
+
+Diese Handler sind dafür verantwortlich, die Default-JSON-Responses zurückzugeben, wenn Sie eine `HTTPException` `raise`n und wenn der Request ungültige Daten enthält.
+
+Sie können diese Exceptionhandler mit Ihren eigenen überschreiben.
+
+### Überschreiben von Request-Validierungs-Exceptions { #override-request-validation-exceptions }
+
+Wenn ein Request ungültige Daten enthält, löst **FastAPI** intern einen `RequestValidationError` aus.
+
+Und es enthält auch einen Default-Exceptionhandler für diesen.
+
+Um diesen zu überschreiben, importieren Sie den `RequestValidationError` und verwenden Sie ihn mit `@app.exception_handler(RequestValidationError)`, um den Exceptionhandler zu dekorieren.
+
+Der Exceptionhandler erhält einen `Request` und die Exception.
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
+
+Wenn Sie nun zu `/items/foo` gehen, erhalten Sie anstelle des standardmäßigen JSON-Fehlers mit:
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ]
+}
+```
+
+eine Textversion mit:
+
+```
+Validation errors:
+Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer
+```
+
+### Überschreiben des `HTTPException`-Fehlerhandlers { #override-the-httpexception-error-handler }
+
+Auf die gleiche Weise können Sie den `HTTPException`-Handler überschreiben.
+
+Zum Beispiel könnten Sie eine Klartext-Response statt JSON für diese Fehler zurückgeben wollen:
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
+
+/// note | Technische Details
+
+Sie könnten auch `from starlette.responses import PlainTextResponse` verwenden.
+
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, nur als Annehmlichkeit für Sie, den Entwickler. Aber die meisten verfügbaren Responses kommen direkt von Starlette.
+
+///
+
+/// warning | Achtung
+
+Beachten Sie, dass der `RequestValidationError` Informationen über den Dateinamen und die Zeile enthält, in der der Validierungsfehler auftritt, sodass Sie ihn bei Bedarf mit den relevanten Informationen in Ihren Logs anzeigen können.
+
+Das bedeutet aber auch, dass, wenn Sie ihn einfach in einen String umwandeln und diese Informationen direkt zurückgeben, Sie möglicherweise ein paar Informationen über Ihr System preisgeben. Daher extrahiert und zeigt der Code hier jeden Fehler getrennt.
+
+///
+
+### Verwenden des `RequestValidationError`-Bodys { #use-the-requestvalidationerror-body }
+
+Der `RequestValidationError` enthält den empfangenen `body` mit den ungültigen Daten.
+
+Sie könnten diesen während der Entwicklung Ihrer Anwendung verwenden, um den Body zu loggen und zu debuggen, ihn an den Benutzer zurückzugeben usw.
+
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
+
+Versuchen Sie nun, einen ungültigen Artikel zu senden:
+
+```JSON
+{
+ "title": "towel",
+ "size": "XL"
+}
+```
+
+Sie erhalten eine Response, die Ihnen sagt, dass die Daten ungültig sind und die den empfangenen Body enthält:
+
+```JSON hl_lines="12-15"
+{
+ "detail": [
+ {
+ "loc": [
+ "body",
+ "size"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ],
+ "body": {
+ "title": "towel",
+ "size": "XL"
+ }
+}
+```
+
+#### FastAPIs `HTTPException` vs. Starlettes `HTTPException` { #fastapis-httpexception-vs-starlettes-httpexception }
+
+**FastAPI** hat seine eigene `HTTPException`.
+
+Und die `HTTPException`-Fehlerklasse von **FastAPI** erbt von der `HTTPException`-Fehlerklasse von Starlette.
+
+Der einzige Unterschied besteht darin, dass die `HTTPException` von **FastAPI** beliebige JSON-konvertierbare Daten für das `detail`-Feld akzeptiert, während die `HTTPException` von Starlette nur Strings dafür akzeptiert.
+
+Sie können also weiterhin die `HTTPException` von **FastAPI** wie üblich in Ihrem Code auslösen.
+
+Aber wenn Sie einen Exceptionhandler registrieren, sollten Sie ihn für die `HTTPException` von Starlette registrieren.
+
+Auf diese Weise, wenn irgendein Teil des internen Codes von Starlette, oder eine Starlette-Erweiterung oder ein Plug-in, eine Starlette `HTTPException` auslöst, wird Ihr Handler in der Lage sein, diese abzufangen und zu handhaben.
+
+Um in diesem Beispiel beide `HTTPException`s im selben Code zu haben, wird die Exception von Starlette zu `StarletteHTTPException` umbenannt:
+
+```Python
+from starlette.exceptions import HTTPException as StarletteHTTPException
+```
+
+### Die Exceptionhandler von **FastAPI** wiederverwenden { #reuse-fastapis-exception-handlers }
+
+Wenn Sie die Exception zusammen mit den gleichen Default-Exceptionhandlern von **FastAPI** verwenden möchten, können Sie die Default-Exceptionhandler aus `fastapi.exception_handlers` importieren und wiederverwenden:
+
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
+
+In diesem Beispiel geben Sie nur den Fehler mit einer sehr ausdrucksstarken Nachricht aus, aber Sie verstehen das Prinzip. Sie können die Exception verwenden und dann einfach die Default-Exceptionhandler wiederverwenden.
diff --git a/docs/de/docs/tutorial/header-param-models.md b/docs/de/docs/tutorial/header-param-models.md
new file mode 100644
index 0000000000000..8c1bf61aec889
--- /dev/null
+++ b/docs/de/docs/tutorial/header-param-models.md
@@ -0,0 +1,72 @@
+# Header-Parameter-Modelle { #header-parameter-models }
+
+Wenn Sie eine Gruppe verwandter **Header-Parameter** haben, können Sie ein **Pydantic-Modell** erstellen, um diese zu deklarieren.
+
+Dadurch können Sie das **Modell an mehreren Stellen wiederverwenden** und auch Validierungen und Metadaten für alle Parameter gleichzeitig deklarieren. 😎
+
+/// note | Hinweis
+
+Dies wird seit FastAPI Version `0.115.0` unterstützt. 🤓
+
+///
+
+## Header-Parameter mit einem Pydantic-Modell { #header-parameters-with-a-pydantic-model }
+
+Deklarieren Sie die erforderlichen **Header-Parameter** in einem **Pydantic-Modell** und dann den Parameter als `Header`:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI** wird die Daten für **jedes Feld** aus den **Headern** des Request extrahieren und Ihnen das von Ihnen definierte Pydantic-Modell geben.
+
+## Die Dokumentation testen { #check-the-docs }
+
+Sie können die erforderlichen Header in der Dokumentationsoberfläche unter `/docs` sehen:
+
+
+contact-Felder| Parameter | Typ | Beschreibung |
|---|---|---|
name | str | Der identifizierende Name der Kontaktperson/Organisation. |
url | str | Die URL, die auf die Kontaktinformationen verweist. MUSS im Format einer URL vorliegen. |
email | str | Die E-Mail-Adresse der Kontaktperson/Organisation. MUSS im Format einer E-Mail-Adresse vorliegen. |
license_info-Felder| Parameter | Typ | Beschreibung |
|---|---|---|
name | str | ERFORDERLICH (wenn eine license_info festgelegt ist). Der für die API verwendete Lizenzname. |
identifier | str | Ein [SPDX](https://spdx.org/licenses/)-Lizenzausdruck für die API. Das Feld identifier und das Feld url schließen sich gegenseitig aus. Verfügbar seit OpenAPI 3.1.0, FastAPI 0.99.0. |
url | str | Eine URL zur Lizenz, die für die API verwendet wird. MUSS im Format einer URL vorliegen. |
+
+## Lizenzkennung { #license-identifier }
+
+Seit OpenAPI 3.1.0 und FastAPI 0.99.0 können Sie die `license_info` auch mit einem `identifier` anstelle einer `url` festlegen.
+
+Zum Beispiel:
+
+{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}
+
+## Metadaten für Tags { #metadata-for-tags }
+
+Sie können auch zusätzliche Metadaten für die verschiedenen Tags hinzufügen, die zum Gruppieren Ihrer Pfadoperationen verwendet werden, mit dem Parameter `openapi_tags`.
+
+Er nimmt eine Liste entgegen, die für jeden Tag ein Dictionary enthält.
+
+Jedes Dictionary kann Folgendes enthalten:
+
+* `name` (**erforderlich**): ein `str` mit demselben Tag-Namen, den Sie im Parameter `tags` in Ihren *Pfadoperationen* und `APIRouter`n verwenden.
+* `description`: ein `str` mit einer kurzen Beschreibung für das Tag. Sie kann Markdown enthalten und wird in der Benutzeroberfläche der Dokumentation angezeigt.
+* `externalDocs`: ein `dict`, das externe Dokumentation beschreibt mit:
+ * `description`: ein `str` mit einer kurzen Beschreibung für die externe Dokumentation.
+ * `url` (**erforderlich**): ein `str` mit der URL für die externe Dokumentation.
+
+### Metadaten für Tags erstellen { #create-metadata-for-tags }
+
+Versuchen wir es mit einem Beispiel mit Tags für `users` und `items`.
+
+Erstellen Sie Metadaten für Ihre Tags und übergeben Sie diese an den Parameter `openapi_tags`:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}
+
+Beachten Sie, dass Sie Markdown innerhalb der Beschreibungen verwenden können. Zum Beispiel wird „login“ in Fettschrift (**login**) und „fancy“ in Kursivschrift (_fancy_) angezeigt.
+
+/// tip | Tipp
+
+Sie müssen nicht für alle von Ihnen verwendeten Tags Metadaten hinzufügen.
+
+///
+
+### Ihre Tags verwenden { #use-your-tags }
+
+Verwenden Sie den Parameter `tags` mit Ihren *Pfadoperationen* (und `APIRouter`n), um diese verschiedenen Tags zuzuweisen:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}
+
+/// info | Info
+
+Lesen Sie mehr zu Tags unter [Pfadoperation-Konfiguration](path-operation-configuration.md#tags).
+
+///
+
+### Die Dokumentation testen { #check-the-docs }
+
+Wenn Sie nun die Dokumentation ansehen, werden dort alle zusätzlichen Metadaten angezeigt:
+
+
+
+### Reihenfolge der Tags { #order-of-tags }
+
+Die Reihenfolge der Tag-Metadaten-Dictionarys definiert auch die Reihenfolge, in der diese in der Benutzeroberfläche der Dokumentation angezeigt werden.
+
+Auch wenn beispielsweise `users` im Alphabet nach `items` kommt, wird es vor diesen angezeigt, da wir deren Metadaten als erstes Dictionary der Liste hinzugefügt haben.
+
+## OpenAPI-URL { #openapi-url }
+
+Standardmäßig wird das OpenAPI-Schema unter `/openapi.json` bereitgestellt.
+
+Sie können das aber mit dem Parameter `openapi_url` konfigurieren.
+
+Um beispielsweise festzulegen, dass es unter `/api/v1/openapi.json` bereitgestellt wird:
+
+{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}
+
+Wenn Sie das OpenAPI-Schema vollständig deaktivieren möchten, können Sie `openapi_url=None` festlegen, wodurch auch die Dokumentationsbenutzeroberflächen deaktiviert werden, die es verwenden.
+
+## Dokumentations-URLs { #docs-urls }
+
+Sie können die beiden enthaltenen Dokumentationsbenutzeroberflächen konfigurieren:
+
+* **Swagger UI**: bereitgestellt unter `/docs`.
+ * Sie können deren URL mit dem Parameter `docs_url` festlegen.
+ * Sie können sie deaktivieren, indem Sie `docs_url=None` festlegen.
+* **ReDoc**: bereitgestellt unter `/redoc`.
+ * Sie können deren URL mit dem Parameter `redoc_url` festlegen.
+ * Sie können sie deaktivieren, indem Sie `redoc_url=None` festlegen.
+
+Um beispielsweise Swagger UI so einzustellen, dass sie unter `/documentation` bereitgestellt wird, und ReDoc zu deaktivieren:
+
+{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}
diff --git a/docs/de/docs/tutorial/middleware.md b/docs/de/docs/tutorial/middleware.md
new file mode 100644
index 0000000000000..0e8da4dcefa52
--- /dev/null
+++ b/docs/de/docs/tutorial/middleware.md
@@ -0,0 +1,95 @@
+# Middleware { #middleware }
+
+Sie können Middleware zu **FastAPI**-Anwendungen hinzufügen.
+
+Eine „Middleware“ ist eine Funktion, die mit jedem **Request** arbeitet, bevor er von einer bestimmten *Pfadoperation* verarbeitet wird. Und auch mit jeder **Response**, bevor sie zurückgegeben wird.
+
+* Sie nimmt jeden **Request** entgegen, der an Ihre Anwendung gesendet wird.
+* Sie kann dann etwas mit diesem **Request** tun oder beliebigen Code ausführen.
+* Dann gibt sie den **Request** zur Verarbeitung durch den Rest der Anwendung weiter (durch eine bestimmte *Pfadoperation*).
+* Sie nimmt dann die **Response** entgegen, die von der Anwendung generiert wurde (durch eine bestimmte *Pfadoperation*).
+* Sie kann etwas mit dieser **Response** tun oder beliebigen Code ausführen.
+* Dann gibt sie die **Response** zurück.
+
+/// note | Technische Details
+
+Wenn Sie Abhängigkeiten mit `yield` haben, wird der Exit-Code *nach* der Middleware ausgeführt.
+
+Wenn es Hintergrundtasks gab (dies wird später im [Hintergrundtasks](background-tasks.md)-Abschnitt behandelt), werden sie *nach* allen Middlewares ausgeführt.
+
+///
+
+## Eine Middleware erstellen { #create-a-middleware }
+
+Um eine Middleware zu erstellen, verwenden Sie den Dekorator `@app.middleware("http")` über einer Funktion.
+
+Die Middleware-Funktion erhält:
+
+* Den `request`.
+* Eine Funktion `call_next`, die den `request` als Parameter erhält.
+ * Diese Funktion gibt den `request` an die entsprechende *Pfadoperation* weiter.
+ * Dann gibt es die von der entsprechenden *Pfadoperation* generierte `response` zurück.
+* Sie können die `response` dann weiter modifizieren, bevor Sie sie zurückgeben.
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}
+
+/// tip | Tipp
+
+Beachten Sie, dass benutzerdefinierte proprietäre Header hinzugefügt werden können [unter Verwendung des `X-`-Präfixes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers).
+
+Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser sehen soll, müssen Sie sie zu Ihrer CORS-Konfiguration ([CORS (Cross-Origin Resource Sharing)](cors.md)) hinzufügen, indem Sie den Parameter `expose_headers` verwenden, der in [Starlettes CORS-Dokumentation](https://www.starlette.dev/middleware/#corsmiddleware) dokumentiert ist.
+
+///
+
+/// note | Technische Details
+
+Sie könnten auch `from starlette.requests import Request` verwenden.
+
+**FastAPI** bietet es als Komfort für Sie, den Entwickler, an. Aber es stammt direkt von Starlette.
+
+///
+
+### Vor und nach der `response` { #before-and-after-the-response }
+
+Sie können Code hinzufügen, der mit dem `request` ausgeführt wird, bevor dieser von einer beliebigen *Pfadoperation* empfangen wird.
+
+Und auch nachdem die `response` generiert wurde, bevor sie zurückgegeben wird.
+
+Sie könnten beispielsweise einen benutzerdefinierten Header `X-Process-Time` hinzufügen, der die Zeit in Sekunden enthält, die benötigt wurde, um den Request zu verarbeiten und eine Response zu generieren:
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}
+
+/// tip | Tipp
+
+Hier verwenden wir [`time.perf_counter()`](https://docs.python.org/3/library/time.html#time.perf_counter) anstelle von `time.time()`, da es für diese Anwendungsfälle präziser sein kann. 🤓
+
+///
+
+## Ausführungsreihenfolge bei mehreren Middlewares { #multiple-middleware-execution-order }
+
+Wenn Sie mehrere Middlewares hinzufügen, entweder mit dem `@app.middleware()` Dekorator oder der Methode `app.add_middleware()`, umschließt jede neue Middleware die Anwendung und bildet einen Stapel. Die zuletzt hinzugefügte Middleware ist die *äußerste*, und die erste ist die *innerste*.
+
+Auf dem Requestpfad läuft die *äußerste* Middleware zuerst.
+
+Auf dem Responsepfad läuft sie zuletzt.
+
+Zum Beispiel:
+
+```Python
+app.add_middleware(MiddlewareA)
+app.add_middleware(MiddlewareB)
+```
+
+Dies führt zu folgender Ausführungsreihenfolge:
+
+* **Request**: MiddlewareB → MiddlewareA → Route
+
+* **Response**: Route → MiddlewareA → MiddlewareB
+
+Dieses Stapelverhalten stellt sicher, dass Middlewares in einer vorhersehbaren und kontrollierbaren Reihenfolge ausgeführt werden.
+
+## Andere Middlewares { #other-middlewares }
+
+Sie können später mehr über andere Middlewares im [Handbuch für fortgeschrittene Benutzer: Fortgeschrittene Middleware](../advanced/middleware.md) lesen.
+
+In der nächsten Sektion erfahren Sie, wie Sie CORS mit einer Middleware behandeln können.
diff --git a/docs/de/docs/tutorial/path-operation-configuration.md b/docs/de/docs/tutorial/path-operation-configuration.md
new file mode 100644
index 0000000000000..111c714946131
--- /dev/null
+++ b/docs/de/docs/tutorial/path-operation-configuration.md
@@ -0,0 +1,107 @@
+# Pfadoperation-Konfiguration { #path-operation-configuration }
+
+Es gibt mehrere Parameter, die Sie Ihrem *Pfadoperation-Dekorator* übergeben können, um ihn zu konfigurieren.
+
+/// warning | Achtung
+
+Beachten Sie, dass diese Parameter direkt dem *Pfadoperation-Dekorator* übergeben werden, nicht der *Pfadoperation-Funktion*.
+
+///
+
+## Response-Statuscode { #response-status-code }
+
+Sie können den (HTTP-)`status_code` definieren, der in der Response Ihrer *Pfadoperation* verwendet werden soll.
+
+Sie können direkt den `int`-Code übergeben, etwa `404`.
+
+Aber falls Sie sich nicht mehr erinnern, wofür jeder Nummerncode steht, können Sie die Abkürzungs-Konstanten in `status` verwenden:
+
+{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *}
+
+Dieser Statuscode wird in der Response verwendet und zum OpenAPI-Schema hinzugefügt.
+
+/// note | Technische Details
+
+Sie können auch `from starlette import status` verwenden.
+
+**FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette.
+
+///
+
+## Tags { #tags }
+
+Sie können Ihrer *Pfadoperation* Tags hinzufügen, indem Sie dem Parameter `tags` eine `list`e von `str`s übergeben (in der Regel nur ein `str`):
+
+{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *}
+
+Diese werden zum OpenAPI-Schema hinzugefügt und von den automatischen Dokumentations-Benutzeroberflächen verwendet:
+
+
+
+### Tags mittels Enumeration { #tags-with-enums }
+
+Wenn Sie eine große Anwendung haben, können sich am Ende **viele Tags** anhäufen, und Sie möchten sicherstellen, dass Sie für verwandte *Pfadoperationen* immer den **gleichen Tag** verwenden.
+
+In diesem Fall macht es Sinn, die Tags in einem `Enum` zu speichern.
+
+**FastAPI** unterstützt das auf die gleiche Weise wie einfache Strings:
+
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
+
+## Zusammenfassung und Beschreibung { #summary-and-description }
+
+Sie können eine `summary` und eine `description` hinzufügen:
+
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *}
+
+## Beschreibung mittels Docstring { #description-from-docstring }
+
+Da Beschreibungen oft mehrere Zeilen lang sind, können Sie die Beschreibung der *Pfadoperation* im Docstring der Funktion deklarieren, und **FastAPI** wird sie daraus auslesen.
+
+Sie können [Markdown](https://en.wikipedia.org/wiki/Markdown) im Docstring schreiben, es wird korrekt interpretiert und angezeigt (unter Berücksichtigung der Einrückung des Docstring).
+
+{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}
+
+Es wird in der interaktiven Dokumentation verwendet:
+
+
+
+## Beschreibung der Response { #response-description }
+
+Sie können die Response mit dem Parameter `response_description` beschreiben:
+
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
+
+/// info | Info
+
+Beachten Sie, dass sich `response_description` speziell auf die Response bezieht, während `description` sich generell auf die *Pfadoperation* bezieht.
+
+///
+
+/// check | Testen
+
+OpenAPI verlangt, dass jede *Pfadoperation* über eine Beschreibung der Response verfügt.
+
+Daher, wenn Sie keine vergeben, wird **FastAPI** automatisch eine für „Erfolgreiche Response“ erstellen.
+
+///
+
+
+
+## Eine *Pfadoperation* deprecaten { #deprecate-a-path-operation }
+
+Wenn Sie eine *Pfadoperation* als deprecatet kennzeichnen möchten, ohne sie zu entfernen, fügen Sie den Parameter `deprecated` hinzu:
+
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
+
+Sie wird in der interaktiven Dokumentation gut sichtbar als deprecatet markiert werden:
+
+
+
+Vergleichen Sie, wie deprecatete und nicht-deprecatete *Pfadoperationen* aussehen:
+
+
+
+## Zusammenfassung { #recap }
+
+Sie können auf einfache Weise Metadaten für Ihre *Pfadoperationen* definieren, indem Sie den *Pfadoperation-Dekoratoren* Parameter hinzufügen.
diff --git a/docs/de/docs/tutorial/path-params-numeric-validations.md b/docs/de/docs/tutorial/path-params-numeric-validations.md
new file mode 100644
index 0000000000000..76c782c52cf97
--- /dev/null
+++ b/docs/de/docs/tutorial/path-params-numeric-validations.md
@@ -0,0 +1,154 @@
+# Pfad-Parameter und Validierung von Zahlen { #path-parameters-and-numeric-validations }
+
+So wie Sie mit `Query` für Query-Parameter zusätzliche Validierungen und Metadaten deklarieren können, können Sie mit `Path` die gleichen Validierungen und Metadaten für Pfad-Parameter deklarieren.
+
+## `Path` importieren { #import-path }
+
+Importieren Sie zuerst `Path` von `fastapi`, und importieren Sie `Annotated`:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
+
+/// info | Info
+
+FastAPI hat in Version 0.95.0 Unterstützung für `Annotated` hinzugefügt und es zur Verwendung empfohlen.
+
+Wenn Sie eine ältere Version haben, würden Fehler angezeigt werden, wenn Sie versuchen, `Annotated` zu verwenden.
+
+Stellen Sie sicher, dass Sie [FastAPI aktualisieren](../deployment/versions.md#upgrading-the-fastapi-versions), auf mindestens Version 0.95.1, bevor Sie `Annotated` verwenden.
+
+///
+
+## Metadaten deklarieren { #declare-metadata }
+
+Sie können dieselben Parameter wie für `Query` deklarieren.
+
+Um zum Beispiel einen `title`-Metadaten-Wert für den Pfad-Parameter `item_id` zu deklarieren, können Sie schreiben:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *}
+
+/// note | Hinweis
+
+Ein Pfad-Parameter ist immer erforderlich, da er Teil des Pfads sein muss. Selbst wenn Sie ihn mit `None` deklarieren oder einen Defaultwert setzen, würde das nichts ändern, er wäre dennoch immer erforderlich.
+
+///
+
+## Die Parameter sortieren, wie Sie möchten { #order-the-parameters-as-you-need }
+
+/// tip | Tipp
+
+Das ist wahrscheinlich nicht so wichtig oder notwendig, wenn Sie `Annotated` verwenden.
+
+///
+
+Angenommen, Sie möchten den Query-Parameter `q` als erforderlichen `str` deklarieren.
+
+Und Sie müssen sonst nichts anderes für diesen Parameter deklarieren, Sie brauchen also `Query` nicht wirklich.
+
+Aber Sie müssen dennoch `Path` für den `item_id`-Pfad-Parameter verwenden. Und aus irgendeinem Grund möchten Sie `Annotated` nicht verwenden.
+
+Python wird sich beschweren, wenn Sie einen Wert mit einem „Default“ vor einem Wert ohne „Default“ setzen.
+
+Aber Sie können die Reihenfolge ändern und den Wert ohne Default (den Query-Parameter `q`) zuerst setzen.
+
+Für **FastAPI** spielt es keine Rolle. Es erkennt die Parameter anhand ihrer Namen, Typen und Default-Deklarationen (`Query`, `Path`, usw.), es kümmert sich nicht um die Reihenfolge.
+
+Sie können Ihre Funktion also so deklarieren:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
+
+Aber bedenken Sie, dass Sie dieses Problem nicht haben, wenn Sie `Annotated` verwenden, da es nicht darauf ankommt, dass Sie keine Funktionsparameter-Defaultwerte für `Query()` oder `Path()` verwenden.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
+
+## Die Parameter sortieren, wie Sie möchten: Tricks { #order-the-parameters-as-you-need-tricks }
+
+/// tip | Tipp
+
+Das ist wahrscheinlich nicht so wichtig oder notwendig, wenn Sie `Annotated` verwenden.
+
+///
+
+Hier ist ein **kleiner Trick**, der nützlich sein kann, obwohl Sie ihn nicht oft benötigen werden.
+
+Wenn Sie:
+
+* den `q`-Query-Parameter sowohl ohne `Query` als auch ohne Defaultwert deklarieren
+* den Pfad-Parameter `item_id` mit `Path` deklarieren
+* sie in einer anderen Reihenfolge haben
+* nicht `Annotated` verwenden
+
+... möchten, dann hat Python eine kleine Spezial-Syntax dafür.
+
+Übergeben Sie `*`, als den ersten Parameter der Funktion.
+
+Python wird nichts mit diesem `*` machen, aber es wird wissen, dass alle folgenden Parameter als Schlüsselwortargumente (Schlüssel-Wert-Paare) verwendet werden sollen, auch bekannt als kwargs. Selbst wenn diese keinen Defaultwert haben.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
+
+### Besser mit `Annotated` { #better-with-annotated }
+
+Bedenken Sie, dass Sie, wenn Sie `Annotated` verwenden, da Sie keine Funktionsparameter-Defaultwerte verwenden, dieses Problem nicht haben werden und wahrscheinlich nicht `*` verwenden müssen.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
+
+## Validierung von Zahlen: Größer oder gleich { #number-validations-greater-than-or-equal }
+
+Mit `Query` und `Path` (und anderen, die Sie später sehen werden) können Sie Zahlenbeschränkungen deklarieren.
+
+Hier, mit `ge=1`, muss `item_id` eine ganze Zahl sein, die „`g`reater than or `e`qual to“ (größer oder gleich) `1` ist.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
+
+## Validierung von Zahlen: Größer und kleiner oder gleich { #number-validations-greater-than-and-less-than-or-equal }
+
+Das Gleiche gilt für:
+
+* `gt`: `g`reater `t`han (größer als)
+* `le`: `l`ess than or `e`qual (kleiner oder gleich)
+
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
+
+## Validierung von Zahlen: Floats, größer und kleiner { #number-validations-floats-greater-than-and-less-than }
+
+Zahlenvalidierung funktioniert auch für `float`-Werte.
+
+Hier wird es wichtig, in der Lage zu sein, gt und nicht nur ge zu deklarieren. Da Sie mit dieser Option erzwingen können, dass ein Wert größer als `0` sein muss, selbst wenn er kleiner als `1` ist.
+
+Also wäre `0.5` ein gültiger Wert. Aber `0.0` oder `0` nicht.
+
+Und das Gleiche gilt für lt.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
+
+## Zusammenfassung { #recap }
+
+Mit `Query`, `Path` (und anderen, die Sie noch nicht gesehen haben) können Sie Metadaten und Stringvalidierungen auf die gleichen Weisen deklarieren wie in [Query-Parameter und Stringvalidierungen](query-params-str-validations.md) beschrieben.
+
+Und Sie können auch Zahlenvalidierungen deklarieren:
+
+* `gt`: `g`reater `t`han (größer als)
+* `ge`: `g`reater than or `e`qual (größer oder gleich)
+* `lt`: `l`ess `t`han (kleiner als)
+* `le`: `l`ess than or `e`qual (kleiner oder gleich)
+
+/// info | Info
+
+`Query`, `Path`, und andere Klassen, die Sie später sehen werden, sind Unterklassen einer gemeinsamen `Param`-Klasse.
+
+Alle von ihnen teilen die gleichen Parameter für zusätzliche Validierung und Metadaten, die Sie gesehen haben.
+
+///
+
+/// note | Technische Details
+
+Wenn Sie `Query`, `Path` und andere von `fastapi` importieren, sind sie tatsächlich Funktionen.
+
+Die, wenn sie aufgerufen werden, Instanzen von Klassen mit demselben Namen zurückgeben.
+
+Sie importieren also `Query`, was eine Funktion ist. Und wenn Sie sie aufrufen, gibt sie eine Instanz einer Klasse zurück, die auch `Query` genannt wird.
+
+Diese Funktionen existieren (statt die Klassen direkt zu verwenden), damit Ihr Editor keine Fehlermeldungen über ihre Typen ausgibt.
+
+Auf diese Weise können Sie Ihren normalen Editor und Ihre Programmier-Tools verwenden, ohne besondere Einstellungen vornehmen zu müssen, um diese Fehlermeldungen stummzuschalten.
+
+///
diff --git a/docs/de/docs/tutorial/path-params.md b/docs/de/docs/tutorial/path-params.md
new file mode 100644
index 0000000000000..0e0a3bdbdf14e
--- /dev/null
+++ b/docs/de/docs/tutorial/path-params.md
@@ -0,0 +1,251 @@
+# Pfad-Parameter { #path-parameters }
+
+Sie können Pfad-„Parameter“ oder -„Variablen“ mit der gleichen Syntax deklarieren, welche in Python-Formatstrings verwendet wird:
+
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
+
+Der Wert des Pfad-Parameters `item_id` wird Ihrer Funktion als das Argument `item_id` übergeben.
+
+Wenn Sie dieses Beispiel ausführen und auf [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo) gehen, sehen Sie als Response:
+
+```JSON
+{"item_id":"foo"}
+```
+
+## Pfad-Parameter mit Typen { #path-parameters-with-types }
+
+Sie können den Typ eines Pfad-Parameters in der Argumentliste der Funktion deklarieren, mit Standard-Python-Typannotationen:
+
+{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}
+
+In diesem Fall wird `item_id` als `int` deklariert, also als Ganzzahl.
+
+/// check | Testen
+
+Dadurch erhalten Sie Editor-Unterstützung innerhalb Ihrer Funktion, mit Fehlerprüfungen, Codevervollständigung, usw.
+
+///
+
+## Daten-Konversion { #data-conversion }
+
+Wenn Sie dieses Beispiel ausführen und Ihren Browser unter [http://127.0.0.1:8000/items/3](http://127.0.0.1:8000/items/3) öffnen, sehen Sie als Response:
+
+```JSON
+{"item_id":3}
+```
+
+/// check | Testen
+
+Beachten Sie, dass der Wert, den Ihre Funktion erhält und zurückgibt, die Zahl `3` ist, also ein `int`. Nicht der String „3“, also ein `str`.
+
+Sprich, mit dieser Typdeklaration wird **FastAPI** den „parsen“.
+
+///
+
+## Datenvalidierung { #data-validation }
+
+Wenn Sie aber im Browser [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo) besuchen, erhalten Sie eine hübsche HTTP-Fehlermeldung:
+
+```JSON
+{
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo"
+ }
+ ]
+}
+```
+
+Der Pfad-Parameter `item_id` hatte den Wert „foo“, was kein `int` ist.
+
+Die gleiche Fehlermeldung würde angezeigt werden, wenn Sie ein `float` (also eine Kommazahl) statt eines `int`s übergeben würden, wie etwa in: [http://127.0.0.1:8000/items/4.2](http://127.0.0.1:8000/items/4.2)
+
+/// check | Testen
+
+Sprich, mit der gleichen Python-Typdeklaration gibt Ihnen **FastAPI** Datenvalidierung.
+
+Beachten Sie, dass die Fehlermeldung auch direkt die Stelle anzeigt, wo die Validierung nicht erfolgreich war.
+
+Das ist unglaublich hilfreich, wenn Sie Code entwickeln und debuggen, welcher mit Ihrer API interagiert.
+
+///
+
+## Dokumentation { #documentation }
+
+Wenn Sie die Seite [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) in Ihrem Browser öffnen, sehen Sie eine automatische, interaktive API-Dokumentation:
+
+
+
+/// check | Testen
+
+Wiederum, mit dieser gleichen Python-Typdeklaration gibt Ihnen **FastAPI** eine automatische, interaktive Dokumentation (verwendet die Swagger-Benutzeroberfläche).
+
+Beachten Sie, dass der Pfad-Parameter dort als Ganzzahl deklariert ist.
+
+///
+
+## Nützliche Standards, alternative Dokumentation { #standards-based-benefits-alternative-documentation }
+
+Und weil das generierte Schema vom [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md)-Standard kommt, gibt es viele kompatible Tools.
+
+Zum Beispiel bietet **FastAPI** selbst eine alternative API-Dokumentation (verwendet ReDoc), welche Sie unter [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) einsehen können:
+
+
+
+Und viele weitere kompatible Tools. Inklusive Codegenerierung für viele Sprachen.
+
+## Pydantic { #pydantic }
+
+Die ganze Datenvalidierung wird hinter den Kulissen von [Pydantic](https://docs.pydantic.dev/) durchgeführt, Sie profitieren also von dessen Vorteilen. Und Sie wissen, dass Sie in guten Händen sind.
+
+Sie können für Typdeklarationen auch `str`, `float`, `bool` und viele andere komplexe Datentypen verwenden.
+
+Mehrere davon werden wir in den nächsten Kapiteln erkunden.
+
+## Die Reihenfolge ist wichtig { #order-matters }
+
+Wenn Sie *Pfadoperationen* erstellen, haben Sie manchmal einen fixen Pfad.
+
+Etwa `/users/me`, um Daten über den aktuellen Benutzer zu erhalten.
+
+Und Sie haben auch einen Pfad `/users/{user_id}`, um Daten über einen spezifischen Benutzer zu erhalten, mittels einer Benutzer-ID.
+
+Weil *Pfadoperationen* in ihrer Reihenfolge ausgewertet werden, müssen Sie sicherstellen, dass der Pfad `/users/me` vor `/users/{user_id}` deklariert wurde:
+
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
+
+Ansonsten würde der Pfad für `/users/{user_id}` auch `/users/me` auswerten, und annehmen, dass ein Parameter `user_id` mit dem Wert „me“ übergeben wurde.
+
+Sie können eine Pfadoperation auch nicht erneut definieren:
+
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
+
+Die erste Definition wird immer verwendet werden, da ihr Pfad zuerst übereinstimmt.
+
+## Vordefinierte Parameterwerte { #predefined-values }
+
+Wenn Sie eine *Pfadoperation* haben, welche einen *Pfad-Parameter* hat, aber Sie wollen, dass dessen gültige Werte vordefiniert sind, können Sie ein Standard-Python `Enum` verwenden.
+
+### Eine `Enum`-Klasse erstellen { #create-an-enum-class }
+
+Importieren Sie `Enum` und erstellen Sie eine Unterklasse, die von `str` und `Enum` erbt.
+
+Indem Sie von `str` erben, weiß die API-Dokumentation, dass die Werte vom Typ `str` sein müssen, und wird in der Lage sein, korrekt zu rendern.
+
+Erstellen Sie dann Klassen-Attribute mit festgelegten Werten, welches die erlaubten Werte sein werden:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
+
+/// tip | Tipp
+
+Falls Sie sich fragen, was „AlexNet“, „ResNet“ und „LeNet“ ist, das sind Namen von Modellen für maschinelles Lernen.
+
+///
+
+### Einen *Pfad-Parameter* deklarieren { #declare-a-path-parameter }
+
+Dann erstellen Sie einen *Pfad-Parameter*, der als Typ die gerade erstellte Enum-Klasse hat (`ModelName`):
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
+
+### Die API-Dokumentation testen { #check-the-docs }
+
+Weil die erlaubten Werte für den *Pfad-Parameter* nun vordefiniert sind, kann die interaktive Dokumentation sie als Auswahl-Drop-Down anzeigen:
+
+
+
+### Mit Python-*Enumerationen* arbeiten { #working-with-python-enumerations }
+
+Der *Pfad-Parameter* wird ein *Member einer Enumeration* sein.
+
+#### *Enumeration-Member* vergleichen { #compare-enumeration-members }
+
+Sie können ihn mit einem Member Ihrer Enumeration `ModelName` vergleichen:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}
+
+#### *Enumerations-Wert* erhalten { #get-the-enumeration-value }
+
+Den tatsächlichen Wert (in diesem Fall ein `str`) erhalten Sie via `model_name.value`, oder generell, `your_enum_member.value`:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}
+
+/// tip | Tipp
+
+Sie können den Wert `"lenet"` außerdem mittels `ModelName.lenet.value` abrufen.
+
+///
+
+#### *Enumeration-Member* zurückgeben { #return-enumeration-members }
+
+Sie können *Enum-Member* in ihrer *Pfadoperation* zurückgeben, sogar verschachtelt in einem JSON-Body (z. B. als `dict`).
+
+Diese werden zu ihren entsprechenden Werten konvertiert (in diesem Fall Strings), bevor sie zum Client übertragen werden:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}
+
+In Ihrem Client erhalten Sie eine JSON-Response, wie etwa:
+
+```JSON
+{
+ "model_name": "alexnet",
+ "message": "Deep Learning FTW!"
+}
+```
+
+## Pfad-Parameter, die Pfade enthalten { #path-parameters-containing-paths }
+
+Angenommen, Sie haben eine *Pfadoperation* mit einem Pfad `/files/{file_path}`.
+
+Aber `file_path` soll selbst einen *Pfad* enthalten, etwa `home/johndoe/myfile.txt`.
+
+Sprich, die URL für diese Datei wäre etwas wie: `/files/home/johndoe/myfile.txt`.
+
+### OpenAPI-Unterstützung { #openapi-support }
+
+OpenAPI bietet nicht die Möglichkeit, dass ein *Pfad-Parameter* seinerseits einen *Pfad* enthalten kann, das würde zu Szenarios führen, die schwierig zu testen und zu definieren sind.
+
+Trotzdem können Sie das in **FastAPI** tun, indem Sie eines der internen Tools von Starlette verwenden.
+
+Die Dokumentation würde weiterhin funktionieren, allerdings wird nicht dokumentiert werden, dass der Parameter ein Pfad sein sollte.
+
+### Pfad-Konverter { #path-convertor }
+
+Mittels einer Option direkt von Starlette können Sie einen *Pfad-Parameter* deklarieren, der einen Pfad enthalten soll, indem Sie eine URL wie folgt definieren:
+
+```
+/files/{file_path:path}
+```
+
+In diesem Fall ist der Name des Parameters `file_path`. Der letzte Teil, `:path`, sagt aus, dass der Parameter ein *Pfad* sein soll.
+
+Sie verwenden das also wie folgt:
+
+{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}
+
+/// tip | Tipp
+
+Der Parameter könnte einen führenden Schrägstrich (`/`) haben, wie etwa in `/home/johndoe/myfile.txt`.
+
+In dem Fall wäre die URL: `/files//home/johndoe/myfile.txt`, mit einem doppelten Schrägstrich (`//`) zwischen `files` und `home`.
+
+///
+
+## Zusammenfassung { #recap }
+
+In **FastAPI** erhalten Sie mittels kurzer, intuitiver Typdeklarationen:
+
+* Editor-Unterstützung: Fehlerprüfungen, Codevervollständigung, usw.
+* Daten „parsen“
+* Datenvalidierung
+* API-Annotationen und automatische Dokumentation
+
+Und Sie müssen sie nur einmal deklarieren.
+
+Das ist wahrscheinlich der sichtbarste Unterschied zwischen **FastAPI** und alternativen Frameworks (abgesehen von der reinen Performanz).
diff --git a/docs/de/docs/tutorial/query-param-models.md b/docs/de/docs/tutorial/query-param-models.md
new file mode 100644
index 0000000000000..7d3f2d32e87b1
--- /dev/null
+++ b/docs/de/docs/tutorial/query-param-models.md
@@ -0,0 +1,68 @@
+# Query-Parameter-Modelle { #query-parameter-models }
+
+Wenn Sie eine Gruppe von **Query-Parametern** haben, die miteinander in Beziehung stehen, können Sie ein **Pydantic-Modell** erstellen, um diese zu deklarieren.
+
+Dadurch können Sie das **Modell an mehreren Stellen wiederverwenden** und gleichzeitig Validierungen und Metadaten für alle Parameter auf einmal deklarieren. 😎
+
+/// note | Hinweis
+
+Dies wird seit FastAPI Version `0.115.0` unterstützt. 🤓
+
+///
+
+## Query-Parameter mit einem Pydantic-Modell { #query-parameters-with-a-pydantic-model }
+
+Deklarieren Sie die benötigten **Query-Parameter** in einem **Pydantic-Modell** und dann den Parameter als `Query`:
+
+{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}
+
+**FastAPI** wird die Daten für **jedes Feld** aus den **Query-Parametern** des Request extrahieren und Ihnen das definierte Pydantic-Modell bereitstellen.
+
+## Die Dokumentation testen { #check-the-docs }
+
+Sie können die Query-Parameter in der Dokumentations-Oberfläche unter `/docs` einsehen:
+
+
+
+
+### Query-Parameter-Liste / Mehrere Werte mit Defaults { #query-parameter-list-multiple-values-with-defaults }
+
+Sie können auch eine Default-`list` von Werten definieren, wenn keine bereitgestellt werden:
+
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
+
+Wenn Sie zu:
+
+```
+http://localhost:8000/items/
+```
+
+gehen, wird der Default für `q` sein: `["foo", "bar"]`, und Ihre Response wird sein:
+
+```JSON
+{
+ "q": [
+ "foo",
+ "bar"
+ ]
+}
+```
+
+#### Nur `list` verwenden { #using-just-list }
+
+Sie können auch `list` direkt verwenden, anstelle von `list[str]`:
+
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
+
+/// note | Hinweis
+
+Beachten Sie, dass FastAPI in diesem Fall den Inhalt der Liste nicht überprüft.
+
+Zum Beispiel würde `list[int]` überprüfen (und dokumentieren), dass der Inhalt der Liste Ganzzahlen sind. Aber `list` alleine würde das nicht.
+
+///
+
+## Mehr Metadaten deklarieren { #declare-more-metadata }
+
+Sie können mehr Informationen über den Parameter hinzufügen.
+
+Diese Informationen werden in das generierte OpenAPI aufgenommen und von den Dokumentationsoberflächen und externen Tools verwendet.
+
+/// note | Hinweis
+
+Beachten Sie, dass verschiedene Tools möglicherweise unterschiedliche Unterstützungslevels für OpenAPI haben.
+
+Einige davon könnten noch nicht alle zusätzlichen Informationen anzuzeigen, die Sie erklärten, obwohl in den meisten Fällen die fehlende Funktionalität bereits in der Entwicklung geplant ist.
+
+///
+
+Sie können einen `title` hinzufügen:
+
+{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *}
+
+Und eine `description`:
+
+{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *}
+
+## Alias-Parameter { #alias-parameters }
+
+Stellen Sie sich vor, Sie möchten, dass der Parameter `item-query` ist.
+
+Wie in:
+
+```
+http://127.0.0.1:8000/items/?item-query=foobaritems
+```
+
+Aber `item-query` ist kein gültiger Name für eine Variable in Python.
+
+Der am ähnlichsten wäre `item_query`.
+
+Aber Sie benötigen dennoch, dass er genau `item-query` ist ...
+
+Dann können Sie ein `alias` deklarieren, und dieser Alias wird verwendet, um den Parameterwert zu finden:
+
+{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *}
+
+## Parameter als deprecatet ausweisen { #deprecating-parameters }
+
+Nehmen wir an, Ihnen gefällt dieser Parameter nicht mehr.
+
+Sie müssen ihn eine Weile dort belassen, da es Clients gibt, die ihn verwenden, aber Sie möchten, dass die Dokumentation ihn klar als deprecatet anzeigt.
+
+Dann übergeben Sie den Parameter `deprecated=True` an `Query`:
+
+{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *}
+
+Die Dokumentation wird es so anzeigen:
+
+
+
+## Parameter von OpenAPI ausschließen { #exclude-parameters-from-openapi }
+
+Um einen Query-Parameter aus dem generierten OpenAPI-Schema auszuschließen (und somit aus den automatischen Dokumentationssystemen), setzen Sie den Parameter `include_in_schema` von `Query` auf `False`:
+
+{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *}
+
+## Benutzerdefinierte Validierung { #custom-validation }
+
+Es kann Fälle geben, in denen Sie eine **benutzerdefinierte Validierung** durchführen müssen, die nicht mit den oben gezeigten Parametern durchgeführt werden kann.
+
+In diesen Fällen können Sie eine **benutzerdefinierte Validierungsfunktion** verwenden, die nach der normalen Validierung angewendet wird (z. B. nach der Validierung, dass der Wert ein `str` ist).
+
+Sie können dies mit [Pydantics `AfterValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-after-validator) innerhalb von `Annotated` erreichen.
+
+/// tip | Tipp
+
+Pydantic unterstützt auch [`BeforeValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-before-validator) und andere. 🤓
+
+///
+
+Zum Beispiel überprüft dieser benutzerdefinierte Validator, ob die Artikel-ID mit `isbn-` für eine ISBN-Buchnummer oder mit `imdb-` für eine IMDB-Film-URL-ID beginnt:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
+
+/// info | Info
+
+Dies ist verfügbar seit Pydantic Version 2 oder höher. 😎
+
+///
+
+/// tip | Tipp
+
+Wenn Sie irgendeine Art von Validierung durchführen müssen, die eine Kommunikation mit einer **externen Komponente** erfordert, wie z. B. einer Datenbank oder einer anderen API, sollten Sie stattdessen **FastAPI-Abhängigkeiten** verwenden. Sie werden diese später kennenlernen.
+
+Diese benutzerdefinierten Validatoren sind für Dinge gedacht, die einfach mit denselben **Daten** überprüft werden können, die im Request bereitgestellt werden.
+
+///
+
+### Dieses Codebeispiel verstehen { #understand-that-code }
+
+Der wichtige Punkt ist einfach die Verwendung von **`AfterValidator` mit einer Funktion innerhalb von `Annotated`**. Fühlen Sie sich frei, diesen Teil zu überspringen. 🤸
+
+---
+
+Aber wenn Sie neugierig auf dieses spezielle Codebeispiel sind und immer noch Spaß haben, hier sind einige zusätzliche Details.
+
+#### Zeichenkette mit `value.startswith()` { #string-with-value-startswith }
+
+Haben Sie bemerkt? Eine Zeichenkette mit `value.startswith()` kann ein Tuple übernehmen, und es wird jeden Wert im Tuple überprüfen:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *}
+
+#### Ein zufälliges Item { #a-random-item }
+
+Mit `data.items()` erhalten wir ein iterierbares Objekt mit Tupeln, die Schlüssel und Wert für jedes Dictionary-Element enthalten.
+
+Wir konvertieren dieses iterierbare Objekt mit `list(data.items())` in eine richtige `list`.
+
+Dann können wir mit `random.choice()` einen **zufälligen Wert** aus der Liste erhalten, also bekommen wir ein Tuple mit `(id, name)`. Es wird etwas wie `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")` sein.
+
+Dann **weisen wir diese beiden Werte** des Tupels den Variablen `id` und `name` zu.
+
+Wenn der Benutzer also keine Artikel-ID bereitgestellt hat, erhält er trotzdem einen zufälligen Vorschlag.
+
+... wir tun all dies in einer **einzelnen einfachen Zeile**. 🤯 Lieben Sie nicht auch Python? 🐍
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *}
+
+## Zusammenfassung { #recap }
+
+Sie können zusätzliche Validierungen und Metadaten für Ihre Parameter deklarieren.
+
+Allgemeine Validierungen und Metadaten:
+
+* `alias`
+* `title`
+* `description`
+* `deprecated`
+
+Validierungen, die spezifisch für Strings sind:
+
+* `min_length`
+* `max_length`
+* `pattern`
+
+Benutzerdefinierte Validierungen mit `AfterValidator`.
+
+In diesen Beispielen haben Sie gesehen, wie Sie Validierungen für `str`-Werte deklarieren.
+
+Sehen Sie sich die nächsten Kapitel an, um zu erfahren, wie Sie Validierungen für andere Typen, wie z. B. Zahlen, deklarieren.
diff --git a/docs/de/docs/tutorial/query-params.md b/docs/de/docs/tutorial/query-params.md
new file mode 100644
index 0000000000000..56aca4c2e1969
--- /dev/null
+++ b/docs/de/docs/tutorial/query-params.md
@@ -0,0 +1,187 @@
+# Query-Parameter { #query-parameters }
+
+Wenn Sie in Ihrer Funktion andere Parameter deklarieren, die nicht Teil der Pfad-Parameter sind, dann werden diese automatisch als „Query“-Parameter interpretiert.
+
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
+
+Die Query ist die Menge von Schlüssel-Wert-Paaren, die nach dem `?` in einer URL folgen und durch `&`-Zeichen getrennt sind.
+
+Zum Beispiel sind in der URL:
+
+```
+http://127.0.0.1:8000/items/?skip=0&limit=10
+```
+
+... die Query-Parameter:
+
+* `skip`: mit dem Wert `0`
+* `limit`: mit dem Wert `10`
+
+Da sie Teil der URL sind, sind sie „naturgemäß“ Strings.
+
+Aber wenn Sie sie mit Python-Typen deklarieren (im obigen Beispiel als `int`), werden sie zu diesem Typ konvertiert und gegen diesen validiert.
+
+Die gleichen Prozesse, die für Pfad-Parameter gelten, werden auch auf Query-Parameter angewendet:
+
+* Editor Unterstützung (natürlich)
+* Daten-„Parsen“
+* Datenvalidierung
+* Automatische Dokumentation
+
+## Defaultwerte { #defaults }
+
+Da Query-Parameter kein fester Teil eines Pfades sind, können sie optional sein und Defaultwerte haben.
+
+Im obigen Beispiel haben sie die Defaultwerte `skip=0` und `limit=10`.
+
+Wenn Sie also zur URL:
+
+```
+http://127.0.0.1:8000/items/
+```
+
+gehen, so ist das das gleiche wie die URL:
+
+```
+http://127.0.0.1:8000/items/?skip=0&limit=10
+```
+
+Aber wenn Sie zum Beispiel zu:
+
+```
+http://127.0.0.1:8000/items/?skip=20
+```
+
+gehen, werden die Parameterwerte Ihrer Funktion sein:
+
+* `skip=20`: da Sie das in der URL gesetzt haben
+* `limit=10`: weil das der Defaultwert ist
+
+## Optionale Parameter { #optional-parameters }
+
+Auf die gleiche Weise können Sie optionale Query-Parameter deklarieren, indem Sie deren Defaultwert auf `None` setzen:
+
+{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *}
+
+In diesem Fall wird der Funktionsparameter `q` optional und standardmäßig `None` sein.
+
+/// check | Testen
+
+Beachten Sie auch, dass **FastAPI** intelligent genug ist, um zu erkennen, dass `item_id` ein Pfad-Parameter ist und `q` keiner, daher muss letzteres ein Query-Parameter sein.
+
+///
+
+## Query-Parameter Typkonvertierung { #query-parameter-type-conversion }
+
+Sie können auch `bool`-Typen deklarieren, und sie werden konvertiert:
+
+{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *}
+
+Wenn Sie nun zu:
+
+```
+http://127.0.0.1:8000/items/foo?short=1
+```
+
+oder
+
+```
+http://127.0.0.1:8000/items/foo?short=True
+```
+
+oder
+
+```
+http://127.0.0.1:8000/items/foo?short=true
+```
+
+oder
+
+```
+http://127.0.0.1:8000/items/foo?short=on
+```
+
+oder
+
+```
+http://127.0.0.1:8000/items/foo?short=yes
+```
+
+gehen, oder zu irgendeiner anderen Variante der Groß-/Kleinschreibung (Alles groß, Anfangsbuchstabe groß, usw.), dann wird Ihre Funktion den Parameter `short` mit dem `bool`-Wert `True` sehen, ansonsten mit dem Wert `False`.
+
+## Mehrere Pfad- und Query-Parameter { #multiple-path-and-query-parameters }
+
+Sie können mehrere Pfad-Parameter und Query-Parameter gleichzeitig deklarieren, **FastAPI** weiß, welches welcher ist.
+
+Und Sie müssen sie auch nicht in einer spezifischen Reihenfolge deklarieren.
+
+Parameter werden anhand ihres Namens erkannt:
+
+{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *}
+
+## Erforderliche Query-Parameter { #required-query-parameters }
+
+Wenn Sie einen Defaultwert für Nicht-Pfad-Parameter deklarieren (Bis jetzt haben wir nur Query-Parameter gesehen), dann ist der Parameter nicht erforderlich.
+
+Wenn Sie keinen spezifischen Wert haben wollen, sondern der Parameter einfach optional sein soll, dann setzen Sie den Defaultwert auf `None`.
+
+Aber wenn Sie wollen, dass ein Query-Parameter erforderlich ist, vergeben Sie einfach keinen Defaultwert:
+
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
+
+Hier ist `needy` ein erforderlicher Query-Parameter vom Typ `str`.
+
+Wenn Sie in Ihrem Browser eine URL wie:
+
+```
+http://127.0.0.1:8000/items/foo-item
+```
+
+... öffnen, ohne den benötigten Parameter `needy`, dann erhalten Sie einen Fehler wie den folgenden:
+
+```JSON
+{
+ "detail": [
+ {
+ "type": "missing",
+ "loc": [
+ "query",
+ "needy"
+ ],
+ "msg": "Field required",
+ "input": null
+ }
+ ]
+}
+```
+
+Da `needy` ein erforderlicher Parameter ist, müssen Sie ihn in der URL setzen:
+
+```
+http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
+```
+
+... Das funktioniert:
+
+```JSON
+{
+ "item_id": "foo-item",
+ "needy": "sooooneedy"
+}
+```
+
+Und natürlich können Sie einige Parameter als erforderlich, einige mit Defaultwert, und einige als vollständig optional definieren:
+
+{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *}
+
+In diesem Fall gibt es drei Query-Parameter:
+
+* `needy`, ein erforderlicher `str`.
+* `skip`, ein `int` mit einem Defaultwert `0`.
+* `limit`, ein optionales `int`.
+
+/// tip | Tipp
+
+Sie können auch `Enum`s verwenden, auf die gleiche Weise wie mit [Pfad-Parametern](path-params.md#predefined-values).
+
+///
diff --git a/docs/de/docs/tutorial/request-files.md b/docs/de/docs/tutorial/request-files.md
new file mode 100644
index 0000000000000..a4c1318ef267a
--- /dev/null
+++ b/docs/de/docs/tutorial/request-files.md
@@ -0,0 +1,176 @@
+# Dateien im Request { #request-files }
+
+Sie können Dateien, die vom Client hochgeladen werden, mithilfe von `File` definieren.
+
+/// info | Info
+
+Um hochgeladene Dateien zu empfangen, installieren Sie zuerst [`python-multipart`](https://github.com/Kludex/python-multipart).
+
+Stellen Sie sicher, dass Sie eine [virtuelle Umgebung](../virtual-environments.md) erstellen, sie aktivieren und dann das Paket installieren, zum Beispiel:
+
+```console
+$ pip install python-multipart
+```
+
+Das liegt daran, dass hochgeladene Dateien als „Formulardaten“ gesendet werden.
+
+///
+
+## `File` importieren { #import-file }
+
+Importieren Sie `File` und `UploadFile` von `fastapi`:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
+
+## `File`-Parameter definieren { #define-file-parameters }
+
+Erstellen Sie Datei-Parameter, so wie Sie es auch mit `Body` und `Form` machen würden:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
+
+/// info | Info
+
+`File` ist eine Klasse, die direkt von `Form` erbt.
+
+Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `File` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben.
+
+///
+
+/// tip | Tipp
+
+Um Dateibodys zu deklarieren, müssen Sie `File` verwenden, da diese Parameter sonst als Query-Parameter oder Body (JSON)-Parameter interpretiert werden würden.
+
+///
+
+Die Dateien werden als „Formulardaten“ hochgeladen.
+
+Wenn Sie den Typ Ihrer *Pfadoperation-Funktion* als `bytes` deklarieren, wird **FastAPI** die Datei für Sie auslesen, und Sie erhalten den Inhalt als `bytes`.
+
+Bedenken Sie, dass das bedeutet, dass sich der gesamte Inhalt der Datei im Arbeitsspeicher befindet. Das wird für kleinere Dateien gut funktionieren.
+
+Aber es gibt viele Fälle, in denen Sie davon profitieren, `UploadFile` zu verwenden.
+
+## Datei-Parameter mit `UploadFile` { #file-parameters-with-uploadfile }
+
+Definieren Sie einen Datei-Parameter mit dem Typ `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
+
+`UploadFile` zu verwenden, hat mehrere Vorzüge gegenüber `bytes`:
+
+* Sie müssen `File()` nicht als Parameter-Defaultwert verwenden.
+* Es wird eine „gespoolte“ Datei verwendet:
+ * Eine Datei, die bis zu einem bestimmten Größen-Limit im Arbeitsspeicher behalten wird, und wenn das Limit überschritten wird, auf der Festplatte gespeichert wird.
+* Das bedeutet, es wird für große Dateien wie Bilder, Videos, große Binärdateien, usw. gut funktionieren, ohne den ganzen Arbeitsspeicher aufzubrauchen.
+* Sie können Metadaten aus der hochgeladenen Datei auslesen.
+* Es hat eine [dateiartige](https://docs.python.org/3/glossary.html#term-file-like-object) `async`hrone Schnittstelle.
+* Es stellt ein tatsächliches Python-[`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile)-Objekt bereit, welches Sie direkt anderen Bibliotheken übergeben können, die ein dateiartiges Objekt erwarten.
+
+### `UploadFile` { #uploadfile }
+
+`UploadFile` hat die folgenden Attribute:
+
+* `filename`: Ein `str` mit dem ursprünglichen Namen der hochgeladenen Datei (z. B. `meinbild.jpg`).
+* `content_type`: Ein `str` mit dem Inhaltstyp (MIME-Typ / Medientyp) (z. B. `image/jpeg`).
+* `file`: Ein [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) (ein [dateiartiges](https://docs.python.org/3/glossary.html#term-file-like-object) Objekt). Das ist das tatsächliche Python-Objekt, das Sie direkt anderen Funktionen oder Bibliotheken übergeben können, welche ein „file-like“-Objekt erwarten.
+
+`UploadFile` hat die folgenden `async`hronen Methoden. Sie alle rufen die entsprechenden Methoden des darunterliegenden Datei-Objekts auf (wobei intern `SpooledTemporaryFile` verwendet wird).
+
+* `write(daten)`: Schreibt `daten` (`str` oder `bytes`) in die Datei.
+* `read(anzahl)`: Liest `anzahl` (`int`) bytes/Zeichen aus der Datei.
+* `seek(versatz)`: Geht zur Position `versatz` (`int`) in der Datei.
+ * z. B. würde `await myfile.seek(0)` zum Anfang der Datei gehen.
+ * Das ist besonders dann nützlich, wenn Sie `await myfile.read()` einmal ausführen und dann diese Inhalte erneut auslesen müssen.
+* `close()`: Schließt die Datei.
+
+Da alle diese Methoden `async`hron sind, müssen Sie sie „await“en („erwarten“).
+
+Zum Beispiel können Sie innerhalb einer `async` *Pfadoperation-Funktion* den Inhalt wie folgt auslesen:
+
+```Python
+contents = await myfile.read()
+```
+
+Wenn Sie sich innerhalb einer normalen `def`-*Pfadoperation-Funktion* befinden, können Sie direkt auf `UploadFile.file` zugreifen, zum Beispiel:
+
+```Python
+contents = myfile.file.read()
+```
+
+/// note | Technische Details zu `async`
+
+Wenn Sie die `async`-Methoden verwenden, führt **FastAPI** die Datei-Methoden in einem Threadpool aus und erwartet sie.
+
+///
+
+/// note | Technische Details zu Starlette
+
+FastAPIs `UploadFile` erbt direkt von Starlettes `UploadFile`, fügt aber ein paar notwendige Teile hinzu, um es kompatibel mit **Pydantic** und anderen Teilen von FastAPI zu machen.
+
+///
+
+## Was sind „Formulardaten“ { #what-is-form-data }
+
+Der Weg, wie HTML-Formulare (``) die Daten zum Server senden, verwendet normalerweise eine „spezielle“ Kodierung für diese Daten. Diese unterscheidet sich von JSON.
+
+**FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten.
+
+/// note | Technische Details
+
+Daten aus Formularen werden, wenn es keine Dateien sind, normalerweise mit dem „media type“ `application/x-www-form-urlencoded` kodiert.
+
+Sollte das Formular aber Dateien enthalten, dann werden diese mit `multipart/form-data` kodiert. Wenn Sie `File` verwenden, wird **FastAPI** wissen, dass es die Dateien vom korrekten Teil des Bodys holen muss.
+
+Wenn Sie mehr über diese Kodierungen und Formularfelder lesen möchten, besuchen Sie die [MDN-Webdokumentation für `POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST).
+
+///
+
+/// warning | Achtung
+
+Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert.
+
+Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls.
+
+///
+
+## Optionaler Datei-Upload { #optional-file-upload }
+
+Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwenden und den Defaultwert auf `None` setzen:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## `UploadFile` mit zusätzlichen Metadaten { #uploadfile-with-additional-metadata }
+
+Sie können auch `File()` mit `UploadFile` verwenden, um zum Beispiel zusätzliche Metadaten zu setzen:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
+
+## Mehrere Datei-Uploads { #multiple-file-uploads }
+
+Es ist auch möglich, mehrere Dateien gleichzeitig hochzuladen.
+
+Diese werden demselben Formularfeld zugeordnet, welches mit den Formulardaten gesendet wird.
+
+Um das zu machen, deklarieren Sie eine Liste von `bytes` oder `UploadFile`s:
+
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
+
+Sie erhalten, wie deklariert, eine `list` von `bytes` oder `UploadFile`s.
+
+/// note | Technische Details
+
+Sie können auch `from starlette.responses import HTMLResponse` verwenden.
+
+**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
+
+///
+
+### Mehrere Datei-Uploads mit zusätzlichen Metadaten { #multiple-file-uploads-with-additional-metadata }
+
+Und so wie zuvor können Sie `File()` verwenden, um zusätzliche Parameter zu setzen, sogar für `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
+
+## Zusammenfassung { #recap }
+
+Verwenden Sie `File`, `bytes` und `UploadFile`, um hochladbare Dateien im Request zu deklarieren, die als Formulardaten gesendet werden.
diff --git a/docs/de/docs/tutorial/request-form-models.md b/docs/de/docs/tutorial/request-form-models.md
new file mode 100644
index 0000000000000..f3ddaee813216
--- /dev/null
+++ b/docs/de/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Formularmodelle { #form-models }
+
+Sie können **Pydantic-Modelle** verwenden, um **Formularfelder** in FastAPI zu deklarieren.
+
+/// info | Info
+
+Um Formulare zu verwenden, installieren Sie zuerst [`python-multipart`](https://github.com/Kludex/python-multipart).
+
+Stellen Sie sicher, dass Sie eine [Virtuelle Umgebung](../virtual-environments.md) erstellen, sie aktivieren und es dann installieren, zum Beispiel:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | Hinweis
+
+Dies wird seit FastAPI Version `0.113.0` unterstützt. 🤓
+
+///
+
+## Pydantic-Modelle für Formulare { #pydantic-models-for-forms }
+
+Sie müssen nur ein **Pydantic-Modell** mit den Feldern deklarieren, die Sie als **Formularfelder** erhalten möchten, und dann den Parameter als `Form` deklarieren:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
+
+**FastAPI** wird die Daten für **jedes Feld** aus den **Formulardaten** im Request **extrahieren** und Ihnen das von Ihnen definierte Pydantic-Modell übergeben.
+
+## Die Dokumentation testen { #check-the-docs }
+
+Sie können dies in der Dokumentations-UI unter `/docs` testen:
+
+
+
+
+Und beide Modelle werden auch in der interaktiven API-Dokumentation verwendet:
+
+
+
+## Andere Rückgabetyp-Annotationen { #other-return-type-annotations }
+
+Es kann Fälle geben, bei denen Sie etwas zurückgeben, das kein gültiges Pydantic-Feld ist, und Sie annotieren es in der Funktion nur, um Unterstützung von Tools zu erhalten (Editor, mypy, usw.).
+
+### Eine Response direkt zurückgeben { #return-a-response-directly }
+
+Der häufigste Anwendungsfall ist, wenn Sie [eine Response direkt zurückgeben, wie es später im Handbuch für fortgeschrittene Benutzer erläutert wird](../advanced/response-directly.md).
+
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
+
+Dieser einfache Anwendungsfall wird automatisch von FastAPI gehandhabt, weil die Annotation des Rückgabetyps die Klasse (oder eine Unterklasse von) `Response` ist.
+
+Und Tools werden auch glücklich sein, weil sowohl `RedirectResponse` als auch `JSONResponse` Unterklassen von `Response` sind, die Typannotation ist daher korrekt.
+
+### Eine Unterklasse von Response annotieren { #annotate-a-response-subclass }
+
+Sie können auch eine Unterklasse von `Response` in der Typannotation verwenden.
+
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
+
+Das wird ebenfalls funktionieren, weil `RedirectResponse` eine Unterklasse von `Response` ist, und FastAPI sich um diesen einfachen Anwendungsfall automatisch kümmert.
+
+### Ungültige Rückgabetyp-Annotationen { #invalid-return-type-annotations }
+
+Aber wenn Sie ein beliebiges anderes Objekt zurückgeben, das kein gültiger Pydantic-Typ ist (z. B. ein Datenbank-Objekt), und Sie annotieren es so in der Funktion, wird FastAPI versuchen, ein Pydantic-Responsemodell von dieser Typannotation zu erstellen, und scheitern.
+
+Das gleiche wird passieren, wenn Sie eine Union mehrerer Typen haben, und einer oder mehrere sind nicht gültige Pydantic-Typen. Zum Beispiel funktioniert folgendes nicht 💥:
+
+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
+
+... das scheitert, da die Typannotation kein Pydantic-Typ ist, und auch keine einzelne `Response`-Klasse, oder -Unterklasse, es ist eine Union (eines von beiden) von `Response` und `dict`.
+
+### Responsemodell deaktivieren { #disable-response-model }
+
+Beim Beispiel oben fortsetzend, mögen Sie vielleicht die standardmäßige Datenvalidierung, -Dokumentation, -Filterung, usw., die von FastAPI durchgeführt wird, nicht haben.
+
+Aber Sie möchten dennoch den Rückgabetyp in der Funktion annotieren, um Unterstützung von Editoren und Typcheckern (z. B. mypy) zu erhalten.
+
+In diesem Fall können Sie die Generierung des Responsemodells abschalten, indem Sie `response_model=None` setzen:
+
+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}
+
+Das bewirkt, dass FastAPI die Generierung des Responsemodells unterlässt, und damit können Sie jede gewünschte Rückgabetyp-Annotation haben, ohne dass es Ihre FastAPI-Anwendung beeinflusst. 🤓
+
+## Parameter für die Enkodierung des Responsemodells { #response-model-encoding-parameters }
+
+Ihr Responsemodell könnte Defaultwerte haben, wie:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}
+
+* `description: Union[str, None] = None` (oder `str | None = None` in Python 3.10) hat einen Defaultwert `None`.
+* `tax: float = 10.5` hat einen Defaultwert `10.5`.
+* `tags: List[str] = []` hat eine leere Liste als Defaultwert: `[]`.
+
+Aber Sie möchten diese vielleicht vom Resultat ausschließen, wenn Sie gar nicht gesetzt wurden.
+
+Wenn Sie zum Beispiel Modelle mit vielen optionalen Attributen in einer NoSQL-Datenbank haben, und Sie möchten nicht ellenlange JSON-Responses voller Defaultwerte senden.
+
+### Den `response_model_exclude_unset`-Parameter verwenden { #use-the-response-model-exclude-unset-parameter }
+
+Sie können den *Pfadoperation-Dekorator*-Parameter `response_model_exclude_unset=True` setzen:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}
+
+Die Defaultwerte werden dann nicht in der Response enthalten sein, sondern nur die tatsächlich gesetzten Werte.
+
+Wenn Sie also den Artikel mit der ID `foo` bei der *Pfadoperation* anfragen, wird (ohne die Defaultwerte) die Response sein:
+
+```JSON
+{
+ "name": "Foo",
+ "price": 50.2
+}
+```
+
+/// info | Info
+
+Sie können auch:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+verwenden, wie in der [Pydantic-Dokumentation](https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict) für `exclude_defaults` und `exclude_none` beschrieben.
+
+///
+
+#### Daten mit Werten für Felder mit Defaultwerten { #data-with-values-for-fields-with-defaults }
+
+Aber wenn Ihre Daten Werte für Modellfelder mit Defaultwerten haben, wie etwa der Artikel mit der ID `bar`:
+
+```Python hl_lines="3 5"
+{
+ "name": "Bar",
+ "description": "The bartenders",
+ "price": 62,
+ "tax": 20.2
+}
+```
+
+dann werden diese Werte in der Response enthalten sein.
+
+#### Daten mit den gleichen Werten wie die Defaultwerte { #data-with-the-same-values-as-the-defaults }
+
+Wenn Daten die gleichen Werte haben wie ihre Defaultwerte, wie etwa der Artikel mit der ID `baz`:
+
+```Python hl_lines="3 5-6"
+{
+ "name": "Baz",
+ "description": None,
+ "price": 50.2,
+ "tax": 10.5,
+ "tags": []
+}
+```
+
+dann ist FastAPI klug genug (tatsächlich ist Pydantic klug genug) zu erkennen, dass, obwohl `description`, `tax`, und `tags` die gleichen Werte haben wie ihre Defaultwerte, sie explizit gesetzt wurden (statt dass sie von den Defaultwerten genommen wurden).
+
+Diese Felder werden also in der JSON-Response enthalten sein.
+
+/// tip | Tipp
+
+Beachten Sie, dass Defaultwerte alles Mögliche sein können, nicht nur `None`.
+
+Sie können eine Liste (`[]`), ein `float` `10.5`, usw. sein.
+
+///
+
+### `response_model_include` und `response_model_exclude` { #response-model-include-and-response-model-exclude }
+
+Sie können auch die Parameter `response_model_include` und `response_model_exclude` im **Pfadoperation-Dekorator** verwenden.
+
+Diese nehmen ein `set` von `str`s entgegen, welches Namen von Attributen sind, die eingeschlossen (ohne die Anderen) oder ausgeschlossen (nur die Anderen) werden sollen.
+
+Das kann als schnelle Abkürzung verwendet werden, wenn Sie nur ein Pydantic-Modell haben und ein paar Daten von der Ausgabe ausschließen wollen.
+
+/// tip | Tipp
+
+Es wird dennoch empfohlen, dass Sie die Ideen von oben verwenden, also mehrere Klassen statt dieser Parameter.
+
+Der Grund ist, dass das das generierte JSON-Schema in der OpenAPI Ihrer Anwendung (und deren Dokumentation) dennoch das komplette Modell abbildet, selbst wenn Sie `response_model_include` oder `response_model_exclude` verwenden, um einige Attribute auszuschließen.
+
+Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert.
+
+///
+
+{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}
+
+/// tip | Tipp
+
+Die Syntax `{"name", "description"}` erzeugt ein `set` mit diesen zwei Werten.
+
+Äquivalent zu `set(["name", "description"])`.
+
+///
+
+#### `list`en statt `set`s verwenden { #using-lists-instead-of-sets }
+
+Wenn Sie vergessen, ein `set` zu verwenden, und stattdessen eine `list`e oder ein `tuple` übergeben, wird FastAPI die dennoch in ein `set` konvertieren, und es wird korrekt funktionieren:
+
+{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}
+
+## Zusammenfassung { #recap }
+
+Verwenden Sie den Parameter `response_model` im *Pfadoperation-Dekorator*, um Responsemodelle zu definieren, und besonders, um private Daten herauszufiltern.
+
+Verwenden Sie `response_model_exclude_unset`, um nur explizit gesetzte Werte zurückzugeben.
diff --git a/docs/de/docs/tutorial/response-status-code.md b/docs/de/docs/tutorial/response-status-code.md
new file mode 100644
index 0000000000000..a0018a13dcc50
--- /dev/null
+++ b/docs/de/docs/tutorial/response-status-code.md
@@ -0,0 +1,101 @@
+# Response-Statuscode { #response-status-code }
+
+Genauso wie Sie ein Responsemodell angeben können, können Sie auch den HTTP-Statuscode für die Response mit dem Parameter `status_code` in jeder der *Pfadoperationen* deklarieren:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* usw.
+
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
+
+/// note | Hinweis
+
+Beachten Sie, dass `status_code` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, wie alle anderen Parameter und der Body.
+
+///
+
+Dem `status_code`-Parameter wird eine Zahl mit dem HTTP-Statuscode übergeben.
+
+/// info | Info
+
+Alternativ kann `status_code` auch ein `IntEnum` erhalten, wie etwa Pythons [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus).
+
+///
+
+Dies wird:
+
+* Diesen Statuscode mit der Response zurücksenden.
+* Diesen im OpenAPI-Schema dokumentieren (und somit in den Benutzeroberflächen):
+
+
+
+/// note | Hinweis
+
+Einige Responsecodes (siehe nächsten Abschnitt) kennzeichnen, dass die Response keinen Body hat.
+
+FastAPI erkennt dies und erstellt eine OpenAPI-Dokumentation, die zeigt, dass es keinen Responsebody gibt.
+
+///
+
+## Über HTTP-Statuscodes { #about-http-status-codes }
+
+/// note | Hinweis
+
+Wenn Sie bereits wissen, was HTTP-Statuscodes sind, können Sie diesen Abschnitt überspringen und mit dem nächsten fortfahren.
+
+///
+
+In HTTP senden Sie einen numerischen Statuscode mit 3 Ziffern als Teil der Response.
+
+Diese Statuscodes haben einen zugeordneten Namen, um sie leichter zu erkennen, aber der wichtige Teil ist die Zahl.
+
+Kurz gefasst:
+
+* `100 - 199` stehen für „Information“. Sie verwenden diese selten direkt. Responses mit diesen Statuscodes dürfen keinen Body haben.
+* **`200 - 299`** stehen für „Successful“-Responses („Erfolgreich“). Diese werden Sie am häufigsten verwenden.
+ * `200` ist der Default-Statuscode, was bedeutet, alles ist „OK“.
+ * Ein weiteres Beispiel wäre `201`, „Created“ („Erzeugt“). Dieser wird üblicherweise verwendet, nachdem ein neuer Datensatz in der Datenbank erstellt wurde.
+ * Ein spezieller Fall ist `204`, „No Content“ („Kein Inhalt“). Diese Response wird verwendet, wenn es keinen Inhalt gibt, der an den Client zurückgeschickt werden soll, und diese Response darf daher keinen Body haben.
+* **`300 - 399`** stehen für „Redirection“ („Umleitung“). Responses mit diesen Statuscodes können einen Body haben oder nicht, außer bei `304`, „Not Modified“ („Nicht verändert“), die keinen haben darf.
+* **`400 - 499`** stehen für „Client error“-Responses („Client-Fehler“). Diese sind die zweithäufigsten, die Sie vermutlich verwenden werden.
+ * Ein Beispiel ist `404`, für eine „Not Found“-Response („Nicht gefunden“).
+ * Für allgemeine Fehler beim Client können Sie einfach `400` verwenden.
+* `500 - 599` stehen für Server-Fehler. Diese verwenden Sie fast nie direkt. Wenn in Ihrem Anwendungscode oder Server etwas schiefgeht, wird automatisch einer dieser Fehler-Statuscodes zurückgegeben.
+
+/// tip | Tipp
+
+Um mehr über die einzelnen Statuscodes zu erfahren und welcher wofür verwendet wird, sehen Sie sich die [MDN Dokumentation über HTTP-Statuscodes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) an.
+
+///
+
+## Abkürzung zur Erinnerung an die Namen { #shortcut-to-remember-the-names }
+
+Lassen Sie uns das vorherige Beispiel noch einmal anschauen:
+
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
+
+`201` ist der Statuscode für „Created“ („Erzeugt“).
+
+Aber Sie müssen sich nicht merken, was jeder dieser Codes bedeutet.
+
+Sie können die Annehmlichkeit von Variablen aus `fastapi.status` nutzen.
+
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
+
+Diese sind nur eine Annehmlichkeit, sie enthalten dieselbe Zahl, aber so können Sie die Autovervollständigung Ihres Editors verwenden, um sie zu finden:
+
+
+
+/// note | Technische Details
+
+Sie könnten auch `from starlette import status` verwenden.
+
+**FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, rein zu Ihrer Annehmlichkeit als Entwickler. Aber sie stammen direkt von Starlette.
+
+///
+
+## Den Defaultwert ändern { #changing-the-default }
+
+Später im [Handbuch für fortgeschrittene Benutzer](../advanced/response-change-status-code.md) werden Sie sehen, wie Sie einen anderen Statuscode zurückgeben können, als den Default, den Sie hier deklarieren.
diff --git a/docs/de/docs/tutorial/schema-extra-example.md b/docs/de/docs/tutorial/schema-extra-example.md
new file mode 100644
index 0000000000000..bdb67bd68f5c8
--- /dev/null
+++ b/docs/de/docs/tutorial/schema-extra-example.md
@@ -0,0 +1,202 @@
+# Beispiel-Request-Daten deklarieren { #declare-request-example-data }
+
+Sie können Beispiele für die Daten deklarieren, die Ihre App empfangen kann.
+
+Hier sind mehrere Möglichkeiten, das zu tun.
+
+## Zusätzliche JSON-Schemadaten in Pydantic-Modellen { #extra-json-schema-data-in-pydantic-models }
+
+Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, welche dem generierten JSON-Schema hinzugefügt werden.
+
+{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}
+
+Diese zusätzlichen Informationen werden unverändert zum für dieses Modell ausgegebenen **JSON-Schema** hinzugefügt und in der API-Dokumentation verwendet.
+
+Sie können das Attribut `model_config` verwenden, das ein `dict` akzeptiert, wie beschrieben in [Pydantic-Dokumentation: Configuration](https://docs.pydantic.dev/latest/api/config/).
+
+Sie können `json_schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`.
+
+/// tip | Tipp
+
+Mit derselben Technik können Sie das JSON-Schema erweitern und Ihre eigenen benutzerdefinierten Zusatzinformationen hinzufügen.
+
+Sie könnten das beispielsweise verwenden, um Metadaten für eine Frontend-Benutzeroberfläche usw. hinzuzufügen.
+
+///
+
+/// info | Info
+
+OpenAPI 3.1.0 (verwendet seit FastAPI 0.99.0) hat Unterstützung für `examples` hinzugefügt, was Teil des **JSON Schema** Standards ist.
+
+Zuvor unterstützte es nur das Schlüsselwort `example` mit einem einzigen Beispiel. Dieses wird weiterhin von OpenAPI 3.1.0 unterstützt, ist jedoch deprecatet und nicht Teil des JSON Schema Standards. Wir empfehlen Ihnen daher, von `example` nach `examples` zu migrieren. 🤓
+
+Mehr erfahren Sie am Ende dieser Seite.
+
+///
+
+## Zusätzliche Argumente für `Field` { #field-additional-arguments }
+
+Wenn Sie `Field()` mit Pydantic-Modellen verwenden, können Sie ebenfalls zusätzliche `examples` deklarieren:
+
+{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}
+
+## `examples` im JSON-Schema – OpenAPI { #examples-in-json-schema-openapi }
+
+Bei Verwendung von:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+können Sie auch eine Gruppe von `examples` mit zusätzlichen Informationen deklarieren, die zu ihren **JSON-Schemas** innerhalb von **OpenAPI** hinzugefügt werden.
+
+### `Body` mit `examples` { #body-with-examples }
+
+Hier übergeben wir `examples`, welches ein einzelnes Beispiel für die in `Body()` erwarteten Daten enthält:
+
+{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *}
+
+### Beispiel in der Dokumentations-Benutzeroberfläche { #example-in-the-docs-ui }
+
+Mit jeder der oben genannten Methoden würde es in `/docs` so aussehen:
+
+
+
+### `Body` mit mehreren `examples` { #body-with-multiple-examples }
+
+Sie können natürlich auch mehrere `examples` übergeben:
+
+{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *}
+
+Wenn Sie das tun, werden die Beispiele Teil des internen **JSON-Schemas** für diese Body-Daten.
+
+Nichtsdestotrotz unterstützt Swagger UI, das für die Anzeige der Dokumentations-Benutzeroberfläche zuständige Tool, zum Zeitpunkt der Erstellung nicht die Anzeige mehrerer Beispiele für die Daten in **JSON Schema**. Aber lesen Sie unten für einen Workaround weiter.
+
+### OpenAPI-spezifische `examples` { #openapi-specific-examples }
+
+Schon bevor **JSON Schema** `examples` unterstützte, unterstützte OpenAPI ein anderes Feld, das auch `examples` genannt wurde.
+
+Diese **OpenAPI-spezifischen** `examples` finden sich in einem anderen Abschnitt der OpenAPI-Spezifikation. Sie sind **Details für jede *Pfadoperation***, nicht für jedes JSON-Schema.
+
+Und Swagger UI unterstützt dieses spezielle Feld `examples` schon seit einiger Zeit. Sie können es also verwenden, um verschiedene **Beispiele in der Benutzeroberfläche der Dokumentation anzuzeigen**.
+
+Das Format dieses OpenAPI-spezifischen Felds `examples` ist ein `dict` mit **mehreren Beispielen** (anstelle einer `list`), jedes mit zusätzlichen Informationen, die auch zu **OpenAPI** hinzugefügt werden.
+
+Dies erfolgt nicht innerhalb jedes in OpenAPI enthaltenen JSON-Schemas, sondern außerhalb, in der *Pfadoperation*.
+
+### Verwendung des Parameters `openapi_examples` { #using-the-openapi-examples-parameter }
+
+Sie können die OpenAPI-spezifischen `examples` in FastAPI mit dem Parameter `openapi_examples` deklarieren, für:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+Die Schlüssel des `dict` identifizieren jedes Beispiel, und jeder Wert ist ein weiteres `dict`.
+
+Jedes spezifische Beispiel-`dict` in den `examples` kann Folgendes enthalten:
+
+* `summary`: Kurze Beschreibung für das Beispiel.
+* `description`: Eine lange Beschreibung, die Markdown-Text enthalten kann.
+* `value`: Dies ist das tatsächlich angezeigte Beispiel, z. B. ein `dict`.
+* `externalValue`: Alternative zu `value`, eine URL, die auf das Beispiel verweist. Allerdings wird dies möglicherweise nicht von so vielen Tools unterstützt wie `value`.
+
+Sie können es so verwenden:
+
+{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *}
+
+### OpenAPI-Beispiele in der Dokumentations-Benutzeroberfläche { #openapi-examples-in-the-docs-ui }
+
+Wenn `openapi_examples` zu `Body()` hinzugefügt wird, würde `/docs` so aussehen:
+
+
+
+## Technische Details { #technical-details }
+
+/// tip | Tipp
+
+Wenn Sie bereits **FastAPI** Version **0.99.0 oder höher** verwenden, können Sie diese Details wahrscheinlich **überspringen**.
+
+Sie sind für ältere Versionen relevanter, bevor OpenAPI 3.1.0 verfügbar war.
+
+Sie können dies als eine kurze **Geschichtsstunde** zu OpenAPI und JSON Schema betrachten. 🤓
+
+///
+
+/// warning | Achtung
+
+Dies sind sehr technische Details zu den Standards **JSON Schema** und **OpenAPI**.
+
+Wenn die oben genannten Ideen bereits für Sie funktionieren, reicht das möglicherweise aus und Sie benötigen diese Details wahrscheinlich nicht, überspringen Sie sie gerne.
+
+///
+
+Vor OpenAPI 3.1.0 verwendete OpenAPI eine ältere und modifizierte Version von **JSON Schema**.
+
+JSON Schema hatte keine `examples`, daher fügte OpenAPI seiner eigenen modifizierten Version ein eigenes `example`-Feld hinzu.
+
+OpenAPI fügte auch die Felder `example` und `examples` zu anderen Teilen der Spezifikation hinzu:
+
+* [`Parameter Object` (in der Spezifikation)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object), das verwendet wurde von FastAPIs:
+ * `Path()`
+ * `Query()`
+ * `Header()`
+ * `Cookie()`
+* [`Request Body Object` im Feld `content` des `Media Type Object`s (in der Spezifikation)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object), das verwendet wurde von FastAPIs:
+ * `Body()`
+ * `File()`
+ * `Form()`
+
+/// info | Info
+
+Dieser alte, OpenAPI-spezifische `examples`-Parameter heißt seit FastAPI `0.103.0` jetzt `openapi_examples`.
+
+///
+
+### JSON Schemas Feld `examples` { #json-schemas-examples-field }
+
+Aber dann fügte JSON Schema ein [`examples`](https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.9.5)-Feld zu einer neuen Version der Spezifikation hinzu.
+
+Und dann basierte das neue OpenAPI 3.1.0 auf der neuesten Version (JSON Schema 2020-12), die dieses neue Feld `examples` enthielt.
+
+Und jetzt hat dieses neue `examples`-Feld Vorrang vor dem alten (und benutzerdefinierten) `example`-Feld, im Singular, das jetzt deprecatet ist.
+
+Dieses neue `examples`-Feld in JSON Schema ist **nur eine `list`** von Beispielen, kein Dict mit zusätzlichen Metadaten wie an den anderen Stellen in OpenAPI (oben beschrieben).
+
+/// info | Info
+
+Selbst, nachdem OpenAPI 3.1.0 veröffentlicht wurde, mit dieser neuen, einfacheren Integration mit JSON Schema, unterstützte Swagger UI, das Tool, das die automatische Dokumentation bereitstellt, eine Zeit lang OpenAPI 3.1.0 nicht (das tut es seit Version 5.0.0 🎉).
+
+Aus diesem Grund verwendeten Versionen von FastAPI vor 0.99.0 immer noch Versionen von OpenAPI vor 3.1.0.
+
+///
+
+### Pydantic- und FastAPI-`examples` { #pydantic-and-fastapi-examples }
+
+Wenn Sie `examples` innerhalb eines Pydantic-Modells hinzufügen, indem Sie `schema_extra` oder `Field(examples=["something"])` verwenden, wird dieses Beispiel dem **JSON-Schema** für dieses Pydantic-Modell hinzugefügt.
+
+Und dieses **JSON-Schema** des Pydantic-Modells ist in der **OpenAPI** Ihrer API enthalten und wird dann in der Benutzeroberfläche der Dokumentation verwendet.
+
+In Versionen von FastAPI vor 0.99.0 (0.99.0 und höher verwenden das neuere OpenAPI 3.1.0), wenn Sie `example` oder `examples` mit einem der anderen Werkzeuge (`Query()`, `Body()`, usw.) verwendet haben, wurden diese Beispiele nicht zum JSON-Schema hinzugefügt, das diese Daten beschreibt (nicht einmal zur OpenAPI-eigenen Version von JSON Schema), sondern direkt zur *Pfadoperation*-Deklaration in OpenAPI (außerhalb der Teile von OpenAPI, die JSON Schema verwenden).
+
+Aber jetzt, da FastAPI 0.99.0 und höher, OpenAPI 3.1.0 verwendet, das JSON Schema 2020-12 verwendet, und Swagger UI 5.0.0 und höher, ist alles konsistenter und die Beispiele sind in JSON Schema enthalten.
+
+### Swagger-Benutzeroberfläche und OpenAPI-spezifische `examples` { #swagger-ui-and-openapi-specific-examples }
+
+Da die Swagger-Benutzeroberfläche derzeit nicht mehrere JSON Schema Beispiele unterstützt (Stand: 26.08.2023), hatten Benutzer keine Möglichkeit, mehrere Beispiele in der Dokumentation anzuzeigen.
+
+Um dieses Problem zu lösen, hat FastAPI `0.103.0` **Unterstützung** für die Deklaration desselben alten **OpenAPI-spezifischen** `examples`-Felds mit dem neuen Parameter `openapi_examples` hinzugefügt. 🤓
+
+### Zusammenfassung { #summary }
+
+Ich habe immer gesagt, dass ich Geschichte nicht so sehr mag ... und jetzt schauen Sie mich an, wie ich „Technikgeschichte“-Unterricht gebe. 😅
+
+Kurz gesagt: **Aktualisieren Sie auf FastAPI 0.99.0 oder höher**, und die Dinge sind viel **einfacher, konsistenter und intuitiver**, und Sie müssen nicht alle diese historischen Details kennen. 😎
diff --git a/docs/de/docs/tutorial/security/first-steps.md b/docs/de/docs/tutorial/security/first-steps.md
new file mode 100644
index 0000000000000..8a1d2fbf18697
--- /dev/null
+++ b/docs/de/docs/tutorial/security/first-steps.md
@@ -0,0 +1,205 @@
+# Sicherheit – Erste Schritte { #security-first-steps }
+
+Stellen wir uns vor, dass Sie Ihre **Backend**-API auf einer Domain haben.
+
+Und Sie haben ein **Frontend** auf einer anderen Domain oder in einem anderen Pfad derselben Domain (oder in einer Mobile-Anwendung).
+
+Und Sie möchten eine Möglichkeit haben, dass sich das Frontend mithilfe eines **Benutzernamens** und eines **Passworts** beim Backend authentisieren kann.
+
+Wir können **OAuth2** verwenden, um das mit **FastAPI** zu erstellen.
+
+Aber ersparen wir Ihnen die Zeit, die gesamte lange Spezifikation zu lesen, nur um die kleinen Informationen zu finden, die Sie benötigen.
+
+Lassen Sie uns die von **FastAPI** bereitgestellten Tools verwenden, um Sicherheit zu gewährleisten.
+
+## Wie es aussieht { #how-it-looks }
+
+Lassen Sie uns zunächst einfach den Code verwenden und sehen, wie er funktioniert, und dann kommen wir zurück, um zu verstehen, was passiert.
+
+## `main.py` erstellen { #create-main-py }
+
+Kopieren Sie das Beispiel in eine Datei `main.py`:
+
+{* ../../docs_src/security/tutorial001_an_py310.py *}
+
+## Ausführen { #run-it }
+
+/// info | Info
+
+Das Paket [`python-multipart`](https://github.com/Kludex/python-multipart) wird automatisch mit **FastAPI** installiert, wenn Sie den Befehl `pip install "fastapi[standard]"` ausführen.
+
+Wenn Sie jedoch den Befehl `pip install fastapi` verwenden, ist das Paket `python-multipart` nicht standardmäßig enthalten.
+
+Um es manuell zu installieren, stellen Sie sicher, dass Sie eine [virtuelle Umgebung](../../virtual-environments.md) erstellen, sie aktivieren und es dann mit:
+
+```console
+$ pip install python-multipart
+```
+
+installieren.
+
+Das liegt daran, dass **OAuth2** „Formulardaten“ zum Senden von `username` und `password` verwendet.
+
+///
+
+Führen Sie das Beispiel aus mit:
+
+
+
+/// check | Authorize-Button!
+
+Sie haben bereits einen glänzenden, neuen „Authorize“-Button.
+
+Und Ihre *Pfadoperation* hat in der oberen rechten Ecke ein kleines Schloss, auf das Sie klicken können.
+
+///
+
+Und wenn Sie darauf klicken, erhalten Sie ein kleines Anmeldeformular zur Eingabe eines `username` und `password` (und anderer optionaler Felder):
+
+
+
+/// note | Hinweis
+
+Es spielt keine Rolle, was Sie in das Formular eingeben, es wird noch nicht funktionieren. Wir kommen dahin.
+
+///
+
+Dies ist natürlich nicht das Frontend für die Endbenutzer, aber es ist ein großartiges automatisches Tool, um Ihre gesamte API interaktiv zu dokumentieren.
+
+Es kann vom Frontend-Team verwendet werden (das auch Sie selbst sein können).
+
+Es kann von Anwendungen und Systemen Dritter verwendet werden.
+
+Und es kann auch von Ihnen selbst verwendet werden, um dieselbe Anwendung zu debuggen, zu prüfen und zu testen.
+
+## Der `password`-Flow { #the-password-flow }
+
+Lassen Sie uns nun etwas zurückgehen und verstehen, was das alles ist.
+
+Der `password`-„Flow“ ist eine der in OAuth2 definierten Wege („Flows“) zur Handhabung von Sicherheit und Authentifizierung.
+
+OAuth2 wurde so konzipiert, dass das Backend oder die API unabhängig vom Server sein kann, der den Benutzer authentifiziert.
+
+In diesem Fall handhabt jedoch dieselbe **FastAPI**-Anwendung sowohl die API als auch die Authentifizierung.
+
+Betrachten wir es also aus dieser vereinfachten Sicht:
+
+* Der Benutzer gibt den `username` und das `password` im Frontend ein und drückt `Enter`.
+* Das Frontend (das im Browser des Benutzers läuft) sendet diesen `username` und das `password` an eine bestimmte URL in unserer API (deklariert mit `tokenUrl="token"`).
+* Die API überprüft den `username` und das `password` und antwortet mit einem „Token“ (wir haben davon noch nichts implementiert).
+ * Ein „Token“ ist lediglich ein String mit einem Inhalt, den wir später verwenden können, um diesen Benutzer zu verifizieren.
+ * Normalerweise läuft ein Token nach einiger Zeit ab.
+ * Daher muss sich der Benutzer irgendwann später erneut anmelden.
+ * Und wenn der Token gestohlen wird, ist das Risiko geringer. Es handelt sich nicht um einen dauerhaften Schlüssel, der (in den meisten Fällen) für immer funktioniert.
+* Das Frontend speichert diesen Token vorübergehend irgendwo.
+* Der Benutzer klickt im Frontend, um zu einem anderen Abschnitt der Frontend-Web-Anwendung zu gelangen.
+* Das Frontend muss weitere Daten von der API abrufen.
+ * Es benötigt jedoch eine Authentifizierung für diesen bestimmten Endpunkt.
+ * Um sich also bei unserer API zu authentifizieren, sendet es einen `Authorization`-Header mit dem Wert `Bearer ` plus dem Token.
+ * Wenn der Token `foobar` enthielte, wäre der Inhalt des `Authorization`-Headers: `Bearer foobar`.
+
+## **FastAPI**s `OAuth2PasswordBearer` { #fastapis-oauth2passwordbearer }
+
+**FastAPI** bietet mehrere Tools auf unterschiedlichen Abstraktionsebenen zur Implementierung dieser Sicherheitsfunktionen.
+
+In diesem Beispiel verwenden wir **OAuth2** mit dem **Password**-Flow und einem **Bearer**-Token. Wir machen das mit der Klasse `OAuth2PasswordBearer`.
+
+/// info | Info
+
+Ein „Bearer“-Token ist nicht die einzige Option.
+
+Aber es ist die beste für unseren Anwendungsfall.
+
+Und es ist wahrscheinlich auch für die meisten anderen Anwendungsfälle die beste, es sei denn, Sie sind ein OAuth2-Experte und wissen genau, warum es eine andere Option gibt, die Ihren Anforderungen besser entspricht.
+
+In dem Fall gibt Ihnen **FastAPI** ebenfalls die Tools, die Sie zum Erstellen brauchen.
+
+///
+
+Wenn wir eine Instanz der Klasse `OAuth2PasswordBearer` erstellen, übergeben wir den Parameter `tokenUrl`. Dieser Parameter enthält die URL, die der Client (das Frontend, das im Browser des Benutzers ausgeführt wird) verwendet, wenn er den `username` und das `password` sendet, um einen Token zu erhalten.
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
+
+/// tip | Tipp
+
+Hier bezieht sich `tokenUrl="token"` auf eine relative URL `token`, die wir noch nicht erstellt haben. Da es sich um eine relative URL handelt, entspricht sie `./token`.
+
+Da wir eine relative URL verwenden, würde sich das, wenn sich Ihre API unter `https://example.com/` befindet, auf `https://example.com/token` beziehen. Wenn sich Ihre API jedoch unter `https://example.com/api/v1/` befände, würde es sich auf `https://example.com/api/v1/token` beziehen.
+
+Die Verwendung einer relativen URL ist wichtig, um sicherzustellen, dass Ihre Anwendung auch in einem fortgeschrittenen Anwendungsfall, wie [Hinter einem Proxy](../../advanced/behind-a-proxy.md), weiterhin funktioniert.
+
+///
+
+Dieser Parameter erstellt nicht diesen Endpunkt / diese *Pfadoperation*, sondern deklariert, dass die URL `/token` diejenige sein wird, die der Client verwenden soll, um den Token abzurufen. Diese Information wird in OpenAPI und dann in den interaktiven API-Dokumentationssystemen verwendet.
+
+Wir werden demnächst auch die eigentliche Pfadoperation erstellen.
+
+/// info | Info
+
+Wenn Sie ein sehr strenger „Pythonista“ sind, missfällt Ihnen möglicherweise die Schreibweise des Parameternamens `tokenUrl` anstelle von `token_url`.
+
+Das liegt daran, dass FastAPI denselben Namen wie in der OpenAPI-Spezifikation verwendet. Sodass Sie, wenn Sie mehr über eines dieser Sicherheitsschemas herausfinden möchten, den Namen einfach kopieren und einfügen können, um weitere Informationen darüber zu erhalten.
+
+///
+
+Die Variable `oauth2_scheme` ist eine Instanz von `OAuth2PasswordBearer`, aber auch ein „Callable“.
+
+Es könnte wie folgt aufgerufen werden:
+
+```Python
+oauth2_scheme(some, parameters)
+```
+
+Es kann also mit `Depends` verwendet werden.
+
+### Verwenden { #use-it }
+
+Jetzt können Sie dieses `oauth2_scheme` als Abhängigkeit `Depends` übergeben.
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+Diese Abhängigkeit stellt einen `str` bereit, der dem Parameter `token` der *Pfadoperation-Funktion* zugewiesen wird.
+
+**FastAPI** weiß, dass es diese Abhängigkeit verwenden kann, um ein „Sicherheitsschema“ im OpenAPI-Schema (und der automatischen API-Dokumentation) zu definieren.
+
+/// info | Technische Details
+
+**FastAPI** weiß, dass es die Klasse `OAuth2PasswordBearer` (deklariert in einer Abhängigkeit) verwenden kann, um das Sicherheitsschema in OpenAPI zu definieren, da es von `fastapi.security.oauth2.OAuth2` erbt, das wiederum von `fastapi.security.base.SecurityBase` erbt.
+
+Alle Sicherheits-Werkzeuge, die in OpenAPI integriert sind (und die automatische API-Dokumentation), erben von `SecurityBase`, so weiß **FastAPI**, wie es sie in OpenAPI integrieren muss.
+
+///
+
+## Was es macht { #what-it-does }
+
+FastAPI wird im Request nach diesem `Authorization`-Header suchen, prüfen, ob der Wert `Bearer ` plus ein Token ist, und den Token als `str` zurückgeben.
+
+Wenn es keinen `Authorization`-Header sieht, oder der Wert keinen `Bearer `-Token hat, antwortet es direkt mit einem 401-Statuscode-Error (`UNAUTHORIZED`).
+
+Sie müssen nicht einmal prüfen, ob der Token existiert, um einen Fehler zurückzugeben. Seien Sie sicher, dass Ihre Funktion, wenn sie ausgeführt wird, ein `str` in diesem Token enthält.
+
+Sie können das bereits in der interaktiven Dokumentation ausprobieren:
+
+
+
+Wir überprüfen im Moment noch nicht die Gültigkeit des Tokens, aber das ist bereits ein Anfang.
+
+## Zusammenfassung { #recap }
+
+Mit nur drei oder vier zusätzlichen Zeilen haben Sie so bereits eine primitive Form der Sicherheit.
diff --git a/docs/de/docs/tutorial/security/get-current-user.md b/docs/de/docs/tutorial/security/get-current-user.md
new file mode 100644
index 0000000000000..cfb59ff12f016
--- /dev/null
+++ b/docs/de/docs/tutorial/security/get-current-user.md
@@ -0,0 +1,105 @@
+# Aktuellen Benutzer abrufen { #get-current-user }
+
+Im vorherigen Kapitel hat das Sicherheitssystem (das auf dem Dependency Injection System basiert) der *Pfadoperation-Funktion* einen `token` vom Typ `str` überreicht:
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+Aber das ist immer noch nicht so nützlich.
+
+Lassen wir es uns den aktuellen Benutzer überreichen.
+
+## Ein Benutzermodell erstellen { #create-a-user-model }
+
+Erstellen wir zunächst ein Pydantic-Benutzermodell.
+
+So wie wir Pydantic zum Deklarieren von Bodys verwenden, können wir es auch überall sonst verwenden:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *}
+
+## Eine `get_current_user`-Abhängigkeit erstellen { #create-a-get-current-user-dependency }
+
+Erstellen wir eine Abhängigkeit `get_current_user`.
+
+Erinnern Sie sich, dass Abhängigkeiten Unterabhängigkeiten haben können?
+
+`get_current_user` wird seinerseits von `oauth2_scheme` abhängen, das wir zuvor erstellt haben.
+
+So wie wir es zuvor in der *Pfadoperation* direkt gemacht haben, erhält unsere neue Abhängigkeit `get_current_user` von der Unterabhängigkeit `oauth2_scheme` einen `token` vom Typ `str`:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *}
+
+## Den Benutzer abrufen { #get-the-user }
+
+`get_current_user` wird eine von uns erstellte (gefakte) Hilfsfunktion verwenden, welche einen Token vom Typ `str` entgegennimmt und unser Pydantic-`User`-Modell zurückgibt:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *}
+
+## Den aktuellen Benutzer einfügen { #inject-the-current-user }
+
+Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der *Pfadoperation* verwenden:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *}
+
+Beachten Sie, dass wir als Typ von `current_user` das Pydantic-Modell `User` deklarieren.
+
+Das wird uns innerhalb der Funktion bei Codevervollständigung und Typprüfungen helfen.
+
+/// tip | Tipp
+
+Sie erinnern sich vielleicht, dass Requestbodys ebenfalls mit Pydantic-Modellen deklariert werden.
+
+Weil Sie `Depends` verwenden, wird **FastAPI** hier aber nicht verwirrt.
+
+///
+
+/// check | Testen
+
+Die Art und Weise, wie dieses System von Abhängigkeiten konzipiert ist, ermöglicht es uns, verschiedene Abhängigkeiten (verschiedene „Dependables“) zu haben, die alle ein `User`-Modell zurückgeben.
+
+Wir sind nicht darauf beschränkt, nur eine Abhängigkeit zu haben, die diesen Typ von Daten zurückgeben kann.
+
+///
+
+## Andere Modelle { #other-models }
+
+Sie können jetzt den aktuellen Benutzer direkt in den *Pfadoperation-Funktionen* abrufen und die Sicherheitsmechanismen auf **Dependency Injection** Ebene handhaben, mittels `Depends`.
+
+Und Sie können alle Modelle und Daten für die Sicherheitsanforderungen verwenden (in diesem Fall ein Pydantic-Modell `User`).
+
+Sie sind jedoch nicht auf die Verwendung von bestimmten Datenmodellen, Klassen, oder Typen beschränkt.
+
+Möchten Sie eine `id` und eine `email` und keinen `username` in Ihrem Modell haben? Kein Problem. Sie können dieselben Tools verwenden.
+
+Möchten Sie nur ein `str` haben? Oder nur ein `dict`? Oder direkt eine Instanz eines Modells einer Datenbank-Klasse? Es funktioniert alles auf die gleiche Weise.
+
+Sie haben eigentlich keine Benutzer, die sich bei Ihrer Anwendung anmelden, sondern Roboter, Bots oder andere Systeme, die nur über einen Zugriffstoken verfügen? Auch hier funktioniert alles gleich.
+
+Verwenden Sie einfach jede Art von Modell, jede Art von Klasse, jede Art von Datenbank, die Sie für Ihre Anwendung benötigen. **FastAPI** deckt das alles mit seinem Dependency Injection System ab.
+
+## Codegröße { #code-size }
+
+Dieses Beispiel mag ausführlich erscheinen. Bedenken Sie, dass wir Sicherheit, Datenmodelle, Hilfsfunktionen und *Pfadoperationen* in derselben Datei vermischen.
+
+Aber hier ist der entscheidende Punkt.
+
+Der Code für Sicherheit und Dependency Injection wird einmal geschrieben.
+
+Sie können es so komplex gestalten, wie Sie möchten. Und dennoch haben Sie es nur einmal geschrieben, an einer einzigen Stelle. Mit all der Flexibilität.
+
+Aber Sie können Tausende von Endpunkten (*Pfadoperationen*) haben, die dasselbe Sicherheitssystem verwenden.
+
+Und alle (oder beliebige Teile davon) können Vorteil ziehen aus der Wiederverwendung dieser und anderer von Ihnen erstellter Abhängigkeiten.
+
+Und alle diese Tausenden von *Pfadoperationen* können nur drei Zeilen lang sein:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *}
+
+## Zusammenfassung { #recap }
+
+Sie können jetzt den aktuellen Benutzer direkt in Ihrer *Pfadoperation-Funktion* abrufen.
+
+Wir haben bereits die Hälfte geschafft.
+
+Wir müssen jetzt nur noch eine *Pfadoperation* hinzufügen, mittels der der Benutzer/Client tatsächlich seinen `username` und `password` senden kann.
+
+Das kommt als nächstes.
diff --git a/docs/de/docs/tutorial/security/index.md b/docs/de/docs/tutorial/security/index.md
new file mode 100644
index 0000000000000..6330d3d9dc601
--- /dev/null
+++ b/docs/de/docs/tutorial/security/index.md
@@ -0,0 +1,106 @@
+# Sicherheit { #security }
+
+Es gibt viele Wege, Sicherheit, Authentifizierung und Autorisierung zu handhaben.
+
+Und normalerweise ist es ein komplexes und „schwieriges“ Thema.
+
+In vielen Frameworks und Systemen erfordert allein die Handhabung von Sicherheit und Authentifizierung viel Aufwand und Code (in vielen Fällen kann er 50 % oder mehr des gesamten geschriebenen Codes ausmachen).
+
+**FastAPI** bietet mehrere Tools, die Ihnen helfen, schnell und auf standardisierte Weise mit **Sicherheit** umzugehen, ohne alle Sicherheits-Spezifikationen studieren und erlernen zu müssen.
+
+Aber schauen wir uns zunächst ein paar kleine Konzepte an.
+
+## In Eile? { #in-a-hurry }
+
+Wenn Ihnen diese Begriffe egal sind und Sie einfach *jetzt* Sicherheit mit Authentifizierung basierend auf Benutzername und Passwort hinzufügen müssen, fahren Sie mit den nächsten Kapiteln fort.
+
+## OAuth2 { #oauth2 }
+
+OAuth2 ist eine Spezifikation, die verschiedene Möglichkeiten zur Handhabung von Authentifizierung und Autorisierung definiert.
+
+Es handelt sich um eine recht umfangreiche Spezifikation, und sie deckt mehrere komplexe Anwendungsfälle ab.
+
+Sie umfasst Möglichkeiten zur Authentifizierung mithilfe eines „Dritten“.
+
+Das ist es, was alle diese „Login mit Facebook, Google, X (Twitter), GitHub“-Systeme unter der Haube verwenden.
+
+### OAuth 1 { #oauth-1 }
+
+Es gab ein OAuth 1, das sich stark von OAuth2 unterscheidet und komplexer ist, da es direkte Spezifikationen enthält, wie die Kommunikation verschlüsselt wird.
+
+Heutzutage ist es nicht sehr populär und wird kaum verwendet.
+
+OAuth2 spezifiziert nicht, wie die Kommunikation verschlüsselt werden soll, sondern erwartet, dass Ihre Anwendung mit HTTPS bereitgestellt wird.
+
+/// tip | Tipp
+
+Im Abschnitt über **Deployment** erfahren Sie, wie Sie HTTPS mithilfe von Traefik und Let's Encrypt kostenlos einrichten.
+
+///
+
+## OpenID Connect { #openid-connect }
+
+OpenID Connect ist eine weitere Spezifikation, die auf **OAuth2** basiert.
+
+Sie erweitert lediglich OAuth2, indem sie einige Dinge spezifiziert, die in OAuth2 relativ mehrdeutig sind, um zu versuchen, es interoperabler zu machen.
+
+Beispielsweise verwendet der Google Login OpenID Connect (welches seinerseits OAuth2 verwendet).
+
+Aber der Facebook Login unterstützt OpenID Connect nicht. Es hat seine eigene Variante von OAuth2.
+
+### OpenID (nicht „OpenID Connect“) { #openid-not-openid-connect }
+
+Es gab auch eine „OpenID“-Spezifikation. Sie versuchte das Gleiche zu lösen wie **OpenID Connect**, basierte aber nicht auf OAuth2.
+
+Es handelte sich also um ein komplett zusätzliches System.
+
+Heutzutage ist es nicht sehr populär und wird kaum verwendet.
+
+## OpenAPI { #openapi }
+
+OpenAPI (früher bekannt als Swagger) ist die offene Spezifikation zum Erstellen von APIs (jetzt Teil der Linux Foundation).
+
+**FastAPI** basiert auf **OpenAPI**.
+
+Das ist es, was erlaubt, mehrere automatische interaktive Dokumentations-Oberflächen, Codegenerierung, usw. zu haben.
+
+OpenAPI bietet die Möglichkeit, mehrere Sicherheits„systeme“ zu definieren.
+
+Durch deren Verwendung können Sie alle diese Standards-basierten Tools nutzen, einschließlich dieser interaktiven Dokumentationssysteme.
+
+OpenAPI definiert die folgenden Sicherheitsschemas:
+
+* `apiKey`: ein anwendungsspezifischer Schlüssel, der stammen kann von:
+ * Einem Query-Parameter.
+ * Einem Header.
+ * Einem Cookie.
+* `http`: Standard-HTTP-Authentifizierungssysteme, einschließlich:
+ * `bearer`: ein Header `Authorization` mit dem Wert `Bearer ` plus einem Token. Dies wird von OAuth2 geerbt.
+ * HTTP Basic Authentication.
+ * HTTP Digest, usw.
+* `oauth2`: Alle OAuth2-Methoden zum Umgang mit Sicherheit (genannt „Flows“).
+ * Mehrere dieser Flows eignen sich zum Aufbau eines OAuth 2.0-Authentifizierungsanbieters (wie Google, Facebook, X (Twitter), GitHub usw.):
+ * `implicit`
+ * `clientCredentials`
+ * `authorizationCode`
+ * Es gibt jedoch einen bestimmten „Flow“, der perfekt für die direkte Abwicklung der Authentifizierung in derselben Anwendung verwendet werden kann:
+ * `password`: Einige der nächsten Kapitel werden Beispiele dafür behandeln.
+* `openIdConnect`: bietet eine Möglichkeit, zu definieren, wie OAuth2-Authentifizierungsdaten automatisch ermittelt werden können.
+ * Diese automatische Erkennung ist es, die in der OpenID Connect Spezifikation definiert ist.
+
+
+/// tip | Tipp
+
+Auch die Integration anderer Authentifizierungs-/Autorisierungsanbieter wie Google, Facebook, X (Twitter), GitHub, usw. ist möglich und relativ einfach.
+
+Das komplexeste Problem besteht darin, einen Authentifizierungs-/Autorisierungsanbieter wie solche aufzubauen, aber **FastAPI** reicht Ihnen die Tools, das einfach zu erledigen, während Ihnen die schwere Arbeit abgenommen wird.
+
+///
+
+## **FastAPI** Tools { #fastapi-utilities }
+
+FastAPI stellt für jedes dieser Sicherheitsschemas im Modul `fastapi.security` verschiedene Tools bereit, die die Verwendung dieser Sicherheitsmechanismen vereinfachen.
+
+In den nächsten Kapiteln erfahren Sie, wie Sie mit diesen von **FastAPI** bereitgestellten Tools Sicherheit zu Ihrer API hinzufügen.
+
+Und Sie werden auch sehen, wie dies automatisch in das interaktive Dokumentationssystem integriert wird.
diff --git a/docs/de/docs/tutorial/security/oauth2-jwt.md b/docs/de/docs/tutorial/security/oauth2-jwt.md
new file mode 100644
index 0000000000000..2f727b167adf0
--- /dev/null
+++ b/docs/de/docs/tutorial/security/oauth2-jwt.md
@@ -0,0 +1,277 @@
+# OAuth2 mit Passwort (und Hashing), Bearer mit JWT-Tokens { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
+
+Da wir nun über den gesamten Sicherheitsablauf verfügen, machen wir die Anwendung tatsächlich sicher, indem wir JWT-Tokens und sicheres Passwort-Hashing verwenden.
+
+Diesen Code können Sie tatsächlich in Ihrer Anwendung verwenden, die Passwort-Hashes in Ihrer Datenbank speichern, usw.
+
+Wir bauen auf dem vorherigen Kapitel auf.
+
+## Über JWT { #about-jwt }
+
+JWT bedeutet „JSON Web Tokens“.
+
+Es ist ein Standard, um ein JSON-Objekt in einem langen, kompakten String ohne Leerzeichen zu kodieren. Das sieht so aus:
+
+```
+eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
+```
+
+Da er nicht verschlüsselt ist, kann jeder die Informationen aus dem Inhalt wiederherstellen.
+
+Aber er ist signiert. Wenn Sie also einen von Ihnen gesendeten Token zurückerhalten, können Sie überprüfen, ob Sie ihn tatsächlich gesendet haben.
+
+Auf diese Weise können Sie einen Token mit einer Gültigkeitsdauer von beispielsweise einer Woche erstellen. Und wenn der Benutzer am nächsten Tag mit dem Token zurückkommt, wissen Sie, dass der Benutzer immer noch bei Ihrem System angemeldet ist.
+
+Nach einer Woche läuft der Token ab und der Benutzer wird nicht autorisiert und muss sich erneut anmelden, um einen neuen Token zu erhalten. Und wenn der Benutzer (oder ein Dritter) versuchen würde, den Token zu ändern, um das Ablaufdatum zu ändern, würden Sie das entdecken, weil die Signaturen nicht übereinstimmen würden.
+
+Wenn Sie mit JWT-Tokens spielen und sehen möchten, wie sie funktionieren, schauen Sie sich [https://jwt.io](https://jwt.io/) an.
+
+## `PyJWT` installieren { #install-pyjwt }
+
+Wir müssen `PyJWT` installieren, um die JWT-Tokens in Python zu generieren und zu verifizieren.
+
+Stellen Sie sicher, dass Sie eine [virtuelle Umgebung](../../virtual-environments.md) erstellen, sie aktivieren und dann `pyjwt` installieren:
+
+
+
+Melden Sie sich bei der Anwendung auf die gleiche Weise wie zuvor an.
+
+Verwenden Sie die Anmeldeinformationen:
+
+Benutzername: `johndoe`
+Passwort: `secret`
+
+/// check | Testen
+
+Beachten Sie, dass im Code nirgendwo das Klartext-Passwort „`secret`“ steht, wir haben nur die gehashte Version.
+
+///
+
+
+
+Rufen Sie den Endpunkt `/users/me/` auf, Sie erhalten die Response:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false
+}
+```
+
+
+
+Wenn Sie die Developer Tools öffnen, können Sie sehen, dass die gesendeten Daten nur den Token enthalten. Das Passwort wird nur beim ersten Request gesendet, um den Benutzer zu authentisieren und diesen Zugriffstoken zu erhalten, aber nicht mehr danach:
+
+
+
+/// note | Hinweis
+
+Beachten Sie den Header `Authorization` mit einem Wert, der mit `Bearer ` beginnt.
+
+///
+
+## Fortgeschrittene Verwendung mit `scopes` { #advanced-usage-with-scopes }
+
+OAuth2 hat ein Konzept von „Scopes“.
+
+Sie können diese verwenden, um einem JWT-Token einen bestimmten Satz von Berechtigungen zu übergeben.
+
+Anschließend können Sie diesen Token einem Benutzer direkt oder einem Dritten geben, damit diese mit einer Reihe von Einschränkungen mit Ihrer API interagieren können.
+
+Wie Sie sie verwenden und wie sie in **FastAPI** integriert sind, erfahren Sie später im **Handbuch für fortgeschrittene Benutzer**.
+
+## Zusammenfassung { #recap }
+
+Mit dem, was Sie bis hier gesehen haben, können Sie eine sichere **FastAPI**-Anwendung mithilfe von Standards wie OAuth2 und JWT einrichten.
+
+In fast jedem Framework wird die Handhabung der Sicherheit recht schnell zu einem ziemlich komplexen Thema.
+
+Viele Packages, die es stark vereinfachen, müssen viele Kompromisse beim Datenmodell, der Datenbank und den verfügbaren Funktionen eingehen. Und einige dieser Pakete, die die Dinge zu sehr vereinfachen, weisen tatsächlich Sicherheitslücken auf.
+
+---
+
+**FastAPI** geht bei keiner Datenbank, keinem Datenmodell oder Tool Kompromisse ein.
+
+Es gibt Ihnen die volle Flexibilität, diejenigen auszuwählen, die am besten zu Ihrem Projekt passen.
+
+Und Sie können viele gut gepflegte und weit verbreitete Packages wie `pwdlib` und `PyJWT` direkt verwenden, da **FastAPI** keine komplexen Mechanismen zur Integration externer Pakete erfordert.
+
+Aber es bietet Ihnen die Werkzeuge, um den Prozess so weit wie möglich zu vereinfachen, ohne Kompromisse bei Flexibilität, Robustheit oder Sicherheit einzugehen.
+
+Und Sie können sichere Standardprotokolle wie OAuth2 auf relativ einfache Weise verwenden und implementieren.
+
+Im **Handbuch für fortgeschrittene Benutzer** erfahren Sie mehr darüber, wie Sie OAuth2-„Scopes“ für ein feingranuliertes Berechtigungssystem verwenden, das denselben Standards folgt. OAuth2 mit Scopes ist der Mechanismus, der von vielen großen Authentifizierungsanbietern wie Facebook, Google, GitHub, Microsoft, X (Twitter), usw. verwendet wird, um Drittanbieteranwendungen zu autorisieren, im Namen ihrer Benutzer mit ihren APIs zu interagieren.
diff --git a/docs/de/docs/tutorial/security/simple-oauth2.md b/docs/de/docs/tutorial/security/simple-oauth2.md
new file mode 100644
index 0000000000000..32720706edd64
--- /dev/null
+++ b/docs/de/docs/tutorial/security/simple-oauth2.md
@@ -0,0 +1,289 @@
+# Einfaches OAuth2 mit Password und Bearer { #simple-oauth2-with-password-and-bearer }
+
+Lassen Sie uns nun auf dem vorherigen Kapitel aufbauen und die fehlenden Teile hinzufügen, um einen vollständigen Sicherheits-Flow zu erhalten.
+
+## `username` und `password` entgegennehmen { #get-the-username-and-password }
+
+Wir werden **FastAPIs** Sicherheits-Werkzeuge verwenden, um den `username` und das `password` entgegenzunehmen.
+
+OAuth2 spezifiziert, dass der Client/Benutzer bei Verwendung des „Password Flow“ (den wir verwenden) die Felder `username` und `password` als Formulardaten senden muss.
+
+Und die Spezifikation sagt, dass die Felder so benannt werden müssen. `user-name` oder `email` würde also nicht funktionieren.
+
+Aber keine Sorge, Sie können sie Ihren Endbenutzern im Frontend so anzeigen, wie Sie möchten.
+
+Und Ihre Datenbankmodelle können beliebige andere Namen verwenden.
+
+Aber für die Login-*Pfadoperation* müssen wir diese Namen verwenden, um mit der Spezifikation kompatibel zu sein (und beispielsweise das integrierte API-Dokumentationssystem verwenden zu können).
+
+Die Spezifikation besagt auch, dass `username` und `password` als Formulardaten gesendet werden müssen (hier also kein JSON).
+
+### `scope` { #scope }
+
+Ferner sagt die Spezifikation, dass der Client ein weiteres Formularfeld "`scope`" („Geltungsbereich“) senden kann.
+
+Der Name des Formularfelds lautet `scope` (im Singular), tatsächlich handelt es sich jedoch um einen langen String mit durch Leerzeichen getrennten „Scopes“.
+
+Jeder „Scope“ ist nur ein String (ohne Leerzeichen).
+
+Diese werden normalerweise verwendet, um bestimmte Sicherheitsberechtigungen zu deklarieren, zum Beispiel:
+
+* `users:read` oder `users:write` sind gängige Beispiele.
+* `instagram_basic` wird von Facebook / Instagram verwendet.
+* `https://www.googleapis.com/auth/drive` wird von Google verwendet.
+
+/// info | Info
+
+In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert.
+
+Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist.
+
+Diese Details sind implementierungsspezifisch.
+
+Für OAuth2 sind es einfach nur Strings.
+
+///
+
+## Code, um `username` und `password` entgegenzunehmen { #code-to-get-the-username-and-password }
+
+Lassen Sie uns nun die von **FastAPI** bereitgestellten Werkzeuge verwenden, um das zu erledigen.
+
+### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform }
+
+Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als Abhängigkeit mit `Depends` in der *Pfadoperation* für `/token`:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}
+
+`OAuth2PasswordRequestForm` ist eine Klassenabhängigkeit, die einen Formularbody deklariert mit:
+
+* Dem `username`.
+* Dem `password`.
+* Einem optionalen `scope`-Feld als langem String, bestehend aus durch Leerzeichen getrennten Strings.
+* Einem optionalen `grant_type`.
+
+/// tip | Tipp
+
+Die OAuth2-Spezifikation *erfordert* tatsächlich ein Feld `grant_type` mit dem festen Wert `password`, aber `OAuth2PasswordRequestForm` erzwingt dies nicht.
+
+Wenn Sie es erzwingen müssen, verwenden Sie `OAuth2PasswordRequestFormStrict` anstelle von `OAuth2PasswordRequestForm`.
+
+///
+
+* Eine optionale `client_id` (benötigen wir für unser Beispiel nicht).
+* Ein optionales `client_secret` (benötigen wir für unser Beispiel nicht).
+
+/// info | Info
+
+`OAuth2PasswordRequestForm` ist keine spezielle Klasse für **FastAPI**, so wie `OAuth2PasswordBearer`.
+
+`OAuth2PasswordBearer` lässt **FastAPI** wissen, dass es sich um ein Sicherheitsschema handelt. Daher wird es auf diese Weise zu OpenAPI hinzugefügt.
+
+Aber `OAuth2PasswordRequestForm` ist nur eine Klassenabhängigkeit, die Sie selbst hätten schreiben können, oder Sie hätten `Form`ular-Parameter direkt deklarieren können.
+
+Da es sich jedoch um einen häufigen Anwendungsfall handelt, wird er zur Vereinfachung direkt von **FastAPI** bereitgestellt.
+
+///
+
+### Die Formulardaten verwenden { #use-the-form-data }
+
+/// tip | Tipp
+
+Die Instanz der Klassenabhängigkeit `OAuth2PasswordRequestForm` verfügt, statt eines Attributs `scope` mit dem durch Leerzeichen getrennten langen String, über das Attribut `scopes` mit einer tatsächlichen Liste von Strings, einem für jeden gesendeten Scope.
+
+In diesem Beispiel verwenden wir keine `scopes`, aber die Funktionalität ist vorhanden, wenn Sie sie benötigen.
+
+///
+
+Rufen Sie nun die Benutzerdaten aus der (gefakten) Datenbank ab, für diesen `username` aus dem Formularfeld.
+
+Wenn es keinen solchen Benutzer gibt, geben wir die Fehlermeldung „Incorrect username or password“ zurück.
+
+Für den Fehler verwenden wir die Exception `HTTPException`:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}
+
+### Das Passwort überprüfen { #check-the-password }
+
+Zu diesem Zeitpunkt liegen uns die Benutzerdaten aus unserer Datenbank vor, das Passwort haben wir jedoch noch nicht überprüft.
+
+Lassen Sie uns diese Daten zunächst in das Pydantic-Modell `UserInDB` einfügen.
+
+Sie sollten niemals Klartext-Passwörter speichern, daher verwenden wir ein (gefaktes) Passwort-Hashing-System.
+
+Wenn die Passwörter nicht übereinstimmen, geben wir denselben Fehler zurück.
+
+#### Passwort-Hashing { #password-hashing }
+
+„Hashing“ bedeutet: Konvertieren eines Inhalts (in diesem Fall eines Passworts) in eine Folge von Bytes (ein schlichter String), die wie Kauderwelsch aussieht.
+
+Immer wenn Sie genau den gleichen Inhalt (genau das gleiche Passwort) übergeben, erhalten Sie genau den gleichen Kauderwelsch.
+
+Sie können jedoch nicht vom Kauderwelsch zurück zum Passwort konvertieren.
+
+##### Warum Passwort-Hashing verwenden? { #why-use-password-hashing }
+
+Wenn Ihre Datenbank gestohlen wird, hat der Dieb nicht die Klartext-Passwörter Ihrer Benutzer, sondern nur die Hashes.
+
+Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen System zu verwenden (da viele Benutzer überall das gleiche Passwort verwenden, wäre dies gefährlich).
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}
+
+#### Über `**user_dict` { #about-user-dict }
+
+`UserInDB(**user_dict)` bedeutet:
+
+*Übergib die Schlüssel und Werte des `user_dict` direkt als Schlüssel-Wert-Argumente, äquivalent zu:*
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ disabled = user_dict["disabled"],
+ hashed_password = user_dict["hashed_password"],
+)
+```
+
+/// info | Info
+
+Eine ausführlichere Erklärung von `**user_dict` finden Sie in [der Dokumentation für **Extra Modelle**](../extra-models.md#about-user-in-dict).
+
+///
+
+## Den Token zurückgeben { #return-the-token }
+
+Die Response des `token`-Endpunkts muss ein JSON-Objekt sein.
+
+Es sollte einen `token_type` haben. Da wir in unserem Fall „Bearer“-Token verwenden, sollte der Token-Typ „`bearer`“ sein.
+
+Und es sollte einen `access_token` haben, mit einem String, der unseren Zugriffstoken enthält.
+
+In diesem einfachen Beispiel gehen wir einfach völlig unsicher vor und geben denselben `username` wie der Token zurück.
+
+/// tip | Tipp
+
+Im nächsten Kapitel sehen Sie eine wirklich sichere Implementierung mit Passwort-Hashing und JWT-Tokens.
+
+Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benötigen.
+
+///
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}
+
+/// tip | Tipp
+
+Gemäß der Spezifikation sollten Sie ein JSON mit einem `access_token` und einem `token_type` zurückgeben, genau wie in diesem Beispiel.
+
+Das müssen Sie selbst in Ihrem Code tun und sicherstellen, dass Sie diese JSON-Schlüssel verwenden.
+
+Es ist fast das Einzige, woran Sie denken müssen, es selbst richtigzumachen und die Spezifikationen einzuhalten.
+
+Den Rest erledigt **FastAPI** für Sie.
+
+///
+
+## Die Abhängigkeiten aktualisieren { #update-the-dependencies }
+
+Jetzt werden wir unsere Abhängigkeiten aktualisieren.
+
+Wir möchten den `current_user` *nur* erhalten, wenn dieser Benutzer aktiv ist.
+
+Daher erstellen wir eine zusätzliche Abhängigkeit `get_current_active_user`, die wiederum `get_current_user` als Abhängigkeit verwendet.
+
+Beide Abhängigkeiten geben nur dann einen HTTP-Error zurück, wenn der Benutzer nicht existiert oder inaktiv ist.
+
+In unserem Endpunkt erhalten wir also nur dann einen Benutzer, wenn der Benutzer existiert, korrekt authentifiziert wurde und aktiv ist:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}
+
+/// info | Info
+
+Der zusätzliche Header `WWW-Authenticate` mit dem Wert `Bearer`, den wir hier zurückgeben, ist ebenfalls Teil der Spezifikation.
+
+Jeder HTTP-(Fehler-)Statuscode 401 „UNAUTHORIZED“ soll auch einen `WWW-Authenticate`-Header zurückgeben.
+
+Im Fall von Bearer-Tokens (in unserem Fall) sollte der Wert dieses Headers `Bearer` lauten.
+
+Sie können diesen zusätzlichen Header tatsächlich weglassen und es würde trotzdem funktionieren.
+
+Aber er wird hier bereitgestellt, um den Spezifikationen zu entsprechen.
+
+Außerdem gibt es möglicherweise Tools, die ihn erwarten und verwenden (jetzt oder in der Zukunft) und das könnte für Sie oder Ihre Benutzer jetzt oder in der Zukunft nützlich sein.
+
+Das ist der Vorteil von Standards ...
+
+///
+
+## Es in Aktion sehen { #see-it-in-action }
+
+Öffnen Sie die interaktive Dokumentation: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).
+
+### Authentifizieren { #authenticate }
+
+Klicken Sie auf den Button „Authorize“.
+
+Verwenden Sie die Anmeldedaten:
+
+Benutzer: `johndoe`
+
+Passwort: `secret`.
+
+
+
+Nach der Authentifizierung im System sehen Sie Folgendes:
+
+
+
+### Die eigenen Benutzerdaten ansehen { #get-your-own-user-data }
+
+Verwenden Sie nun die Operation `GET` mit dem Pfad `/users/me`.
+
+Sie erhalten Ihre Benutzerdaten:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false,
+ "hashed_password": "fakehashedsecret"
+}
+```
+
+
+
+Wenn Sie auf das Schlosssymbol klicken und sich abmelden und dann den gleichen Vorgang nochmal versuchen, erhalten Sie einen HTTP 401 Error:
+
+```JSON
+{
+ "detail": "Not authenticated"
+}
+```
+
+### Inaktiver Benutzer { #inactive-user }
+
+Versuchen Sie es nun mit einem inaktiven Benutzer und authentisieren Sie sich mit:
+
+Benutzer: `alice`.
+
+Passwort: `secret2`.
+
+Und versuchen Sie, die Operation `GET` mit dem Pfad `/users/me` zu verwenden.
+
+Sie erhalten die Fehlermeldung „Inactive user“:
+
+```JSON
+{
+ "detail": "Inactive user"
+}
+```
+
+## Zusammenfassung { #recap }
+
+Sie verfügen jetzt über die Tools, um ein vollständiges Sicherheitssystem basierend auf `username` und `password` für Ihre API zu implementieren.
+
+Mit diesen Tools können Sie das Sicherheitssystem mit jeder Datenbank und jedem Benutzer oder Datenmodell kompatibel machen.
+
+Das einzige fehlende Detail ist, dass es noch nicht wirklich „sicher“ ist.
+
+Im nächsten Kapitel erfahren Sie, wie Sie eine sichere Passwort-Hashing-Bibliothek und JWT-Token verwenden.
diff --git a/docs/de/docs/tutorial/server-sent-events.md b/docs/de/docs/tutorial/server-sent-events.md
new file mode 100644
index 0000000000000..f465c1131880b
--- /dev/null
+++ b/docs/de/docs/tutorial/server-sent-events.md
@@ -0,0 +1,120 @@
+# Server-Sent Events (SSE) { #server-sent-events-sse }
+
+Sie können Daten mithilfe von **Server-Sent Events** (SSE) an den Client streamen.
+
+Das ist ähnlich wie [JSON Lines streamen](stream-json-lines.md), verwendet aber das Format `text/event-stream`, das von Browsern nativ mit der [die `EventSource`-API](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) unterstützt wird.
+
+/// info | Info
+
+Hinzugefügt in FastAPI 0.135.0.
+
+///
+
+## Was sind Server-Sent Events? { #what-are-server-sent-events }
+
+SSE ist ein Standard zum Streamen von Daten vom Server zum Client über HTTP.
+
+Jedes Event ist ein kleiner Textblock mit „Feldern“ wie `data`, `event`, `id` und `retry`, getrennt durch Leerzeilen.
+
+Das sieht so aus:
+
+```
+data: {"name": "Portal Gun", "price": 999.99}
+
+data: {"name": "Plumbus", "price": 32.99}
+
+```
+
+SSE wird häufig für KI-Chat-Streaming, Live-Benachrichtigungen, Logs und Observability sowie andere Fälle verwendet, in denen der Server Updates an den Client pusht.
+
+/// tip | Tipp
+
+Wenn Sie Binärdaten streamen wollen, z. B. Video oder Audio, sehen Sie im fortgeschrittenen Handbuch nach: [Daten streamen](../advanced/stream-data.md).
+
+///
+
+## SSE mit FastAPI streamen { #stream-sse-with-fastapi }
+
+Um SSE mit FastAPI zu streamen, verwenden Sie `yield` in Ihrer *Pfadoperation-Funktion* und setzen Sie `response_class=EventSourceResponse`.
+
+Importieren Sie `EventSourceResponse` aus `fastapi.sse`:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[4,22] *}
+
+Jedes mit `yield` zurückgegebene Element wird als JSON kodiert und im Feld `data:` eines SSE-Events gesendet.
+
+Wenn Sie den Rückgabetyp als `AsyncIterable[Item]` deklarieren, verwendet FastAPI ihn, um die Daten mit Pydantic zu **validieren**, zu **dokumentieren** und zu **serialisieren**.
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[10:12,23] *}
+
+/// tip | Tipp
+
+Da Pydantic es auf der **Rust**-Seite serialisiert, erhalten Sie eine deutlich höhere **Leistung**, als wenn Sie keinen Rückgabetyp deklarieren.
+
+///
+
+### Nicht-async-*Pfadoperation-Funktionen* { #non-async-path-operation-functions }
+
+Sie können auch normale `def`-Funktionen (ohne `async`) verwenden und `yield` genauso einsetzen.
+
+FastAPI stellt sicher, dass sie korrekt ausgeführt wird, sodass sie die Event Loop nicht blockiert.
+
+Da die Funktion in diesem Fall nicht async ist, wäre der passende Rückgabetyp `Iterable[Item]`:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[28:31] hl[29] *}
+
+### Kein Rückgabetyp { #no-return-type }
+
+Sie können den Rückgabetyp auch weglassen. FastAPI verwendet dann den [`jsonable_encoder`](./encoder.md), um die Daten zu konvertieren und zu senden.
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[34:37] hl[35] *}
+
+## `ServerSentEvent` { #serversentevent }
+
+Wenn Sie SSE-Felder wie `event`, `id`, `retry` oder `comment` setzen müssen, können Sie statt reiner Daten `ServerSentEvent`-Objekte yielden.
+
+Importieren Sie `ServerSentEvent` aus `fastapi.sse`:
+
+{* ../../docs_src/server_sent_events/tutorial002_py310.py hl[4,26] *}
+
+Das Feld `data` wird immer als JSON kodiert. Sie können jeden Wert übergeben, der als JSON serialisierbar ist, einschließlich Pydantic-Modellen.
+
+## Rohdaten { #raw-data }
+
+Wenn Sie Daten **ohne** JSON-Kodierung senden müssen, verwenden Sie `raw_data` statt `data`.
+
+Das ist nützlich zum Senden vorformatierter Texte, Logzeilen oder spezieller „Sentinel“-Werte wie `[DONE]`.
+
+{* ../../docs_src/server_sent_events/tutorial003_py310.py hl[17] *}
+
+/// note | Hinweis
+
+`data` und `raw_data` schließen sich gegenseitig aus. Sie können pro `ServerSentEvent` nur eines von beiden setzen.
+
+///
+
+## Mit `Last-Event-ID` fortsetzen { #resuming-with-last-event-id }
+
+Wenn ein Browser nach einem Verbindungsabbruch erneut verbindet, sendet er die zuletzt empfangene `id` im Header `Last-Event-ID`.
+
+Sie können ihn als Header-Parameter einlesen und verwenden, um den Stream dort fortzusetzen, wo der Client aufgehört hat:
+
+{* ../../docs_src/server_sent_events/tutorial004_py310.py hl[25,27,31] *}
+
+## SSE mit POST { #sse-with-post }
+
+SSE funktioniert mit **jedem HTTP-Method**, nicht nur mit `GET`.
+
+Das ist nützlich für Protokolle wie [MCP](https://modelcontextprotocol.io), die SSE über `POST` streamen:
+
+{* ../../docs_src/server_sent_events/tutorial005_py310.py hl[14] *}
+
+## Technische Details { #technical-details }
+
+FastAPI implementiert einige bewährte SSE-Praktiken direkt out of the box.
+
+- Alle 15 Sekunden, wenn keine Nachricht gesendet wurde, einen **„keep alive“-`ping`-Kommentar** senden, um zu verhindern, dass einige Proxys die Verbindung schließen, wie in der [HTML-Spezifikation: Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes) vorgeschlagen.
+- Den Header `Cache-Control: no-cache` setzen, um **Caching** des Streams zu verhindern.
+- Einen speziellen Header `X-Accel-Buffering: no` setzen, um **Buffering** in einigen Proxys wie Nginx zu verhindern.
+
+Sie müssen dafür nichts tun, das funktioniert out of the box. 🤓
diff --git a/docs/de/docs/tutorial/sql-databases.md b/docs/de/docs/tutorial/sql-databases.md
new file mode 100644
index 0000000000000..d7988f9a2d38d
--- /dev/null
+++ b/docs/de/docs/tutorial/sql-databases.md
@@ -0,0 +1,357 @@
+# SQL (Relationale) Datenbanken { #sql-relational-databases }
+
+**FastAPI** erfordert nicht, dass Sie eine SQL (relationale) Datenbank verwenden. Sondern Sie können **jede beliebige Datenbank** verwenden, die Sie möchten.
+
+Hier werden wir ein Beispiel mit [SQLModel](https://sqlmodel.tiangolo.com/) sehen.
+
+**SQLModel** basiert auf [SQLAlchemy](https://www.sqlalchemy.org/) und Pydantic. Es wurde vom selben Autor wie **FastAPI** entwickelt, um die perfekte Ergänzung für FastAPI-Anwendungen zu sein, die **SQL-Datenbanken** verwenden müssen.
+
+/// tip | Tipp
+
+Sie könnten jede andere SQL- oder NoSQL-Datenbankbibliothek verwenden, die Sie möchten (in einigen Fällen als „ORMs“ bezeichnet), FastAPI zwingt Sie nicht, irgendetwas zu verwenden. 😎
+
+///
+
+Da SQLModel auf SQLAlchemy basiert, können Sie problemlos **jede von SQLAlchemy unterstützte Datenbank** verwenden (was auch bedeutet, dass sie von SQLModel unterstützt werden), wie:
+
+* PostgreSQL
+* MySQL
+* SQLite
+* Oracle
+* Microsoft SQL Server, usw.
+
+In diesem Beispiel verwenden wir **SQLite**, da es eine einzelne Datei verwendet und Python integrierte Unterstützung bietet. Sie können also dieses Beispiel kopieren und direkt ausführen.
+
+Später, für Ihre Produktionsanwendung, möchten Sie möglicherweise einen Datenbankserver wie **PostgreSQL** verwenden.
+
+/// tip | Tipp
+
+Es gibt einen offiziellen Projektgenerator mit **FastAPI** und **PostgreSQL**, einschließlich eines Frontends und weiterer Tools: [https://github.com/fastapi/full-stack-fastapi-template](https://github.com/fastapi/full-stack-fastapi-template)
+
+///
+
+Dies ist ein sehr einfaches und kurzes Tutorial. Wenn Sie mehr über Datenbanken im Allgemeinen, über SQL oder fortgeschrittenere Funktionen erfahren möchten, besuchen Sie die [SQLModel-Dokumentation](https://sqlmodel.tiangolo.com/).
+
+## `SQLModel` installieren { #install-sqlmodel }
+
+Stellen Sie zunächst sicher, dass Sie Ihre [virtuelle Umgebung](../virtual-environments.md) erstellen, sie aktivieren und dann `sqlmodel` installieren:
+
+
+
+
-
-## 🌀 🔢 📨 & 🛃 🕐
-
-👆 💪 💚 ✔️ 🔁 📨 👈 ✔ 📚 *➡ 🛠️*, ✋️ 👆 💚 🌀 👫 ⏮️ 🛃 📨 💚 🔠 *➡ 🛠️*.
-
-📚 💼, 👆 💪 ⚙️ 🐍 ⚒ "🏗" `dict` ⏮️ `**dict_to_unpack`:
-
-```Python
-old_dict = {
- "old key": "old value",
- "second old key": "second old value",
-}
-new_dict = {**old_dict, "new key": "new value"}
-```
-
-📥, `new_dict` 🔜 🔌 🌐 🔑-💲 👫 ⚪️➡️ `old_dict` ➕ 🆕 🔑-💲 👫:
-
-```Python
-{
- "old key": "old value",
- "second old key": "second old value",
- "new key": "new value",
-}
-```
-
-👆 💪 ⚙️ 👈 ⚒ 🏤-⚙️ 🔢 📨 👆 *➡ 🛠️* & 🌀 👫 ⏮️ 🌖 🛃 🕐.
-
-🖼:
-
-```Python hl_lines="13-17 26"
-{!../../../docs_src/additional_responses/tutorial004.py!}
-```
-
-## 🌖 ℹ 🔃 🗄 📨
-
-👀 ⚫️❔ ⚫️❔ 👆 💪 🔌 📨, 👆 💪 ✅ 👉 📄 🗄 🔧:
-
-* 🗄 📨 🎚, ⚫️ 🔌 `Response Object`.
-* 🗄 📨 🎚, 👆 💪 🔌 🕳 ⚪️➡️ 👉 🔗 🔠 📨 🔘 👆 `responses` 🔢. ✅ `description`, `headers`, `content` (🔘 👉 👈 👆 📣 🎏 🔉 🆎 & 🎻 🔗), & `links`.
diff --git a/docs/em/docs/advanced/additional-status-codes.md b/docs/em/docs/advanced/additional-status-codes.md
deleted file mode 100644
index 392579df6e120..0000000000000
--- a/docs/em/docs/advanced/additional-status-codes.md
+++ /dev/null
@@ -1,37 +0,0 @@
-# 🌖 👔 📟
-
-🔢, **FastAPI** 🔜 📨 📨 ⚙️ `JSONResponse`, 🚮 🎚 👆 📨 ⚪️➡️ 👆 *➡ 🛠️* 🔘 👈 `JSONResponse`.
-
-⚫️ 🔜 ⚙️ 🔢 👔 📟 ⚖️ 1️⃣ 👆 ⚒ 👆 *➡ 🛠️*.
-
-## 🌖 👔 📟
-
-🚥 👆 💚 📨 🌖 👔 📟 ↖️ ⚪️➡️ 👑 1️⃣, 👆 💪 👈 🛬 `Response` 🔗, 💖 `JSONResponse`, & ⚒ 🌖 👔 📟 🔗.
-
-🖼, ➡️ 💬 👈 👆 💚 ✔️ *➡ 🛠️* 👈 ✔ ℹ 🏬, & 📨 🇺🇸🔍 👔 📟 2️⃣0️⃣0️⃣ "👌" 🕐❔ 🏆.
-
-✋️ 👆 💚 ⚫️ 🚫 🆕 🏬. & 🕐❔ 🏬 🚫 🔀 ⏭, ⚫️ ✍ 👫, & 📨 🇺🇸🔍 👔 📟 2️⃣0️⃣1️⃣ "✍".
-
-🏆 👈, 🗄 `JSONResponse`, & 📨 👆 🎚 📤 🔗, ⚒ `status_code` 👈 👆 💚:
-
-```Python hl_lines="4 25"
-{!../../../docs_src/additional_status_codes/tutorial001.py!}
-```
-
-!!! warning
- 🕐❔ 👆 📨 `Response` 🔗, 💖 🖼 🔛, ⚫️ 🔜 📨 🔗.
-
- ⚫️ 🏆 🚫 🎻 ⏮️ 🏷, ♒️.
-
- ⚒ 💭 ⚫️ ✔️ 📊 👆 💚 ⚫️ ✔️, & 👈 💲 ☑ 🎻 (🚥 👆 ⚙️ `JSONResponse`).
-
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import JSONResponse`.
-
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `status`.
-
-## 🗄 & 🛠️ 🩺
-
-🚥 👆 📨 🌖 👔 📟 & 📨 🔗, 👫 🏆 🚫 🔌 🗄 🔗 (🛠️ 🩺), ↩️ FastAPI 🚫 ✔️ 🌌 💭 ⏪ ⚫️❔ 👆 🚶 📨.
-
-✋️ 👆 💪 📄 👈 👆 📟, ⚙️: [🌖 📨](additional-responses.md){.internal-link target=_blank}.
diff --git a/docs/em/docs/advanced/advanced-dependencies.md b/docs/em/docs/advanced/advanced-dependencies.md
deleted file mode 100644
index fa1554734cba6..0000000000000
--- a/docs/em/docs/advanced/advanced-dependencies.md
+++ /dev/null
@@ -1,70 +0,0 @@
-# 🏧 🔗
-
-## 🔗 🔗
-
-🌐 🔗 👥 ✔️ 👀 🔧 🔢 ⚖️ 🎓.
-
-✋️ 📤 💪 💼 🌐❔ 👆 💚 💪 ⚒ 🔢 🔛 🔗, 🍵 ✔️ 📣 📚 🎏 🔢 ⚖️ 🎓.
-
-➡️ 🌈 👈 👥 💚 ✔️ 🔗 👈 ✅ 🚥 🔢 🔢 `q` 🔌 🔧 🎚.
-
-✋️ 👥 💚 💪 🔗 👈 🔧 🎚.
-
-## "🇧🇲" 👐
-
-🐍 📤 🌌 ⚒ 👐 🎓 "🇧🇲".
-
-🚫 🎓 ⚫️ (❔ ⏪ 🇧🇲), ✋️ 👐 👈 🎓.
-
-👈, 👥 📣 👩🔬 `__call__`:
-
-```Python hl_lines="10"
-{!../../../docs_src/dependencies/tutorial011.py!}
-```
-
-👉 💼, 👉 `__call__` ⚫️❔ **FastAPI** 🔜 ⚙️ ✅ 🌖 🔢 & 🎧-🔗, & 👉 ⚫️❔ 🔜 🤙 🚶♀️ 💲 🔢 👆 *➡ 🛠️ 🔢* ⏪.
-
-## 🔗 👐
-
-& 🔜, 👥 💪 ⚙️ `__init__` 📣 🔢 👐 👈 👥 💪 ⚙️ "🔗" 🔗:
-
-```Python hl_lines="7"
-{!../../../docs_src/dependencies/tutorial011.py!}
-```
-
-👉 💼, **FastAPI** 🏆 🚫 ⏱ 👆 ⚖️ 💅 🔃 `__init__`, 👥 🔜 ⚙️ ⚫️ 🔗 👆 📟.
-
-## ✍ 👐
-
-👥 💪 ✍ 👐 👉 🎓 ⏮️:
-
-```Python hl_lines="16"
-{!../../../docs_src/dependencies/tutorial011.py!}
-```
-
-& 👈 🌌 👥 💪 "🔗" 👆 🔗, 👈 🔜 ✔️ `"bar"` 🔘 ⚫️, 🔢 `checker.fixed_content`.
-
-## ⚙️ 👐 🔗
-
-⤴️, 👥 💪 ⚙️ 👉 `checker` `Depends(checker)`, ↩️ `Depends(FixedContentQueryChecker)`, ↩️ 🔗 👐, `checker`, 🚫 🎓 ⚫️.
-
-& 🕐❔ ❎ 🔗, **FastAPI** 🔜 🤙 👉 `checker` 💖:
-
-```Python
-checker(q="somequery")
-```
-
-...& 🚶♀️ ⚫️❔ 👈 📨 💲 🔗 👆 *➡ 🛠️ 🔢* 🔢 `fixed_content_included`:
-
-```Python hl_lines="20"
-{!../../../docs_src/dependencies/tutorial011.py!}
-```
-
-!!! tip
- 🌐 👉 💪 😑 🎭. & ⚫️ 💪 🚫 📶 🆑 ❔ ⚫️ ⚠.
-
- 👫 🖼 😫 🙅, ✋️ 🎦 ❔ ⚫️ 🌐 👷.
-
- 📃 🔃 💂♂, 📤 🚙 🔢 👈 🛠️ 👉 🎏 🌌.
-
- 🚥 👆 🤔 🌐 👉, 👆 ⏪ 💭 ❔ 👈 🚙 🧰 💂♂ 👷 🔘.
diff --git a/docs/em/docs/advanced/async-sql-databases.md b/docs/em/docs/advanced/async-sql-databases.md
deleted file mode 100644
index 848936de16b8a..0000000000000
--- a/docs/em/docs/advanced/async-sql-databases.md
+++ /dev/null
@@ -1,162 +0,0 @@
-# 🔁 🗄 (🔗) 💽
-
-👆 💪 ⚙️ `encode/databases` ⏮️ **FastAPI** 🔗 💽 ⚙️ `async` & `await`.
-
-⚫️ 🔗 ⏮️:
-
-* ✳
-* ✳
-* 🗄
-
-👉 🖼, 👥 🔜 ⚙️ **🗄**, ↩️ ⚫️ ⚙️ 👁 📁 & 🐍 ✔️ 🛠️ 🐕🦺. , 👆 💪 📁 👉 🖼 & 🏃 ⚫️.
-
-⏪, 👆 🏭 🈸, 👆 💪 💚 ⚙️ 💽 💽 💖 **✳**.
-
-!!! tip
- 👆 💪 🛠️ 💭 ⚪️➡️ 📄 🔃 🇸🇲 🐜 ([🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank}), 💖 ⚙️ 🚙 🔢 🎭 🛠️ 💽, 🔬 👆 **FastAPI** 📟.
-
- 👉 📄 🚫 ✔ 📚 💭, 🌓 😑 💃.
-
-## 🗄 & ⚒ 🆙 `SQLAlchemy`
-
-* 🗄 `SQLAlchemy`.
-* ✍ `metadata` 🎚.
-* ✍ 🏓 `notes` ⚙️ `metadata` 🎚.
-
-```Python hl_lines="4 14 16-22"
-{!../../../docs_src/async_sql_databases/tutorial001.py!}
-```
-
-!!! tip
- 👀 👈 🌐 👉 📟 😁 🇸🇲 🐚.
-
- `databases` 🚫 🔨 🕳 📥.
-
-## 🗄 & ⚒ 🆙 `databases`
-
-* 🗄 `databases`.
-* ✍ `DATABASE_URL`.
-* ✍ `database` 🎚.
-
-```Python hl_lines="3 9 12"
-{!../../../docs_src/async_sql_databases/tutorial001.py!}
-```
-
-!!! tip
- 🚥 👆 🔗 🎏 💽 (✅ ✳), 👆 🔜 💪 🔀 `DATABASE_URL`.
-
-## ✍ 🏓
-
-👉 💼, 👥 🏗 🏓 🎏 🐍 📁, ✋️ 🏭, 👆 🔜 🎲 💚 ✍ 👫 ⏮️ ⚗, 🛠️ ⏮️ 🛠️, ♒️.
-
-📥, 👉 📄 🔜 🏃 🔗, ▶️️ ⏭ ▶️ 👆 **FastAPI** 🈸.
-
-* ✍ `engine`.
-* ✍ 🌐 🏓 ⚪️➡️ `metadata` 🎚.
-
-```Python hl_lines="25-28"
-{!../../../docs_src/async_sql_databases/tutorial001.py!}
-```
-
-## ✍ 🏷
-
-✍ Pydantic 🏷:
-
-* 🗒 ✍ (`NoteIn`).
-* 🗒 📨 (`Note`).
-
-```Python hl_lines="31-33 36-39"
-{!../../../docs_src/async_sql_databases/tutorial001.py!}
-```
-
-🏗 👫 Pydantic 🏷, 🔢 💽 🔜 ✔, 🎻 (🗜), & ✍ (📄).
-
-, 👆 🔜 💪 👀 ⚫️ 🌐 🎓 🛠️ 🩺.
-
-## 🔗 & 🔌
-
-* ✍ 👆 `FastAPI` 🈸.
-* ✍ 🎉 🐕🦺 🔗 & 🔌 ⚪️➡️ 💽.
-
-```Python hl_lines="42 45-47 50-52"
-{!../../../docs_src/async_sql_databases/tutorial001.py!}
-```
-
-## ✍ 🗒
-
-✍ *➡ 🛠️ 🔢* ✍ 🗒:
-
-```Python hl_lines="55-58"
-{!../../../docs_src/async_sql_databases/tutorial001.py!}
-```
-
-!!! Note
- 👀 👈 👥 🔗 ⏮️ 💽 ⚙️ `await`, *➡ 🛠️ 🔢* 📣 ⏮️ `async`.
-
-### 👀 `response_model=List[Note]`
-
-⚫️ ⚙️ `typing.List`.
-
-👈 📄 (& ✔, 🎻, ⛽) 🔢 💽, `list` `Note`Ⓜ.
-
-## ✍ 🗒
-
-✍ *➡ 🛠️ 🔢* ✍ 🗒:
-
-```Python hl_lines="61-65"
-{!../../../docs_src/async_sql_databases/tutorial001.py!}
-```
-
-!!! Note
- 👀 👈 👥 🔗 ⏮️ 💽 ⚙️ `await`, *➡ 🛠️ 🔢* 📣 ⏮️ `async`.
-
-### 🔃 `{**note.dict(), "id": last_record_id}`
-
-`note` Pydantic `Note` 🎚.
-
-`note.dict()` 📨 `dict` ⏮️ 🚮 💽, 🕳 💖:
-
-```Python
-{
- "text": "Some note",
- "completed": False,
-}
-```
-
-✋️ ⚫️ 🚫 ✔️ `id` 🏑.
-
-👥 ✍ 🆕 `dict`, 👈 🔌 🔑-💲 👫 ⚪️➡️ `note.dict()` ⏮️:
-
-```Python
-{**note.dict()}
-```
-
-`**note.dict()` "unpacks" the key value pairs directly, so, `{**note.dict()}` would be, more or less, a copy of `note.dict()`.
-
-& ⤴️, 👥 ↔ 👈 📁 `dict`, ❎ ➕1️⃣ 🔑-💲 👫: `"id": last_record_id`:
-
-```Python
-{**note.dict(), "id": last_record_id}
-```
-
-, 🏁 🏁 📨 🔜 🕳 💖:
-
-```Python
-{
- "id": 1,
- "text": "Some note",
- "completed": False,
-}
-```
-
-## ✅ ⚫️
-
-👆 💪 📁 👉 📟, & 👀 🩺 http://127.0.0.1:8000/docs.
-
-📤 👆 💪 👀 🌐 👆 🛠️ 📄 & 🔗 ⏮️ ⚫️:
-
-
-
-## 🌅 ℹ
-
-👆 💪 ✍ 🌅 🔃 `encode/databases` 🚮 📂 📃.
diff --git a/docs/em/docs/advanced/async-tests.md b/docs/em/docs/advanced/async-tests.md
deleted file mode 100644
index df94c6ce7cbbe..0000000000000
--- a/docs/em/docs/advanced/async-tests.md
+++ /dev/null
@@ -1,92 +0,0 @@
-# 🔁 💯
-
-👆 ✔️ ⏪ 👀 ❔ 💯 👆 **FastAPI** 🈸 ⚙️ 🚚 `TestClient`. 🆙 🔜, 👆 ✔️ 🕴 👀 ❔ ✍ 🔁 💯, 🍵 ⚙️ `async` 🔢.
-
-➖ 💪 ⚙️ 🔁 🔢 👆 💯 💪 ⚠, 🖼, 🕐❔ 👆 🔬 👆 💽 🔁. 🌈 👆 💚 💯 📨 📨 👆 FastAPI 🈸 & ⤴️ ✔ 👈 👆 👩💻 ⏪ ✍ ☑ 💽 💽, ⏪ ⚙️ 🔁 💽 🗃.
-
-➡️ 👀 ❔ 👥 💪 ⚒ 👈 👷.
-
-## pytest.mark.anyio
-
-🚥 👥 💚 🤙 🔁 🔢 👆 💯, 👆 💯 🔢 ✔️ 🔁. AnyIO 🚚 👌 📁 👉, 👈 ✔ 👥 ✔ 👈 💯 🔢 🤙 🔁.
-
-## 🇸🇲
-
-🚥 👆 **FastAPI** 🈸 ⚙️ 😐 `def` 🔢 ↩️ `async def`, ⚫️ `async` 🈸 🔘.
-
-`TestClient` 🔨 🎱 🔘 🤙 🔁 FastAPI 🈸 👆 😐 `def` 💯 🔢, ⚙️ 🐩 ✳. ✋️ 👈 🎱 🚫 👷 🚫🔜 🕐❔ 👥 ⚙️ ⚫️ 🔘 🔁 🔢. 🏃 👆 💯 🔁, 👥 💪 🙅♂ 📏 ⚙️ `TestClient` 🔘 👆 💯 🔢.
-
-`TestClient` ⚓️ 🔛 🇸🇲, & ↩️, 👥 💪 ⚙️ ⚫️ 🔗 💯 🛠️.
-
-## 🖼
-
-🙅 🖼, ➡️ 🤔 📁 📊 🎏 1️⃣ 🔬 [🦏 🈸](../tutorial/bigger-applications.md){.internal-link target=_blank} & [🔬](../tutorial/testing.md){.internal-link target=_blank}:
-
-```
-.
-├── app
-│ ├── __init__.py
-│ ├── main.py
-│ └── test_main.py
-```
-
-📁 `main.py` 🔜 ✔️:
-
-```Python
-{!../../../docs_src/async_tests/main.py!}
-```
-
-📁 `test_main.py` 🔜 ✔️ 💯 `main.py`, ⚫️ 💪 👀 💖 👉 🔜:
-
-```Python
-{!../../../docs_src/async_tests/test_main.py!}
-```
-
-## 🏃 ⚫️
-
-👆 💪 🏃 👆 💯 🐌 📨:
-
-
-
-✋️ 🚥 👥 🔐 🩺 🎚 "🛂" 📛 ⚙️ 🗳 ⏮️ ⛴ `9999`, `/api/v1/docs`, ⚫️ 👷 ☑ ❗ 👶
-
-👆 💪 ✅ ⚫️ http://127.0.0.1:9999/api/v1/docs:
-
-
-
-▶️️ 👥 💚 ⚫️. 👶 👶
-
-👉 ↩️ FastAPI ⚙️ 👉 `root_path` ✍ 🔢 `server` 🗄 ⏮️ 📛 🚚 `root_path`.
-
-## 🌖 💽
-
-!!! warning
- 👉 🌅 🏧 ⚙️ 💼. 💭 🆓 🚶 ⚫️.
-
-🔢, **FastAPI** 🔜 ✍ `server` 🗄 🔗 ⏮️ 📛 `root_path`.
-
-✋️ 👆 💪 🚚 🎏 🎛 `servers`, 🖼 🚥 👆 💚 *🎏* 🩺 🎚 🔗 ⏮️ 🏗 & 🏭 🌐.
-
-🚥 👆 🚶♀️ 🛃 📇 `servers` & 📤 `root_path` (↩️ 👆 🛠️ 👨❤👨 ⛅ 🗳), **FastAPI** 🔜 📩 "💽" ⏮️ 👉 `root_path` ▶️ 📇.
-
-🖼:
-
-```Python hl_lines="4-7"
-{!../../../docs_src/behind_a_proxy/tutorial003.py!}
-```
-
-🔜 🏗 🗄 🔗 💖:
-
-```JSON hl_lines="5-7"
-{
- "openapi": "3.0.2",
- // More stuff here
- "servers": [
- {
- "url": "/api/v1"
- },
- {
- "url": "https://stag.example.com",
- "description": "Staging environment"
- },
- {
- "url": "https://prod.example.com",
- "description": "Production environment"
- }
- ],
- "paths": {
- // More stuff here
- }
-}
-```
-
-!!! tip
- 👀 🚘-🏗 💽 ⏮️ `url` 💲 `/api/v1`, ✊ ⚪️➡️ `root_path`.
-
-🩺 🎚 http://127.0.0.1:9999/api/v1/docs ⚫️ 🔜 👀 💖:
-
-
-
-!!! tip
- 🩺 🎚 🔜 🔗 ⏮️ 💽 👈 👆 🖊.
-
-### ❎ 🏧 💽 ⚪️➡️ `root_path`
-
-🚥 👆 🚫 💚 **FastAPI** 🔌 🏧 💽 ⚙️ `root_path`, 👆 💪 ⚙️ 🔢 `root_path_in_servers=False`:
-
-```Python hl_lines="9"
-{!../../../docs_src/behind_a_proxy/tutorial004.py!}
-```
-
-& ⤴️ ⚫️ 🏆 🚫 🔌 ⚫️ 🗄 🔗.
-
-## 🗜 🎧-🈸
-
-🚥 👆 💪 🗻 🎧-🈸 (🔬 [🎧 🈸 - 🗻](./sub-applications.md){.internal-link target=_blank}) ⏪ ⚙️ 🗳 ⏮️ `root_path`, 👆 💪 ⚫️ 🛎, 👆 🔜 ⌛.
-
-FastAPI 🔜 🔘 ⚙️ `root_path` 🎆, ⚫️ 🔜 👷. 👶
diff --git a/docs/em/docs/advanced/custom-response.md b/docs/em/docs/advanced/custom-response.md
deleted file mode 100644
index cf76c01d068f9..0000000000000
--- a/docs/em/docs/advanced/custom-response.md
+++ /dev/null
@@ -1,300 +0,0 @@
-# 🛃 📨 - 🕸, 🎏, 📁, 🎏
-
-🔢, **FastAPI** 🔜 📨 📨 ⚙️ `JSONResponse`.
-
-👆 💪 🔐 ⚫️ 🛬 `Response` 🔗 👀 [📨 📨 🔗](response-directly.md){.internal-link target=_blank}.
-
-✋️ 🚥 👆 📨 `Response` 🔗, 📊 🏆 🚫 🔁 🗜, & 🧾 🏆 🚫 🔁 🏗 (🖼, 🔌 🎯 "📻 🆎", 🇺🇸🔍 🎚 `Content-Type` 🍕 🏗 🗄).
-
-✋️ 👆 💪 📣 `Response` 👈 👆 💚 ⚙️, *➡ 🛠️ 👨🎨*.
-
-🎚 👈 👆 📨 ⚪️➡️ 👆 *➡ 🛠️ 🔢* 🔜 🚮 🔘 👈 `Response`.
-
-& 🚥 👈 `Response` ✔️ 🎻 📻 🆎 (`application/json`), 💖 💼 ⏮️ `JSONResponse` & `UJSONResponse`, 💽 👆 📨 🔜 🔁 🗜 (& ⛽) ⏮️ 🙆 Pydantic `response_model` 👈 👆 📣 *➡ 🛠️ 👨🎨*.
-
-!!! note
- 🚥 👆 ⚙️ 📨 🎓 ⏮️ 🙅♂ 📻 🆎, FastAPI 🔜 ⌛ 👆 📨 ✔️ 🙅♂ 🎚, ⚫️ 🔜 🚫 📄 📨 📁 🚮 🏗 🗄 🩺.
-
-## ⚙️ `ORJSONResponse`
-
-🖼, 🚥 👆 ✊ 🎭, 👆 💪 ❎ & ⚙️ `orjson` & ⚒ 📨 `ORJSONResponse`.
-
-🗄 `Response` 🎓 (🎧-🎓) 👆 💚 ⚙️ & 📣 ⚫️ *➡ 🛠️ 👨🎨*.
-
-⭕ 📨, 📨 `Response` 🔗 🌅 ⏩ 🌘 🛬 📖.
-
-👉 ↩️ 🔢, FastAPI 🔜 ✔ 🔠 🏬 🔘 & ⚒ 💭 ⚫️ 🎻 ⏮️ 🎻, ⚙️ 🎏 [🎻 🔗 🔢](../tutorial/encoder.md){.internal-link target=_blank} 🔬 🔰. 👉 ⚫️❔ ✔ 👆 📨 **❌ 🎚**, 🖼 💽 🏷.
-
-✋️ 🚥 👆 🎯 👈 🎚 👈 👆 🛬 **🎻 ⏮️ 🎻**, 👆 💪 🚶♀️ ⚫️ 🔗 📨 🎓 & ❎ ➕ 🌥 👈 FastAPI 🔜 ✔️ 🚶♀️ 👆 📨 🎚 🔘 `jsonable_encoder` ⏭ 🚶♀️ ⚫️ 📨 🎓.
-
-```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001b.py!}
-```
-
-!!! info
- 🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨.
-
- 👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `application/json`.
-
- & ⚫️ 🔜 📄 ✅ 🗄.
-
-!!! tip
- `ORJSONResponse` ⏳ 🕴 💪 FastAPI, 🚫 💃.
-
-## 🕸 📨
-
-📨 📨 ⏮️ 🕸 🔗 ⚪️➡️ **FastAPI**, ⚙️ `HTMLResponse`.
-
-* 🗄 `HTMLResponse`.
-* 🚶♀️ `HTMLResponse` 🔢 `response_class` 👆 *➡ 🛠️ 👨🎨*.
-
-```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial002.py!}
-```
-
-!!! info
- 🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨.
-
- 👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `text/html`.
-
- & ⚫️ 🔜 📄 ✅ 🗄.
-
-### 📨 `Response`
-
-👀 [📨 📨 🔗](response-directly.md){.internal-link target=_blank}, 👆 💪 🔐 📨 🔗 👆 *➡ 🛠️*, 🛬 ⚫️.
-
-🎏 🖼 ⚪️➡️ 🔛, 🛬 `HTMLResponse`, 💪 👀 💖:
-
-```Python hl_lines="2 7 19"
-{!../../../docs_src/custom_response/tutorial003.py!}
-```
-
-!!! warning
- `Response` 📨 🔗 👆 *➡ 🛠️ 🔢* 🏆 🚫 📄 🗄 (🖼, `Content-Type` 🏆 🚫 📄) & 🏆 🚫 ⭐ 🏧 🎓 🩺.
-
-!!! info
- ↗️, ☑ `Content-Type` 🎚, 👔 📟, ♒️, 🔜 👟 ⚪️➡️ `Response` 🎚 👆 📨.
-
-### 📄 🗄 & 🔐 `Response`
-
-🚥 👆 💚 🔐 📨 ⚪️➡️ 🔘 🔢 ✋️ 🎏 🕰 📄 "📻 🆎" 🗄, 👆 💪 ⚙️ `response_class` 🔢 & 📨 `Response` 🎚.
-
-`response_class` 🔜 ⤴️ ⚙️ 🕴 📄 🗄 *➡ 🛠️*, ✋️ 👆 `Response` 🔜 ⚙️.
-
-#### 📨 `HTMLResponse` 🔗
-
-🖼, ⚫️ 💪 🕳 💖:
-
-```Python hl_lines="7 21 23"
-{!../../../docs_src/custom_response/tutorial004.py!}
-```
-
-👉 🖼, 🔢 `generate_html_response()` ⏪ 🏗 & 📨 `Response` ↩️ 🛬 🕸 `str`.
-
-🛬 🏁 🤙 `generate_html_response()`, 👆 ⏪ 🛬 `Response` 👈 🔜 🔐 🔢 **FastAPI** 🎭.
-
-✋️ 👆 🚶♀️ `HTMLResponse` `response_class` 💁♂️, **FastAPI** 🔜 💭 ❔ 📄 ⚫️ 🗄 & 🎓 🩺 🕸 ⏮️ `text/html`:
-
-
-
-## 💪 📨
-
-📥 💪 📨.
-
-✔️ 🤯 👈 👆 💪 ⚙️ `Response` 📨 🕳 🙆, ⚖️ ✍ 🛃 🎧-🎓.
-
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`.
-
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
-
-### `Response`
-
-👑 `Response` 🎓, 🌐 🎏 📨 😖 ⚪️➡️ ⚫️.
-
-👆 💪 📨 ⚫️ 🔗.
-
-⚫️ 🚫 📄 🔢:
-
-* `content` - `str` ⚖️ `bytes`.
-* `status_code` - `int` 🇺🇸🔍 👔 📟.
-* `headers` - `dict` 🎻.
-* `media_type` - `str` 🤝 📻 🆎. 🤶 Ⓜ. `"text/html"`.
-
-FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🎚, ⚓️ 🔛 = & 🔁 = ✍ 🆎.
-
-```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
-```
-
-### `HTMLResponse`
-
-✊ ✍ ⚖️ 🔢 & 📨 🕸 📨, 👆 ✍ 🔛.
-
-### `PlainTextResponse`
-
-✊ ✍ ⚖️ 🔢 & 📨 ✅ ✍ 📨.
-
-```Python hl_lines="2 7 9"
-{!../../../docs_src/custom_response/tutorial005.py!}
-```
-
-### `JSONResponse`
-
-✊ 💽 & 📨 `application/json` 🗜 📨.
-
-👉 🔢 📨 ⚙️ **FastAPI**, 👆 ✍ 🔛.
-
-### `ORJSONResponse`
-
-⏩ 🎛 🎻 📨 ⚙️ `orjson`, 👆 ✍ 🔛.
-
-### `UJSONResponse`
-
-🎛 🎻 📨 ⚙️ `ujson`.
-
-!!! warning
- `ujson` 🌘 💛 🌘 🐍 🏗-🛠️ ❔ ⚫️ 🍵 📐-💼.
-
-```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001.py!}
-```
-
-!!! tip
- ⚫️ 💪 👈 `ORJSONResponse` 💪 ⏩ 🎛.
-
-### `RedirectResponse`
-
-📨 🇺🇸🔍 ❎. ⚙️ 3️⃣0️⃣7️⃣ 👔 📟 (🍕 ❎) 🔢.
-
-👆 💪 📨 `RedirectResponse` 🔗:
-
-```Python hl_lines="2 9"
-{!../../../docs_src/custom_response/tutorial006.py!}
-```
-
----
-
-⚖️ 👆 💪 ⚙️ ⚫️ `response_class` 🔢:
-
-
-```Python hl_lines="2 7 9"
-{!../../../docs_src/custom_response/tutorial006b.py!}
-```
-
-🚥 👆 👈, ⤴️ 👆 💪 📨 📛 🔗 ⚪️➡️ 👆 *➡ 🛠️* 🔢.
-
-👉 💼, `status_code` ⚙️ 🔜 🔢 1️⃣ `RedirectResponse`, ❔ `307`.
-
----
-
-👆 💪 ⚙️ `status_code` 🔢 🌀 ⏮️ `response_class` 🔢:
-
-```Python hl_lines="2 7 9"
-{!../../../docs_src/custom_response/tutorial006c.py!}
-```
-
-### `StreamingResponse`
-
-✊ 🔁 🚂 ⚖️ 😐 🚂/🎻 & 🎏 📨 💪.
-
-```Python hl_lines="2 14"
-{!../../../docs_src/custom_response/tutorial007.py!}
-```
-
-#### ⚙️ `StreamingResponse` ⏮️ 📁-💖 🎚
-
-🚥 👆 ✔️ 📁-💖 🎚 (✅ 🎚 📨 `open()`), 👆 💪 ✍ 🚂 🔢 🔁 🤭 👈 📁-💖 🎚.
-
-👈 🌌, 👆 🚫 ✔️ ✍ ⚫️ 🌐 🥇 💾, & 👆 💪 🚶♀️ 👈 🚂 🔢 `StreamingResponse`, & 📨 ⚫️.
-
-👉 🔌 📚 🗃 🔗 ⏮️ ☁ 💾, 📹 🏭, & 🎏.
-
-```{ .python .annotate hl_lines="2 10-12 14" }
-{!../../../docs_src/custom_response/tutorial008.py!}
-```
-
-1️⃣. 👉 🚂 🔢. ⚫️ "🚂 🔢" ↩️ ⚫️ 🔌 `yield` 📄 🔘.
-2️⃣. ⚙️ `with` 🍫, 👥 ⚒ 💭 👈 📁-💖 🎚 📪 ⏮️ 🚂 🔢 🔨. , ⏮️ ⚫️ 🏁 📨 📨.
-3️⃣. 👉 `yield from` 💬 🔢 🔁 🤭 👈 👜 🌟 `file_like`. & ⤴️, 🔠 🍕 🔁, 🌾 👈 🍕 👟 ⚪️➡️ 👉 🚂 🔢.
-
- , ⚫️ 🚂 🔢 👈 📨 "🏭" 👷 🕳 🙆 🔘.
-
- 🔨 ⚫️ 👉 🌌, 👥 💪 🚮 ⚫️ `with` 🍫, & 👈 🌌, 🚚 👈 ⚫️ 📪 ⏮️ 🏁.
-
-!!! tip
- 👀 👈 📥 👥 ⚙️ 🐩 `open()` 👈 🚫 🐕🦺 `async` & `await`, 👥 📣 ➡ 🛠️ ⏮️ 😐 `def`.
-
-### `FileResponse`
-
-🔁 🎏 📁 📨.
-
-✊ 🎏 ⚒ ❌ 🔗 🌘 🎏 📨 🆎:
-
-* `path` - 📁 📁 🎏.
-* `headers` - 🙆 🛃 🎚 🔌, 📖.
-* `media_type` - 🎻 🤝 📻 🆎. 🚥 🔢, 📁 ⚖️ ➡ 🔜 ⚙️ 🔑 📻 🆎.
-* `filename` - 🚥 ⚒, 👉 🔜 🔌 📨 `Content-Disposition`.
-
-📁 📨 🔜 🔌 ☑ `Content-Length`, `Last-Modified` & `ETag` 🎚.
-
-```Python hl_lines="2 10"
-{!../../../docs_src/custom_response/tutorial009.py!}
-```
-
-👆 💪 ⚙️ `response_class` 🔢:
-
-```Python hl_lines="2 8 10"
-{!../../../docs_src/custom_response/tutorial009b.py!}
-```
-
-👉 💼, 👆 💪 📨 📁 ➡ 🔗 ⚪️➡️ 👆 *➡ 🛠️* 🔢.
-
-## 🛃 📨 🎓
-
-👆 💪 ✍ 👆 👍 🛃 📨 🎓, 😖 ⚪️➡️ `Response` & ⚙️ ⚫️.
-
-🖼, ➡️ 💬 👈 👆 💚 ⚙️ `orjson`, ✋️ ⏮️ 🛃 ⚒ 🚫 ⚙️ 🔌 `ORJSONResponse` 🎓.
-
-➡️ 💬 👆 💚 ⚫️ 📨 🔂 & 📁 🎻, 👆 💚 ⚙️ Orjson 🎛 `orjson.OPT_INDENT_2`.
-
-👆 💪 ✍ `CustomORJSONResponse`. 👑 👜 👆 ✔️ ✍ `Response.render(content)` 👩🔬 👈 📨 🎚 `bytes`:
-
-```Python hl_lines="9-14 17"
-{!../../../docs_src/custom_response/tutorial009c.py!}
-```
-
-🔜 ↩️ 🛬:
-
-```json
-{"message": "Hello World"}
-```
-
-...👉 📨 🔜 📨:
-
-```json
-{
- "message": "Hello World"
-}
-```
-
-↗️, 👆 🔜 🎲 🔎 🌅 👍 🌌 ✊ 📈 👉 🌘 ❕ 🎻. 👶
-
-## 🔢 📨 🎓
-
-🕐❔ 🏗 **FastAPI** 🎓 👐 ⚖️ `APIRouter` 👆 💪 ✔ ❔ 📨 🎓 ⚙️ 🔢.
-
-🔢 👈 🔬 👉 `default_response_class`.
-
-🖼 🔛, **FastAPI** 🔜 ⚙️ `ORJSONResponse` 🔢, 🌐 *➡ 🛠️*, ↩️ `JSONResponse`.
-
-```Python hl_lines="2 4"
-{!../../../docs_src/custom_response/tutorial010.py!}
-```
-
-!!! tip
- 👆 💪 🔐 `response_class` *➡ 🛠️* ⏭.
-
-## 🌖 🧾
-
-👆 💪 📣 📻 🆎 & 📚 🎏 ℹ 🗄 ⚙️ `responses`: [🌖 📨 🗄](additional-responses.md){.internal-link target=_blank}.
diff --git a/docs/em/docs/advanced/dataclasses.md b/docs/em/docs/advanced/dataclasses.md
deleted file mode 100644
index a4c2871062ccb..0000000000000
--- a/docs/em/docs/advanced/dataclasses.md
+++ /dev/null
@@ -1,98 +0,0 @@
-# ⚙️ 🎻
-
-FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pydantic 🏷 📣 📨 & 📨.
-
-✋️ FastAPI 🐕🦺 ⚙️ `dataclasses` 🎏 🌌:
-
-```Python hl_lines="1 7-12 19-20"
-{!../../../docs_src/dataclasses/tutorial001.py!}
-```
-
-👉 🐕🦺 👏 **Pydantic**, ⚫️ ✔️ 🔗 🐕🦺 `dataclasses`.
-
-, ⏮️ 📟 🔛 👈 🚫 ⚙️ Pydantic 🎯, FastAPI ⚙️ Pydantic 🗜 📚 🐩 🎻 Pydantic 👍 🍛 🎻.
-
-& ↗️, ⚫️ 🐕🦺 🎏:
-
-* 💽 🔬
-* 💽 🛠️
-* 💽 🧾, ♒️.
-
-👉 👷 🎏 🌌 ⏮️ Pydantic 🏷. & ⚫️ 🤙 🏆 🎏 🌌 🔘, ⚙️ Pydantic.
-
-!!! info
- ✔️ 🤯 👈 🎻 💪 🚫 🌐 Pydantic 🏷 💪.
-
- , 👆 5️⃣📆 💪 ⚙️ Pydantic 🏷.
-
- ✋️ 🚥 👆 ✔️ 📚 🎻 🤥 🤭, 👉 👌 🎱 ⚙️ 👫 🏋️ 🕸 🛠️ ⚙️ FastAPI. 👶
-
-## 🎻 `response_model`
-
-👆 💪 ⚙️ `dataclasses` `response_model` 🔢:
-
-```Python hl_lines="1 7-13 19"
-{!../../../docs_src/dataclasses/tutorial002.py!}
-```
-
-🎻 🔜 🔁 🗜 Pydantic 🎻.
-
-👉 🌌, 🚮 🔗 🔜 🎦 🆙 🛠️ 🩺 👩💻 🔢:
-
-
-
-## 🎻 🔁 📊 📊
-
-👆 💪 🌀 `dataclasses` ⏮️ 🎏 🆎 ✍ ⚒ 🐦 📊 📊.
-
-💼, 👆 💪 ✔️ ⚙️ Pydantic ⏬ `dataclasses`. 🖼, 🚥 👆 ✔️ ❌ ⏮️ 🔁 🏗 🛠️ 🧾.
-
-👈 💼, 👆 💪 🎯 💱 🐩 `dataclasses` ⏮️ `pydantic.dataclasses`, ❔ 💧-♻:
-
-```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" }
-{!../../../docs_src/dataclasses/tutorial003.py!}
-```
-
-1️⃣. 👥 🗄 `field` ⚪️➡️ 🐩 `dataclasses`.
-
-2️⃣. `pydantic.dataclasses` 💧-♻ `dataclasses`.
-
-3️⃣. `Author` 🎻 🔌 📇 `Item` 🎻.
-
-4️⃣. `Author` 🎻 ⚙️ `response_model` 🔢.
-
-5️⃣. 👆 💪 ⚙️ 🎏 🐩 🆎 ✍ ⏮️ 🎻 📨 💪.
-
- 👉 💼, ⚫️ 📇 `Item` 🎻.
-
-6️⃣. 📥 👥 🛬 📖 👈 🔌 `items` ❔ 📇 🎻.
-
- FastAPI 🎯 ✍ 💽 🎻.
-
-7️⃣. 📥 `response_model` ⚙️ 🆎 ✍ 📇 `Author` 🎻.
-
- 🔄, 👆 💪 🌀 `dataclasses` ⏮️ 🐩 🆎 ✍.
-
-8️⃣. 👀 👈 👉 *➡ 🛠️ 🔢* ⚙️ 🥔 `def` ↩️ `async def`.
-
- 🕧, FastAPI 👆 💪 🌀 `def` & `async def` 💪.
-
- 🚥 👆 💪 ↗️ 🔃 🕐❔ ⚙️ ❔, ✅ 👅 📄 _"🏃 ❓" _ 🩺 🔃 `async` & `await`.
-
-9️⃣. 👉 *➡ 🛠️ 🔢* 🚫 🛬 🎻 (👐 ⚫️ 💪), ✋️ 📇 📖 ⏮️ 🔗 💽.
-
- FastAPI 🔜 ⚙️ `response_model` 🔢 (👈 🔌 🎻) 🗜 📨.
-
-👆 💪 🌀 `dataclasses` ⏮️ 🎏 🆎 ✍ 📚 🎏 🌀 📨 🏗 📊 📊.
-
-✅-📟 ✍ 💁♂ 🔛 👀 🌅 🎯 ℹ.
-
-## 💡 🌅
-
-👆 💪 🌀 `dataclasses` ⏮️ 🎏 Pydantic 🏷, 😖 ⚪️➡️ 👫, 🔌 👫 👆 👍 🏷, ♒️.
-
-💡 🌅, ✅ Pydantic 🩺 🔃 🎻.
-
-## ⏬
-
-👉 💪 ↩️ FastAPI ⏬ `0.67.0`. 👶
diff --git a/docs/em/docs/advanced/events.md b/docs/em/docs/advanced/events.md
deleted file mode 100644
index 671e81b186efd..0000000000000
--- a/docs/em/docs/advanced/events.md
+++ /dev/null
@@ -1,160 +0,0 @@
-# 🔆 🎉
-
-👆 💪 🔬 ⚛ (📟) 👈 🔜 🛠️ ⏭ 🈸 **▶️ 🆙**. 👉 ⛓ 👈 👉 📟 🔜 🛠️ **🕐**, **⏭** 🈸 **▶️ 📨 📨**.
-
-🎏 🌌, 👆 💪 🔬 ⚛ (📟) 👈 🔜 🛠️ 🕐❔ 🈸 **🤫 🔽**. 👉 💼, 👉 📟 🔜 🛠️ **🕐**, **⏮️** ✔️ 🍵 🎲 **📚 📨**.
-
-↩️ 👉 📟 🛠️ ⏭ 🈸 **▶️** ✊ 📨, & ▶️️ ⏮️ ⚫️ **🏁** 🚚 📨, ⚫️ 📔 🎂 🈸 **🔆** (🔤 "🔆" 🔜 ⚠ 🥈 👶).
-
-👉 💪 📶 ⚠ ⚒ 🆙 **ℹ** 👈 👆 💪 ⚙️ 🎂 📱, & 👈 **💰** 👪 📨, &/⚖️ 👈 👆 💪 **🧹 🆙** ⏮️. 🖼, 💽 🔗 🎱, ⚖️ 🚚 🔗 🎰 🏫 🏷.
-
-## ⚙️ 💼
-
-➡️ ▶️ ⏮️ 🖼 **⚙️ 💼** & ⤴️ 👀 ❔ ❎ ⚫️ ⏮️ 👉.
-
-➡️ 🌈 👈 👆 ✔️ **🎰 🏫 🏷** 👈 👆 💚 ⚙️ 🍵 📨. 👶
-
-🎏 🏷 🔗 👪 📨,, ⚫️ 🚫 1️⃣ 🏷 📍 📨, ⚖️ 1️⃣ 📍 👩💻 ⚖️ 🕳 🎏.
-
-➡️ 🌈 👈 🚚 🏷 💪 **✊ 🕰**, ↩️ ⚫️ ✔️ ✍ 📚 **💽 ⚪️➡️ 💾**. 👆 🚫 💚 ⚫️ 🔠 📨.
-
-👆 💪 📐 ⚫️ 🔝 🎚 🕹/📁, ✋️ 👈 🔜 ⛓ 👈 ⚫️ 🔜 **📐 🏷** 🚥 👆 🏃♂ 🙅 🏧 💯, ⤴️ 👈 💯 🔜 **🐌** ↩️ ⚫️ 🔜 ✔️ ⌛ 🏷 📐 ⏭ 💆♂ 💪 🏃 🔬 🍕 📟.
-
-👈 ⚫️❔ 👥 🔜 ❎, ➡️ 📐 🏷 ⏭ 📨 🍵, ✋️ 🕴 ▶️️ ⏭ 🈸 ▶️ 📨 📨, 🚫 ⏪ 📟 ➖ 📐.
-
-## 🔆
-
-👆 💪 🔬 👉 *🕴* & *🤫* ⚛ ⚙️ `lifespan` 🔢 `FastAPI` 📱, & "🔑 👨💼" (👤 🔜 🎦 👆 ⚫️❔ 👈 🥈).
-
-➡️ ▶️ ⏮️ 🖼 & ⤴️ 👀 ⚫️ ℹ.
-
-👥 ✍ 🔁 🔢 `lifespan()` ⏮️ `yield` 💖 👉:
-
-```Python hl_lines="16 19"
-{!../../../docs_src/events/tutorial003.py!}
-```
-
-📥 👥 ⚖ 😥 *🕴* 🛠️ 🚚 🏷 🚮 (❌) 🏷 🔢 📖 ⏮️ 🎰 🏫 🏷 ⏭ `yield`. 👉 📟 🔜 🛠️ **⏭** 🈸 **▶️ ✊ 📨**, ⏮️ *🕴*.
-
-& ⤴️, ▶️️ ⏮️ `yield`, 👥 🚚 🏷. 👉 📟 🔜 🛠️ **⏮️** 🈸 **🏁 🚚 📨**, ▶️️ ⏭ *🤫*. 👉 💪, 🖼, 🚀 ℹ 💖 💾 ⚖️ 💻.
-
-!!! tip
- `shutdown` 🔜 🔨 🕐❔ 👆 **⛔️** 🈸.
-
- 🎲 👆 💪 ▶️ 🆕 ⏬, ⚖️ 👆 🤚 🎡 🏃 ⚫️. 🤷
-
-### 🔆 🔢
-
-🥇 👜 👀, 👈 👥 ⚖ 🔁 🔢 ⏮️ `yield`. 👉 📶 🎏 🔗 ⏮️ `yield`.
-
-```Python hl_lines="14-19"
-{!../../../docs_src/events/tutorial003.py!}
-```
-
-🥇 🍕 🔢, ⏭ `yield`, 🔜 🛠️ **⏭** 🈸 ▶️.
-
-& 🍕 ⏮️ `yield` 🔜 🛠️ **⏮️** 🈸 ✔️ 🏁.
-
-### 🔁 🔑 👨💼
-
-🚥 👆 ✅, 🔢 🎀 ⏮️ `@asynccontextmanager`.
-
-👈 🗜 🔢 🔘 🕳 🤙 "**🔁 🔑 👨💼**".
-
-```Python hl_lines="1 13"
-{!../../../docs_src/events/tutorial003.py!}
-```
-
-**🔑 👨💼** 🐍 🕳 👈 👆 💪 ⚙️ `with` 📄, 🖼, `open()` 💪 ⚙️ 🔑 👨💼:
-
-```Python
-with open("file.txt") as file:
- file.read()
-```
-
-⏮️ ⏬ 🐍, 📤 **🔁 🔑 👨💼**. 👆 🔜 ⚙️ ⚫️ ⏮️ `async with`:
-
-```Python
-async with lifespan(app):
- await do_stuff()
-```
-
-🕐❔ 👆 ✍ 🔑 👨💼 ⚖️ 🔁 🔑 👨💼 💖 🔛, ⚫️❔ ⚫️ 🔨 👈, ⏭ 🛬 `with` 🍫, ⚫️ 🔜 🛠️ 📟 ⏭ `yield`, & ⏮️ ❎ `with` 🍫, ⚫️ 🔜 🛠️ 📟 ⏮️ `yield`.
-
-👆 📟 🖼 🔛, 👥 🚫 ⚙️ ⚫️ 🔗, ✋️ 👥 🚶♀️ ⚫️ FastAPI ⚫️ ⚙️ ⚫️.
-
-`lifespan` 🔢 `FastAPI` 📱 ✊ **🔁 🔑 👨💼**, 👥 💪 🚶♀️ 👆 🆕 `lifespan` 🔁 🔑 👨💼 ⚫️.
-
-```Python hl_lines="22"
-{!../../../docs_src/events/tutorial003.py!}
-```
-
-## 🎛 🎉 (😢)
-
-!!! warning
- 👍 🌌 🍵 *🕴* & *🤫* ⚙️ `lifespan` 🔢 `FastAPI` 📱 🔬 🔛.
-
- 👆 💪 🎲 🚶 👉 🍕.
-
-📤 🎛 🌌 🔬 👉 ⚛ 🛠️ ⏮️ *🕴* & ⏮️ *🤫*.
-
-👆 💪 🔬 🎉 🐕🦺 (🔢) 👈 💪 🛠️ ⏭ 🈸 ▶️ 🆙, ⚖️ 🕐❔ 🈸 🤫 🔽.
-
-👫 🔢 💪 📣 ⏮️ `async def` ⚖️ 😐 `def`.
-
-### `startup` 🎉
-
-🚮 🔢 👈 🔜 🏃 ⏭ 🈸 ▶️, 📣 ⚫️ ⏮️ 🎉 `"startup"`:
-
-```Python hl_lines="8"
-{!../../../docs_src/events/tutorial001.py!}
-```
-
-👉 💼, `startup` 🎉 🐕🦺 🔢 🔜 🔢 🏬 "💽" ( `dict`) ⏮️ 💲.
-
-👆 💪 🚮 🌅 🌘 1️⃣ 🎉 🐕🦺 🔢.
-
-& 👆 🈸 🏆 🚫 ▶️ 📨 📨 ⏭ 🌐 `startup` 🎉 🐕🦺 ✔️ 🏁.
-
-### `shutdown` 🎉
-
-🚮 🔢 👈 🔜 🏃 🕐❔ 🈸 🤫 🔽, 📣 ⚫️ ⏮️ 🎉 `"shutdown"`:
-
-```Python hl_lines="6"
-{!../../../docs_src/events/tutorial002.py!}
-```
-
-📥, `shutdown` 🎉 🐕🦺 🔢 🔜 ✍ ✍ ⏸ `"Application shutdown"` 📁 `log.txt`.
-
-!!! info
- `open()` 🔢, `mode="a"` ⛓ "🎻",, ⏸ 🔜 🚮 ⏮️ ⚫️❔ 🔛 👈 📁, 🍵 📁 ⏮️ 🎚.
-
-!!! tip
- 👀 👈 👉 💼 👥 ⚙️ 🐩 🐍 `open()` 🔢 👈 🔗 ⏮️ 📁.
-
- , ⚫️ 🔌 👤/🅾 (🔢/🔢), 👈 🚚 "⌛" 👜 ✍ 💾.
-
- ✋️ `open()` 🚫 ⚙️ `async` & `await`.
-
- , 👥 📣 🎉 🐕🦺 🔢 ⏮️ 🐩 `def` ↩️ `async def`.
-
-!!! info
- 👆 💪 ✍ 🌅 🔃 👫 🎉 🐕🦺 💃 🎉' 🩺.
-
-### `startup` & `shutdown` 👯♂️
-
-📤 ↕ 🤞 👈 ⚛ 👆 *🕴* & *🤫* 🔗, 👆 💪 💚 ▶️ 🕳 & ⤴️ 🏁 ⚫️, 📎 ℹ & ⤴️ 🚀 ⚫️, ♒️.
-
-🔨 👈 👽 🔢 👈 🚫 💰 ⚛ ⚖️ 🔢 👯♂️ 🌅 ⚠ 👆 🔜 💪 🏪 💲 🌐 🔢 ⚖️ 🎏 🎱.
-
-↩️ 👈, ⚫️ 🔜 👍 ↩️ ⚙️ `lifespan` 🔬 🔛.
-
-## 📡 ℹ
-
-📡 ℹ 😟 🤓. 👶
-
-🔘, 🔫 📡 🔧, 👉 🍕 🔆 🛠️, & ⚫️ 🔬 🎉 🤙 `startup` & `shutdown`.
-
-## 🎧 🈸
-
-👶 ✔️ 🤯 👈 👫 🔆 🎉 (🕴 & 🤫) 🔜 🕴 🛠️ 👑 🈸, 🚫 [🎧 🈸 - 🗻](./sub-applications.md){.internal-link target=_blank}.
diff --git a/docs/em/docs/advanced/generate-clients.md b/docs/em/docs/advanced/generate-clients.md
deleted file mode 100644
index 30560c8c659c5..0000000000000
--- a/docs/em/docs/advanced/generate-clients.md
+++ /dev/null
@@ -1,267 +0,0 @@
-# 🏗 👩💻
-
-**FastAPI** ⚓️ 🔛 🗄 🔧, 👆 🤚 🏧 🔗 ⏮️ 📚 🧰, 🔌 🏧 🛠️ 🩺 (🚚 🦁 🎚).
-
-1️⃣ 🎯 📈 👈 🚫 🎯 ⭐ 👈 👆 💪 **🏗 👩💻** (🕣 🤙 **📱** ) 👆 🛠️, 📚 🎏 **🛠️ 🇪🇸**.
-
-## 🗄 👩💻 🚂
-
-📤 📚 🧰 🏗 👩💻 ⚪️➡️ **🗄**.
-
-⚠ 🧰 🗄 🚂.
-
-🚥 👆 🏗 **🕸**, 📶 😌 🎛 🗄-📕-🇦🇪.
-
-## 🏗 📕 🕸 👩💻
-
-➡️ ▶️ ⏮️ 🙅 FastAPI 🈸:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9-11 14-15 18 19 23"
- {!> ../../../docs_src/generate_clients/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="7-9 12-13 16-17 21"
- {!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
- ```
-
-👀 👈 *➡ 🛠️* 🔬 🏷 👫 ⚙️ 📨 🚀 & 📨 🚀, ⚙️ 🏷 `Item` & `ResponseMessage`.
-
-### 🛠️ 🩺
-
-🚥 👆 🚶 🛠️ 🩺, 👆 🔜 👀 👈 ⚫️ ✔️ **🔗** 📊 📨 📨 & 📨 📨:
-
-
-
-👆 💪 👀 👈 🔗 ↩️ 👫 📣 ⏮️ 🏷 📱.
-
-👈 ℹ 💪 📱 **🗄 🔗**, & ⤴️ 🎦 🛠️ 🩺 (🦁 🎚).
-
-& 👈 🎏 ℹ ⚪️➡️ 🏷 👈 🔌 🗄 ⚫️❔ 💪 ⚙️ **🏗 👩💻 📟**.
-
-### 🏗 📕 👩💻
-
-🔜 👈 👥 ✔️ 📱 ⏮️ 🏷, 👥 💪 🏗 👩💻 📟 🕸.
-
-#### ❎ `openapi-typescript-codegen`
-
-👆 💪 ❎ `openapi-typescript-codegen` 👆 🕸 📟 ⏮️:
-
-
-
-👆 🔜 🤚 ✍ 🚀 📨:
-
-
-
-!!! tip
- 👀 ✍ `name` & `price`, 👈 🔬 FastAPI 🈸, `Item` 🏷.
-
-👆 🔜 ✔️ ⏸ ❌ 📊 👈 👆 📨:
-
-
-
-📨 🎚 🔜 ✔️ ✍:
-
-
-
-## FastAPI 📱 ⏮️ 🔖
-
-📚 💼 👆 FastAPI 📱 🔜 🦏, & 👆 🔜 🎲 ⚙️ 🔖 🎏 🎏 👪 *➡ 🛠️*.
-
-🖼, 👆 💪 ✔️ 📄 **🏬** & ➕1️⃣ 📄 **👩💻**, & 👫 💪 👽 🔖:
-
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="23 28 36"
- {!> ../../../docs_src/generate_clients/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="21 26 34"
- {!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
- ```
-
-### 🏗 📕 👩💻 ⏮️ 🔖
-
-🚥 👆 🏗 👩💻 FastAPI 📱 ⚙️ 🔖, ⚫️ 🔜 🛎 🎏 👩💻 📟 ⚓️ 🔛 🔖.
-
-👉 🌌 👆 🔜 💪 ✔️ 👜 ✔ & 👪 ☑ 👩💻 📟:
-
-
-
-👉 💼 👆 ✔️:
-
-* `ItemsService`
-* `UsersService`
-
-### 👩💻 👩🔬 📛
-
-▶️️ 🔜 🏗 👩🔬 📛 💖 `createItemItemsPost` 🚫 👀 📶 🧹:
-
-```TypeScript
-ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
-```
-
-...👈 ↩️ 👩💻 🚂 ⚙️ 🗄 🔗 **🛠️ 🆔** 🔠 *➡ 🛠️*.
-
-🗄 🚚 👈 🔠 🛠️ 🆔 😍 🤭 🌐 *➡ 🛠️*, FastAPI ⚙️ **🔢 📛**, **➡**, & **🇺🇸🔍 👩🔬/🛠️** 🏗 👈 🛠️ 🆔, ↩️ 👈 🌌 ⚫️ 💪 ⚒ 💭 👈 🛠️ 🆔 😍.
-
-✋️ 👤 🔜 🎦 👆 ❔ 📉 👈 ⏭. 👶
-
-## 🛃 🛠️ 🆔 & 👍 👩🔬 📛
-
-👆 💪 **🔀** 🌌 👫 🛠️ 🆔 **🏗** ⚒ 👫 🙅 & ✔️ **🙅 👩🔬 📛** 👩💻.
-
-👉 💼 👆 🔜 ✔️ 🚚 👈 🔠 🛠️ 🆔 **😍** 🎏 🌌.
-
-🖼, 👆 💪 ⚒ 💭 👈 🔠 *➡ 🛠️* ✔️ 🔖, & ⤴️ 🏗 🛠️ 🆔 ⚓️ 🔛 **🔖** & *➡ 🛠️* **📛** (🔢 📛).
-
-### 🛃 🏗 😍 🆔 🔢
-
-FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔** & 📛 🙆 💪 🛃 🏷, 📨 ⚖️ 📨.
-
-👆 💪 🛃 👈 🔢. ⚫️ ✊ `APIRoute` & 🔢 🎻.
-
-🖼, 📥 ⚫️ ⚙️ 🥇 🔖 (👆 🔜 🎲 ✔️ 🕴 1️⃣ 🔖) & *➡ 🛠️* 📛 (🔢 📛).
-
-👆 💪 ⤴️ 🚶♀️ 👈 🛃 🔢 **FastAPI** `generate_unique_id_function` 🔢:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="8-9 12"
- {!> ../../../docs_src/generate_clients/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="6-7 10"
- {!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
- ```
-
-### 🏗 📕 👩💻 ⏮️ 🛃 🛠️ 🆔
-
-🔜 🚥 👆 🏗 👩💻 🔄, 👆 🔜 👀 👈 ⚫️ ✔️ 📉 👩🔬 📛:
-
-
-
-👆 👀, 👩🔬 📛 🔜 ✔️ 🔖 & ⤴️ 🔢 📛, 🔜 👫 🚫 🔌 ℹ ⚪️➡️ 📛 ➡ & 🇺🇸🔍 🛠️.
-
-### 🗜 🗄 🔧 👩💻 🚂
-
-🏗 📟 ✔️ **❎ ℹ**.
-
-👥 ⏪ 💭 👈 👉 👩🔬 🔗 **🏬** ↩️ 👈 🔤 `ItemsService` (✊ ⚪️➡️ 🔖), ✋️ 👥 ✔️ 📛 🔡 👩🔬 📛 💁♂️. 👶
-
-👥 🔜 🎲 💚 🚧 ⚫️ 🗄 🏢, 👈 🔜 🚚 👈 🛠️ 🆔 **😍**.
-
-✋️ 🏗 👩💻 👥 💪 **🔀** 🗄 🛠️ 🆔 ▶️️ ⏭ 🏭 👩💻, ⚒ 👈 👩🔬 📛 👌 & **🧹**.
-
-👥 💪 ⏬ 🗄 🎻 📁 `openapi.json` & ⤴️ 👥 💪 **❎ 👈 🔡 🔖** ⏮️ ✍ 💖 👉:
-
-```Python
-{!../../../docs_src/generate_clients/tutorial004.py!}
-```
-
-⏮️ 👈, 🛠️ 🆔 🔜 📁 ⚪️➡️ 👜 💖 `items-get_items` `get_items`, 👈 🌌 👩💻 🚂 💪 🏗 🙅 👩🔬 📛.
-
-### 🏗 📕 👩💻 ⏮️ 🗜 🗄
-
-🔜 🔚 🏁 📁 `openapi.json`, 👆 🔜 🔀 `package.json` ⚙️ 👈 🇧🇿 📁, 🖼:
-
-```JSON hl_lines="7"
-{
- "name": "frontend-app",
- "version": "1.0.0",
- "description": "",
- "main": "index.js",
- "scripts": {
- "generate-client": "openapi --input ./openapi.json --output ./src/client --client axios"
- },
- "author": "",
- "license": "",
- "devDependencies": {
- "openapi-typescript-codegen": "^0.20.1",
- "typescript": "^4.6.2"
- }
-}
-```
-
-⏮️ 🏭 🆕 👩💻, 👆 🔜 🔜 ✔️ **🧹 👩🔬 📛**, ⏮️ 🌐 **✍**, **⏸ ❌**, ♒️:
-
-
-
-## 💰
-
-🕐❔ ⚙️ 🔁 🏗 👩💻 👆 🔜 **✍** :
-
-* 👩🔬.
-* 📨 🚀 💪, 🔢 🔢, ♒️.
-* 📨 🚀.
-
-👆 🔜 ✔️ **⏸ ❌** 🌐.
-
-& 🕐❔ 👆 ℹ 👩💻 📟, & **♻** 🕸, ⚫️ 🔜 ✔️ 🙆 🆕 *➡ 🛠️* 💪 👩🔬, 🗝 🕐 ❎, & 🙆 🎏 🔀 🔜 🎨 🔛 🏗 📟. 👶
-
-👉 ⛓ 👈 🚥 🕳 🔀 ⚫️ 🔜 **🎨** 🔛 👩💻 📟 🔁. & 🚥 👆 **🏗** 👩💻 ⚫️ 🔜 ❌ 👅 🚥 👆 ✔️ 🙆 **🔖** 📊 ⚙️.
-
-, 👆 🔜 **🔍 📚 ❌** 📶 ⏪ 🛠️ 🛵 ↩️ ✔️ ⌛ ❌ 🎦 🆙 👆 🏁 👩💻 🏭 & ⤴️ 🔄 ℹ 🌐❔ ⚠. 👶
diff --git a/docs/em/docs/advanced/index.md b/docs/em/docs/advanced/index.md
deleted file mode 100644
index abe8d357c90ac..0000000000000
--- a/docs/em/docs/advanced/index.md
+++ /dev/null
@@ -1,24 +0,0 @@
-# 🏧 👩💻 🦮
-
-## 🌖 ⚒
-
-👑 [🔰 - 👩💻 🦮](../tutorial/){.internal-link target=_blank} 🔜 🥃 🤝 👆 🎫 🔘 🌐 👑 ⚒ **FastAPI**.
-
-⏭ 📄 👆 🔜 👀 🎏 🎛, 📳, & 🌖 ⚒.
-
-!!! tip
- ⏭ 📄 **🚫 🎯 "🏧"**.
-
- & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
-
-## ✍ 🔰 🥇
-
-👆 💪 ⚙️ 🏆 ⚒ **FastAPI** ⏮️ 💡 ⚪️➡️ 👑 [🔰 - 👩💻 🦮](../tutorial/){.internal-link target=_blank}.
-
-& ⏭ 📄 🤔 👆 ⏪ ✍ ⚫️, & 🤔 👈 👆 💭 👈 👑 💭.
-
-## 🏎.🅾 ↗️
-
-🚥 👆 🔜 💖 ✊ 🏧-🔰 ↗️ 🔗 👉 📄 🩺, 👆 💪 💚 ✅: 💯-💾 🛠️ ⏮️ FastAPI & ☁ **🏎.🅾**.
-
-👫 ⏳ 🩸 1️⃣0️⃣ 💯 🌐 💰 🛠️ **FastAPI**. 👶 👶
diff --git a/docs/em/docs/advanced/middleware.md b/docs/em/docs/advanced/middleware.md
deleted file mode 100644
index b3e722ed08d46..0000000000000
--- a/docs/em/docs/advanced/middleware.md
+++ /dev/null
@@ -1,99 +0,0 @@
-# 🏧 🛠️
-
-👑 🔰 👆 ✍ ❔ 🚮 [🛃 🛠️](../tutorial/middleware.md){.internal-link target=_blank} 👆 🈸.
-
-& ⤴️ 👆 ✍ ❔ 🍵 [⚜ ⏮️ `CORSMiddleware`](../tutorial/cors.md){.internal-link target=_blank}.
-
-👉 📄 👥 🔜 👀 ❔ ⚙️ 🎏 🛠️.
-
-## ❎ 🔫 🛠️
-
-**FastAPI** ⚓️ 🔛 💃 & 🛠️ 🔫 🔧, 👆 💪 ⚙️ 🙆 🔫 🛠️.
-
-🛠️ 🚫 ✔️ ⚒ FastAPI ⚖️ 💃 👷, 📏 ⚫️ ⏩ 🔫 🔌.
-
-🏢, 🔫 🛠️ 🎓 👈 ⌛ 📨 🔫 📱 🥇 ❌.
-
-, 🧾 🥉-🥳 🔫 🛠️ 👫 🔜 🎲 💬 👆 🕳 💖:
-
-```Python
-from unicorn import UnicornMiddleware
-
-app = SomeASGIApp()
-
-new_app = UnicornMiddleware(app, some_config="rainbow")
-```
-
-✋️ FastAPI (🤙 💃) 🚚 🙅 🌌 ⚫️ 👈 ⚒ 💭 👈 🔗 🛠️ 🍵 💽 ❌ & 🛃 ⚠ 🐕🦺 👷 ☑.
-
-👈, 👆 ⚙️ `app.add_middleware()` (🖼 ⚜).
-
-```Python
-from fastapi import FastAPI
-from unicorn import UnicornMiddleware
-
-app = FastAPI()
-
-app.add_middleware(UnicornMiddleware, some_config="rainbow")
-```
-
-`app.add_middleware()` 📨 🛠️ 🎓 🥇 ❌ & 🙆 🌖 ❌ 🚶♀️ 🛠️.
-
-## 🛠️ 🛠️
-
-**FastAPI** 🔌 📚 🛠️ ⚠ ⚙️ 💼, 👥 🔜 👀 ⏭ ❔ ⚙️ 👫.
-
-!!! note "📡 ℹ"
- ⏭ 🖼, 👆 💪 ⚙️ `from starlette.middleware.something import SomethingMiddleware`.
-
- **FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃.
-
-## `HTTPSRedirectMiddleware`
-
-🛠️ 👈 🌐 📨 📨 🔜 👯♂️ `https` ⚖️ `wss`.
-
-🙆 📨 📨 `http` ⚖️ `ws` 🔜 ❎ 🔐 ⚖ ↩️.
-
-```Python hl_lines="2 6"
-{!../../../docs_src/advanced_middleware/tutorial001.py!}
-```
-
-## `TrustedHostMiddleware`
-
-🛠️ 👈 🌐 📨 📨 ✔️ ☑ ⚒ `Host` 🎚, ✔ 💂♂ 🛡 🇺🇸🔍 🦠 🎚 👊.
-
-```Python hl_lines="2 6-8"
-{!../../../docs_src/advanced_middleware/tutorial002.py!}
-```
-
-📄 ❌ 🐕🦺:
-
-* `allowed_hosts` - 📇 🆔 📛 👈 🔜 ✔ 📛. 🃏 🆔 ✅ `*.example.com` 🐕🦺 🎀 📁. ✔ 🙆 📛 👯♂️ ⚙️ `allowed_hosts=["*"]` ⚖️ 🚫 🛠️.
-
-🚥 📨 📨 🔨 🚫 ✔ ☑ ⤴️ `400` 📨 🔜 📨.
-
-## `GZipMiddleware`
-
-🍵 🗜 📨 🙆 📨 👈 🔌 `"gzip"` `Accept-Encoding` 🎚.
-
-🛠️ 🔜 🍵 👯♂️ 🐩 & 🎥 📨.
-
-```Python hl_lines="2 6"
-{!../../../docs_src/advanced_middleware/tutorial003.py!}
-```
-
-📄 ❌ 🐕🦺:
-
-* `minimum_size` - 🚫 🗜 📨 👈 🤪 🌘 👉 💯 📐 🔢. 🔢 `500`.
-
-## 🎏 🛠️
-
-📤 📚 🎏 🔫 🛠️.
-
-🖼:
-
-* 🔫
-* Uvicorn `ProxyHeadersMiddleware`
-* 🇸🇲
-
-👀 🎏 💪 🛠️ ✅ 💃 🛠️ 🩺 & 🔫 👌 📇.
diff --git a/docs/em/docs/advanced/nosql-databases.md b/docs/em/docs/advanced/nosql-databases.md
deleted file mode 100644
index 9c828a909478a..0000000000000
--- a/docs/em/docs/advanced/nosql-databases.md
+++ /dev/null
@@ -1,156 +0,0 @@
-# ☁ (📎 / 🦏 💽) 💽
-
-**FastAPI** 💪 🛠️ ⏮️ 🙆 ☁.
-
-📥 👥 🔜 👀 🖼 ⚙️ **🗄**, 📄 🧢 ☁ 💽.
-
-👆 💪 🛠️ ⚫️ 🙆 🎏 ☁ 💽 💖:
-
-* **✳**
-* **👸**
-* **✳**
-* **🇸🇲**
-* **✳**, ♒️.
-
-!!! tip
- 📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **🗄**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: https://github.com/tiangolo/full-stack-fastapi-couchbase
-
-## 🗄 🗄 🦲
-
-🔜, 🚫 💸 🙋 🎂, 🕴 🗄:
-
-```Python hl_lines="3-5"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-## 🔬 📉 ⚙️ "📄 🆎"
-
-👥 🔜 ⚙️ ⚫️ ⏪ 🔧 🏑 `type` 👆 📄.
-
-👉 🚫 ✔ 🗄, ✋️ 👍 💡 👈 🔜 ℹ 👆 ⏮️.
-
-```Python hl_lines="9"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-## 🚮 🔢 🤚 `Bucket`
-
-**🗄**, 🥡 ⚒ 📄, 👈 💪 🎏 🆎.
-
-👫 🛎 🌐 🔗 🎏 🈸.
-
-🔑 🔗 💽 🌏 🔜 "💽" (🎯 💽, 🚫 💽 💽).
-
-🔑 **✳** 🔜 "🗃".
-
-📟, `Bucket` 🎨 👑 🇨🇻 📻 ⏮️ 💽.
-
-👉 🚙 🔢 🔜:
-
-* 🔗 **🗄** 🌑 (👈 💪 👁 🎰).
- * ⚒ 🔢 ⏲.
-* 🔓 🌑.
-* 🤚 `Bucket` 👐.
- * ⚒ 🔢 ⏲.
-* 📨 ⚫️.
-
-```Python hl_lines="12-21"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-## ✍ Pydantic 🏷
-
-**🗄** "📄" 🤙 "🎻 🎚", 👥 💪 🏷 👫 ⏮️ Pydantic.
-
-### `User` 🏷
-
-🥇, ➡️ ✍ `User` 🏷:
-
-```Python hl_lines="24-28"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-👥 🔜 ⚙️ 👉 🏷 👆 *➡ 🛠️ 🔢*,, 👥 🚫 🔌 ⚫️ `hashed_password`.
-
-### `UserInDB` 🏷
-
-🔜, ➡️ ✍ `UserInDB` 🏷.
-
-👉 🔜 ✔️ 💽 👈 🤙 🏪 💽.
-
-👥 🚫 ✍ ⚫️ 🏿 Pydantic `BaseModel` ✋️ 🏿 👆 👍 `User`, ↩️ ⚫️ 🔜 ✔️ 🌐 🔢 `User` ➕ 👩❤👨 🌅:
-
-```Python hl_lines="31-33"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-!!! note
- 👀 👈 👥 ✔️ `hashed_password` & `type` 🏑 👈 🔜 🏪 💽.
-
- ✋️ ⚫️ 🚫 🍕 🏢 `User` 🏷 (1️⃣ 👥 🔜 📨 *➡ 🛠️*).
-
-## 🤚 👩💻
-
-🔜 ✍ 🔢 👈 🔜:
-
-* ✊ 🆔.
-* 🏗 📄 🆔 ⚪️➡️ ⚫️.
-* 🤚 📄 ⏮️ 👈 🆔.
-* 🚮 🎚 📄 `UserInDB` 🏷.
-
-🏗 🔢 👈 🕴 💡 🤚 👆 👩💻 ⚪️➡️ `username` (⚖️ 🙆 🎏 🔢) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 🏤-⚙️ ⚫️ 💗 🍕 & 🚮 ⚒ 💯 ⚫️:
-
-```Python hl_lines="36-42"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-### Ⓜ-🎻
-
-🚥 👆 🚫 😰 ⏮️ `f"userprofile::{username}"`, ⚫️ 🐍 "Ⓜ-🎻".
-
-🙆 🔢 👈 🚮 🔘 `{}` Ⓜ-🎻 🔜 ↔ / 💉 🎻.
-
-### `dict` 🏗
-
-🚥 👆 🚫 😰 ⏮️ `UserInDB(**result.value)`, ⚫️ ⚙️ `dict` "🏗".
-
-⚫️ 🔜 ✊ `dict` `result.value`, & ✊ 🔠 🚮 🔑 & 💲 & 🚶♀️ 👫 🔑-💲 `UserInDB` 🇨🇻 ❌.
-
-, 🚥 `dict` 🔌:
-
-```Python
-{
- "username": "johndoe",
- "hashed_password": "some_hash",
-}
-```
-
-⚫️ 🔜 🚶♀️ `UserInDB` :
-
-```Python
-UserInDB(username="johndoe", hashed_password="some_hash")
-```
-
-## ✍ 👆 **FastAPI** 📟
-
-### ✍ `FastAPI` 📱
-
-```Python hl_lines="46"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-### ✍ *➡ 🛠️ 🔢*
-
-👆 📟 🤙 🗄 & 👥 🚫 ⚙️ 🥼 🐍 await 🐕🦺, 👥 🔜 📣 👆 🔢 ⏮️ 😐 `def` ↩️ `async def`.
-
-, 🗄 👍 🚫 ⚙️ 👁 `Bucket` 🎚 💗 "🧵Ⓜ",, 👥 💪 🤚 🥡 🔗 & 🚶♀️ ⚫️ 👆 🚙 🔢:
-
-```Python hl_lines="49-53"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-## 🌃
-
-👆 💪 🛠️ 🙆 🥉 🥳 ☁ 💽, ⚙️ 👫 🐩 📦.
-
-🎏 ✔ 🙆 🎏 🔢 🧰, ⚙️ ⚖️ 🛠️.
diff --git a/docs/em/docs/advanced/openapi-callbacks.md b/docs/em/docs/advanced/openapi-callbacks.md
deleted file mode 100644
index 630b75ed29f0b..0000000000000
--- a/docs/em/docs/advanced/openapi-callbacks.md
+++ /dev/null
@@ -1,179 +0,0 @@
-# 🗄 ⏲
-
-👆 💪 ✍ 🛠️ ⏮️ *➡ 🛠️* 👈 💪 ⏲ 📨 *🔢 🛠️* ✍ 👱 🙆 (🎲 🎏 👩💻 👈 🔜 *⚙️* 👆 🛠️).
-
-🛠️ 👈 🔨 🕐❔ 👆 🛠️ 📱 🤙 *🔢 🛠️* 📛 "⏲". ↩️ 🖥 👈 🔢 👩💻 ✍ 📨 📨 👆 🛠️ & ⤴️ 👆 🛠️ *🤙 🔙*, 📨 📨 *🔢 🛠️* (👈 🎲 ✍ 🎏 👩💻).
-
-👉 💼, 👆 💪 💚 📄 ❔ 👈 🔢 🛠️ *🔜* 👀 💖. ⚫️❔ *➡ 🛠️* ⚫️ 🔜 ✔️, ⚫️❔ 💪 ⚫️ 🔜 ⌛, ⚫️❔ 📨 ⚫️ 🔜 📨, ♒️.
-
-## 📱 ⏮️ ⏲
-
-➡️ 👀 🌐 👉 ⏮️ 🖼.
-
-🌈 👆 🛠️ 📱 👈 ✔ 🏗 🧾.
-
-👉 🧾 🔜 ✔️ `id`, `title` (📦), `customer`, & `total`.
-
-👩💻 👆 🛠️ (🔢 👩💻) 🔜 ✍ 🧾 👆 🛠️ ⏮️ 🏤 📨.
-
-⤴️ 👆 🛠️ 🔜 (➡️ 🌈):
-
-* 📨 🧾 🕴 🔢 👩💻.
-* 📈 💸.
-* 📨 📨 🔙 🛠️ 👩💻 (🔢 👩💻).
- * 👉 🔜 🔨 📨 🏤 📨 (⚪️➡️ *👆 🛠️*) *🔢 🛠️* 🚚 👈 🔢 👩💻 (👉 "⏲").
-
-## 😐 **FastAPI** 📱
-
-➡️ 🥇 👀 ❔ 😐 🛠️ 📱 🔜 👀 💖 ⏭ ❎ ⏲.
-
-⚫️ 🔜 ✔️ *➡ 🛠️* 👈 🔜 📨 `Invoice` 💪, & 🔢 🔢 `callback_url` 👈 🔜 🔌 📛 ⏲.
-
-👉 🍕 📶 😐, 🌅 📟 🎲 ⏪ 😰 👆:
-
-```Python hl_lines="9-13 36-53"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
-```
-
-!!! tip
- `callback_url` 🔢 🔢 ⚙️ Pydantic 📛 🆎.
-
-🕴 🆕 👜 `callbacks=messages_callback_router.routes` ❌ *➡ 🛠️ 👨🎨*. 👥 🔜 👀 ⚫️❔ 👈 ⏭.
-
-## 🔬 ⏲
-
-☑ ⏲ 📟 🔜 🪀 🙇 🔛 👆 👍 🛠️ 📱.
-
-& ⚫️ 🔜 🎲 🪀 📚 ⚪️➡️ 1️⃣ 📱 ⏭.
-
-⚫️ 💪 1️⃣ ⚖️ 2️⃣ ⏸ 📟, 💖:
-
-```Python
-callback_url = "https://example.com/api/v1/invoices/events/"
-httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
-```
-
-✋️ 🎲 🏆 ⚠ 🍕 ⏲ ⚒ 💭 👈 👆 🛠️ 👩💻 (🔢 👩💻) 🛠️ *🔢 🛠️* ☑, 🛄 💽 👈 *👆 🛠️* 🔜 📨 📨 💪 ⏲, ♒️.
-
-, ⚫️❔ 👥 🔜 ⏭ 🚮 📟 📄 ❔ 👈 *🔢 🛠️* 🔜 👀 💖 📨 ⏲ ⚪️➡️ *👆 🛠️*.
-
-👈 🧾 🔜 🎦 🆙 🦁 🎚 `/docs` 👆 🛠️, & ⚫️ 🔜 ➡️ 🔢 👩💻 💭 ❔ 🏗 *🔢 🛠️*.
-
-👉 🖼 🚫 🛠️ ⏲ ⚫️ (👈 💪 ⏸ 📟), 🕴 🧾 🍕.
-
-!!! tip
- ☑ ⏲ 🇺🇸🔍 📨.
-
- 🕐❔ 🛠️ ⏲ 👆, 👆 💪 ⚙️ 🕳 💖 🇸🇲 ⚖️ 📨.
-
-## ✍ ⏲ 🧾 📟
-
-👉 📟 🏆 🚫 🛠️ 👆 📱, 👥 🕴 💪 ⚫️ *📄* ❔ 👈 *🔢 🛠️* 🔜 👀 💖.
-
-✋️, 👆 ⏪ 💭 ❔ 💪 ✍ 🏧 🧾 🛠️ ⏮️ **FastAPI**.
-
-👥 🔜 ⚙️ 👈 🎏 💡 📄 ❔ *🔢 🛠️* 🔜 👀 💖... 🏗 *➡ 🛠️(Ⓜ)* 👈 🔢 🛠️ 🔜 🛠️ (🕐 👆 🛠️ 🔜 🤙).
-
-!!! tip
- 🕐❔ ✍ 📟 📄 ⏲, ⚫️ 💪 ⚠ 🌈 👈 👆 👈 *🔢 👩💻*. & 👈 👆 ⏳ 🛠️ *🔢 🛠️*, 🚫 *👆 🛠️*.
-
- 🍕 🛠️ 👉 ☝ 🎑 ( *🔢 👩💻*) 💪 ℹ 👆 💭 💖 ⚫️ 🌅 ⭐ 🌐❔ 🚮 🔢, Pydantic 🏷 💪, 📨, ♒️. 👈 *🔢 🛠️*.
-
-### ✍ ⏲ `APIRouter`
-
-🥇 ✍ 🆕 `APIRouter` 👈 🔜 🔌 1️⃣ ⚖️ 🌅 ⏲.
-
-```Python hl_lines="3 25"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
-```
-
-### ✍ ⏲ *➡ 🛠️*
-
-✍ ⏲ *➡ 🛠️* ⚙️ 🎏 `APIRouter` 👆 ✍ 🔛.
-
-⚫️ 🔜 👀 💖 😐 FastAPI *➡ 🛠️*:
-
-* ⚫️ 🔜 🎲 ✔️ 📄 💪 ⚫️ 🔜 📨, ✅ `body: InvoiceEvent`.
-* & ⚫️ 💪 ✔️ 📄 📨 ⚫️ 🔜 📨, ✅ `response_model=InvoiceEventReceived`.
-
-```Python hl_lines="16-18 21-22 28-32"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
-```
-
-📤 2️⃣ 👑 🔺 ⚪️➡️ 😐 *➡ 🛠️*:
-
-* ⚫️ 🚫 💪 ✔️ 🙆 ☑ 📟, ↩️ 👆 📱 🔜 🙅 🤙 👉 📟. ⚫️ 🕴 ⚙️ 📄 *🔢 🛠️*. , 🔢 💪 ✔️ `pass`.
-* *➡* 💪 🔌 🗄 3️⃣ 🧬 (👀 🌖 🔛) 🌐❔ ⚫️ 💪 ⚙️ 🔢 ⏮️ 🔢 & 🍕 ⏮️ 📨 📨 *👆 🛠️*.
-
-### ⏲ ➡ 🧬
-
-⏲ *➡* 💪 ✔️ 🗄 3️⃣ 🧬 👈 💪 🔌 🍕 ⏮️ 📨 📨 *👆 🛠️*.
-
-👉 💼, ⚫️ `str`:
-
-```Python
-"{$callback_url}/invoices/{$request.body.id}"
-```
-
-, 🚥 👆 🛠️ 👩💻 (🔢 👩💻) 📨 📨 *👆 🛠️* :
-
-```
-https://yourapi.com/invoices/?callback_url=https://www.external.org/events
-```
-
-⏮️ 🎻 💪:
-
-```JSON
-{
- "id": "2expen51ve",
- "customer": "Mr. Richie Rich",
- "total": "9999"
-}
-```
-
-⤴️ *👆 🛠️* 🔜 🛠️ 🧾, & ☝ ⏪, 📨 ⏲ 📨 `callback_url` ( *🔢 🛠️*):
-
-```
-https://www.external.org/events/invoices/2expen51ve
-```
-
-⏮️ 🎻 💪 ⚗ 🕳 💖:
-
-```JSON
-{
- "description": "Payment celebration",
- "paid": true
-}
-```
-
-& ⚫️ 🔜 ⌛ 📨 ⚪️➡️ 👈 *🔢 🛠️* ⏮️ 🎻 💪 💖:
-
-```JSON
-{
- "ok": true
-}
-```
-
-!!! tip
- 👀 ❔ ⏲ 📛 ⚙️ 🔌 📛 📨 🔢 🔢 `callback_url` (`https://www.external.org/events`) & 🧾 `id` ⚪️➡️ 🔘 🎻 💪 (`2expen51ve`).
-
-### 🚮 ⏲ 📻
-
-👉 ☝ 👆 ✔️ *⏲ ➡ 🛠️(Ⓜ)* 💪 (1️⃣(Ⓜ) 👈 *🔢 👩💻* 🔜 🛠️ *🔢 🛠️*) ⏲ 📻 👆 ✍ 🔛.
-
-🔜 ⚙️ 🔢 `callbacks` *👆 🛠️ ➡ 🛠️ 👨🎨* 🚶♀️ 🔢 `.routes` (👈 🤙 `list` 🛣/*➡ 🛠️*) ⚪️➡️ 👈 ⏲ 📻:
-
-```Python hl_lines="35"
-{!../../../docs_src/openapi_callbacks/tutorial001.py!}
-```
-
-!!! tip
- 👀 👈 👆 🚫 🚶♀️ 📻 ⚫️ (`invoices_callback_router`) `callback=`, ✋️ 🔢 `.routes`, `invoices_callback_router.routes`.
-
-### ✅ 🩺
-
-🔜 👆 💪 ▶️ 👆 📱 ⏮️ Uvicorn & 🚶 http://127.0.0.1:8000/docs.
-
-👆 🔜 👀 👆 🩺 ✅ "⏲" 📄 👆 *➡ 🛠️* 👈 🎦 ❔ *🔢 🛠️* 🔜 👀 💖:
-
-
diff --git a/docs/em/docs/advanced/path-operation-advanced-configuration.md b/docs/em/docs/advanced/path-operation-advanced-configuration.md
deleted file mode 100644
index ec72318706fee..0000000000000
--- a/docs/em/docs/advanced/path-operation-advanced-configuration.md
+++ /dev/null
@@ -1,170 +0,0 @@
-# ➡ 🛠️ 🏧 📳
-
-## 🗄 {
-
-!!! warning
- 🚥 👆 🚫 "🕴" 🗄, 👆 🎲 🚫 💪 👉.
-
-👆 💪 ⚒ 🗄 `operationId` ⚙️ 👆 *➡ 🛠️* ⏮️ 🔢 `operation_id`.
-
-👆 🔜 ✔️ ⚒ 💭 👈 ⚫️ 😍 🔠 🛠️.
-
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
-```
-
-### ⚙️ *➡ 🛠️ 🔢* 📛 {
-
-🚥 👆 💚 ⚙️ 👆 🔗' 🔢 📛 `operationId`Ⓜ, 👆 💪 🔁 🤭 🌐 👫 & 🔐 🔠 *➡ 🛠️* `operation_id` ⚙️ 👫 `APIRoute.name`.
-
-👆 🔜 ⚫️ ⏮️ ❎ 🌐 👆 *➡ 🛠️*.
-
-```Python hl_lines="2 12-21 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
-```
-
-!!! tip
- 🚥 👆 ❎ 🤙 `app.openapi()`, 👆 🔜 ℹ `operationId`Ⓜ ⏭ 👈.
-
-!!! warning
- 🚥 👆 👉, 👆 ✔️ ⚒ 💭 🔠 1️⃣ 👆 *➡ 🛠️ 🔢* ✔️ 😍 📛.
-
- 🚥 👫 🎏 🕹 (🐍 📁).
-
-## 🚫 ⚪️➡️ 🗄
-
-🚫 *➡ 🛠️* ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚙️ 🔢 `include_in_schema` & ⚒ ⚫️ `False`:
-
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
-```
-
-## 🏧 📛 ⚪️➡️ #️⃣
-
-👆 💪 📉 ⏸ ⚙️ ⚪️➡️ #️⃣ *➡ 🛠️ 🔢* 🗄.
-
-❎ `\f` (😖 "📨 🍼" 🦹) 🤕 **FastAPI** 🔁 🔢 ⚙️ 🗄 👉 ☝.
-
-⚫️ 🏆 🚫 🎦 🆙 🧾, ✋️ 🎏 🧰 (✅ 🐉) 🔜 💪 ⚙️ 🎂.
-
-```Python hl_lines="19-29"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
-```
-
-## 🌖 📨
-
-👆 🎲 ✔️ 👀 ❔ 📣 `response_model` & `status_code` *➡ 🛠️*.
-
-👈 🔬 🗃 🔃 👑 📨 *➡ 🛠️*.
-
-👆 💪 📣 🌖 📨 ⏮️ 👫 🏷, 👔 📟, ♒️.
-
-📤 🎂 📃 📥 🧾 🔃 ⚫️, 👆 💪 ✍ ⚫️ [🌖 📨 🗄](./additional-responses.md){.internal-link target=_blank}.
-
-## 🗄 ➕
-
-🕐❔ 👆 📣 *➡ 🛠️* 👆 🈸, **FastAPI** 🔁 🏗 🔗 🗃 🔃 👈 *➡ 🛠️* 🔌 🗄 🔗.
-
-!!! note "📡 ℹ"
- 🗄 🔧 ⚫️ 🤙 🛠️ 🎚.
-
-⚫️ ✔️ 🌐 ℹ 🔃 *➡ 🛠️* & ⚙️ 🏗 🏧 🧾.
-
-⚫️ 🔌 `tags`, `parameters`, `requestBody`, `responses`, ♒️.
-
-👉 *➡ 🛠️*-🎯 🗄 🔗 🛎 🏗 🔁 **FastAPI**, ✋️ 👆 💪 ↔ ⚫️.
-
-!!! tip
- 👉 🔅 🎚 ↔ ☝.
-
- 🚥 👆 🕴 💪 📣 🌖 📨, 🌅 🏪 🌌 ⚫️ ⏮️ [🌖 📨 🗄](./additional-responses.md){.internal-link target=_blank}.
-
-👆 💪 ↔ 🗄 🔗 *➡ 🛠️* ⚙️ 🔢 `openapi_extra`.
-
-### 🗄 ↔
-
-👉 `openapi_extra` 💪 👍, 🖼, 📣 [🗄 ↔](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):
-
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!}
-```
-
-🚥 👆 📂 🏧 🛠️ 🩺, 👆 ↔ 🔜 🎦 🆙 🔝 🎯 *➡ 🛠️*.
-
-
-
-& 🚥 👆 👀 📉 🗄 ( `/openapi.json` 👆 🛠️), 👆 🔜 👀 👆 ↔ 🍕 🎯 *➡ 🛠️* 💁♂️:
-
-```JSON hl_lines="22"
-{
- "openapi": "3.0.2",
- "info": {
- "title": "FastAPI",
- "version": "0.1.0"
- },
- "paths": {
- "/items/": {
- "get": {
- "summary": "Read Items",
- "operationId": "read_items_items__get",
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {}
- }
- }
- }
- },
- "x-aperture-labs-portal": "blue"
- }
- }
- }
-}
-```
-
-### 🛃 🗄 *➡ 🛠️* 🔗
-
-📖 `openapi_extra` 🔜 🙇 🔗 ⏮️ 🔁 🏗 🗄 🔗 *➡ 🛠️*.
-
-, 👆 💪 🚮 🌖 💽 🔁 🏗 🔗.
-
-🖼, 👆 💪 💭 ✍ & ✔ 📨 ⏮️ 👆 👍 📟, 🍵 ⚙️ 🏧 ⚒ FastAPI ⏮️ Pydantic, ✋️ 👆 💪 💚 🔬 📨 🗄 🔗.
-
-👆 💪 👈 ⏮️ `openapi_extra`:
-
-```Python hl_lines="20-37 39-40"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py!}
-```
-
-👉 🖼, 👥 🚫 📣 🙆 Pydantic 🏷. 👐, 📨 💪 🚫 🎻 🎻, ⚫️ ✍ 🔗 `bytes`, & 🔢 `magic_data_reader()` 🔜 🈚 🎻 ⚫️ 🌌.
-
-👐, 👥 💪 📣 📈 🔗 📨 💪.
-
-### 🛃 🗄 🎚 🆎
-
-⚙️ 👉 🎏 🎱, 👆 💪 ⚙️ Pydantic 🏷 🔬 🎻 🔗 👈 ⤴️ 🔌 🛃 🗄 🔗 📄 *➡ 🛠️*.
-
-& 👆 💪 👉 🚥 💽 🆎 📨 🚫 🎻.
-
-🖼, 👉 🈸 👥 🚫 ⚙️ FastAPI 🛠️ 🛠️ ⚗ 🎻 🔗 ⚪️➡️ Pydantic 🏷 🚫 🏧 🔬 🎻. 👐, 👥 📣 📨 🎚 🆎 📁, 🚫 🎻:
-
-```Python hl_lines="17-22 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
-```
-
-👐, 👐 👥 🚫 ⚙️ 🔢 🛠️ 🛠️, 👥 ⚙️ Pydantic 🏷 ❎ 🏗 🎻 🔗 💽 👈 👥 💚 📨 📁.
-
-⤴️ 👥 ⚙️ 📨 🔗, & ⚗ 💪 `bytes`. 👉 ⛓ 👈 FastAPI 🏆 🚫 🔄 🎻 📨 🚀 🎻.
-
-& ⤴️ 👆 📟, 👥 🎻 👈 📁 🎚 🔗, & ⤴️ 👥 🔄 ⚙️ 🎏 Pydantic 🏷 ✔ 📁 🎚:
-
-```Python hl_lines="26-33"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
-```
-
-!!! tip
- 📥 👥 🏤-⚙️ 🎏 Pydantic 🏷.
-
- ✋️ 🎏 🌌, 👥 💪 ✔️ ✔ ⚫️ 🎏 🌌.
diff --git a/docs/em/docs/advanced/response-change-status-code.md b/docs/em/docs/advanced/response-change-status-code.md
deleted file mode 100644
index 156efcc16ab49..0000000000000
--- a/docs/em/docs/advanced/response-change-status-code.md
+++ /dev/null
@@ -1,33 +0,0 @@
-# 📨 - 🔀 👔 📟
-
-👆 🎲 ✍ ⏭ 👈 👆 💪 ⚒ 🔢 [📨 👔 📟](../tutorial/response-status-code.md){.internal-link target=_blank}.
-
-✋️ 💼 👆 💪 📨 🎏 👔 📟 🌘 🔢.
-
-## ⚙️ 💼
-
-🖼, 🌈 👈 👆 💚 📨 🇺🇸🔍 👔 📟 "👌" `200` 🔢.
-
-✋️ 🚥 💽 🚫 🔀, 👆 💚 ✍ ⚫️, & 📨 🇺🇸🔍 👔 📟 "✍" `201`.
-
-✋️ 👆 💚 💪 ⛽ & 🗜 💽 👆 📨 ⏮️ `response_model`.
-
-📚 💼, 👆 💪 ⚙️ `Response` 🔢.
-
-## ⚙️ `Response` 🔢
-
-👆 💪 📣 🔢 🆎 `Response` 👆 *➡ 🛠️ 🔢* (👆 💪 🍪 & 🎚).
-
-& ⤴️ 👆 💪 ⚒ `status_code` 👈 *🔀* 📨 🎚.
-
-```Python hl_lines="1 9 12"
-{!../../../docs_src/response_change_status_code/tutorial001.py!}
-```
-
-& ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️).
-
-& 🚥 👆 📣 `response_model`, ⚫️ 🔜 ⚙️ ⛽ & 🗜 🎚 👆 📨.
-
-**FastAPI** 🔜 ⚙️ 👈 *🔀* 📨 ⚗ 👔 📟 (🍪 & 🎚), & 🔜 🚮 👫 🏁 📨 👈 🔌 💲 👆 📨, ⛽ 🙆 `response_model`.
-
-👆 💪 📣 `Response` 🔢 🔗, & ⚒ 👔 📟 👫. ✋️ ✔️ 🤯 👈 🏁 1️⃣ ⚒ 🔜 🏆.
diff --git a/docs/em/docs/advanced/response-cookies.md b/docs/em/docs/advanced/response-cookies.md
deleted file mode 100644
index 23fffe1ddc19b..0000000000000
--- a/docs/em/docs/advanced/response-cookies.md
+++ /dev/null
@@ -1,49 +0,0 @@
-# 📨 🍪
-
-## ⚙️ `Response` 🔢
-
-👆 💪 📣 🔢 🆎 `Response` 👆 *➡ 🛠️ 🔢*.
-
-& ⤴️ 👆 💪 ⚒ 🍪 👈 *🔀* 📨 🎚.
-
-```Python hl_lines="1 8-9"
-{!../../../docs_src/response_cookies/tutorial002.py!}
-```
-
-& ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️).
-
-& 🚥 👆 📣 `response_model`, ⚫️ 🔜 ⚙️ ⛽ & 🗜 🎚 👆 📨.
-
-**FastAPI** 🔜 ⚙️ 👈 *🔀* 📨 ⚗ 🍪 (🎚 & 👔 📟), & 🔜 🚮 👫 🏁 📨 👈 🔌 💲 👆 📨, ⛽ 🙆 `response_model`.
-
-👆 💪 📣 `Response` 🔢 🔗, & ⚒ 🍪 (& 🎚) 👫.
-
-## 📨 `Response` 🔗
-
-👆 💪 ✍ 🍪 🕐❔ 🛬 `Response` 🔗 👆 📟.
-
-👈, 👆 💪 ✍ 📨 🔬 [📨 📨 🔗](response-directly.md){.internal-link target=_blank}.
-
-⤴️ ⚒ 🍪 ⚫️, & ⤴️ 📨 ⚫️:
-
-```Python hl_lines="10-12"
-{!../../../docs_src/response_cookies/tutorial001.py!}
-```
-
-!!! tip
- ✔️ 🤯 👈 🚥 👆 📨 📨 🔗 ↩️ ⚙️ `Response` 🔢, FastAPI 🔜 📨 ⚫️ 🔗.
-
- , 👆 🔜 ✔️ ⚒ 💭 👆 💽 ☑ 🆎. 🤶 Ⓜ. ⚫️ 🔗 ⏮️ 🎻, 🚥 👆 🛬 `JSONResponse`.
-
- & 👈 👆 🚫 📨 🙆 📊 👈 🔜 ✔️ ⛽ `response_model`.
-
-### 🌅 ℹ
-
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`.
-
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
-
- & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`.
-
-👀 🌐 💪 🔢 & 🎛, ✅ 🧾 💃.
diff --git a/docs/em/docs/advanced/response-directly.md b/docs/em/docs/advanced/response-directly.md
deleted file mode 100644
index ba09734fb3447..0000000000000
--- a/docs/em/docs/advanced/response-directly.md
+++ /dev/null
@@ -1,63 +0,0 @@
-# 📨 📨 🔗
-
-🕐❔ 👆 ✍ **FastAPI** *➡ 🛠️* 👆 💪 🛎 📨 🙆 📊 ⚪️➡️ ⚫️: `dict`, `list`, Pydantic 🏷, 💽 🏷, ♒️.
-
-🔢, **FastAPI** 🔜 🔁 🗜 👈 📨 💲 🎻 ⚙️ `jsonable_encoder` 🔬 [🎻 🔗 🔢](../tutorial/encoder.md){.internal-link target=_blank}.
-
-⤴️, ⛅ 🎑, ⚫️ 🔜 🚮 👈 🎻-🔗 💽 (✅ `dict`) 🔘 `JSONResponse` 👈 🔜 ⚙️ 📨 📨 👩💻.
-
-✋️ 👆 💪 📨 `JSONResponse` 🔗 ⚪️➡️ 👆 *➡ 🛠️*.
-
-⚫️ 💪 ⚠, 🖼, 📨 🛃 🎚 ⚖️ 🍪.
-
-## 📨 `Response`
-
-👐, 👆 💪 📨 🙆 `Response` ⚖️ 🙆 🎧-🎓 ⚫️.
-
-!!! tip
- `JSONResponse` ⚫️ 🎧-🎓 `Response`.
-
-& 🕐❔ 👆 📨 `Response`, **FastAPI** 🔜 🚶♀️ ⚫️ 🔗.
-
-⚫️ 🏆 🚫 🙆 💽 🛠️ ⏮️ Pydantic 🏷, ⚫️ 🏆 🚫 🗜 🎚 🙆 🆎, ♒️.
-
-👉 🤝 👆 📚 💪. 👆 💪 📨 🙆 📊 🆎, 🔐 🙆 💽 📄 ⚖️ 🔬, ♒️.
-
-## ⚙️ `jsonable_encoder` `Response`
-
-↩️ **FastAPI** 🚫 🙆 🔀 `Response` 👆 📨, 👆 ✔️ ⚒ 💭 ⚫️ 🎚 🔜 ⚫️.
-
-🖼, 👆 🚫🔜 🚮 Pydantic 🏷 `JSONResponse` 🍵 🥇 🏭 ⚫️ `dict` ⏮️ 🌐 📊 🆎 (💖 `datetime`, `UUID`, ♒️) 🗜 🎻-🔗 🆎.
-
-📚 💼, 👆 💪 ⚙️ `jsonable_encoder` 🗜 👆 📊 ⏭ 🚶♀️ ⚫️ 📨:
-
-```Python hl_lines="6-7 21-22"
-{!../../../docs_src/response_directly/tutorial001.py!}
-```
-
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import JSONResponse`.
-
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
-
-## 🛬 🛃 `Response`
-
-🖼 🔛 🎦 🌐 🍕 👆 💪, ✋️ ⚫️ 🚫 📶 ⚠, 👆 💪 ✔️ 📨 `item` 🔗, & **FastAPI** 🔜 🚮 ⚫️ `JSONResponse` 👆, 🏭 ⚫️ `dict`, ♒️. 🌐 👈 🔢.
-
-🔜, ➡️ 👀 ❔ 👆 💪 ⚙️ 👈 📨 🛃 📨.
-
-➡️ 💬 👈 👆 💚 📨 📂 📨.
-
-👆 💪 🚮 👆 📂 🎚 🎻, 🚮 ⚫️ `Response`, & 📨 ⚫️:
-
-```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
-```
-
-## 🗒
-
-🕐❔ 👆 📨 `Response` 🔗 🚮 📊 🚫 ✔, 🗜 (🎻), 🚫 📄 🔁.
-
-✋️ 👆 💪 📄 ⚫️ 🔬 [🌖 📨 🗄](additional-responses.md){.internal-link target=_blank}.
-
-👆 💪 👀 ⏪ 📄 ❔ ⚙️/📣 👉 🛃 `Response`Ⓜ ⏪ ✔️ 🏧 💽 🛠️, 🧾, ♒️.
diff --git a/docs/em/docs/advanced/response-headers.md b/docs/em/docs/advanced/response-headers.md
deleted file mode 100644
index de798982a95d0..0000000000000
--- a/docs/em/docs/advanced/response-headers.md
+++ /dev/null
@@ -1,42 +0,0 @@
-# 📨 🎚
-
-## ⚙️ `Response` 🔢
-
-👆 💪 📣 🔢 🆎 `Response` 👆 *➡ 🛠️ 🔢* (👆 💪 🍪).
-
-& ⤴️ 👆 💪 ⚒ 🎚 👈 *🔀* 📨 🎚.
-
-```Python hl_lines="1 7-8"
-{!../../../docs_src/response_headers/tutorial002.py!}
-```
-
-& ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️).
-
-& 🚥 👆 📣 `response_model`, ⚫️ 🔜 ⚙️ ⛽ & 🗜 🎚 👆 📨.
-
-**FastAPI** 🔜 ⚙️ 👈 *🔀* 📨 ⚗ 🎚 (🍪 & 👔 📟), & 🔜 🚮 👫 🏁 📨 👈 🔌 💲 👆 📨, ⛽ 🙆 `response_model`.
-
-👆 💪 📣 `Response` 🔢 🔗, & ⚒ 🎚 (& 🍪) 👫.
-
-## 📨 `Response` 🔗
-
-👆 💪 🚮 🎚 🕐❔ 👆 📨 `Response` 🔗.
-
-✍ 📨 🔬 [📨 📨 🔗](response-directly.md){.internal-link target=_blank} & 🚶♀️ 🎚 🌖 🔢:
-
-```Python hl_lines="10-12"
-{!../../../docs_src/response_headers/tutorial001.py!}
-```
-
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`.
-
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
-
- & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`.
-
-## 🛃 🎚
-
-✔️ 🤯 👈 🛃 © 🎚 💪 🚮 ⚙️ '✖-' 🔡.
-
-✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 (✍ 🌅 [⚜ (✖️-🇨🇳 ℹ 🤝)](../tutorial/cors.md){.internal-link target=_blank}), ⚙️ 🔢 `expose_headers` 📄 💃 ⚜ 🩺.
diff --git a/docs/em/docs/advanced/security/http-basic-auth.md b/docs/em/docs/advanced/security/http-basic-auth.md
deleted file mode 100644
index 33470a7268905..0000000000000
--- a/docs/em/docs/advanced/security/http-basic-auth.md
+++ /dev/null
@@ -1,113 +0,0 @@
-# 🇺🇸🔍 🔰 🔐
-
-🙅 💼, 👆 💪 ⚙️ 🇺🇸🔍 🔰 🔐.
-
-🇺🇸🔍 🔰 🔐, 🈸 ⌛ 🎚 👈 🔌 🆔 & 🔐.
-
-🚥 ⚫️ 🚫 📨 ⚫️, ⚫️ 📨 🇺🇸🔍 4️⃣0️⃣1️⃣ "⛔" ❌.
-
-& 📨 🎚 `WWW-Authenticate` ⏮️ 💲 `Basic`, & 📦 `realm` 🔢.
-
-👈 💬 🖥 🎦 🛠️ 📋 🆔 & 🔐.
-
-⤴️, 🕐❔ 👆 🆎 👈 🆔 & 🔐, 🖥 📨 👫 🎚 🔁.
-
-## 🙅 🇺🇸🔍 🔰 🔐
-
-* 🗄 `HTTPBasic` & `HTTPBasicCredentials`.
-* ✍ "`security` ⚖" ⚙️ `HTTPBasic`.
-* ⚙️ 👈 `security` ⏮️ 🔗 👆 *➡ 🛠️*.
-* ⚫️ 📨 🎚 🆎 `HTTPBasicCredentials`:
- * ⚫️ 🔌 `username` & `password` 📨.
-
-```Python hl_lines="2 6 10"
-{!../../../docs_src/security/tutorial006.py!}
-```
-
-🕐❔ 👆 🔄 📂 📛 🥇 🕰 (⚖️ 🖊 "🛠️" 🔼 🩺) 🖥 🔜 💭 👆 👆 🆔 & 🔐:
-
-
-
-## ✅ 🆔
-
-📥 🌅 🏁 🖼.
-
-⚙️ 🔗 ✅ 🚥 🆔 & 🔐 ☑.
-
-👉, ⚙️ 🐍 🐩 🕹 `secrets` ✅ 🆔 & 🔐.
-
-`secrets.compare_digest()` 💪 ✊ `bytes` ⚖️ `str` 👈 🕴 🔌 🔠 🦹 (🕐 🇪🇸), 👉 ⛓ ⚫️ 🚫🔜 👷 ⏮️ 🦹 💖 `á`, `Sebastián`.
-
-🍵 👈, 👥 🥇 🗜 `username` & `password` `bytes` 🔢 👫 ⏮️ 🔠-8️⃣.
-
-⤴️ 👥 💪 ⚙️ `secrets.compare_digest()` 🚚 👈 `credentials.username` `"stanleyjobson"`, & 👈 `credentials.password` `"swordfish"`.
-
-```Python hl_lines="1 11-21"
-{!../../../docs_src/security/tutorial007.py!}
-```
-
-👉 🔜 🎏:
-
-```Python
-if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
- # Return some error
- ...
-```
-
-✋️ ⚙️ `secrets.compare_digest()` ⚫️ 🔜 🔐 🛡 🆎 👊 🤙 "🕰 👊".
-
-### ⏲ 👊
-
-✋️ ⚫️❔ "⏲ 👊"❓
-
-➡️ 🌈 👊 🔄 💭 🆔 & 🔐.
-
-& 👫 📨 📨 ⏮️ 🆔 `johndoe` & 🔐 `love123`.
-
-⤴️ 🐍 📟 👆 🈸 🔜 🌓 🕳 💖:
-
-```Python
-if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
- ...
-```
-
-✋️ ▶️️ 🙍 🐍 🔬 🥇 `j` `johndoe` 🥇 `s` `stanleyjobson`, ⚫️ 🔜 📨 `False`, ↩️ ⚫️ ⏪ 💭 👈 📚 2️⃣ 🎻 🚫 🎏, 💭 👈 "📤 🙅♂ 💪 🗑 🌅 📊 ⚖ 🎂 🔤". & 👆 🈸 🔜 💬 "❌ 👩💻 ⚖️ 🔐".
-
-✋️ ⤴️ 👊 🔄 ⏮️ 🆔 `stanleyjobsox` & 🔐 `love123`.
-
-& 👆 🈸 📟 🔨 🕳 💖:
-
-```Python
-if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
- ...
-```
-
-🐍 🔜 ✔️ 🔬 🎂 `stanleyjobso` 👯♂️ `stanleyjobsox` & `stanleyjobson` ⏭ 🤔 👈 👯♂️ 🎻 🚫 🎏. ⚫️ 🔜 ✊ ➕ ⏲ 📨 🔙 "❌ 👩💻 ⚖️ 🔐".
-
-#### 🕰 ❔ ℹ 👊
-
-👈 ☝, 👀 👈 💽 ✊ ⏲ 📏 📨 "❌ 👩💻 ⚖️ 🔐" 📨, 👊 🔜 💭 👈 👫 🤚 _🕳_ ▶️️, ▶️ 🔤 ▶️️.
-
-& ⤴️ 👫 💪 🔄 🔄 🤔 👈 ⚫️ 🎲 🕳 🌖 🎏 `stanleyjobsox` 🌘 `johndoe`.
-
-#### "🕴" 👊
-
-↗️, 👊 🔜 🚫 🔄 🌐 👉 ✋, 👫 🔜 ✍ 📋 ⚫️, 🎲 ⏮️ 💯 ⚖️ 💯 💯 📍 🥈. & 🔜 🤚 1️⃣ ➕ ☑ 🔤 🕰.
-
-✋️ 🔨 👈, ⏲ ⚖️ 📆 👊 🔜 ✔️ 💭 ☑ 🆔 & 🔐, ⏮️ "ℹ" 👆 🈸, ⚙️ 🕰 ✊ ❔.
-
-#### 🔧 ⚫️ ⏮️ `secrets.compare_digest()`
-
-✋️ 👆 📟 👥 🤙 ⚙️ `secrets.compare_digest()`.
-
-📏, ⚫️ 🔜 ✊ 🎏 🕰 🔬 `stanleyjobsox` `stanleyjobson` 🌘 ⚫️ ✊ 🔬 `johndoe` `stanleyjobson`. & 🎏 🔐.
-
-👈 🌌, ⚙️ `secrets.compare_digest()` 👆 🈸 📟, ⚫️ 🔜 🔒 🛡 👉 🎂 ↔ 💂♂ 👊.
-
-### 📨 ❌
-
-⏮️ 🔍 👈 🎓 ❌, 📨 `HTTPException` ⏮️ 👔 📟 4️⃣0️⃣1️⃣ (🎏 📨 🕐❔ 🙅♂ 🎓 🚚) & 🚮 🎚 `WWW-Authenticate` ⚒ 🖥 🎦 💳 📋 🔄:
-
-```Python hl_lines="23-27"
-{!../../../docs_src/security/tutorial007.py!}
-```
diff --git a/docs/em/docs/advanced/security/index.md b/docs/em/docs/advanced/security/index.md
deleted file mode 100644
index f2bb66df465c2..0000000000000
--- a/docs/em/docs/advanced/security/index.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# 🏧 💂♂
-
-## 🌖 ⚒
-
-📤 ➕ ⚒ 🍵 💂♂ ↖️ ⚪️➡️ 🕐 📔 [🔰 - 👩💻 🦮: 💂♂](../../tutorial/security/){.internal-link target=_blank}.
-
-!!! tip
- ⏭ 📄 **🚫 🎯 "🏧"**.
-
- & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫.
-
-## ✍ 🔰 🥇
-
-⏭ 📄 🤔 👆 ⏪ ✍ 👑 [🔰 - 👩💻 🦮: 💂♂](../../tutorial/security/){.internal-link target=_blank}.
-
-👫 🌐 ⚓️ 🔛 🎏 🔧, ✋️ ✔ ➕ 🛠️.
diff --git a/docs/em/docs/advanced/security/oauth2-scopes.md b/docs/em/docs/advanced/security/oauth2-scopes.md
deleted file mode 100644
index a4684352ccd4d..0000000000000
--- a/docs/em/docs/advanced/security/oauth2-scopes.md
+++ /dev/null
@@ -1,269 +0,0 @@
-# Oauth2️⃣ ↔
-
-👆 💪 ⚙️ Oauth2️⃣ ↔ 🔗 ⏮️ **FastAPI**, 👫 🛠️ 👷 💎.
-
-👉 🔜 ✔ 👆 ✔️ 🌖 👌-🧽 ✔ ⚙️, 📄 Oauth2️⃣ 🐩, 🛠️ 🔘 👆 🗄 🈸 (& 🛠️ 🩺).
-
-Oauth2️⃣ ⏮️ ↔ 🛠️ ⚙️ 📚 🦏 🤝 🐕🦺, 💖 👱📔, 🇺🇸🔍, 📂, 🤸♂, 👱📔, ♒️. 👫 ⚙️ ⚫️ 🚚 🎯 ✔ 👩💻 & 🈸.
-
-🔠 🕰 👆 "🕹 ⏮️" 👱📔, 🇺🇸🔍, 📂, 🤸♂, 👱📔, 👈 🈸 ⚙️ Oauth2️⃣ ⏮️ ↔.
-
-👉 📄 👆 🔜 👀 ❔ 🛠️ 🤝 & ✔ ⏮️ 🎏 Oauth2️⃣ ⏮️ ↔ 👆 **FastAPI** 🈸.
-
-!!! warning
- 👉 🌅 ⚖️ 🌘 🏧 📄. 🚥 👆 ▶️, 👆 💪 🚶 ⚫️.
-
- 👆 🚫 🎯 💪 Oauth2️⃣ ↔, & 👆 💪 🍵 🤝 & ✔ 👐 👆 💚.
-
- ✋️ Oauth2️⃣ ⏮️ ↔ 💪 🎆 🛠️ 🔘 👆 🛠️ (⏮️ 🗄) & 👆 🛠️ 🩺.
-
- 👐, 👆 🛠️ 📚 ↔, ⚖️ 🙆 🎏 💂♂/✔ 📄, 👐 👆 💪, 👆 📟.
-
- 📚 💼, Oauth2️⃣ ⏮️ ↔ 💪 👹.
-
- ✋️ 🚥 👆 💭 👆 💪 ⚫️, ⚖️ 👆 😟, 🚧 👂.
-
-## Oauth2️⃣ ↔ & 🗄
-
-Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
-
-🎚 🔠 👉 🎻 💪 ✔️ 🙆 📁, ✋️ 🔜 🚫 🔌 🚀.
-
-👫 ↔ 🎨 "✔".
-
-🗄 (✅ 🛠️ 🩺), 👆 💪 🔬 "💂♂ ⚖".
-
-🕐❔ 1️⃣ 👫 💂♂ ⚖ ⚙️ Oauth2️⃣, 👆 💪 📣 & ⚙️ ↔.
-
-🔠 "↔" 🎻 (🍵 🚀).
-
-👫 🛎 ⚙️ 📣 🎯 💂♂ ✔, 🖼:
-
-* `users:read` ⚖️ `users:write` ⚠ 🖼.
-* `instagram_basic` ⚙️ 👱📔 / 👱📔.
-* `https://www.googleapis.com/auth/drive` ⚙️ 🇺🇸🔍.
-
-!!! info
- Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔.
-
- ⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛.
-
- 👈 ℹ 🛠️ 🎯.
-
- Oauth2️⃣ 👫 🎻.
-
-## 🌐 🎑
-
-🥇, ➡️ 🔜 👀 🍕 👈 🔀 ⚪️➡️ 🖼 👑 **🔰 - 👩💻 🦮** [Oauth2️⃣ ⏮️ 🔐 (& 🔁), 📨 ⏮️ 🥙 🤝](../../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"
-{!../../../docs_src/security/tutorial005.py!}
-```
-
-🔜 ➡️ 📄 👈 🔀 🔁 🔁.
-
-## Oauth2️⃣ 💂♂ ⚖
-
-🥇 🔀 👈 🔜 👥 📣 Oauth2️⃣ 💂♂ ⚖ ⏮️ 2️⃣ 💪 ↔, `me` & `items`.
-
-`scopes` 🔢 📨 `dict` ⏮️ 🔠 ↔ 🔑 & 📛 💲:
-
-```Python hl_lines="62-65"
-{!../../../docs_src/security/tutorial005.py!}
-```
-
-↩️ 👥 🔜 📣 📚 ↔, 👫 🔜 🎦 🆙 🛠️ 🩺 🕐❔ 👆 🕹-/✔.
-
-& 👆 🔜 💪 🖊 ❔ ↔ 👆 💚 🤝 🔐: `me` & `items`.
-
-👉 🎏 🛠️ ⚙️ 🕐❔ 👆 🤝 ✔ ⏪ 🚨 ⏮️ 👱📔, 🇺🇸🔍, 📂, ♒️:
-
-
-
-## 🥙 🤝 ⏮️ ↔
-
-🔜, 🔀 🤝 *➡ 🛠️* 📨 ↔ 📨.
-
-👥 ⚙️ 🎏 `OAuth2PasswordRequestForm`. ⚫️ 🔌 🏠 `scopes` ⏮️ `list` `str`, ⏮️ 🔠 ↔ ⚫️ 📨 📨.
-
-& 👥 📨 ↔ 🍕 🥙 🤝.
-
-!!! danger
- 🦁, 📥 👥 ❎ ↔ 📨 🔗 🤝.
-
- ✋️ 👆 🈸, 💂♂, 👆 🔜 ⚒ 💭 👆 🕴 🚮 ↔ 👈 👩💻 🤙 💪 ✔️, ⚖️ 🕐 👆 ✔️ 🔁.
-
-```Python hl_lines="153"
-{!../../../docs_src/security/tutorial005.py!}
-```
-
-## 📣 ↔ *➡ 🛠️* & 🔗
-
-🔜 👥 📣 👈 *➡ 🛠️* `/users/me/items/` 🚚 ↔ `items`.
-
-👉, 👥 🗄 & ⚙️ `Security` ⚪️➡️ `fastapi`.
-
-👆 💪 ⚙️ `Security` 📣 🔗 (💖 `Depends`), ✋️ `Security` 📨 🔢 `scopes` ⏮️ 📇 ↔ (🎻).
-
-👉 💼, 👥 🚶♀️ 🔗 🔢 `get_current_active_user` `Security` (🎏 🌌 👥 🔜 ⏮️ `Depends`).
-
-✋️ 👥 🚶♀️ `list` ↔, 👉 💼 ⏮️ 1️⃣ ↔: `items` (⚫️ 💪 ✔️ 🌅).
-
-& 🔗 🔢 `get_current_active_user` 💪 📣 🎧-🔗, 🚫 🕴 ⏮️ `Depends` ✋️ ⏮️ `Security`. 📣 🚮 👍 🎧-🔗 🔢 (`get_current_user`), & 🌖 ↔ 📄.
-
-👉 💼, ⚫️ 🚚 ↔ `me` (⚫️ 💪 🚚 🌅 🌘 1️⃣ ↔).
-
-!!! note
- 👆 🚫 🎯 💪 🚮 🎏 ↔ 🎏 🥉.
-
- 👥 🔨 ⚫️ 📥 🎦 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚.
-
-```Python hl_lines="4 139 166"
-{!../../../docs_src/security/tutorial005.py!}
-```
-
-!!! info "📡 ℹ"
- `Security` 🤙 🏿 `Depends`, & ⚫️ ✔️ 1️⃣ ➕ 🔢 👈 👥 🔜 👀 ⏪.
-
- ✋️ ⚙️ `Security` ↩️ `Depends`, **FastAPI** 🔜 💭 👈 ⚫️ 💪 📣 💂♂ ↔, ⚙️ 👫 🔘, & 📄 🛠️ ⏮️ 🗄.
-
- ✋️ 🕐❔ 👆 🗄 `Query`, `Path`, `Depends`, `Security` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
-
-## ⚙️ `SecurityScopes`
-
-🔜 ℹ 🔗 `get_current_user`.
-
-👉 1️⃣ ⚙️ 🔗 🔛.
-
-📥 👥 ⚙️ 🎏 Oauth2️⃣ ⚖ 👥 ✍ ⏭, 📣 ⚫️ 🔗: `oauth2_scheme`.
-
-↩️ 👉 🔗 🔢 🚫 ✔️ 🙆 ↔ 📄 ⚫️, 👥 💪 ⚙️ `Depends` ⏮️ `oauth2_scheme`, 👥 🚫 ✔️ ⚙️ `Security` 🕐❔ 👥 🚫 💪 ✔ 💂♂ ↔.
-
-👥 📣 🎁 🔢 🆎 `SecurityScopes`, 🗄 ⚪️➡️ `fastapi.security`.
-
-👉 `SecurityScopes` 🎓 🎏 `Request` (`Request` ⚙️ 🤚 📨 🎚 🔗).
-
-```Python hl_lines="8 105"
-{!../../../docs_src/security/tutorial005.py!}
-```
-
-## ⚙️ `scopes`
-
-🔢 `security_scopes` 🔜 🆎 `SecurityScopes`.
-
-⚫️ 🔜 ✔️ 🏠 `scopes` ⏮️ 📇 ⚗ 🌐 ↔ ✔ ⚫️ & 🌐 🔗 👈 ⚙️ 👉 🎧-🔗. 👈 ⛓, 🌐 "⚓️"... 👉 💪 🔊 😨, ⚫️ 🔬 🔄 ⏪ 🔛.
-
-`security_scopes` 🎚 (🎓 `SecurityScopes`) 🚚 `scope_str` 🔢 ⏮️ 👁 🎻, 🔌 👈 ↔ 👽 🚀 (👥 🔜 ⚙️ ⚫️).
-
-👥 ✍ `HTTPException` 👈 👥 💪 🏤-⚙️ (`raise`) ⏪ 📚 ☝.
-
-👉 ⚠, 👥 🔌 ↔ 🚚 (🚥 🙆) 🎻 👽 🚀 (⚙️ `scope_str`). 👥 🚮 👈 🎻 ⚗ ↔ `WWW-Authenticate` 🎚 (👉 🍕 🔌).
-
-```Python hl_lines="105 107-115"
-{!../../../docs_src/security/tutorial005.py!}
-```
-
-## ✔ `username` & 💽 💠
-
-👥 ✔ 👈 👥 🤚 `username`, & ⚗ ↔.
-
-& ⤴️ 👥 ✔ 👈 📊 ⏮️ Pydantic 🏷 (✊ `ValidationError` ⚠), & 🚥 👥 🤚 ❌ 👂 🥙 🤝 ⚖️ ⚖ 📊 ⏮️ Pydantic, 👥 🤚 `HTTPException` 👥 ✍ ⏭.
-
-👈, 👥 ℹ Pydantic 🏷 `TokenData` ⏮️ 🆕 🏠 `scopes`.
-
-⚖ 📊 ⏮️ Pydantic 👥 💪 ⚒ 💭 👈 👥 ✔️, 🖼, ⚫️❔ `list` `str` ⏮️ ↔ & `str` ⏮️ `username`.
-
-↩️, 🖼, `dict`, ⚖️ 🕳 🙆, ⚫️ 💪 💔 🈸 ☝ ⏪, ⚒ ⚫️ 💂♂ ⚠.
-
-👥 ✔ 👈 👥 ✔️ 👩💻 ⏮️ 👈 🆔, & 🚥 🚫, 👥 🤚 👈 🎏 ⚠ 👥 ✍ ⏭.
-
-```Python hl_lines="46 116-127"
-{!../../../docs_src/security/tutorial005.py!}
-```
-
-## ✔ `scopes`
-
-👥 🔜 ✔ 👈 🌐 ↔ ✔, 👉 🔗 & 🌐 ⚓️ (🔌 *➡ 🛠️*), 🔌 ↔ 🚚 🤝 📨, ⏪ 🤚 `HTTPException`.
-
-👉, 👥 ⚙️ `security_scopes.scopes`, 👈 🔌 `list` ⏮️ 🌐 👫 ↔ `str`.
-
-```Python hl_lines="128-134"
-{!../../../docs_src/security/tutorial005.py!}
-```
-
-## 🔗 🌲 & ↔
-
-➡️ 📄 🔄 👉 🔗 🌲 & ↔.
-
-`get_current_active_user` 🔗 ✔️ 🎧-🔗 🔛 `get_current_user`, ↔ `"me"` 📣 `get_current_active_user` 🔜 🔌 📇 ✔ ↔ `security_scopes.scopes` 🚶♀️ `get_current_user`.
-
-*➡ 🛠️* ⚫️ 📣 ↔, `"items"`, 👉 🔜 📇 `security_scopes.scopes` 🚶♀️ `get_current_user`.
-
-📥 ❔ 🔗 🔗 & ↔ 👀 💖:
-
-* *➡ 🛠️* `read_own_items` ✔️:
- * ✔ ↔ `["items"]` ⏮️ 🔗:
- * `get_current_active_user`:
- * 🔗 🔢 `get_current_active_user` ✔️:
- * ✔ ↔ `["me"]` ⏮️ 🔗:
- * `get_current_user`:
- * 🔗 🔢 `get_current_user` ✔️:
- * 🙅♂ ↔ ✔ ⚫️.
- * 🔗 ⚙️ `oauth2_scheme`.
- * `security_scopes` 🔢 🆎 `SecurityScopes`:
- * 👉 `security_scopes` 🔢 ✔️ 🏠 `scopes` ⏮️ `list` ⚗ 🌐 👫 ↔ 📣 🔛,:
- * `security_scopes.scopes` 🔜 🔌 `["me", "items"]` *➡ 🛠️* `read_own_items`.
- * `security_scopes.scopes` 🔜 🔌 `["me"]` *➡ 🛠️* `read_users_me`, ↩️ ⚫️ 📣 🔗 `get_current_active_user`.
- * `security_scopes.scopes` 🔜 🔌 `[]` (🕳) *➡ 🛠️* `read_system_status`, ↩️ ⚫️ 🚫 📣 🙆 `Security` ⏮️ `scopes`, & 🚮 🔗, `get_current_user`, 🚫 📣 🙆 `scope` 👯♂️.
-
-!!! tip
- ⚠ & "🎱" 👜 📥 👈 `get_current_user` 🔜 ✔️ 🎏 📇 `scopes` ✅ 🔠 *➡ 🛠️*.
-
- 🌐 ⚓️ 🔛 `scopes` 📣 🔠 *➡ 🛠️* & 🔠 🔗 🔗 🌲 👈 🎯 *➡ 🛠️*.
-
-## 🌖 ℹ 🔃 `SecurityScopes`
-
-👆 💪 ⚙️ `SecurityScopes` 🙆 ☝, & 💗 🥉, ⚫️ 🚫 ✔️ "🌱" 🔗.
-
-⚫️ 🔜 🕧 ✔️ 💂♂ ↔ 📣 ⏮️ `Security` 🔗 & 🌐 ⚓️ **👈 🎯** *➡ 🛠️* & **👈 🎯** 🔗 🌲.
-
-↩️ `SecurityScopes` 🔜 ✔️ 🌐 ↔ 📣 ⚓️, 👆 💪 ⚙️ ⚫️ ✔ 👈 🤝 ✔️ 🚚 ↔ 🇨🇫 🔗 🔢, & ⤴️ 📣 🎏 ↔ 📄 🎏 *➡ 🛠️*.
-
-👫 🔜 ✅ ➡ 🔠 *➡ 🛠️*.
-
-## ✅ ⚫️
-
-🚥 👆 📂 🛠️ 🩺, 👆 💪 🔓 & ✔ ❔ ↔ 👆 💚 ✔.
-
-
-
-🚥 👆 🚫 🖊 🙆 ↔, 👆 🔜 "🔓", ✋️ 🕐❔ 👆 🔄 🔐 `/users/me/` ⚖️ `/users/me/items/` 👆 🔜 🤚 ❌ 💬 👈 👆 🚫 ✔️ 🥃 ✔. 👆 🔜 💪 🔐 `/status/`.
-
-& 🚥 👆 🖊 ↔ `me` ✋️ 🚫 ↔ `items`, 👆 🔜 💪 🔐 `/users/me/` ✋️ 🚫 `/users/me/items/`.
-
-👈 ⚫️❔ 🔜 🔨 🥉 🥳 🈸 👈 🔄 🔐 1️⃣ 👫 *➡ 🛠️* ⏮️ 🤝 🚚 👩💻, ⚓️ 🔛 ❔ 📚 ✔ 👩💻 🤝 🈸.
-
-## 🔃 🥉 🥳 🛠️
-
-👉 🖼 👥 ⚙️ Oauth2️⃣ "🔐" 💧.
-
-👉 ☑ 🕐❔ 👥 🚨 👆 👍 🈸, 🎲 ⏮️ 👆 👍 🕸.
-
-↩️ 👥 💪 💙 ⚫️ 📨 `username` & `password`, 👥 🎛 ⚫️.
-
-✋️ 🚥 👆 🏗 Oauth2️⃣ 🈸 👈 🎏 🔜 🔗 (➡, 🚥 👆 🏗 🤝 🐕🦺 🌓 👱📔, 🇺🇸🔍, 📂, ♒️.) 👆 🔜 ⚙️ 1️⃣ 🎏 💧.
-
-🌅 ⚠ 🔑 💧.
-
-🏆 🔐 📟 💧, ✋️ 🌖 🏗 🛠️ ⚫️ 🚚 🌅 📶. ⚫️ 🌅 🏗, 📚 🐕🦺 🔚 🆙 ✔ 🔑 💧.
-
-!!! note
- ⚫️ ⚠ 👈 🔠 🤝 🐕🦺 📛 👫 💧 🎏 🌌, ⚒ ⚫️ 🍕 👫 🏷.
-
- ✋️ 🔚, 👫 🛠️ 🎏 Oauth2️⃣ 🐩.
-
-**FastAPI** 🔌 🚙 🌐 👫 Oauth2️⃣ 🤝 💧 `fastapi.security.oauth2`.
-
-## `Security` 👨🎨 `dependencies`
-
-🎏 🌌 👆 💪 🔬 `list` `Depends` 👨🎨 `dependencies` 🔢 (🔬 [🔗 ➡ 🛠️ 👨🎨](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), 👆 💪 ⚙️ `Security` ⏮️ `scopes` 📤.
diff --git a/docs/em/docs/advanced/settings.md b/docs/em/docs/advanced/settings.md
deleted file mode 100644
index bc50bf755ae43..0000000000000
--- a/docs/em/docs/advanced/settings.md
+++ /dev/null
@@ -1,382 +0,0 @@
-# ⚒ & 🌐 🔢
-
-📚 💼 👆 🈸 💪 💪 🔢 ⚒ ⚖️ 📳, 🖼 ㊙ 🔑, 💽 🎓, 🎓 📧 🐕🦺, ♒️.
-
-🏆 👫 ⚒ 🔢 (💪 🔀), 💖 💽 📛. & 📚 💪 🚿, 💖 ㊙.
-
-👉 🤔 ⚫️ ⚠ 🚚 👫 🌐 🔢 👈 ✍ 🈸.
-
-## 🌐 🔢
-
-!!! tip
- 🚥 👆 ⏪ 💭 ⚫️❔ "🌐 🔢" & ❔ ⚙️ 👫, 💭 🆓 🚶 ⏭ 📄 🔛.
-
-🌐 🔢 (💭 "🇨🇻 {") 🔢 👈 🖖 🏞 🐍 📟, 🏃♂ ⚙️, & 💪 ✍ 👆 🐍 📟 (⚖️ 🎏 📋 👍).
-
-👆 💪 ✍ & ⚙️ 🌐 🔢 🐚, 🍵 💆♂ 🐍:
-
-=== "💾, 🇸🇻, 🚪 🎉"
-
-
-
-& ⤴️, 📂 🩺 🎧-🈸, http://127.0.0.1:8000/subapi/docs.
-
-👆 🔜 👀 🏧 🛠️ 🩺 🎧-🈸, ✅ 🕴 🚮 👍 _➡ 🛠️_, 🌐 🔽 ☑ 🎧-➡ 🔡 `/subapi`:
-
-
-
-🚥 👆 🔄 🔗 ⏮️ 🙆 2️⃣ 👩💻 🔢, 👫 🔜 👷 ☑, ↩️ 🖥 🔜 💪 💬 🔠 🎯 📱 ⚖️ 🎧-📱.
-
-### 📡 ℹ: `root_path`
-
-🕐❔ 👆 🗻 🎧-🈸 🔬 🔛, FastAPI 🔜 ✊ 💅 🔗 🗻 ➡ 🎧-🈸 ⚙️ 🛠️ ⚪️➡️ 🔫 🔧 🤙 `root_path`.
-
-👈 🌌, 🎧-🈸 🔜 💭 ⚙️ 👈 ➡ 🔡 🩺 🎚.
-
-& 🎧-🈸 💪 ✔️ 🚮 👍 📌 🎧-🈸 & 🌐 🔜 👷 ☑, ↩️ FastAPI 🍵 🌐 👉 `root_path`Ⓜ 🔁.
-
-👆 🔜 💡 🌅 🔃 `root_path` & ❔ ⚙️ ⚫️ 🎯 📄 🔃 [⛅ 🗳](./behind-a-proxy.md){.internal-link target=_blank}.
diff --git a/docs/em/docs/advanced/templates.md b/docs/em/docs/advanced/templates.md
deleted file mode 100644
index 1fb57725af175..0000000000000
--- a/docs/em/docs/advanced/templates.md
+++ /dev/null
@@ -1,77 +0,0 @@
-# 📄
-
-👆 💪 ⚙️ 🙆 📄 🚒 👆 💚 ⏮️ **FastAPI**.
-
-⚠ ⚒ Jinja2️⃣, 🎏 1️⃣ ⚙️ 🏺 & 🎏 🧰.
-
-📤 🚙 🔗 ⚫️ 💪 👈 👆 💪 ⚙️ 🔗 👆 **FastAPI** 🈸 (🚚 💃).
-
-## ❎ 🔗
-
-❎ `jinja2`:
-
-
-
-👆 💪 🆎 📧 🔢 📦, & 📨 👫:
-
-
-
-& 👆 **FastAPI** 🈸 ⏮️ *️⃣ 🔜 📨 🔙:
-
-
-
-👆 💪 📨 (& 📨) 📚 📧:
-
-
-
-& 🌐 👫 🔜 ⚙️ 🎏 *️⃣ 🔗.
-
-## ⚙️ `Depends` & 🎏
-
-*️⃣ 🔗 👆 💪 🗄 ⚪️➡️ `fastapi` & ⚙️:
-
-* `Depends`
-* `Security`
-* `Cookie`
-* `Header`
-* `Path`
-* `Query`
-
-👫 👷 🎏 🌌 🎏 FastAPI 🔗/*➡ 🛠️*:
-
-```Python hl_lines="66-77 76-91"
-{!../../../docs_src/websockets/tutorial002.py!}
-```
-
-!!! info
- 👉 *️⃣ ⚫️ 🚫 🤙 ⚒ 🔑 🤚 `HTTPException`, ↩️ 👥 🤚 `WebSocketException`.
-
- 👆 💪 ⚙️ 📪 📟 ⚪️➡️ ☑ 📟 🔬 🔧.
-
-### 🔄 *️⃣ ⏮️ 🔗
-
-🚥 👆 📁 📛 `main.py`, 🏃 👆 🈸 ⏮️:
-
-
-
-## 🚚 🔀 & 💗 👩💻
-
-🕐❔ *️⃣ 🔗 📪, `await websocket.receive_text()` 🔜 🤚 `WebSocketDisconnect` ⚠, ❔ 👆 💪 ⤴️ ✊ & 🍵 💖 👉 🖼.
-
-```Python hl_lines="81-83"
-{!../../../docs_src/websockets/tutorial003.py!}
-```
-
-🔄 ⚫️ 👅:
-
-* 📂 📱 ⏮️ 📚 🖥 📑.
-* ✍ 📧 ⚪️➡️ 👫.
-* ⤴️ 🔐 1️⃣ 📑.
-
-👈 🔜 🤚 `WebSocketDisconnect` ⚠, & 🌐 🎏 👩💻 🔜 📨 📧 💖:
-
-```
-Client #1596980209979 left the chat
-```
-
-!!! tip
- 📱 🔛 ⭐ & 🙅 🖼 🎦 ❔ 🍵 & 📻 📧 📚 *️⃣ 🔗.
-
- ✋️ ✔️ 🤯 👈, 🌐 🍵 💾, 👁 📇, ⚫️ 🔜 🕴 👷 ⏪ 🛠️ 🏃, & 🔜 🕴 👷 ⏮️ 👁 🛠️.
-
- 🚥 👆 💪 🕳 ⏩ 🛠️ ⏮️ FastAPI ✋️ 👈 🌖 🏋️, 🐕🦺 ✳, ✳ ⚖️ 🎏, ✅ 🗜/📻.
-
-## 🌅 ℹ
-
-💡 🌅 🔃 🎛, ✅ 💃 🧾:
-
-* `WebSocket` 🎓.
-* 🎓-⚓️ *️⃣ 🚚.
diff --git a/docs/em/docs/advanced/wsgi.md b/docs/em/docs/advanced/wsgi.md
deleted file mode 100644
index 4d051807fbeac..0000000000000
--- a/docs/em/docs/advanced/wsgi.md
+++ /dev/null
@@ -1,37 +0,0 @@
-# ✅ 🇨🇻 - 🏺, ✳, 🎏
-
-👆 💪 🗻 🇨🇻 🈸 👆 👀 ⏮️ [🎧 🈸 - 🗻](./sub-applications.md){.internal-link target=_blank}, [⛅ 🗳](./behind-a-proxy.md){.internal-link target=_blank}.
-
-👈, 👆 💪 ⚙️ `WSGIMiddleware` & ⚙️ ⚫️ 🎁 👆 🇨🇻 🈸, 🖼, 🏺, ✳, ♒️.
-
-## ⚙️ `WSGIMiddleware`
-
-👆 💪 🗄 `WSGIMiddleware`.
-
-⤴️ 🎁 🇨🇻 (✅ 🏺) 📱 ⏮️ 🛠️.
-
-& ⤴️ 🗻 👈 🔽 ➡.
-
-```Python hl_lines="2-3 22"
-{!../../../docs_src/wsgi/tutorial001.py!}
-```
-
-## ✅ ⚫️
-
-🔜, 🔠 📨 🔽 ➡ `/v1/` 🔜 🍵 🏺 🈸.
-
-& 🎂 🔜 🍵 **FastAPI**.
-
-🚥 👆 🏃 ⚫️ ⏮️ Uvicorn & 🚶 http://localhost:8000/v1/ 👆 🔜 👀 📨 ⚪️➡️ 🏺:
-
-```txt
-Hello, World from Flask!
-```
-
-& 🚥 👆 🚶 http://localhost:8000/v2 👆 🔜 👀 📨 ⚪️➡️ FastAPI:
-
-```JSON
-{
- "message": "Hello World"
-}
-```
diff --git a/docs/em/docs/alternatives.md b/docs/em/docs/alternatives.md
deleted file mode 100644
index 6169aa52d7128..0000000000000
--- a/docs/em/docs/alternatives.md
+++ /dev/null
@@ -1,414 +0,0 @@
-# 🎛, 🌈 & 🔺
-
-⚫️❔ 😮 **FastAPI**, ❔ ⚫️ 🔬 🎏 🎛 & ⚫️❔ ⚫️ 🇭🇲 ⚪️➡️ 👫.
-
-## 🎶
-
-**FastAPI** 🚫🔜 🔀 🚥 🚫 ⏮️ 👷 🎏.
-
-📤 ✔️ 📚 🧰 ✍ ⏭ 👈 ✔️ ℹ 😮 🚮 🏗.
-
-👤 ✔️ ❎ 🏗 🆕 🛠️ 📚 1️⃣2️⃣🗓️. 🥇 👤 🔄 ❎ 🌐 ⚒ 📔 **FastAPI** ⚙️ 📚 🎏 🛠️, 🔌-🔌, & 🧰.
-
-✋️ ☝, 📤 🙅♂ 🎏 🎛 🌘 🏗 🕳 👈 🚚 🌐 👫 ⚒, ✊ 🏆 💭 ⚪️➡️ ⏮️ 🧰, & 🌀 👫 🏆 🌌 💪, ⚙️ 🇪🇸 ⚒ 👈 ➖🚫 💪 ⏭ (🐍 3️⃣.6️⃣ ➕ 🆎 🔑).
-
-## ⏮️ 🧰
-
-### ✳
-
-⚫️ 🌅 🌟 🐍 🛠️ & 🛎 🕴. ⚫️ ⚙️ 🏗 ⚙️ 💖 👱📔.
-
-⚫️ 📶 😆 🔗 ⏮️ 🔗 💽 (💖 ✳ ⚖️ ✳),, ✔️ ☁ 💽 (💖 🗄, ✳, 👸, ♒️) 👑 🏪 🚒 🚫 📶 ⏩.
-
-⚫️ ✍ 🏗 🕸 👩💻, 🚫 ✍ 🔗 ⚙️ 🏛 🕸 (💖 😥, Vue.js & 📐) ⚖️ 🎏 ⚙️ (💖 ☁ 📳) 🔗 ⏮️ ⚫️.
-
-### ✳ 🎂 🛠️
-
-✳ 🎂 🛠️ ✍ 🗜 🧰 🏗 🕸 🔗 ⚙️ ✳ 🔘, 📉 🚮 🛠️ 🛠️.
-
-⚫️ ⚙️ 📚 🏢 ✅ 🦎, 🟥 👒 & 🎟.
-
-⚫️ 🕐 🥇 🖼 **🏧 🛠️ 🧾**, & 👉 🎯 🕐 🥇 💭 👈 😮 "🔎" **FastAPI**.
-
-!!! note
- ✳ 🎂 🛠️ ✍ ✡ 🇺🇸🏛. 🎏 👼 💃 & Uvicorn, 🔛 ❔ **FastAPI** ⚓️.
-
-
-!!! check "😮 **FastAPI** "
- ✔️ 🏧 🛠️ 🧾 🕸 👩💻 🔢.
-
-### 🏺
-
-🏺 "🕸", ⚫️ 🚫 🔌 💽 🛠️ 🚫 📚 👜 👈 👟 🔢 ✳.
-
-👉 🦁 & 💪 ✔ 🔨 👜 💖 ⚙️ ☁ 💽 👑 💽 💾 ⚙️.
-
-⚫️ 📶 🙅, ⚫️ 📶 🏋️ 💡, 👐 🧾 🤚 🙁 📡 ☝.
-
-⚫️ 🛎 ⚙️ 🎏 🈸 👈 🚫 🎯 💪 💽, 👩💻 🧾, ⚖️ 🙆 📚 ⚒ 👈 👟 🏤-🏗 ✳. 👐 📚 👫 ⚒ 💪 🚮 ⏮️ 🔌-🔌.
-
-👉 ⚖ 🍕, & ➖ "🕸" 👈 💪 ↔ 📔 ⚫️❔ ⚫️❔ 💪 🔑 ⚒ 👈 👤 💚 🚧.
-
-👐 🦁 🏺, ⚫️ 😑 💖 👍 🏏 🏗 🔗. ⏭ 👜 🔎 "✳ 🎂 🛠️" 🏺.
-
-!!! check "😮 **FastAPI** "
- ◾-🛠️. ⚒ ⚫️ ⏩ 🌀 & 🏏 🧰 & 🍕 💪.
-
- ✔️ 🙅 & ⏩ ⚙️ 🕹 ⚙️.
-
-
-### 📨
-
-**FastAPI** 🚫 🤙 🎛 **📨**. 👫 ↔ 📶 🎏.
-
-⚫️ 🔜 🤙 ⚠ ⚙️ 📨 *🔘* FastAPI 🈸.
-
-✋️, FastAPI 🤚 🌈 ⚪️➡️ 📨.
-
-**📨** 🗃 *🔗* ⏮️ 🔗 (👩💻), ⏪ **FastAPI** 🗃 *🏗* 🔗 (💽).
-
-👫, 🌖 ⚖️ 🌘, 🔄 🔚, 🔗 🔠 🎏.
-
-📨 ✔️ 📶 🙅 & 🏋️ 🔧, ⚫️ 📶 ⏩ ⚙️, ⏮️ 🤔 🔢. ✋️ 🎏 🕰, ⚫️ 📶 🏋️ & 🛃.
-
-👈 ⚫️❔, 💬 🛂 🕸:
-
-> 📨 1️⃣ 🏆 ⏬ 🐍 📦 🌐 🕰
-
-🌌 👆 ⚙️ ⚫️ 📶 🙅. 🖼, `GET` 📨, 👆 🔜 ✍:
-
-```Python
-response = requests.get("http://example.com/some/url")
-```
-
-FastAPI 😑 🛠️ *➡ 🛠️* 💪 👀 💖:
-
-```Python hl_lines="1"
-@app.get("/some/url")
-def read_url():
- return {"message": "Hello World"}
-```
-
-👀 🔀 `requests.get(...)` & `@app.get(...)`.
-
-!!! check "😮 **FastAPI** "
- * ✔️ 🙅 & 🏋️ 🛠️.
- * ⚙️ 🇺🇸🔍 👩🔬 📛 (🛠️) 🔗, 🎯 & 🏋️ 🌌.
- * ✔️ 🤔 🔢, ✋️ 🏋️ 🛃.
-
-
-### 🦁 / 🗄
-
-👑 ⚒ 👤 💚 ⚪️➡️ ✳ 🎂 🛠️ 🏧 🛠️ 🧾.
-
-⤴️ 👤 🔎 👈 📤 🐩 📄 🔗, ⚙️ 🎻 (⚖️ 📁, ↔ 🎻) 🤙 🦁.
-
-& 📤 🕸 👩💻 🔢 🦁 🛠️ ⏪ ✍. , 💆♂ 💪 🏗 🦁 🧾 🛠️ 🔜 ✔ ⚙️ 👉 🕸 👩💻 🔢 🔁.
-
-☝, 🦁 👐 💾 🏛, 📁 🗄.
-
-👈 ⚫️❔ 🕐❔ 💬 🔃 ⏬ 2️⃣.0️⃣ ⚫️ ⚠ 💬 "🦁", & ⏬ 3️⃣ ➕ "🗄".
-
-!!! check "😮 **FastAPI** "
- 🛠️ & ⚙️ 📂 🐩 🛠️ 🔧, ↩️ 🛃 🔗.
-
- & 🛠️ 🐩-⚓️ 👩💻 🔢 🧰:
-
- * 🦁 🎚
- * 📄
-
- 👫 2️⃣ 👐 ➖ 📶 🌟 & ⚖, ✋️ 🔨 ⏩ 🔎, 👆 💪 🔎 💯 🌖 🎛 👩💻 🔢 🗄 (👈 👆 💪 ⚙️ ⏮️ **FastAPI**).
-
-### 🏺 🎂 🛠️
-
-📤 📚 🏺 🎂 🛠️, ✋️ ⏮️ 💰 🕰 & 👷 🔘 🔬 👫, 👤 🔎 👈 📚 😞 ⚖️ 🚫, ⏮️ 📚 🧍 ❔ 👈 ⚒ 👫 🙃.
-
-### 🍭
-
-1️⃣ 👑 ⚒ 💪 🛠️ ⚙️ 📊 "🛠️" ❔ ✊ 📊 ⚪️➡️ 📟 (🐍) & 🏭 ⚫️ 🔘 🕳 👈 💪 📨 🔘 🕸. 🖼, 🏭 🎚 ⚗ 📊 ⚪️➡️ 💽 🔘 🎻 🎚. 🏭 `datetime` 🎚 🔘 🎻, ♒️.
-
-➕1️⃣ 🦏 ⚒ 💚 🔗 💽 🔬, ⚒ 💭 👈 💽 ☑, 🤝 🎯 🔢. 🖼, 👈 🏑 `int`, & 🚫 🎲 🎻. 👉 ✴️ ⚠ 📨 💽.
-
-🍵 💽 🔬 ⚙️, 👆 🔜 ✔️ 🌐 ✅ ✋, 📟.
-
-👫 ⚒ ⚫️❔ 🍭 🏗 🚚. ⚫️ 👑 🗃, & 👤 ✔️ ⚙️ ⚫️ 📚 ⏭.
-
-✋️ ⚫️ ✍ ⏭ 📤 🔀 🐍 🆎 🔑. , 🔬 🔠 🔗 👆 💪 ⚙️ 🎯 🇨🇻 & 🎓 🚚 🍭.
-
-!!! check "😮 **FastAPI** "
- ⚙️ 📟 🔬 "🔗" 👈 🚚 💽 🆎 & 🔬, 🔁.
-
-### Webarg
-
-➕1️⃣ 🦏 ⚒ ✔ 🔗 ✍ 📊 ⚪️➡️ 📨 📨.
-
-Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺.
-
-⚫️ ⚙️ 🍭 🔘 💽 🔬. & ⚫️ ✍ 🎏 👩💻.
-
-⚫️ 👑 🧰 & 👤 ✔️ ⚙️ ⚫️ 📚 💁♂️, ⏭ ✔️ **FastAPI**.
-
-!!! info
- Webarg ✍ 🎏 🍭 👩💻.
-
-!!! check "😮 **FastAPI** "
- ✔️ 🏧 🔬 📨 📨 💽.
-
-### APISpec
-
-🍭 & Webarg 🚚 🔬, ✍ & 🛠️ 🔌-🔌.
-
-✋️ 🧾 ❌. ⤴️ APISpec ✍.
-
-⚫️ 🔌-📚 🛠️ (& 📤 🔌-💃 💁♂️).
-
-🌌 ⚫️ 👷 👈 👆 ✍ 🔑 🔗 ⚙️ 📁 📁 🔘 #️⃣ 🔠 🔢 🚚 🛣.
-
-& ⚫️ 🏗 🗄 🔗.
-
-👈 ❔ ⚫️ 👷 🏺, 💃, 🆘, ♒️.
-
-✋️ ⤴️, 👥 ✔️ 🔄 ⚠ ✔️ ◾-❕, 🔘 🐍 🎻 (🦏 📁).
-
-👨🎨 💪 🚫 ℹ 🌅 ⏮️ 👈. & 🚥 👥 🔀 🔢 ⚖️ 🍭 🔗 & 💭 🔀 👈 📁#️⃣, 🏗 🔗 🔜 ❌.
-
-!!! info
- APISpec ✍ 🎏 🍭 👩💻.
-
-
-!!! check "😮 **FastAPI** "
- 🐕🦺 📂 🐩 🛠️, 🗄.
-
-### 🏺-Apispec
-
-⚫️ 🏺 🔌 -, 👈 👔 👯♂️ Webarg, 🍭 & APISpec.
-
-⚫️ ⚙️ ℹ ⚪️➡️ Webarg & 🍭 🔁 🏗 🗄 🔗, ⚙️ APISpec.
-
-⚫️ 👑 🧰, 📶 🔽-📈. ⚫️ 🔜 🌌 🌖 🌟 🌘 📚 🏺 🔌-🔌 👅 📤. ⚫️ 💪 ↩️ 🚮 🧾 ➖ 💁♂️ 🩲 & 📝.
-
-👉 ❎ ✔️ ✍ 📁 (➕1️⃣ ❕) 🔘 🐍 ✍.
-
-👉 🌀 🏺, 🏺-Apispec ⏮️ 🍭 & Webarg 👇 💕 👩💻 📚 ⏭ 🏗 **FastAPI**.
-
-⚙️ ⚫️ ↘️ 🏗 📚 🏺 🌕-📚 🚂. 👫 👑 📚 👤 (& 📚 🔢 🏉) ✔️ ⚙️ 🆙 🔜:
-
-* https://github.com/tiangolo/full-stack
-* https://github.com/tiangolo/full-stack-flask-couchbase
-* https://github.com/tiangolo/full-stack-flask-couchdb
-
-& 👫 🎏 🌕-📚 🚂 🧢 [**FastAPI** 🏗 🚂](project-generation.md){.internal-link target=_blank}.
-
-!!! info
- 🏺-Apispec ✍ 🎏 🍭 👩💻.
-
-!!! check "😮 **FastAPI** "
- 🏗 🗄 🔗 🔁, ⚪️➡️ 🎏 📟 👈 🔬 🛠️ & 🔬.
-
-### NestJS (& 📐)
-
-👉 ➖🚫 🚫 🐍, NestJS 🕸 (📕) ✳ 🛠️ 😮 📐.
-
-⚫️ 🏆 🕳 🙁 🎏 ⚫️❔ 💪 🔨 ⏮️ 🏺-Apispec.
-
-⚫️ ✔️ 🛠️ 🔗 💉 ⚙️, 😮 📐 2️⃣. ⚫️ 🚚 🏤-® "💉" (💖 🌐 🎏 🔗 💉 ⚙️ 👤 💭),, ⚫️ 🚮 🎭 & 📟 🔁.
-
-🔢 🔬 ⏮️ 📕 🆎 (🎏 🐍 🆎 🔑), 👨🎨 🐕🦺 👍.
-
-✋️ 📕 📊 🚫 🛡 ⏮️ 📹 🕸, ⚫️ 🚫🔜 ⚓️ 🔛 🆎 🔬 🔬, 🛠️ & 🧾 🎏 🕰. ↩️ 👉 & 🔧 🚫, 🤚 🔬, 🛠️ & 🏧 🔗 ⚡, ⚫️ 💪 🚮 👨🎨 📚 🥉. , ⚫️ ▶️️ 🔁.
-
-⚫️ 💪 🚫 🍵 🔁 🏷 📶 👍. , 🚥 🎻 💪 📨 🎻 🎚 👈 ✔️ 🔘 🏑 👈 🔄 🐦 🎻 🎚, ⚫️ 🚫🔜 ☑ 📄 & ✔.
-
-!!! check "😮 **FastAPI** "
- ⚙️ 🐍 🆎 ✔️ 👑 👨🎨 🐕🦺.
-
- ✔️ 🏋️ 🔗 💉 ⚙️. 🔎 🌌 📉 📟 🔁.
-
-### 🤣
-
-⚫️ 🕐 🥇 📶 ⏩ 🐍 🛠️ ⚓️ 🔛 `asyncio`. ⚫️ ⚒ 📶 🎏 🏺.
-
-!!! note "📡 ℹ"
- ⚫️ ⚙️ `uvloop` ↩️ 🔢 🐍 `asyncio` ➰. 👈 ⚫️❔ ⚒ ⚫️ ⏩.
-
- ⚫️ 🎯 😮 Uvicorn & 💃, 👈 ⏳ ⏩ 🌘 🤣 📂 📇.
-
-!!! check "😮 **FastAPI** "
- 🔎 🌌 ✔️ 😜 🎭.
-
- 👈 ⚫️❔ **FastAPI** ⚓️ 🔛 💃, ⚫️ ⏩ 🛠️ 💪 (💯 🥉-🥳 📇).
-
-### 🦅
-
-🦅 ➕1️⃣ ↕ 🎭 🐍 🛠️, ⚫️ 🔧 ⭐, & 👷 🏛 🎏 🛠️ 💖 🤗.
-
-⚫️ 🏗 ✔️ 🔢 👈 📨 2️⃣ 🔢, 1️⃣ "📨" & 1️⃣ "📨". ⤴️ 👆 "✍" 🍕 ⚪️➡️ 📨, & "✍" 🍕 📨. ↩️ 👉 🔧, ⚫️ 🚫 💪 📣 📨 🔢 & 💪 ⏮️ 🐩 🐍 🆎 🔑 🔢 🔢.
-
-, 💽 🔬, 🛠️, & 🧾, ✔️ ⌛ 📟, 🚫 🔁. ⚖️ 👫 ✔️ 🛠️ 🛠️ 🔛 🔝 🦅, 💖 🤗. 👉 🎏 🔺 🔨 🎏 🛠️ 👈 😮 🦅 🔧, ✔️ 1️⃣ 📨 🎚 & 1️⃣ 📨 🎚 🔢.
-
-!!! check "😮 **FastAPI** "
- 🔎 🌌 🤚 👑 🎭.
-
- ⤴️ ⏮️ 🤗 (🤗 ⚓️ 🔛 🦅) 😮 **FastAPI** 📣 `response` 🔢 🔢.
-
- 👐 FastAPI ⚫️ 📦, & ⚙️ ✴️ ⚒ 🎚, 🍪, & 🎛 👔 📟.
-
-### ♨
-
-👤 🔎 ♨ 🥇 ▶️ 🏗 **FastAPI**. & ⚫️ ✔️ 🎏 💭:
-
-* ⚓️ 🔛 🐍 🆎 🔑.
-* 🔬 & 🧾 ⚪️➡️ 👫 🆎.
-* 🔗 💉 ⚙️.
-
-⚫️ 🚫 ⚙️ 💽 🔬, 🛠️ & 🧾 🥉-🥳 🗃 💖 Pydantic, ⚫️ ✔️ 🚮 👍. , 👫 💽 🆎 🔑 🔜 🚫 ♻ 💪.
-
-⚫️ 🚚 🐥 🍖 🌅 🔁 📳. & ⚫️ ⚓️ 🔛 🇨🇻 (↩️ 🔫), ⚫️ 🚫 🔧 ✊ 📈 ↕-🎭 🚚 🧰 💖 Uvicorn, 💃 & 🤣.
-
-🔗 💉 ⚙️ 🚚 🏤-® 🔗 & 🔗 ❎ 🧢 🔛 📣 🆎. , ⚫️ 🚫 💪 📣 🌅 🌘 1️⃣ "🦲" 👈 🚚 🎯 🆎.
-
-🛣 📣 👁 🥉, ⚙️ 🔢 📣 🎏 🥉 (↩️ ⚙️ 👨🎨 👈 💪 🥉 ▶️️ 🔛 🔝 🔢 👈 🍵 🔗). 👉 🔐 ❔ ✳ 🔨 ⚫️ 🌘 ❔ 🏺 (& 💃) 🔨 ⚫️. ⚫️ 🎏 📟 👜 👈 📶 😆 🔗.
-
-!!! check "😮 **FastAPI** "
- 🔬 ➕ 🔬 💽 🆎 ⚙️ "🔢" 💲 🏷 🔢. 👉 📉 👨🎨 🐕🦺, & ⚫️ 🚫 💪 Pydantic ⏭.
-
- 👉 🤙 😮 🛠️ 🍕 Pydantic, 🐕🦺 🎏 🔬 📄 👗 (🌐 👉 🛠️ 🔜 ⏪ 💪 Pydantic).
-
-### 🤗
-
-🤗 🕐 🥇 🛠️ 🛠️ 📄 🛠️ 🔢 🆎 ⚙️ 🐍 🆎 🔑. 👉 👑 💭 👈 😮 🎏 🧰 🎏.
-
-⚫️ ⚙️ 🛃 🆎 🚮 📄 ↩️ 🐩 🐍 🆎, ✋️ ⚫️ 🦏 🔁 ⏩.
-
-⚫️ 🕐 🥇 🛠️ 🏗 🛃 🔗 📣 🎂 🛠️ 🎻.
-
-⚫️ 🚫 ⚓️ 🔛 🐩 💖 🗄 & 🎻 🔗. ⚫️ 🚫🔜 🎯 🛠️ ⚫️ ⏮️ 🎏 🧰, 💖 🦁 🎚. ✋️ 🔄, ⚫️ 📶 💡 💭.
-
-⚫️ ✔️ 😌, ⭐ ⚒: ⚙️ 🎏 🛠️, ⚫️ 💪 ✍ 🔗 & 🇳🇨.
-
-⚫️ ⚓️ 🔛 ⏮️ 🐩 🔁 🐍 🕸 🛠️ (🇨🇻), ⚫️ 💪 🚫 🍵 *️⃣ & 🎏 👜, 👐 ⚫️ ✔️ ↕ 🎭 💁♂️.
-
-!!! info
- 🤗 ✍ ✡ 🗄, 🎏 👼 `isort`, 👑 🧰 🔁 😇 🗄 🐍 📁.
-
-!!! check "💭 😮 **FastAPI**"
- 🤗 😮 🍕 APIStar, & 1️⃣ 🧰 👤 🔎 🏆 👍, 🌟 APIStar.
-
- 🤗 ℹ 😍 **FastAPI** ⚙️ 🐍 🆎 🔑 📣 🔢, & 🏗 🔗 ⚖ 🛠️ 🔁.
-
- 🤗 😮 **FastAPI** 📣 `response` 🔢 🔢 ⚒ 🎚 & 🍪.
-
-### APIStar (<= 0️⃣.5️⃣)
-
-▶️️ ⏭ 🤔 🏗 **FastAPI** 👤 🔎 **APIStar** 💽. ⚫️ ✔️ 🌖 🌐 👤 👀 & ✔️ 👑 🔧.
-
-⚫️ 🕐 🥇 🛠️ 🛠️ ⚙️ 🐍 🆎 🔑 📣 🔢 & 📨 👈 👤 ⏱ 👀 (⏭ NestJS & ♨). 👤 🔎 ⚫️ 🌅 ⚖️ 🌘 🎏 🕰 🤗. ✋️ APIStar ⚙️ 🗄 🐩.
-
-⚫️ ✔️ 🏧 💽 🔬, 💽 🛠️ & 🗄 🔗 ⚡ ⚓️ 🔛 🎏 🆎 🔑 📚 🥉.
-
-💪 🔗 🔑 🚫 ⚙️ 🎏 🐍 🆎 🔑 💖 Pydantic, ⚫️ 🍖 🌅 🎏 🍭,, 👨🎨 🐕🦺 🚫🔜 👍, ✋️, APIStar 🏆 💪 🎛.
-
-⚫️ ✔️ 🏆 🎭 📇 🕰 (🕴 💥 💃).
-
-🥇, ⚫️ 🚫 ✔️ 🏧 🛠️ 🧾 🕸 🎚, ✋️ 👤 💭 👤 💪 🚮 🦁 🎚 ⚫️.
-
-⚫️ ✔️ 🔗 💉 ⚙️. ⚫️ ✔ 🏤-® 🦲, 🎏 🧰 🔬 🔛. ✋️, ⚫️ 👑 ⚒.
-
-👤 🙅 💪 ⚙️ ⚫️ 🌕 🏗, ⚫️ 🚫 ✔️ 💂♂ 🛠️,, 👤 🚫 🚫 ❎ 🌐 ⚒ 👤 ✔️ ⏮️ 🌕-📚 🚂 ⚓️ 🔛 🏺-Apispec. 👤 ✔️ 👇 📈 🏗 ✍ 🚲 📨 ❎ 👈 🛠️.
-
-✋️ ⤴️, 🏗 🎯 🔀.
-
-⚫️ 🙅♂ 📏 🛠️ 🕸 🛠️, 👼 💪 🎯 🔛 💃.
-
-🔜 APIStar ⚒ 🧰 ✔ 🗄 🔧, 🚫 🕸 🛠️.
-
-!!! info
- APIStar ✍ ✡ 🇺🇸🏛. 🎏 👨 👈 ✍:
-
- * ✳ 🎂 🛠️
- * 💃 (❔ **FastAPI** ⚓️)
- * Uvicorn (⚙️ 💃 & **FastAPI**)
-
-!!! check "😮 **FastAPI** "
- 🔀.
-
- 💭 📣 💗 👜 (💽 🔬, 🛠️ & 🧾) ⏮️ 🎏 🐍 🆎, 👈 🎏 🕰 🚚 👑 👨🎨 🐕🦺, 🕳 👤 🤔 💎 💭.
-
- & ⏮️ 🔎 📏 🕰 🎏 🛠️ & 🔬 📚 🎏 🎛, APIStar 🏆 🎛 💪.
-
- ⤴️ APIStar ⛔️ 🔀 💽 & 💃 ✍, & 🆕 👻 🏛 ✅ ⚙️. 👈 🏁 🌈 🏗 **FastAPI**.
-
- 👤 🤔 **FastAPI** "🛐 👨💼" APIStar, ⏪ 📉 & 📈 ⚒, ⌨ ⚙️, & 🎏 🍕, ⚓️ 🔛 🏫 ⚪️➡️ 🌐 👉 ⏮️ 🧰.
-
-## ⚙️ **FastAPI**
-
-### Pydantic
-
-Pydantic 🗃 🔬 💽 🔬, 🛠️ & 🧾 (⚙️ 🎻 🔗) ⚓️ 🔛 🐍 🆎 🔑.
-
-👈 ⚒ ⚫️ 📶 🏋️.
-
-⚫️ ⭐ 🍭. 👐 ⚫️ ⏩ 🌘 🍭 📇. & ⚫️ ⚓️ 🔛 🎏 🐍 🆎 🔑, 👨🎨 🐕🦺 👑.
-
-!!! check "**FastAPI** ⚙️ ⚫️"
- 🍵 🌐 💽 🔬, 💽 🛠️ & 🏧 🏷 🧾 (⚓️ 🔛 🎻 🔗).
-
- **FastAPI** ⤴️ ✊ 👈 🎻 🔗 💽 & 🚮 ⚫️ 🗄, ↖️ ⚪️➡️ 🌐 🎏 👜 ⚫️ 🔨.
-
-### 💃
-
-💃 💿 🔫 🛠️/🧰, ❔ 💯 🏗 ↕-🎭 ✳ 🐕🦺.
-
-⚫️ 📶 🙅 & 🏋️. ⚫️ 🔧 💪 🏧, & ✔️ 🔧 🦲.
-
-⚫️ ✔️:
-
-* 🤙 🎆 🎭.
-* *️⃣ 🐕🦺.
-* -🛠️ 🖥 📋.
-* 🕴 & 🤫 🎉.
-* 💯 👩💻 🏗 🔛 🇸🇲.
-* ⚜, 🗜, 🎻 📁, 🎏 📨.
-* 🎉 & 🍪 🐕🦺.
-* 1️⃣0️⃣0️⃣ 💯 💯 💰.
-* 1️⃣0️⃣0️⃣ 💯 🆎 ✍ ✍.
-* 👩❤👨 🏋️ 🔗.
-
-💃 ⏳ ⏩ 🐍 🛠️ 💯. 🕴 💥 Uvicorn, ❔ 🚫 🛠️, ✋️ 💽.
-
-💃 🚚 🌐 🔰 🕸 🕸 🛠️.
-
-✋️ ⚫️ 🚫 🚚 🏧 💽 🔬, 🛠️ ⚖️ 🧾.
-
-👈 1️⃣ 👑 👜 👈 **FastAPI** 🚮 🔛 🔝, 🌐 ⚓️ 🔛 🐍 🆎 🔑 (⚙️ Pydantic). 👈, ➕ 🔗 💉 ⚙️, 💂♂ 🚙, 🗄 🔗 ⚡, ♒️.
-
-!!! note "📡 ℹ"
- 🔫 🆕 "🐩" ➖ 🛠️ ✳ 🐚 🏉 👨🎓. ⚫️ 🚫 "🐍 🐩" (🇩🇬), 👐 👫 🛠️ 🔨 👈.
-
- 👐, ⚫️ ⏪ ➖ ⚙️ "🐩" 📚 🧰. 👉 📉 📉 🛠️, 👆 💪 🎛 Uvicorn 🙆 🎏 🔫 💽 (💖 👸 ⚖️ Hypercorn), ⚖️ 👆 💪 🚮 🔫 🔗 🧰, 💖 `python-socketio`.
-
-!!! check "**FastAPI** ⚙️ ⚫️"
- 🍵 🌐 🐚 🕸 🍕. ❎ ⚒ 🔛 🔝.
-
- 🎓 `FastAPI` ⚫️ 😖 🔗 ⚪️➡️ 🎓 `Starlette`.
-
- , 🕳 👈 👆 💪 ⏮️ 💃, 👆 💪 ⚫️ 🔗 ⏮️ **FastAPI**, ⚫️ 🌖 💃 🔛 💊.
-
-### Uvicorn
-
-Uvicorn 🌩-⏩ 🔫 💽, 🏗 🔛 uvloop & httptool.
-
-⚫️ 🚫 🕸 🛠️, ✋️ 💽. 🖼, ⚫️ 🚫 🚚 🧰 🕹 ➡. 👈 🕳 👈 🛠️ 💖 💃 (⚖️ **FastAPI**) 🔜 🚚 🔛 🔝.
-
-⚫️ 👍 💽 💃 & **FastAPI**.
-
-!!! check "**FastAPI** 👍 ⚫️"
- 👑 🕸 💽 🏃 **FastAPI** 🈸.
-
- 👆 💪 🌀 ⚫️ ⏮️ 🐁, ✔️ 🔁 👁-🛠️ 💽.
-
- ✅ 🌅 ℹ [🛠️](deployment/index.md){.internal-link target=_blank} 📄.
-
-## 📇 & 🚅
-
-🤔, 🔬, & 👀 🔺 🖖 Uvicorn, 💃 & FastAPI, ✅ 📄 🔃 [📇](benchmarks.md){.internal-link target=_blank}.
diff --git a/docs/em/docs/async.md b/docs/em/docs/async.md
deleted file mode 100644
index 13b362b5de681..0000000000000
--- a/docs/em/docs/async.md
+++ /dev/null
@@ -1,430 +0,0 @@
-# 🛠️ & 🔁 / ⌛
-
-ℹ 🔃 `async def` ❕ *➡ 🛠️ 🔢* & 🖥 🔃 🔁 📟, 🛠️, & 🔁.
-
-## 🏃 ❓
-
-🆑;👩⚕️:
-
-🚥 👆 ⚙️ 🥉 🥳 🗃 👈 💬 👆 🤙 👫 ⏮️ `await`, 💖:
-
-```Python
-results = await some_library()
-```
-
-⤴️, 📣 👆 *➡ 🛠️ 🔢* ⏮️ `async def` 💖:
-
-```Python hl_lines="2"
-@app.get('/')
-async def read_results():
- results = await some_library()
- return results
-```
-
-!!! note
- 👆 💪 🕴 ⚙️ `await` 🔘 🔢 ✍ ⏮️ `async def`.
-
----
-
-🚥 👆 ⚙️ 🥉 🥳 🗃 👈 🔗 ⏮️ 🕳 (💽, 🛠️, 📁 ⚙️, ♒️.) & 🚫 ✔️ 🐕🦺 ⚙️ `await`, (👉 ⏳ 💼 🌅 💽 🗃), ⤴️ 📣 👆 *➡ 🛠️ 🔢* 🛎, ⏮️ `def`, 💖:
-
-```Python hl_lines="2"
-@app.get('/')
-def results():
- results = some_library()
- return results
-```
-
----
-
-🚥 👆 🈸 (😫) 🚫 ✔️ 🔗 ⏮️ 🕳 🙆 & ⌛ ⚫️ 📨, ⚙️ `async def`.
-
----
-
-🚥 👆 🚫 💭, ⚙️ 😐 `def`.
-
----
-
-**🗒**: 👆 💪 🌀 `def` & `async def` 👆 *➡ 🛠️ 🔢* 🌅 👆 💪 & 🔬 🔠 1️⃣ ⚙️ 🏆 🎛 👆. FastAPI 🔜 ▶️️ 👜 ⏮️ 👫.
-
-😆, 🙆 💼 🔛, FastAPI 🔜 👷 🔁 & 📶 ⏩.
-
-✋️ 📄 📶 🔛, ⚫️ 🔜 💪 🎭 🛠️.
-
-## 📡 ℹ
-
-🏛 ⏬ 🐍 ✔️ 🐕🦺 **"🔁 📟"** ⚙️ 🕳 🤙 **"🔁"**, ⏮️ **`async` & `await`** ❕.
-
-➡️ 👀 👈 🔤 🍕 📄 🔛:
-
-* **🔁 📟**
-* **`async` & `await`**
-* **🔁**
-
-## 🔁 📟
-
-🔁 📟 ⛓ 👈 🇪🇸 👶 ✔️ 🌌 💬 💻 / 📋 👶 👈 ☝ 📟, ⚫️ 👶 🔜 ✔️ ⌛ *🕳 🙆* 🏁 👱 🙆. ➡️ 💬 👈 *🕳 🙆* 🤙 "🐌-📁" 👶.
-
-, ⏮️ 👈 🕰, 💻 💪 🚶 & 🎏 👷, ⏪ "🐌-📁" 👶 🏁.
-
-⤴️ 💻 / 📋 👶 🔜 👟 🔙 🔠 🕰 ⚫️ ✔️ 🤞 ↩️ ⚫️ ⌛ 🔄, ⚖️ 🕐❔ ⚫️ 👶 🏁 🌐 👷 ⚫️ ✔️ 👈 ☝. & ⚫️ 👶 🔜 👀 🚥 🙆 📋 ⚫️ ⌛ ✔️ ⏪ 🏁, 🤸 ⚫️❔ ⚫️ ✔️.
-
-⏭, ⚫️ 👶 ✊ 🥇 📋 🏁 (➡️ 💬, 👆 "🐌-📁" 👶) & 😣 ⚫️❔ ⚫️ ✔️ ⏮️ ⚫️.
-
-👈 "⌛ 🕳 🙆" 🛎 🔗 👤/🅾 🛠️ 👈 📶 "🐌" (🔬 🚅 🕹 & 💾 💾), 💖 ⌛:
-
-* 📊 ⚪️➡️ 👩💻 📨 🔘 🕸
-* 📊 📨 👆 📋 📨 👩💻 🔘 🕸
-* 🎚 📁 💾 ✍ ⚙️ & 🤝 👆 📋
-* 🎚 👆 📋 🤝 ⚙️ ✍ 💾
-* 🛰 🛠️ 🛠️
-* 💽 🛠️ 🏁
-* 💽 🔢 📨 🏁
-* ♒️.
-
-🛠️ 🕰 🍴 ✴️ ⌛ 👤/🅾 🛠️, 👫 🤙 👫 "👤/🅾 🔗" 🛠️.
-
-⚫️ 🤙 "🔁" ↩️ 💻 / 📋 🚫 ✔️ "🔁" ⏮️ 🐌 📋, ⌛ ☑ 🙍 👈 📋 🏁, ⏪ 🔨 🕳, 💪 ✊ 📋 🏁 & 😣 👷.
-
-↩️ 👈, 💆♂ "🔁" ⚙️, 🕐 🏁, 📋 💪 ⌛ ⏸ 🐥 👄 (⏲) 💻 / 📋 🏁 ⚫️❔ ⚫️ 🚶, & ⤴️ 👟 🔙 ✊ 🏁 & 😣 👷 ⏮️ 👫.
-
-"🔁" (👽 "🔁") 👫 🛎 ⚙️ ⚖ "🔁", ↩️ 💻 / 📋 ⏩ 🌐 📶 🔁 ⏭ 🔀 🎏 📋, 🚥 👈 🔁 🔌 ⌛.
-
-### 🛠️ & 🍔
-
-👉 💭 **🔁** 📟 🔬 🔛 🕣 🤙 **"🛠️"**. ⚫️ 🎏 ⚪️➡️ **"🔁"**.
-
-**🛠️** & **🔁** 👯♂️ 🔗 "🎏 👜 😥 🌅 ⚖️ 🌘 🎏 🕰".
-
-✋️ ℹ 🖖 *🛠️* & *🔁* 🎏.
-
-👀 🔺, 🌈 📄 📖 🔃 🍔:
-
-### 🛠️ 🍔
-
-👆 🚶 ⏮️ 👆 🥰 🤚 ⏩ 🥕, 👆 🧍 ⏸ ⏪ 🏧 ✊ ✔ ⚪️➡️ 👫👫 🚪 👆. 👶
-
-
-
-⤴️ ⚫️ 👆 🔄, 👆 🥉 👆 ✔ 2️⃣ 📶 🎀 🍔 👆 🥰 & 👆. 👶 👶
-
-
-
-🏧 💬 🕳 🍳 👨🍳 👫 💭 👫 ✔️ 🏗 👆 🍔 (✋️ 👫 ⏳ 🏗 🕐 ⏮️ 👩💻).
-
-
-
-👆 💸. 👶
-
-🏧 🤝 👆 🔢 👆 🔄.
-
-
-
-⏪ 👆 ⌛, 👆 🚶 ⏮️ 👆 🥰 & ⚒ 🏓, 👆 🧎 & 💬 ⏮️ 👆 🥰 📏 🕰 (👆 🍔 📶 🎀 & ✊ 🕰 🏗).
-
-👆 🏖 🏓 ⏮️ 👆 🥰, ⏪ 👆 ⌛ 🍔, 👆 💪 💸 👈 🕰 😮 ❔ 👌, 🐨 & 🙃 👆 🥰 👶 👶 👶.
-
-
-
-⏪ ⌛ & 💬 👆 🥰, ⚪️➡️ 🕰 🕰, 👆 ✅ 🔢 🖥 🔛 ⏲ 👀 🚥 ⚫️ 👆 🔄 ⏪.
-
-⤴️ ☝, ⚫️ 😒 👆 🔄. 👆 🚶 ⏲, 🤚 👆 🍔 & 👟 🔙 🏓.
-
-
-
-👆 & 👆 🥰 🍴 🍔 & ✔️ 👌 🕰. 👶
-
-
-
-!!! info
- 🌹 🖼 👯 🍏. 👶
-
----
-
-🌈 👆 💻 / 📋 👶 👈 📖.
-
-⏪ 👆 ⏸, 👆 ⛽ 👶, ⌛ 👆 🔄, 🚫 🔨 🕳 📶 "😌". ✋️ ⏸ ⏩ ↩️ 🏧 🕴 ✊ ✔ (🚫 🏗 👫), 👈 👌.
-
-⤴️, 🕐❔ ⚫️ 👆 🔄, 👆 ☑ "😌" 👷, 👆 🛠️ 🍣, 💭 ⚫️❔ 👆 💚, 🤚 👆 🥰 ⚒, 💸, ✅ 👈 👆 🤝 ☑ 💵 ⚖️ 💳, ✅ 👈 👆 🈚 ☑, ✅ 👈 ✔ ✔️ ☑ 🏬, ♒️.
-
-✋️ ⤴️, ✋️ 👆 🚫 ✔️ 👆 🍔, 👆 👷 ⏮️ 🏧 "🔛 ⏸" ⏸, ↩️ 👆 ✔️ ⌛ 👶 👆 🍔 🔜.
-
-✋️ 👆 🚶 ↖️ ⚪️➡️ ⏲ & 🧎 🏓 ⏮️ 🔢 👆 🔄, 👆 💪 🎛 👶 👆 🙋 👆 🥰, & "👷" 👶 👶 🔛 👈. ⤴️ 👆 🔄 🔨 🕳 📶 "😌" 😏 ⏮️ 👆 🥰 👶.
-
-⤴️ 🏧 👶 💬 "👤 🏁 ⏮️ 🔨 🍔" 🚮 👆 🔢 🔛 ⏲ 🖥, ✋️ 👆 🚫 🦘 💖 😜 ⏪ 🕐❔ 🖥 🔢 🔀 👆 🔄 🔢. 👆 💭 🙅♂ 1️⃣ 🔜 📎 👆 🍔 ↩️ 👆 ✔️ 🔢 👆 🔄, & 👫 ✔️ 👫.
-
-👆 ⌛ 👆 🥰 🏁 📖 (🏁 ⏮️ 👷 👶 / 📋 ➖ 🛠️ 👶), 😀 🖐 & 💬 👈 👆 🔜 🍔 ⏸.
-
-⤴️ 👆 🚶 ⏲ 👶, ▶️ 📋 👈 🔜 🏁 👶, ⚒ 🍔, 💬 👏 & ✊ 👫 🏓. 👈 🏁 👈 🔁 / 📋 🔗 ⏮️ ⏲ ⏹. 👈 🔄, ✍ 🆕 📋, "🍴 🍔" 👶 👶, ✋️ ⏮️ 1️⃣ "🤚 🍔" 🏁 ⏹.
-
-### 🔗 🍔
-
-🔜 ➡️ 🌈 👫 ➖🚫 🚫 "🛠️ 🍔", ✋️ "🔗 🍔".
-
-👆 🚶 ⏮️ 👆 🥰 🤚 🔗 ⏩ 🥕.
-
-👆 🧍 ⏸ ⏪ 📚 (➡️ 💬 8️⃣) 🏧 👈 🎏 🕰 🍳 ✊ ✔ ⚪️➡️ 👫👫 🚪 👆.
-
-👱 ⏭ 👆 ⌛ 👫 🍔 🔜 ⏭ 🍂 ⏲ ↩️ 🔠 8️⃣ 🏧 🚶 & 🏗 🍔 ▶️️ ↖️ ⏭ 💆♂ ⏭ ✔.
-
-
-
-⤴️ ⚫️ 😒 👆 🔄, 👆 🥉 👆 ✔ 2️⃣ 📶 🎀 🍔 👆 🥰 & 👆.
-
-👆 💸 👶.
-
-
-
-🏧 🚶 👨🍳.
-
-👆 ⌛, 🧍 🚪 ⏲ 👶, 👈 🙅♂ 1️⃣ 🙆 ✊ 👆 🍔 ⏭ 👆, 📤 🙅♂ 🔢 🔄.
-
-
-
-👆 & 👆 🥰 😩 🚫 ➡️ 🙆 🤚 🚪 👆 & ✊ 👆 🍔 🕐❔ 👫 🛬, 👆 🚫🔜 💸 🙋 👆 🥰. 👶
-
-👉 "🔁" 👷, 👆 "🔁" ⏮️ 🏧/🍳 👶 👶. 👆 ✔️ ⌛ 👶 & 📤 ☑ 🙍 👈 🏧/🍳 👶 👶 🏁 🍔 & 🤝 👫 👆, ⚖️ ⏪, 👱 🙆 💪 ✊ 👫.
-
-
-
-⤴️ 👆 🏧/🍳 👶 👶 😒 👟 🔙 ⏮️ 👆 🍔, ⏮️ 📏 🕰 ⌛ 👶 📤 🚪 ⏲.
-
-
-
-👆 ✊ 👆 🍔 & 🚶 🏓 ⏮️ 👆 🥰.
-
-👆 🍴 👫, & 👆 🔨. ⏹
-
-
-
-📤 🚫 🌅 💬 ⚖️ 😏 🌅 🕰 💸 ⌛ 👶 🚪 ⏲. 👶
-
-!!! info
- 🌹 🖼 👯 🍏. 👶
-
----
-
-👉 😐 🔗 🍔, 👆 💻 / 📋 👶 ⏮️ 2️⃣ 🕹 (👆 & 👆 🥰), 👯♂️ ⌛ 👶 & 💡 👫 🙋 👶 "⌛ 🔛 ⏲" 👶 📏 🕰.
-
-⏩ 🥕 🏪 ✔️ 8️⃣ 🕹 (🏧/🍳). ⏪ 🛠️ 🍔 🏪 💪 ✔️ ✔️ 🕴 2️⃣ (1️⃣ 🏧 & 1️⃣ 🍳).
-
-✋️, 🏁 💡 🚫 🏆. 👶
-
----
-
-👉 🔜 🔗 🌓 📖 🍔. 👶
-
-🌅 "🎰 👨❤👨" 🖼 👉, 🌈 🏦.
-
-🆙 ⏳, 🏆 🏦 ✔️ 💗 🏧 👶 👶 👶 👶 👶 👶 👶 👶 & 🦏 ⏸ 👶 👶 👶 👶 👶 👶 👶 👶.
-
-🌐 🏧 🔨 🌐 👷 ⏮️ 1️⃣ 👩💻 ⏮️ 🎏 👶 👶 👶.
-
-& 👆 ✔️ ⌛ 👶 ⏸ 📏 🕰 ⚖️ 👆 💸 👆 🔄.
-
-👆 🎲 🚫🔜 💚 ✊ 👆 🥰 👶 ⏮️ 👆 👷 🏦 👶.
-
-### 🍔 🏁
-
-👉 😐 "⏩ 🥕 🍔 ⏮️ 👆 🥰", 📤 📚 ⌛ 👶, ⚫️ ⚒ 📚 🌅 🔑 ✔️ 🛠️ ⚙️ ⏸ 👶 👶.
-
-👉 💼 🌅 🕸 🈸.
-
-📚, 📚 👩💻, ✋️ 👆 💽 ⌛ 👶 👫 🚫--👍 🔗 📨 👫 📨.
-
-& ⤴️ ⌛ 👶 🔄 📨 👟 🔙.
-
-👉 "⌛" 👶 ⚖ ⏲, ✋️, ⚖ ⚫️ 🌐, ⚫️ 📚 ⌛ 🔚.
-
-👈 ⚫️❔ ⚫️ ⚒ 📚 🔑 ⚙️ 🔁 ⏸ 👶 👶 📟 🕸 🔗.
-
-👉 😇 🔀 ⚫️❔ ⚒ ✳ 🌟 (✋️ ✳ 🚫 🔗) & 👈 💪 🚶 🛠️ 🇪🇸.
-
-& 👈 🎏 🎚 🎭 👆 🤚 ⏮️ **FastAPI**.
-
-& 👆 💪 ✔️ 🔁 & 🔀 🎏 🕰, 👆 🤚 ↕ 🎭 🌘 🌅 💯 ✳ 🛠️ & 🔛 🇷🇪 ⏮️ 🚶, ❔ ✍ 🇪🇸 🔐 🅱 (🌐 👏 💃).
-
-### 🛠️ 👍 🌘 🔁 ❓
-
-😆 ❗ 👈 🚫 🛐 📖.
-
-🛠️ 🎏 🌘 🔁. & ⚫️ 👻 🔛 **🎯** 😐 👈 🔌 📚 ⌛. ↩️ 👈, ⚫️ 🛎 📚 👍 🌘 🔁 🕸 🈸 🛠️. ✋️ 🚫 🌐.
-
-, ⚖ 👈 👅, 🌈 📄 📏 📖:
-
-> 👆 ✔️ 🧹 🦏, 💩 🏠.
-
-*😆, 👈 🎂 📖*.
-
----
-
-📤 🙅♂ ⌛ 👶 🙆, 📚 👷 🔨, 🔛 💗 🥉 🏠.
-
-👆 💪 ✔️ 🔄 🍔 🖼, 🥇 🏠 🧖♂, ⤴️ 👨🍳, ✋️ 👆 🚫 ⌛ 👶 🕳, 🧹 & 🧹, 🔄 🚫🔜 📉 🕳.
-
-⚫️ 🔜 ✊ 🎏 💸 🕰 🏁 ⏮️ ⚖️ 🍵 🔄 (🛠️) & 👆 🔜 ✔️ ⌛ 🎏 💸 👷.
-
-✋️ 👉 💼, 🚥 👆 💪 ✊️ 8️⃣ 👰-🏧/🍳/🔜-🧹, & 🔠 1️⃣ 👫 (➕ 👆) 💪 ✊ 🏒 🏠 🧹 ⚫️, 👆 💪 🌐 👷 **🔗**, ⏮️ ➕ ℹ, & 🏁 🌅 🔜.
-
-👉 😐, 🔠 1️⃣ 🧹 (🔌 👆) 🔜 🕹, 🤸 👫 🍕 👨🏭.
-
-& 🏆 🛠️ 🕰 ✊ ☑ 👷 (↩️ ⌛), & 👷 💻 ⌛ 💽, 👫 🤙 👫 ⚠ "💽 🎁".
-
----
-
-⚠ 🖼 💽 🔗 🛠️ 👜 👈 🚚 🏗 🧪 🏭.
-
-🖼:
-
-* **🎧** ⚖️ **🖼 🏭**.
-* **💻 👓**: 🖼 ✍ 💯 🔅, 🔠 🔅 ✔️ 3️⃣ 💲 / 🎨, 🏭 👈 🛎 🚚 💻 🕳 🔛 📚 🔅, 🌐 🎏 🕰.
-* **🎰 🏫**: ⚫️ 🛎 🚚 📚 "✖" & "🖼" ✖. 💭 🦏 📋 ⏮️ 🔢 & ✖ 🌐 👫 👯♂️ 🎏 🕰.
-* **⏬ 🏫**: 👉 🎧-🏑 🎰 🏫,, 🎏 ✔. ⚫️ 👈 📤 🚫 👁 📋 🔢 ✖, ✋️ 🦏 ⚒ 👫, & 📚 💼, 👆 ⚙️ 🎁 🕹 🏗 & / ⚖️ ⚙️ 👈 🏷.
-
-### 🛠️ ➕ 🔁: 🕸 ➕ 🎰 🏫
-
-⏮️ **FastAPI** 👆 💪 ✊ 📈 🛠️ 👈 📶 ⚠ 🕸 🛠️ (🎏 👑 🧲 ✳).
-
-✋️ 👆 💪 🐄 💰 🔁 & 💾 (✔️ 💗 🛠️ 🏃♂ 🔗) **💽 🎁** ⚖ 💖 👈 🎰 🏫 ⚙️.
-
-👈, ➕ 🙅 👐 👈 🐍 👑 🇪🇸 **💽 🧪**, 🎰 🏫 & ✴️ ⏬ 🏫, ⚒ FastAPI 📶 👍 🏏 💽 🧪 / 🎰 🏫 🕸 🔗 & 🈸 (👪 📚 🎏).
-
-👀 ❔ 🏆 👉 🔁 🏭 👀 📄 🔃 [🛠️](deployment/index.md){.internal-link target=_blank}.
-
-## `async` & `await`
-
-🏛 ⏬ 🐍 ✔️ 📶 🏋️ 🌌 🔬 🔁 📟. 👉 ⚒ ⚫️ 👀 💖 😐 "🔁" 📟 & "⌛" 👆 ▶️️ 🙍.
-
-🕐❔ 📤 🛠️ 👈 🔜 🚚 ⌛ ⏭ 🤝 🏁 & ✔️ 🐕🦺 👉 🆕 🐍 ⚒, 👆 💪 📟 ⚫️ 💖:
-
-```Python
-burgers = await get_burgers(2)
-```
-
-🔑 📥 `await`. ⚫️ 💬 🐍 👈 ⚫️ ✔️ ⌛ ⏸ `get_burgers(2)` 🏁 🔨 🚮 👜 👶 ⏭ ♻ 🏁 `burgers`. ⏮️ 👈, 🐍 🔜 💭 👈 ⚫️ 💪 🚶 & 🕳 🙆 👶 👶 👐 (💖 📨 ➕1️⃣ 📨).
-
-`await` 👷, ⚫️ ✔️ 🔘 🔢 👈 🐕🦺 👉 🔀. 👈, 👆 📣 ⚫️ ⏮️ `async def`:
-
-```Python hl_lines="1"
-async def get_burgers(number: int):
- # Do some asynchronous stuff to create the burgers
- return burgers
-```
-
-...↩️ `def`:
-
-```Python hl_lines="2"
-# This is not asynchronous
-def get_sequential_burgers(number: int):
- # Do some sequential stuff to create the burgers
- return burgers
-```
-
-⏮️ `async def`, 🐍 💭 👈, 🔘 👈 🔢, ⚫️ ✔️ 🤔 `await` 🧬, & 👈 ⚫️ 💪 "⏸" ⏸ 🛠️ 👈 🔢 & 🚶 🕳 🙆 👶 ⏭ 👟 🔙.
-
-🕐❔ 👆 💚 🤙 `async def` 🔢, 👆 ✔️ "⌛" ⚫️. , 👉 🏆 🚫 👷:
-
-```Python
-# This won't work, because get_burgers was defined with: async def
-burgers = get_burgers(2)
-```
-
----
-
-, 🚥 👆 ⚙️ 🗃 👈 💬 👆 👈 👆 💪 🤙 ⚫️ ⏮️ `await`, 👆 💪 ✍ *➡ 🛠️ 🔢* 👈 ⚙️ ⚫️ ⏮️ `async def`, 💖:
-
-```Python hl_lines="2-3"
-@app.get('/burgers')
-async def read_burgers():
- burgers = await get_burgers(2)
- return burgers
-```
-
-### 🌅 📡 ℹ
-
-👆 💪 ✔️ 👀 👈 `await` 💪 🕴 ⚙️ 🔘 🔢 🔬 ⏮️ `async def`.
-
-✋️ 🎏 🕰, 🔢 🔬 ⏮️ `async def` ✔️ "⌛". , 🔢 ⏮️ `async def` 💪 🕴 🤙 🔘 🔢 🔬 ⏮️ `async def` 💁♂️.
-
-, 🔃 🥚 & 🐔, ❔ 👆 🤙 🥇 `async` 🔢 ❓
-
-🚥 👆 👷 ⏮️ **FastAPI** 👆 🚫 ✔️ 😟 🔃 👈, ↩️ 👈 "🥇" 🔢 🔜 👆 *➡ 🛠️ 🔢*, & FastAPI 🔜 💭 ❔ ▶️️ 👜.
-
-✋️ 🚥 👆 💚 ⚙️ `async` / `await` 🍵 FastAPI, 👆 💪 ⚫️ 👍.
-
-### ✍ 👆 👍 🔁 📟
-
-💃 (& **FastAPI**) ⚓️ 🔛 AnyIO, ❔ ⚒ ⚫️ 🔗 ⏮️ 👯♂️ 🐍 🐩 🗃 ✳ & 🎻.
-
-🎯, 👆 💪 🔗 ⚙️ AnyIO 👆 🏧 🛠️ ⚙️ 💼 👈 🚚 🌅 🏧 ⚓ 👆 👍 📟.
-
-& 🚥 👆 🚫 ⚙️ FastAPI, 👆 💪 ✍ 👆 👍 🔁 🈸 ⏮️ AnyIO 🏆 🔗 & 🤚 🚮 💰 (✅ *📊 🛠️*).
-
-### 🎏 📨 🔁 📟
-
-👉 👗 ⚙️ `async` & `await` 📶 🆕 🇪🇸.
-
-✋️ ⚫️ ⚒ 👷 ⏮️ 🔁 📟 📚 ⏩.
-
-👉 🎏 ❕ (⚖️ 🌖 🌓) 🔌 ⏳ 🏛 ⏬ 🕸 (🖥 & ✳).
-
-✋️ ⏭ 👈, 🚚 🔁 📟 🌖 🏗 & ⚠.
-
-⏮️ ⏬ 🐍, 👆 💪 ✔️ ⚙️ 🧵 ⚖️ 🐁. ✋️ 📟 🌌 🌖 🏗 🤔, ℹ, & 💭 🔃.
-
-⏮️ ⏬ ✳ / 🖥 🕸, 👆 🔜 ✔️ ⚙️ "⏲". ❔ ↘️ ⏲ 🔥😈.
-
-## 🔁
-
-**🔁** 📶 🎀 ⚖ 👜 📨 `async def` 🔢. 🐍 💭 👈 ⚫️ 🕳 💖 🔢 👈 ⚫️ 💪 ▶️ & 👈 ⚫️ 🔜 🔚 ☝, ✋️ 👈 ⚫️ 5️⃣📆 ⏸ ⏸ 🔘 💁♂️, 🕐❔ 📤 `await` 🔘 ⚫️.
-
-✋️ 🌐 👉 🛠️ ⚙️ 🔁 📟 ⏮️ `async` & `await` 📚 🕰 🔬 ⚙️ "🔁". ⚫️ ⭐ 👑 🔑 ⚒ 🚶, "🔁".
-
-## 🏁
-
-➡️ 👀 🎏 🔤 ⚪️➡️ 🔛:
-
-> 🏛 ⏬ 🐍 ✔️ 🐕🦺 **"🔁 📟"** ⚙️ 🕳 🤙 **"🔁"**, ⏮️ **`async` & `await`** ❕.
-
-👈 🔜 ⚒ 🌅 🔑 🔜. 👶
-
-🌐 👈 ⚫️❔ 🏋️ FastAPI (🔘 💃) & ⚫️❔ ⚒ ⚫️ ✔️ ✅ 🎆 🎭.
-
-## 📶 📡 ℹ
-
-!!! warning
- 👆 💪 🎲 🚶 👉.
-
- 👉 📶 📡 ℹ ❔ **FastAPI** 👷 🔘.
-
- 🚥 👆 ✔️ 📡 💡 (🈶-🏋, 🧵, 🍫, ♒️.) & 😟 🔃 ❔ FastAPI 🍵 `async def` 🆚 😐 `def`, 🚶 ⤴️.
-
-### ➡ 🛠️ 🔢
-
-🕐❔ 👆 📣 *➡ 🛠️ 🔢* ⏮️ 😐 `def` ↩️ `async def`, ⚫️ 🏃 🔢 🧵 👈 ⤴️ ⌛, ↩️ ➖ 🤙 🔗 (⚫️ 🔜 🍫 💽).
-
-🚥 👆 👟 ⚪️➡️ ➕1️⃣ 🔁 🛠️ 👈 🔨 🚫 👷 🌌 🔬 🔛 & 👆 ⚙️ ⚖ 🙃 📊-🕴 *➡ 🛠️ 🔢* ⏮️ ✅ `def` 🤪 🎭 📈 (🔃 1️⃣0️⃣0️⃣ 💓), 🙏 🗒 👈 **FastAPI** ⭐ 🔜 🔄. 👫 💼, ⚫️ 👻 ⚙️ `async def` 🚥 👆 *➡ 🛠️ 🔢* ⚙️ 📟 👈 🎭 🚧 👤/🅾.
-
-, 👯♂️ ⚠, 🤞 👈 **FastAPI** 🔜 [⏩](/#performance){.internal-link target=_blank} 🌘 (⚖️ 🌘 ⭐) 👆 ⏮️ 🛠️.
-
-### 🔗
-
-🎏 ✔ [🔗](/tutorial/dependencies/index.md){.internal-link target=_blank}. 🚥 🔗 🐩 `def` 🔢 ↩️ `async def`, ⚫️ 🏃 🔢 🧵.
-
-### 🎧-🔗
-
-👆 💪 ✔️ 💗 🔗 & [🎧-🔗](/tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} 🚫 🔠 🎏 (🔢 🔢 🔑), 👫 💪 ✍ ⏮️ `async def` & ⏮️ 😐 `def`. ⚫️ 🔜 👷, & 🕐 ✍ ⏮️ 😐 `def` 🔜 🤙 🔛 🔢 🧵 (⚪️➡️ 🧵) ↩️ ➖ "⌛".
-
-### 🎏 🚙 🔢
-
-🙆 🎏 🚙 🔢 👈 👆 🤙 🔗 💪 ✍ ⏮️ 😐 `def` ⚖️ `async def` & FastAPI 🏆 🚫 📉 🌌 👆 🤙 ⚫️.
-
-👉 🔅 🔢 👈 FastAPI 🤙 👆: *➡ 🛠️ 🔢* & 🔗.
-
-🚥 👆 🚙 🔢 😐 🔢 ⏮️ `def`, ⚫️ 🔜 🤙 🔗 (👆 ✍ ⚫️ 👆 📟), 🚫 🧵, 🚥 🔢 ✍ ⏮️ `async def` ⤴️ 👆 🔜 `await` 👈 🔢 🕐❔ 👆 🤙 ⚫️ 👆 📟.
-
----
-
-🔄, 👉 📶 📡 ℹ 👈 🔜 🎲 ⚠ 🚥 👆 👟 🔎 👫.
-
-⏪, 👆 🔜 👍 ⏮️ 📄 ⚪️➡️ 📄 🔛: 🏃 ❓.
diff --git a/docs/em/docs/benchmarks.md b/docs/em/docs/benchmarks.md
deleted file mode 100644
index 003c3f62de172..0000000000000
--- a/docs/em/docs/benchmarks.md
+++ /dev/null
@@ -1,34 +0,0 @@
-# 📇
-
-🔬 🇸🇲 📇 🎦 **FastAPI** 🈸 🏃♂ 🔽 Uvicorn 1️⃣ ⏩ 🐍 🛠️ 💪, 🕴 🔛 💃 & Uvicorn 👫 (⚙️ 🔘 FastAPI). (*)
-
-✋️ 🕐❔ ✅ 📇 & 🔺 👆 🔜 ✔️ 📄 🤯.
-
-## 📇 & 🚅
-
-🕐❔ 👆 ✅ 📇, ⚫️ ⚠ 👀 📚 🧰 🎏 🆎 🔬 🌓.
-
-🎯, 👀 Uvicorn, 💃 & FastAPI 🔬 👯♂️ (👪 📚 🎏 🧰).
-
-🙅 ⚠ ❎ 🧰, 👍 🎭 ⚫️ 🔜 🤚. & 🏆 📇 🚫 💯 🌖 ⚒ 🚚 🧰.
-
-🔗 💖:
-
-* **Uvicorn**: 🔫 💽
- * **💃**: (⚙️ Uvicorn) 🕸 🕸
- * **FastAPI**: (⚙️ 💃) 🛠️ 🕸 ⏮️ 📚 🌖 ⚒ 🏗 🔗, ⏮️ 💽 🔬, ♒️.
-
-* **Uvicorn**:
- * 🔜 ✔️ 🏆 🎭, ⚫️ 🚫 ✔️ 🌅 ➕ 📟 ↖️ ⚪️➡️ 💽 ⚫️.
- * 👆 🚫🔜 ✍ 🈸 Uvicorn 🔗. 👈 🔜 ⛓ 👈 👆 📟 🔜 ✔️ 🔌 🌖 ⚖️ 🌘, 🌘, 🌐 📟 🚚 💃 (⚖️ **FastAPI**). & 🚥 👆 👈, 👆 🏁 🈸 🔜 ✔️ 🎏 🌥 ✔️ ⚙️ 🛠️ & 📉 👆 📱 📟 & 🐛.
- * 🚥 👆 ⚖ Uvicorn, 🔬 ⚫️ 🛡 👸, Hypercorn, ✳, ♒️. 🈸 💽.
-* **💃**:
- * 🔜 ✔️ ⏭ 🏆 🎭, ⏮️ Uvicorn. 👐, 💃 ⚙️ Uvicorn 🏃. , ⚫️ 🎲 💪 🕴 🤚 "🐌" 🌘 Uvicorn ✔️ 🛠️ 🌅 📟.
- * ✋️ ⚫️ 🚚 👆 🧰 🏗 🙅 🕸 🈸, ⏮️ 🕹 ⚓️ 🔛 ➡, ♒️.
- * 🚥 👆 ⚖ 💃, 🔬 ⚫️ 🛡 🤣, 🏺, ✳, ♒️. 🕸 🛠️ (⚖️ 🕸).
-* **FastAPI**:
- * 🎏 🌌 👈 💃 ⚙️ Uvicorn & 🚫🔜 ⏩ 🌘 ⚫️, **FastAPI** ⚙️ 💃, ⚫️ 🚫🔜 ⏩ 🌘 ⚫️.
- * FastAPI 🚚 🌅 ⚒ 🔛 🔝 💃. ⚒ 👈 👆 🌖 🕧 💪 🕐❔ 🏗 🔗, 💖 💽 🔬 & 🛠️. & ⚙️ ⚫️, 👆 🤚 🏧 🧾 🆓 (🏧 🧾 🚫 🚮 🌥 🏃♂ 🈸, ⚫️ 🏗 🔛 🕴).
- * 🚥 👆 🚫 ⚙️ FastAPI & ⚙️ 💃 🔗 (⚖️ ➕1️⃣ 🧰, 💖 🤣, 🏺, 🆘, ♒️) 👆 🔜 ✔️ 🛠️ 🌐 💽 🔬 & 🛠️ 👆. , 👆 🏁 🈸 🔜 ✔️ 🎏 🌥 🚥 ⚫️ 🏗 ⚙️ FastAPI. & 📚 💼, 👉 💽 🔬 & 🛠️ 🦏 💸 📟 ✍ 🈸.
- * , ⚙️ FastAPI 👆 ♻ 🛠️ 🕰, 🐛, ⏸ 📟, & 👆 🔜 🎲 🤚 🎏 🎭 (⚖️ 👍) 👆 🔜 🚥 👆 🚫 ⚙️ ⚫️ (👆 🔜 ✔️ 🛠️ ⚫️ 🌐 👆 📟).
- * 🚥 👆 ⚖ FastAPI, 🔬 ⚫️ 🛡 🕸 🈸 🛠️ (⚖️ ⚒ 🧰) 👈 🚚 💽 🔬, 🛠️ & 🧾, 💖 🏺-apispec, NestJS, ♨, ♒️. 🛠️ ⏮️ 🛠️ 🏧 💽 🔬, 🛠️ & 🧾.
diff --git a/docs/em/docs/contributing.md b/docs/em/docs/contributing.md
deleted file mode 100644
index 748928f88fe38..0000000000000
--- a/docs/em/docs/contributing.md
+++ /dev/null
@@ -1,465 +0,0 @@
-# 🛠️ - 📉
-
-🥇, 👆 💪 💚 👀 🔰 🌌 [ℹ FastAPI & 🤚 ℹ](help-fastapi.md){.internal-link target=_blank}.
-
-## 🛠️
-
-🚥 👆 ⏪ 🖖 🗃 & 👆 💭 👈 👆 💪 ⏬ 🤿 📟, 📥 📄 ⚒ 🆙 👆 🌐.
-
-### 🕹 🌐 ⏮️ `venv`
-
-👆 💪 ✍ 🕹 🌐 📁 ⚙️ 🐍 `venv` 🕹:
-
-
-
----
-
-🔜 👈 👥 💭 🔺 🖖 ⚖ **🛠️** & **📋**, ➡️ 😣 💬 🔃 🛠️.
-
-## 🏃♂ 🔛 🕴
-
-🌅 💼, 🕐❔ 👆 ✍ 🕸 🛠️, 👆 💚 ⚫️ **🕧 🏃♂**, ➡, 👈 👆 👩💻 💪 🕧 🔐 ⚫️. 👉 ↗️, 🚥 👆 ✔️ 🎯 🤔 ⚫️❔ 👆 💚 ⚫️ 🏃 🕴 🎯 ⚠, ✋️ 🌅 🕰 👆 💚 ⚫️ 🕧 🏃♂ & **💪**.
-
-### 🛰 💽
-
-🕐❔ 👆 ⚒ 🆙 🛰 💽 (☁ 💽, 🕹 🎰, ♒️.) 🙅 👜 👆 💪 🏃 Uvicorn (⚖️ 🎏) ❎, 🎏 🌌 👆 🕐❔ 🛠️ 🌐.
-
-& ⚫️ 🔜 👷 & 🔜 ⚠ **⏮️ 🛠️**.
-
-✋️ 🚥 👆 🔗 💽 💸, **🏃♂ 🛠️** 🔜 🎲 ☠️.
-
-& 🚥 💽 ⏏ (🖼 ⏮️ ℹ, ⚖️ 🛠️ ⚪️➡️ ☁ 🐕🦺) 👆 🎲 **🏆 🚫 👀 ⚫️**. & ↩️ 👈, 👆 🏆 🚫 💭 👈 👆 ✔️ ⏏ 🛠️ ❎. , 👆 🛠️ 🔜 🚧 ☠️. 👶
-
-### 🏃 🔁 🔛 🕴
-
-🏢, 👆 🔜 🎲 💚 💽 📋 (✅ Uvicorn) ▶️ 🔁 🔛 💽 🕴, & 🍵 💪 🙆 **🗿 🏥**, ✔️ 🛠️ 🕧 🏃 ⏮️ 👆 🛠️ (✅ Uvicorn 🏃♂ 👆 FastAPI 📱).
-
-### 🎏 📋
-
-🏆 👉, 👆 🔜 🛎 ✔️ **🎏 📋** 👈 🔜 ⚒ 💭 👆 🈸 🏃 🔛 🕴. & 📚 💼, ⚫️ 🔜 ⚒ 💭 🎏 🦲 ⚖️ 🈸 🏃, 🖼, 💽.
-
-### 🖼 🧰 🏃 🕴
-
-🖼 🧰 👈 💪 👉 👨🏭:
-
-* ☁
-* Kubernete
-* ☁ ✍
-* ☁ 🐝 📳
-* ✳
-* 👨💻
-* 🍵 🔘 ☁ 🐕🦺 🍕 👫 🐕🦺
-* 🎏...
-
-👤 🔜 🤝 👆 🌅 🧱 🖼 ⏭ 📃.
-
-## ⏏
-
-🎏 ⚒ 💭 👆 🈸 🏃 🔛 🕴, 👆 🎲 💚 ⚒ 💭 ⚫️ **⏏** ⏮️ ❌.
-
-### 👥 ⚒ ❌
-
-👥, 🗿, ⚒ **❌**, 🌐 🕰. 🖥 🌖 *🕧* ✔️ **🐛** 🕵♂ 🎏 🥉. 👶
-
-& 👥 👩💻 🚧 📉 📟 👥 🔎 👈 🐛 & 👥 🛠️ 🆕 ⚒ (🎲 ❎ 🆕 🐛 💁♂️ 👶).
-
-### 🤪 ❌ 🔁 🍵
-
-🕐❔ 🏗 🕸 🔗 ⏮️ FastAPI, 🚥 📤 ❌ 👆 📟, FastAPI 🔜 🛎 🔌 ⚫️ 👁 📨 👈 ⏲ ❌. 🛡
-
-👩💻 🔜 🤚 **5️⃣0️⃣0️⃣ 🔗 💽 ❌** 👈 📨, ✋️ 🈸 🔜 😣 👷 ⏭ 📨 ↩️ 💥 🍕.
-
-### 🦏 ❌ - 💥
-
-👐, 📤 5️⃣📆 💼 🌐❔ 👥 ✍ 📟 👈 **💥 🎂 🈸** ⚒ Uvicorn & 🐍 💥. 👶
-
-& , 👆 🔜 🎲 🚫 💚 🈸 🚧 ☠️ ↩️ 📤 ❌ 1️⃣ 🥉, 👆 🎲 💚 ⚫️ **😣 🏃** 🌘 *➡ 🛠️* 👈 🚫 💔.
-
-### ⏏ ⏮️ 💥
-
-✋️ 👈 💼 ⏮️ 🤙 👎 ❌ 👈 💥 🏃♂ **🛠️**, 👆 🔜 💚 🔢 🦲 👈 🈚 **🔁** 🛠️, 🌘 👩❤👨 🕰...
-
-!!! tip
- ...👐 🚥 🎂 🈸 **💥 ⏪** ⚫️ 🎲 🚫 ⚒ 🔑 🚧 🔁 ⚫️ ♾. ✋️ 📚 💼, 👆 🔜 🎲 👀 ⚫️ ⏮️ 🛠️, ⚖️ 🌘 ▶️️ ⏮️ 🛠️.
-
- ➡️ 🎯 🔛 👑 💼, 🌐❔ ⚫️ 💪 💥 🍕 🎯 💼 **🔮**, & ⚫️ ⚒ 🔑 ⏏ ⚫️.
-
-👆 🔜 🎲 💚 ✔️ 👜 🈚 🔁 👆 🈸 **🔢 🦲**, ↩️ 👈 ☝, 🎏 🈸 ⏮️ Uvicorn & 🐍 ⏪ 💥, 📤 🕳 🎏 📟 🎏 📱 👈 💪 🕳 🔃 ⚫️.
-
-### 🖼 🧰 ⏏ 🔁
-
-🏆 💼, 🎏 🧰 👈 ⚙️ **🏃 📋 🔛 🕴** ⚙️ 🍵 🏧 **⏏**.
-
-🖼, 👉 💪 🍵:
-
-* ☁
-* Kubernete
-* ☁ ✍
-* ☁ 🐝 📳
-* ✳
-* 👨💻
-* 🍵 🔘 ☁ 🐕🦺 🍕 👫 🐕🦺
-* 🎏...
-
-## 🧬 - 🛠️ & 💾
-
-⏮️ FastAPI 🈸, ⚙️ 💽 📋 💖 Uvicorn, 🏃♂ ⚫️ 🕐 **1️⃣ 🛠️** 💪 🍦 💗 👩💻 🔁.
-
-✋️ 📚 💼, 👆 🔜 💚 🏃 📚 👨🏭 🛠️ 🎏 🕰.
-
-### 💗 🛠️ - 👨🏭
-
-🚥 👆 ✔️ 🌅 👩💻 🌘 ⚫️❔ 👁 🛠️ 💪 🍵 (🖼 🚥 🕹 🎰 🚫 💁♂️ 🦏) & 👆 ✔️ **💗 🐚** 💽 💽, ⤴️ 👆 💪 ✔️ **💗 🛠️** 🏃♂ ⏮️ 🎏 🈸 🎏 🕰, & 📎 🌐 📨 👪 👫.
-
-🕐❔ 👆 🏃 **💗 🛠️** 🎏 🛠️ 📋, 👫 🛎 🤙 **👨🏭**.
-
-### 👨🏭 🛠️ & ⛴
-
-💭 ⚪️➡️ 🩺 [🔃 🇺🇸🔍](./https.md){.internal-link target=_blank} 👈 🕴 1️⃣ 🛠️ 💪 👂 🔛 1️⃣ 🌀 ⛴ & 📢 📢 💽 ❓
-
-👉 ☑.
-
-, 💪 ✔️ **💗 🛠️** 🎏 🕰, 📤 ✔️ **👁 🛠️ 👂 🔛 ⛴** 👈 ⤴️ 📶 📻 🔠 👨🏭 🛠️ 🌌.
-
-### 💾 📍 🛠️
-
-🔜, 🕐❔ 📋 📐 👜 💾, 🖼, 🎰 🏫 🏷 🔢, ⚖️ 🎚 ⭕ 📁 🔢, 🌐 👈 **🍴 👄 💾 (💾)** 💽.
-
-& 💗 🛠️ 🛎 **🚫 💰 🙆 💾**. 👉 ⛓ 👈 🔠 🏃 🛠️ ✔️ 🚮 👍 👜, 🔢, & 💾. & 🚥 👆 😩 ⭕ 💸 💾 👆 📟, **🔠 🛠️** 🔜 🍴 🌓 💸 💾.
-
-### 💽 💾
-
-🖼, 🚥 👆 📟 📐 🎰 🏫 🏷 ⏮️ **1️⃣ 💾 📐**, 🕐❔ 👆 🏃 1️⃣ 🛠️ ⏮️ 👆 🛠️, ⚫️ 🔜 🍴 🌘 1️⃣ 💾 💾. & 🚥 👆 ▶️ **4️⃣ 🛠️** (4️⃣ 👨🏭), 🔠 🔜 🍴 1️⃣ 💾 💾. 🌐, 👆 🛠️ 🔜 🍴 **4️⃣ 💾 💾**.
-
-& 🚥 👆 🛰 💽 ⚖️ 🕹 🎰 🕴 ✔️ 3️⃣ 💾 💾, 🔄 📐 🌅 🌘 4️⃣ 💾 💾 🔜 🤕 ⚠. 👶
-
-### 💗 🛠️ - 🖼
-
-👉 🖼, 📤 **👨💼 🛠️** 👈 ▶️ & 🎛 2️⃣ **👨🏭 🛠️**.
-
-👉 👨💼 🛠️ 🔜 🎲 1️⃣ 👂 🔛 **⛴** 📢. & ⚫️ 🔜 📶 🌐 📻 👨🏭 🛠️.
-
-👈 👨🏭 🛠️ 🔜 🕐 🏃♂ 👆 🈸, 👫 🔜 🎭 👑 📊 📨 **📨** & 📨 **📨**, & 👫 🔜 📐 🕳 👆 🚮 🔢 💾.
-
-- -**FastAPI** 🚫🔜 🔀 🚥 🚫 ⏮️ 👷 🎏. - -📤 ✔️ 📚 🧰 ✍ ⏭ 👈 ✔️ ℹ 😮 🚮 🏗. - -👤 ✔️ ❎ 🏗 🆕 🛠️ 📚 1️⃣2️⃣🗓️. 🥇 👤 🔄 ❎ 🌐 ⚒ 📔 **FastAPI** ⚙️ 📚 🎏 🛠️, 🔌-🔌, & 🧰. - -✋️ ☝, 📤 🙅♂ 🎏 🎛 🌘 🏗 🕳 👈 🚚 🌐 👫 ⚒, ✊ 🏆 💭 ⚪️➡️ ⏮️ 🧰, & 🌀 👫 🏆 🌌 💪, ⚙️ 🇪🇸 ⚒ 👈 ➖🚫 💪 ⏭ (🐍 3️⃣.6️⃣ ➕ 🆎 🔑). - -- -## 🔬 - -⚙️ 🌐 ⏮️ 🎛 👤 ✔️ 🤞 💡 ⚪️➡️ 🌐 👫, ✊ 💭, & 🌀 👫 🏆 🌌 👤 💪 🔎 👤 & 🏉 👩💻 👤 ✔️ 👷 ⏮️. - -🖼, ⚫️ 🆑 👈 🎲 ⚫️ 🔜 ⚓️ 🔛 🐩 🐍 🆎 🔑. - -, 🏆 🎯 ⚙️ ⏪ ♻ 🐩. - -, ⏭ ▶️ 📟 **FastAPI**, 👤 💸 📚 🗓️ 🎓 🔌 🗄, 🎻 🔗, Oauth2️⃣, ♒️. 🎯 👫 💛, 🔀, & 🔺. - -## 🔧 - -⤴️ 👤 💸 🕰 🔧 👩💻 "🛠️" 👤 💚 ✔️ 👩💻 (👩💻 ⚙️ FastAPI). - -👤 💯 📚 💭 🏆 🌟 🐍 👨🎨: 🗒, 🆚 📟, 🎠 🧢 👨🎨. - -🏁 🐍 👩💻 🔬, 👈 📔 🔃 8️⃣0️⃣ 💯 👩💻. - -⚫️ ⛓ 👈 **FastAPI** 🎯 💯 ⏮️ 👨🎨 ⚙️ 8️⃣0️⃣ 💯 🐍 👩💻. & 🏆 🎏 👨🎨 😑 👷 ➡, 🌐 🚮 💰 🔜 👷 🌖 🌐 👨🎨. - -👈 🌌 👤 💪 🔎 🏆 🌌 📉 📟 ❎ 🌅 💪, ✔️ 🛠️ 🌐, 🆎 & ❌ ✅, ♒️. - -🌐 🌌 👈 🚚 🏆 🛠️ 💡 🌐 👩💻. - -## 📄 - -⏮️ 🔬 📚 🎛, 👤 💭 👈 👤 🔜 ⚙️ **Pydantic** 🚮 📈. - -⤴️ 👤 📉 ⚫️, ⚒ ⚫️ 🍕 🛠️ ⏮️ 🎻 🔗, 🐕🦺 🎏 🌌 🔬 ⚛ 📄, & 📉 👨🎨 🐕🦺 (🆎 ✅, ✍) ⚓️ 🔛 💯 📚 👨🎨. - -⏮️ 🛠️, 👤 📉 **💃**, 🎏 🔑 📄. - -## 🛠️ - -🕰 👤 ▶️ 🏗 **FastAPI** ⚫️, 🏆 🍖 ⏪ 🥉, 🔧 🔬, 📄 & 🧰 🔜, & 💡 🔃 🐩 & 🔧 🆑 & 🍋. - -## 🔮 - -👉 ☝, ⚫️ ⏪ 🆑 👈 **FastAPI** ⏮️ 🚮 💭 ➖ ⚠ 📚 👫👫. - -⚫️ 💆♂ 👐 🤭 ⏮️ 🎛 ♣ 📚 ⚙️ 💼 👍. - -📚 👩💻 & 🏉 ⏪ 🪀 🔛 **FastAPI** 👫 🏗 (🔌 👤 & 👇 🏉). - -✋️, 📤 📚 📈 & ⚒ 👟. - -**FastAPI** ✔️ 👑 🔮 ⤴️. - -& [👆 ℹ](help-fastapi.md){.internal-link target=_blank} 📉 👍. diff --git a/docs/em/docs/how-to/conditional-openapi.md b/docs/em/docs/how-to/conditional-openapi.md deleted file mode 100644 index a17ba4eec52c1..0000000000000 --- a/docs/em/docs/how-to/conditional-openapi.md +++ /dev/null @@ -1,58 +0,0 @@ -# 🎲 🗄 - -🚥 👆 💪, 👆 💪 ⚙️ ⚒ & 🌐 🔢 🔗 🗄 ✔ ⚓️ 🔛 🌐, & ❎ ⚫️ 🍕. - -## 🔃 💂♂, 🔗, & 🩺 - -🕵♂ 👆 🧾 👩💻 🔢 🏭 *🚫🔜 🚫* 🌌 🛡 👆 🛠️. - -👈 🚫 🚮 🙆 ➕ 💂♂ 👆 🛠️, *➡ 🛠️* 🔜 💪 🌐❔ 👫. - -🚥 📤 💂♂ ⚠ 👆 📟, ⚫️ 🔜 🔀. - -🕵♂ 🧾 ⚒ ⚫️ 🌅 ⚠ 🤔 ❔ 🔗 ⏮️ 👆 🛠️, & 💪 ⚒ ⚫️ 🌅 ⚠ 👆 ℹ ⚫️ 🏭. ⚫️ 💪 🤔 🎯 📨 💂♂ 🔘 🌌. - -🚥 👆 💚 🔐 👆 🛠️, 📤 📚 👍 👜 👆 💪, 🖼: - -* ⚒ 💭 👆 ✔️ 👍 🔬 Pydantic 🏷 👆 📨 💪 & 📨. -* 🔗 🙆 ✔ ✔ & 🔑 ⚙️ 🔗. -* 🙅 🏪 🔢 🔐, 🕴 🔐#️⃣. -* 🛠️ & ⚙️ 👍-💭 🔐 🧰, 💖 🇸🇲 & 🥙 🤝, ♒️. -* 🚮 🌅 🧽 ✔ 🎛 ⏮️ Oauth2️⃣ ↔ 🌐❔ 💪. -* ...♒️. - -👐, 👆 5️⃣📆 ✔️ 📶 🎯 ⚙️ 💼 🌐❔ 👆 🤙 💪 ❎ 🛠️ 🩺 🌐 (✅ 🏭) ⚖️ ⚓️ 🔛 📳 ⚪️➡️ 🌐 🔢. - -## 🎲 🗄 ⚪️➡️ ⚒ & 🇨🇻 { - -👆 💪 💪 ⚙️ 🎏 Pydantic ⚒ 🔗 👆 🏗 🗄 & 🩺 ⚜. - -🖼: - -```Python hl_lines="6 11" -{!../../../docs_src/conditional_openapi/tutorial001.py!} -``` - -📥 👥 📣 ⚒ `openapi_url` ⏮️ 🎏 🔢 `"/openapi.json"`. - -& ⤴️ 👥 ⚙️ ⚫️ 🕐❔ 🏗 `FastAPI` 📱. - -⤴️ 👆 💪 ❎ 🗄 (✅ 🎚 🩺) ⚒ 🌐 🔢 `OPENAPI_URL` 🛁 🎻, 💖: - -
diff --git a/docs/em/docs/how-to/graphql.md b/docs/em/docs/how-to/graphql.md
deleted file mode 100644
index 8509643ce88a8..0000000000000
--- a/docs/em/docs/how-to/graphql.md
+++ /dev/null
@@ -1,56 +0,0 @@
-# 🕹
-
-**FastAPI** ⚓️ 🔛 **🔫** 🐩, ⚫️ 📶 ⏩ 🛠️ 🙆 **🕹** 🗃 🔗 ⏮️ 🔫.
-
-👆 💪 🌀 😐 FastAPI *➡ 🛠️* ⏮️ 🕹 🔛 🎏 🈸.
-
-!!! tip
- **🕹** ❎ 📶 🎯 ⚙️ 💼.
-
- ⚫️ ✔️ **📈** & **⚠** 🕐❔ 🔬 ⚠ **🕸 🔗**.
-
- ⚒ 💭 👆 🔬 🚥 **💰** 👆 ⚙️ 💼 ⚖ **👐**. 👶
-
-## 🕹 🗃
-
-📥 **🕹** 🗃 👈 ✔️ **🔫** 🐕🦺. 👆 💪 ⚙️ 👫 ⏮️ **FastAPI**:
-
-* 🍓 👶
- * ⏮️ 🩺 FastAPI
-* 👸
- * ⏮️ 🩺 💃 (👈 ✔ FastAPI)
-* 🍟
- * ⏮️ 🍟 🔫 🚚 🔫 🛠️
-* ⚗
- * ⏮️ 💃-Graphene3️⃣
-
-## 🕹 ⏮️ 🍓
-
-🚥 👆 💪 ⚖️ 💚 👷 ⏮️ **🕹**, **🍓** **👍** 🗃 ⚫️ ✔️ 🔧 🔐 **FastAPI** 🔧, ⚫️ 🌐 ⚓️ 🔛 **🆎 ✍**.
-
-⚓️ 🔛 👆 ⚙️ 💼, 👆 5️⃣📆 💖 ⚙️ 🎏 🗃, ✋️ 🚥 👆 💭 👤, 👤 🔜 🎲 🤔 👆 🔄 **🍓**.
-
-📥 🤪 🎮 ❔ 👆 💪 🛠️ 🍓 ⏮️ FastAPI:
-
-```Python hl_lines="3 22 25-26"
-{!../../../docs_src/graphql/tutorial001.py!}
-```
-
-👆 💪 💡 🌅 🔃 🍓 🍓 🧾.
-
-& 🩺 🔃 🍓 ⏮️ FastAPI.
-
-## 🗝 `GraphQLApp` ⚪️➡️ 💃
-
-⏮️ ⏬ 💃 🔌 `GraphQLApp` 🎓 🛠️ ⏮️ ⚗.
-
-⚫️ 😢 ⚪️➡️ 💃, ✋️ 🚥 👆 ✔️ 📟 👈 ⚙️ ⚫️, 👆 💪 💪 **↔** 💃-Graphene3️⃣, 👈 📔 🎏 ⚙️ 💼 & ✔️ **🌖 🌓 🔢**.
-
-!!! tip
- 🚥 👆 💪 🕹, 👤 🔜 👍 👆 ✅ 👅 🍓, ⚫️ ⚓️ 🔛 🆎 ✍ ↩️ 🛃 🎓 & 🆎.
-
-## 💡 🌅
-
-👆 💪 💡 🌅 🔃 **🕹** 🛂 🕹 🧾.
-
-👆 💪 ✍ 🌅 🔃 🔠 👈 🗃 🔬 🔛 👫 🔗.
diff --git a/docs/em/docs/how-to/sql-databases-peewee.md b/docs/em/docs/how-to/sql-databases-peewee.md
deleted file mode 100644
index 62619fc2c3606..0000000000000
--- a/docs/em/docs/how-to/sql-databases-peewee.md
+++ /dev/null
@@ -1,529 +0,0 @@
-# 🗄 (🔗) 💽 ⏮️ 🏒
-
-!!! warning
- 🚥 👆 ▶️, 🔰 [🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank} 👈 ⚙️ 🇸🇲 🔜 🥃.
-
- 💭 🆓 🚶 👉.
-
-🚥 👆 ▶️ 🏗 ⚪️➡️ 🖌, 👆 🎲 👻 📆 ⏮️ 🇸🇲 🐜 ([🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank}), ⚖️ 🙆 🎏 🔁 🐜.
-
-🚥 👆 ⏪ ✔️ 📟 🧢 👈 ⚙️ 🏒 🐜, 👆 💪 ✅ 📥 ❔ ⚙️ ⚫️ ⏮️ **FastAPI**.
-
-!!! warning "🐍 3️⃣.7️⃣ ➕ ✔"
- 👆 🔜 💪 🐍 3️⃣.7️⃣ ⚖️ 🔛 🔒 ⚙️ 🏒 ⏮️ FastAPI.
-
-## 🏒 🔁
-
-🏒 🚫 🔧 🔁 🛠️, ⚖️ ⏮️ 👫 🤯.
-
-🏒 ✔️ 🏋️ 🔑 🔃 🚮 🔢 & 🔃 ❔ ⚫️ 🔜 ⚙️.
-
-🚥 👆 🛠️ 🈸 ⏮️ 🗝 🚫-🔁 🛠️, & 💪 👷 ⏮️ 🌐 🚮 🔢, **⚫️ 💪 👑 🧰**.
-
-✋️ 🚥 👆 💪 🔀 🔢, 🐕🦺 🌖 🌘 1️⃣ 🔁 💽, 👷 ⏮️ 🔁 🛠️ (💖 FastAPI), ♒️, 👆 🔜 💪 🚮 🏗 ➕ 📟 🔐 👈 🔢.
-
-👐, ⚫️ 💪 ⚫️, & 📥 👆 🔜 👀 ⚫️❔ ⚫️❔ 📟 👆 ✔️ 🚮 💪 ⚙️ 🏒 ⏮️ FastAPI.
-
-!!! note "📡 ℹ"
- 👆 💪 ✍ 🌅 🔃 🏒 🧍 🔃 🔁 🐍 🩺, ❔, 🇵🇷.
-
-## 🎏 📱
-
-👥 🔜 ✍ 🎏 🈸 🇸🇲 🔰 ([🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank}).
-
-🌅 📟 🤙 🎏.
-
-, 👥 🔜 🎯 🕴 🔛 🔺.
-
-## 📁 📊
-
-➡️ 💬 👆 ✔️ 📁 📛 `my_super_project` 👈 🔌 🎧-📁 🤙 `sql_app` ⏮️ 📊 💖 👉:
-
-```
-.
-└── sql_app
- ├── __init__.py
- ├── crud.py
- ├── database.py
- ├── main.py
- └── schemas.py
-```
-
-👉 🌖 🎏 📊 👥 ✔️ 🇸🇲 🔰.
-
-🔜 ➡️ 👀 ⚫️❔ 🔠 📁/🕹 🔨.
-
-## ✍ 🏒 🍕
-
-➡️ 🔗 📁 `sql_app/database.py`.
-
-### 🐩 🏒 📟
-
-➡️ 🥇 ✅ 🌐 😐 🏒 📟, ✍ 🏒 💽:
-
-```Python hl_lines="3 5 22"
-{!../../../docs_src/sql_databases_peewee/sql_app/database.py!}
-```
-
-!!! tip
- ✔️ 🤯 👈 🚥 👆 💚 ⚙️ 🎏 💽, 💖 ✳, 👆 🚫 🚫 🔀 🎻. 👆 🔜 💪 ⚙️ 🎏 🏒 💽 🎓.
-
-#### 🗒
-
-❌:
-
-```Python
-check_same_thread=False
-```
-
-🌓 1️⃣ 🇸🇲 🔰:
-
-```Python
-connect_args={"check_same_thread": False}
-```
-
-...⚫️ 💪 🕴 `SQLite`.
-
-!!! info "📡 ℹ"
-
- ⚫️❔ 🎏 📡 ℹ [🗄 (🔗) 💽](../tutorial/sql-databases.md#note){.internal-link target=_blank} ✔.
-
-### ⚒ 🏒 🔁-🔗 `PeeweeConnectionState`
-
-👑 ❔ ⏮️ 🏒 & FastAPI 👈 🏒 ⚓️ 🙇 🔛 🐍 `threading.local`, & ⚫️ 🚫 ✔️ 🎯 🌌 🔐 ⚫️ ⚖️ ➡️ 👆 🍵 🔗/🎉 🔗 (🔨 🇸🇲 🔰).
-
-& `threading.local` 🚫 🔗 ⏮️ 🆕 🔁 ⚒ 🏛 🐍.
-
-!!! note "📡 ℹ"
- `threading.local` ⚙️ ✔️ "🎱" 🔢 👈 ✔️ 🎏 💲 🔠 🧵.
-
- 👉 ⚠ 🗝 🛠️ 🏗 ✔️ 1️⃣ 👁 🧵 📍 📨, 🙅♂ 🌖, 🙅♂ 🌘.
-
- ⚙️ 👉, 🔠 📨 🔜 ✔️ 🚮 👍 💽 🔗/🎉, ❔ ☑ 🏁 🥅.
-
- ✋️ FastAPI, ⚙️ 🆕 🔁 ⚒, 💪 🍵 🌅 🌘 1️⃣ 📨 🔛 🎏 🧵. & 🎏 🕰, 👁 📨, ⚫️ 💪 🏃 💗 👜 🎏 🧵 (🧵), ⚓️ 🔛 🚥 👆 ⚙️ `async def` ⚖️ 😐 `def`. 👉 ⚫️❔ 🤝 🌐 🎭 📈 FastAPI.
-
-✋️ 🐍 3️⃣.7️⃣ & 🔛 🚚 🌖 🏧 🎛 `threading.local`, 👈 💪 ⚙️ 🥉 🌐❔ `threading.local` 🔜 ⚙️, ✋️ 🔗 ⏮️ 🆕 🔁 ⚒.
-
-👥 🔜 ⚙️ 👈. ⚫️ 🤙 `contextvars`.
-
-👥 🔜 🔐 🔗 🍕 🏒 👈 ⚙️ `threading.local` & ❎ 👫 ⏮️ `contextvars`, ⏮️ 🔗 ℹ.
-
-👉 5️⃣📆 😑 🍖 🏗 (& ⚫️ 🤙), 👆 🚫 🤙 💪 🍕 🤔 ❔ ⚫️ 👷 ⚙️ ⚫️.
-
-👥 🔜 ✍ `PeeweeConnectionState`:
-
-```Python hl_lines="10-19"
-{!../../../docs_src/sql_databases_peewee/sql_app/database.py!}
-```
-
-👉 🎓 😖 ⚪️➡️ 🎁 🔗 🎓 ⚙️ 🏒.
-
-⚫️ ✔️ 🌐 ⚛ ⚒ 🏒 ⚙️ `contextvars` ↩️ `threading.local`.
-
-`contextvars` 👷 🍖 🎏 🌘 `threading.local`. ✋️ 🎂 🏒 🔗 📟 🤔 👈 👉 🎓 👷 ⏮️ `threading.local`.
-
-, 👥 💪 ➕ 🎱 ⚒ ⚫️ 👷 🚥 ⚫️ ⚙️ `threading.local`. `__init__`, `__setattr__`, & `__getattr__` 🛠️ 🌐 ✔ 🎱 👉 ⚙️ 🏒 🍵 🤔 👈 ⚫️ 🔜 🔗 ⏮️ FastAPI.
-
-!!! tip
- 👉 🔜 ⚒ 🏒 🎭 ☑ 🕐❔ ⚙️ ⏮️ FastAPI. 🚫 🎲 📂 ⚖️ 📪 🔗 👈 ➖ ⚙️, 🏗 ❌, ♒️.
-
- ✋️ ⚫️ 🚫 🤝 🏒 🔁 💎-🏋️. 👆 🔜 ⚙️ 😐 `def` 🔢 & 🚫 `async def`.
-
-### ⚙️ 🛃 `PeeweeConnectionState` 🎓
-
-🔜, 📁 `._state` 🔗 🔢 🏒 💽 `db` 🎚 ⚙️ 🆕 `PeeweeConnectionState`:
-
-```Python hl_lines="24"
-{!../../../docs_src/sql_databases_peewee/sql_app/database.py!}
-```
-
-!!! tip
- ⚒ 💭 👆 📁 `db._state` *⏮️* 🏗 `db`.
-
-!!! tip
- 👆 🔜 🎏 🙆 🎏 🏒 💽, 🔌 `PostgresqlDatabase`, `MySQLDatabase`, ♒️.
-
-## ✍ 💽 🏷
-
-➡️ 🔜 👀 📁 `sql_app/models.py`.
-
-### ✍ 🏒 🏷 👆 💽
-
-🔜 ✍ 🏒 🏷 (🎓) `User` & `Item`.
-
-👉 🎏 👆 🔜 🚥 👆 ⏩ 🏒 🔰 & ℹ 🏷 ✔️ 🎏 💽 🇸🇲 🔰.
-
-!!! tip
- 🏒 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽.
-
- ✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐.
-
-🗄 `db` ⚪️➡️ `database` (📁 `database.py` ⚪️➡️ 🔛) & ⚙️ ⚫️ 📥.
-
-```Python hl_lines="3 6-12 15-21"
-{!../../../docs_src/sql_databases_peewee/sql_app/models.py!}
-```
-
-!!! tip
- 🏒 ✍ 📚 🎱 🔢.
-
- ⚫️ 🔜 🔁 🚮 `id` 🔢 🔢 👑 🔑.
-
- ⚫️ 🔜 ⚒ 📛 🏓 ⚓️ 🔛 🎓 📛.
-
- `Item`, ⚫️ 🔜 ✍ 🔢 `owner_id` ⏮️ 🔢 🆔 `User`. ✋️ 👥 🚫 📣 ⚫️ 🙆.
-
-## ✍ Pydantic 🏷
-
-🔜 ➡️ ✅ 📁 `sql_app/schemas.py`.
-
-!!! tip
- ❎ 😨 🖖 🏒 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🏒 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷.
-
- 👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠).
-
- 👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯♂️.
-
-### ✍ Pydantic *🏷* / 🔗
-
-✍ 🌐 🎏 Pydantic 🏷 🇸🇲 🔰:
-
-```Python hl_lines="16-18 21-22 25-30 34-35 38-39 42-48"
-{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!}
-```
-
-!!! tip
- 📥 👥 🏗 🏷 ⏮️ `id`.
-
- 👥 🚫 🎯 ✔ `id` 🔢 🏒 🏷, ✋️ 🏒 🚮 1️⃣ 🔁.
-
- 👥 ❎ 🎱 `owner_id` 🔢 `Item`.
-
-### ✍ `PeeweeGetterDict` Pydantic *🏷* / 🔗
-
-🕐❔ 👆 🔐 💛 🏒 🎚, 💖 `some_user.items`, 🏒 🚫 🚚 `list` `Item`.
-
-⚫️ 🚚 🎁 🛃 🎚 🎓 `ModelSelect`.
-
-⚫️ 💪 ✍ `list` 🚮 🏬 ⏮️ `list(some_user.items)`.
-
-✋️ 🎚 ⚫️ 🚫 `list`. & ⚫️ 🚫 ☑ 🐍 🚂. ↩️ 👉, Pydantic 🚫 💭 🔢 ❔ 🗜 ⚫️ `list` Pydantic *🏷* / 🔗.
-
-✋️ ⏮️ ⏬ Pydantic ✔ 🚚 🛃 🎓 👈 😖 ⚪️➡️ `pydantic.utils.GetterDict`, 🚚 🛠️ ⚙️ 🕐❔ ⚙️ `orm_mode = True` 🗃 💲 🐜 🏷 🔢.
-
-👥 🔜 ✍ 🛃 `PeeweeGetterDict` 🎓 & ⚙️ ⚫️ 🌐 🎏 Pydantic *🏷* / 🔗 👈 ⚙️ `orm_mode`:
-
-```Python hl_lines="3 8-13 31 49"
-{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!}
-```
-
-📥 👥 ✅ 🚥 🔢 👈 ➖ 🔐 (✅ `.items` `some_user.items`) 👐 `peewee.ModelSelect`.
-
-& 🚥 👈 💼, 📨 `list` ⏮️ ⚫️.
-
-& ⤴️ 👥 ⚙️ ⚫️ Pydantic *🏷* / 🔗 👈 ⚙️ `orm_mode = True`, ⏮️ 📳 🔢 `getter_dict = PeeweeGetterDict`.
-
-!!! tip
- 👥 🕴 💪 ✍ 1️⃣ `PeeweeGetterDict` 🎓, & 👥 💪 ⚙️ ⚫️ 🌐 Pydantic *🏷* / 🔗.
-
-## 💩 🇨🇻
-
-🔜 ➡️ 👀 📁 `sql_app/crud.py`.
-
-### ✍ 🌐 💩 🇨🇻
-
-✍ 🌐 🎏 💩 🇨🇻 🇸🇲 🔰, 🌐 📟 📶 🎏:
-
-```Python hl_lines="1 4-5 8-9 12-13 16-20 23-24 27-30"
-{!../../../docs_src/sql_databases_peewee/sql_app/crud.py!}
-```
-
-📤 🔺 ⏮️ 📟 🇸🇲 🔰.
-
-👥 🚫 🚶♀️ `db` 🔢 🤭. ↩️ 👥 ⚙️ 🏷 🔗. 👉 ↩️ `db` 🎚 🌐 🎚, 👈 🔌 🌐 🔗 ⚛. 👈 ⚫️❔ 👥 ✔️ 🌐 `contextvars` ℹ 🔛.
-
-🆖, 🕐❔ 🛬 📚 🎚, 💖 `get_users`, 👥 🔗 🤙 `list`, 💖:
-
-```Python
-list(models.User.select())
-```
-
-👉 🎏 🤔 👈 👥 ✔️ ✍ 🛃 `PeeweeGetterDict`. ✋️ 🛬 🕳 👈 ⏪ `list` ↩️ `peewee.ModelSelect` `response_model` *➡ 🛠️* ⏮️ `List[models.User]` (👈 👥 🔜 👀 ⏪) 🔜 👷 ☑.
-
-## 👑 **FastAPI** 📱
-
-& 🔜 📁 `sql_app/main.py` ➡️ 🛠️ & ⚙️ 🌐 🎏 🍕 👥 ✍ ⏭.
-
-### ✍ 💽 🏓
-
-📶 🙃 🌌 ✍ 💽 🏓:
-
-```Python hl_lines="9-11"
-{!../../../docs_src/sql_databases_peewee/sql_app/main.py!}
-```
-
-### ✍ 🔗
-
-✍ 🔗 👈 🔜 🔗 💽 ▶️️ ▶️ 📨 & 🔌 ⚫️ 🔚:
-
-```Python hl_lines="23-29"
-{!../../../docs_src/sql_databases_peewee/sql_app/main.py!}
-```
-
-📥 👥 ✔️ 🛁 `yield` ↩️ 👥 🤙 🚫 ⚙️ 💽 🎚 🔗.
-
-⚫️ 🔗 💽 & ♻ 🔗 💽 🔗 🔢 👈 🔬 🔠 📨 (⚙️ `contextvars` 🎱 ⚪️➡️ 🔛).
-
-↩️ 💽 🔗 ⚠ 👤/🅾 🚧, 👉 🔗 ✍ ⏮️ 😐 `def` 🔢.
-
-& ⤴️, 🔠 *➡ 🛠️ 🔢* 👈 💪 🔐 💽 👥 🚮 ⚫️ 🔗.
-
-✋️ 👥 🚫 ⚙️ 💲 👐 👉 🔗 (⚫️ 🤙 🚫 🤝 🙆 💲, ⚫️ ✔️ 🛁 `yield`). , 👥 🚫 🚮 ⚫️ *➡ 🛠️ 🔢* ✋️ *➡ 🛠️ 👨🎨* `dependencies` 🔢:
-
-```Python hl_lines="32 40 47 59 65 72"
-{!../../../docs_src/sql_databases_peewee/sql_app/main.py!}
-```
-
-### 🔑 🔢 🎧-🔗
-
-🌐 `contextvars` 🍕 👷, 👥 💪 ⚒ 💭 👥 ✔️ 🔬 💲 `ContextVar` 🔠 📨 👈 ⚙️ 💽, & 👈 💲 🔜 ⚙️ 💽 🇵🇸 (🔗, 💵, ♒️) 🎂 📨.
-
-👈, 👥 💪 ✍ ➕1️⃣ `async` 🔗 `reset_db_state()` 👈 ⚙️ 🎧-🔗 `get_db()`. ⚫️ 🔜 ⚒ 💲 🔑 🔢 (⏮️ 🔢 `dict`) 👈 🔜 ⚙️ 💽 🇵🇸 🎂 📨. & ⤴️ 🔗 `get_db()` 🔜 🏪 ⚫️ 💽 🇵🇸 (🔗, 💵, ♒️).
-
-```Python hl_lines="18-20"
-{!../../../docs_src/sql_databases_peewee/sql_app/main.py!}
-```
-
-**⏭ 📨**, 👥 🔜 ⏲ 👈 🔑 🔢 🔄 `async` 🔗 `reset_db_state()` & ⤴️ ✍ 🆕 🔗 `get_db()` 🔗, 👈 🆕 📨 🔜 ✔️ 🚮 👍 💽 🇵🇸 (🔗, 💵, ♒️).
-
-!!! tip
- FastAPI 🔁 🛠️, 1️⃣ 📨 💪 ▶️ ➖ 🛠️, & ⏭ 🏁, ➕1️⃣ 📨 💪 📨 & ▶️ 🏭 👍, & ⚫️ 🌐 💪 🛠️ 🎏 🧵.
-
- ✋️ 🔑 🔢 🤔 👫 🔁 ⚒,, 🏒 💽 🇵🇸 ⚒ `async` 🔗 `reset_db_state()` 🔜 🚧 🚮 👍 💽 🎂 🎂 📨.
-
- & 🎏 🕰, 🎏 🛠️ 📨 🔜 ✔️ 🚮 👍 💽 🇵🇸 👈 🔜 🔬 🎂 📨.
-
-#### 🏒 🗳
-
-🚥 👆 ⚙️ 🏒 🗳, ☑ 💽 `db.obj`.
-
-, 👆 🔜 ⏲ ⚫️ ⏮️:
-
-```Python hl_lines="3-4"
-async def reset_db_state():
- database.db.obj._state._state.set(db_state_default.copy())
- database.db.obj._state.reset()
-```
-
-### ✍ 👆 **FastAPI** *➡ 🛠️*
-
-🔜, 😒, 📥 🐩 **FastAPI** *➡ 🛠️* 📟.
-
-```Python hl_lines="32-37 40-43 46-53 56-62 65-68 71-79"
-{!../../../docs_src/sql_databases_peewee/sql_app/main.py!}
-```
-
-### 🔃 `def` 🆚 `async def`
-
-🎏 ⏮️ 🇸🇲, 👥 🚫 🔨 🕳 💖:
-
-```Python
-user = await models.User.select().first()
-```
-
-...✋️ ↩️ 👥 ⚙️:
-
-```Python
-user = models.User.select().first()
-```
-
-, 🔄, 👥 🔜 📣 *➡ 🛠️ 🔢* & 🔗 🍵 `async def`, ⏮️ 😐 `def`,:
-
-```Python hl_lines="2"
-# Something goes here
-def read_users(skip: int = 0, limit: int = 100):
- # Something goes here
-```
-
-## 🔬 🏒 ⏮️ 🔁
-
-👉 🖼 🔌 ➕ *➡ 🛠️* 👈 🔬 📏 🏭 📨 ⏮️ `time.sleep(sleep_time)`.
-
-⚫️ 🔜 ✔️ 💽 🔗 📂 ▶️ & 🔜 ⌛ 🥈 ⏭ 🙇 🔙. & 🔠 🆕 📨 🔜 ⌛ 🕐 🥈 🌘.
-
-👉 🔜 💪 ➡️ 👆 💯 👈 👆 📱 ⏮️ 🏒 & FastAPI 🎭 ☑ ⏮️ 🌐 💩 🔃 🧵.
-
-🚥 👆 💚 ✅ ❔ 🏒 🔜 💔 👆 📱 🚥 ⚙️ 🍵 🛠️, 🚶 `sql_app/database.py` 📁 & 🏤 ⏸:
-
-```Python
-# db._state = PeeweeConnectionState()
-```
-
-& 📁 `sql_app/main.py` 📁, 🏤 💪 `async` 🔗 `reset_db_state()` & ❎ ⚫️ ⏮️ `pass`:
-
-```Python
-async def reset_db_state():
-# database.db._state._state.set(db_state_default.copy())
-# database.db._state.reset()
- pass
-```
-
-⤴️ 🏃 👆 📱 ⏮️ Uvicorn:
-
-- FastAPI 🛠️, ↕ 🎭, ⏩ 💡, ⏩ 📟, 🔜 🏭 -
- - ---- - -**🧾**: https://fastapi.tiangolo.com - -**ℹ 📟**: https://github.com/tiangolo/fastapi - ---- - -FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.7️⃣ ➕ ⚓️ 🔛 🐩 🐍 🆎 🔑. - -🔑 ⚒: - -* **⏩**: 📶 ↕ 🎭, 🔛 🇷🇪 ⏮️ **✳** & **🚶** (👏 💃 & Pydantic). [1️⃣ ⏩ 🐍 🛠️ 💪](#performance). -* **⏩ 📟**: 📈 🚅 🛠️ ⚒ 🔃 2️⃣0️⃣0️⃣ 💯 3️⃣0️⃣0️⃣ 💯. * -* **👩❤👨 🐛**: 📉 🔃 4️⃣0️⃣ 💯 🗿 (👩💻) 📉 ❌. * -* **🏋️**: 👑 👨🎨 🐕🦺. 🛠️ 🌐. 🌘 🕰 🛠️. -* **⏩**: 🔧 ⏩ ⚙️ & 💡. 🌘 🕰 👂 🩺. -* **📏**: 📉 📟 ❎. 💗 ⚒ ⚪️➡️ 🔠 🔢 📄. 👩❤👨 🐛. -* **🏋️**: 🤚 🏭-🔜 📟. ⏮️ 🏧 🎓 🧾. -* **🐩-⚓️**: ⚓️ 🔛 (& 🍕 🔗 ⏮️) 📂 🐩 🔗: 🗄 (⏪ 💭 🦁) & 🎻 🔗. - -* ⚖ ⚓️ 🔛 💯 🔛 🔗 🛠️ 🏉, 🏗 🏭 🈸. - -## 💰 - - - -{% if sponsors %} -{% for sponsor in sponsors.gold -%} -async def...uvicorn main:app --reload...ujson - ⏩ 🎻 "🎻".
-* email_validator - 📧 🔬.
-
-⚙️ 💃:
-
-* httpx - ✔ 🚥 👆 💚 ⚙️ `TestClient`.
-* jinja2 - ✔ 🚥 👆 💚 ⚙️ 🔢 📄 📳.
-* python-multipart - ✔ 🚥 👆 💚 🐕🦺 📨 "✍", ⏮️ `request.form()`.
-* itsdangerous - ✔ `SessionMiddleware` 🐕🦺.
-* pyyaml - ✔ 💃 `SchemaGenerator` 🐕🦺 (👆 🎲 🚫 💪 ⚫️ ⏮️ FastAPI).
-* ujson - ✔ 🚥 👆 💚 ⚙️ `UJSONResponse`.
-
-⚙️ FastAPI / 💃:
-
-* uvicorn - 💽 👈 📐 & 🍦 👆 🈸.
-* orjson - ✔ 🚥 👆 💚 ⚙️ `ORJSONResponse`.
-
-👆 💪 ❎ 🌐 👫 ⏮️ `pip install "fastapi[all]"`.
-
-## 🛂
-
-👉 🏗 ® 🔽 ⚖ 🇩🇪 🛂.
diff --git a/docs/em/docs/project-generation.md b/docs/em/docs/project-generation.md
deleted file mode 100644
index 5fd667ad19bf2..0000000000000
--- a/docs/em/docs/project-generation.md
+++ /dev/null
@@ -1,84 +0,0 @@
-# 🏗 ⚡ - 📄
-
-👆 💪 ⚙️ 🏗 🚂 🤚 ▶️, ⚫️ 🔌 📚 ▶️ ⚒ 🆙, 💂♂, 💽 & 🛠️ 🔗 ⏪ ⌛ 👆.
-
-🏗 🚂 🔜 🕧 ✔️ 📶 🙃 🖥 👈 👆 🔜 ℹ & 🛠️ 👆 👍 💪, ✋️ ⚫️ 💪 👍 ▶️ ☝ 👆 🏗.
-
-## 🌕 📚 FastAPI ✳
-
-📂: https://github.com/tiangolo/full-stack-fastapi-postgresql
-
-### 🌕 📚 FastAPI ✳ - ⚒
-
-* 🌕 **☁** 🛠️ (☁ 🧢).
-* ☁ 🐝 📳 🛠️.
-* **☁ ✍** 🛠️ & 🛠️ 🇧🇿 🛠️.
-* **🏭 🔜** 🐍 🕸 💽 ⚙️ Uvicorn & 🐁.
-* 🐍 **FastAPI** 👩💻:
- * **⏩**: 📶 ↕ 🎭, 🔛 🇷🇪 ⏮️ **✳** & **🚶** (👏 💃 & Pydantic).
- * **🏋️**: 👑 👨🎨 🐕🦺. 🛠️ 🌐. 🌘 🕰 🛠️.
- * **⏩**: 🔧 ⏩ ⚙️ & 💡. 🌘 🕰 👂 🩺.
- * **📏**: 📉 📟 ❎. 💗 ⚒ ⚪️➡️ 🔠 🔢 📄.
- * **🏋️**: 🤚 🏭-🔜 📟. ⏮️ 🏧 🎓 🧾.
- * **🐩-⚓️**: ⚓️ 🔛 (& 🍕 🔗 ⏮️) 📂 🐩 🔗: 🗄 & 🎻 🔗.
- * **📚 🎏 ⚒** 🔌 🏧 🔬, 🛠️, 🎓 🧾, 🤝 ⏮️ Oauth2️⃣ 🥙 🤝, ♒️.
-* **🔐 🔐** 🔁 🔢.
-* **🥙 🤝** 🤝.
-* **🇸🇲** 🏷 (🔬 🏺 ↔, 👫 💪 ⚙️ ⏮️ 🥒 👨🏭 🔗).
-* 🔰 ▶️ 🏷 👩💻 (🔀 & ❎ 👆 💪).
-* **⚗** 🛠️.
-* **⚜** (✖️ 🇨🇳 ℹ 🤝).
-* **🥒** 👨🏭 👈 💪 🗄 & ⚙️ 🏷 & 📟 ⚪️➡️ 🎂 👩💻 🍕.
-* 🎂 👩💻 💯 ⚓️ 🔛 **✳**, 🛠️ ⏮️ ☁, 👆 💪 💯 🌕 🛠️ 🔗, 🔬 🔛 💽. ⚫️ 🏃 ☁, ⚫️ 💪 🏗 🆕 💽 🏪 ⚪️➡️ 🖌 🔠 🕰 (👆 💪 ⚙️ ✳, ✳, ✳, ⚖️ ⚫️❔ 👆 💚, & 💯 👈 🛠️ 👷).
-* ⏩ 🐍 🛠️ ⏮️ **📂 💾** 🛰 ⚖️-☁ 🛠️ ⏮️ ↔ 💖 ⚛ ⚗ ⚖️ 🎙 🎙 📟 📂.
-* **🎦** 🕸:
- * 🏗 ⏮️ 🎦 ✳.
- * **🥙 🤝** 🚚.
- * 💳 🎑.
- * ⏮️ 💳, 👑 🕹 🎑.
- * 👑 🕹 ⏮️ 👩💻 🏗 & 📕.
- * 👤 👩💻 📕.
- * **🇷🇪**.
- * **🎦-📻**.
- * **Vuetify** 🌹 🧽 🔧 🦲.
- * **📕**.
- * ☁ 💽 ⚓️ 🔛 **👌** (📶 🤾 🎆 ⏮️ 🎦-📻).
- * ☁ 👁-▶️ 🏗, 👆 🚫 💪 🖊 ⚖️ 💕 ✍ 📟.
- * 🕸 💯 🏃 🏗 🕰 (💪 🔕 💁♂️).
- * ⚒ 🔧 💪, ⚫️ 👷 👅 📦, ✋️ 👆 💪 🏤-🏗 ⏮️ 🎦 ✳ ⚖️ ✍ ⚫️ 👆 💪, & 🏤-⚙️ ⚫️❔ 👆 💚.
-* ** *️⃣ ** ✳ 💽, 👆 💪 🔀 ⚫️ ⚙️ 📁 & ✳ 💪.
-* **🥀** 🥒 👨🏭 ⚖.
-* 📐 ⚖ 🖖 🕸 & 👩💻 ⏮️ **Traefik**, 👆 💪 ✔️ 👯♂️ 🔽 🎏 🆔, 👽 ➡, ✋️ 🍦 🎏 📦.
-* Traefik 🛠️, ✅ ➡️ 🗜 **🇺🇸🔍** 📄 🏧 ⚡.
-* ✳ **🆑** (🔁 🛠️), 🔌 🕸 & 👩💻 🔬.
-
-## 🌕 📚 FastAPI 🗄
-
-📂: https://github.com/tiangolo/full-stack-fastapi-couchbase
-
-👶 👶 **⚠** 👶 👶
-
-🚥 👆 ▶️ 🆕 🏗 ⚪️➡️ 🖌, ✅ 🎛 📥.
-
-🖼, 🏗 🚂 🌕 📚 FastAPI ✳ 💪 👍 🎛, ⚫️ 🎯 🚧 & ⚙️. & ⚫️ 🔌 🌐 🆕 ⚒ & 📈.
-
-👆 🆓 ⚙️ 🗄-⚓️ 🚂 🚥 👆 💚, ⚫️ 🔜 🎲 👷 👌, & 🚥 👆 ⏪ ✔️ 🏗 🏗 ⏮️ ⚫️ 👈 👌 👍 (& 👆 🎲 ⏪ ℹ ⚫️ ♣ 👆 💪).
-
-👆 💪 ✍ 🌅 🔃 ⚫️ 🩺 🏦.
-
-## 🌕 📚 FastAPI ✳
-
-...💪 👟 ⏪, ⚓️ 🔛 👇 🕰 🚚 & 🎏 ⚖. 👶 👶
-
-## 🎰 🏫 🏷 ⏮️ 🌈 & FastAPI
-
-📂: https://github.com/microsoft/cookiecutter-spacy-fastapi
-
-### 🎰 🏫 🏷 ⏮️ 🌈 & FastAPI - ⚒
-
-* **🌈** 🕜 🏷 🛠️.
-* **☁ 🧠 🔎** 📨 📁 🏗.
-* **🏭 🔜** 🐍 🕸 💽 ⚙️ Uvicorn & 🐁.
-* **☁ 👩💻** Kubernete (🦲) 🆑/💿 🛠️ 🏗.
-* **🤸♂** 💪 ⚒ 1️⃣ 🌈 🏗 🇪🇸 ⏮️ 🏗 🖥.
-* **💪 🏧** 🎏 🏷 🛠️ (Pytorch, 🇸🇲), 🚫 🌈.
diff --git a/docs/em/docs/python-types.md b/docs/em/docs/python-types.md
deleted file mode 100644
index e079d9039dd37..0000000000000
--- a/docs/em/docs/python-types.md
+++ /dev/null
@@ -1,490 +0,0 @@
-# 🐍 🆎 🎶
-
-🐍 ✔️ 🐕🦺 📦 "🆎 🔑".
-
-👫 **"🆎 🔑"** 🎁 ❕ 👈 ✔ 📣 🆎 🔢.
-
-📣 🆎 👆 🔢, 👨🎨 & 🧰 💪 🤝 👆 👍 🐕🦺.
-
-👉 **⏩ 🔰 / ↗️** 🔃 🐍 🆎 🔑. ⚫️ 📔 🕴 💯 💪 ⚙️ 👫 ⏮️ **FastAPI**... ❔ 🤙 📶 🐥.
-
-**FastAPI** 🌐 ⚓️ 🔛 👫 🆎 🔑, 👫 🤝 ⚫️ 📚 📈 & 💰.
-
-✋️ 🚥 👆 🙅 ⚙️ **FastAPI**, 👆 🔜 💰 ⚪️➡️ 🏫 🍖 🔃 👫.
-
-!!! note
- 🚥 👆 🐍 🕴, & 👆 ⏪ 💭 🌐 🔃 🆎 🔑, 🚶 ⏭ 📃.
-
-## 🎯
-
-➡️ ▶️ ⏮️ 🙅 🖼:
-
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
-
-🤙 👉 📋 🔢:
-
-```
-John Doe
-```
-
-🔢 🔨 📄:
-
-* ✊ `first_name` & `last_name`.
-* 🗜 🥇 🔤 🔠 1️⃣ ↖ 💼 ⏮️ `title()`.
-* 🔢 👫 ⏮️ 🚀 🖕.
-
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
-
-### ✍ ⚫️
-
-⚫️ 📶 🙅 📋.
-
-✋️ 🔜 🌈 👈 👆 ✍ ⚫️ ⚪️➡️ 🖌.
-
-☝ 👆 🔜 ✔️ ▶️ 🔑 🔢, 👆 ✔️ 🔢 🔜...
-
-✋️ ⤴️ 👆 ✔️ 🤙 "👈 👩🔬 👈 🗜 🥇 🔤 ↖ 💼".
-
-⚫️ `upper`❓ ⚫️ `uppercase`❓ `first_uppercase`❓ `capitalize`❓
-
-⤴️, 👆 🔄 ⏮️ 🗝 👩💻 👨👧👦, 👨🎨 ✍.
-
-👆 🆎 🥇 🔢 🔢, `first_name`, ⤴️ ❣ (`.`) & ⤴️ 🎯 `Ctrl+Space` ⏲ 🛠️.
-
-✋️, 😞, 👆 🤚 🕳 ⚠:
-
-
-
-### 🚮 🆎
-
-➡️ 🔀 👁 ⏸ ⚪️➡️ ⏮️ ⏬.
-
-👥 🔜 🔀 ⚫️❔ 👉 🧬, 🔢 🔢, ⚪️➡️:
-
-```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` & 👆 👀:
-
-
-
-⏮️ 👈, 👆 💪 📜, 👀 🎛, ⏭ 👆 🔎 1️⃣ 👈 "💍 🔔":
-
-
-
-## 🌅 🎯
-
-✅ 👉 🔢, ⚫️ ⏪ ✔️ 🆎 🔑:
-
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
-
-↩️ 👨🎨 💭 🆎 🔢, 👆 🚫 🕴 🤚 🛠️, 👆 🤚 ❌ ✅:
-
-
-
-🔜 👆 💭 👈 👆 ✔️ 🔧 ⚫️, 🗜 `age` 🎻 ⏮️ `str(age)`:
-
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
-
-## 📣 🆎
-
-👆 👀 👑 🥉 📣 🆎 🔑. 🔢 🔢.
-
-👉 👑 🥉 👆 🔜 ⚙️ 👫 ⏮️ **FastAPI**.
-
-### 🙅 🆎
-
-👆 💪 📣 🌐 🐩 🐍 🆎, 🚫 🕴 `str`.
-
-👆 💪 ⚙️, 🖼:
-
-* `int`
-* `float`
-* `bool`
-* `bytes`
-
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
-```
-
-### 💊 🆎 ⏮️ 🆎 🔢
-
-📤 📊 📊 👈 💪 🔌 🎏 💲, 💖 `dict`, `list`, `set` & `tuple`. & 🔗 💲 💪 ✔️ 👫 👍 🆎 💁♂️.
-
-👉 🆎 👈 ✔️ 🔗 🆎 🤙 "**💊**" 🆎. & ⚫️ 💪 📣 👫, ⏮️ 👫 🔗 🆎.
-
-📣 👈 🆎 & 🔗 🆎, 👆 💪 ⚙️ 🐩 🐍 🕹 `typing`. ⚫️ 🔀 🎯 🐕🦺 👫 🆎 🔑.
-
-#### 🆕 ⏬ 🐍
-
-❕ ⚙️ `typing` **🔗** ⏮️ 🌐 ⏬, ⚪️➡️ 🐍 3️⃣.6️⃣ ⏪ 🕐, ✅ 🐍 3️⃣.9️⃣, 🐍 3️⃣.1️⃣0️⃣, ♒️.
-
-🐍 🏧, **🆕 ⏬** 👟 ⏮️ 📉 🐕🦺 👉 🆎 ✍ & 📚 💼 👆 🏆 🚫 💪 🗄 & ⚙️ `typing` 🕹 📣 🆎 ✍.
-
-🚥 👆 💪 ⚒ 🌖 ⏮️ ⏬ 🐍 👆 🏗, 👆 🔜 💪 ✊ 📈 👈 ➕ 🦁. 👀 🖼 🔛.
-
-#### 📇
-
-🖼, ➡️ 🔬 🔢 `list` `str`.
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ⚪️➡️ `typing`, 🗄 `List` (⏮️ 🔠 `L`):
-
- ``` Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
-
- 📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕.
-
- 🆎, 🚮 `List` 👈 👆 🗄 ⚪️➡️ `typing`.
-
- 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜:
-
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- 📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕.
-
- 🆎, 🚮 `list`.
-
- 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜:
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
-
-!!! info
- 👈 🔗 🆎 ⬜ 🗜 🤙 "🆎 🔢".
-
- 👉 💼, `str` 🆎 🔢 🚶♀️ `List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛).
-
-👈 ⛓: "🔢 `items` `list`, & 🔠 🏬 👉 📇 `str`".
-
-!!! tip
- 🚥 👆 ⚙️ 🐍 3️⃣.9️⃣ ⚖️ 🔛, 👆 🚫 ✔️ 🗄 `List` ⚪️➡️ `typing`, 👆 💪 ⚙️ 🎏 🥔 `list` 🆎 ↩️.
-
-🔨 👈, 👆 👨🎨 💪 🚚 🐕🦺 ⏪ 🏭 🏬 ⚪️➡️ 📇:
-
-
-
-🍵 🆎, 👈 🌖 💪 🏆.
-
-👀 👈 🔢 `item` 1️⃣ 🔣 📇 `items`.
-
-& , 👨🎨 💭 ⚫️ `str`, & 🚚 🐕🦺 👈.
-
-#### 🔢 & ⚒
-
-👆 🔜 🎏 📣 `tuple`Ⓜ & `set`Ⓜ:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
-
-👉 ⛓:
-
-* 🔢 `items_t` `tuple` ⏮️ 3️⃣ 🏬, `int`, ➕1️⃣ `int`, & `str`.
-* 🔢 `items_s` `set`, & 🔠 🚮 🏬 🆎 `bytes`.
-
-#### #️⃣
-
-🔬 `dict`, 👆 🚶♀️ 2️⃣ 🆎 🔢, 🎏 ❕.
-
-🥇 🆎 🔢 🔑 `dict`.
-
-🥈 🆎 🔢 💲 `dict`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
-
-👉 ⛓:
-
-* 🔢 `prices` `dict`:
- * 🔑 👉 `dict` 🆎 `str` (➡️ 💬, 📛 🔠 🏬).
- * 💲 👉 `dict` 🆎 `float` (➡️ 💬, 🔖 🔠 🏬).
-
-#### 🇪🇺
-
-👆 💪 📣 👈 🔢 💪 🙆 **📚 🆎**, 🖼, `int` ⚖️ `str`.
-
-🐍 3️⃣.6️⃣ & 🔛 (✅ 🐍 3️⃣.1️⃣0️⃣) 👆 💪 ⚙️ `Union` 🆎 ⚪️➡️ `typing` & 🚮 🔘 ⬜ 🗜 💪 🆎 🚫.
-
-🐍 3️⃣.1️⃣0️⃣ 📤 **🎛 ❕** 🌐❔ 👆 💪 🚮 💪 🆎 👽 ⏸ ⏸ (`|`).
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
-
-👯♂️ 💼 👉 ⛓ 👈 `item` 💪 `int` ⚖️ `str`.
-
-#### 🎲 `None`
-
-👆 💪 📣 👈 💲 💪 ✔️ 🆎, 💖 `str`, ✋️ 👈 ⚫️ 💪 `None`.
-
-🐍 3️⃣.6️⃣ & 🔛 (✅ 🐍 3️⃣.1️⃣0️⃣) 👆 💪 📣 ⚫️ 🏭 & ⚙️ `Optional` ⚪️➡️ `typing` 🕹.
-
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
-```
-
-⚙️ `Optional[str]` ↩️ `str` 🔜 ➡️ 👨🎨 ℹ 👆 🔍 ❌ 🌐❔ 👆 💪 🤔 👈 💲 🕧 `str`, 🕐❔ ⚫️ 💪 🤙 `None` 💁♂️.
-
-`Optional[Something]` 🤙 ⌨ `Union[Something, None]`, 👫 🌓.
-
-👉 ⛓ 👈 🐍 3️⃣.1️⃣0️⃣, 👆 💪 ⚙️ `Something | None`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
- ```
-
-=== "🐍 3️⃣.6️⃣ & 🔛 - 🎛"
-
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
-
-#### ⚙️ `Union` ⚖️ `Optional`
-
-🚥 👆 ⚙️ 🐍 ⏬ 🔛 3️⃣.1️⃣0️⃣, 📥 💁♂ ⚪️➡️ 👇 📶 **🤔** ☝ 🎑:
-
-* 👶 ❎ ⚙️ `Optional[SomeType]`
-* ↩️ 👶 **⚙️ `Union[SomeType, None]`** 👶.
-
-👯♂️ 🌓 & 🔘 👫 🎏, ✋️ 👤 🔜 👍 `Union` ↩️ `Optional` ↩️ 🔤 "**📦**" 🔜 😑 🔑 👈 💲 📦, & ⚫️ 🤙 ⛓ "⚫️ 💪 `None`", 🚥 ⚫️ 🚫 📦 & ✔.
-
-👤 💭 `Union[SomeType, None]` 🌖 🔑 🔃 ⚫️❔ ⚫️ ⛓.
-
-⚫️ 🔃 🔤 & 📛. ✋️ 👈 🔤 💪 📉 ❔ 👆 & 👆 🤽♂ 💭 🔃 📟.
-
-🖼, ➡️ ✊ 👉 🔢:
-
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c.py!}
-```
-
-🔢 `name` 🔬 `Optional[str]`, ✋️ ⚫️ **🚫 📦**, 👆 🚫🔜 🤙 🔢 🍵 🔢:
-
-```Python
-say_hi() # Oh, no, this throws an error! 😱
-```
-
-`name` 🔢 **✔** (🚫 *📦*) ↩️ ⚫️ 🚫 ✔️ 🔢 💲. , `name` 🚫 `None` 💲:
-
-```Python
-say_hi(name=None) # This works, None is valid 🎉
-```
-
-👍 📰, 🕐 👆 🔛 🐍 3️⃣.1️⃣0️⃣ 👆 🏆 🚫 ✔️ 😟 🔃 👈, 👆 🔜 💪 🎯 ⚙️ `|` 🔬 🇪🇺 🆎:
-
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c_py310.py!}
-```
-
-& ⤴️ 👆 🏆 🚫 ✔️ 😟 🔃 📛 💖 `Optional` & `Union`. 👶
-
-#### 💊 🆎
-
-👉 🆎 👈 ✊ 🆎 🔢 ⬜ 🗜 🤙 **💊 🆎** ⚖️ **💊**, 🖼:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ...& 🎏.
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- 👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘):
-
- * `list`
- * `tuple`
- * `set`
- * `dict`
-
- & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
-
- * `Union`
- * `Optional`
- * ...& 🎏.
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- 👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘):
-
- * `list`
- * `tuple`
- * `set`
- * `dict`
-
- & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹:
-
- * `Union`
- * `Optional` (🎏 ⏮️ 🐍 3️⃣.6️⃣)
- * ...& 🎏.
-
- 🐍 3️⃣.1️⃣0️⃣, 🎛 ⚙️ 💊 `Union` & `Optional`, 👆 💪 ⚙️ ⏸ ⏸ (`|`) 📣 🇪🇺 🆎.
-
-### 🎓 🆎
-
-👆 💪 📣 🎓 🆎 🔢.
-
-➡️ 💬 👆 ✔️ 🎓 `Person`, ⏮️ 📛:
-
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
-
-⤴️ 👆 💪 📣 🔢 🆎 `Person`:
-
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
-
-& ⤴️, 🔄, 👆 🤚 🌐 👨🎨 🐕🦺:
-
-
-
-## Pydantic 🏷
-
-Pydantic 🐍 🗃 🎭 📊 🔬.
-
-👆 📣 "💠" 💽 🎓 ⏮️ 🔢.
-
-& 🔠 🔢 ✔️ 🆎.
-
-⤴️ 👆 ✍ 👐 👈 🎓 ⏮️ 💲 & ⚫️ 🔜 ✔ 💲, 🗜 👫 ☑ 🆎 (🚥 👈 💼) & 🤝 👆 🎚 ⏮️ 🌐 💽.
-
-& 👆 🤚 🌐 👨🎨 🐕🦺 ⏮️ 👈 📉 🎚.
-
-🖼 ⚪️➡️ 🛂 Pydantic 🩺:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
-
-!!! info
- 💡 🌖 🔃 Pydantic, ✅ 🚮 🩺.
-
-**FastAPI** 🌐 ⚓️ 🔛 Pydantic.
-
-👆 🔜 👀 📚 🌅 🌐 👉 💡 [🔰 - 👩💻 🦮](tutorial/index.md){.internal-link target=_blank}.
-
-!!! tip
- Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑.
-
-## 🆎 🔑 **FastAPI**
-
-**FastAPI** ✊ 📈 👫 🆎 🔑 📚 👜.
-
-⏮️ **FastAPI** 👆 📣 🔢 ⏮️ 🆎 🔑 & 👆 🤚:
-
-* **👨🎨 🐕🦺**.
-* **🆎 ✅**.
-
-...and **FastAPI** uses the same declarations :
-
-* **🔬 📄**: ⚪️➡️ 📨 ➡ 🔢, 🔢 🔢, 🎚, 💪, 🔗, ♒️.
-* **🗜 💽**: ⚪️➡️ 📨 🚚 🆎.
-* **✔ 💽**: 👟 ⚪️➡️ 🔠 📨:
- * 🏭 **🏧 ❌** 📨 👩💻 🕐❔ 📊 ❌.
-* **📄** 🛠️ ⚙️ 🗄:
- * ❔ ⤴️ ⚙️ 🏧 🎓 🧾 👩💻 🔢.
-
-👉 5️⃣📆 🌐 🔊 📝. 🚫 😟. 👆 🔜 👀 🌐 👉 🎯 [🔰 - 👩💻 🦮](tutorial/index.md){.internal-link target=_blank}.
-
-⚠ 👜 👈 ⚙️ 🐩 🐍 🆎, 👁 🥉 (↩️ ❎ 🌖 🎓, 👨🎨, ♒️), **FastAPI** 🔜 📚 👷 👆.
-
-!!! info
- 🚥 👆 ⏪ 🚶 🔘 🌐 🔰 & 👟 🔙 👀 🌅 🔃 🆎, 👍 ℹ "🎮 🎼" ⚪️➡️ `mypy`.
diff --git a/docs/em/docs/tutorial/background-tasks.md b/docs/em/docs/tutorial/background-tasks.md
deleted file mode 100644
index e28ead4155383..0000000000000
--- a/docs/em/docs/tutorial/background-tasks.md
+++ /dev/null
@@ -1,102 +0,0 @@
-# 🖥 📋
-
-👆 💪 🔬 🖥 📋 🏃 *⏮️* 🛬 📨.
-
-👉 ⚠ 🛠️ 👈 💪 🔨 ⏮️ 📨, ✋️ 👈 👩💻 🚫 🤙 ✔️ ⌛ 🛠️ 🏁 ⏭ 📨 📨.
-
-👉 🔌, 🖼:
-
-* 📧 📨 📨 ⏮️ 🎭 🎯:
- * 🔗 📧 💽 & 📨 📧 😑 "🐌" (📚 🥈), 👆 💪 📨 📨 ▶️️ ↖️ & 📨 📧 📨 🖥.
-* 🏭 💽:
- * 🖼, ➡️ 💬 👆 📨 📁 👈 🔜 🚶 🔘 🐌 🛠️, 👆 💪 📨 📨 "🚫" (🇺🇸🔍 2️⃣0️⃣2️⃣) & 🛠️ ⚫️ 🖥.
-
-## ⚙️ `BackgroundTasks`
-
-🥇, 🗄 `BackgroundTasks` & 🔬 🔢 👆 *➡ 🛠️ 🔢* ⏮️ 🆎 📄 `BackgroundTasks`:
-
-```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!}
-```
-
-## 🚮 🖥 📋
-
-🔘 👆 *➡ 🛠️ 🔢*, 🚶♀️ 👆 📋 🔢 *🖥 📋* 🎚 ⏮️ 👩🔬 `.add_task()`:
-
-```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
-
-`.add_task()` 📨 ❌:
-
-* 📋 🔢 🏃 🖥 (`write_notification`).
-* 🙆 🔁 ❌ 👈 🔜 🚶♀️ 📋 🔢 ✔ (`email`).
-* 🙆 🇨🇻 ❌ 👈 🔜 🚶♀️ 📋 🔢 (`message="some notification"`).
-
-## 🔗 💉
-
-⚙️ `BackgroundTasks` 👷 ⏮️ 🔗 💉 ⚙️, 👆 💪 📣 🔢 🆎 `BackgroundTasks` 💗 🎚: *➡ 🛠️ 🔢*, 🔗 (☑), 🎧-🔗, ♒️.
-
-**FastAPI** 💭 ⚫️❔ 🔠 💼 & ❔ 🏤-⚙️ 🎏 🎚, 👈 🌐 🖥 📋 🔗 👯♂️ & 🏃 🖥 ⏮️:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
-
-👉 🖼, 📧 🔜 ✍ `log.txt` 📁 *⏮️* 📨 📨.
-
-🚥 📤 🔢 📨, ⚫️ 🔜 ✍ 🕹 🖥 📋.
-
-& ⤴️ ➕1️⃣ 🖥 📋 🏗 *➡ 🛠️ 🔢* 🔜 ✍ 📧 ⚙️ `email` ➡ 🔢.
-
-## 📡 ℹ
-
-🎓 `BackgroundTasks` 👟 🔗 ⚪️➡️ `starlette.background`.
-
-⚫️ 🗄/🔌 🔗 🔘 FastAPI 👈 👆 💪 🗄 ⚫️ ⚪️➡️ `fastapi` & ❎ 😫 🗄 🎛 `BackgroundTask` (🍵 `s` 🔚) ⚪️➡️ `starlette.background`.
-
-🕴 ⚙️ `BackgroundTasks` (& 🚫 `BackgroundTask`), ⚫️ ⤴️ 💪 ⚙️ ⚫️ *➡ 🛠️ 🔢* 🔢 & ✔️ **FastAPI** 🍵 🎂 👆, 💖 🕐❔ ⚙️ `Request` 🎚 🔗.
-
-⚫️ 💪 ⚙️ `BackgroundTask` 😞 FastAPI, ✋️ 👆 ✔️ ✍ 🎚 👆 📟 & 📨 💃 `Response` 🔌 ⚫️.
-
-👆 💪 👀 🌖 ℹ 💃 🛂 🩺 🖥 📋.
-
-## ⚠
-
-🚥 👆 💪 🎭 🏋️ 🖥 📊 & 👆 🚫 🎯 💪 ⚫️ 🏃 🎏 🛠️ (🖼, 👆 🚫 💪 💰 💾, 🔢, ♒️), 👆 💪 💰 ⚪️➡️ ⚙️ 🎏 🦏 🧰 💖 🥒.
-
-👫 😑 🚚 🌖 🏗 📳, 📧/👨🏭 📤 👨💼, 💖 ✳ ⚖️ ✳, ✋️ 👫 ✔ 👆 🏃 🖥 📋 💗 🛠️, & ✴️, 💗 💽.
-
-👀 🖼, ✅ [🏗 🚂](../project-generation.md){.internal-link target=_blank}, 👫 🌐 🔌 🥒 ⏪ 📶.
-
-✋️ 🚥 👆 💪 🔐 🔢 & 🎚 ⚪️➡️ 🎏 **FastAPI** 📱, ⚖️ 👆 💪 🎭 🤪 🖥 📋 (💖 📨 📧 📨), 👆 💪 🎯 ⚙️ `BackgroundTasks`.
-
-## 🌃
-
-🗄 & ⚙️ `BackgroundTasks` ⏮️ 🔢 *➡ 🛠️ 🔢* & 🔗 🚮 🖥 📋.
diff --git a/docs/em/docs/tutorial/bigger-applications.md b/docs/em/docs/tutorial/bigger-applications.md
deleted file mode 100644
index 7b4694387dd9b..0000000000000
--- a/docs/em/docs/tutorial/bigger-applications.md
+++ /dev/null
@@ -1,488 +0,0 @@
-# 🦏 🈸 - 💗 📁
-
-🚥 👆 🏗 🈸 ⚖️ 🕸 🛠️, ⚫️ 🛎 💼 👈 👆 💪 🚮 🌐 🔛 👁 📁.
-
-**FastAPI** 🚚 🏪 🧰 📊 👆 🈸 ⏪ 🚧 🌐 💪.
-
-!!! info
- 🚥 👆 👟 ⚪️➡️ 🏺, 👉 🔜 🌓 🏺 📗.
-
-## 🖼 📁 📊
-
-➡️ 💬 👆 ✔️ 📁 📊 💖 👉:
-
-```
-.
-├── app
-│ ├── __init__.py
-│ ├── main.py
-│ ├── dependencies.py
-│ └── routers
-│ │ ├── __init__.py
-│ │ ├── items.py
-│ │ └── users.py
-│ └── internal
-│ ├── __init__.py
-│ └── admin.py
-```
-
-!!! tip
- 📤 📚 `__init__.py` 📁: 1️⃣ 🔠 📁 ⚖️ 📁.
-
- 👉 ⚫️❔ ✔ 🏭 📟 ⚪️➡️ 1️⃣ 📁 🔘 ➕1️⃣.
-
- 🖼, `app/main.py` 👆 💪 ✔️ ⏸ 💖:
-
- ```
- from app.routers import items
- ```
-
-* `app` 📁 🔌 🌐. & ⚫️ ✔️ 🛁 📁 `app/__init__.py`, ⚫️ "🐍 📦" (🗃 "🐍 🕹"): `app`.
-* ⚫️ 🔌 `app/main.py` 📁. ⚫️ 🔘 🐍 📦 (📁 ⏮️ 📁 `__init__.py`), ⚫️ "🕹" 👈 📦: `app.main`.
-* 📤 `app/dependencies.py` 📁, 💖 `app/main.py`, ⚫️ "🕹": `app.dependencies`.
-* 📤 📁 `app/routers/` ⏮️ ➕1️⃣ 📁 `__init__.py`, ⚫️ "🐍 📦": `app.routers`.
-* 📁 `app/routers/items.py` 🔘 📦, `app/routers/`,, ⚫️ 🔁: `app.routers.items`.
-* 🎏 ⏮️ `app/routers/users.py`, ⚫️ ➕1️⃣ 🔁: `app.routers.users`.
-* 📤 📁 `app/internal/` ⏮️ ➕1️⃣ 📁 `__init__.py`, ⚫️ ➕1️⃣ "🐍 📦": `app.internal`.
-* & 📁 `app/internal/admin.py` ➕1️⃣ 🔁: `app.internal.admin`.
-
-
-
-## 🔌 🎏 📻 💗 🕰 ⏮️ 🎏 `prefix`
-
-👆 💪 ⚙️ `.include_router()` 💗 🕰 ⏮️ *🎏* 📻 ⚙️ 🎏 🔡.
-
-👉 💪 ⚠, 🖼, 🎦 🎏 🛠️ 🔽 🎏 🔡, ✅ `/api/v1` & `/api/latest`.
-
-👉 🏧 ⚙️ 👈 👆 5️⃣📆 🚫 🤙 💪, ✋️ ⚫️ 📤 💼 👆.
-
-## 🔌 `APIRouter` ➕1️⃣
-
-🎏 🌌 👆 💪 🔌 `APIRouter` `FastAPI` 🈸, 👆 💪 🔌 `APIRouter` ➕1️⃣ `APIRouter` ⚙️:
-
-```Python
-router.include_router(other_router)
-```
-
-⚒ 💭 👆 ⚫️ ⏭ 🔌 `router` `FastAPI` 📱, 👈 *➡ 🛠️* ⚪️➡️ `other_router` 🔌.
diff --git a/docs/em/docs/tutorial/body-fields.md b/docs/em/docs/tutorial/body-fields.md
deleted file mode 100644
index 9f2c914f4bf93..0000000000000
--- a/docs/em/docs/tutorial/body-fields.md
+++ /dev/null
@@ -1,68 +0,0 @@
-# 💪 - 🏑
-
-🎏 🌌 👆 💪 📣 🌖 🔬 & 🗃 *➡ 🛠️ 🔢* 🔢 ⏮️ `Query`, `Path` & `Body`, 👆 💪 📣 🔬 & 🗃 🔘 Pydantic 🏷 ⚙️ Pydantic `Field`.
-
-## 🗄 `Field`
-
-🥇, 👆 ✔️ 🗄 ⚫️:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
-
-!!! warning
- 👀 👈 `Field` 🗄 🔗 ⚪️➡️ `pydantic`, 🚫 ⚪️➡️ `fastapi` 🌐 🎂 (`Query`, `Path`, `Body`, ♒️).
-
-## 📣 🏷 🔢
-
-👆 💪 ⤴️ ⚙️ `Field` ⏮️ 🏷 🔢:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
-
-`Field` 👷 🎏 🌌 `Query`, `Path` & `Body`, ⚫️ ✔️ 🌐 🎏 🔢, ♒️.
-
-!!! note "📡 ℹ"
- 🤙, `Query`, `Path` & 🎏 👆 🔜 👀 ⏭ ✍ 🎚 🏿 ⚠ `Param` 🎓, ❔ ⚫️ 🏿 Pydantic `FieldInfo` 🎓.
-
- & Pydantic `Field` 📨 👐 `FieldInfo` 👍.
-
- `Body` 📨 🎚 🏿 `FieldInfo` 🔗. & 📤 🎏 👆 🔜 👀 ⏪ 👈 🏿 `Body` 🎓.
-
- 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
-
-!!! tip
- 👀 ❔ 🔠 🏷 🔢 ⏮️ 🆎, 🔢 💲 & `Field` ✔️ 🎏 📊 *➡ 🛠️ 🔢* 🔢, ⏮️ `Field` ↩️ `Path`, `Query` & `Body`.
-
-## 🚮 ➕ ℹ
-
-👆 💪 📣 ➕ ℹ `Field`, `Query`, `Body`, ♒️. & ⚫️ 🔜 🔌 🏗 🎻 🔗.
-
-👆 🔜 💡 🌅 🔃 ❎ ➕ ℹ ⏪ 🩺, 🕐❔ 🏫 📣 🖼.
-
-!!! warning
- ➕ 🔑 🚶♀️ `Field` 🔜 🎁 📉 🗄 🔗 👆 🈸.
- 👫 🔑 5️⃣📆 🚫 🎯 🍕 🗄 🔧, 🗄 🧰, 🖼 [🗄 💳](https://validator.swagger.io/), 5️⃣📆 🚫 👷 ⏮️ 👆 🏗 🔗.
-
-## 🌃
-
-👆 💪 ⚙️ Pydantic `Field` 📣 ➕ 🔬 & 🗃 🏷 🔢.
-
-👆 💪 ⚙️ ➕ 🇨🇻 ❌ 🚶♀️ 🌖 🎻 🔗 🗃.
diff --git a/docs/em/docs/tutorial/body-multiple-params.md b/docs/em/docs/tutorial/body-multiple-params.md
deleted file mode 100644
index 9ada7dee10c3e..0000000000000
--- a/docs/em/docs/tutorial/body-multiple-params.md
+++ /dev/null
@@ -1,213 +0,0 @@
-# 💪 - 💗 🔢
-
-🔜 👈 👥 ✔️ 👀 ❔ ⚙️ `Path` & `Query`, ➡️ 👀 🌅 🏧 ⚙️ 📨 💪 📄.
-
-## 🌀 `Path`, `Query` & 💪 🔢
-
-🥇, ↗️, 👆 💪 🌀 `Path`, `Query` & 📨 💪 🔢 📄 ➡ & **FastAPI** 🔜 💭 ⚫️❔.
-
-& 👆 💪 📣 💪 🔢 📦, ⚒ 🔢 `None`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
-
-!!! note
- 👀 👈, 👉 💼, `item` 👈 🔜 ✊ ⚪️➡️ 💪 📦. ⚫️ ✔️ `None` 🔢 💲.
-
-## 💗 💪 🔢
-
-⏮️ 🖼, *➡ 🛠️* 🔜 ⌛ 🎻 💪 ⏮️ 🔢 `Item`, 💖:
-
-```JSON
-{
- "name": "Foo",
- "description": "The pretender",
- "price": 42.0,
- "tax": 3.2
-}
-```
-
-✋️ 👆 💪 📣 💗 💪 🔢, ✅ `item` & `user`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
- ```
-
-👉 💼, **FastAPI** 🔜 👀 👈 📤 🌅 🌘 1️⃣ 💪 🔢 🔢 (2️⃣ 🔢 👈 Pydantic 🏷).
-
-, ⚫️ 🔜 ⤴️ ⚙️ 🔢 📛 🔑 (🏑 📛) 💪, & ⌛ 💪 💖:
-
-```JSON
-{
- "item": {
- "name": "Foo",
- "description": "The pretender",
- "price": 42.0,
- "tax": 3.2
- },
- "user": {
- "username": "dave",
- "full_name": "Dave Grohl"
- }
-}
-```
-
-!!! note
- 👀 👈 ✋️ `item` 📣 🎏 🌌 ⏭, ⚫️ 🔜 ⌛ 🔘 💪 ⏮️ 🔑 `item`.
-
-
-**FastAPI** 🔜 🏧 🛠️ ⚪️➡️ 📨, 👈 🔢 `item` 📨 ⚫️ 🎯 🎚 & 🎏 `user`.
-
-⚫️ 🔜 🎭 🔬 ⚗ 💽, & 🔜 📄 ⚫️ 💖 👈 🗄 🔗 & 🏧 🩺.
-
-## ⭐ 💲 💪
-
-🎏 🌌 📤 `Query` & `Path` 🔬 ➕ 💽 🔢 & ➡ 🔢, **FastAPI** 🚚 🌓 `Body`.
-
-🖼, ↔ ⏮️ 🏷, 👆 💪 💭 👈 👆 💚 ✔️ ➕1️⃣ 🔑 `importance` 🎏 💪, 🥈 `item` & `user`.
-
-🚥 👆 📣 ⚫️, ↩️ ⚫️ ⭐ 💲, **FastAPI** 🔜 🤔 👈 ⚫️ 🔢 🔢.
-
-✋️ 👆 💪 💡 **FastAPI** 😥 ⚫️ ➕1️⃣ 💪 🔑 ⚙️ `Body`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial003_py310.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: Union[str, None] = None
-```
-
-⚖️ 🐍 3️⃣.1️⃣0️⃣ & 🔛:
-
-```Python
-q: str | None = None
-```
-
-🖼:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="26"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
-
-!!! info
- `Body` ✔️ 🌐 🎏 ➕ 🔬 & 🗃 🔢 `Query`,`Path` & 🎏 👆 🔜 👀 ⏪.
-
-## ⏯ 👁 💪 🔢
-
-➡️ 💬 👆 🕴 ✔️ 👁 `item` 💪 🔢 ⚪️➡️ Pydantic 🏷 `Item`.
-
-🔢, **FastAPI** 🔜 ⤴️ ⌛ 🚮 💪 🔗.
-
-✋️ 🚥 👆 💚 ⚫️ ⌛ 🎻 ⏮️ 🔑 `item` & 🔘 ⚫️ 🏷 🎚, ⚫️ 🔨 🕐❔ 👆 📣 ➕ 💪 🔢, 👆 💪 ⚙️ 🎁 `Body` 🔢 `embed`:
-
-```Python
-item: Item = Body(embed=True)
-```
-
-:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.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
-}
-```
-
-## 🌃
-
-👆 💪 🚮 💗 💪 🔢 👆 *➡ 🛠️ 🔢*, ✋️ 📨 💪 🕴 ✔️ 👁 💪.
-
-✋️ **FastAPI** 🔜 🍵 ⚫️, 🤝 👆 ☑ 📊 👆 🔢, & ✔ & 📄 ☑ 🔗 *➡ 🛠️*.
-
-👆 💪 📣 ⭐ 💲 📨 🍕 💪.
-
-& 👆 💪 💡 **FastAPI** ⏯ 💪 🔑 🕐❔ 📤 🕴 👁 🔢 📣.
diff --git a/docs/em/docs/tutorial/body-nested-models.md b/docs/em/docs/tutorial/body-nested-models.md
deleted file mode 100644
index f4bd50f5cbd96..0000000000000
--- a/docs/em/docs/tutorial/body-nested-models.md
+++ /dev/null
@@ -1,382 +0,0 @@
-# 💪 - 🔁 🏷
-
-⏮️ **FastAPI**, 👆 💪 🔬, ✔, 📄, & ⚙️ 🎲 🙇 🐦 🏷 (👏 Pydantic).
-
-## 📇 🏑
-
-👆 💪 🔬 🔢 🏾. 🖼, 🐍 `list`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
- ```
-
-👉 🔜 ⚒ `tags` 📇, 👐 ⚫️ 🚫 📣 🆎 🔣 📇.
-
-## 📇 🏑 ⏮️ 🆎 🔢
-
-✋️ 🐍 ✔️ 🎯 🌌 📣 📇 ⏮️ 🔗 🆎, ⚖️ "🆎 🔢":
-
-### 🗄 ⌨ `List`
-
-🐍 3️⃣.9️⃣ & 🔛 👆 💪 ⚙️ 🐩 `list` 📣 👫 🆎 ✍ 👥 🔜 👀 🔛. 👶
-
-✋️ 🐍 ⏬ ⏭ 3️⃣.9️⃣ (3️⃣.6️⃣ & 🔛), 👆 🥇 💪 🗄 `List` ⚪️➡️ 🐩 🐍 `typing` 🕹:
-
-```Python hl_lines="1"
-{!> ../../../docs_src/body_nested_models/tutorial002.py!}
-```
-
-### 📣 `list` ⏮️ 🆎 🔢
-
-📣 🆎 👈 ✔️ 🆎 🔢 (🔗 🆎), 💖 `list`, `dict`, `tuple`:
-
-* 🚥 👆 🐍 ⏬ 🔅 🌘 3️⃣.9️⃣, 🗄 👫 🌓 ⏬ ⚪️➡️ `typing` 🕹
-* 🚶♀️ 🔗 🆎(Ⓜ) "🆎 🔢" ⚙️ ⬜ 🗜: `[` & `]`
-
-🐍 3️⃣.9️⃣ ⚫️ 🔜:
-
-```Python
-my_list: list[str]
-```
-
-⏬ 🐍 ⏭ 3️⃣.9️⃣, ⚫️ 🔜:
-
-```Python
-from typing import List
-
-my_list: List[str]
-```
-
-👈 🌐 🐩 🐍 ❕ 🆎 📄.
-
-⚙️ 👈 🎏 🐩 ❕ 🏷 🔢 ⏮️ 🔗 🆎.
-
-, 👆 🖼, 👥 💪 ⚒ `tags` 🎯 "📇 🎻":
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
- ```
-
-## ⚒ 🆎
-
-✋️ ⤴️ 👥 💭 🔃 ⚫️, & 🤔 👈 🔖 🚫🔜 🚫 🔁, 👫 🔜 🎲 😍 🎻.
-
-& 🐍 ✔️ 🎁 💽 🆎 ⚒ 😍 🏬, `set`.
-
-⤴️ 👥 💪 📣 `tags` ⚒ 🎻:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="1 14"
- {!> ../../../docs_src/body_nested_models/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
- ```
-
-⏮️ 👉, 🚥 👆 📨 📨 ⏮️ ❎ 📊, ⚫️ 🔜 🗜 ⚒ 😍 🏬.
-
-& 🕐❔ 👆 🔢 👈 📊, 🚥 ℹ ✔️ ❎, ⚫️ 🔜 🔢 ⚒ 😍 🏬.
-
-& ⚫️ 🔜 ✍ / 📄 ➡️ 💁♂️.
-
-## 🐦 🏷
-
-🔠 🔢 Pydantic 🏷 ✔️ 🆎.
-
-✋️ 👈 🆎 💪 ⚫️ ➕1️⃣ Pydantic 🏷.
-
-, 👆 💪 📣 🙇 🐦 🎻 "🎚" ⏮️ 🎯 🔢 📛, 🆎 & 🔬.
-
-🌐 👈, 🎲 🐦.
-
-### 🔬 📊
-
-🖼, 👥 💪 🔬 `Image` 🏷:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7-9"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
-
-### ⚙️ 📊 🆎
-
-& ⤴️ 👥 💪 ⚙️ ⚫️ 🆎 🔢:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.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`.
-
-👀 🌐 🎛 👆 ✔️, 🛒 🩺 Pydantic 😍 🆎. 👆 🔜 👀 🖼 ⏭ 📃.
-
-🖼, `Image` 🏷 👥 ✔️ `url` 🏑, 👥 💪 📣 ⚫️ ↩️ `str`, Pydantic `HttpUrl`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="2 8"
- {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
- ```
-
-🎻 🔜 ✅ ☑ 📛, & 📄 🎻 🔗 / 🗄 ✅.
-
-## 🔢 ⏮️ 📇 📊
-
-👆 💪 ⚙️ Pydantic 🏷 🏾 `list`, `set`, ♒️:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
- ```
-
-👉 🔜 ⌛ (🗜, ✔, 📄, ♒️) 🎻 💪 💖:
-
-```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` 🔑 🔜 ✔️ 📇 🖼 🎚.
-
-## 🙇 🐦 🏷
-
-👆 💪 🔬 🎲 🙇 🐦 🏷:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7 12 18 21 25"
- {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
- ```
-
-!!! info
- 👀 ❔ `Offer` ✔️ 📇 `Item`Ⓜ, ❔ 🔄 ✔️ 📦 📇 `Image`Ⓜ
-
-## 💪 😁 📇
-
-🚥 🔝 🎚 💲 🎻 💪 👆 ⌛ 🎻 `array` (🐍 `list`), 👆 💪 📣 🆎 🔢 🔢, 🎏 Pydantic 🏷:
-
-```Python
-images: List[Image]
-```
-
-⚖️ 🐍 3️⃣.9️⃣ & 🔛:
-
-```Python
-images: list[Image]
-```
-
-:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_nested_models/tutorial008.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
- ```
-
-## 👨🎨 🐕🦺 🌐
-
-& 👆 🤚 👨🎨 🐕🦺 🌐.
-
-🏬 🔘 📇:
-
-
-
-👆 🚫 🚫 🤚 👉 😇 👨🎨 🐕🦺 🚥 👆 👷 🔗 ⏮️ `dict` ↩️ Pydantic 🏷.
-
-✋️ 👆 🚫 ✔️ 😟 🔃 👫 👯♂️, 📨 #️⃣ 🗜 🔁 & 👆 🔢 🗜 🔁 🎻 💁♂️.
-
-## 💪 ❌ `dict`Ⓜ
-
-👆 💪 📣 💪 `dict` ⏮️ 🔑 🆎 & 💲 🎏 🆎.
-
-🍵 ✔️ 💭 ⏪ ⚫️❔ ☑ 🏑/🔢 📛 (🔜 💼 ⏮️ Pydantic 🏷).
-
-👉 🔜 ⚠ 🚥 👆 💚 📨 🔑 👈 👆 🚫 ⏪ 💭.
-
----
-
-🎏 ⚠ 💼 🕐❔ 👆 💚 ✔️ 🔑 🎏 🆎, ✅ `int`.
-
-👈 ⚫️❔ 👥 🔜 👀 📥.
-
-👉 💼, 👆 🔜 🚫 🙆 `dict` 📏 ⚫️ ✔️ `int` 🔑 ⏮️ `float` 💲:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
- ```
-
-!!! tip
- ✔️ 🤯 👈 🎻 🕴 🐕🦺 `str` 🔑.
-
- ✋️ Pydantic ✔️ 🏧 💽 🛠️.
-
- 👉 ⛓ 👈, ✋️ 👆 🛠️ 👩💻 💪 🕴 📨 🎻 🔑, 📏 👈 🎻 🔌 😁 🔢, Pydantic 🔜 🗜 👫 & ✔ 👫.
-
- & `dict` 👆 📨 `weights` 🔜 🤙 ✔️ `int` 🔑 & `float` 💲.
-
-## 🌃
-
-⏮️ **FastAPI** 👆 ✔️ 🔆 💪 🚚 Pydantic 🏷, ⏪ 🚧 👆 📟 🙅, 📏 & 😍.
-
-✋️ ⏮️ 🌐 💰:
-
-* 👨🎨 🐕🦺 (🛠️ 🌐 ❗)
-* 💽 🛠️ (.Ⓜ.. ✍ / 🛠️)
-* 💽 🔬
-* 🔗 🧾
-* 🏧 🩺
diff --git a/docs/em/docs/tutorial/body-updates.md b/docs/em/docs/tutorial/body-updates.md
deleted file mode 100644
index 98058ab52666b..0000000000000
--- a/docs/em/docs/tutorial/body-updates.md
+++ /dev/null
@@ -1,155 +0,0 @@
-# 💪 - ℹ
-
-## ℹ ❎ ⏮️ `PUT`
-
-ℹ 🏬 👆 💪 ⚙️ 🇺🇸🔍 `PUT` 🛠️.
-
-👆 💪 ⚙️ `jsonable_encoder` 🗜 🔢 💽 📊 👈 💪 🏪 🎻 (✅ ⏮️ ☁ 💽). 🖼, 🏭 `datetime` `str`.
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="28-33"
- {!> ../../../docs_src/body_updates/tutorial001_py310.py!}
- ```
-
-`PUT` ⚙️ 📨 💽 👈 🔜 ❎ ♻ 💽.
-
-### ⚠ 🔃 ❎
-
-👈 ⛓ 👈 🚥 👆 💚 ℹ 🏬 `bar` ⚙️ `PUT` ⏮️ 💪 ⚗:
-
-```Python
-{
- "name": "Barz",
- "price": 3,
- "description": None,
-}
-```
-
-↩️ ⚫️ 🚫 🔌 ⏪ 🏪 🔢 `"tax": 20.2`, 🔢 🏷 🔜 ✊ 🔢 💲 `"tax": 10.5`.
-
-& 📊 🔜 🖊 ⏮️ 👈 "🆕" `tax` `10.5`.
-
-## 🍕 ℹ ⏮️ `PATCH`
-
-👆 💪 ⚙️ 🇺🇸🔍 `PATCH` 🛠️ *🍕* ℹ 💽.
-
-👉 ⛓ 👈 👆 💪 📨 🕴 💽 👈 👆 💚 ℹ, 🍂 🎂 🐣.
-
-!!! Note
- `PATCH` 🌘 🛎 ⚙️ & 💭 🌘 `PUT`.
-
- & 📚 🏉 ⚙️ 🕴 `PUT`, 🍕 ℹ.
-
- 👆 **🆓** ⚙️ 👫 👐 👆 💚, **FastAPI** 🚫 🚫 🙆 🚫.
-
- ✋️ 👉 🦮 🎦 👆, 🌖 ⚖️ 🌘, ❔ 👫 🎯 ⚙️.
-
-### ⚙️ Pydantic `exclude_unset` 🔢
-
-🚥 👆 💚 📨 🍕 ℹ, ⚫️ 📶 ⚠ ⚙️ 🔢 `exclude_unset` Pydantic 🏷 `.dict()`.
-
-💖 `item.dict(exclude_unset=True)`.
-
-👈 🔜 🏗 `dict` ⏮️ 🕴 💽 👈 ⚒ 🕐❔ 🏗 `item` 🏷, 🚫 🔢 💲.
-
-⤴️ 👆 💪 ⚙️ 👉 🏗 `dict` ⏮️ 🕴 💽 👈 ⚒ (📨 📨), 🚫 🔢 💲:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="32"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
-
-### ⚙️ Pydantic `update` 🔢
-
-🔜, 👆 💪 ✍ 📁 ♻ 🏷 ⚙️ `.copy()`, & 🚶♀️ `update` 🔢 ⏮️ `dict` ⚗ 💽 ℹ.
-
-💖 `stored_item_model.copy(update=update_data)`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="33"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
-
-### 🍕 ℹ 🌃
-
-📄, ✔ 🍕 ℹ 👆 🔜:
-
-* (⚗) ⚙️ `PATCH` ↩️ `PUT`.
-* 🗃 🏪 💽.
-* 🚮 👈 💽 Pydantic 🏷.
-* 🏗 `dict` 🍵 🔢 💲 ⚪️➡️ 🔢 🏷 (⚙️ `exclude_unset`).
- * 👉 🌌 👆 💪 ℹ 🕴 💲 🤙 ⚒ 👩💻, ↩️ 🔐 💲 ⏪ 🏪 ⏮️ 🔢 💲 👆 🏷.
-* ✍ 📁 🏪 🏷, 🛠️ ⚫️ 🔢 ⏮️ 📨 🍕 ℹ (⚙️ `update` 🔢).
-* 🗜 📁 🏷 🕳 👈 💪 🏪 👆 💽 (🖼, ⚙️ `jsonable_encoder`).
- * 👉 ⭐ ⚙️ 🏷 `.dict()` 👩🔬 🔄, ✋️ ⚫️ ⚒ 💭 (& 🗜) 💲 💽 🆎 👈 💪 🗜 🎻, 🖼, `datetime` `str`.
-* 🖊 💽 👆 💽.
-* 📨 ℹ 🏷.
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="28-35"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
-
-!!! tip
- 👆 💪 🤙 ⚙️ 👉 🎏 ⚒ ⏮️ 🇺🇸🔍 `PUT` 🛠️.
-
- ✋️ 🖼 📥 ⚙️ `PATCH` ↩️ ⚫️ ✍ 👫 ⚙️ 💼.
-
-!!! note
- 👀 👈 🔢 🏷 ✔.
-
- , 🚥 👆 💚 📨 🍕 ℹ 👈 💪 🚫 🌐 🔢, 👆 💪 ✔️ 🏷 ⏮️ 🌐 🔢 ™ 📦 (⏮️ 🔢 💲 ⚖️ `None`).
-
- 🔬 ⚪️➡️ 🏷 ⏮️ 🌐 📦 💲 **ℹ** & 🏷 ⏮️ ✔ 💲 **🏗**, 👆 💪 ⚙️ 💭 🔬 [➕ 🏷](extra-models.md){.internal-link target=_blank}.
diff --git a/docs/em/docs/tutorial/body.md b/docs/em/docs/tutorial/body.md
deleted file mode 100644
index ca2f113bf4c48..0000000000000
--- a/docs/em/docs/tutorial/body.md
+++ /dev/null
@@ -1,213 +0,0 @@
-# 📨 💪
-
-🕐❔ 👆 💪 📨 📊 ⚪️➡️ 👩💻 (➡️ 💬, 🖥) 👆 🛠️, 👆 📨 ⚫️ **📨 💪**.
-
-**📨** 💪 📊 📨 👩💻 👆 🛠️. **📨** 💪 💽 👆 🛠️ 📨 👩💻.
-
-👆 🛠️ 🌖 🕧 ✔️ 📨 **📨** 💪. ✋️ 👩💻 🚫 🎯 💪 📨 **📨** 💪 🌐 🕰.
-
-📣 **📨** 💪, 👆 ⚙️ Pydantic 🏷 ⏮️ 🌐 👫 🏋️ & 💰.
-
-!!! info
- 📨 💽, 👆 🔜 ⚙️ 1️⃣: `POST` (🌅 ⚠), `PUT`, `DELETE` ⚖️ `PATCH`.
-
- 📨 💪 ⏮️ `GET` 📨 ✔️ ⚠ 🎭 🔧, 👐, ⚫️ 🐕🦺 FastAPI, 🕴 📶 🏗/😕 ⚙️ 💼.
-
- ⚫️ 🚫, 🎓 🩺 ⏮️ 🦁 🎚 🏆 🚫 🎦 🧾 💪 🕐❔ ⚙️ `GET`, & 🗳 🖕 💪 🚫 🐕🦺 ⚫️.
-
-## 🗄 Pydantic `BaseModel`
-
-🥇, 👆 💪 🗄 `BaseModel` ⚪️➡️ `pydantic`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
-
-## ✍ 👆 💽 🏷
-
-⤴️ 👆 📣 👆 💽 🏷 🎓 👈 😖 ⚪️➡️ `BaseModel`.
-
-⚙️ 🐩 🐍 🆎 🌐 🔢:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
-
-🎏 🕐❔ 📣 🔢 🔢, 🕐❔ 🏷 🔢 ✔️ 🔢 💲, ⚫️ 🚫 ✔. ⏪, ⚫️ ✔. ⚙️ `None` ⚒ ⚫️ 📦.
-
-🖼, 👉 🏷 🔛 📣 🎻 "`object`" (⚖️ 🐍 `dict`) 💖:
-
-```JSON
-{
- "name": "Foo",
- "description": "An optional description",
- "price": 45.2,
- "tax": 3.5
-}
-```
-
-... `description` & `tax` 📦 (⏮️ 🔢 💲 `None`), 👉 🎻 "`object`" 🔜 ☑:
-
-```JSON
-{
- "name": "Foo",
- "price": 45.2
-}
-```
-
-## 📣 ⚫️ 🔢
-
-🚮 ⚫️ 👆 *➡ 🛠️*, 📣 ⚫️ 🎏 🌌 👆 📣 ➡ & 🔢 🔢:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
-
-...& 📣 🚮 🆎 🏷 👆 ✍, `Item`.
-
-## 🏁
-
-⏮️ 👈 🐍 🆎 📄, **FastAPI** 🔜:
-
-* ✍ 💪 📨 🎻.
-* 🗜 🔗 🆎 (🚥 💪).
-* ✔ 💽.
- * 🚥 💽 ❌, ⚫️ 🔜 📨 👌 & 🆑 ❌, ☠️ ⚫️❔ 🌐❔ & ⚫️❔ ❌ 📊.
-* 🤝 👆 📨 📊 🔢 `item`.
- * 👆 📣 ⚫️ 🔢 🆎 `Item`, 👆 🔜 ✔️ 🌐 👨🎨 🐕🦺 (🛠️, ♒️) 🌐 🔢 & 👫 🆎.
-* 🏗 🎻 🔗 🔑 👆 🏷, 👆 💪 ⚙️ 👫 🙆 🙆 👆 💖 🚥 ⚫️ ⚒ 🔑 👆 🏗.
-* 👈 🔗 🔜 🍕 🏗 🗄 🔗, & ⚙️ 🏧 🧾 ⚜.
-
-## 🏧 🩺
-
-🎻 🔗 👆 🏷 🔜 🍕 👆 🗄 🏗 🔗, & 🔜 🎦 🎓 🛠️ 🩺:
-
-
-
-& 🔜 ⚙️ 🛠️ 🩺 🔘 🔠 *➡ 🛠️* 👈 💪 👫:
-
-
-
-## 👨🎨 🐕🦺
-
-👆 👨🎨, 🔘 👆 🔢 👆 🔜 🤚 🆎 🔑 & 🛠️ 🌐 (👉 🚫🔜 🔨 🚥 👆 📨 `dict` ↩️ Pydantic 🏷):
-
-
-
-👆 🤚 ❌ ✅ ❌ 🆎 🛠️:
-
-
-
-👉 🚫 🤞, 🎂 🛠️ 🏗 🤭 👈 🔧.
-
-& ⚫️ 🙇 💯 🔧 🌓, ⏭ 🙆 🛠️, 🚚 ⚫️ 🔜 👷 ⏮️ 🌐 👨🎨.
-
-📤 🔀 Pydantic ⚫️ 🐕🦺 👉.
-
-⏮️ 🖼 ✊ ⏮️ 🎙 🎙 📟.
-
-✋️ 👆 🔜 🤚 🎏 👨🎨 🐕🦺 ⏮️ 🗒 & 🌅 🎏 🐍 👨🎨:
-
-
-
-!!! tip
- 🚥 👆 ⚙️ 🗒 👆 👨🎨, 👆 💪 ⚙️ Pydantic 🗒 📁.
-
- ⚫️ 📉 👨🎨 🐕🦺 Pydantic 🏷, ⏮️:
-
- * 🚘-🛠️
- * 🆎 ✅
- * 🛠️
- * 🔎
- * 🔬
-
-## ⚙️ 🏷
-
-🔘 🔢, 👆 💪 🔐 🌐 🔢 🏷 🎚 🔗:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
-
-## 📨 💪 ➕ ➡ 🔢
-
-👆 💪 📣 ➡ 🔢 & 📨 💪 🎏 🕰.
-
-**FastAPI** 🔜 🤔 👈 🔢 🔢 👈 🏏 ➡ 🔢 🔜 **✊ ⚪️➡️ ➡**, & 👈 🔢 🔢 👈 📣 Pydantic 🏷 🔜 **✊ ⚪️➡️ 📨 💪**.
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
-
-## 📨 💪 ➕ ➡ ➕ 🔢 🔢
-
-👆 💪 📣 **💪**, **➡** & **🔢** 🔢, 🌐 🎏 🕰.
-
-**FastAPI** 🔜 🤔 🔠 👫 & ✊ 📊 ⚪️➡️ ☑ 🥉.
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
-
-🔢 🔢 🔜 🤔 ⏩:
-
-* 🚥 🔢 📣 **➡**, ⚫️ 🔜 ⚙️ ➡ 🔢.
-* 🚥 🔢 **⭐ 🆎** (💖 `int`, `float`, `str`, `bool`, ♒️) ⚫️ 🔜 🔬 **🔢** 🔢.
-* 🚥 🔢 📣 🆎 **Pydantic 🏷**, ⚫️ 🔜 🔬 📨 **💪**.
-
-!!! note
- FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`.
-
- `Union` `Union[str, None]` 🚫 ⚙️ FastAPI, ✋️ 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌.
-
-## 🍵 Pydantic
-
-🚥 👆 🚫 💚 ⚙️ Pydantic 🏷, 👆 💪 ⚙️ **💪** 🔢. 👀 🩺 [💪 - 💗 🔢: ⭐ 💲 💪](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}.
diff --git a/docs/em/docs/tutorial/cookie-params.md b/docs/em/docs/tutorial/cookie-params.md
deleted file mode 100644
index 47f4a62f5c2ad..0000000000000
--- a/docs/em/docs/tutorial/cookie-params.md
+++ /dev/null
@@ -1,49 +0,0 @@
-# 🍪 🔢
-
-👆 💪 🔬 🍪 🔢 🎏 🌌 👆 🔬 `Query` & `Path` 🔢.
-
-## 🗄 `Cookie`
-
-🥇 🗄 `Cookie`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
-
-## 📣 `Cookie` 🔢
-
-⤴️ 📣 🍪 🔢 ⚙️ 🎏 📊 ⏮️ `Path` & `Query`.
-
-🥇 💲 🔢 💲, 👆 💪 🚶♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/cookie_params/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/cookie_params/tutorial001_py310.py!}
- ```
-
-!!! note "📡 ℹ"
- `Cookie` "👭" 🎓 `Path` & `Query`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓.
-
- ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Cookie` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
-
-!!! info
- 📣 🍪, 👆 💪 ⚙️ `Cookie`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢.
-
-## 🌃
-
-📣 🍪 ⏮️ `Cookie`, ⚙️ 🎏 ⚠ ⚓ `Query` & `Path`.
diff --git a/docs/em/docs/tutorial/cors.md b/docs/em/docs/tutorial/cors.md
deleted file mode 100644
index 8c5e33ed7b196..0000000000000
--- a/docs/em/docs/tutorial/cors.md
+++ /dev/null
@@ -1,84 +0,0 @@
-# ⚜ (✖️-🇨🇳 ℹ 🤝)
-
-⚜ ⚖️ "✖️-🇨🇳 ℹ 🤝" 🔗 ⚠ 🕐❔ 🕸 🏃♂ 🖥 ✔️ 🕸 📟 👈 🔗 ⏮️ 👩💻, & 👩💻 🎏 "🇨🇳" 🌘 🕸.
-
-## 🇨🇳
-
-🇨🇳 🌀 🛠️ (`http`, `https`), 🆔 (`myapp.com`, `localhost`, `localhost.tiangolo.com`), & ⛴ (`80`, `443`, `8080`).
-
-, 🌐 👫 🎏 🇨🇳:
-
-* `http://localhost`
-* `https://localhost`
-* `http://localhost:8080`
-
-🚥 👫 🌐 `localhost`, 👫 ⚙️ 🎏 🛠️ ⚖️ ⛴,, 👫 🎏 "🇨🇳".
-
-## 🔁
-
-, ➡️ 💬 👆 ✔️ 🕸 🏃 👆 🖥 `http://localhost:8080`, & 🚮 🕸 🔄 🔗 ⏮️ 👩💻 🏃 `http://localhost` (↩️ 👥 🚫 ✔ ⛴, 🖥 🔜 🤔 🔢 ⛴ `80`).
-
-⤴️, 🖥 🔜 📨 🇺🇸🔍 `OPTIONS` 📨 👩💻, & 🚥 👩💻 📨 ☑ 🎚 ✔ 📻 ⚪️➡️ 👉 🎏 🇨🇳 (`http://localhost:8080`) ⤴️ 🖥 🔜 ➡️ 🕸 🕸 📨 🚮 📨 👩💻.
-
-🏆 👉, 👩💻 🔜 ✔️ 📇 "✔ 🇨🇳".
-
-👉 💼, ⚫️ 🔜 ✔️ 🔌 `http://localhost:8080` 🕸 👷 ☑.
-
-## 🃏
-
-⚫️ 💪 📣 📇 `"*"` ("🃏") 💬 👈 🌐 ✔.
-
-✋️ 👈 🔜 🕴 ✔ 🎯 🆎 📻, 🚫 🌐 👈 🔌 🎓: 🍪, ✔ 🎚 💖 📚 ⚙️ ⏮️ 📨 🤝, ♒️.
-
-, 🌐 👷 ☑, ⚫️ 👻 ✔ 🎯 ✔ 🇨🇳.
-
-## ⚙️ `CORSMiddleware`
-
-👆 💪 🔗 ⚫️ 👆 **FastAPI** 🈸 ⚙️ `CORSMiddleware`.
-
-* 🗄 `CORSMiddleware`.
-* ✍ 📇 ✔ 🇨🇳 (🎻).
-* 🚮 ⚫️ "🛠️" 👆 **FastAPI** 🈸.
-
-👆 💪 ✔ 🚥 👆 👩💻 ✔:
-
-* 🎓 (✔ 🎚, 🍪, ♒️).
-* 🎯 🇺🇸🔍 👩🔬 (`POST`, `PUT`) ⚖️ 🌐 👫 ⏮️ 🃏 `"*"`.
-* 🎯 🇺🇸🔍 🎚 ⚖️ 🌐 👫 ⏮️ 🃏 `"*"`.
-
-```Python hl_lines="2 6-11 13-19"
-{!../../../docs_src/cors/tutorial001.py!}
-```
-
-🔢 🔢 ⚙️ `CORSMiddleware` 🛠️ 🚫 🔢, 👆 🔜 💪 🎯 🛠️ 🎯 🇨🇳, 👩🔬, ⚖️ 🎚, ✔ 🖥 ✔ ⚙️ 👫 ✖️-🆔 🔑.
-
-📄 ❌ 🐕🦺:
-
-* `allow_origins` - 📇 🇨🇳 👈 🔜 ✔ ⚒ ✖️-🇨🇳 📨. 🤶 Ⓜ. `['https://example.org', 'https://www.example.org']`. 👆 💪 ⚙️ `['*']` ✔ 🙆 🇨🇳.
-* `allow_origin_regex` - 🎻 🎻 🏏 🛡 🇨🇳 👈 🔜 ✔ ⚒ ✖️-🇨🇳 📨. ✅ `'https://.*\.example\.org'`.
-* `allow_methods` - 📇 🇺🇸🔍 👩🔬 👈 🔜 ✔ ✖️-🇨🇳 📨. 🔢 `['GET']`. 👆 💪 ⚙️ `['*']` ✔ 🌐 🐩 👩🔬.
-* `allow_headers` - 📇 🇺🇸🔍 📨 🎚 👈 🔜 🐕🦺 ✖️-🇨🇳 📨. 🔢 `[]`. 👆 💪 ⚙️ `['*']` ✔ 🌐 🎚. `Accept`, `Accept-Language`, `Content-Language` & `Content-Type` 🎚 🕧 ✔ 🙅 ⚜ 📨.
-* `allow_credentials` - 🎦 👈 🍪 🔜 🐕🦺 ✖️-🇨🇳 📨. 🔢 `False`. , `allow_origins` 🚫🔜 ⚒ `['*']` 🎓 ✔, 🇨🇳 🔜 ✔.
-* `expose_headers` - 🎦 🙆 📨 🎚 👈 🔜 ⚒ ♿ 🖥. 🔢 `[]`.
-* `max_age` - ⚒ 🔆 🕰 🥈 🖥 💾 ⚜ 📨. 🔢 `600`.
-
-🛠️ 📨 2️⃣ 🎯 🆎 🇺🇸🔍 📨...
-
-### ⚜ 🛫 📨
-
-👉 🙆 `OPTIONS` 📨 ⏮️ `Origin` & `Access-Control-Request-Method` 🎚.
-
-👉 💼 🛠️ 🔜 🆘 📨 📨 & 📨 ⏮️ ☑ ⚜ 🎚, & 👯♂️ `200` ⚖️ `400` 📨 🎓 🎯.
-
-### 🙅 📨
-
-🙆 📨 ⏮️ `Origin` 🎚. 👉 💼 🛠️ 🔜 🚶♀️ 📨 🔘 😐, ✋️ 🔜 🔌 ☑ ⚜ 🎚 🔛 📨.
-
-## 🌅 ℹ
-
-🌖 ℹ 🔃 ⚜, ✅ 🦎 ⚜ 🧾.
-
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.middleware.cors import CORSMiddleware`.
-
- **FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃.
diff --git a/docs/em/docs/tutorial/debugging.md b/docs/em/docs/tutorial/debugging.md
deleted file mode 100644
index c7c11b5cec506..0000000000000
--- a/docs/em/docs/tutorial/debugging.md
+++ /dev/null
@@ -1,112 +0,0 @@
-# 🛠️
-
-👆 💪 🔗 🕹 👆 👨🎨, 🖼 ⏮️ 🎙 🎙 📟 ⚖️ 🗒.
-
-## 🤙 `uvicorn`
-
-👆 FastAPI 🈸, 🗄 & 🏃 `uvicorn` 🔗:
-
-```Python hl_lines="1 15"
-{!../../../docs_src/debugging/tutorial001.py!}
-```
-
-### 🔃 `__name__ == "__main__"`
-
-👑 🎯 `__name__ == "__main__"` ✔️ 📟 👈 🛠️ 🕐❔ 👆 📁 🤙 ⏮️:
-
-
-
----
-
-🚥 👆 ⚙️ 🗒, 👆 💪:
-
-* 📂 "🏃" 🍣.
-* 🖊 🎛 "ℹ...".
-* ⤴️ 🔑 🍣 🎦 🆙.
-* 🖊 📁 ℹ (👉 💼, `main.py`).
-
-⚫️ 🔜 ⤴️ ▶️ 💽 ⏮️ 👆 **FastAPI** 📟, ⛔️ 👆 0️⃣, ♒️.
-
-📥 ❔ ⚫️ 💪 👀:
-
-
diff --git a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md
deleted file mode 100644
index e2d2686d34dce..0000000000000
--- a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md
+++ /dev/null
@@ -1,247 +0,0 @@
-# 🎓 🔗
-
-⏭ 🤿 ⏬ 🔘 **🔗 💉** ⚙️, ➡️ ♻ ⏮️ 🖼.
-
-## `dict` ⚪️➡️ ⏮️ 🖼
-
-⏮️ 🖼, 👥 🛬 `dict` ⚪️➡️ 👆 🔗 ("☑"):
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
-
-✋️ ⤴️ 👥 🤚 `dict` 🔢 `commons` *➡ 🛠️ 🔢*.
-
-& 👥 💭 👈 👨🎨 💪 🚫 🚚 📚 🐕🦺 (💖 🛠️) `dict`Ⓜ, ↩️ 👫 💪 🚫 💭 👫 🔑 & 💲 🆎.
-
-👥 💪 👍...
-
-## ⚫️❔ ⚒ 🔗
-
-🆙 🔜 👆 ✔️ 👀 🔗 📣 🔢.
-
-✋️ 👈 🚫 🕴 🌌 📣 🔗 (👐 ⚫️ 🔜 🎲 🌖 ⚠).
-
-🔑 ⚖ 👈 🔗 🔜 "🇧🇲".
-
-"**🇧🇲**" 🐍 🕳 👈 🐍 💪 "🤙" 💖 🔢.
-
-, 🚥 👆 ✔️ 🎚 `something` (👈 💪 _🚫_ 🔢) & 👆 💪 "🤙" ⚫️ (🛠️ ⚫️) 💖:
-
-```Python
-something()
-```
-
-⚖️
-
-```Python
-something(some_argument, some_keyword_argument="foo")
-```
-
-⤴️ ⚫️ "🇧🇲".
-
-## 🎓 🔗
-
-👆 5️⃣📆 👀 👈 ✍ 👐 🐍 🎓, 👆 ⚙️ 👈 🎏 ❕.
-
-🖼:
-
-```Python
-class Cat:
- def __init__(self, name: str):
- self.name = name
-
-
-fluffy = Cat(name="Mr Fluffy")
-```
-
-👉 💼, `fluffy` 👐 🎓 `Cat`.
-
-& ✍ `fluffy`, 👆 "🤙" `Cat`.
-
-, 🐍 🎓 **🇧🇲**.
-
-⤴️, **FastAPI**, 👆 💪 ⚙️ 🐍 🎓 🔗.
-
-⚫️❔ FastAPI 🤙 ✅ 👈 ⚫️ "🇧🇲" (🔢, 🎓 ⚖️ 🕳 🙆) & 🔢 🔬.
-
-🚥 👆 🚶♀️ "🇧🇲" 🔗 **FastAPI**, ⚫️ 🔜 🔬 🔢 👈 "🇧🇲", & 🛠️ 👫 🎏 🌌 🔢 *➡ 🛠️ 🔢*. ✅ 🎧-🔗.
-
-👈 ✔ 🇧🇲 ⏮️ 🙅♂ 🔢 🌐. 🎏 ⚫️ 🔜 *➡ 🛠️ 🔢* ⏮️ 🙅♂ 🔢.
-
-⤴️, 👥 💪 🔀 🔗 "☑" `common_parameters` ⚪️➡️ 🔛 🎓 `CommonQueryParams`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="9-13"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
-
-💸 🙋 `__init__` 👩🔬 ⚙️ ✍ 👐 🎓:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
-
-...⚫️ ✔️ 🎏 🔢 👆 ⏮️ `common_parameters`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="6"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
-
-📚 🔢 ⚫️❔ **FastAPI** 🔜 ⚙️ "❎" 🔗.
-
-👯♂️ 💼, ⚫️ 🔜 ✔️:
-
-* 📦 `q` 🔢 🔢 👈 `str`.
-* `skip` 🔢 🔢 👈 `int`, ⏮️ 🔢 `0`.
-* `limit` 🔢 🔢 👈 `int`, ⏮️ 🔢 `100`.
-
-👯♂️ 💼 💽 🔜 🗜, ✔, 📄 🔛 🗄 🔗, ♒️.
-
-## ⚙️ ⚫️
-
-🔜 👆 💪 📣 👆 🔗 ⚙️ 👉 🎓.
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
-
-**FastAPI** 🤙 `CommonQueryParams` 🎓. 👉 ✍ "👐" 👈 🎓 & 👐 🔜 🚶♀️ 🔢 `commons` 👆 🔢.
-
-## 🆎 ✍ 🆚 `Depends`
-
-👀 ❔ 👥 ✍ `CommonQueryParams` 🕐 🔛 📟:
-
-```Python
-commons: CommonQueryParams = Depends(CommonQueryParams)
-```
-
-🏁 `CommonQueryParams`,:
-
-```Python
-... = Depends(CommonQueryParams)
-```
-
-...⚫️❔ **FastAPI** 🔜 🤙 ⚙️ 💭 ⚫️❔ 🔗.
-
-⚪️➡️ ⚫️ 👈 FastAPI 🔜 ⚗ 📣 🔢 & 👈 ⚫️❔ FastAPI 🔜 🤙 🤙.
-
----
-
-👉 💼, 🥇 `CommonQueryParams`,:
-
-```Python
-commons: CommonQueryParams ...
-```
-
-...🚫 ✔️ 🙆 🎁 🔑 **FastAPI**. FastAPI 🏆 🚫 ⚙️ ⚫️ 💽 🛠️, 🔬, ♒️. (⚫️ ⚙️ `= Depends(CommonQueryParams)` 👈).
-
-👆 💪 🤙 ✍:
-
-```Python
-commons = Depends(CommonQueryParams)
-```
-
-...:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial003_py310.py!}
- ```
-
-✋️ 📣 🆎 💡 👈 🌌 👆 👨🎨 🔜 💭 ⚫️❔ 🔜 🚶♀️ 🔢 `commons`, & ⤴️ ⚫️ 💪 ℹ 👆 ⏮️ 📟 🛠️, 🆎 ✅, ♒️:
-
-
-
-## ⌨
-
-✋️ 👆 👀 👈 👥 ✔️ 📟 🔁 📥, ✍ `CommonQueryParams` 🕐:
-
-```Python
-commons: CommonQueryParams = Depends(CommonQueryParams)
-```
-
-**FastAPI** 🚚 ⌨ 👫 💼, 🌐❔ 🔗 *🎯* 🎓 👈 **FastAPI** 🔜 "🤙" ✍ 👐 🎓 ⚫️.
-
-📚 🎯 💼, 👆 💪 📄:
-
-↩️ ✍:
-
-```Python
-commons: CommonQueryParams = Depends(CommonQueryParams)
-```
-
-...👆 ✍:
-
-```Python
-commons: CommonQueryParams = Depends()
-```
-
-👆 📣 🔗 🆎 🔢, & 👆 ⚙️ `Depends()` 🚮 "🔢" 💲 (👈 ⏮️ `=`) 👈 🔢 🔢, 🍵 🙆 🔢 `Depends()`, ↩️ ✔️ ✍ 🌕 🎓 *🔄* 🔘 `Depends(CommonQueryParams)`.
-
-🎏 🖼 🔜 ⤴️ 👀 💖:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
-
-...& **FastAPI** 🔜 💭 ⚫️❔.
-
-!!! tip
- 🚥 👈 😑 🌅 😨 🌘 👍, 🤷♂ ⚫️, 👆 🚫 *💪* ⚫️.
-
- ⚫️ ⌨. ↩️ **FastAPI** 💅 🔃 🤝 👆 📉 📟 🔁.
diff --git a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
deleted file mode 100644
index 4d54b91c77e00..0000000000000
--- a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
+++ /dev/null
@@ -1,71 +0,0 @@
-# 🔗 ➡ 🛠️ 👨🎨
-
-💼 👆 🚫 🤙 💪 📨 💲 🔗 🔘 👆 *➡ 🛠️ 🔢*.
-
-⚖️ 🔗 🚫 📨 💲.
-
-✋️ 👆 💪 ⚫️ 🛠️/❎.
-
-📚 💼, ↩️ 📣 *➡ 🛠️ 🔢* 🔢 ⏮️ `Depends`, 👆 💪 🚮 `list` `dependencies` *➡ 🛠️ 👨🎨*.
-
-## 🚮 `dependencies` *➡ 🛠️ 👨🎨*
-
-*➡ 🛠️ 👨🎨* 📨 📦 ❌ `dependencies`.
-
-⚫️ 🔜 `list` `Depends()`:
-
-```Python hl_lines="17"
-{!../../../docs_src/dependencies/tutorial006.py!}
-```
-
-👉 🔗 🔜 🛠️/❎ 🎏 🌌 😐 🔗. ✋️ 👫 💲 (🚥 👫 📨 🙆) 🏆 🚫 🚶♀️ 👆 *➡ 🛠️ 🔢*.
-
-!!! tip
- 👨🎨 ✅ ♻ 🔢 🔢, & 🎦 👫 ❌.
-
- ⚙️ 👉 `dependencies` *➡ 🛠️ 👨🎨* 👆 💪 ⚒ 💭 👫 🛠️ ⏪ ❎ 👨🎨/🏭 ❌.
-
- ⚫️ 💪 ℹ ❎ 😨 🆕 👩💻 👈 👀 ♻ 🔢 👆 📟 & 💪 💭 ⚫️ 🙃.
-
-!!! info
- 👉 🖼 👥 ⚙️ 💭 🛃 🎚 `X-Key` & `X-Token`.
-
- ✋️ 🎰 💼, 🕐❔ 🛠️ 💂♂, 👆 🔜 🤚 🌖 💰 ⚪️➡️ ⚙️ 🛠️ [💂♂ 🚙 (⏭ 📃)](../security/index.md){.internal-link target=_blank}.
-
-## 🔗 ❌ & 📨 💲
-
-👆 💪 ⚙️ 🎏 🔗 *🔢* 👆 ⚙️ 🛎.
-
-### 🔗 📄
-
-👫 💪 📣 📨 📄 (💖 🎚) ⚖️ 🎏 🎧-🔗:
-
-```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!}
-```
-
-## 🔗 👪 *➡ 🛠️*
-
-⏪, 🕐❔ 👂 🔃 ❔ 📊 🦏 🈸 ([🦏 🈸 - 💗 📁](../../tutorial/bigger-applications.md){.internal-link target=_blank}), 🎲 ⏮️ 💗 📁, 👆 🔜 💡 ❔ 📣 👁 `dependencies` 🔢 👪 *➡ 🛠️*.
-
-## 🌐 🔗
-
-⏭ 👥 🔜 👀 ❔ 🚮 🔗 🎂 `FastAPI` 🈸, 👈 👫 ✔ 🔠 *➡ 🛠️*.
diff --git a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md
deleted file mode 100644
index 9617667f43b3d..0000000000000
--- a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md
+++ /dev/null
@@ -1,219 +0,0 @@
-# 🔗 ⏮️ 🌾
-
-FastAPI 🐕🦺 🔗 👈 ➕ 🔁 ⏮️ 🏁.
-
-👉, ⚙️ `yield` ↩️ `return`, & ✍ ➕ 🔁 ⏮️.
-
-!!! tip
- ⚒ 💭 ⚙️ `yield` 1️⃣ 👁 🕰.
-
-!!! note "📡 ℹ"
- 🙆 🔢 👈 ☑ ⚙️ ⏮️:
-
- * `@contextlib.contextmanager` ⚖️
- * `@contextlib.asynccontextmanager`
-
- 🔜 ☑ ⚙️ **FastAPI** 🔗.
-
- 👐, FastAPI ⚙️ 📚 2️⃣ 👨🎨 🔘.
-
-## 💽 🔗 ⏮️ `yield`
-
-🖼, 👆 💪 ⚙️ 👉 ✍ 💽 🎉 & 🔐 ⚫️ ⏮️ 🏁.
-
-🕴 📟 ⏭ & 🔌 `yield` 📄 🛠️ ⏭ 📨 📨:
-
-```Python hl_lines="2-4"
-{!../../../docs_src/dependencies/tutorial007.py!}
-```
-
-🌾 💲 ⚫️❔ 💉 🔘 *➡ 🛠️* & 🎏 🔗:
-
-```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`
-
-🚥 👆 ⚙️ `try` 🍫 🔗 ⏮️ `yield`, 👆 🔜 📨 🙆 ⚠ 👈 🚮 🕐❔ ⚙️ 🔗.
-
-🖼, 🚥 📟 ☝ 🖕, ➕1️⃣ 🔗 ⚖️ *➡ 🛠️*, ⚒ 💽 💵 "💾" ⚖️ ✍ 🙆 🎏 ❌, 👆 🔜 📨 ⚠ 👆 🔗.
-
-, 👆 💪 👀 👈 🎯 ⚠ 🔘 🔗 ⏮️ `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 "📡 ℹ"
- 👉 👷 👏 🐍 🔑 👨💼.
-
- **FastAPI** ⚙️ 👫 🔘 🏆 👉.
-
-## 🔗 ⏮️ `yield` & `HTTPException`
-
-👆 👀 👈 👆 💪 ⚙️ 🔗 ⏮️ `yield` & ✔️ `try` 🍫 👈 ✊ ⚠.
-
-⚫️ 5️⃣📆 😋 🤚 `HTTPException` ⚖️ 🎏 🚪 📟, ⏮️ `yield`. ✋️ **⚫️ 🏆 🚫 👷**.
-
-🚪 📟 🔗 ⏮️ `yield` 🛠️ *⏮️* 📨 📨, [⚠ 🐕🦺](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} 🔜 ✔️ ⏪ 🏃. 📤 🕳 😽 ⚠ 🚮 👆 🔗 🚪 📟 (⏮️ `yield`).
-
-, 🚥 👆 🤚 `HTTPException` ⏮️ `yield`, 🔢 (⚖️ 🙆 🛃) ⚠ 🐕🦺 👈 ✊ `HTTPException`Ⓜ & 📨 🇺🇸🔍 4️⃣0️⃣0️⃣ 📨 🏆 🚫 📤 ✊ 👈 ⚠ 🚫🔜.
-
-👉 ⚫️❔ ✔ 🕳 ⚒ 🔗 (✅ 💽 🎉), 🖼, ⚙️ 🖥 📋.
-
-🖥 📋 🏃 *⏮️* 📨 ✔️ 📨. 📤 🙅♂ 🌌 🤚 `HTTPException` ↩️ 📤 🚫 🌌 🔀 📨 👈 *⏪ 📨*.
-
-✋️ 🚥 🖥 📋 ✍ 💽 ❌, 🌘 👆 💪 💾 ⚖️ 😬 🔐 🎉 🔗 ⏮️ `yield`, & 🎲 🕹 ❌ ⚖️ 📄 ⚫️ 🛰 🕵 ⚙️.
-
-🚥 👆 ✔️ 📟 👈 👆 💭 💪 🤚 ⚠, 🏆 😐/"🙃" 👜 & 🚮 `try` 🍫 👈 📄 📟.
-
-🚥 👆 ✔️ 🛃 ⚠ 👈 👆 🔜 💖 🍵 *⏭* 🛬 📨 & 🎲 ❎ 📨, 🎲 🙋♀ `HTTPException`, ✍ [🛃 ⚠ 🐕🦺](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.
-
-!!! tip
- 👆 💪 🤚 ⚠ 🔌 `HTTPException` *⏭* `yield`. ✋️ 🚫 ⏮️.
-
-🔁 🛠️ 🌅 ⚖️ 🌘 💖 👉 📊. 🕰 💧 ⚪️➡️ 🔝 🔝. & 🔠 🏓 1️⃣ 🍕 🔗 ⚖️ 🛠️ 📟.
-
-```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 -->> dep: Raise HTTPException
- dep -->> handler: Auto forward exception
- handler -->> client: HTTP error response
- operation -->> dep: Raise other exception
- dep -->> handler: Auto forward 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️⃣ 📨** 🔜 📨 👩💻. ⚫️ 💪 1️⃣ ❌ 📨 ⚖️ ⚫️ 🔜 📨 ⚪️➡️ *➡ 🛠️*.
-
- ⏮️ 1️⃣ 📚 📨 📨, 🙅♂ 🎏 📨 💪 📨.
-
-!!! tip
- 👉 📊 🎦 `HTTPException`, ✋️ 👆 💪 🤚 🙆 🎏 ⚠ ❔ 👆 ✍ [🛃 ⚠ 🐕🦺](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.
-
- 🚥 👆 🤚 🙆 ⚠, ⚫️ 🔜 🚶♀️ 🔗 ⏮️ 🌾, 🔌 `HTTPException`, & ⤴️ **🔄** ⚠ 🐕🦺. 🚥 📤 🙅♂ ⚠ 🐕🦺 👈 ⚠, ⚫️ 🔜 ⤴️ 🍵 🔢 🔗 `ServerErrorMiddleware`, 🛬 5️⃣0️⃣0️⃣ 🇺🇸🔍 👔 📟, ➡️ 👩💻 💭 👈 📤 ❌ 💽.
-
-## 🔑 👨💼
-
-### ⚫️❔ "🔑 👨💼"
-
-"🔑 👨💼" 🙆 👈 🐍 🎚 👈 👆 💪 ⚙️ `with` 📄.
-
-🖼, 👆 💪 ⚙️ `with` ✍ 📁:
-
-```Python
-with open("./somefile.txt") as f:
- contents = f.read()
- print(contents)
-```
-
-🔘, `open("./somefile.txt")` ✍ 🎚 👈 🤙 "🔑 👨💼".
-
-🕐❔ `with` 🍫 🏁, ⚫️ ⚒ 💭 🔐 📁, 🚥 📤 ⚠.
-
-🕐❔ 👆 ✍ 🔗 ⏮️ `yield`, **FastAPI** 🔜 🔘 🗜 ⚫️ 🔑 👨💼, & 🌀 ⚫️ ⏮️ 🎏 🔗 🧰.
-
-### ⚙️ 🔑 👨💼 🔗 ⏮️ `yield`
-
-!!! warning
- 👉, 🌅 ⚖️ 🌘, "🏧" 💭.
-
- 🚥 👆 ▶️ ⏮️ **FastAPI** 👆 💪 💚 🚶 ⚫️ 🔜.
-
-🐍, 👆 💪 ✍ 🔑 👨💼 🏗 🎓 ⏮️ 2️⃣ 👩🔬: `__enter__()` & `__exit__()`.
-
-👆 💪 ⚙️ 👫 🔘 **FastAPI** 🔗 ⏮️ `yield` ⚙️
-`with` ⚖️ `async with` 📄 🔘 🔗 🔢:
-
-```Python hl_lines="1-9 13"
-{!../../../docs_src/dependencies/tutorial010.py!}
-```
-
-!!! tip
- ➕1️⃣ 🌌 ✍ 🔑 👨💼 ⏮️:
-
- * `@contextlib.contextmanager` ⚖️
- * `@contextlib.asynccontextmanager`
-
- ⚙️ 👫 🎀 🔢 ⏮️ 👁 `yield`.
-
- 👈 ⚫️❔ **FastAPI** ⚙️ 🔘 🔗 ⏮️ `yield`.
-
- ✋️ 👆 🚫 ✔️ ⚙️ 👨🎨 FastAPI 🔗 (& 👆 🚫🔜 🚫).
-
- FastAPI 🔜 ⚫️ 👆 🔘.
diff --git a/docs/em/docs/tutorial/dependencies/global-dependencies.md b/docs/em/docs/tutorial/dependencies/global-dependencies.md
deleted file mode 100644
index 81759d0e83199..0000000000000
--- a/docs/em/docs/tutorial/dependencies/global-dependencies.md
+++ /dev/null
@@ -1,17 +0,0 @@
-# 🌐 🔗
-
-🆎 🈸 👆 💪 💚 🚮 🔗 🎂 🈸.
-
-🎏 🌌 👆 💪 [🚮 `dependencies` *➡ 🛠️ 👨🎨*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, 👆 💪 🚮 👫 `FastAPI` 🈸.
-
-👈 💼, 👫 🔜 ✔ 🌐 *➡ 🛠️* 🈸:
-
-```Python hl_lines="15"
-{!../../../docs_src/dependencies/tutorial012.py!}
-```
-
-& 🌐 💭 📄 🔃 [❎ `dependencies` *➡ 🛠️ 👨🎨*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} ✔, ✋️ 👉 💼, 🌐 *➡ 🛠️* 📱.
-
-## 🔗 👪 *➡ 🛠️*
-
-⏪, 🕐❔ 👂 🔃 ❔ 📊 🦏 🈸 ([🦏 🈸 - 💗 📁](../../tutorial/bigger-applications.md){.internal-link target=_blank}), 🎲 ⏮️ 💗 📁, 👆 🔜 💡 ❔ 📣 👁 `dependencies` 🔢 👪 *➡ 🛠️*.
diff --git a/docs/em/docs/tutorial/dependencies/index.md b/docs/em/docs/tutorial/dependencies/index.md
deleted file mode 100644
index ffd38d71684f3..0000000000000
--- a/docs/em/docs/tutorial/dependencies/index.md
+++ /dev/null
@@ -1,233 +0,0 @@
-# 🔗
-
-**FastAPI** ✔️ 📶 🏋️ ✋️ 🏋️ **🔗 💉** ⚙️.
-
-⚫️ 🏗 📶 🙅 ⚙️, & ⚒ ⚫️ 📶 ⏩ 🙆 👩💻 🛠️ 🎏 🦲 ⏮️ **FastAPI**.
-
-## ⚫️❔ "🔗 💉"
-
-**"🔗 💉"** ⛓, 📋, 👈 📤 🌌 👆 📟 (👉 💼, 👆 *➡ 🛠️ 🔢*) 📣 👜 👈 ⚫️ 🚚 👷 & ⚙️: "🔗".
-
-& ⤴️, 👈 ⚙️ (👉 💼 **FastAPI**) 🔜 ✊ 💅 🔨 ⚫️❔ 💪 🚚 👆 📟 ⏮️ 📚 💪 🔗 ("💉" 🔗).
-
-👉 📶 ⚠ 🕐❔ 👆 💪:
-
-* ✔️ 💰 ⚛ (🎏 📟 ⚛ 🔄 & 🔄).
-* 💰 💽 🔗.
-* 🛠️ 💂♂, 🤝, 🔑 📄, ♒️.
-* & 📚 🎏 👜...
-
-🌐 👫, ⏪ 📉 📟 🔁.
-
-## 🥇 🔁
-
-➡️ 👀 📶 🙅 🖼. ⚫️ 🔜 🙅 👈 ⚫️ 🚫 📶 ⚠, 🔜.
-
-✋️ 👉 🌌 👥 💪 🎯 🔛 ❔ **🔗 💉** ⚙️ 👷.
-
-### ✍ 🔗, ⚖️ "☑"
-
-➡️ 🥇 🎯 🔛 🔗.
-
-⚫️ 🔢 👈 💪 ✊ 🌐 🎏 🔢 👈 *➡ 🛠️ 🔢* 💪 ✊:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
-
-👈 ⚫️.
-
-**2️⃣ ⏸**.
-
-& ⚫️ ✔️ 🎏 💠 & 📊 👈 🌐 👆 *➡ 🛠️ 🔢* ✔️.
-
-👆 💪 💭 ⚫️ *➡ 🛠️ 🔢* 🍵 "👨🎨" (🍵 `@app.get("/some-path")`).
-
-& ⚫️ 💪 📨 🕳 👆 💚.
-
-👉 💼, 👉 🔗 ⌛:
-
-* 📦 🔢 🔢 `q` 👈 `str`.
-* 📦 🔢 🔢 `skip` 👈 `int`, & 🔢 `0`.
-* 📦 🔢 🔢 `limit` 👈 `int`, & 🔢 `100`.
-
-& ⤴️ ⚫️ 📨 `dict` ⚗ 📚 💲.
-
-### 🗄 `Depends`
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
-
-### 📣 🔗, "⚓️"
-
-🎏 🌌 👆 ⚙️ `Body`, `Query`, ♒️. ⏮️ 👆 *➡ 🛠️ 🔢* 🔢, ⚙️ `Depends` ⏮️ 🆕 🔢:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
-
-👐 👆 ⚙️ `Depends` 🔢 👆 🔢 🎏 🌌 👆 ⚙️ `Body`, `Query`, ♒️, `Depends` 👷 👄 🎏.
-
-👆 🕴 🤝 `Depends` 👁 🔢.
-
-👉 🔢 🔜 🕳 💖 🔢.
-
-& 👈 🔢 ✊ 🔢 🎏 🌌 👈 *➡ 🛠️ 🔢* .
-
-!!! tip
- 👆 🔜 👀 ⚫️❔ 🎏 "👜", ↖️ ⚪️➡️ 🔢, 💪 ⚙️ 🔗 ⏭ 📃.
-
-🕐❔ 🆕 📨 🛬, **FastAPI** 🔜 ✊ 💅:
-
-* 🤙 👆 🔗 ("☑") 🔢 ⏮️ ☑ 🔢.
-* 🤚 🏁 ⚪️➡️ 👆 🔢.
-* 🛠️ 👈 🏁 🔢 👆 *➡ 🛠️ 🔢*.
-
-```mermaid
-graph TB
-
-common_parameters(["common_parameters"])
-read_items["/items/"]
-read_users["/users/"]
-
-common_parameters --> read_items
-common_parameters --> read_users
-```
-
-👉 🌌 👆 ✍ 🔗 📟 🕐 & **FastAPI** ✊ 💅 🤙 ⚫️ 👆 *➡ 🛠️*.
-
-!!! check
- 👀 👈 👆 🚫 ✔️ ✍ 🎁 🎓 & 🚶♀️ ⚫️ 👱 **FastAPI** "®" ⚫️ ⚖️ 🕳 🎏.
-
- 👆 🚶♀️ ⚫️ `Depends` & **FastAPI** 💭 ❔ 🎂.
-
-## `async` ⚖️ 🚫 `async`
-
-🔗 🔜 🤙 **FastAPI** (🎏 👆 *➡ 🛠️ 🔢*), 🎏 🚫 ✔ ⏪ 🔬 👆 🔢.
-
-👆 💪 ⚙️ `async def` ⚖️ 😐 `def`.
-
-& 👆 💪 📣 🔗 ⏮️ `async def` 🔘 😐 `def` *➡ 🛠️ 🔢*, ⚖️ `def` 🔗 🔘 `async def` *➡ 🛠️ 🔢*, ♒️.
-
-⚫️ 🚫 🤔. **FastAPI** 🔜 💭 ⚫️❔.
-
-!!! note
- 🚥 👆 🚫 💭, ✅ [🔁: *"🏃 ❓" *](../../async.md){.internal-link target=_blank} 📄 🔃 `async` & `await` 🩺.
-
-## 🛠️ ⏮️ 🗄
-
-🌐 📨 📄, 🔬 & 📄 👆 🔗 (& 🎧-🔗) 🔜 🛠️ 🎏 🗄 🔗.
-
-, 🎓 🩺 🔜 ✔️ 🌐 ℹ ⚪️➡️ 👫 🔗 💁♂️:
-
-
-
-## 🙅 ⚙️
-
-🚥 👆 👀 ⚫️, *➡ 🛠️ 🔢* 📣 ⚙️ 🕐❔ *➡* & *🛠️* 🏏, & ⤴️ **FastAPI** ✊ 💅 🤙 🔢 ⏮️ ☑ 🔢, ❎ 📊 ⚪️➡️ 📨.
-
-🤙, 🌐 (⚖️ 🏆) 🕸 🛠️ 👷 👉 🎏 🌌.
-
-👆 🙅 🤙 👈 🔢 🔗. 👫 🤙 👆 🛠️ (👉 💼, **FastAPI**).
-
-⏮️ 🔗 💉 ⚙️, 👆 💪 💬 **FastAPI** 👈 👆 *➡ 🛠️ 🔢* "🪀" 🔛 🕳 🙆 👈 🔜 🛠️ ⏭ 👆 *➡ 🛠️ 🔢*, & **FastAPI** 🔜 ✊ 💅 🛠️ ⚫️ & "💉" 🏁.
-
-🎏 ⚠ ⚖ 👉 🎏 💭 "🔗 💉":
-
-* ℹ
-* 🐕🦺
-* 🐕🦺
-* 💉
-* 🦲
-
-## **FastAPI** 🔌-🔌
-
-🛠️ & "🔌-"Ⓜ 💪 🏗 ⚙️ **🔗 💉** ⚙️. ✋️ 👐, 📤 🤙 **🙅♂ 💪 ✍ "🔌-🔌"**, ⚙️ 🔗 ⚫️ 💪 📣 ♾ 🔢 🛠️ & 🔗 👈 ▶️️ 💪 👆 *➡ 🛠️ 🔢*.
-
-& 🔗 💪 ✍ 📶 🙅 & 🏋️ 🌌 👈 ✔ 👆 🗄 🐍 📦 👆 💪, & 🛠️ 👫 ⏮️ 👆 🛠️ 🔢 👩❤👨 ⏸ 📟, *🌖*.
-
-👆 🔜 👀 🖼 👉 ⏭ 📃, 🔃 🔗 & ☁ 💽, 💂♂, ♒️.
-
-## **FastAPI** 🔗
-
-🦁 🔗 💉 ⚙️ ⚒ **FastAPI** 🔗 ⏮️:
-
-* 🌐 🔗 💽
-* ☁ 💽
-* 🔢 📦
-* 🔢 🔗
-* 🤝 & ✔ ⚙️
-* 🛠️ ⚙️ ⚖ ⚙️
-* 📨 💽 💉 ⚙️
-* ♒️.
-
-## 🙅 & 🏋️
-
-👐 🔗 🔗 💉 ⚙️ 📶 🙅 🔬 & ⚙️, ⚫️ 📶 🏋️.
-
-👆 💪 🔬 🔗 👈 🔄 💪 🔬 🔗 👫.
-
-🔚, 🔗 🌲 🔗 🏗, & **🔗 💉** ⚙️ ✊ 💅 🔬 🌐 👉 🔗 👆 (& 👫 🎧-🔗) & 🚚 (💉) 🏁 🔠 🔁.
-
-🖼, ➡️ 💬 👆 ✔️ 4️⃣ 🛠️ 🔗 (*➡ 🛠️*):
-
-* `/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
-```
-
-## 🛠️ ⏮️ **🗄**
-
-🌐 👫 🔗, ⏪ 📣 👫 📄, 🚮 🔢, 🔬, ♒️. 👆 *➡ 🛠️*.
-
-**FastAPI** 🔜 ✊ 💅 🚮 ⚫️ 🌐 🗄 🔗, 👈 ⚫️ 🎦 🎓 🧾 ⚙️.
diff --git a/docs/em/docs/tutorial/dependencies/sub-dependencies.md b/docs/em/docs/tutorial/dependencies/sub-dependencies.md
deleted file mode 100644
index 454ff51298b59..0000000000000
--- a/docs/em/docs/tutorial/dependencies/sub-dependencies.md
+++ /dev/null
@@ -1,110 +0,0 @@
-# 🎧-🔗
-
-👆 💪 ✍ 🔗 👈 ✔️ **🎧-🔗**.
-
-👫 💪 **⏬** 👆 💪 👫.
-
-**FastAPI** 🔜 ✊ 💅 🔬 👫.
-
-## 🥇 🔗 "☑"
-
-👆 💪 ✍ 🥇 🔗 ("☑") 💖:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
-
-⚫️ 📣 📦 🔢 🔢 `q` `str`, & ⤴️ ⚫️ 📨 ⚫️.
-
-👉 🙅 (🚫 📶 ⚠), ✋️ 🔜 ℹ 👥 🎯 🔛 ❔ 🎧-🔗 👷.
-
-## 🥈 🔗, "☑" & "⚓️"
-
-⤴️ 👆 💪 ✍ ➕1️⃣ 🔗 🔢 ("☑") 👈 🎏 🕰 📣 🔗 🚮 👍 (⚫️ "⚓️" 💁♂️):
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
-
-➡️ 🎯 🔛 🔢 📣:
-
-* ✋️ 👉 🔢 🔗 ("☑") ⚫️, ⚫️ 📣 ➕1️⃣ 🔗 (⚫️ "🪀" 🔛 🕳 🙆).
- * ⚫️ 🪀 🔛 `query_extractor`, & 🛠️ 💲 📨 ⚫️ 🔢 `q`.
-* ⚫️ 📣 📦 `last_query` 🍪, `str`.
- * 🚥 👩💻 🚫 🚚 🙆 🔢 `q`, 👥 ⚙️ 🏁 🔢 ⚙️, ❔ 👥 🖊 🍪 ⏭.
-
-## ⚙️ 🔗
-
-⤴️ 👥 💪 ⚙️ 🔗 ⏮️:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
-
-!!! info
- 👀 👈 👥 🕴 📣 1️⃣ 🔗 *➡ 🛠️ 🔢*, `query_or_cookie_extractor`.
-
- ✋️ **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️⃣ 👆 🔗 📣 💗 🕰 🎏 *➡ 🛠️*, 🖼, 💗 🔗 ✔️ ⚠ 🎧-🔗, **FastAPI** 🔜 💭 🤙 👈 🎧-🔗 🕴 🕐 📍 📨.
-
-& ⚫️ 🔜 🖊 📨 💲 "💾" & 🚶♀️ ⚫️ 🌐 "⚓️" 👈 💪 ⚫️ 👈 🎯 📨, ↩️ 🤙 🔗 💗 🕰 🎏 📨.
-
-🏧 😐 🌐❔ 👆 💭 👆 💪 🔗 🤙 🔠 🔁 (🎲 💗 🕰) 🎏 📨 ↩️ ⚙️ "💾" 💲, 👆 💪 ⚒ 🔢 `use_cache=False` 🕐❔ ⚙️ `Depends`:
-
-```Python hl_lines="1"
-async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
- return {"fresh_value": fresh_value}
-```
-
-## 🌃
-
-↖️ ⚪️➡️ 🌐 🎀 🔤 ⚙️ 📥, **🔗 💉** ⚙️ 🙅.
-
-🔢 👈 👀 🎏 *➡ 🛠️ 🔢*.
-
-✋️, ⚫️ 📶 🏋️, & ✔ 👆 📣 🎲 🙇 🐦 🔗 "📊" (🌲).
-
-!!! tip
- 🌐 👉 💪 🚫 😑 ⚠ ⏮️ 👫 🙅 🖼.
-
- ✋️ 👆 🔜 👀 ❔ ⚠ ⚫️ 📃 🔃 **💂♂**.
-
- & 👆 🔜 👀 💸 📟 ⚫️ 🔜 🖊 👆.
diff --git a/docs/em/docs/tutorial/encoder.md b/docs/em/docs/tutorial/encoder.md
deleted file mode 100644
index 75ca3824da9ff..0000000000000
--- a/docs/em/docs/tutorial/encoder.md
+++ /dev/null
@@ -1,42 +0,0 @@
-# 🎻 🔗 🔢
-
-📤 💼 🌐❔ 👆 5️⃣📆 💪 🗜 💽 🆎 (💖 Pydantic 🏷) 🕳 🔗 ⏮️ 🎻 (💖 `dict`, `list`, ♒️).
-
-🖼, 🚥 👆 💪 🏪 ⚫️ 💽.
-
-👈, **FastAPI** 🚚 `jsonable_encoder()` 🔢.
-
-## ⚙️ `jsonable_encoder`
-
-➡️ 🌈 👈 👆 ✔️ 💽 `fake_db` 👈 🕴 📨 🎻 🔗 💽.
-
-🖼, ⚫️ 🚫 📨 `datetime` 🎚, 👈 🚫 🔗 ⏮️ 🎻.
-
-, `datetime` 🎚 🔜 ✔️ 🗜 `str` ⚗ 💽 💾 📁.
-
-🎏 🌌, 👉 💽 🚫🔜 📨 Pydantic 🏷 (🎚 ⏮️ 🔢), 🕴 `dict`.
-
-👆 💪 ⚙️ `jsonable_encoder` 👈.
-
-⚫️ 📨 🎚, 💖 Pydantic 🏷, & 📨 🎻 🔗 ⏬:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="5 22"
- {!> ../../../docs_src/encoder/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="4 21"
- {!> ../../../docs_src/encoder/tutorial001_py310.py!}
- ```
-
-👉 🖼, ⚫️ 🔜 🗜 Pydantic 🏷 `dict`, & `datetime` `str`.
-
-🏁 🤙 ⚫️ 🕳 👈 💪 🗜 ⏮️ 🐍 🐩 `json.dumps()`.
-
-⚫️ 🚫 📨 ⭕ `str` ⚗ 💽 🎻 📁 (🎻). ⚫️ 📨 🐍 🐩 💽 📊 (✅ `dict`) ⏮️ 💲 & 🎧-💲 👈 🌐 🔗 ⏮️ 🎻.
-
-!!! note
- `jsonable_encoder` 🤙 ⚙️ **FastAPI** 🔘 🗜 💽. ✋️ ⚫️ ⚠ 📚 🎏 😐.
diff --git a/docs/em/docs/tutorial/extra-data-types.md b/docs/em/docs/tutorial/extra-data-types.md
deleted file mode 100644
index dfdf6141b8ee1..0000000000000
--- a/docs/em/docs/tutorial/extra-data-types.md
+++ /dev/null
@@ -1,82 +0,0 @@
-# ➕ 💽 🆎
-
-🆙 🔜, 👆 ✔️ ⚙️ ⚠ 📊 🆎, 💖:
-
-* `int`
-* `float`
-* `str`
-* `bool`
-
-✋️ 👆 💪 ⚙️ 🌅 🏗 📊 🆎.
-
-& 👆 🔜 ✔️ 🎏 ⚒ 👀 🆙 🔜:
-
-* 👑 👨🎨 🐕🦺.
-* 💽 🛠️ ⚪️➡️ 📨 📨.
-* 💽 🛠️ 📨 💽.
-* 💽 🔬.
-* 🏧 ✍ & 🧾.
-
-## 🎏 💽 🆎
-
-📥 🌖 📊 🆎 👆 💪 ⚙️:
-
-* `UUID`:
- * 🐩 "⭐ 😍 🆔", ⚠ 🆔 📚 💽 & ⚙️.
- * 📨 & 📨 🔜 🎨 `str`.
-* `datetime.datetime`:
- * 🐍 `datetime.datetime`.
- * 📨 & 📨 🔜 🎨 `str` 💾 8️⃣6️⃣0️⃣1️⃣ 📁, 💖: `2008-09-15T15:53:00+05:00`.
-* `datetime.date`:
- * 🐍 `datetime.date`.
- * 📨 & 📨 🔜 🎨 `str` 💾 8️⃣6️⃣0️⃣1️⃣ 📁, 💖: `2008-09-15`.
-* `datetime.time`:
- * 🐍 `datetime.time`.
- * 📨 & 📨 🔜 🎨 `str` 💾 8️⃣6️⃣0️⃣1️⃣ 📁, 💖: `14:23:55.003`.
-* `datetime.timedelta`:
- * 🐍 `datetime.timedelta`.
- * 📨 & 📨 🔜 🎨 `float` 🌐 🥈.
- * Pydantic ✔ 🎦 ⚫️ "💾 8️⃣6️⃣0️⃣1️⃣ 🕰 ➕ 🔢", 👀 🩺 🌅 ℹ.
-* `frozenset`:
- * 📨 & 📨, 😥 🎏 `set`:
- * 📨, 📇 🔜 ✍, ❎ ❎ & 🏭 ⚫️ `set`.
- * 📨, `set` 🔜 🗜 `list`.
- * 🏗 🔗 🔜 ✔ 👈 `set` 💲 😍 (⚙️ 🎻 🔗 `uniqueItems`).
-* `bytes`:
- * 🐩 🐍 `bytes`.
- * 📨 & 📨 🔜 😥 `str`.
- * 🏗 🔗 🔜 ✔ 👈 ⚫️ `str` ⏮️ `binary` "📁".
-* `Decimal`:
- * 🐩 🐍 `Decimal`.
- * 📨 & 📨, 🍵 🎏 `float`.
-* 👆 💪 ✅ 🌐 ☑ Pydantic 📊 🆎 📥: Pydantic 📊 🆎.
-
-## 🖼
-
-📥 🖼 *➡ 🛠️* ⏮️ 🔢 ⚙️ 🔛 🆎.
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="1 2 11-15"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
-
-🗒 👈 🔢 🔘 🔢 ✔️ 👫 🐠 💽 🆎, & 👆 💪, 🖼, 🎭 😐 📅 🎭, 💖:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
diff --git a/docs/em/docs/tutorial/extra-models.md b/docs/em/docs/tutorial/extra-models.md
deleted file mode 100644
index 06c36285d3392..0000000000000
--- a/docs/em/docs/tutorial/extra-models.md
+++ /dev/null
@@ -1,252 +0,0 @@
-# ➕ 🏷
-
-▶️ ⏮️ ⏮️ 🖼, ⚫️ 🔜 ⚠ ✔️ 🌅 🌘 1️⃣ 🔗 🏷.
-
-👉 ✴️ 💼 👩💻 🏷, ↩️:
-
-* **🔢 🏷** 💪 💪 ✔️ 🔐.
-* **🔢 🏷** 🔜 🚫 ✔️ 🔐.
-* **💽 🏷** 🔜 🎲 💪 ✔️ #️⃣ 🔐.
-
-!!! danger
- 🙅 🏪 👩💻 🔢 🔐. 🕧 🏪 "🔐 #️⃣" 👈 👆 💪 ⤴️ ✔.
-
- 🚥 👆 🚫 💭, 👆 🔜 💡 ⚫️❔ "🔐#️⃣" [💂♂ 📃](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}.
-
-## 💗 🏷
-
-📥 🏢 💭 ❔ 🏷 💪 👀 💖 ⏮️ 👫 🔐 🏑 & 🥉 🌐❔ 👫 ⚙️:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
- {!> ../../../docs_src/extra_models/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
- {!> ../../../docs_src/extra_models/tutorial001_py310.py!}
- ```
-
-### 🔃 `**user_in.dict()`
-
-#### Pydantic `.dict()`
-
-`user_in` Pydantic 🏷 🎓 `UserIn`.
-
-Pydantic 🏷 ✔️ `.dict()` 👩🔬 👈 📨 `dict` ⏮️ 🏷 💽.
-
-, 🚥 👥 ✍ Pydantic 🎚 `user_in` 💖:
-
-```Python
-user_in = UserIn(username="john", password="secret", email="john.doe@example.com")
-```
-
-& ⤴️ 👥 🤙:
-
-```Python
-user_dict = user_in.dict()
-```
-
-👥 🔜 ✔️ `dict` ⏮️ 💽 🔢 `user_dict` (⚫️ `dict` ↩️ Pydantic 🏷 🎚).
-
-& 🚥 👥 🤙:
-
-```Python
-print(user_dict)
-```
-
-👥 🔜 🤚 🐍 `dict` ⏮️:
-
-```Python
-{
- 'username': 'john',
- 'password': 'secret',
- 'email': 'john.doe@example.com',
- 'full_name': None,
-}
-```
-
-#### 🎁 `dict`
-
-🚥 👥 ✊ `dict` 💖 `user_dict` & 🚶♀️ ⚫️ 🔢 (⚖️ 🎓) ⏮️ `**user_dict`, 🐍 🔜 "🎁" ⚫️. ⚫️ 🔜 🚶♀️ 🔑 & 💲 `user_dict` 🔗 🔑-💲 ❌.
-
-, ▶️ ⏮️ `user_dict` ⚪️➡️ 🔛, ✍:
-
-```Python
-UserInDB(**user_dict)
-```
-
-🔜 🏁 🕳 🌓:
-
-```Python
-UserInDB(
- username="john",
- password="secret",
- email="john.doe@example.com",
- 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 🏷 ⚪️➡️ 🎚 ➕1️⃣
-
-🖼 🔛 👥 🤚 `user_dict` ⚪️➡️ `user_in.dict()`, 👉 📟:
-
-```Python
-user_dict = user_in.dict()
-UserInDB(**user_dict)
-```
-
-🔜 🌓:
-
-```Python
-UserInDB(**user_in.dict())
-```
-
-...↩️ `user_in.dict()` `dict`, & ⤴️ 👥 ⚒ 🐍 "🎁" ⚫️ 🚶♀️ ⚫️ `UserInDB` 🔠 ⏮️ `**`.
-
-, 👥 🤚 Pydantic 🏷 ⚪️➡️ 💽 ➕1️⃣ 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
- 🔗 🌖 🔢 🤖 💪 💧 💽, ✋️ 👫 ↗️ 🚫 🚚 🙆 🎰 💂♂.
-
-## 📉 ❎
-
-📉 📟 ❎ 1️⃣ 🐚 💭 **FastAPI**.
-
-📟 ❎ 📈 🤞 🐛, 💂♂ ❔, 📟 🔁 ❔ (🕐❔ 👆 ℹ 1️⃣ 🥉 ✋️ 🚫 🎏), ♒️.
-
-& 👉 🏷 🌐 🤝 📚 💽 & ❎ 🔢 📛 & 🆎.
-
-👥 💪 👻.
-
-👥 💪 📣 `UserBase` 🏷 👈 🍦 🧢 👆 🎏 🏷. & ⤴️ 👥 💪 ⚒ 🏿 👈 🏷 👈 😖 🚮 🔢 (🆎 📄, 🔬, ♒️).
-
-🌐 💽 🛠️, 🔬, 🧾, ♒️. 🔜 👷 🛎.
-
-👈 🌌, 👥 💪 📣 🔺 🖖 🏷 (⏮️ 🔢 `password`, ⏮️ `hashed_password` & 🍵 🔐):
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9 15-16 19-20 23-24"
- {!> ../../../docs_src/extra_models/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7 13-14 17-18 21-22"
- {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
- ```
-
-## `Union` ⚖️ `anyOf`
-
-👆 💪 📣 📨 `Union` 2️⃣ 🆎, 👈 ⛓, 👈 📨 🔜 🙆 2️⃣.
-
-⚫️ 🔜 🔬 🗄 ⏮️ `anyOf`.
-
-👈, ⚙️ 🐩 🐍 🆎 🔑 `typing.Union`:
-
-!!! note
- 🕐❔ ⚖ `Union`, 🔌 🏆 🎯 🆎 🥇, ⏩ 🌘 🎯 🆎. 🖼 🔛, 🌖 🎯 `PlaneItem` 👟 ⏭ `CarItem` `Union[PlaneItem, CarItem]`.
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003_py310.py!}
- ```
-
-### `Union` 🐍 3️⃣.1️⃣0️⃣
-
-👉 🖼 👥 🚶♀️ `Union[PlaneItem, CarItem]` 💲 ❌ `response_model`.
-
-↩️ 👥 🚶♀️ ⚫️ **💲 ❌** ↩️ 🚮 ⚫️ **🆎 ✍**, 👥 ✔️ ⚙️ `Union` 🐍 3️⃣.1️⃣0️⃣.
-
-🚥 ⚫️ 🆎 ✍ 👥 💪 ✔️ ⚙️ ⏸ ⏸,:
-
-```Python
-some_variable: PlaneItem | CarItem
-```
-
-✋️ 🚥 👥 🚮 👈 `response_model=PlaneItem | CarItem` 👥 🔜 🤚 ❌, ↩️ 🐍 🔜 🔄 🎭 **❌ 🛠️** 🖖 `PlaneItem` & `CarItem` ↩️ 🔬 👈 🆎 ✍.
-
-## 📇 🏷
-
-🎏 🌌, 👆 💪 📣 📨 📇 🎚.
-
-👈, ⚙️ 🐩 🐍 `typing.List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛):
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="1 20"
- {!> ../../../docs_src/extra_models/tutorial004.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/extra_models/tutorial004_py39.py!}
- ```
-
-## 📨 ⏮️ ❌ `dict`
-
-👆 💪 📣 📨 ⚙️ ✅ ❌ `dict`, 📣 🆎 🔑 & 💲, 🍵 ⚙️ Pydantic 🏷.
-
-👉 ⚠ 🚥 👆 🚫 💭 ☑ 🏑/🔢 📛 (👈 🔜 💪 Pydantic 🏷) ⏪.
-
-👉 💼, 👆 💪 ⚙️ `typing.Dict` (⚖️ `dict` 🐍 3️⃣.9️⃣ & 🔛):
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="1 8"
- {!> ../../../docs_src/extra_models/tutorial005.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="6"
- {!> ../../../docs_src/extra_models/tutorial005_py39.py!}
- ```
-
-## 🌃
-
-⚙️ 💗 Pydantic 🏷 & 😖 ➡ 🔠 💼.
-
-👆 🚫 💪 ✔️ 👁 💽 🏷 📍 👨💼 🚥 👈 👨💼 🔜 💪 ✔️ 🎏 "🇵🇸". 💼 ⏮️ 👩💻 "👨💼" ⏮️ 🇵🇸 ✅ `password`, `password_hash` & 🙅♂ 🔐.
diff --git a/docs/em/docs/tutorial/first-steps.md b/docs/em/docs/tutorial/first-steps.md
deleted file mode 100644
index 252e769f41a35..0000000000000
--- a/docs/em/docs/tutorial/first-steps.md
+++ /dev/null
@@ -1,333 +0,0 @@
-# 🥇 🔁
-
-🙅 FastAPI 📁 💪 👀 💖 👉:
-
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
-
-📁 👈 📁 `main.py`.
-
-🏃 🖖 💽:
-
-get 🛠️
-
-!!! info "`@decorator` ℹ"
- 👈 `@something` ❕ 🐍 🤙 "👨🎨".
-
- 👆 🚮 ⚫️ 🔛 🔝 🔢. 💖 📶 📔 👒 (👤 💭 👈 🌐❔ ⚖ 👟 ⚪️➡️).
-
- "👨🎨" ✊ 🔢 🔛 & 🔨 🕳 ⏮️ ⚫️.
-
- 👆 💼, 👉 👨🎨 💬 **FastAPI** 👈 🔢 🔛 🔗 **➡** `/` ⏮️ **🛠️** `get`.
-
- ⚫️ "**➡ 🛠️ 👨🎨**".
-
-👆 💪 ⚙️ 🎏 🛠️:
-
-* `@app.post()`
-* `@app.put()`
-* `@app.delete()`
-
-& 🌅 😍 🕐:
-
-* `@app.options()`
-* `@app.head()`
-* `@app.patch()`
-* `@app.trace()`
-
-!!! tip
- 👆 🆓 ⚙️ 🔠 🛠️ (🇺🇸🔍 👩🔬) 👆 🎋.
-
- **FastAPI** 🚫 🛠️ 🙆 🎯 🔑.
-
- ℹ 📥 🎁 📄, 🚫 📄.
-
- 🖼, 🕐❔ ⚙️ 🕹 👆 🛎 🎭 🌐 🎯 ⚙️ 🕴 `POST` 🛠️.
-
-### 🔁 4️⃣: 🔬 **➡ 🛠️ 🔢**
-
-👉 👆 "**➡ 🛠️ 🔢**":
-
-* **➡**: `/`.
-* **🛠️**: `get`.
-* **🔢**: 🔢 🔛 "👨🎨" (🔛 `@app.get("/")`).
-
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
-
-👉 🐍 🔢.
-
-⚫️ 🔜 🤙 **FastAPI** 🕐❔ ⚫️ 📨 📨 📛 "`/`" ⚙️ `GET` 🛠️.
-
-👉 💼, ⚫️ `async` 🔢.
-
----
-
-👆 💪 🔬 ⚫️ 😐 🔢 ↩️ `async def`:
-
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
-
-!!! note
- 🚥 👆 🚫 💭 🔺, ✅ [🔁: *"🏃 ❓"*](../async.md#in-a-hurry){.internal-link target=_blank}.
-
-### 🔁 5️⃣: 📨 🎚
-
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
-
-👆 💪 📨 `dict`, `list`, ⭐ 💲 `str`, `int`, ♒️.
-
-👆 💪 📨 Pydantic 🏷 (👆 🔜 👀 🌅 🔃 👈 ⏪).
-
-📤 📚 🎏 🎚 & 🏷 👈 🔜 🔁 🗜 🎻 (🔌 🐜, ♒️). 🔄 ⚙️ 👆 💕 🕐, ⚫️ 🏆 🎲 👈 👫 ⏪ 🐕🦺.
-
-## 🌃
-
-* 🗄 `FastAPI`.
-* ✍ `app` 👐.
-* ✍ **➡ 🛠️ 👨🎨** (💖 `@app.get("/")`).
-* ✍ **➡ 🛠️ 🔢** (💖 `def root(): ...` 🔛).
-* 🏃 🛠️ 💽 (💖 `uvicorn main:app --reload`).
diff --git a/docs/em/docs/tutorial/handling-errors.md b/docs/em/docs/tutorial/handling-errors.md
deleted file mode 100644
index ef7bbfa6516fb..0000000000000
--- a/docs/em/docs/tutorial/handling-errors.md
+++ /dev/null
@@ -1,261 +0,0 @@
-# 🚚 ❌
-
-📤 📚 ⚠ 🌐❔ 👆 💪 🚨 ❌ 👩💻 👈 ⚙️ 👆 🛠️.
-
-👉 👩💻 💪 🖥 ⏮️ 🕸, 📟 ⚪️➡️ 👱 🙆, ☁ 📳, ♒️.
-
-👆 💪 💪 💬 👩💻 👈:
-
-* 👩💻 🚫 ✔️ 🥃 😌 👈 🛠️.
-* 👩💻 🚫 ✔️ 🔐 👈 ℹ.
-* 🏬 👩💻 🔄 🔐 🚫 🔀.
-* ♒️.
-
-👫 💼, 👆 🔜 🛎 📨 **🇺🇸🔍 👔 📟** ↔ **4️⃣0️⃣0️⃣** (⚪️➡️ 4️⃣0️⃣0️⃣ 4️⃣9️⃣9️⃣).
-
-👉 🎏 2️⃣0️⃣0️⃣ 🇺🇸🔍 👔 📟 (⚪️➡️ 2️⃣0️⃣0️⃣ 2️⃣9️⃣9️⃣). 👈 "2️⃣0️⃣0️⃣" 👔 📟 ⛓ 👈 😫 📤 "🏆" 📨.
-
-👔 📟 4️⃣0️⃣0️⃣ ↔ ⛓ 👈 📤 ❌ ⚪️➡️ 👩💻.
-
-💭 🌐 👈 **"4️⃣0️⃣4️⃣ 🚫 🔎"** ❌ (& 🤣) ❓
-
-## ⚙️ `HTTPException`
-
-📨 🇺🇸🔍 📨 ⏮️ ❌ 👩💻 👆 ⚙️ `HTTPException`.
-
-### 🗄 `HTTPException`
-
-```Python hl_lines="1"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-```
-
-### 🤚 `HTTPException` 👆 📟
-
-`HTTPException` 😐 🐍 ⚠ ⏮️ 🌖 📊 🔗 🔗.
-
-↩️ ⚫️ 🐍 ⚠, 👆 🚫 `return` ⚫️, 👆 `raise` ⚫️.
-
-👉 ⛓ 👈 🚥 👆 🔘 🚙 🔢 👈 👆 🤙 🔘 👆 *➡ 🛠️ 🔢*, & 👆 🤚 `HTTPException` ⚪️➡️ 🔘 👈 🚙 🔢, ⚫️ 🏆 🚫 🏃 🎂 📟 *➡ 🛠️ 🔢*, ⚫️ 🔜 ❎ 👈 📨 ▶️️ ↖️ & 📨 🇺🇸🔍 ❌ ⚪️➡️ `HTTPException` 👩💻.
-
-💰 🙋♀ ⚠ 🤭 `return`😅 💲 🔜 🌖 ⭐ 📄 🔃 🔗 & 💂♂.
-
-👉 🖼, 🕐❔ 👩💻 📨 🏬 🆔 👈 🚫 🔀, 🤚 ⚠ ⏮️ 👔 📟 `404`:
-
-```Python hl_lines="11"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-```
-
-### 📉 📨
-
-🚥 👩💻 📨 `http://example.com/items/foo` ( `item_id` `"foo"`), 👈 👩💻 🔜 📨 🇺🇸🔍 👔 📟 2️⃣0️⃣0️⃣, & 🎻 📨:
-
-```JSON
-{
- "item": "The Foo Wrestlers"
-}
-```
-
-✋️ 🚥 👩💻 📨 `http://example.com/items/bar` (🚫-🚫 `item_id` `"bar"`), 👈 👩💻 🔜 📨 🇺🇸🔍 👔 📟 4️⃣0️⃣4️⃣ ("🚫 🔎" ❌), & 🎻 📨:
-
-```JSON
-{
- "detail": "Item not found"
-}
-```
-
-!!! tip
- 🕐❔ 🙋♀ `HTTPException`, 👆 💪 🚶♀️ 🙆 💲 👈 💪 🗜 🎻 🔢 `detail`, 🚫 🕴 `str`.
-
- 👆 💪 🚶♀️ `dict`, `list`, ♒️.
-
- 👫 🍵 🔁 **FastAPI** & 🗜 🎻.
-
-## 🚮 🛃 🎚
-
-📤 ⚠ 🌐❔ ⚫️ ⚠ 💪 🚮 🛃 🎚 🇺🇸🔍 ❌. 🖼, 🆎 💂♂.
-
-👆 🎲 🏆 🚫 💪 ⚙️ ⚫️ 🔗 👆 📟.
-
-✋️ 💼 👆 💪 ⚫️ 🏧 😐, 👆 💪 🚮 🛃 🎚:
-
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial002.py!}
-```
-
-## ❎ 🛃 ⚠ 🐕🦺
-
-👆 💪 🚮 🛃 ⚠ 🐕🦺 ⏮️ 🎏 ⚠ 🚙 ⚪️➡️ 💃.
-
-➡️ 💬 👆 ✔️ 🛃 ⚠ `UnicornException` 👈 👆 (⚖️ 🗃 👆 ⚙️) 💪 `raise`.
-
-& 👆 💚 🍵 👉 ⚠ 🌐 ⏮️ FastAPI.
-
-👆 💪 🚮 🛃 ⚠ 🐕🦺 ⏮️ `@app.exception_handler()`:
-
-```Python hl_lines="5-7 13-18 24"
-{!../../../docs_src/handling_errors/tutorial003.py!}
-```
-
-📥, 🚥 👆 📨 `/unicorns/yolo`, *➡ 🛠️* 🔜 `raise` `UnicornException`.
-
-✋️ ⚫️ 🔜 🍵 `unicorn_exception_handler`.
-
-, 👆 🔜 📨 🧹 ❌, ⏮️ 🇺🇸🔍 👔 📟 `418` & 🎻 🎚:
-
-```JSON
-{"message": "Oops! yolo did something. There goes a rainbow..."}
-```
-
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.requests import Request` & `from starlette.responses import JSONResponse`.
-
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `Request`.
-
-## 🔐 🔢 ⚠ 🐕🦺
-
-**FastAPI** ✔️ 🔢 ⚠ 🐕🦺.
-
-👫 🐕🦺 🈚 🛬 🔢 🎻 📨 🕐❔ 👆 `raise` `HTTPException` & 🕐❔ 📨 ✔️ ❌ 💽.
-
-👆 💪 🔐 👫 ⚠ 🐕🦺 ⏮️ 👆 👍.
-
-### 🔐 📨 🔬 ⚠
-
-🕐❔ 📨 🔌 ❌ 📊, **FastAPI** 🔘 🤚 `RequestValidationError`.
-
-& ⚫️ 🔌 🔢 ⚠ 🐕🦺 ⚫️.
-
-🔐 ⚫️, 🗄 `RequestValidationError` & ⚙️ ⚫️ ⏮️ `@app.exception_handler(RequestValidationError)` 🎀 ⚠ 🐕🦺.
-
-⚠ 🐕🦺 🔜 📨 `Request` & ⚠.
-
-```Python hl_lines="2 14-16"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-```
-
-🔜, 🚥 👆 🚶 `/items/foo`, ↩️ 💆♂ 🔢 🎻 ❌ ⏮️:
-
-```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 `ValidationError`.
-
-**FastAPI** ⚙️ ⚫️ 👈, 🚥 👆 ⚙️ Pydantic 🏷 `response_model`, & 👆 💽 ✔️ ❌, 👆 🔜 👀 ❌ 👆 🕹.
-
-✋️ 👩💻/👩💻 🔜 🚫 👀 ⚫️. ↩️, 👩💻 🔜 📨 "🔗 💽 ❌" ⏮️ 🇺🇸🔍 👔 📟 `500`.
-
-⚫️ 🔜 👉 🌌 ↩️ 🚥 👆 ✔️ Pydantic `ValidationError` 👆 *📨* ⚖️ 🙆 👆 📟 (🚫 👩💻 *📨*), ⚫️ 🤙 🐛 👆 📟.
-
-& ⏪ 👆 🔧 ⚫️, 👆 👩💻/👩💻 🚫🔜 🚫 ✔️ 🔐 🔗 ℹ 🔃 ❌, 👈 💪 🎦 💂♂ ⚠.
-
-### 🔐 `HTTPException` ❌ 🐕🦺
-
-🎏 🌌, 👆 💪 🔐 `HTTPException` 🐕🦺.
-
-🖼, 👆 💪 💚 📨 ✅ ✍ 📨 ↩️ 🎻 👫 ❌:
-
-```Python hl_lines="3-4 9-11 22"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-```
-
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import PlainTextResponse`.
-
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
-
-### ⚙️ `RequestValidationError` 💪
-
-`RequestValidationError` 🔌 `body` ⚫️ 📨 ⏮️ ❌ 💽.
-
-👆 💪 ⚙️ ⚫️ ⏪ 🛠️ 👆 📱 🕹 💪 & ℹ ⚫️, 📨 ⚫️ 👩💻, ♒️.
-
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial005.py!}
-```
-
-🔜 🔄 📨 ❌ 🏬 💖:
-
-```JSON
-{
- "title": "towel",
- "size": "XL"
-}
-```
-
-👆 🔜 📨 📨 💬 👆 👈 💽 ❌ ⚗ 📨 💪:
-
-```JSON hl_lines="12-15"
-{
- "detail": [
- {
- "loc": [
- "body",
- "size"
- ],
- "msg": "value is not a valid integer",
- "type": "type_error.integer"
- }
- ],
- "body": {
- "title": "towel",
- "size": "XL"
- }
-}
-```
-
-#### FastAPI `HTTPException` 🆚 💃 `HTTPException`
-
-**FastAPI** ✔️ 🚮 👍 `HTTPException`.
-
-& **FastAPI**'Ⓜ `HTTPException` ❌ 🎓 😖 ⚪️➡️ 💃 `HTTPException` ❌ 🎓.
-
-🕴 🔺, 👈 **FastAPI**'Ⓜ `HTTPException` ✔ 👆 🚮 🎚 🔌 📨.
-
-👉 💪/⚙️ 🔘 ✳ 2️⃣.0️⃣ & 💂♂ 🚙.
-
-, 👆 💪 🚧 🙋♀ **FastAPI**'Ⓜ `HTTPException` 🛎 👆 📟.
-
-✋️ 🕐❔ 👆 ® ⚠ 🐕🦺, 👆 🔜 ® ⚫️ 💃 `HTTPException`.
-
-👉 🌌, 🚥 🙆 🍕 💃 🔗 📟, ⚖️ 💃 ↔ ⚖️ 🔌 -, 🤚 💃 `HTTPException`, 👆 🐕🦺 🔜 💪 ✊ & 🍵 ⚫️.
-
-👉 🖼, 💪 ✔️ 👯♂️ `HTTPException`Ⓜ 🎏 📟, 💃 ⚠ 📁 `StarletteHTTPException`:
-
-```Python
-from starlette.exceptions import HTTPException as StarletteHTTPException
-```
-
-### 🏤-⚙️ **FastAPI**'Ⓜ ⚠ 🐕🦺
-
-🚥 👆 💚 ⚙️ ⚠ ⤴️ ⏮️ 🎏 🔢 ⚠ 🐕🦺 ⚪️➡️ **FastAPI**, 👆 💪 🗄 & 🏤-⚙️ 🔢 ⚠ 🐕🦺 ⚪️➡️ `fastapi.exception_handlers`:
-
-```Python hl_lines="2-5 15 21"
-{!../../../docs_src/handling_errors/tutorial006.py!}
-```
-
-👉 🖼 👆 `print`😅 ❌ ⏮️ 📶 🎨 📧, ✋️ 👆 🤚 💭. 👆 💪 ⚙️ ⚠ & ⤴️ 🏤-⚙️ 🔢 ⚠ 🐕🦺.
diff --git a/docs/em/docs/tutorial/header-params.md b/docs/em/docs/tutorial/header-params.md
deleted file mode 100644
index 0f33a17747ddf..0000000000000
--- a/docs/em/docs/tutorial/header-params.md
+++ /dev/null
@@ -1,128 +0,0 @@
-# 🎚 🔢
-
-👆 💪 🔬 🎚 🔢 🎏 🌌 👆 🔬 `Query`, `Path` & `Cookie` 🔢.
-
-## 🗄 `Header`
-
-🥇 🗄 `Header`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
-
-## 📣 `Header` 🔢
-
-⤴️ 📣 🎚 🔢 ⚙️ 🎏 📊 ⏮️ `Path`, `Query` & `Cookie`.
-
-🥇 💲 🔢 💲, 👆 💪 🚶♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial001_py310.py!}
- ```
-
-!!! note "📡 ℹ"
- `Header` "👭" 🎓 `Path`, `Query` & `Cookie`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓.
-
- ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Header`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
-
-!!! info
- 📣 🎚, 👆 💪 ⚙️ `Header`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢.
-
-## 🏧 🛠️
-
-`Header` ✔️ 🐥 ➕ 🛠️ 🔛 🔝 ⚫️❔ `Path`, `Query` & `Cookie` 🚚.
-
-🌅 🐩 🎚 🎏 "🔠" 🦹, 💭 "➖ 🔣" (`-`).
-
-✋️ 🔢 💖 `user-agent` ❌ 🐍.
-
-, 🔢, `Header` 🔜 🗜 🔢 📛 🦹 ⚪️➡️ 🎦 (`_`) 🔠 (`-`) ⚗ & 📄 🎚.
-
-, 🇺🇸🔍 🎚 💼-😛,, 👆 💪 📣 👫 ⏮️ 🐩 🐍 👗 (💭 "🔡").
-
-, 👆 💪 ⚙️ `user_agent` 👆 🛎 🔜 🐍 📟, ↩️ 💆♂ 🎯 🥇 🔤 `User_Agent` ⚖️ 🕳 🎏.
-
-🚥 🤔 👆 💪 ❎ 🏧 🛠️ 🎦 🔠, ⚒ 🔢 `convert_underscores` `Header` `False`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/header_params/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/header_params/tutorial002_py310.py!}
- ```
-
-!!! warning
- ⏭ ⚒ `convert_underscores` `False`, 🐻 🤯 👈 🇺🇸🔍 🗳 & 💽 / ⚙️ 🎚 ⏮️ 🎦.
-
-## ❎ 🎚
-
-⚫️ 💪 📨 ❎ 🎚. 👈 ⛓, 🎏 🎚 ⏮️ 💗 💲.
-
-👆 💪 🔬 👈 💼 ⚙️ 📇 🆎 📄.
-
-👆 🔜 📨 🌐 💲 ⚪️➡️ ❎ 🎚 🐍 `list`.
-
-🖼, 📣 🎚 `X-Token` 👈 💪 😑 🌅 🌘 🕐, 👆 💪 ✍:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/header_params/tutorial003_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/header_params/tutorial003_py310.py!}
- ```
-
-🚥 👆 🔗 ⏮️ 👈 *➡ 🛠️* 📨 2️⃣ 🇺🇸🔍 🎚 💖:
-
-```
-X-Token: foo
-X-Token: bar
-```
-
-📨 🔜 💖:
-
-```JSON
-{
- "X-Token values": [
- "bar",
- "foo"
- ]
-}
-```
-
-## 🌃
-
-📣 🎚 ⏮️ `Header`, ⚙️ 🎏 ⚠ ⚓ `Query`, `Path` & `Cookie`.
-
-& 🚫 😟 🔃 🎦 👆 🔢, **FastAPI** 🔜 ✊ 💅 🏭 👫.
diff --git a/docs/em/docs/tutorial/index.md b/docs/em/docs/tutorial/index.md
deleted file mode 100644
index 26b4c1913a5e3..0000000000000
--- a/docs/em/docs/tutorial/index.md
+++ /dev/null
@@ -1,80 +0,0 @@
-# 🔰 - 👩💻 🦮
-
-👉 🔰 🎦 👆 ❔ ⚙️ **FastAPI** ⏮️ 🌅 🚮 ⚒, 🔁 🔁.
-
-🔠 📄 📉 🏗 🔛 ⏮️ 🕐, ✋️ ⚫️ 🏗 🎏 ❔, 👈 👆 💪 🚶 🔗 🙆 🎯 1️⃣ ❎ 👆 🎯 🛠️ 💪.
-
-⚫️ 🏗 👷 🔮 🔗.
-
-👆 💪 👟 🔙 & 👀 ⚫️❔ ⚫️❔ 👆 💪.
-
-## 🏃 📟
-
-🌐 📟 🍫 💪 📁 & ⚙️ 🔗 (👫 🤙 💯 🐍 📁).
-
-🏃 🙆 🖼, 📁 📟 📁 `main.py`, & ▶️ `uvicorn` ⏮️:
-
-contact 🏑| 🔢 | 🆎 | 📛 |
|---|---|---|
name | str | ⚖ 📛 📧 👨💼/🏢. |
url | str | 📛 ☝ 📧 ℹ. 🔜 📁 📛. |
email | str | 📧 📢 📧 👨💼/🏢. 🔜 📁 📧 📢. |
license_info 🏑| 🔢 | 🆎 | 📛 |
|---|---|---|
name | str | 🚚 (🚥 license_info ⚒). 🛂 📛 ⚙️ 🛠️. |
url | str | 📛 🛂 ⚙️ 🛠️. 🔜 📁 📛. |
-
-## 🗃 🔖
-
-👆 💪 🚮 🌖 🗃 🎏 🔖 ⚙️ 👪 👆 ➡ 🛠️ ⏮️ 🔢 `openapi_tags`.
-
-⚫️ ✊ 📇 ⚗ 1️⃣ 📖 🔠 🔖.
-
-🔠 📖 💪 🔌:
-
-* `name` (**✔**): `str` ⏮️ 🎏 📛 👆 ⚙️ `tags` 🔢 👆 *➡ 🛠️* & `APIRouter`Ⓜ.
-* `description`: `str` ⏮️ 📏 📛 🔖. ⚫️ 💪 ✔️ ✍ & 🔜 🎦 🩺 🎚.
-* `externalDocs`: `dict` 🔬 🔢 🧾 ⏮️:
- * `description`: `str` ⏮️ 📏 📛 🔢 🩺.
- * `url` (**✔**): `str` ⏮️ 📛 🔢 🧾.
-
-### ✍ 🗃 🔖
-
-➡️ 🔄 👈 🖼 ⏮️ 🔖 `users` & `items`.
-
-✍ 🗃 👆 🔖 & 🚶♀️ ⚫️ `openapi_tags` 🔢:
-
-```Python hl_lines="3-16 18"
-{!../../../docs_src/metadata/tutorial004.py!}
-```
-
-👀 👈 👆 💪 ⚙️ ✍ 🔘 📛, 🖼 "💳" 🔜 🎦 🦁 (**💳**) & "🎀" 🔜 🎦 ❕ (_🎀_).
-
-!!! tip
- 👆 🚫 ✔️ 🚮 🗃 🌐 🔖 👈 👆 ⚙️.
-
-### ⚙️ 👆 🔖
-
-⚙️ `tags` 🔢 ⏮️ 👆 *➡ 🛠️* (& `APIRouter`Ⓜ) 🛠️ 👫 🎏 🔖:
-
-```Python hl_lines="21 26"
-{!../../../docs_src/metadata/tutorial004.py!}
-```
-
-!!! info
- ✍ 🌅 🔃 🔖 [➡ 🛠️ 📳](../path-operation-configuration/#tags){.internal-link target=_blank}.
-
-### ✅ 🩺
-
-🔜, 🚥 👆 ✅ 🩺, 👫 🔜 🎦 🌐 🌖 🗃:
-
-
-
-### ✔ 🔖
-
-✔ 🔠 🔖 🗃 📖 🔬 ✔ 🎦 🩺 🎚.
-
-🖼, ✋️ `users` 🔜 🚶 ⏮️ `items` 🔤 ✔, ⚫️ 🎦 ⏭ 👫, ↩️ 👥 🚮 👫 🗃 🥇 📖 📇.
-
-## 🗄 📛
-
-🔢, 🗄 🔗 🍦 `/openapi.json`.
-
-✋️ 👆 💪 🔗 ⚫️ ⏮️ 🔢 `openapi_url`.
-
-🖼, ⚒ ⚫️ 🍦 `/api/v1/openapi.json`:
-
-```Python hl_lines="3"
-{!../../../docs_src/metadata/tutorial002.py!}
-```
-
-🚥 👆 💚 ❎ 🗄 🔗 🍕 👆 💪 ⚒ `openapi_url=None`, 👈 🔜 ❎ 🧾 👩💻 🔢 👈 ⚙️ ⚫️.
-
-## 🩺 📛
-
-👆 💪 🔗 2️⃣ 🧾 👩💻 🔢 🔌:
-
-* **🦁 🎚**: 🍦 `/docs`.
- * 👆 💪 ⚒ 🚮 📛 ⏮️ 🔢 `docs_url`.
- * 👆 💪 ❎ ⚫️ ⚒ `docs_url=None`.
-* **📄**: 🍦 `/redoc`.
- * 👆 💪 ⚒ 🚮 📛 ⏮️ 🔢 `redoc_url`.
- * 👆 💪 ❎ ⚫️ ⚒ `redoc_url=None`.
-
-🖼, ⚒ 🦁 🎚 🍦 `/documentation` & ❎ 📄:
-
-```Python hl_lines="3"
-{!../../../docs_src/metadata/tutorial003.py!}
-```
diff --git a/docs/em/docs/tutorial/middleware.md b/docs/em/docs/tutorial/middleware.md
deleted file mode 100644
index 644b4690c11c2..0000000000000
--- a/docs/em/docs/tutorial/middleware.md
+++ /dev/null
@@ -1,61 +0,0 @@
-# 🛠️
-
-👆 💪 🚮 🛠️ **FastAPI** 🈸.
-
-"🛠️" 🔢 👈 👷 ⏮️ 🔠 **📨** ⏭ ⚫️ 🛠️ 🙆 🎯 *➡ 🛠️*. & ⏮️ 🔠 **📨** ⏭ 🛬 ⚫️.
-
-* ⚫️ ✊ 🔠 **📨** 👈 👟 👆 🈸.
-* ⚫️ 💪 ⤴️ 🕳 👈 **📨** ⚖️ 🏃 🙆 💪 📟.
-* ⤴️ ⚫️ 🚶♀️ **📨** 🛠️ 🎂 🈸 ( *➡ 🛠️*).
-* ⚫️ ⤴️ ✊ **📨** 🏗 🈸 ( *➡ 🛠️*).
-* ⚫️ 💪 🕳 👈 **📨** ⚖️ 🏃 🙆 💪 📟.
-* ⤴️ ⚫️ 📨 **📨**.
-
-!!! note "📡 ℹ"
- 🚥 👆 ✔️ 🔗 ⏮️ `yield`, 🚪 📟 🔜 🏃 *⏮️* 🛠️.
-
- 🚥 📤 🙆 🖥 📋 (📄 ⏪), 👫 🔜 🏃 *⏮️* 🌐 🛠️.
-
-## ✍ 🛠️
-
-✍ 🛠️ 👆 ⚙️ 👨🎨 `@app.middleware("http")` 🔛 🔝 🔢.
-
-🛠️ 🔢 📨:
-
-* `request`.
-* 🔢 `call_next` 👈 🔜 📨 `request` 🔢.
- * 👉 🔢 🔜 🚶♀️ `request` 🔗 *➡ 🛠️*.
- * ⤴️ ⚫️ 📨 `response` 🏗 🔗 *➡ 🛠️*.
-* 👆 💪 ⤴️ 🔀 🌅 `response` ⏭ 🛬 ⚫️.
-
-```Python hl_lines="8-9 11 14"
-{!../../../docs_src/middleware/tutorial001.py!}
-```
-
-!!! tip
- ✔️ 🤯 👈 🛃 © 🎚 💪 🚮 ⚙️ '✖-' 🔡.
-
- ✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 ([⚜ (✖️-🇨🇳 ℹ 🤝)](cors.md){.internal-link target=_blank}) ⚙️ 🔢 `expose_headers` 📄 💃 ⚜ 🩺.
-
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.requests import Request`.
-
- **FastAPI** 🚚 ⚫️ 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
-
-### ⏭ & ⏮️ `response`
-
-👆 💪 🚮 📟 🏃 ⏮️ `request`, ⏭ 🙆 *➡ 🛠️* 📨 ⚫️.
-
-& ⏮️ `response` 🏗, ⏭ 🛬 ⚫️.
-
-🖼, 👆 💪 🚮 🛃 🎚 `X-Process-Time` ⚗ 🕰 🥈 👈 ⚫️ ✊ 🛠️ 📨 & 🏗 📨:
-
-```Python hl_lines="10 12-13"
-{!../../../docs_src/middleware/tutorial001.py!}
-```
-
-## 🎏 🛠️
-
-👆 💪 ⏪ ✍ 🌖 🔃 🎏 🛠️ [🏧 👩💻 🦮: 🏧 🛠️](../advanced/middleware.md){.internal-link target=_blank}.
-
-👆 🔜 ✍ 🔃 ❔ 🍵 ⚜ ⏮️ 🛠️ ⏭ 📄.
diff --git a/docs/em/docs/tutorial/path-operation-configuration.md b/docs/em/docs/tutorial/path-operation-configuration.md
deleted file mode 100644
index 916529258dd81..0000000000000
--- a/docs/em/docs/tutorial/path-operation-configuration.md
+++ /dev/null
@@ -1,179 +0,0 @@
-# ➡ 🛠️ 📳
-
-📤 📚 🔢 👈 👆 💪 🚶♀️ 👆 *➡ 🛠️ 👨🎨* 🔗 ⚫️.
-
-!!! warning
- 👀 👈 👫 🔢 🚶♀️ 🔗 *➡ 🛠️ 👨🎨*, 🚫 👆 *➡ 🛠️ 🔢*.
-
-## 📨 👔 📟
-
-👆 💪 🔬 (🇺🇸🔍) `status_code` ⚙️ 📨 👆 *➡ 🛠️*.
-
-👆 💪 🚶♀️ 🔗 `int` 📟, 💖 `404`.
-
-✋️ 🚥 👆 🚫 💭 ⚫️❔ 🔠 🔢 📟, 👆 💪 ⚙️ ⌨ 📉 `status`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="1 15"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
- ```
-
-👈 👔 📟 🔜 ⚙️ 📨 & 🔜 🚮 🗄 🔗.
-
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette import status`.
-
- **FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
-
-## 🔖
-
-👆 💪 🚮 🔖 👆 *➡ 🛠️*, 🚶♀️ 🔢 `tags` ⏮️ `list` `str` (🛎 1️⃣ `str`):
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="15 20 25"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
- ```
-
-👫 🔜 🚮 🗄 🔗 & ⚙️ 🏧 🧾 🔢:
-
-
-
-### 🔖 ⏮️ 🔢
-
-🚥 👆 ✔️ 🦏 🈸, 👆 5️⃣📆 🔚 🆙 📈 **📚 🔖**, & 👆 🔜 💚 ⚒ 💭 👆 🕧 ⚙️ **🎏 🔖** 🔗 *➡ 🛠️*.
-
-👫 💼, ⚫️ 💪 ⚒ 🔑 🏪 🔖 `Enum`.
-
-**FastAPI** 🐕🦺 👈 🎏 🌌 ⏮️ ✅ 🎻:
-
-```Python hl_lines="1 8-10 13 18"
-{!../../../docs_src/path_operation_configuration/tutorial002b.py!}
-```
-
-## 📄 & 📛
-
-👆 💪 🚮 `summary` & `description`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
- ```
-
-## 📛 ⚪️➡️ #️⃣
-
-📛 😑 📏 & 📔 💗 ⏸, 👆 💪 📣 *➡ 🛠️* 📛 🔢 #️⃣ & **FastAPI** 🔜 ✍ ⚫️ ⚪️➡️ 📤.
-
-👆 💪 ✍ ✍ #️⃣ , ⚫️ 🔜 🔬 & 🖥 ☑ (✊ 🔘 🏧 #️⃣ 📐).
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="17-25"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
- ```
-
-⚫️ 🔜 ⚙️ 🎓 🩺:
-
-
-
-## 📨 📛
-
-👆 💪 ✔ 📨 📛 ⏮️ 🔢 `response_description`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="19"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
- ```
-
-!!! info
- 👀 👈 `response_description` 🔗 🎯 📨, `description` 🔗 *➡ 🛠️* 🏢.
-
-!!! check
- 🗄 ✔ 👈 🔠 *➡ 🛠️* 🚚 📨 📛.
-
- , 🚥 👆 🚫 🚚 1️⃣, **FastAPI** 🔜 🔁 🏗 1️⃣ "🏆 📨".
-
-
-
-## 😢 *➡ 🛠️*
-
-🚥 👆 💪 ™ *➡ 🛠️* 😢, ✋️ 🍵 ❎ ⚫️, 🚶♀️ 🔢 `deprecated`:
-
-```Python hl_lines="16"
-{!../../../docs_src/path_operation_configuration/tutorial006.py!}
-```
-
-⚫️ 🔜 🎯 ™ 😢 🎓 🩺:
-
-
-
-✅ ❔ 😢 & 🚫-😢 *➡ 🛠️* 👀 💖:
-
-
-
-## 🌃
-
-👆 💪 🔗 & 🚮 🗃 👆 *➡ 🛠️* 💪 🚶♀️ 🔢 *➡ 🛠️ 👨🎨*.
diff --git a/docs/em/docs/tutorial/path-params-numeric-validations.md b/docs/em/docs/tutorial/path-params-numeric-validations.md
deleted file mode 100644
index b1ba2670b6c07..0000000000000
--- a/docs/em/docs/tutorial/path-params-numeric-validations.md
+++ /dev/null
@@ -1,138 +0,0 @@
-# ➡ 🔢 & 🔢 🔬
-
-🎏 🌌 👈 👆 💪 📣 🌅 🔬 & 🗃 🔢 🔢 ⏮️ `Query`, 👆 💪 📣 🎏 🆎 🔬 & 🗃 ➡ 🔢 ⏮️ `Path`.
-
-## 🗄 ➡
-
-🥇, 🗄 `Path` ⚪️➡️ `fastapi`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
-
-## 📣 🗃
-
-👆 💪 📣 🌐 🎏 🔢 `Query`.
-
-🖼, 📣 `title` 🗃 💲 ➡ 🔢 `item_id` 👆 💪 🆎:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
-
-!!! note
- ➡ 🔢 🕧 ✔ ⚫️ ✔️ 🍕 ➡.
-
- , 👆 🔜 📣 ⚫️ ⏮️ `...` ™ ⚫️ ✔.
-
- 👐, 🚥 👆 📣 ⚫️ ⏮️ `None` ⚖️ ⚒ 🔢 💲, ⚫️ 🔜 🚫 📉 🕳, ⚫️ 🔜 🕧 🚚.
-
-## ✔ 🔢 👆 💪
-
-➡️ 💬 👈 👆 💚 📣 🔢 🔢 `q` ✔ `str`.
-
-& 👆 🚫 💪 📣 🕳 🙆 👈 🔢, 👆 🚫 🤙 💪 ⚙️ `Query`.
-
-✋️ 👆 💪 ⚙️ `Path` `item_id` ➡ 🔢.
-
-🐍 🔜 😭 🚥 👆 🚮 💲 ⏮️ "🔢" ⏭ 💲 👈 🚫 ✔️ "🔢".
-
-✋️ 👆 💪 🏤-✔ 👫, & ✔️ 💲 🍵 🔢 (🔢 🔢 `q`) 🥇.
-
-⚫️ 🚫 🤔 **FastAPI**. ⚫️ 🔜 🔍 🔢 👫 📛, 🆎 & 🔢 📄 (`Query`, `Path`, ♒️), ⚫️ 🚫 💅 🔃 ✔.
-
-, 👆 💪 📣 👆 🔢:
-
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial002.py!}
-```
-
-## ✔ 🔢 👆 💪, 🎱
-
-🚥 👆 💚 📣 `q` 🔢 🔢 🍵 `Query` 🚫 🙆 🔢 💲, & ➡ 🔢 `item_id` ⚙️ `Path`, & ✔️ 👫 🎏 ✔, 🐍 ✔️ 🐥 🎁 ❕ 👈.
-
-🚶♀️ `*`, 🥇 🔢 🔢.
-
-🐍 🏆 🚫 🕳 ⏮️ 👈 `*`, ✋️ ⚫️ 🔜 💭 👈 🌐 📄 🔢 🔜 🤙 🇨🇻 ❌ (🔑-💲 👫), 💭 kwargs. 🚥 👫 🚫 ✔️ 🔢 💲.
-
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
-```
-
-## 🔢 🔬: 👑 🌘 ⚖️ 🌓
-
-⏮️ `Query` & `Path` (& 🎏 👆 🔜 👀 ⏪) 👆 💪 📣 🔢 ⚛.
-
-📥, ⏮️ `ge=1`, `item_id` 🔜 💪 🔢 🔢 "`g`🅾 🌘 ⚖️ `e`🅾" `1`.
-
-```Python hl_lines="8"
-{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
-```
-
-## 🔢 🔬: 🌘 🌘 & 🌘 🌘 ⚖️ 🌓
-
-🎏 ✔:
-
-* `gt`: `g`🅾 `t`👲
-* `le`: `l`👭 🌘 ⚖️ `e`🅾
-
-```Python hl_lines="9"
-{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
-```
-
-## 🔢 🔬: 🎈, 🌘 🌘 & 🌘 🌘
-
-🔢 🔬 👷 `float` 💲.
-
-📥 🌐❔ ⚫️ ▶️️ ⚠ 💪 📣 gt & 🚫 ge. ⏮️ ⚫️ 👆 💪 🚚, 🖼, 👈 💲 🔜 👑 🌘 `0`, 🚥 ⚫️ 🌘 🌘 `1`.
-
-, `0.5` 🔜 ☑ 💲. ✋️ `0.0` ⚖️ `0` 🔜 🚫.
-
-& 🎏 lt.
-
-```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`🅾 `t`👲
-* `ge`: `g`🅾 🌘 ⚖️ `e`🅾
-* `lt`: `l`👭 `t`👲
-* `le`: `l`👭 🌘 ⚖️ `e`🅾
-
-!!! info
- `Query`, `Path`, & 🎏 🎓 👆 🔜 👀 ⏪ 🏿 ⚠ `Param` 🎓.
-
- 🌐 👫 💰 🎏 🔢 🌖 🔬 & 🗃 👆 ✔️ 👀.
-
-!!! note "📡 ℹ"
- 🕐❔ 👆 🗄 `Query`, `Path` & 🎏 ⚪️➡️ `fastapi`, 👫 🤙 🔢.
-
- 👈 🕐❔ 🤙, 📨 👐 🎓 🎏 📛.
-
- , 👆 🗄 `Query`, ❔ 🔢. & 🕐❔ 👆 🤙 ⚫️, ⚫️ 📨 👐 🎓 🌟 `Query`.
-
- 👫 🔢 📤 (↩️ ⚙️ 🎓 🔗) 👈 👆 👨🎨 🚫 ™ ❌ 🔃 👫 🆎.
-
- 👈 🌌 👆 💪 ⚙️ 👆 😐 👨🎨 & 🛠️ 🧰 🍵 ✔️ 🚮 🛃 📳 🤷♂ 📚 ❌.
diff --git a/docs/em/docs/tutorial/path-params.md b/docs/em/docs/tutorial/path-params.md
deleted file mode 100644
index ea939b458a8e6..0000000000000
--- a/docs/em/docs/tutorial/path-params.md
+++ /dev/null
@@ -1,252 +0,0 @@
-# ➡ 🔢
-
-👆 💪 📣 ➡ "🔢" ⚖️ "🔢" ⏮️ 🎏 ❕ ⚙️ 🐍 📁 🎻:
-
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
-
-💲 ➡ 🔢 `item_id` 🔜 🚶♀️ 👆 🔢 ❌ `item_id`.
-
-, 🚥 👆 🏃 👉 🖼 & 🚶 http://127.0.0.1:8000/items/foo, 👆 🔜 👀 📨:
-
-```JSON
-{"item_id":"foo"}
-```
-
-## ➡ 🔢 ⏮️ 🆎
-
-👆 💪 📣 🆎 ➡ 🔢 🔢, ⚙️ 🐩 🐍 🆎 ✍:
-
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
-
-👉 💼, `item_id` 📣 `int`.
-
-!!! check
- 👉 🔜 🤝 👆 👨🎨 🐕🦺 🔘 👆 🔢, ⏮️ ❌ ✅, 🛠️, ♒️.
-
-## 💽 🛠️
-
-🚥 👆 🏃 👉 🖼 & 📂 👆 🖥 http://127.0.0.1:8000/items/3, 👆 🔜 👀 📨:
-
-```JSON
-{"item_id":3}
-```
-
-!!! check
- 👀 👈 💲 👆 🔢 📨 (& 📨) `3`, 🐍 `int`, 🚫 🎻 `"3"`.
-
- , ⏮️ 👈 🆎 📄, **FastAPI** 🤝 👆 🏧 📨 "✍".
-
-## 💽 🔬
-
-✋️ 🚥 👆 🚶 🖥 http://127.0.0.1:8000/items/foo, 👆 🔜 👀 👌 🇺🇸🔍 ❌:
-
-```JSON
-{
- "detail": [
- {
- "loc": [
- "path",
- "item_id"
- ],
- "msg": "value is not a valid integer",
- "type": "type_error.integer"
- }
- ]
-}
-```
-
-↩️ ➡ 🔢 `item_id` ✔️ 💲 `"foo"`, ❔ 🚫 `int`.
-
-🎏 ❌ 🔜 😑 🚥 👆 🚚 `float` ↩️ `int`,: http://127.0.0.1:8000/items/4.2
-
-!!! check
- , ⏮️ 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 💽 🔬.
-
- 👀 👈 ❌ 🎯 🇵🇸 ⚫️❔ ☝ 🌐❔ 🔬 🚫 🚶♀️.
-
- 👉 🙃 👍 ⏪ 🛠️ & 🛠️ 📟 👈 🔗 ⏮️ 👆 🛠️.
-
-## 🧾
-
-& 🕐❔ 👆 📂 👆 🖥 http://127.0.0.1:8000/docs, 👆 🔜 👀 🏧, 🎓, 🛠️ 🧾 💖:
-
-
-
-!!! check
- 🔄, ⏮️ 👈 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 🏧, 🎓 🧾 (🛠️ 🦁 🎚).
-
- 👀 👈 ➡ 🔢 📣 🔢.
-
-## 🐩-⚓️ 💰, 🎛 🧾
-
-& ↩️ 🏗 🔗 ⚪️➡️ 🗄 🐩, 📤 📚 🔗 🧰.
-
-↩️ 👉, **FastAPI** ⚫️ 🚚 🎛 🛠️ 🧾 (⚙️ 📄), ❔ 👆 💪 🔐 http://127.0.0.1:8000/redoc:
-
-
-
-🎏 🌌, 📤 📚 🔗 🧰. ✅ 📟 ⚡ 🧰 📚 🇪🇸.
-
-## Pydantic
-
-🌐 💽 🔬 🎭 🔽 🚘 Pydantic, 👆 🤚 🌐 💰 ⚪️➡️ ⚫️. & 👆 💭 👆 👍 ✋.
-
-👆 💪 ⚙️ 🎏 🆎 📄 ⏮️ `str`, `float`, `bool` & 📚 🎏 🏗 📊 🆎.
-
-📚 👫 🔬 ⏭ 📃 🔰.
-
-## ✔ 🤔
-
-🕐❔ 🏗 *➡ 🛠️*, 👆 💪 🔎 ⚠ 🌐❔ 👆 ✔️ 🔧 ➡.
-
-💖 `/users/me`, ➡️ 💬 👈 ⚫️ 🤚 📊 🔃 ⏮️ 👩💻.
-
-& ⤴️ 👆 💪 ✔️ ➡ `/users/{user_id}` 🤚 💽 🔃 🎯 👩💻 👩💻 🆔.
-
-↩️ *➡ 🛠️* 🔬 ✔, 👆 💪 ⚒ 💭 👈 ➡ `/users/me` 📣 ⏭ 1️⃣ `/users/{user_id}`:
-
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
-```
-
-⏪, ➡ `/users/{user_id}` 🔜 🏏 `/users/me`, "💭" 👈 ⚫️ 📨 🔢 `user_id` ⏮️ 💲 `"me"`.
-
-➡, 👆 🚫🔜 ↔ ➡ 🛠️:
-
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003b.py!}
-```
-
-🥇 🕐 🔜 🕧 ⚙️ ↩️ ➡ 🏏 🥇.
-
-## 🔁 💲
-
-🚥 👆 ✔️ *➡ 🛠️* 👈 📨 *➡ 🔢*, ✋️ 👆 💚 💪 ☑ *➡ 🔢* 💲 🔁, 👆 💪 ⚙️ 🐩 🐍 `Enum`.
-
-### ✍ `Enum` 🎓
-
-🗄 `Enum` & ✍ 🎧-🎓 👈 😖 ⚪️➡️ `str` & ⚪️➡️ `Enum`.
-
-😖 ⚪️➡️ `str` 🛠️ 🩺 🔜 💪 💭 👈 💲 🔜 🆎 `string` & 🔜 💪 ✍ ☑.
-
-⤴️ ✍ 🎓 🔢 ⏮️ 🔧 💲, ❔ 🔜 💪 ☑ 💲:
-
-```Python hl_lines="1 6-9"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
-
-!!! info
- 🔢 (⚖️ 🔢) 💪 🐍 ↩️ ⏬ 3️⃣.4️⃣.
-
-!!! tip
- 🚥 👆 💭, "📊", "🎓", & "🍏" 📛 🎰 🏫 🏷.
-
-### 📣 *➡ 🔢*
-
-⤴️ ✍ *➡ 🔢* ⏮️ 🆎 ✍ ⚙️ 🔢 🎓 👆 ✍ (`ModelName`):
-
-```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
-
-### ✅ 🩺
-
-↩️ 💪 💲 *➡ 🔢* 🔢, 🎓 🩺 💪 🎦 👫 🎆:
-
-
-
-### 👷 ⏮️ 🐍 *🔢*
-
-💲 *➡ 🔢* 🔜 *🔢 👨🎓*.
-
-#### 🔬 *🔢 👨🎓*
-
-👆 💪 🔬 ⚫️ ⏮️ *🔢 👨🎓* 👆 ✍ 🔢 `ModelName`:
-
-```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
-
-#### 🤚 *🔢 💲*
-
-👆 💪 🤚 ☑ 💲 ( `str` 👉 💼) ⚙️ `model_name.value`, ⚖️ 🏢, `your_enum_member.value`:
-
-```Python hl_lines="20"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
-
-!!! tip
- 👆 💪 🔐 💲 `"lenet"` ⏮️ `ModelName.lenet.value`.
-
-#### 📨 *🔢 👨🎓*
-
-👆 💪 📨 *🔢 👨🎓* ⚪️➡️ 👆 *➡ 🛠️*, 🐦 🎻 💪 (✅ `dict`).
-
-👫 🔜 🗜 👫 🔗 💲 (🎻 👉 💼) ⏭ 🛬 👫 👩💻:
-
-```Python hl_lines="18 21 23"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
-
-👆 👩💻 👆 🔜 🤚 🎻 📨 💖:
-
-```JSON
-{
- "model_name": "alexnet",
- "message": "Deep Learning FTW!"
-}
-```
-
-## ➡ 🔢 ⚗ ➡
-
-➡️ 💬 👆 ✔️ *➡ 🛠️* ⏮️ ➡ `/files/{file_path}`.
-
-✋️ 👆 💪 `file_path` ⚫️ 🔌 *➡*, 💖 `home/johndoe/myfile.txt`.
-
-, 📛 👈 📁 🔜 🕳 💖: `/files/home/johndoe/myfile.txt`.
-
-### 🗄 🐕🦺
-
-🗄 🚫 🐕🦺 🌌 📣 *➡ 🔢* 🔌 *➡* 🔘, 👈 💪 ↘️ 😐 👈 ⚠ 💯 & 🔬.
-
-👐, 👆 💪 ⚫️ **FastAPI**, ⚙️ 1️⃣ 🔗 🧰 ⚪️➡️ 💃.
-
-& 🩺 🔜 👷, 👐 🚫 ❎ 🙆 🧾 💬 👈 🔢 🔜 🔌 ➡.
-
-### ➡ 🔌
-
-⚙️ 🎛 🔗 ⚪️➡️ 💃 👆 💪 📣 *➡ 🔢* ⚗ *➡* ⚙️ 📛 💖:
-
-```
-/files/{file_path:path}
-```
-
-👉 💼, 📛 🔢 `file_path`, & 🏁 🍕, `:path`, 💬 ⚫️ 👈 🔢 🔜 🏏 🙆 *➡*.
-
-, 👆 💪 ⚙️ ⚫️ ⏮️:
-
-```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
-```
-
-!!! tip
- 👆 💪 💪 🔢 🔌 `/home/johndoe/myfile.txt`, ⏮️ 🏁 🔪 (`/`).
-
- 👈 💼, 📛 🔜: `/files//home/johndoe/myfile.txt`, ⏮️ 2️⃣✖️ 🔪 (`//`) 🖖 `files` & `home`.
-
-## 🌃
-
-⏮️ **FastAPI**, ⚙️ 📏, 🏋️ & 🐩 🐍 🆎 📄, 👆 🤚:
-
-* 👨🎨 🐕🦺: ❌ ✅, ✍, ♒️.
-* 💽 "✍"
-* 💽 🔬
-* 🛠️ ✍ & 🏧 🧾
-
-& 👆 🕴 ✔️ 📣 👫 🕐.
-
-👈 🎲 👑 ⭐ 📈 **FastAPI** 🔬 🎛 🛠️ (↖️ ⚪️➡️ 🍣 🎭).
diff --git a/docs/em/docs/tutorial/query-params-str-validations.md b/docs/em/docs/tutorial/query-params-str-validations.md
deleted file mode 100644
index d6b67bd518f73..0000000000000
--- a/docs/em/docs/tutorial/query-params-str-validations.md
+++ /dev/null
@@ -1,467 +0,0 @@
-# 🔢 🔢 & 🎻 🔬
-
-**FastAPI** ✔ 👆 📣 🌖 ℹ & 🔬 👆 🔢.
-
-➡️ ✊ 👉 🈸 🖼:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!}
- ```
-
-🔢 🔢 `q` 🆎 `Union[str, None]` (⚖️ `str | None` 🐍 3️⃣.1️⃣0️⃣), 👈 ⛓ 👈 ⚫️ 🆎 `str` ✋️ 💪 `None`, & 👐, 🔢 💲 `None`, FastAPI 🔜 💭 ⚫️ 🚫 ✔.
-
-!!! note
- FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`.
-
- `Union` `Union[str, None]` 🔜 ✔ 👆 👨🎨 🤝 👆 👍 🐕🦺 & 🔍 ❌.
-
-## 🌖 🔬
-
-👥 🔜 🛠️ 👈 ✋️ `q` 📦, 🕐❔ ⚫️ 🚚, **🚮 📐 🚫 📉 5️⃣0️⃣ 🦹**.
-
-### 🗄 `Query`
-
-🏆 👈, 🥇 🗄 `Query` ⚪️➡️ `fastapi`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
- ```
-
-## ⚙️ `Query` 🔢 💲
-
-& 🔜 ⚙️ ⚫️ 🔢 💲 👆 🔢, ⚒ 🔢 `max_length` 5️⃣0️⃣:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!}
- ```
-
-👥 ✔️ ❎ 🔢 💲 `None` 🔢 ⏮️ `Query()`, 👥 💪 🔜 ⚒ 🔢 💲 ⏮️ 🔢 `Query(default=None)`, ⚫️ 🍦 🎏 🎯 ⚖ 👈 🔢 💲.
-
-:
-
-```Python
-q: Union[str, None] = Query(default=None)
-```
-
-...⚒ 🔢 📦, 🎏:
-
-```Python
-q: Union[str, None] = None
-```
-
-& 🐍 3️⃣.1️⃣0️⃣ & 🔛:
-
-```Python
-q: str | None = Query(default=None)
-```
-
-...⚒ 🔢 📦, 🎏:
-
-```Python
-q: str | None = None
-```
-
-✋️ ⚫️ 📣 ⚫️ 🎯 💆♂ 🔢 🔢.
-
-!!! info
- ✔️ 🤯 👈 🌅 ⚠ 🍕 ⚒ 🔢 📦 🍕:
-
- ```Python
- = None
- ```
-
- ⚖️:
-
- ```Python
- = Query(default=None)
- ```
-
- ⚫️ 🔜 ⚙️ 👈 `None` 🔢 💲, & 👈 🌌 ⚒ 🔢 **🚫 ✔**.
-
- `Union[str, None]` 🍕 ✔ 👆 👨🎨 🚚 👻 🐕🦺, ✋️ ⚫️ 🚫 ⚫️❔ 💬 FastAPI 👈 👉 🔢 🚫 ✔.
-
-⤴️, 👥 💪 🚶♀️ 🌅 🔢 `Query`. 👉 💼, `max_length` 🔢 👈 ✔ 🎻:
-
-```Python
-q: Union[str, None] = Query(default=None, max_length=50)
-```
-
-👉 🔜 ✔ 📊, 🎦 🆑 ❌ 🕐❔ 📊 🚫 ☑, & 📄 🔢 🗄 🔗 *➡ 🛠️*.
-
-## 🚮 🌅 🔬
-
-👆 💪 🚮 🔢 `min_length`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!}
- ```
-
-## 🚮 🥔 🧬
-
-👆 💪 🔬 🥔 🧬 👈 🔢 🔜 🏏:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial004.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!}
- ```
-
-👉 🎯 🥔 🧬 ✅ 👈 📨 🔢 💲:
-
-* `^`: ▶️ ⏮️ 📄 🦹, 🚫 ✔️ 🦹 ⏭.
-* `fixedquery`: ✔️ ☑ 💲 `fixedquery`.
-* `$`: 🔚 📤, 🚫 ✔️ 🙆 🌖 🦹 ⏮️ `fixedquery`.
-
-🚥 👆 💭 💸 ⏮️ 🌐 👉 **"🥔 🧬"** 💭, 🚫 😟. 👫 🏋️ ❔ 📚 👫👫. 👆 💪 📚 💩 🍵 💆♂ 🥔 🧬.
-
-✋️ 🕐❔ 👆 💪 👫 & 🚶 & 💡 👫, 💭 👈 👆 💪 ⏪ ⚙️ 👫 🔗 **FastAPI**.
-
-## 🔢 💲
-
-🎏 🌌 👈 👆 💪 🚶♀️ `None` 💲 `default` 🔢, 👆 💪 🚶♀️ 🎏 💲.
-
-➡️ 💬 👈 👆 💚 📣 `q` 🔢 🔢 ✔️ `min_length` `3`, & ✔️ 🔢 💲 `"fixedquery"`:
-
-```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial005.py!}
-```
-
-!!! note
- ✔️ 🔢 💲 ⚒ 🔢 📦.
-
-## ⚒ ⚫️ ✔
-
-🕐❔ 👥 🚫 💪 📣 🌅 🔬 ⚖️ 🗃, 👥 💪 ⚒ `q` 🔢 🔢 ✔ 🚫 📣 🔢 💲, 💖:
-
-```Python
-q: str
-```
-
-↩️:
-
-```Python
-q: Union[str, None] = None
-```
-
-✋️ 👥 🔜 📣 ⚫️ ⏮️ `Query`, 🖼 💖:
-
-```Python
-q: Union[str, None] = Query(default=None, min_length=3)
-```
-
-, 🕐❔ 👆 💪 📣 💲 ✔ ⏪ ⚙️ `Query`, 👆 💪 🎯 🚫 📣 🔢 💲:
-
-```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial006.py!}
-```
-
-### ✔ ⏮️ ❕ (`...`)
-
-📤 🎛 🌌 🎯 📣 👈 💲 ✔. 👆 💪 ⚒ `default` 🔢 🔑 💲 `...`:
-
-```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial006b.py!}
-```
-
-!!! info
- 🚥 👆 🚫 👀 👈 `...` ⏭: ⚫️ 🎁 👁 💲, ⚫️ 🍕 🐍 & 🤙 "❕".
-
- ⚫️ ⚙️ Pydantic & FastAPI 🎯 📣 👈 💲 ✔.
-
-👉 🔜 ➡️ **FastAPI** 💭 👈 👉 🔢 ✔.
-
-### ✔ ⏮️ `None`
-
-👆 💪 📣 👈 🔢 💪 🚫 `None`, ✋️ 👈 ⚫️ ✔. 👉 🔜 ⚡ 👩💻 📨 💲, 🚥 💲 `None`.
-
-👈, 👆 💪 📣 👈 `None` ☑ 🆎 ✋️ ⚙️ `default=...`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!}
- ```
-
-!!! tip
- Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑.
-
-### ⚙️ Pydantic `Required` ↩️ ❕ (`...`)
-
-🚥 👆 💭 😬 ⚙️ `...`, 👆 💪 🗄 & ⚙️ `Required` ⚪️➡️ Pydantic:
-
-```Python hl_lines="2 8"
-{!../../../docs_src/query_params_str_validations/tutorial006d.py!}
-```
-
-!!! tip
- 💭 👈 🌅 💼, 🕐❔ 🕳 🚚, 👆 💪 🎯 🚫 `default` 🔢, 👆 🛎 🚫 ✔️ ⚙️ `...` 🚫 `Required`.
-
-## 🔢 🔢 📇 / 💗 💲
-
-🕐❔ 👆 🔬 🔢 🔢 🎯 ⏮️ `Query` 👆 💪 📣 ⚫️ 📨 📇 💲, ⚖️ 🙆♀ 🎏 🌌, 📨 💗 💲.
-
-🖼, 📣 🔢 🔢 `q` 👈 💪 😑 💗 🕰 📛, 👆 💪 ✍:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!}
- ```
-
-⤴️, ⏮️ 📛 💖:
-
-```
-http://localhost:8000/items/?q=foo&q=bar
-```
-
-👆 🔜 📨 💗 `q` *🔢 🔢'* 💲 (`foo` & `bar`) 🐍 `list` 🔘 👆 *➡ 🛠️ 🔢*, *🔢 🔢* `q`.
-
-, 📨 👈 📛 🔜:
-
-```JSON
-{
- "q": [
- "foo",
- "bar"
- ]
-}
-```
-
-!!! tip
- 📣 🔢 🔢 ⏮️ 🆎 `list`, 💖 🖼 🔛, 👆 💪 🎯 ⚙️ `Query`, ⏪ ⚫️ 🔜 🔬 📨 💪.
-
-🎓 🛠️ 🩺 🔜 ℹ ➡️, ✔ 💗 💲:
-
-
-
-### 🔢 🔢 📇 / 💗 💲 ⏮️ 🔢
-
-& 👆 💪 🔬 🔢 `list` 💲 🚥 👌 🚚:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
- ```
-
-🚥 👆 🚶:
-
-```
-http://localhost:8000/items/
-```
-
-🔢 `q` 🔜: `["foo", "bar"]` & 👆 📨 🔜:
-
-```JSON
-{
- "q": [
- "foo",
- "bar"
- ]
-}
-```
-
-#### ⚙️ `list`
-
-👆 💪 ⚙️ `list` 🔗 ↩️ `List[str]` (⚖️ `list[str]` 🐍 3️⃣.9️⃣ ➕):
-
-```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial013.py!}
-```
-
-!!! note
- ✔️ 🤯 👈 👉 💼, FastAPI 🏆 🚫 ✅ 🎚 📇.
-
- 🖼, `List[int]` 🔜 ✅ (& 📄) 👈 🎚 📇 🔢. ✋️ `list` 😞 🚫🔜.
-
-## 📣 🌅 🗃
-
-👆 💪 🚮 🌅 ℹ 🔃 🔢.
-
-👈 ℹ 🔜 🔌 🏗 🗄 & ⚙️ 🧾 👩💻 🔢 & 🔢 🧰.
-
-!!! note
- ✔️ 🤯 👈 🎏 🧰 5️⃣📆 ✔️ 🎏 🎚 🗄 🐕🦺.
-
- 👫 💪 🚫 🎦 🌐 ➕ ℹ 📣, 👐 🌅 💼, ❌ ⚒ ⏪ 📄 🛠️.
-
-👆 💪 🚮 `title`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
- ```
-
-& `description`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
- ```
-
-## 📛 🔢
-
-🌈 👈 👆 💚 🔢 `item-query`.
-
-💖:
-
-```
-http://127.0.0.1:8000/items/?item-query=foobaritems
-```
-
-✋️ `item-query` 🚫 ☑ 🐍 🔢 📛.
-
-🔐 🔜 `item_query`.
-
-✋️ 👆 💪 ⚫️ ⚫️❔ `item-query`...
-
-⤴️ 👆 💪 📣 `alias`, & 👈 📛 ⚫️❔ 🔜 ⚙️ 🔎 🔢 💲:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
- ```
-
-## 😛 🔢
-
-🔜 ➡️ 💬 👆 🚫 💖 👉 🔢 🚫🔜.
-
-👆 ✔️ 👈 ⚫️ 📤 ⏪ ↩️ 📤 👩💻 ⚙️ ⚫️, ✋️ 👆 💚 🩺 🎯 🎦 ⚫️ 😢.
-
-⤴️ 🚶♀️ 🔢 `deprecated=True` `Query`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
- ```
-
-🩺 🔜 🎦 ⚫️ 💖 👉:
-
-
-
-## 🚫 ⚪️➡️ 🗄
-
-🚫 🔢 🔢 ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚒ 🔢 `include_in_schema` `Query` `False`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
- ```
-
-## 🌃
-
-👆 💪 📣 🌖 🔬 & 🗃 👆 🔢.
-
-💊 🔬 & 🗃:
-
-* `alias`
-* `title`
-* `description`
-* `deprecated`
-
-🔬 🎯 🎻:
-
-* `min_length`
-* `max_length`
-* `regex`
-
-👫 🖼 👆 👀 ❔ 📣 🔬 `str` 💲.
-
-👀 ⏭ 📃 👀 ❔ 📣 🔬 🎏 🆎, 💖 🔢.
diff --git a/docs/em/docs/tutorial/query-params.md b/docs/em/docs/tutorial/query-params.md
deleted file mode 100644
index ccb235c1514fc..0000000000000
--- a/docs/em/docs/tutorial/query-params.md
+++ /dev/null
@@ -1,225 +0,0 @@
-# 🔢 🔢
-
-🕐❔ 👆 📣 🎏 🔢 🔢 👈 🚫 🍕 ➡ 🔢, 👫 🔁 🔬 "🔢" 🔢.
-
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial001.py!}
-```
-
-🔢 ⚒ 🔑-💲 👫 👈 🚶 ⏮️ `?` 📛, 🎏 `&` 🦹.
-
-🖼, 📛:
-
-```
-http://127.0.0.1:8000/items/?skip=0&limit=10
-```
-
-...🔢 🔢:
-
-* `skip`: ⏮️ 💲 `0`
-* `limit`: ⏮️ 💲 `10`
-
-👫 🍕 📛, 👫 "🛎" 🎻.
-
-✋️ 🕐❔ 👆 📣 👫 ⏮️ 🐍 🆎 (🖼 🔛, `int`), 👫 🗜 👈 🆎 & ✔ 🛡 ⚫️.
-
-🌐 🎏 🛠️ 👈 ⚖ ➡ 🔢 ✔ 🔢 🔢:
-
-* 👨🎨 🐕🦺 (🎲)
-* 💽 "✍"
-* 💽 🔬
-* 🏧 🧾
-
-## 🔢
-
-🔢 🔢 🚫 🔧 🍕 ➡, 👫 💪 📦 & 💪 ✔️ 🔢 💲.
-
-🖼 🔛 👫 ✔️ 🔢 💲 `skip=0` & `limit=10`.
-
-, 🔜 📛:
-
-```
-http://127.0.0.1:8000/items/
-```
-
-🔜 🎏 🔜:
-
-```
-http://127.0.0.1:8000/items/?skip=0&limit=10
-```
-
-✋️ 🚥 👆 🚶, 🖼:
-
-```
-http://127.0.0.1:8000/items/?skip=20
-```
-
-🔢 💲 👆 🔢 🔜:
-
-* `skip=20`: ↩️ 👆 ⚒ ⚫️ 📛
-* `limit=10`: ↩️ 👈 🔢 💲
-
-## 📦 🔢
-
-🎏 🌌, 👆 💪 📣 📦 🔢 🔢, ⚒ 👫 🔢 `None`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
- ```
-
-👉 💼, 🔢 🔢 `q` 🔜 📦, & 🔜 `None` 🔢.
-
-!!! check
- 👀 👈 **FastAPI** 🙃 🥃 👀 👈 ➡ 🔢 `item_id` ➡ 🔢 & `q` 🚫,, ⚫️ 🔢 🔢.
-
-## 🔢 🔢 🆎 🛠️
-
-👆 💪 📣 `bool` 🆎, & 👫 🔜 🗜:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
- ```
-
-👉 💼, 🚥 👆 🚶:
-
-```
-http://127.0.0.1:8000/items/foo?short=1
-```
-
-⚖️
-
-```
-http://127.0.0.1:8000/items/foo?short=True
-```
-
-⚖️
-
-```
-http://127.0.0.1:8000/items/foo?short=true
-```
-
-⚖️
-
-```
-http://127.0.0.1:8000/items/foo?short=on
-```
-
-⚖️
-
-```
-http://127.0.0.1:8000/items/foo?short=yes
-```
-
-⚖️ 🙆 🎏 💼 📈 (🔠, 🥇 🔤 🔠, ♒️), 👆 🔢 🔜 👀 🔢 `short` ⏮️ `bool` 💲 `True`. ⏪ `False`.
-
-
-## 💗 ➡ & 🔢 🔢
-
-👆 💪 📣 💗 ➡ 🔢 & 🔢 🔢 🎏 🕰, **FastAPI** 💭 ❔ ❔.
-
-& 👆 🚫 ✔️ 📣 👫 🙆 🎯 ✔.
-
-👫 🔜 🔬 📛:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="6 8"
- {!> ../../../docs_src/query_params/tutorial004_py310.py!}
- ```
-
-## ✔ 🔢 🔢
-
-🕐❔ 👆 📣 🔢 💲 🚫-➡ 🔢 (🔜, 👥 ✔️ 🕴 👀 🔢 🔢), ⤴️ ⚫️ 🚫 ✔.
-
-🚥 👆 🚫 💚 🚮 🎯 💲 ✋️ ⚒ ⚫️ 📦, ⚒ 🔢 `None`.
-
-✋️ 🕐❔ 👆 💚 ⚒ 🔢 🔢 ✔, 👆 💪 🚫 📣 🙆 🔢 💲:
-
-```Python hl_lines="6-7"
-{!../../../docs_src/query_params/tutorial005.py!}
-```
-
-📥 🔢 🔢 `needy` ✔ 🔢 🔢 🆎 `str`.
-
-🚥 👆 📂 👆 🖥 📛 💖:
-
-```
-http://127.0.0.1:8000/items/foo-item
-```
-
-...🍵 ❎ ✔ 🔢 `needy`, 👆 🔜 👀 ❌ 💖:
-
-```JSON
-{
- "detail": [
- {
- "loc": [
- "query",
- "needy"
- ],
- "msg": "field required",
- "type": "value_error.missing"
- }
- ]
-}
-```
-
-`needy` 🚚 🔢, 👆 🔜 💪 ⚒ ⚫️ 📛:
-
-```
-http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
-```
-
-...👉 🔜 👷:
-
-```JSON
-{
- "item_id": "foo-item",
- "needy": "sooooneedy"
-}
-```
-
-& ↗️, 👆 💪 🔬 🔢 ✔, ✔️ 🔢 💲, & 🍕 📦:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params/tutorial006.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params/tutorial006_py310.py!}
- ```
-
-👉 💼, 📤 3️⃣ 🔢 🔢:
-
-* `needy`, ✔ `str`.
-* `skip`, `int` ⏮️ 🔢 💲 `0`.
-* `limit`, 📦 `int`.
-
-!!! tip
- 👆 💪 ⚙️ `Enum`Ⓜ 🎏 🌌 ⏮️ [➡ 🔢](path-params.md#predefined-values){.internal-link target=_blank}.
diff --git a/docs/em/docs/tutorial/request-files.md b/docs/em/docs/tutorial/request-files.md
deleted file mode 100644
index 26631823f204e..0000000000000
--- a/docs/em/docs/tutorial/request-files.md
+++ /dev/null
@@ -1,186 +0,0 @@
-# 📨 📁
-
-👆 💪 🔬 📁 📂 👩💻 ⚙️ `File`.
-
-!!! info
- 📨 📂 📁, 🥇 ❎ `python-multipart`.
-
- 🤶 Ⓜ. `pip install python-multipart`.
-
- 👉 ↩️ 📂 📁 📨 "📨 💽".
-
-## 🗄 `File`
-
-🗄 `File` & `UploadFile` ⚪️➡️ `fastapi`:
-
-```Python hl_lines="1"
-{!../../../docs_src/request_files/tutorial001.py!}
-```
-
-## 🔬 `File` 🔢
-
-✍ 📁 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Form`:
-
-```Python hl_lines="7"
-{!../../../docs_src/request_files/tutorial001.py!}
-```
-
-!!! info
- `File` 🎓 👈 😖 🔗 ⚪️➡️ `Form`.
-
- ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `File` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓.
-
-!!! tip
- 📣 📁 💪, 👆 💪 ⚙️ `File`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
-
-📁 🔜 📂 "📨 💽".
-
-🚥 👆 📣 🆎 👆 *➡ 🛠️ 🔢* 🔢 `bytes`, **FastAPI** 🔜 ✍ 📁 👆 & 👆 🔜 📨 🎚 `bytes`.
-
-✔️ 🤯 👈 👉 ⛓ 👈 🎂 🎚 🔜 🏪 💾. 👉 🔜 👷 👍 🤪 📁.
-
-✋️ 📤 📚 💼 ❔ 👆 💪 💰 ⚪️➡️ ⚙️ `UploadFile`.
-
-## 📁 🔢 ⏮️ `UploadFile`
-
-🔬 📁 🔢 ⏮️ 🆎 `UploadFile`:
-
-```Python hl_lines="12"
-{!../../../docs_src/request_files/tutorial001.py!}
-```
-
-⚙️ `UploadFile` ✔️ 📚 📈 🤭 `bytes`:
-
-* 👆 🚫 ✔️ ⚙️ `File()` 🔢 💲 🔢.
-* ⚫️ ⚙️ "🧵" 📁:
- * 📁 🏪 💾 🆙 🔆 📐 📉, & ⏮️ 🚶♀️ 👉 📉 ⚫️ 🔜 🏪 💾.
-* 👉 ⛓ 👈 ⚫️ 🔜 👷 👍 ⭕ 📁 💖 🖼, 📹, ⭕ 💱, ♒️. 🍵 😩 🌐 💾.
-* 👆 💪 🤚 🗃 ⚪️➡️ 📂 📁.
-* ⚫️ ✔️ 📁-💖 `async` 🔢.
-* ⚫️ 🎦 ☑ 🐍 `SpooledTemporaryFile` 🎚 👈 👆 💪 🚶♀️ 🔗 🎏 🗃 👈 ⌛ 📁-💖 🎚.
-
-### `UploadFile`
-
-`UploadFile` ✔️ 📄 🔢:
-
-* `filename`: `str` ⏮️ ⏮️ 📁 📛 👈 📂 (✅ `myimage.jpg`).
-* `content_type`: `str` ⏮️ 🎚 🆎 (📁 🆎 / 📻 🆎) (✅ `image/jpeg`).
-* `file`: `SpooledTemporaryFile` ( 📁-💖 🎚). 👉 ☑ 🐍 📁 👈 👆 💪 🚶♀️ 🔗 🎏 🔢 ⚖️ 🗃 👈 ⌛ "📁-💖" 🎚.
-
-`UploadFile` ✔️ 📄 `async` 👩🔬. 👫 🌐 🤙 🔗 📁 👩🔬 🔘 (⚙️ 🔗 `SpooledTemporaryFile`).
-
-* `write(data)`: ✍ `data` (`str` ⚖️ `bytes`) 📁.
-* `read(size)`: ✍ `size` (`int`) 🔢/🦹 📁.
-* `seek(offset)`: 🚶 🔢 🧘 `offset` (`int`) 📁.
- * 🤶 Ⓜ., `await myfile.seek(0)` 🔜 🚶 ▶️ 📁.
- * 👉 ✴️ ⚠ 🚥 👆 🏃 `await myfile.read()` 🕐 & ⤴️ 💪 ✍ 🎚 🔄.
-* `close()`: 🔐 📁.
-
-🌐 👫 👩🔬 `async` 👩🔬, 👆 💪 "⌛" 👫.
-
-🖼, 🔘 `async` *➡ 🛠️ 🔢* 👆 💪 🤚 🎚 ⏮️:
-
-```Python
-contents = await myfile.read()
-```
-
-🚥 👆 🔘 😐 `def` *➡ 🛠️ 🔢*, 👆 💪 🔐 `UploadFile.file` 🔗, 🖼:
-
-```Python
-contents = myfile.file.read()
-```
-
-!!! note "`async` 📡 ℹ"
- 🕐❔ 👆 ⚙️ `async` 👩🔬, **FastAPI** 🏃 📁 👩🔬 🧵 & ⌛ 👫.
-
-!!! note "💃 📡 ℹ"
- **FastAPI**'Ⓜ `UploadFile` 😖 🔗 ⚪️➡️ **💃**'Ⓜ `UploadFile`, ✋️ 🚮 💪 🍕 ⚒ ⚫️ 🔗 ⏮️ **Pydantic** & 🎏 🍕 FastAPI.
-
-## ⚫️❔ "📨 💽"
-
-🌌 🕸 📨 (``) 📨 💽 💽 🛎 ⚙️ "🎁" 🔢 👈 📊, ⚫️ 🎏 ⚪️➡️ 🎻.
-
-**FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻.
-
-!!! note "📡 ℹ"
- 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded` 🕐❔ ⚫️ 🚫 🔌 📁.
-
- ✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 🚥 👆 ⚙️ `File`, **FastAPI** 🔜 💭 ⚫️ ✔️ 🤚 📁 ⚪️➡️ ☑ 🍕 💪.
-
- 🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST.
-
-!!! warning
- 👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
-
- 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
-
-## 📦 📁 📂
-
-👆 💪 ⚒ 📁 📦 ⚙️ 🐩 🆎 ✍ & ⚒ 🔢 💲 `None`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7 14"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
-
-## `UploadFile` ⏮️ 🌖 🗃
-
-👆 💪 ⚙️ `File()` ⏮️ `UploadFile`, 🖼, ⚒ 🌖 🗃:
-
-```Python hl_lines="13"
-{!../../../docs_src/request_files/tutorial001_03.py!}
-```
-
-## 💗 📁 📂
-
-⚫️ 💪 📂 📚 📁 🎏 🕰.
-
-👫 🔜 👨💼 🎏 "📨 🏑" 📨 ⚙️ "📨 💽".
-
-⚙️ 👈, 📣 📇 `bytes` ⚖️ `UploadFile`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
-
-👆 🔜 📨, 📣, `list` `bytes` ⚖️ `UploadFile`Ⓜ.
-
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`.
-
- **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃.
-
-### 💗 📁 📂 ⏮️ 🌖 🗃
-
-& 🎏 🌌 ⏭, 👆 💪 ⚙️ `File()` ⚒ 🌖 🔢, `UploadFile`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
-
-## 🌃
-
-⚙️ `File`, `bytes`, & `UploadFile` 📣 📁 📂 📨, 📨 📨 💽.
diff --git a/docs/em/docs/tutorial/request-forms-and-files.md b/docs/em/docs/tutorial/request-forms-and-files.md
deleted file mode 100644
index 99aeca000353a..0000000000000
--- a/docs/em/docs/tutorial/request-forms-and-files.md
+++ /dev/null
@@ -1,35 +0,0 @@
-# 📨 📨 & 📁
-
-👆 💪 🔬 📁 & 📨 🏑 🎏 🕰 ⚙️ `File` & `Form`.
-
-!!! info
- 📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ `python-multipart`.
-
- 🤶 Ⓜ. `pip install python-multipart`.
-
-## 🗄 `File` & `Form`
-
-```Python hl_lines="1"
-{!../../../docs_src/request_forms_and_files/tutorial001.py!}
-```
-
-## 🔬 `File` & `Form` 🔢
-
-✍ 📁 & 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`:
-
-```Python hl_lines="8"
-{!../../../docs_src/request_forms_and_files/tutorial001.py!}
-```
-
-📁 & 📨 🏑 🔜 📂 📨 📊 & 👆 🔜 📨 📁 & 📨 🏑.
-
-& 👆 💪 📣 📁 `bytes` & `UploadFile`.
-
-!!! warning
- 👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`.
-
- 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
-
-## 🌃
-
-⚙️ `File` & `Form` 👯♂️ 🕐❔ 👆 💪 📨 💽 & 📁 🎏 📨.
diff --git a/docs/em/docs/tutorial/request-forms.md b/docs/em/docs/tutorial/request-forms.md
deleted file mode 100644
index fa74adae5de11..0000000000000
--- a/docs/em/docs/tutorial/request-forms.md
+++ /dev/null
@@ -1,58 +0,0 @@
-# 📨 💽
-
-🕐❔ 👆 💪 📨 📨 🏑 ↩️ 🎻, 👆 💪 ⚙️ `Form`.
-
-!!! info
- ⚙️ 📨, 🥇 ❎ `python-multipart`.
-
- 🤶 Ⓜ. `pip install python-multipart`.
-
-## 🗄 `Form`
-
-🗄 `Form` ⚪️➡️ `fastapi`:
-
-```Python hl_lines="1"
-{!../../../docs_src/request_forms/tutorial001.py!}
-```
-
-## 🔬 `Form` 🔢
-
-✍ 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`:
-
-```Python hl_lines="7"
-{!../../../docs_src/request_forms/tutorial001.py!}
-```
-
-🖼, 1️⃣ 🌌 Oauth2️⃣ 🔧 💪 ⚙️ (🤙 "🔐 💧") ⚫️ ✔ 📨 `username` & `password` 📨 🏑.
-
-🔌 🚚 🏑 ⚫️❔ 📛 `username` & `password`, & 📨 📨 🏑, 🚫 🎻.
-
-⏮️ `Form` 👆 💪 📣 🎏 📳 ⏮️ `Body` (& `Query`, `Path`, `Cookie`), 🔌 🔬, 🖼, 📛 (✅ `user-name` ↩️ `username`), ♒️.
-
-!!! info
- `Form` 🎓 👈 😖 🔗 ⚪️➡️ `Body`.
-
-!!! tip
- 📣 📨 💪, 👆 💪 ⚙️ `Form` 🎯, ↩️ 🍵 ⚫️ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢.
-
-## 🔃 "📨 🏑"
-
-🌌 🕸 📨 (``) 📨 💽 💽 🛎 ⚙️ "🎁" 🔢 👈 📊, ⚫️ 🎏 ⚪️➡️ 🎻.
-
-**FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻.
-
-!!! note "📡 ℹ"
- 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`.
-
- ✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 👆 🔜 ✍ 🔃 🚚 📁 ⏭ 📃.
-
- 🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST.
-
-!!! warning
- 👆 💪 📣 💗 `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `application/x-www-form-urlencoded` ↩️ `application/json`.
-
- 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️.
-
-## 🌃
-
-⚙️ `Form` 📣 📨 💽 🔢 🔢.
diff --git a/docs/em/docs/tutorial/response-model.md b/docs/em/docs/tutorial/response-model.md
deleted file mode 100644
index 6ea4413f89b32..0000000000000
--- a/docs/em/docs/tutorial/response-model.md
+++ /dev/null
@@ -1,481 +0,0 @@
-# 📨 🏷 - 📨 🆎
-
-👆 💪 📣 🆎 ⚙️ 📨 ✍ *➡ 🛠️ 🔢* **📨 🆎**.
-
-👆 💪 ⚙️ **🆎 ✍** 🎏 🌌 👆 🔜 🔢 💽 🔢 **🔢**, 👆 💪 ⚙️ Pydantic 🏷, 📇, 📖, 📊 💲 💖 🔢, 🎻, ♒️.
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
- ```
-
-FastAPI 🔜 ⚙️ 👉 📨 🆎:
-
-* **✔** 📨 💽.
- * 🚥 💽 ❌ (✅ 👆 ❌ 🏑), ⚫️ ⛓ 👈 *👆* 📱 📟 💔, 🚫 🛬 ⚫️❔ ⚫️ 🔜, & ⚫️ 🔜 📨 💽 ❌ ↩️ 🛬 ❌ 💽. 👉 🌌 👆 & 👆 👩💻 💪 🎯 👈 👫 🔜 📨 💽 & 💽 💠 📈.
-* 🚮 **🎻 🔗** 📨, 🗄 *➡ 🛠️*.
- * 👉 🔜 ⚙️ **🏧 🩺**.
- * ⚫️ 🔜 ⚙️ 🏧 👩💻 📟 ⚡ 🧰.
-
-✋️ 🏆 🥈:
-
-* ⚫️ 🔜 **📉 & ⛽** 🔢 📊 ⚫️❔ 🔬 📨 🆎.
- * 👉 ✴️ ⚠ **💂♂**, 👥 🔜 👀 🌅 👈 🔛.
-
-## `response_model` 🔢
-
-📤 💼 🌐❔ 👆 💪 ⚖️ 💚 📨 💽 👈 🚫 ⚫️❔ ⚫️❔ 🆎 📣.
-
-🖼, 👆 💪 💚 **📨 📖** ⚖️ 💽 🎚, ✋️ **📣 ⚫️ Pydantic 🏷**. 👉 🌌 Pydantic 🏷 🔜 🌐 💽 🧾, 🔬, ♒️. 🎚 👈 👆 📨 (✅ 📖 ⚖️ 💽 🎚).
-
-🚥 👆 🚮 📨 🆎 ✍, 🧰 & 👨🎨 🔜 😭 ⏮️ (☑) ❌ 💬 👆 👈 👆 🔢 🛬 🆎 (✅#️⃣) 👈 🎏 ⚪️➡️ ⚫️❔ 👆 📣 (✅ Pydantic 🏷).
-
-📚 💼, 👆 💪 ⚙️ *➡ 🛠️ 👨🎨* 🔢 `response_model` ↩️ 📨 🆎.
-
-👆 💪 ⚙️ `response_model` 🔢 🙆 *➡ 🛠️*:
-
-* `@app.get()`
-* `@app.post()`
-* `@app.put()`
-* `@app.delete()`
-* ♒️.
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py310.py!}
- ```
-
-!!! note
- 👀 👈 `response_model` 🔢 "👨🎨" 👩🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪.
-
-`response_model` 📨 🎏 🆎 👆 🔜 📣 Pydantic 🏷 🏑,, ⚫️ 💪 Pydantic 🏷, ✋️ ⚫️ 💪, ✅ `list` Pydantic 🏷, 💖 `List[Item]`.
-
-FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & **🗜 & ⛽ 🔢 📊** 🚮 🆎 📄.
-
-!!! tip
- 🚥 👆 ✔️ ⚠ 🆎 ✅ 👆 👨🎨, ✍, ♒️, 👆 💪 📣 🔢 📨 🆎 `Any`.
-
- 👈 🌌 👆 💬 👨🎨 👈 👆 😫 🛬 🕳. ✋️ FastAPI 🔜 💽 🧾, 🔬, 🖥, ♒️. ⏮️ `response_model`.
-
-### `response_model` 📫
-
-🚥 👆 📣 👯♂️ 📨 🆎 & `response_model`, `response_model` 🔜 ✊ 📫 & ⚙️ FastAPI.
-
-👉 🌌 👆 💪 🚮 ☑ 🆎 ✍ 👆 🔢 🕐❔ 👆 🛬 🆎 🎏 🌘 📨 🏷, ⚙️ 👨🎨 & 🧰 💖 ✍. & 👆 💪 ✔️ FastAPI 💽 🔬, 🧾, ♒️. ⚙️ `response_model`.
-
-👆 💪 ⚙️ `response_model=None` ❎ 🏗 📨 🏷 👈 *➡ 🛠️*, 👆 5️⃣📆 💪 ⚫️ 🚥 👆 ❎ 🆎 ✍ 👜 👈 🚫 ☑ Pydantic 🏑, 👆 🔜 👀 🖼 👈 1️⃣ 📄 🔛.
-
-## 📨 🎏 🔢 💽
-
-📥 👥 📣 `UserIn` 🏷, ⚫️ 🔜 🔌 🔢 🔐:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9 11"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7 9"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
-
-!!! info
- ⚙️ `EmailStr`, 🥇 ❎ `email_validator`.
-
- 🤶 Ⓜ. `pip install email-validator`
- ⚖️ `pip install pydantic[email]`.
-
-& 👥 ⚙️ 👉 🏷 📣 👆 🔢 & 🎏 🏷 📣 👆 🔢:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
-
-🔜, 🕐❔ 🖥 🏗 👩💻 ⏮️ 🔐, 🛠️ 🔜 📨 🎏 🔐 📨.
-
-👉 💼, ⚫️ 💪 🚫 ⚠, ↩️ ⚫️ 🎏 👩💻 📨 🔐.
-
-✋️ 🚥 👥 ⚙️ 🎏 🏷 ➕1️⃣ *➡ 🛠️*, 👥 💪 📨 👆 👩💻 🔐 🔠 👩💻.
-
-!!! danger
- 🙅 🏪 ✅ 🔐 👩💻 ⚖️ 📨 ⚫️ 📨 💖 👉, 🚥 👆 💭 🌐 ⚠ & 👆 💭 ⚫️❔ 👆 🔨.
-
-## 🚮 🔢 🏷
-
-👥 💪 ↩️ ✍ 🔢 🏷 ⏮️ 🔢 🔐 & 🔢 🏷 🍵 ⚫️:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
-
-📥, ✋️ 👆 *➡ 🛠️ 🔢* 🛬 🎏 🔢 👩💻 👈 🔌 🔐:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
-
-...👥 📣 `response_model` 👆 🏷 `UserOut`, 👈 🚫 🔌 🔐:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
-
-, **FastAPI** 🔜 ✊ 💅 🖥 👅 🌐 💽 👈 🚫 📣 🔢 🏷 (⚙️ Pydantic).
-
-### `response_model` ⚖️ 📨 🆎
-
-👉 💼, ↩️ 2️⃣ 🏷 🎏, 🚥 👥 ✍ 🔢 📨 🆎 `UserOut`, 👨🎨 & 🧰 🔜 😭 👈 👥 🛬 ❌ 🆎, 📚 🎏 🎓.
-
-👈 ⚫️❔ 👉 🖼 👥 ✔️ 📣 ⚫️ `response_model` 🔢.
-
-...✋️ 😣 👂 🔛 👀 ❔ ❎ 👈.
-
-## 📨 🆎 & 💽 🖥
-
-➡️ 😣 ⚪️➡️ ⏮️ 🖼. 👥 💚 **✍ 🔢 ⏮️ 1️⃣ 🆎** ✋️ 📨 🕳 👈 🔌 **🌅 💽**.
-
-👥 💚 FastAPI 🚧 **🖥** 📊 ⚙️ 📨 🏷.
-
-⏮️ 🖼, ↩️ 🎓 🎏, 👥 ✔️ ⚙️ `response_model` 🔢. ✋️ 👈 ⛓ 👈 👥 🚫 🤚 🐕🦺 ⚪️➡️ 👨🎨 & 🧰 ✅ 🔢 📨 🆎.
-
-✋️ 🌅 💼 🌐❔ 👥 💪 🕳 💖 👉, 👥 💚 🏷 **⛽/❎** 📊 👉 🖼.
-
-& 👈 💼, 👥 💪 ⚙️ 🎓 & 🧬 ✊ 📈 🔢 **🆎 ✍** 🤚 👍 🐕🦺 👨🎨 & 🧰, & 🤚 FastAPI **💽 🖥**.
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9-13 15-16 20"
- {!> ../../../docs_src/response_model/tutorial003_01.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7-10 13-14 18"
- {!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
- ```
-
-⏮️ 👉, 👥 🤚 🏭 🐕🦺, ⚪️➡️ 👨🎨 & ✍ 👉 📟 ☑ ⚖ 🆎, ✋️ 👥 🤚 💽 🖥 ⚪️➡️ FastAPI.
-
-❔ 🔨 👉 👷 ❓ ➡️ ✅ 👈 👅. 👶
-
-### 🆎 ✍ & 🏭
-
-🥇 ➡️ 👀 ❔ 👨🎨, ✍ & 🎏 🧰 🔜 👀 👉.
-
-`BaseUser` ✔️ 🧢 🏑. ⤴️ `UserIn` 😖 ⚪️➡️ `BaseUser` & 🚮 `password` 🏑,, ⚫️ 🔜 🔌 🌐 🏑 ⚪️➡️ 👯♂️ 🏷.
-
-👥 ✍ 🔢 📨 🆎 `BaseUser`, ✋️ 👥 🤙 🛬 `UserIn` 👐.
-
-👨🎨, ✍, & 🎏 🧰 🏆 🚫 😭 🔃 👉 ↩️, ⌨ ⚖, `UserIn` 🏿 `BaseUser`, ❔ ⛓ ⚫️ *☑* 🆎 🕐❔ ⚫️❔ ⌛ 🕳 👈 `BaseUser`.
-
-### FastAPI 💽 🖥
-
-🔜, FastAPI, ⚫️ 🔜 👀 📨 🆎 & ⚒ 💭 👈 ⚫️❔ 👆 📨 🔌 **🕴** 🏑 👈 📣 🆎.
-
-FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 🧬 🚫 ⚙️ 📨 💽 🖥, ⏪ 👆 💪 🔚 🆙 🛬 🌅 🌅 💽 🌘 ⚫️❔ 👆 📈.
-
-👉 🌌, 👆 💪 🤚 🏆 👯♂️ 🌏: 🆎 ✍ ⏮️ **🏭 🐕🦺** & **💽 🖥**.
-
-## 👀 ⚫️ 🩺
-
-🕐❔ 👆 👀 🏧 🩺, 👆 💪 ✅ 👈 🔢 🏷 & 🔢 🏷 🔜 👯♂️ ✔️ 👫 👍 🎻 🔗:
-
-
-
-& 👯♂️ 🏷 🔜 ⚙️ 🎓 🛠️ 🧾:
-
-
-
-## 🎏 📨 🆎 ✍
-
-📤 5️⃣📆 💼 🌐❔ 👆 📨 🕳 👈 🚫 ☑ Pydantic 🏑 & 👆 ✍ ⚫️ 🔢, 🕴 🤚 🐕🦺 🚚 🏭 (👨🎨, ✍, ♒️).
-
-### 📨 📨 🔗
-
-🏆 ⚠ 💼 🔜 [🛬 📨 🔗 🔬 ⏪ 🏧 🩺](../advanced/response-directly.md){.internal-link target=_blank}.
-
-```Python hl_lines="8 10-11"
-{!> ../../../docs_src/response_model/tutorial003_02.py!}
-```
-
-👉 🙅 💼 🍵 🔁 FastAPI ↩️ 📨 🆎 ✍ 🎓 (⚖️ 🏿) `Response`.
-
-& 🧰 🔜 😄 ↩️ 👯♂️ `RedirectResponse` & `JSONResponse` 🏿 `Response`, 🆎 ✍ ☑.
-
-### ✍ 📨 🏿
-
-👆 💪 ⚙️ 🏿 `Response` 🆎 ✍:
-
-```Python hl_lines="8-9"
-{!> ../../../docs_src/response_model/tutorial003_03.py!}
-```
-
-👉 🔜 👷 ↩️ `RedirectResponse` 🏿 `Response`, & FastAPI 🔜 🔁 🍵 👉 🙅 💼.
-
-### ❌ 📨 🆎 ✍
-
-✋️ 🕐❔ 👆 📨 🎏 ❌ 🎚 👈 🚫 ☑ Pydantic 🆎 (✅ 💽 🎚) & 👆 ✍ ⚫️ 💖 👈 🔢, FastAPI 🔜 🔄 ✍ Pydantic 📨 🏷 ⚪️➡️ 👈 🆎 ✍, & 🔜 ❌.
-
-🎏 🔜 🔨 🚥 👆 ✔️ 🕳 💖 🇪🇺 🖖 🎏 🆎 🌐❔ 1️⃣ ⚖️ 🌅 👫 🚫 ☑ Pydantic 🆎, 🖼 👉 🔜 ❌ 👶:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/response_model/tutorial003_04.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
- ```
-
-...👉 ❌ ↩️ 🆎 ✍ 🚫 Pydantic 🆎 & 🚫 👁 `Response` 🎓 ⚖️ 🏿, ⚫️ 🇪🇺 (🙆 2️⃣) 🖖 `Response` & `dict`.
-
-### ❎ 📨 🏷
-
-▶️ ⚪️➡️ 🖼 🔛, 👆 5️⃣📆 🚫 💚 ✔️ 🔢 💽 🔬, 🧾, 🖥, ♒️. 👈 🎭 FastAPI.
-
-✋️ 👆 💪 💚 🚧 📨 🆎 ✍ 🔢 🤚 🐕🦺 ⚪️➡️ 🧰 💖 👨🎨 & 🆎 ☑ (✅ ✍).
-
-👉 💼, 👆 💪 ❎ 📨 🏷 ⚡ ⚒ `response_model=None`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/response_model/tutorial003_05.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
- ```
-
-👉 🔜 ⚒ FastAPI 🚶 📨 🏷 ⚡ & 👈 🌌 👆 💪 ✔️ 🙆 📨 🆎 ✍ 👆 💪 🍵 ⚫️ 🤕 👆 FastAPI 🈸. 👶
-
-## 📨 🏷 🔢 🔢
-
-👆 📨 🏷 💪 ✔️ 🔢 💲, 💖:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="9 11-12"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
-
-* `description: Union[str, None] = None` (⚖️ `str | None = None` 🐍 3️⃣.1️⃣0️⃣) ✔️ 🔢 `None`.
-* `tax: float = 10.5` ✔️ 🔢 `10.5`.
-* `tags: List[str] = []` 🔢 🛁 📇: `[]`.
-
-✋️ 👆 💪 💚 🚫 👫 ⚪️➡️ 🏁 🚥 👫 🚫 🤙 🏪.
-
-🖼, 🚥 👆 ✔️ 🏷 ⏮️ 📚 📦 🔢 ☁ 💽, ✋️ 👆 🚫 💚 📨 📶 📏 🎻 📨 🌕 🔢 💲.
-
-### ⚙️ `response_model_exclude_unset` 🔢
-
-👆 💪 ⚒ *➡ 🛠️ 👨🎨* 🔢 `response_model_exclude_unset=True`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
-
-& 👈 🔢 💲 🏆 🚫 🔌 📨, 🕴 💲 🤙 ⚒.
-
-, 🚥 👆 📨 📨 👈 *➡ 🛠️* 🏬 ⏮️ 🆔 `foo`, 📨 (🚫 ✅ 🔢 💲) 🔜:
-
-```JSON
-{
- "name": "Foo",
- "price": 50.2
-}
-```
-
-!!! info
- FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ 🚮 `exclude_unset` 🔢 🏆 👉.
-
-!!! info
- 👆 💪 ⚙️:
-
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
-
- 🔬 Pydantic 🩺 `exclude_defaults` & `exclude_none`.
-
-#### 📊 ⏮️ 💲 🏑 ⏮️ 🔢
-
-✋️ 🚥 👆 📊 ✔️ 💲 🏷 🏑 ⏮️ 🔢 💲, 💖 🏬 ⏮️ 🆔 `bar`:
-
-```Python hl_lines="3 5"
-{
- "name": "Bar",
- "description": "The bartenders",
- "price": 62,
- "tax": 20.2
-}
-```
-
-👫 🔜 🔌 📨.
-
-#### 📊 ⏮️ 🎏 💲 🔢
-
-🚥 📊 ✔️ 🎏 💲 🔢 🕐, 💖 🏬 ⏮️ 🆔 `baz`:
-
-```Python hl_lines="3 5-6"
-{
- "name": "Baz",
- "description": None,
- "price": 50.2,
- "tax": 10.5,
- "tags": []
-}
-```
-
-FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `tax`, & `tags` ✔️ 🎏 💲 🔢, 👫 ⚒ 🎯 (↩️ ✊ ⚪️➡️ 🔢).
-
-, 👫 🔜 🔌 🎻 📨.
-
-!!! tip
- 👀 👈 🔢 💲 💪 🕳, 🚫 🕴 `None`.
-
- 👫 💪 📇 (`[]`), `float` `10.5`, ♒️.
-
-### `response_model_include` & `response_model_exclude`
-
-👆 💪 ⚙️ *➡ 🛠️ 👨🎨* 🔢 `response_model_include` & `response_model_exclude`.
-
-👫 ✊ `set` `str` ⏮️ 📛 🔢 🔌 (❎ 🎂) ⚖️ 🚫 (✅ 🎂).
-
-👉 💪 ⚙️ ⏩ ⌨ 🚥 👆 ✔️ 🕴 1️⃣ Pydantic 🏷 & 💚 ❎ 💽 ⚪️➡️ 🔢.
-
-!!! tip
- ✋️ ⚫️ 👍 ⚙️ 💭 🔛, ⚙️ 💗 🎓, ↩️ 👫 🔢.
-
- 👉 ↩️ 🎻 🔗 🏗 👆 📱 🗄 (& 🩺) 🔜 1️⃣ 🏁 🏷, 🚥 👆 ⚙️ `response_model_include` ⚖️ `response_model_exclude` 🚫 🔢.
-
- 👉 ✔ `response_model_by_alias` 👈 👷 ➡.
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial005.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial005_py310.py!}
- ```
-
-!!! tip
- ❕ `{"name", "description"}` ✍ `set` ⏮️ 📚 2️⃣ 💲.
-
- ⚫️ 🌓 `set(["name", "description"])`.
-
-#### ⚙️ `list`Ⓜ ↩️ `set`Ⓜ
-
-🚥 👆 💭 ⚙️ `set` & ⚙️ `list` ⚖️ `tuple` ↩️, FastAPI 🔜 🗜 ⚫️ `set` & ⚫️ 🔜 👷 ☑:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial006.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial006_py310.py!}
- ```
-
-## 🌃
-
-⚙️ *➡ 🛠️ 👨🎨* 🔢 `response_model` 🔬 📨 🏷 & ✴️ 🚚 📢 💽 ⛽ 👅.
-
-⚙️ `response_model_exclude_unset` 📨 🕴 💲 🎯 ⚒.
diff --git a/docs/em/docs/tutorial/response-status-code.md b/docs/em/docs/tutorial/response-status-code.md
deleted file mode 100644
index e5149de7db7cd..0000000000000
--- a/docs/em/docs/tutorial/response-status-code.md
+++ /dev/null
@@ -1,89 +0,0 @@
-# 📨 👔 📟
-
-🎏 🌌 👆 💪 ✔ 📨 🏷, 👆 💪 📣 🇺🇸🔍 👔 📟 ⚙️ 📨 ⏮️ 🔢 `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`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪.
-
-`status_code` 🔢 📨 🔢 ⏮️ 🇺🇸🔍 👔 📟.
-
-!!! info
- `status_code` 💪 👐 📨 `IntEnum`, ✅ 🐍 `http.HTTPStatus`.
-
-⚫️ 🔜:
-
-* 📨 👈 👔 📟 📨.
-* 📄 ⚫️ ✅ 🗄 🔗 ( & , 👩💻 🔢):
-
-
-
-!!! note
- 📨 📟 (👀 ⏭ 📄) 🎦 👈 📨 🔨 🚫 ✔️ 💪.
-
- FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅♂ 📨 💪.
-
-## 🔃 🇺🇸🔍 👔 📟
-
-!!! note
- 🚥 👆 ⏪ 💭 ⚫️❔ 🇺🇸🔍 👔 📟, 🚶 ⏭ 📄.
-
-🇺🇸🔍, 👆 📨 🔢 👔 📟 3️⃣ 9️⃣ 🍕 📨.
-
-👫 👔 📟 ✔️ 📛 🔗 🤔 👫, ✋️ ⚠ 🍕 🔢.
-
-📏:
-
-* `100` & 🔛 "ℹ". 👆 🛎 ⚙️ 👫 🔗. 📨 ⏮️ 👫 👔 📟 🚫🔜 ✔️ 💪.
-* **`200`** & 🔛 "🏆" 📨. 👫 🕐 👆 🔜 ⚙️ 🏆.
- * `200` 🔢 👔 📟, ❔ ⛓ 🌐 "👌".
- * ➕1️⃣ 🖼 🔜 `201`, "✍". ⚫️ 🛎 ⚙️ ⏮️ 🏗 🆕 ⏺ 💽.
- * 🎁 💼 `204`, "🙅♂ 🎚". 👉 📨 ⚙️ 🕐❔ 📤 🙅♂ 🎚 📨 👩💻, & 📨 🔜 🚫 ✔️ 💪.
-* **`300`** & 🔛 "❎". 📨 ⏮️ 👫 👔 📟 5️⃣📆 ⚖️ 5️⃣📆 🚫 ✔️ 💪, 🌖 `304`, "🚫 🔀", ❔ 🔜 🚫 ✔️ 1️⃣.
-* **`400`** & 🔛 "👩💻 ❌" 📨. 👫 🥈 🆎 👆 🔜 🎲 ⚙️ 🏆.
- * 🖼 `404`, "🚫 🔎" 📨.
- * 💊 ❌ ⚪️➡️ 👩💻, 👆 💪 ⚙️ `400`.
-* `500` & 🔛 💽 ❌. 👆 🌖 🙅 ⚙️ 👫 🔗. 🕐❔ 🕳 🚶 ❌ 🍕 👆 🈸 📟, ⚖️ 💽, ⚫️ 🔜 🔁 📨 1️⃣ 👫 👔 📟.
-
-!!! tip
- 💭 🌅 🔃 🔠 👔 📟 & ❔ 📟 ⚫️❔, ✅ 🏇 🧾 🔃 🇺🇸🔍 👔 📟.
-
-## ⌨ 💭 📛
-
-➡️ 👀 ⏮️ 🖼 🔄:
-
-```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!}
-```
-
-👫 🏪, 👫 🧑🤝🧑 🎏 🔢, ✋️ 👈 🌌 👆 💪 ⚙️ 👨🎨 📋 🔎 👫:
-
-
-
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette import status`.
-
- **FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
-
-## 🔀 🔢
-
-⏪, [🏧 👩💻 🦮](../advanced/response-change-status-code.md){.internal-link target=_blank}, 👆 🔜 👀 ❔ 📨 🎏 👔 📟 🌘 🔢 👆 📣 📥.
diff --git a/docs/em/docs/tutorial/schema-extra-example.md b/docs/em/docs/tutorial/schema-extra-example.md
deleted file mode 100644
index d5bf8810aa26c..0000000000000
--- a/docs/em/docs/tutorial/schema-extra-example.md
+++ /dev/null
@@ -1,141 +0,0 @@
-# 📣 📨 🖼 💽
-
-👆 💪 📣 🖼 💽 👆 📱 💪 📨.
-
-📥 📚 🌌 ⚫️.
-
-## Pydantic `schema_extra`
-
-👆 💪 📣 `example` Pydantic 🏷 ⚙️ `Config` & `schema_extra`, 🔬 Pydantic 🩺: 🔗 🛃:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="15-23"
- {!> ../../../docs_src/schema_extra_example/tutorial001.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="13-21"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
- ```
-
-👈 ➕ ℹ 🔜 🚮-🔢 **🎻 🔗** 👈 🏷, & ⚫️ 🔜 ⚙️ 🛠️ 🩺.
-
-!!! tip
- 👆 💪 ⚙️ 🎏 ⚒ ↔ 🎻 🔗 & 🚮 👆 👍 🛃 ➕ ℹ.
-
- 🖼 👆 💪 ⚙️ ⚫️ 🚮 🗃 🕸 👩💻 🔢, ♒️.
-
-## `Field` 🌖 ❌
-
-🕐❔ ⚙️ `Field()` ⏮️ Pydantic 🏷, 👆 💪 📣 ➕ ℹ **🎻 🔗** 🚶♀️ 🙆 🎏 ❌ ❌ 🔢.
-
-👆 💪 ⚙️ 👉 🚮 `example` 🔠 🏑:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
- ```
-
-!!! warning
- 🚧 🤯 👈 📚 ➕ ❌ 🚶♀️ 🏆 🚫 🚮 🙆 🔬, 🕴 ➕ ℹ, 🧾 🎯.
-
-## `example` & `examples` 🗄
-
-🕐❔ ⚙️ 🙆:
-
-* `Path()`
-* `Query()`
-* `Header()`
-* `Cookie()`
-* `Body()`
-* `Form()`
-* `File()`
-
-👆 💪 📣 💽 `example` ⚖️ 👪 `examples` ⏮️ 🌖 ℹ 👈 🔜 🚮 **🗄**.
-
-### `Body` ⏮️ `example`
-
-📥 👥 🚶♀️ `example` 📊 ⌛ `Body()`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="20-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="18-23"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
-
-### 🖼 🩺 🎚
-
-⏮️ 🙆 👩🔬 🔛 ⚫️ 🔜 👀 💖 👉 `/docs`:
-
-
-
-### `Body` ⏮️ 💗 `examples`
-
-👐 👁 `example`, 👆 💪 🚶♀️ `examples` ⚙️ `dict` ⏮️ **💗 🖼**, 🔠 ⏮️ ➕ ℹ 👈 🔜 🚮 **🗄** 💁♂️.
-
-🔑 `dict` 🔬 🔠 🖼, & 🔠 💲 ➕1️⃣ `dict`.
-
-🔠 🎯 🖼 `dict` `examples` 💪 🔌:
-
-* `summary`: 📏 📛 🖼.
-* `description`: 📏 📛 👈 💪 🔌 ✍ ✍.
-* `value`: 👉 ☑ 🖼 🎦, ✅ `dict`.
-* `externalValue`: 🎛 `value`, 📛 ☝ 🖼. 👐 👉 5️⃣📆 🚫 🐕🦺 📚 🧰 `value`.
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="21-47"
- {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="19-45"
- {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
- ```
-
-### 🖼 🩺 🎚
-
-⏮️ `examples` 🚮 `Body()` `/docs` 🔜 👀 💖:
-
-
-
-## 📡 ℹ
-
-!!! warning
- 👉 📶 📡 ℹ 🔃 🐩 **🎻 🔗** & **🗄**.
-
- 🚥 💭 🔛 ⏪ 👷 👆, 👈 💪 🥃, & 👆 🎲 🚫 💪 👉 ℹ, 💭 🆓 🚶 👫.
-
-🕐❔ 👆 🚮 🖼 🔘 Pydantic 🏷, ⚙️ `schema_extra` ⚖️ `Field(example="something")` 👈 🖼 🚮 **🎻 🔗** 👈 Pydantic 🏷.
-
-& 👈 **🎻 🔗** Pydantic 🏷 🔌 **🗄** 👆 🛠️, & ⤴️ ⚫️ ⚙️ 🩺 🎚.
-
-**🎻 🔗** 🚫 🤙 ✔️ 🏑 `example` 🐩. ⏮️ ⏬ 🎻 🔗 🔬 🏑 `examples`, ✋️ 🗄 3️⃣.0️⃣.3️⃣ ⚓️ 🔛 🗝 ⏬ 🎻 🔗 👈 🚫 ✔️ `examples`.
-
-, 🗄 3️⃣.0️⃣.3️⃣ 🔬 🚮 👍 `example` 🔀 ⏬ **🎻 🔗** ⚫️ ⚙️, 🎏 🎯 (✋️ ⚫️ 👁 `example`, 🚫 `examples`), & 👈 ⚫️❔ ⚙️ 🛠️ 🩺 🎚 (⚙️ 🦁 🎚).
-
-, 👐 `example` 🚫 🍕 🎻 🔗, ⚫️ 🍕 🗄 🛃 ⏬ 🎻 🔗, & 👈 ⚫️❔ 🔜 ⚙️ 🩺 🎚.
-
-✋️ 🕐❔ 👆 ⚙️ `example` ⚖️ `examples` ⏮️ 🙆 🎏 🚙 (`Query()`, `Body()`, ♒️.) 📚 🖼 🚫 🚮 🎻 🔗 👈 🔬 👈 💽 (🚫 🗄 👍 ⏬ 🎻 🔗), 👫 🚮 🔗 *➡ 🛠️* 📄 🗄 (🏞 🍕 🗄 👈 ⚙️ 🎻 🔗).
-
-`Path()`, `Query()`, `Header()`, & `Cookie()`, `example` ⚖️ `examples` 🚮 🗄 🔑, `Parameter Object` (🔧).
-
-& `Body()`, `File()`, & `Form()`, `example` ⚖️ `examples` 📊 🚮 🗄 🔑, `Request Body Object`, 🏑 `content`, 🔛 `Media Type Object` (🔧).
-
-🔛 🎏 ✋, 📤 🆕 ⏬ 🗄: **3️⃣.1️⃣.0️⃣**, ⏳ 🚀. ⚫️ ⚓️ 🔛 ⏪ 🎻 🔗 & 🏆 🛠️ ⚪️➡️ 🗄 🛃 ⏬ 🎻 🔗 ❎, 💱 ⚒ ⚪️➡️ ⏮️ ⏬ 🎻 🔗, 🌐 👫 🤪 🔺 📉. 👐, 🦁 🎚 ⏳ 🚫 🐕🦺 🗄 3️⃣.1️⃣.0️⃣,, 🔜, ⚫️ 👍 😣 ⚙️ 💭 🔛.
diff --git a/docs/em/docs/tutorial/security/first-steps.md b/docs/em/docs/tutorial/security/first-steps.md
deleted file mode 100644
index 6dec6f2c343a1..0000000000000
--- a/docs/em/docs/tutorial/security/first-steps.md
+++ /dev/null
@@ -1,182 +0,0 @@
-# 💂♂ - 🥇 🔁
-
-➡️ 🌈 👈 👆 ✔️ 👆 **👩💻** 🛠️ 🆔.
-
-& 👆 ✔️ **🕸** ➕1️⃣ 🆔 ⚖️ 🎏 ➡ 🎏 🆔 (⚖️ 📱 🈸).
-
-& 👆 💚 ✔️ 🌌 🕸 🔓 ⏮️ 👩💻, ⚙️ **🆔** & **🔐**.
-
-👥 💪 ⚙️ **Oauth2️⃣** 🏗 👈 ⏮️ **FastAPI**.
-
-✋️ ➡️ 🖊 👆 🕰 👂 🌕 📏 🔧 🔎 👈 🐥 🍖 ℹ 👆 💪.
-
-➡️ ⚙️ 🧰 🚚 **FastAPI** 🍵 💂♂.
-
-## ❔ ⚫️ 👀
-
-➡️ 🥇 ⚙️ 📟 & 👀 ❔ ⚫️ 👷, & ⤴️ 👥 🔜 👟 🔙 🤔 ⚫️❔ 😥.
-
-## ✍ `main.py`
-
-📁 🖼 📁 `main.py`:
-
-```Python
-{!../../../docs_src/security/tutorial001.py!}
-```
-
-## 🏃 ⚫️
-
-!!! info
- 🥇 ❎ `python-multipart`.
-
- 🤶 Ⓜ. `pip install python-multipart`.
-
- 👉 ↩️ **Oauth2️⃣** ⚙️ "📨 📊" 📨 `username` & `password`.
-
-🏃 🖼 ⏮️:
-
-
-
-!!! check "✔ 🔼 ❗"
- 👆 ⏪ ✔️ ✨ 🆕 "✔" 🔼.
-
- & 👆 *➡ 🛠️* ✔️ 🐥 🔒 🔝-▶️️ ↩ 👈 👆 💪 🖊.
-
-& 🚥 👆 🖊 ⚫️, 👆 ✔️ 🐥 ✔ 📨 🆎 `username` & `password` (& 🎏 📦 🏑):
-
-
-
-!!! note
- ⚫️ 🚫 🤔 ⚫️❔ 👆 🆎 📨, ⚫️ 🏆 🚫 👷. ✋️ 👥 🔜 🤚 📤.
-
-👉 ↗️ 🚫 🕸 🏁 👩💻, ✋️ ⚫️ 👑 🏧 🧰 📄 🖥 🌐 👆 🛠️.
-
-⚫️ 💪 ⚙️ 🕸 🏉 (👈 💪 👆).
-
-⚫️ 💪 ⚙️ 🥉 🥳 🈸 & ⚙️.
-
-& ⚫️ 💪 ⚙️ 👆, ℹ, ✅ & 💯 🎏 🈸.
-
-## `password` 💧
-
-🔜 ➡️ 🚶 🔙 👄 & 🤔 ⚫️❔ 🌐 👈.
-
-`password` "💧" 1️⃣ 🌌 ("💧") 🔬 Oauth2️⃣, 🍵 💂♂ & 🤝.
-
-Oauth2️⃣ 🔧 👈 👩💻 ⚖️ 🛠️ 💪 🔬 💽 👈 🔓 👩💻.
-
-✋️ 👉 💼, 🎏 **FastAPI** 🈸 🔜 🍵 🛠️ & 🤝.
-
-, ➡️ 📄 ⚫️ ⚪️➡️ 👈 📉 ☝ 🎑:
-
-* 👩💻 🆎 `username` & `password` 🕸, & 🎯 `Enter`.
-* 🕸 (🏃♂ 👩💻 🖥) 📨 👈 `username` & `password` 🎯 📛 👆 🛠️ (📣 ⏮️ `tokenUrl="token"`).
-* 🛠️ ✅ 👈 `username` & `password`, & 📨 ⏮️ "🤝" (👥 🚫 🛠️ 🙆 👉).
- * "🤝" 🎻 ⏮️ 🎚 👈 👥 💪 ⚙️ ⏪ ✔ 👉 👩💻.
- * 🛎, 🤝 ⚒ 🕛 ⏮️ 🕰.
- * , 👩💻 🔜 ✔️ 🕹 🔄 ☝ ⏪.
- * & 🚥 🤝 📎, ⚠ 🌘. ⚫️ 🚫 💖 🧲 🔑 👈 🔜 👷 ♾ (🏆 💼).
-* 🕸 🏪 👈 🤝 🍕 👱.
-* 👩💻 🖊 🕸 🚶 ➕1️⃣ 📄 🕸 🕸 📱.
-* 🕸 💪 ☕ 🌅 💽 ⚪️➡️ 🛠️.
- * ✋️ ⚫️ 💪 🤝 👈 🎯 🔗.
- * , 🔓 ⏮️ 👆 🛠️, ⚫️ 📨 🎚 `Authorization` ⏮️ 💲 `Bearer ` ➕ 🤝.
- * 🚥 🤝 🔌 `foobar`, 🎚 `Authorization` 🎚 🔜: `Bearer foobar`.
-
-## **FastAPI**'Ⓜ `OAuth2PasswordBearer`
-
-**FastAPI** 🚚 📚 🧰, 🎏 🎚 ⚛, 🛠️ 👫 💂♂ ⚒.
-
-👉 🖼 👥 🔜 ⚙️ **Oauth2️⃣**, ⏮️ **🔐** 💧, ⚙️ **📨** 🤝. 👥 👈 ⚙️ `OAuth2PasswordBearer` 🎓.
-
-!!! info
- "📨" 🤝 🚫 🕴 🎛.
-
- ✋️ ⚫️ 🏆 1️⃣ 👆 ⚙️ 💼.
-
- & ⚫️ 💪 🏆 🏆 ⚙️ 💼, 🚥 👆 Oauth2️⃣ 🕴 & 💭 ⚫️❔ ⚫️❔ 📤 ➕1️⃣ 🎛 👈 ♣ 👻 👆 💪.
-
- 👈 💼, **FastAPI** 🚚 👆 ⏮️ 🧰 🏗 ⚫️.
-
-🕐❔ 👥 ✍ 👐 `OAuth2PasswordBearer` 🎓 👥 🚶♀️ `tokenUrl` 🔢. 👉 🔢 🔌 📛 👈 👩💻 (🕸 🏃 👩💻 🖥) 🔜 ⚙️ 📨 `username` & `password` ✔ 🤚 🤝.
-
-```Python hl_lines="6"
-{!../../../docs_src/security/tutorial001.py!}
-```
-
-!!! tip
- 📥 `tokenUrl="token"` 🔗 ⚖ 📛 `token` 👈 👥 🚫 ✍. ⚫️ ⚖ 📛, ⚫️ 🌓 `./token`.
-
- ↩️ 👥 ⚙️ ⚖ 📛, 🚥 👆 🛠️ 🔎 `https://example.com/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/token`. ✋️ 🚥 👆 🛠️ 🔎 `https://example.com/api/v1/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/api/v1/token`.
-
- ⚙️ ⚖ 📛 ⚠ ⚒ 💭 👆 🈸 🚧 👷 🏧 ⚙️ 💼 💖 [⛅ 🗳](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
-
-👉 🔢 🚫 ✍ 👈 🔗 / *➡ 🛠️*, ✋️ 📣 👈 📛 `/token` 🔜 1️⃣ 👈 👩💻 🔜 ⚙️ 🤚 🤝. 👈 ℹ ⚙️ 🗄, & ⤴️ 🎓 🛠️ 🧾 ⚙️.
-
-👥 🔜 🔜 ✍ ☑ ➡ 🛠️.
-
-!!! info
- 🚥 👆 📶 ⚠ "✍" 👆 💪 👎 👗 🔢 📛 `tokenUrl` ↩️ `token_url`.
-
- 👈 ↩️ ⚫️ ⚙️ 🎏 📛 🗄 🔌. 👈 🚥 👆 💪 🔬 🌅 🔃 🙆 👫 💂♂ ⚖ 👆 💪 📁 & 📋 ⚫️ 🔎 🌖 ℹ 🔃 ⚫️.
-
-`oauth2_scheme` 🔢 👐 `OAuth2PasswordBearer`, ✋️ ⚫️ "🇧🇲".
-
-⚫️ 💪 🤙:
-
-```Python
-oauth2_scheme(some, parameters)
-```
-
-, ⚫️ 💪 ⚙️ ⏮️ `Depends`.
-
-### ⚙️ ⚫️
-
-🔜 👆 💪 🚶♀️ 👈 `oauth2_scheme` 🔗 ⏮️ `Depends`.
-
-```Python hl_lines="10"
-{!../../../docs_src/security/tutorial001.py!}
-```
-
-👉 🔗 🔜 🚚 `str` 👈 🛠️ 🔢 `token` *➡ 🛠️ 🔢*.
-
-**FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 👉 🔗 🔬 "💂♂ ⚖" 🗄 🔗 (& 🏧 🛠️ 🩺).
-
-!!! info "📡 ℹ"
- **FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 🎓 `OAuth2PasswordBearer` (📣 🔗) 🔬 💂♂ ⚖ 🗄 ↩️ ⚫️ 😖 ⚪️➡️ `fastapi.security.oauth2.OAuth2`, ❔ 🔄 😖 ⚪️➡️ `fastapi.security.base.SecurityBase`.
-
- 🌐 💂♂ 🚙 👈 🛠️ ⏮️ 🗄 (& 🏧 🛠️ 🩺) 😖 ⚪️➡️ `SecurityBase`, 👈 ❔ **FastAPI** 💪 💭 ❔ 🛠️ 👫 🗄.
-
-## ⚫️❔ ⚫️ 🔨
-
-⚫️ 🔜 🚶 & 👀 📨 👈 `Authorization` 🎚, ✅ 🚥 💲 `Bearer ` ➕ 🤝, & 🔜 📨 🤝 `str`.
-
-🚥 ⚫️ 🚫 👀 `Authorization` 🎚, ⚖️ 💲 🚫 ✔️ `Bearer ` 🤝, ⚫️ 🔜 📨 ⏮️ 4️⃣0️⃣1️⃣ 👔 📟 ❌ (`UNAUTHORIZED`) 🔗.
-
-👆 🚫 ✔️ ✅ 🚥 🤝 🔀 📨 ❌. 👆 💪 💭 👈 🚥 👆 🔢 🛠️, ⚫️ 🔜 ✔️ `str` 👈 🤝.
-
-👆 💪 🔄 ⚫️ ⏪ 🎓 🩺:
-
-
-
-👥 🚫 ✔ 🔬 🤝, ✋️ 👈 ▶️ ⏪.
-
-## 🌃
-
-, 3️⃣ ⚖️ 4️⃣ ➕ ⏸, 👆 ⏪ ✔️ 🐒 📨 💂♂.
diff --git a/docs/em/docs/tutorial/security/get-current-user.md b/docs/em/docs/tutorial/security/get-current-user.md
deleted file mode 100644
index 455cb4f46fb45..0000000000000
--- a/docs/em/docs/tutorial/security/get-current-user.md
+++ /dev/null
@@ -1,151 +0,0 @@
-# 🤚 ⏮️ 👩💻
-
-⏮️ 📃 💂♂ ⚙️ (❔ 🧢 🔛 🔗 💉 ⚙️) 🤝 *➡ 🛠️ 🔢* `token` `str`:
-
-```Python hl_lines="10"
-{!../../../docs_src/security/tutorial001.py!}
-```
-
-✋️ 👈 🚫 👈 ⚠.
-
-➡️ ⚒ ⚫️ 🤝 👥 ⏮️ 👩💻.
-
-## ✍ 👩💻 🏷
-
-🥇, ➡️ ✍ Pydantic 👩💻 🏷.
-
-🎏 🌌 👥 ⚙️ Pydantic 📣 💪, 👥 💪 ⚙️ ⚫️ 🙆 🙆:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="3 10-14"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
-
-## ✍ `get_current_user` 🔗
-
-➡️ ✍ 🔗 `get_current_user`.
-
-💭 👈 🔗 💪 ✔️ 🎧-🔗 ❓
-
-`get_current_user` 🔜 ✔️ 🔗 ⏮️ 🎏 `oauth2_scheme` 👥 ✍ ⏭.
-
-🎏 👥 🔨 ⏭ *➡ 🛠️* 🔗, 👆 🆕 🔗 `get_current_user` 🔜 📨 `token` `str` ⚪️➡️ 🎧-🔗 `oauth2_scheme`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="23"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
-
-## 🤚 👩💻
-
-`get_current_user` 🔜 ⚙️ (❌) 🚙 🔢 👥 ✍, 👈 ✊ 🤝 `str` & 📨 👆 Pydantic `User` 🏷:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="17-20 24-25"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
-
-## 💉 ⏮️ 👩💻
-
-🔜 👥 💪 ⚙️ 🎏 `Depends` ⏮️ 👆 `get_current_user` *➡ 🛠️*:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="29"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
-
-👀 👈 👥 📣 🆎 `current_user` Pydantic 🏷 `User`.
-
-👉 🔜 ℹ 🇺🇲 🔘 🔢 ⏮️ 🌐 🛠️ & 🆎 ✅.
-
-!!! tip
- 👆 5️⃣📆 💭 👈 📨 💪 📣 ⏮️ Pydantic 🏷.
-
- 📥 **FastAPI** 🏆 🚫 🤚 😨 ↩️ 👆 ⚙️ `Depends`.
-
-!!! check
- 🌌 👉 🔗 ⚙️ 🏗 ✔ 👥 ✔️ 🎏 🔗 (🎏 "☑") 👈 🌐 📨 `User` 🏷.
-
- 👥 🚫 🚫 ✔️ 🕴 1️⃣ 🔗 👈 💪 📨 👈 🆎 💽.
-
-## 🎏 🏷
-
-👆 💪 🔜 🤚 ⏮️ 👩💻 🔗 *➡ 🛠️ 🔢* & 🙅 ⏮️ 💂♂ 🛠️ **🔗 💉** 🎚, ⚙️ `Depends`.
-
-& 👆 💪 ⚙️ 🙆 🏷 ⚖️ 💽 💂♂ 📄 (👉 💼, Pydantic 🏷 `User`).
-
-✋️ 👆 🚫 🚫 ⚙️ 🎯 💽 🏷, 🎓 ⚖️ 🆎.
-
-👆 💚 ✔️ `id` & `email` & 🚫 ✔️ 🙆 `username` 👆 🏷 ❓ 💭. 👆 💪 ⚙️ 👉 🎏 🧰.
-
-👆 💚 ✔️ `str`❓ ⚖️ `dict`❓ ⚖️ 💽 🎓 🏷 👐 🔗 ❓ ⚫️ 🌐 👷 🎏 🌌.
-
-👆 🤙 🚫 ✔️ 👩💻 👈 🕹 👆 🈸 ✋️ 🤖, 🤖, ⚖️ 🎏 ⚙️, 👈 ✔️ 🔐 🤝 ❓ 🔄, ⚫️ 🌐 👷 🎏.
-
-⚙️ 🙆 😇 🏷, 🙆 😇 🎓, 🙆 😇 💽 👈 👆 💪 👆 🈸. **FastAPI** ✔️ 👆 📔 ⏮️ 🔗 💉 ⚙️.
-
-## 📟 📐
-
-👉 🖼 5️⃣📆 😑 🔁. ✔️ 🤯 👈 👥 🌀 💂♂, 📊 🏷, 🚙 🔢 & *➡ 🛠️* 🎏 📁.
-
-✋️ 📥 🔑 ☝.
-
-💂♂ & 🔗 💉 💩 ✍ 🕐.
-
-& 👆 💪 ⚒ ⚫️ 🏗 👆 💚. & , ✔️ ⚫️ ✍ 🕴 🕐, 👁 🥉. ⏮️ 🌐 💪.
-
-✋️ 👆 💪 ✔️ 💯 🔗 (*➡ 🛠️*) ⚙️ 🎏 💂♂ ⚙️.
-
-& 🌐 👫 (⚖️ 🙆 ↔ 👫 👈 👆 💚) 💪 ✊ 📈 🏤-⚙️ 👫 🔗 ⚖️ 🙆 🎏 🔗 👆 ✍.
-
-& 🌐 👉 💯 *➡ 🛠️* 💪 🤪 3️⃣ ⏸:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="28-30"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
-
-## 🌃
-
-👆 💪 🔜 🤚 ⏮️ 👩💻 🔗 👆 *➡ 🛠️ 🔢*.
-
-👥 ⏪ 😬 📤.
-
-👥 💪 🚮 *➡ 🛠️* 👩💻/👩💻 🤙 📨 `username` & `password`.
-
-👈 👟 ⏭.
diff --git a/docs/em/docs/tutorial/security/index.md b/docs/em/docs/tutorial/security/index.md
deleted file mode 100644
index d76f7203fe96b..0000000000000
--- a/docs/em/docs/tutorial/security/index.md
+++ /dev/null
@@ -1,101 +0,0 @@
-# 💂♂
-
-📤 📚 🌌 🍵 💂♂, 🤝 & ✔.
-
-& ⚫️ 🛎 🏗 & "⚠" ❔.
-
-📚 🛠️ & ⚙️ 🍵 💂♂ & 🤝 ✊ 🦏 💸 🎯 & 📟 (📚 💼 ⚫️ 💪 5️⃣0️⃣ 💯 ⚖️ 🌅 🌐 📟 ✍).
-
-**FastAPI** 🚚 📚 🧰 ℹ 👆 🙅 ⏮️ **💂♂** 💪, 📉, 🐩 🌌, 🍵 ✔️ 🔬 & 💡 🌐 💂♂ 🔧.
-
-✋️ 🥇, ➡️ ✅ 🤪 🔧.
-
-## 🏃 ❓
-
-🚥 👆 🚫 💅 🔃 🙆 👉 ⚖ & 👆 💪 🚮 💂♂ ⏮️ 🤝 ⚓️ 🔛 🆔 & 🔐 *▶️️ 🔜*, 🚶 ⏭ 📃.
-
-## Oauth2️⃣
-
-Oauth2️⃣ 🔧 👈 🔬 📚 🌌 🍵 🤝 & ✔.
-
-⚫️ 🔬 🔧 & 📔 📚 🏗 ⚙️ 💼.
-
-⚫️ 🔌 🌌 🔓 ⚙️ "🥉 🥳".
-
-👈 ⚫️❔ 🌐 ⚙️ ⏮️ "💳 ⏮️ 👱📔, 🇺🇸🔍, 👱📔, 📂" ⚙️ 🔘.
-
-### ✳ 1️⃣
-
-📤 ✳ 1️⃣, ❔ 📶 🎏 ⚪️➡️ Oauth2️⃣, & 🌖 🏗, ⚫️ 🔌 🔗 🔧 🔛 ❔ 🗜 📻.
-
-⚫️ 🚫 📶 🌟 ⚖️ ⚙️ 🛎.
-
-Oauth2️⃣ 🚫 ✔ ❔ 🗜 📻, ⚫️ ⌛ 👆 ✔️ 👆 🈸 🍦 ⏮️ 🇺🇸🔍.
-
-!!! tip
- 📄 🔃 **🛠️** 👆 🔜 👀 ❔ ⚒ 🆙 🇺🇸🔍 🆓, ⚙️ Traefik & ➡️ 🗜.
-
-
-## 👩💻 🔗
-
-👩💻 🔗 ➕1️⃣ 🔧, 🧢 🔛 **Oauth2️⃣**.
-
-⚫️ ↔ Oauth2️⃣ ✔ 👜 👈 📶 🌌 Oauth2️⃣, 🔄 ⚒ ⚫️ 🌅 🛠️.
-
-🖼, 🇺🇸🔍 💳 ⚙️ 👩💻 🔗 (❔ 🔘 ⚙️ Oauth2️⃣).
-
-✋️ 👱📔 💳 🚫 🐕🦺 👩💻 🔗. ⚫️ ✔️ 🚮 👍 🍛 Oauth2️⃣.
-
-### 👩💻 (🚫 "👩💻 🔗")
-
-📤 "👩💻" 🔧. 👈 🔄 ❎ 🎏 👜 **👩💻 🔗**, ✋️ 🚫 ⚓️ 🔛 Oauth2️⃣.
-
-, ⚫️ 🏁 🌖 ⚙️.
-
-⚫️ 🚫 📶 🌟 ⚖️ ⚙️ 🛎.
-
-## 🗄
-
-🗄 (⏪ 💭 🦁) 📂 🔧 🏗 🔗 (🔜 🍕 💾 🏛).
-
-**FastAPI** ⚓️ 🔛 **🗄**.
-
-👈 ⚫️❔ ⚒ ⚫️ 💪 ✔️ 💗 🏧 🎓 🧾 🔢, 📟 ⚡, ♒️.
-
-🗄 ✔️ 🌌 🔬 💗 💂♂ "⚖".
-
-⚙️ 👫, 👆 💪 ✊ 📈 🌐 👫 🐩-⚓️ 🧰, 🔌 👉 🎓 🧾 ⚙️.
-
-🗄 🔬 📄 💂♂ ⚖:
-
-* `apiKey`: 🈸 🎯 🔑 👈 💪 👟 ⚪️➡️:
- * 🔢 🔢.
- * 🎚.
- * 🍪.
-* `http`: 🐩 🇺🇸🔍 🤝 ⚙️, 🔌:
- * `bearer`: 🎚 `Authorization` ⏮️ 💲 `Bearer ` ➕ 🤝. 👉 😖 ⚪️➡️ Oauth2️⃣.
- * 🇺🇸🔍 🔰 🤝.
- * 🇺🇸🔍 📰, ♒️.
-* `oauth2`: 🌐 Oauth2️⃣ 🌌 🍵 💂♂ (🤙 "💧").
- * 📚 👫 💧 ☑ 🏗 ✳ 2️⃣.0️⃣ 🤝 🐕🦺 (💖 🇺🇸🔍, 👱📔, 👱📔, 📂, ♒️):
- * `implicit`
- * `clientCredentials`
- * `authorizationCode`
- * ✋️ 📤 1️⃣ 🎯 "💧" 👈 💪 👌 ⚙️ 🚚 🤝 🎏 🈸 🔗:
- * `password`: ⏭ 📃 🔜 📔 🖼 👉.
-* `openIdConnect`: ✔️ 🌌 🔬 ❔ 🔎 Oauth2️⃣ 🤝 📊 🔁.
- * 👉 🏧 🔍 ⚫️❔ 🔬 👩💻 🔗 🔧.
-
-
-!!! tip
- 🛠️ 🎏 🤝/✔ 🐕🦺 💖 🇺🇸🔍, 👱📔, 👱📔, 📂, ♒️. 💪 & 📶 ⏩.
-
- 🌅 🏗 ⚠ 🏗 🤝/✔ 🐕🦺 💖 👈, ✋️ **FastAPI** 🤝 👆 🧰 ⚫️ 💪, ⏪ 🔨 🏋️ 🏋♂ 👆.
-
-## **FastAPI** 🚙
-
-FastAPI 🚚 📚 🧰 🔠 👉 💂♂ ⚖ `fastapi.security` 🕹 👈 📉 ⚙️ 👉 💂♂ 🛠️.
-
-⏭ 📃 👆 🔜 👀 ❔ 🚮 💂♂ 👆 🛠️ ⚙️ 📚 🧰 🚚 **FastAPI**.
-
-& 👆 🔜 👀 ❔ ⚫️ 🤚 🔁 🛠️ 🔘 🎓 🧾 ⚙️.
diff --git a/docs/em/docs/tutorial/security/oauth2-jwt.md b/docs/em/docs/tutorial/security/oauth2-jwt.md
deleted file mode 100644
index bc207c5666d90..0000000000000
--- a/docs/em/docs/tutorial/security/oauth2-jwt.md
+++ /dev/null
@@ -1,297 +0,0 @@
-# Oauth2️⃣ ⏮️ 🔐 (& 🔁), 📨 ⏮️ 🥙 🤝
-
-🔜 👈 👥 ✔️ 🌐 💂♂ 💧, ➡️ ⚒ 🈸 🤙 🔐, ⚙️ 🥙 🤝 & 🔐 🔐 🔁.
-
-👉 📟 🕳 👆 💪 🤙 ⚙️ 👆 🈸, 🖊 🔐 #️⃣ 👆 💽, ♒️.
-
-👥 🔜 ▶️ ⚪️➡️ 🌐❔ 👥 ◀️ ⏮️ 📃 & 📈 ⚫️.
-
-## 🔃 🥙
-
-🥙 ⛓ "🎻 🕸 🤝".
-
-⚫️ 🐩 🚫 🎻 🎚 📏 💧 🎻 🍵 🚀. ⚫️ 👀 💖 👉:
-
-```
-eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
-```
-
-⚫️ 🚫 🗜,, 🙆 💪 🛡 ℹ ⚪️➡️ 🎚.
-
-✋️ ⚫️ 🛑. , 🕐❔ 👆 📨 🤝 👈 👆 ♨, 👆 💪 ✔ 👈 👆 🤙 ♨ ⚫️.
-
-👈 🌌, 👆 💪 ✍ 🤝 ⏮️ 👔, ➡️ 💬, 1️⃣ 🗓️. & ⤴️ 🕐❔ 👩💻 👟 🔙 ⏭ 📆 ⏮️ 🤝, 👆 💭 👈 👩💻 🕹 👆 ⚙️.
-
-⏮️ 🗓️, 🤝 🔜 🕛 & 👩💻 🔜 🚫 ✔ & 🔜 ✔️ 🛑 🔄 🤚 🆕 🤝. & 🚥 👩💻 (⚖️ 🥉 🥳) 🔄 🔀 🤝 🔀 👔, 👆 🔜 💪 🔎 ⚫️, ↩️ 💳 🔜 🚫 🏏.
-
-🚥 👆 💚 🤾 ⏮️ 🥙 🤝 & 👀 ❔ 👫 👷, ✅ https://jwt.io.
-
-## ❎ `python-jose`
-
-👥 💪 ❎ `python-jose` 🏗 & ✔ 🥙 🤝 🐍:
-
-
-
-✔ 🈸 🎏 🌌 ⏭.
-
-⚙️ 🎓:
-
-🆔: `johndoe`
-🔐: `secret`
-
-!!! check
- 👀 👈 🕳 📟 🔢 🔐 "`secret`", 👥 🕴 ✔️ #️⃣ ⏬.
-
-
-
-🤙 🔗 `/users/me/`, 👆 🔜 🤚 📨:
-
-```JSON
-{
- "username": "johndoe",
- "email": "johndoe@example.com",
- "full_name": "John Doe",
- "disabled": false
-}
-```
-
-
-
-🚥 👆 📂 👩💻 🧰, 👆 💪 👀 ❔ 📊 📨 🕴 🔌 🤝, 🔐 🕴 📨 🥇 📨 🔓 👩💻 & 🤚 👈 🔐 🤝, ✋️ 🚫 ⏮️:
-
-
-
-!!! note
- 👀 🎚 `Authorization`, ⏮️ 💲 👈 ▶️ ⏮️ `Bearer `.
-
-## 🏧 ⚙️ ⏮️ `scopes`
-
-Oauth2️⃣ ✔️ 🔑 "↔".
-
-👆 💪 ⚙️ 👫 🚮 🎯 ⚒ ✔ 🥙 🤝.
-
-⤴️ 👆 💪 🤝 👉 🤝 👩💻 🔗 ⚖️ 🥉 🥳, 🔗 ⏮️ 👆 🛠️ ⏮️ ⚒ 🚫.
-
-👆 💪 💡 ❔ ⚙️ 👫 & ❔ 👫 🛠️ 🔘 **FastAPI** ⏪ **🏧 👩💻 🦮**.
-
-## 🌃
-
-⏮️ ⚫️❔ 👆 ✔️ 👀 🆙 🔜, 👆 💪 ⚒ 🆙 🔐 **FastAPI** 🈸 ⚙️ 🐩 💖 Oauth2️⃣ & 🥙.
-
-🌖 🙆 🛠️ 🚚 💂♂ ▶️️ 👍 🏗 📄 🔜.
-
-📚 📦 👈 📉 ⚫️ 📚 ✔️ ⚒ 📚 ⚠ ⏮️ 💽 🏷, 💽, & 💪 ⚒. & 👉 📦 👈 📉 👜 💁♂️ 🌅 🤙 ✔️ 💂♂ ⚠ 🔘.
-
----
-
-**FastAPI** 🚫 ⚒ 🙆 ⚠ ⏮️ 🙆 💽, 💽 🏷 ⚖️ 🧰.
-
-⚫️ 🤝 👆 🌐 💪 ⚒ 🕐 👈 👖 👆 🏗 🏆.
-
-& 👆 💪 ⚙️ 🔗 📚 👍 🚧 & 🛎 ⚙️ 📦 💖 `passlib` & `python-jose`, ↩️ **FastAPI** 🚫 🚚 🙆 🏗 🛠️ 🛠️ 🔢 📦.
-
-✋️ ⚫️ 🚚 👆 🧰 📉 🛠️ 🌅 💪 🍵 🎯 💪, ⚖, ⚖️ 💂♂.
-
-& 👆 💪 ⚙️ & 🛠️ 🔐, 🐩 🛠️, 💖 Oauth2️⃣ 📶 🙅 🌌.
-
-👆 💪 💡 🌅 **🏧 👩💻 🦮** 🔃 ❔ ⚙️ Oauth2️⃣ "↔", 🌖 👌-🧽 ✔ ⚙️, 📄 👫 🎏 🐩. Oauth2️⃣ ⏮️ ↔ 🛠️ ⚙️ 📚 🦏 🤝 🐕🦺, 💖 👱📔, 🇺🇸🔍, 📂, 🤸♂, 👱📔, ♒️. ✔ 🥉 🥳 🈸 🔗 ⏮️ 👫 🔗 🔛 👨💼 👫 👩💻.
diff --git a/docs/em/docs/tutorial/security/simple-oauth2.md b/docs/em/docs/tutorial/security/simple-oauth2.md
deleted file mode 100644
index 765d9403947f9..0000000000000
--- a/docs/em/docs/tutorial/security/simple-oauth2.md
+++ /dev/null
@@ -1,315 +0,0 @@
-# 🙅 Oauth2️⃣ ⏮️ 🔐 & 📨
-
-🔜 ➡️ 🏗 ⚪️➡️ ⏮️ 📃 & 🚮 ❌ 🍕 ✔️ 🏁 💂♂ 💧.
-
-## 🤚 `username` & `password`
-
-👥 🔜 ⚙️ **FastAPI** 💂♂ 🚙 🤚 `username` & `password`.
-
-Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩💻/👩💻 🔜 📨 `username` & `password` 🏑 📨 💽.
-
-& 🔌 💬 👈 🏑 ✔️ 🌟 💖 👈. `user-name` ⚖️ `email` 🚫🔜 👷.
-
-✋️ 🚫 😟, 👆 💪 🎦 ⚫️ 👆 🎋 👆 🏁 👩💻 🕸.
-
-& 👆 💽 🏷 💪 ⚙️ 🙆 🎏 📛 👆 💚.
-
-✋️ 💳 *➡ 🛠️*, 👥 💪 ⚙️ 👉 📛 🔗 ⏮️ 🔌 (& 💪, 🖼, ⚙️ 🛠️ 🛠️ 🧾 ⚙️).
-
-🔌 🇵🇸 👈 `username` & `password` 🔜 📨 📨 💽 (, 🙅♂ 🎻 📥).
-
-### `scope`
-
-🔌 💬 👈 👩💻 💪 📨 ➕1️⃣ 📨 🏑 "`scope`".
-
-📨 🏑 📛 `scope` (⭐), ✋️ ⚫️ 🤙 📏 🎻 ⏮️ "↔" 🎏 🚀.
-
-🔠 "↔" 🎻 (🍵 🚀).
-
-👫 🛎 ⚙️ 📣 🎯 💂♂ ✔, 🖼:
-
-* `users:read` ⚖️ `users:write` ⚠ 🖼.
-* `instagram_basic` ⚙️ 👱📔 / 👱📔.
-* `https://www.googleapis.com/auth/drive` ⚙️ 🇺🇸🔍.
-
-!!! info
- Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔.
-
- ⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛.
-
- 👈 ℹ 🛠️ 🎯.
-
- Oauth2️⃣ 👫 🎻.
-
-## 📟 🤚 `username` & `password`
-
-🔜 ➡️ ⚙️ 🚙 🚚 **FastAPI** 🍵 👉.
-
-### `OAuth2PasswordRequestForm`
-
-🥇, 🗄 `OAuth2PasswordRequestForm`, & ⚙️ ⚫️ 🔗 ⏮️ `Depends` *➡ 🛠️* `/token`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="4 76"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="2 74"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
-
-`OAuth2PasswordRequestForm` 🎓 🔗 👈 📣 📨 💪 ⏮️:
-
-* `username`.
-* `password`.
-* 📦 `scope` 🏑 🦏 🎻, ✍ 🎻 🎏 🚀.
-* 📦 `grant_type`.
-
-!!! tip
- Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋️ `OAuth2PasswordRequestForm` 🚫 🛠️ ⚫️.
-
- 🚥 👆 💪 🛠️ ⚫️, ⚙️ `OAuth2PasswordRequestFormStrict` ↩️ `OAuth2PasswordRequestForm`.
-
-* 📦 `client_id` (👥 🚫 💪 ⚫️ 👆 🖼).
-* 📦 `client_secret` (👥 🚫 💪 ⚫️ 👆 🖼).
-
-!!! info
- `OAuth2PasswordRequestForm` 🚫 🎁 🎓 **FastAPI** `OAuth2PasswordBearer`.
-
- `OAuth2PasswordBearer` ⚒ **FastAPI** 💭 👈 ⚫️ 💂♂ ⚖. ⚫️ 🚮 👈 🌌 🗄.
-
- ✋️ `OAuth2PasswordRequestForm` 🎓 🔗 👈 👆 💪 ✔️ ✍ 👆, ⚖️ 👆 💪 ✔️ 📣 `Form` 🔢 🔗.
-
- ✋️ ⚫️ ⚠ ⚙️ 💼, ⚫️ 🚚 **FastAPI** 🔗, ⚒ ⚫️ ⏩.
-
-### ⚙️ 📨 💽
-
-!!! tip
- 👐 🔗 🎓 `OAuth2PasswordRequestForm` 🏆 🚫 ✔️ 🔢 `scope` ⏮️ 📏 🎻 👽 🚀, ↩️, ⚫️ 🔜 ✔️ `scopes` 🔢 ⏮️ ☑ 📇 🎻 🔠 ↔ 📨.
-
- 👥 🚫 ⚙️ `scopes` 👉 🖼, ✋️ 🛠️ 📤 🚥 👆 💪 ⚫️.
-
-🔜, 🤚 👩💻 📊 ⚪️➡️ (❌) 💽, ⚙️ `username` ⚪️➡️ 📨 🏑.
-
-🚥 📤 🙅♂ ✅ 👩💻, 👥 📨 ❌ 💬 "❌ 🆔 ⚖️ 🔐".
-
-❌, 👥 ⚙️ ⚠ `HTTPException`:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="3 77-79"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="1 75-77"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
-
-### ✅ 🔐
-
-👉 ☝ 👥 ✔️ 👩💻 📊 ⚪️➡️ 👆 💽, ✋️ 👥 🚫 ✅ 🔐.
-
-➡️ 🚮 👈 💽 Pydantic `UserInDB` 🏷 🥇.
-
-👆 🔜 🙅 🖊 🔢 🔐,, 👥 🔜 ⚙️ (❌) 🔐 🔁 ⚙️.
-
-🚥 🔐 🚫 🏏, 👥 📨 🎏 ❌.
-
-#### 🔐 🔁
-
-"🔁" ⛓: 🏭 🎚 (🔐 👉 💼) 🔘 🔁 🔢 (🎻) 👈 👀 💖 🙃.
-
-🕐❔ 👆 🚶♀️ ⚫️❔ 🎏 🎚 (⚫️❔ 🎏 🔐) 👆 🤚 ⚫️❔ 🎏 🙃.
-
-✋️ 👆 🚫🔜 🗜 ⚪️➡️ 🙃 🔙 🔐.
-
-##### ⚫️❔ ⚙️ 🔐 🔁
-
-🚥 👆 💽 📎, 🧙♀ 🏆 🚫 ✔️ 👆 👩💻' 🔢 🔐, 🕴#️⃣.
-
-, 🧙♀ 🏆 🚫 💪 🔄 ⚙️ 👈 🎏 🔐 ➕1️⃣ ⚙️ (📚 👩💻 ⚙️ 🎏 🔐 🌐, 👉 🔜 ⚠).
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="80-83"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="78-81"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
-
-#### 🔃 `**user_dict`
-
-`UserInDB(**user_dict)` ⛓:
-
-*🚶♀️ 🔑 & 💲 `user_dict` 🔗 🔑-💲 ❌, 🌓:*
-
-```Python
-UserInDB(
- username = user_dict["username"],
- email = user_dict["email"],
- full_name = user_dict["full_name"],
- disabled = user_dict["disabled"],
- hashed_password = user_dict["hashed_password"],
-)
-```
-
-!!! info
- 🌅 🏁 🔑 `**👩💻_ #️⃣ ` ✅ 🔙 [🧾 **➕ 🏷**](../extra-models.md#about-user_indict){.internal-link target=_blank}.
-
-## 📨 🤝
-
-📨 `token` 🔗 🔜 🎻 🎚.
-
-⚫️ 🔜 ✔️ `token_type`. 👆 💼, 👥 ⚙️ "📨" 🤝, 🤝 🆎 🔜 "`bearer`".
-
-& ⚫️ 🔜 ✔️ `access_token`, ⏮️ 🎻 ⚗ 👆 🔐 🤝.
-
-👉 🙅 🖼, 👥 🔜 🍕 😟 & 📨 🎏 `username` 🤝.
-
-!!! tip
- ⏭ 📃, 👆 🔜 👀 🎰 🔐 🛠️, ⏮️ 🔐 #️⃣ & 🥙 🤝.
-
- ✋️ 🔜, ➡️ 🎯 🔛 🎯 ℹ 👥 💪.
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="85"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="83"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
-
-!!! tip
- 🔌, 👆 🔜 📨 🎻 ⏮️ `access_token` & `token_type`, 🎏 👉 🖼.
-
- 👉 🕳 👈 👆 ✔️ 👆 👆 📟, & ⚒ 💭 👆 ⚙️ 📚 🎻 🔑.
-
- ⚫️ 🌖 🕴 👜 👈 👆 ✔️ 💭 ☑ 👆, 🛠️ ⏮️ 🔧.
-
- 🎂, **FastAPI** 🍵 ⚫️ 👆.
-
-## ℹ 🔗
-
-🔜 👥 🔜 ℹ 👆 🔗.
-
-👥 💚 🤚 `current_user` *🕴* 🚥 👉 👩💻 🦁.
-
-, 👥 ✍ 🌖 🔗 `get_current_active_user` 👈 🔄 ⚙️ `get_current_user` 🔗.
-
-👯♂️ 👉 🔗 🔜 📨 🇺🇸🔍 ❌ 🚥 👩💻 🚫 🔀, ⚖️ 🚥 🔕.
-
-, 👆 🔗, 👥 🔜 🕴 🤚 👩💻 🚥 👩💻 🔀, ☑ 🔓, & 🦁:
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="58-66 69-72 90"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python hl_lines="55-64 67-70 88"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
-
-!!! info
- 🌖 🎚 `WWW-Authenticate` ⏮️ 💲 `Bearer` 👥 🛬 📥 🍕 🔌.
-
- 🙆 🇺🇸🔍 (❌) 👔 📟 4️⃣0️⃣1️⃣ "⛔" 🤔 📨 `WWW-Authenticate` 🎚.
-
- 💼 📨 🤝 (👆 💼), 💲 👈 🎚 🔜 `Bearer`.
-
- 👆 💪 🤙 🚶 👈 ➕ 🎚 & ⚫️ 🔜 👷.
-
- ✋️ ⚫️ 🚚 📥 🛠️ ⏮️ 🔧.
-
- , 📤 5️⃣📆 🧰 👈 ⌛ & ⚙️ ⚫️ (🔜 ⚖️ 🔮) & 👈 💪 ⚠ 👆 ⚖️ 👆 👩💻, 🔜 ⚖️ 🔮.
-
- 👈 💰 🐩...
-
-## 👀 ⚫️ 🎯
-
-📂 🎓 🩺: http://127.0.0.1:8000/docs.
-
-### 🔓
-
-🖊 "✔" 🔼.
-
-⚙️ 🎓:
-
-👩💻: `johndoe`
-
-🔐: `secret`
-
-
-
-⏮️ 🔗 ⚙️, 👆 🔜 👀 ⚫️ 💖:
-
-
-
-### 🤚 👆 👍 👩💻 💽
-
-🔜 ⚙️ 🛠️ `GET` ⏮️ ➡ `/users/me`.
-
-👆 🔜 🤚 👆 👩💻 📊, 💖:
-
-```JSON
-{
- "username": "johndoe",
- "email": "johndoe@example.com",
- "full_name": "John Doe",
- "disabled": false,
- "hashed_password": "fakehashedsecret"
-}
-```
-
-
-
-🚥 👆 🖊 🔒 ℹ & ⏏, & ⤴️ 🔄 🎏 🛠️ 🔄, 👆 🔜 🤚 🇺🇸🔍 4️⃣0️⃣1️⃣ ❌:
-
-```JSON
-{
- "detail": "Not authenticated"
-}
-```
-
-### 🔕 👩💻
-
-🔜 🔄 ⏮️ 🔕 👩💻, 🔓 ⏮️:
-
-👩💻: `alice`
-
-🔐: `secret2`
-
-& 🔄 ⚙️ 🛠️ `GET` ⏮️ ➡ `/users/me`.
-
-👆 🔜 🤚 "🔕 👩💻" ❌, 💖:
-
-```JSON
-{
- "detail": "Inactive user"
-}
-```
-
-## 🌃
-
-👆 🔜 ✔️ 🧰 🛠️ 🏁 💂♂ ⚙️ ⚓️ 🔛 `username` & `password` 👆 🛠️.
-
-⚙️ 👫 🧰, 👆 💪 ⚒ 💂♂ ⚙️ 🔗 ⏮️ 🙆 💽 & ⏮️ 🙆 👩💻 ⚖️ 💽 🏷.
-
-🕴 ℹ ❌ 👈 ⚫️ 🚫 🤙 "🔐".
-
-⏭ 📃 👆 🔜 👀 ❔ ⚙️ 🔐 🔐 🔁 🗃 & 🥙 🤝.
diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md
deleted file mode 100644
index 9d46c2460843a..0000000000000
--- a/docs/em/docs/tutorial/sql-databases.md
+++ /dev/null
@@ -1,786 +0,0 @@
-# 🗄 (🔗) 💽
-
-**FastAPI** 🚫 🚚 👆 ⚙️ 🗄 (🔗) 💽.
-
-✋️ 👆 💪 ⚙️ 🙆 🔗 💽 👈 👆 💚.
-
-📥 👥 🔜 👀 🖼 ⚙️ 🇸🇲.
-
-👆 💪 💪 🛠️ ⚫️ 🙆 💽 🐕🦺 🇸🇲, 💖:
-
-* ✳
-* ✳
-* 🗄
-* 🐸
-* 🤸♂ 🗄 💽, ♒️.
-
-👉 🖼, 👥 🔜 ⚙️ **🗄**, ↩️ ⚫️ ⚙️ 👁 📁 & 🐍 ✔️ 🛠️ 🐕🦺. , 👆 💪 📁 👉 🖼 & 🏃 ⚫️.
-
-⏪, 👆 🏭 🈸, 👆 💪 💚 ⚙️ 💽 💽 💖 **✳**.
-
-!!! tip
- 📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **✳**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: https://github.com/tiangolo/full-stack-fastapi-postgresql
-
-!!! note
- 👀 👈 📚 📟 🐩 `SQLAlchemy` 📟 👆 🔜 ⚙️ ⏮️ 🙆 🛠️.
-
- **FastAPI** 🎯 📟 🤪 🕧.
-
-## 🐜
-
-**FastAPI** 👷 ⏮️ 🙆 💽 & 🙆 👗 🗃 💬 💽.
-
-⚠ ⚓ ⚙️ "🐜": "🎚-🔗 🗺" 🗃.
-
-🐜 ✔️ 🧰 🗜 ("*🗺*") 🖖 *🎚* 📟 & 💽 🏓 ("*🔗*").
-
-⏮️ 🐜, 👆 🛎 ✍ 🎓 👈 🎨 🏓 🗄 💽, 🔠 🔢 🎓 🎨 🏓, ⏮️ 📛 & 🆎.
-
-🖼 🎓 `Pet` 💪 🎨 🗄 🏓 `pets`.
-
-& 🔠 *👐* 🎚 👈 🎓 🎨 ⏭ 💽.
-
-🖼 🎚 `orion_cat` (👐 `Pet`) 💪 ✔️ 🔢 `orion_cat.type`, 🏓 `type`. & 💲 👈 🔢 💪, ✅ `"cat"`.
-
-👫 🐜 ✔️ 🧰 ⚒ 🔗 ⚖️ 🔗 🖖 🏓 ⚖️ 👨💼.
-
-👉 🌌, 👆 💪 ✔️ 🔢 `orion_cat.owner` & 👨💼 🔜 🔌 💽 👉 🐶 👨💼, ✊ ⚪️➡️ 🏓 *👨💼*.
-
-, `orion_cat.owner.name` 💪 📛 (⚪️➡️ `name` 🏓 `owners` 🏓) 👉 🐶 👨💼.
-
-⚫️ 💪 ✔️ 💲 💖 `"Arquilian"`.
-
-& 🐜 🔜 🌐 👷 🤚 ℹ ⚪️➡️ 🔗 🏓 *👨💼* 🕐❔ 👆 🔄 🔐 ⚫️ ⚪️➡️ 👆 🐶 🎚.
-
-⚠ 🐜 🖼: ✳-🐜 (🍕 ✳ 🛠️), 🇸🇲 🐜 (🍕 🇸🇲, 🔬 🛠️) & 🏒 (🔬 🛠️), 👪 🎏.
-
-📥 👥 🔜 👀 ❔ 👷 ⏮️ **🇸🇲 🐜**.
-
-🎏 🌌 👆 💪 ⚙️ 🙆 🎏 🐜.
-
-!!! tip
- 📤 🌓 📄 ⚙️ 🏒 📥 🩺.
-
-## 📁 📊
-
-👫 🖼, ➡️ 💬 👆 ✔️ 📁 📛 `my_super_project` 👈 🔌 🎧-📁 🤙 `sql_app` ⏮️ 📊 💖 👉:
-
-```
-.
-└── sql_app
- ├── __init__.py
- ├── crud.py
- ├── database.py
- ├── main.py
- ├── models.py
- └── schemas.py
-```
-
-📁 `__init__.py` 🛁 📁, ✋️ ⚫️ 💬 🐍 👈 `sql_app` ⏮️ 🌐 🚮 🕹 (🐍 📁) 📦.
-
-🔜 ➡️ 👀 ⚫️❔ 🔠 📁/🕹 🔨.
-
-## ❎ `SQLAlchemy`
-
-🥇 👆 💪 ❎ `SQLAlchemy`:
-
-
-
-## 🔗 ⏮️ 💽 🔗
-
-🚥 👆 💚 🔬 🗄 💽 (📁) 🔗, ➡ FastAPI, ℹ 🚮 🎚, 🚮 🏓, 🏓, ⏺, 🔀 📊, ♒️. 👆 💪 ⚙️ 💽 🖥 🗄.
-
-⚫️ 🔜 👀 💖 👉:
-
-
-
-👆 💪 ⚙️ 💳 🗄 🖥 💖 🗄 📋 ⚖️ ExtendsClass.
-
-## 🎛 💽 🎉 ⏮️ 🛠️
-
-🚥 👆 💪 🚫 ⚙️ 🔗 ⏮️ `yield` - 🖼, 🚥 👆 🚫 ⚙️ **🐍 3️⃣.7️⃣** & 💪 🚫 ❎ "🐛" 🤔 🔛 **🐍 3️⃣.6️⃣** - 👆 💪 ⚒ 🆙 🎉 "🛠️" 🎏 🌌.
-
-"🛠️" 🌖 🔢 👈 🕧 🛠️ 🔠 📨, ⏮️ 📟 🛠️ ⏭, & 📟 🛠️ ⏮️ 🔗 🔢.
-
-### ✍ 🛠️
-
-🛠️ 👥 🔜 🚮 (🔢) 🔜 ✍ 🆕 🇸🇲 `SessionLocal` 🔠 📨, 🚮 ⚫️ 📨 & ⤴️ 🔐 ⚫️ 🕐 📨 🏁.
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python hl_lines="14-22"
- {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!}
- ```
-
-=== "🐍 3️⃣.9️⃣ & 🔛"
-
- ```Python hl_lines="12-20"
- {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!}
- ```
-
-!!! info
- 👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫.
-
- & ⤴️ 👥 🔐 ⚫️ `finally` 🍫.
-
- 👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨.
-
-### 🔃 `request.state`
-
-`request.state` 🏠 🔠 `Request` 🎚. ⚫️ 📤 🏪 ❌ 🎚 📎 📨 ⚫️, 💖 💽 🎉 👉 💼. 👆 💪 ✍ 🌅 🔃 ⚫️ 💃 🩺 🔃 `Request` 🇵🇸.
-
-👥 👉 💼, ⚫️ ℹ 👥 🚚 👁 💽 🎉 ⚙️ 🔘 🌐 📨, & ⤴️ 🔐 ⏮️ (🛠️).
-
-### 🔗 ⏮️ `yield` ⚖️ 🛠️
-
-❎ **🛠️** 📥 🎏 ⚫️❔ 🔗 ⏮️ `yield` 🔨, ⏮️ 🔺:
-
-* ⚫️ 🚚 🌖 📟 & 👄 🌅 🏗.
-* 🛠️ ✔️ `async` 🔢.
- * 🚥 📤 📟 ⚫️ 👈 ✔️ "⌛" 🕸, ⚫️ 💪 "🍫" 👆 🈸 📤 & 📉 🎭 🍖.
- * 👐 ⚫️ 🎲 🚫 📶 ⚠ 📥 ⏮️ 🌌 `SQLAlchemy` 👷.
- * ✋️ 🚥 👆 🚮 🌖 📟 🛠️ 👈 ✔️ 📚 👤/🅾 ⌛, ⚫️ 💪 ⤴️ ⚠.
-* 🛠️ 🏃 *🔠* 📨.
- * , 🔗 🔜 ✍ 🔠 📨.
- * 🕐❔ *➡ 🛠️* 👈 🍵 👈 📨 🚫 💪 💽.
-
-!!! tip
- ⚫️ 🎲 👍 ⚙️ 🔗 ⏮️ `yield` 🕐❔ 👫 🥃 ⚙️ 💼.
-
-!!! info
- 🔗 ⏮️ `yield` 🚮 ⏳ **FastAPI**.
-
- ⏮️ ⏬ 👉 🔰 🕴 ✔️ 🖼 ⏮️ 🛠️ & 📤 🎲 📚 🈸 ⚙️ 🛠️ 💽 🎉 🧾.
diff --git a/docs/em/docs/tutorial/static-files.md b/docs/em/docs/tutorial/static-files.md
deleted file mode 100644
index 6090c53385f32..0000000000000
--- a/docs/em/docs/tutorial/static-files.md
+++ /dev/null
@@ -1,39 +0,0 @@
-# 🎻 📁
-
-👆 💪 🍦 🎻 📁 🔁 ⚪️➡️ 📁 ⚙️ `StaticFiles`.
-
-## ⚙️ `StaticFiles`
-
-* 🗄 `StaticFiles`.
-* "🗻" `StaticFiles()` 👐 🎯 ➡.
-
-```Python hl_lines="2 6"
-{!../../../docs_src/static_files/tutorial001.py!}
-```
-
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.staticfiles import StaticFiles`.
-
- **FastAPI** 🚚 🎏 `starlette.staticfiles` `fastapi.staticfiles` 🏪 👆, 👩💻. ✋️ ⚫️ 🤙 👟 🔗 ⚪️➡️ 💃.
-
-### ⚫️❔ "🗜"
-
-"🗜" ⛓ ❎ 🏁 "🔬" 🈸 🎯 ➡, 👈 ⤴️ ✊ 💅 🚚 🌐 🎧-➡.
-
-👉 🎏 ⚪️➡️ ⚙️ `APIRouter` 🗻 🈸 🍕 🔬. 🗄 & 🩺 ⚪️➡️ 👆 👑 🈸 🏆 🚫 🔌 🕳 ⚪️➡️ 🗻 🈸, ♒️.
-
-👆 💪 ✍ 🌅 🔃 👉 **🏧 👩💻 🦮**.
-
-## ℹ
-
-🥇 `"/static"` 🔗 🎧-➡ 👉 "🎧-🈸" 🔜 "🗻" 🔛. , 🙆 ➡ 👈 ▶️ ⏮️ `"/static"` 🔜 🍵 ⚫️.
-
-`directory="static"` 🔗 📛 📁 👈 🔌 👆 🎻 📁.
-
-`name="static"` 🤝 ⚫️ 📛 👈 💪 ⚙️ 🔘 **FastAPI**.
-
-🌐 👫 🔢 💪 🎏 🌘 "`static`", 🔆 👫 ⏮️ 💪 & 🎯 ℹ 👆 👍 🈸.
-
-## 🌅 ℹ
-
-🌖 ℹ & 🎛 ✅ 💃 🩺 🔃 🎻 📁.
diff --git a/docs/em/docs/tutorial/testing.md b/docs/em/docs/tutorial/testing.md
deleted file mode 100644
index 999d67cd3536f..0000000000000
--- a/docs/em/docs/tutorial/testing.md
+++ /dev/null
@@ -1,188 +0,0 @@
-# 🔬
-
-👏 💃, 🔬 **FastAPI** 🈸 ⏩ & 😌.
-
-⚫️ ⚓️ 🔛 🇸🇲, ❔ 🔄 🏗 ⚓️ 🔛 📨, ⚫️ 📶 😰 & 🏋️.
-
-⏮️ ⚫️, 👆 💪 ⚙️ ✳ 🔗 ⏮️ **FastAPI**.
-
-## ⚙️ `TestClient`
-
-!!! info
- ⚙️ `TestClient`, 🥇 ❎ `httpx`.
-
- 🤶 Ⓜ. `pip install httpx`.
-
-🗄 `TestClient`.
-
-✍ `TestClient` 🚶♀️ 👆 **FastAPI** 🈸 ⚫️.
-
-✍ 🔢 ⏮️ 📛 👈 ▶️ ⏮️ `test_` (👉 🐩 `pytest` 🏛).
-
-⚙️ `TestClient` 🎚 🎏 🌌 👆 ⏮️ `httpx`.
-
-✍ 🙅 `assert` 📄 ⏮️ 🐩 🐍 🧬 👈 👆 💪 ✅ (🔄, 🐩 `pytest`).
-
-```Python hl_lines="2 12 15-18"
-{!../../../docs_src/app_testing/tutorial001.py!}
-```
-
-!!! tip
- 👀 👈 🔬 🔢 😐 `def`, 🚫 `async def`.
-
- & 🤙 👩💻 😐 🤙, 🚫 ⚙️ `await`.
-
- 👉 ✔ 👆 ⚙️ `pytest` 🔗 🍵 🤢.
-
-!!! note "📡 ℹ"
- 👆 💪 ⚙️ `from starlette.testclient import TestClient`.
-
- **FastAPI** 🚚 🎏 `starlette.testclient` `fastapi.testclient` 🏪 👆, 👩💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃.
-
-!!! tip
- 🚥 👆 💚 🤙 `async` 🔢 👆 💯 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 (✅ 🔁 💽 🔢), ✔️ 👀 [🔁 💯](../advanced/async-tests.md){.internal-link target=_blank} 🏧 🔰.
-
-## 🎏 💯
-
-🎰 🈸, 👆 🎲 🔜 ✔️ 👆 💯 🎏 📁.
-
-& 👆 **FastAPI** 🈸 5️⃣📆 ✍ 📚 📁/🕹, ♒️.
-
-### **FastAPI** 📱 📁
-
-➡️ 💬 👆 ✔️ 📁 📊 🔬 [🦏 🈸](./bigger-applications.md){.internal-link target=_blank}:
-
-```
-.
-├── app
-│ ├── __init__.py
-│ └── main.py
-```
-
-📁 `main.py` 👆 ✔️ 👆 **FastAPI** 📱:
-
-
-```Python
-{!../../../docs_src/app_testing/main.py!}
-```
-
-### 🔬 📁
-
-⤴️ 👆 💪 ✔️ 📁 `test_main.py` ⏮️ 👆 💯. ⚫️ 💪 🖖 🔛 🎏 🐍 📦 (🎏 📁 ⏮️ `__init__.py` 📁):
-
-``` hl_lines="5"
-.
-├── app
-│ ├── __init__.py
-│ ├── main.py
-│ └── test_main.py
-```
-
-↩️ 👉 📁 🎏 📦, 👆 💪 ⚙️ ⚖ 🗄 🗄 🎚 `app` ⚪️➡️ `main` 🕹 (`main.py`):
-
-```Python hl_lines="3"
-{!../../../docs_src/app_testing/test_main.py!}
-```
-
-...& ✔️ 📟 💯 💖 ⏭.
-
-## 🔬: ↔ 🖼
-
-🔜 ➡️ ↔ 👉 🖼 & 🚮 🌖 ℹ 👀 ❔ 💯 🎏 🍕.
-
-### ↔ **FastAPI** 📱 📁
-
-➡️ 😣 ⏮️ 🎏 📁 📊 ⏭:
-
-```
-.
-├── app
-│ ├── __init__.py
-│ ├── main.py
-│ └── test_main.py
-```
-
-➡️ 💬 👈 🔜 📁 `main.py` ⏮️ 👆 **FastAPI** 📱 ✔️ 🎏 **➡ 🛠️**.
-
-⚫️ ✔️ `GET` 🛠️ 👈 💪 📨 ❌.
-
-⚫️ ✔️ `POST` 🛠️ 👈 💪 📨 📚 ❌.
-
-👯♂️ *➡ 🛠️* 🚚 `X-Token` 🎚.
-
-=== "🐍 3️⃣.6️⃣ & 🔛"
-
- ```Python
- {!> ../../../docs_src/app_testing/app_b/main.py!}
- ```
-
-=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
-
- ```Python
- {!> ../../../docs_src/app_testing/app_b_py310/main.py!}
- ```
-
-### ↔ 🔬 📁
-
-👆 💪 ⤴️ ℹ `test_main.py` ⏮️ ↔ 💯:
-
-```Python
-{!> ../../../docs_src/app_testing/app_b/test_main.py!}
-```
-
-🕐❔ 👆 💪 👩💻 🚶♀️ ℹ 📨 & 👆 🚫 💭 ❔, 👆 💪 🔎 (🇺🇸🔍) ❔ ⚫️ `httpx`, ⚖️ ❔ ⚫️ ⏮️ `requests`, 🇸🇲 🔧 ⚓️ 🔛 📨' 🔧.
-
-⤴️ 👆 🎏 👆 💯.
-
-🤶 Ⓜ.:
-
-* 🚶♀️ *➡* ⚖️ *🔢* 🔢, 🚮 ⚫️ 📛 ⚫️.
-* 🚶♀️ 🎻 💪, 🚶♀️ 🐍 🎚 (✅ `dict`) 🔢 `json`.
-* 🚥 👆 💪 📨 *📨 💽* ↩️ 🎻, ⚙️ `data` 🔢 ↩️.
-* 🚶♀️ *🎚*, ⚙️ `dict` `headers` 🔢.
-* *🍪*, `dict` `cookies` 🔢.
-
-🌖 ℹ 🔃 ❔ 🚶♀️ 💽 👩💻 (⚙️ `httpx` ⚖️ `TestClient`) ✅ 🇸🇲 🧾.
-
-!!! info
- 🗒 👈 `TestClient` 📨 💽 👈 💪 🗜 🎻, 🚫 Pydantic 🏷.
-
- 🚥 👆 ✔️ Pydantic 🏷 👆 💯 & 👆 💚 📨 🚮 💽 🈸 ⏮️ 🔬, 👆 💪 ⚙️ `jsonable_encoder` 🔬 [🎻 🔗 🔢](encoder.md){.internal-link target=_blank}.
-
-## 🏃 ⚫️
-
-⏮️ 👈, 👆 💪 ❎ `pytest`:
-
-lt
+* XWT
+* PSGI
+
+### The abbr gives a full phrase and an explanation { #the-abbr-gives-a-full-phrase-and-an-explanation }
+
+* MDN
+* I/O.
+
+////
+
+//// tab | Info
+
+"title" attributes of "abbr" elements are translated following some specific instructions.
+
+Translations can add their own "abbr" elements which the LLM should not remove. E.g. to explain English words.
+
+See section `### HTML abbr elements` in the general prompt in `scripts/translate.py`.
+
+////
+
+## HTML "dfn" elements { #html-dfn-elements }
+
+* cluster
+* Deep Learning
+
+## Headings { #headings }
+
+//// tab | Test
+
+### Develop a webapp - a tutorial { #develop-a-webapp-a-tutorial }
+
+Hello.
+
+### Type hints and -annotations { #type-hints-and-annotations }
+
+Hello again.
+
+### Super- and subclasses { #super-and-subclasses }
+
+Hello again.
+
+////
+
+//// tab | Info
+
+The only hard rule for headings is that the LLM leaves the hash part inside curly brackets unchanged, which ensures that links do not break.
+
+See section `### Headings` in the general prompt in `scripts/translate.py`.
+
+For some language specific instructions, see e.g. section `### Headings` in `docs/de/llm-prompt.md`.
+
+////
+
+## Terms used in the docs { #terms-used-in-the-docs }
+
+//// tab | Test
+
+* you
+* your
+
+* e.g.
+* etc.
+
+* `foo` as an `int`
+* `bar` as a `str`
+* `baz` as a `list`
+
+* the Tutorial - User guide
+* the Advanced User Guide
+* the SQLModel docs
+* the API docs
+* the automatic docs
+
+* Data Science
+* Deep Learning
+* Machine Learning
+* Dependency Injection
+* HTTP Basic authentication
+* HTTP Digest
+* ISO format
+* the JSON Schema standard
+* the JSON schema
+* the schema definition
+* Password Flow
+* Mobile
+
+* deprecated
+* designed
+* invalid
+* on the fly
+* standard
+* default
+* case-sensitive
+* case-insensitive
+
+* to serve the application
+* to serve the page
+
+* the app
+* the application
+
+* the request
+* the response
+* the error response
+
+* the path operation
+* the path operation decorator
+* the path operation function
+
+* the body
+* the request body
+* the response body
+* the JSON body
+* the form body
+* the file body
+* the function body
+
+* the parameter
+* the body parameter
+* the path parameter
+* the query parameter
+* the cookie parameter
+* the header parameter
+* the form parameter
+* the function parameter
+
+* the event
+* the startup event
+* the startup of the server
+* the shutdown event
+* the lifespan event
+
+* the handler
+* the event handler
+* the exception handler
+* to handle
+
+* the model
+* the Pydantic model
+* the data model
+* the database model
+* the form model
+* the model object
+
+* the class
+* the base class
+* the parent class
+* the subclass
+* the child class
+* the sibling class
+* the class method
+
+* the header
+* the headers
+* the authorization header
+* the `Authorization` header
+* the forwarded header
+
+* the dependency injection system
+* the dependency
+* the dependable
+* the dependant
+
+* I/O bound
+* CPU bound
+* concurrency
+* parallelism
+* multiprocessing
+
+* the env var
+* the environment variable
+* the `PATH`
+* the `PATH` variable
+
+* the authentication
+* the authentication provider
+* the authorization
+* the authorization form
+* the authorization provider
+* the user authenticates
+* the system authenticates the user
+
+* the CLI
+* the command line interface
+
+* the server
+* the client
+
+* the cloud provider
+* the cloud service
+
+* the development
+* the development stages
+
+* the dict
+* the dictionary
+* the enumeration
+* the enum
+* the enum member
+
+* the encoder
+* the decoder
+* to encode
+* to decode
+
+* the exception
+* to raise
+
+* the expression
+* the statement
+
+* the frontend
+* the backend
+
+* the GitHub discussion
+* the GitHub issue
+
+* the performance
+* the performance optimization
+
+* the return type
+* the return value
+
+* the security
+* the security scheme
+
+* the task
+* the background task
+* the task function
+
+* the template
+* the template engine
+
+* the type annotation
+* the type hint
+
+* the server worker
+* the Uvicorn worker
+* the Gunicorn Worker
+* the worker process
+* the worker class
+* the workload
+
+* the deployment
+* to deploy
+
+* the SDK
+* the software development kit
+
+* the `APIRouter`
+* the `requirements.txt`
+* the Bearer Token
+* the breaking change
+* the bug
+* the button
+* the callable
+* the code
+* the commit
+* the context manager
+* the coroutine
+* the database session
+* the disk
+* the domain
+* the engine
+* the fake X
+* the HTTP GET method
+* the item
+* the library
+* the lifespan
+* the lock
+* the middleware
+* the mobile application
+* the module
+* the mounting
+* the network
+* the origin
+* the override
+* the payload
+* the processor
+* the property
+* the proxy
+* the pull request
+* the query
+* the RAM
+* the remote machine
+* the status code
+* the string
+* the tag
+* the web framework
+* the wildcard
+* to return
+* to validate
+
+////
+
+//// tab | Info
+
+This is a not complete and not normative list of (mostly) technical terms seen in the docs. It may be helpful for the prompt designer to figure out for which terms the LLM needs a helping hand. For example when it keeps reverting a good translation to a suboptimal translation. Or when it has problems conjugating/declinating a term in your language.
+
+See e.g. section `### List of English terms and their preferred German translations` in `docs/de/llm-prompt.md`.
+
+////
diff --git a/docs/en/docs/about/index.md b/docs/en/docs/about/index.md
new file mode 100644
index 0000000000000..d178dfec75b23
--- /dev/null
+++ b/docs/en/docs/about/index.md
@@ -0,0 +1,3 @@
+# About { #about }
+
+About FastAPI, its design, inspiration and more. 🤓
diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md
index 624036ce974c5..577c06daa5cea 100644
--- a/docs/en/docs/advanced/additional-responses.md
+++ b/docs/en/docs/advanced/additional-responses.md
@@ -1,9 +1,12 @@
-# Additional Responses in OpenAPI
+# Additional Responses in OpenAPI { #additional-responses-in-openapi }
-!!! warning
- This is a rather advanced topic.
+/// warning
- If you are starting with **FastAPI**, you might not need this.
+This is a rather advanced topic.
+
+If you are starting with **FastAPI**, you might not need this.
+
+///
You can declare additional responses, with additional status codes, media types, descriptions, etc.
@@ -11,11 +14,11 @@ Those additional responses will be included in the OpenAPI schema, so they will
But for those additional responses you have to make sure you return a `Response` like `JSONResponse` directly, with your status code and content.
-## Additional Response with `model`
+## Additional Response with `model` { #additional-response-with-model }
You can pass to your *path operation decorators* a parameter `responses`.
-It receives a `dict`, the keys are status codes for each response, like `200`, and the values are other `dict`s with the information for each of them.
+It receives a `dict`: the keys are status codes for each response (like `200`), and the values are other `dict`s with the information for each of them.
Each of those response `dict`s can have a key `model`, containing a Pydantic model, just like `response_model`.
@@ -23,24 +26,28 @@ Each of those response `dict`s can have a key `model`, containing a Pydantic mod
For example, to declare another response with a status code `404` and a Pydantic model `Message`, you can write:
-```Python hl_lines="18 22"
-{!../../../docs_src/additional_responses/tutorial001.py!}
-```
+{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}
+
+/// note
+
+Keep in mind that you have to return the `JSONResponse` directly.
+
+///
+
+/// info
-!!! note
- Have in mind that you have to return the `JSONResponse` directly.
+The `model` key is not part of OpenAPI.
-!!! info
- The `model` key is not part of OpenAPI.
+**FastAPI** will take the Pydantic model from there, generate the JSON Schema, and put it in the correct place.
- **FastAPI** will take the Pydantic model from there, generate the `JSON Schema`, and put it in the correct place.
+The correct place is:
- The correct place is:
+* In the key `content`, that has as value another JSON object (`dict`) that contains:
+ * A key with the media type, e.g. `application/json`, that contains as value another JSON object, that contains:
+ * A key `schema`, that has as the value the JSON Schema from the model, here's the correct place.
+ * **FastAPI** adds a reference here to the global JSON Schemas in another place in your OpenAPI instead of including it directly. This way, other applications and clients can use those JSON Schemas directly, provide better code generation tools, etc.
- * In the key `content`, that has as value another JSON object (`dict`) that contains:
- * A key with the media type, e.g. `application/json`, that contains as value another JSON object, that contains:
- * A key `schema`, that has as the value the JSON Schema from the model, here's the correct place.
- * **FastAPI** adds a reference here to the global JSON Schemas in another place in your OpenAPI instead of including it directly. This way, other applications and clients can use those JSON Schemas directly, provide better code generation tools, etc.
+///
The generated responses in the OpenAPI for this *path operation* will be:
@@ -162,25 +169,29 @@ The schemas are referenced to another place inside the OpenAPI schema:
}
```
-## Additional media types for the main response
+## Additional media types for the main response { #additional-media-types-for-the-main-response }
You can use this same `responses` parameter to add different media types for the same main response.
For example, you can add an additional media type of `image/png`, declaring that your *path operation* can return a JSON object (with media type `application/json`) or a PNG image:
-```Python hl_lines="19-24 28"
-{!../../../docs_src/additional_responses/tutorial002.py!}
-```
+{* ../../docs_src/additional_responses/tutorial002_py310.py hl[17:22,26] *}
+
+/// note
+
+Notice that you have to return the image using a `FileResponse` directly.
+
+///
-!!! note
- Notice that you have to return the image using a `FileResponse` directly.
+/// info
-!!! info
- Unless you specify a different media type explicitly in your `responses` parameter, FastAPI will assume the response has the same media type as the main response class (default `application/json`).
+Unless you specify a different media type explicitly in your `responses` parameter, FastAPI will assume the response has the same media type as the main response class (default `application/json`).
- But if you have specified a custom response class with `None` as its media type, FastAPI will use `application/json` for any additional response that has an associated model.
+But if you have specified a custom response class with `None` as its media type, FastAPI will use `application/json` for any additional response that has an associated model.
-## Combining information
+///
+
+## Combining information { #combining-information }
You can also combine response information from multiple places, including the `response_model`, `status_code`, and `responses` parameters.
@@ -192,15 +203,13 @@ For example, you can declare a response with a status code `404` that uses a Pyd
And a response with a status code `200` that uses your `response_model`, but includes a custom `example`:
-```Python hl_lines="20-31"
-{!../../../docs_src/additional_responses/tutorial003.py!}
-```
+{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}
It will all be combined and included in your OpenAPI, and shown in the API docs:
-## Combine predefined responses and custom ones
+## Combine predefined responses and custom ones { #combine-predefined-responses-and-custom-ones }
You might want to have some predefined responses that apply to many *path operations*, but you want to combine them with custom responses needed by each *path operation*.
@@ -224,17 +233,15 @@ Here, `new_dict` will contain all the key-value pairs from `old_dict` plus the n
}
```
-You can use that technique to re-use some predefined responses in your *path operations* and combine them with additional custom ones.
+You can use that technique to reuse some predefined responses in your *path operations* and combine them with additional custom ones.
For example:
-```Python hl_lines="13-17 26"
-{!../../../docs_src/additional_responses/tutorial004.py!}
-```
+{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}
-## More information about OpenAPI responses
+## More information about OpenAPI responses { #more-information-about-openapi-responses }
To see what exactly you can include in the responses, you can check these sections in the OpenAPI specification:
-* OpenAPI Responses Object, it includes the `Response Object`.
-* OpenAPI Response Object, you can include anything from this directly in each response inside your `responses` parameter. Including `description`, `headers`, `content` (inside of this is that you declare different media types and JSON Schemas), and `links`.
+* [OpenAPI Responses Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responses-object), it includes the `Response Object`.
+* [OpenAPI Response Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#response-object), you can include anything from this directly in each response inside your `responses` parameter. Including `description`, `headers`, `content` (inside of this is that you declare different media types and JSON Schemas), and `links`.
diff --git a/docs/en/docs/advanced/additional-status-codes.md b/docs/en/docs/advanced/additional-status-codes.md
index 416444d3bdaae..3b6da2355718e 100644
--- a/docs/en/docs/advanced/additional-status-codes.md
+++ b/docs/en/docs/advanced/additional-status-codes.md
@@ -1,10 +1,10 @@
-# Additional Status Codes
+# Additional Status Codes { #additional-status-codes }
By default, **FastAPI** will return the responses using a `JSONResponse`, putting the content you return from your *path operation* inside of that `JSONResponse`.
It will use the default status code or the one you set in your *path operation*.
-## Additional status codes
+## Additional status codes { #additional-status-codes_1 }
If you want to return additional status codes apart from the main one, you can do that by returning a `Response` directly, like a `JSONResponse`, and set the additional status code directly.
@@ -14,56 +14,28 @@ But you also want it to accept new items. And when the items didn't exist before
To achieve that, import `JSONResponse`, and return your content there directly, setting the `status_code` that you want:
-=== "Python 3.10+"
+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
- ```
+/// warning
-=== "Python 3.9+"
+When you return a `Response` directly, like in the example above, it will be returned directly.
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
- ```
+It won't be serialized with a model, etc.
-=== "Python 3.6+"
+Make sure it has the data you want it to have, and that the values are valid JSON (if you are using `JSONResponse`).
- ```Python hl_lines="4 26"
- {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!}
- ```
+///
-=== "Python 3.10+ non-Annotated"
+/// note | Technical Details
- !!! tip
- Prefer to use the `Annotated` version if possible.
+You could also use `from starlette.responses import JSONResponse`.
- ```Python hl_lines="2 23"
- {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!}
- ```
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `status`.
-=== "Python 3.6+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="4 25"
- {!> ../../../docs_src/additional_status_codes/tutorial001.py!}
- ```
-
-!!! warning
- When you return a `Response` directly, like in the example above, it will be returned directly.
-
- It won't be serialized with a model, etc.
-
- Make sure it has the data you want it to have, and that the values are valid JSON (if you are using `JSONResponse`).
-
-!!! note "Technical Details"
- You could also use `from starlette.responses import JSONResponse`.
-
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `status`.
-
-## OpenAPI and API docs
+## OpenAPI and API docs { #openapi-and-api-docs }
If you return additional status codes and responses directly, they won't be included in the OpenAPI schema (the API docs), because FastAPI doesn't have a way to know beforehand what you are going to return.
-But you can document that in your code, using: [Additional Responses](additional-responses.md){.internal-link target=_blank}.
+But you can document that in your code, using: [Additional Responses](additional-responses.md).
diff --git a/docs/en/docs/advanced/advanced-dependencies.md b/docs/en/docs/advanced/advanced-dependencies.md
index 402c5d7553f9b..6c940f5a9b64e 100644
--- a/docs/en/docs/advanced/advanced-dependencies.md
+++ b/docs/en/docs/advanced/advanced-dependencies.md
@@ -1,6 +1,6 @@
-# Advanced Dependencies
+# Advanced Dependencies { #advanced-dependencies }
-## Parameterized dependencies
+## Parameterized dependencies { #parameterized-dependencies }
All the dependencies we have seen are a fixed function or class.
@@ -10,7 +10,7 @@ Let's imagine that we want to have a dependency that checks if the query paramet
But we want to be able to parameterize that fixed content.
-## A "callable" instance
+## A "callable" instance { #a-callable-instance }
In Python there's a way to make an instance of a class a "callable".
@@ -18,121 +18,146 @@ Not the class itself (which is already a callable), but an instance of that clas
To do that, we declare a method `__call__`:
-=== "Python 3.9+"
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+In this case, this `__call__` is what **FastAPI** will use to check for additional parameters and sub-dependencies, and this is what will be called to pass a value to the parameter in your *path operation function* later.
-=== "Python 3.6+"
+## Parameterize the instance { #parameterize-the-instance }
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+And now, we can use `__init__` to declare the parameters of the instance that we can use to "parameterize" the dependency:
-=== "Python 3.6+ non-Annotated"
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}
- !!! tip
- Prefer to use the `Annotated` version if possible.
+In this case, **FastAPI** won't ever touch or care about `__init__`, we will use it directly in our code.
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+## Create an instance { #create-an-instance }
-In this case, this `__call__` is what **FastAPI** will use to check for additional parameters and sub-dependencies, and this is what will be called to pass a value to the parameter in your *path operation function* later.
+We could create an instance of this class with:
-## Parameterize the instance
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}
-And now, we can use `__init__` to declare the parameters of the instance that we can use to "parameterize" the dependency:
+And that way we are able to "parameterize" our dependency, that now has `"bar"` inside of it, as the attribute `checker.fixed_content`.
-=== "Python 3.9+"
+## Use the instance as a dependency { #use-the-instance-as-a-dependency }
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+Then, we could use this `checker` in a `Depends(checker)`, instead of `Depends(FixedContentQueryChecker)`, because the dependency is the instance, `checker`, not the class itself.
-=== "Python 3.6+"
+And when solving the dependency, **FastAPI** will call this `checker` like:
- ```Python hl_lines="8"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+```Python
+checker(q="somequery")
+```
-=== "Python 3.6+ non-Annotated"
+...and pass whatever that returns as the value of the dependency in our *path operation function* as the parameter `fixed_content_included`:
- !!! tip
- Prefer to use the `Annotated` version if possible.
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+/// tip
-In this case, **FastAPI** won't ever touch or care about `__init__`, we will use it directly in our code.
+All this might seem contrived. And it might not be very clear how is it useful yet.
-## Create an instance
+These examples are intentionally simple, but show how it all works.
-We could create an instance of this class with:
+In the chapters about security, there are utility functions that are implemented in this same way.
-=== "Python 3.9+"
+If you understood all this, you already know how those utility tools for security work underneath.
- ```Python hl_lines="18"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+///
-=== "Python 3.6+"
+## Dependencies with `yield`, `HTTPException`, `except` and Background Tasks { #dependencies-with-yield-httpexception-except-and-background-tasks }
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+/// warning
-=== "Python 3.6+ non-Annotated"
+You most probably don't need these technical details.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+These details are useful mainly if you had a FastAPI application older than 0.121.0 and you are facing issues with dependencies with `yield`.
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+///
-And that way we are able to "parameterize" our dependency, that now has `"bar"` inside of it, as the attribute `checker.fixed_content`.
+Dependencies with `yield` have evolved over time to account for the different use cases and to fix some issues, here's a summary of what has changed.
-## Use the instance as a dependency
+### Dependencies with `yield` and `scope` { #dependencies-with-yield-and-scope }
-Then, we could use this `checker` in a `Depends(checker)`, instead of `Depends(FixedContentQueryChecker)`, because the dependency is the instance, `checker`, not the class itself.
+In version 0.121.0, FastAPI added support for `Depends(scope="function")` for dependencies with `yield`.
-And when solving the dependency, **FastAPI** will call this `checker` like:
+Using `Depends(scope="function")`, the exit code after `yield` is executed right after the *path operation function* is finished, before the response is sent back to the client.
-```Python
-checker(q="somequery")
-```
+And when using `Depends(scope="request")` (the default), the exit code after `yield` is executed after the response is sent.
-...and pass whatever that returns as the value of the dependency in our *path operation function* as the parameter `fixed_content_included`:
+You can read more about it in the docs for [Dependencies with `yield` - Early exit and `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope).
+
+### Dependencies with `yield` and `StreamingResponse`, Technical Details { #dependencies-with-yield-and-streamingresponse-technical-details }
+
+Before FastAPI 0.118.0, if you used a dependency with `yield`, it would run the exit code after the *path operation function* returned but right before sending the response.
+
+The intention was to avoid holding resources for longer than necessary, waiting for the response to travel through the network.
+
+This change also meant that if you returned a `StreamingResponse`, the exit code of the dependency with `yield` would have been already run.
+
+For example, if you had a database session in a dependency with `yield`, the `StreamingResponse` would not be able to use that session while streaming data because the session would have already been closed in the exit code after `yield`.
+
+This behavior was reverted in 0.118.0, to make the exit code after `yield` be executed after the response is sent.
+
+/// info
+
+As you will see below, this is very similar to the behavior before version 0.106.0, but with several improvements and bug fixes for corner cases.
+
+///
+
+#### Use Cases with Early Exit Code { #use-cases-with-early-exit-code }
+
+There are some use cases with specific conditions that could benefit from the old behavior of running the exit code of dependencies with `yield` before sending the response.
+
+For example, imagine you have code that uses a database session in a dependency with `yield` only to verify a user, but the database session is never used again in the *path operation function*, only in the dependency, **and** the response takes a long time to be sent, like a `StreamingResponse` that sends data slowly, but for some reason doesn't use the database.
+
+In this case, the database session would be held until the response is finished being sent, but if you don't use it, then it wouldn't be necessary to hold it.
+
+Here's how it could look like:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
+
+The exit code, the automatic closing of the `Session` in:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
+
+...would be run after the response finishes sending the slow data:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
+
+But as `generate_stream()` doesn't use the database session, it is not really necessary to keep the session open while sending the response.
+
+If you have this specific use case using SQLModel (or SQLAlchemy), you could explicitly close the session after you don't need it anymore:
+
+{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}
+
+That way the session would release the database connection, so other requests could use it.
+
+If you have a different use case that needs to exit early from a dependency with `yield`, please create a [GitHub Discussion Question](https://github.com/fastapi/fastapi/discussions/new?category=questions) with your specific use case and why you would benefit from having early closing for dependencies with `yield`.
+
+If there are compelling use cases for early closing in dependencies with `yield`, I would consider adding a new way to opt in to early closing.
+
+### Dependencies with `yield` and `except`, Technical Details { #dependencies-with-yield-and-except-technical-details }
+
+Before FastAPI 0.110.0, if you used a dependency with `yield`, and then you captured an exception with `except` in that dependency, and you didn't raise the exception again, the exception would be automatically raised/forwarded to any exception handlers or the internal server error handler.
-=== "Python 3.9+"
+This was changed in version 0.110.0 to fix unhandled memory consumption from forwarded exceptions without a handler (internal server errors), and to make it consistent with the behavior of regular Python code.
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!}
- ```
+### Background Tasks and Dependencies with `yield`, Technical Details { #background-tasks-and-dependencies-with-yield-technical-details }
-=== "Python 3.6+"
+Before FastAPI 0.106.0, raising exceptions after `yield` was not possible, the exit code in dependencies with `yield` was executed *after* the response was sent, so [Exception Handlers](../tutorial/handling-errors.md#install-custom-exception-handlers) would have already run.
- ```Python hl_lines="21"
- {!> ../../../docs_src/dependencies/tutorial011_an.py!}
- ```
+This was designed this way mainly to allow using the same objects "yielded" by dependencies inside of background tasks, because the exit code would be executed after the background tasks were finished.
-=== "Python 3.6+ non-Annotated"
+This was changed in FastAPI 0.106.0 with the intention to not hold resources while waiting for the response to travel through the network.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial011.py!}
- ```
+Additionally, a background task is normally an independent set of logic that should be handled separately, with its own resources (e.g. its own database connection).
-!!! tip
- All this might seem contrived. And it might not be very clear how is it useful yet.
+So, this way you will probably have cleaner code.
- These examples are intentionally simple, but show how it all works.
+///
- In the chapters about security, there are utility functions that are implemented in this same way.
+If you used to rely on this behavior, now you should create the resources for background tasks inside the background task itself, and use internally only data that doesn't depend on the resources of dependencies with `yield`.
- If you understood all this, you already know how those utility tools for security work underneath.
+For example, instead of using the same database session, you would create a new database session inside of the background task, and you would obtain the objects from the database using this new session. And then instead of passing the object from the database as a parameter to the background task function, you would pass the ID of that object and then obtain the object again inside the background task function.
diff --git a/docs/en/docs/advanced/advanced-python-types.md b/docs/en/docs/advanced/advanced-python-types.md
new file mode 100644
index 0000000000000..6495cbe443238
--- /dev/null
+++ b/docs/en/docs/advanced/advanced-python-types.md
@@ -0,0 +1,61 @@
+# Advanced Python Types { #advanced-python-types }
+
+Here are some additional ideas that might be useful when working with Python types.
+
+## Using `Union` or `Optional` { #using-union-or-optional }
+
+If your code for some reason can't use `|`, for example if it's not in a type annotation but in something like `response_model=`, instead of using the vertical bar (`|`) you can use `Union` from `typing`.
+
+For example, you could declare that something could be a `str` or `None`:
+
+```python
+from typing import Union
+
+
+def say_hi(name: Union[str, None]):
+ print(f"Hi {name}!")
+```
+
+`typing` also has a shortcut to declare that something could be `None`, with `Optional`.
+
+Here's a tip from my very **subjective** point of view:
+
+* 🚨 Avoid using `Optional[SomeType]`
+* Instead ✨ **use `Union[SomeType, None]`** ✨.
+
+Both are equivalent and underneath they are the same, but I would recommend `Union` instead of `Optional` because the word "**optional**" would seem to imply that the value is optional, and it actually means "it can be `None`", even if it's not optional and is still required.
+
+I think `Union[SomeType, None]` is more explicit about what it means.
+
+It's just about the words and names. But those words can affect how you and your teammates think about the code.
+
+As an example, let's take this function:
+
+```python
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+ print(f"Hey {name}!")
+```
+
+The parameter `name` is defined as `Optional[str]`, but it is **not optional**, you cannot call the function without the parameter:
+
+```Python
+say_hi() # Oh, no, this throws an error! 😱
+```
+
+The `name` parameter is **still required** (not *optional*) because it doesn't have a default value. Still, `name` accepts `None` as the value:
+
+```Python
+say_hi(name=None) # This works, None is valid 🎉
+```
+
+The good news is, in most cases, you will be able to simply use `|` to define unions of types:
+
+```python
+def say_hi(name: str | None):
+ print(f"Hey {name}!")
+```
+
+So, normally you don't have to worry about names like `Optional` and `Union`. 😎
diff --git a/docs/en/docs/advanced/async-tests.md b/docs/en/docs/advanced/async-tests.md
index 9b39d70fca6a8..c7ec5e9e2905f 100644
--- a/docs/en/docs/advanced/async-tests.md
+++ b/docs/en/docs/advanced/async-tests.md
@@ -1,4 +1,4 @@
-# Async Tests
+# Async Tests { #async-tests }
You have already seen how to test your **FastAPI** applications using the provided `TestClient`. Up to now, you have only seen how to write synchronous tests, without using `async` functions.
@@ -6,21 +6,21 @@ Being able to use asynchronous functions in your tests could be useful, for exam
Let's look at how we can make that work.
-## pytest.mark.anyio
+## pytest.mark.anyio { #pytest-mark-anyio }
If we want to call asynchronous functions in our tests, our test functions have to be asynchronous. AnyIO provides a neat plugin for this, that allows us to specify that some test functions are to be called asynchronously.
-## HTTPX
+## HTTPX { #httpx }
Even if your **FastAPI** application uses normal `def` functions instead of `async def`, it is still an `async` application underneath.
The `TestClient` does some magic inside to call the asynchronous FastAPI application in your normal `def` test functions, using standard pytest. But that magic doesn't work anymore when we're using it inside asynchronous functions. By running our tests asynchronously, we can no longer use the `TestClient` inside our test functions.
-The `TestClient` is based on HTTPX, and luckily, we can use it directly to test the API.
+The `TestClient` is based on [HTTPX](https://www.python-httpx.org), and luckily, we can use it directly to test the API.
-## Example
+## Example { #example }
-For a simple example, let's consider a file structure similar to the one described in [Bigger Applications](../tutorial/bigger-applications.md){.internal-link target=_blank} and [Testing](../tutorial/testing.md){.internal-link target=_blank}:
+For a simple example, let's consider a file structure similar to the one described in [Bigger Applications](../tutorial/bigger-applications.md) and [Testing](../tutorial/testing.md):
```
.
@@ -32,17 +32,13 @@ For a simple example, let's consider a file structure similar to the one describ
The file `main.py` would have:
-```Python
-{!../../../docs_src/async_tests/main.py!}
-```
+{* ../../docs_src/async_tests/app_a_py310/main.py *}
The file `test_main.py` would have the tests for `main.py`, it could look like this now:
-```Python
-{!../../../docs_src/async_tests/test_main.py!}
-```
+{* ../../docs_src/async_tests/app_a_py310/test_main.py *}
-## Run it
+## Run it { #run-it }
You can run your tests as usual via:
@@ -56,22 +52,21 @@ $ pytest
-## In Detail
+## In Detail { #in-detail }
The marker `@pytest.mark.anyio` tells pytest that this test function should be called asynchronously:
-```Python hl_lines="7"
-{!../../../docs_src/async_tests/test_main.py!}
-```
+{* ../../docs_src/async_tests/app_a_py310/test_main.py hl[7] *}
+
+/// tip
-!!! tip
- Note that the test function is now `async def` instead of just `def` as before when using the `TestClient`.
+Note that the test function is now `async def` instead of just `def` as before when using the `TestClient`.
+
+///
Then we can create an `AsyncClient` with the app, and send async requests to it, using `await`.
-```Python hl_lines="9-10"
-{!../../../docs_src/async_tests/test_main.py!}
-```
+{* ../../docs_src/async_tests/app_a_py310/test_main.py hl[9:12] *}
This is the equivalent to:
@@ -81,12 +76,24 @@ response = client.get('/')
...that we used to make our requests with the `TestClient`.
-!!! tip
- Note that we're using async/await with the new `AsyncClient` - the request is asynchronous.
+/// tip
-## Other Asynchronous Function Calls
+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 [florimondmanca/asgi-lifespan](https://github.com/florimondmanca/asgi-lifespan#usage).
+
+///
+
+## Other Asynchronous Function Calls { #other-asynchronous-function-calls }
As the testing function is now asynchronous, you can now also call (and `await`) other `async` functions apart from sending requests to your FastAPI application in your tests, exactly as you would call them anywhere else in your code.
-!!! tip
- If you encounter a `RuntimeError: Task attached to a different loop` when integrating asynchronous function calls in your tests (e.g. when using MongoDB's MotorClient) Remember to instantiate objects that need an event loop only within async functions, e.g. an `'@app.on_event("startup")` callback.
+/// tip
+
+If you encounter a `RuntimeError: Task attached to a different loop` when integrating asynchronous function calls in your tests (e.g. when using [MongoDB's MotorClient](https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop)), remember to instantiate objects that need an event loop only within async functions, e.g. an `@app.on_event("startup")` callback.
+
+///
diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md
index e7af77f3da1af..c413fccdfe152 100644
--- a/docs/en/docs/advanced/behind-a-proxy.md
+++ b/docs/en/docs/advanced/behind-a-proxy.md
@@ -1,6 +1,105 @@
-# Behind a Proxy
+# Behind a Proxy { #behind-a-proxy }
-In some situations, you might need to use a **proxy** server like Traefik or Nginx with a configuration that adds an extra path prefix that is not seen by your application.
+In many situations, you would use a **proxy** like Traefik or Nginx in front of your FastAPI app.
+
+These proxies could handle HTTPS certificates and other things.
+
+## Proxy Forwarded Headers { #proxy-forwarded-headers }
+
+A **proxy** in front of your application would normally set some headers on the fly before sending the requests to your **server** to let the server know that the request was **forwarded** by the proxy, letting it know the original (public) URL, including the domain, that it is using HTTPS, etc.
+
+The **server** program (for example **Uvicorn** via **FastAPI CLI**) is capable of interpreting these headers, and then passing that information to your application.
+
+But for security, as the server doesn't know it is behind a trusted proxy, it won't interpret those headers.
+
+/// note | Technical Details
+
+The proxy headers are:
+
+* [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-For)
+* [X-Forwarded-Proto](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-Proto)
+* [X-Forwarded-Host](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-Host)
+
+///
+
+### Enable Proxy Forwarded Headers { #enable-proxy-forwarded-headers }
+
+You can start FastAPI CLI with the *CLI Option* `--forwarded-allow-ips` and pass the IP addresses that should be trusted to read those forwarded headers.
+
+If you set it to `--forwarded-allow-ips="*"` it would trust all the incoming IPs.
+
+If your **server** is behind a trusted **proxy** and only the proxy talks to it, this would make it accept whatever is the IP of that **proxy**.
+
+
But if we access the docs UI at the "official" URL using the proxy with port `9999`, at `/api/v1/docs`, it works correctly! 🎉
-You can check it at http://127.0.0.1:9999/api/v1/docs:
+You can check it at [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs):
@@ -277,22 +384,23 @@ Right as we wanted it. ✔️
This is because FastAPI uses this `root_path` to create the default `server` in OpenAPI with the URL provided by `root_path`.
-## Additional servers
+## Additional servers { #additional-servers }
+
+/// warning
-!!! warning
- This is a more advanced use case. Feel free to skip it.
+This is a more advanced use case. Feel free to skip it.
+
+///
By default, **FastAPI** will create a `server` in the OpenAPI schema with the URL for the `root_path`.
-But you can also provide other alternative `servers`, for example if you want *the same* docs UI to interact with a staging and production environments.
+But you can also provide other alternative `servers`, for example if you want *the same* docs UI to interact with both a staging and a production environment.
If you pass a custom list of `servers` and there's a `root_path` (because your API lives behind a proxy), **FastAPI** will insert a "server" with this `root_path` at the beginning of the list.
For example:
-```Python hl_lines="4-7"
-{!../../../docs_src/behind_a_proxy/tutorial003.py!}
-```
+{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}
Will generate an OpenAPI schema like:
@@ -319,28 +427,40 @@ Will generate an OpenAPI schema like:
}
```
-!!! tip
- Notice the auto-generated server with a `url` value of `/api/v1`, taken from the `root_path`.
+/// tip
-In the docs UI at http://127.0.0.1:9999/api/v1/docs it would look like:
+Notice the auto-generated server with a `url` value of `/api/v1`, taken from the `root_path`.
+
+///
+
+In the docs UI at [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs) it would look like:
-!!! tip
- The docs UI will interact with the server that you select.
+/// tip
+
+The docs UI will interact with the server that you select.
+
+///
+
+/// note | Technical Details
-### Disable automatic server from `root_path`
+The `servers` property in the OpenAPI specification is optional.
+
+If you don't specify the `servers` parameter and `root_path` is equal to `/`, the `servers` property in the generated OpenAPI schema will be omitted entirely by default, which is the equivalent of a single server with a `url` value of `/`.
+
+///
+
+### Disable automatic server from `root_path` { #disable-automatic-server-from-root-path }
If you don't want **FastAPI** to include an automatic server using the `root_path`, you can use the parameter `root_path_in_servers=False`:
-```Python hl_lines="9"
-{!../../../docs_src/behind_a_proxy/tutorial004.py!}
-```
+{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}
and then it won't include it in the OpenAPI schema.
-## Mounting a sub-application
+## Mounting a sub-application { #mounting-a-sub-application }
-If you need to mount a sub-application (as described in [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}) while also using a proxy with `root_path`, you can do it normally, as you would expect.
+If you need to mount a sub-application (as described in [Sub Applications - Mounts](sub-applications.md)) while also using a proxy with `root_path`, you can do it normally, as you would expect.
FastAPI will internally use the `root_path` smartly, so it will just work. ✨
diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md
index ce2619e8de5fc..0dcb575176d17 100644
--- a/docs/en/docs/advanced/custom-response.md
+++ b/docs/en/docs/advanced/custom-response.md
@@ -1,93 +1,87 @@
-# Custom Response - HTML, Stream, File, others
+# Custom Response - HTML, Stream, File, others { #custom-response-html-stream-file-others }
-By default, **FastAPI** will return the responses using `JSONResponse`.
+By default, **FastAPI** will return JSON responses.
-You can override it by returning a `Response` directly as seen in [Return a Response directly](response-directly.md){.internal-link target=_blank}.
+You can override it by returning a `Response` directly as seen in [Return a Response directly](response-directly.md).
-But if you return a `Response` directly, the data won't be automatically converted, and the documentation won't be automatically generated (for example, including the specific "media type", in the HTTP header `Content-Type` as part of the generated OpenAPI).
+But if you return a `Response` directly (or any subclass, like `JSONResponse`), the data won't be automatically converted (even if you declare a `response_model`), and the documentation won't be automatically generated (for example, including the specific "media type", in the HTTP header `Content-Type` as part of the generated OpenAPI).
-But you can also declare the `Response` that you want to be used, in the *path operation decorator*.
+But you can also declare the `Response` that you want to be used (e.g. any `Response` subclass), in the *path operation decorator* using the `response_class` parameter.
The contents that you return from your *path operation function* will be put inside of that `Response`.
-And if that `Response` has a JSON media type (`application/json`), like is the case with the `JSONResponse` and `UJSONResponse`, the data you return will be automatically converted (and filtered) with any Pydantic `response_model` that you declared in the *path operation decorator*.
+/// note
-!!! note
- If you use a response class with no media type, FastAPI will expect your response to have no content, so it will not document the response format in its generated OpenAPI docs.
+If you use a response class with no media type, FastAPI will expect your response to have no content, so it will not document the response format in its generated OpenAPI docs.
-## Use `ORJSONResponse`
+///
-For example, if you are squeezing performance, you can install and use `orjson` and set the response to be `ORJSONResponse`.
+## JSON Responses { #json-responses }
-Import the `Response` class (sub-class) you want to use and declare it in the *path operation decorator*.
+By default FastAPI returns JSON responses.
-For large responses, returning a `Response` directly is much faster than returning a dictionary.
+If you declare a [Response Model](../tutorial/response-model.md) FastAPI will use it to serialize the data to JSON, using Pydantic.
-This is because by default, FastAPI will inspect every item inside and make sure it is serializable with JSON, using the same [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank} explained in the tutorial. This is what allows you to return **arbitrary objects**, for example database models.
+If you don't declare a response model, FastAPI will use the `jsonable_encoder` explained in [JSON Compatible Encoder](../tutorial/encoder.md) and put it in a `JSONResponse`.
-But if you are certain that the content that you are returning is **serializable with JSON**, you can pass it directly to the response class and avoid the extra overhead that FastAPI would have by passing your return content through the `jsonable_encoder` before passing it to the response class.
+If you declare a `response_class` with a JSON media type (`application/json`), like is the case with the `JSONResponse`, the data you return will be automatically converted (and filtered) with any Pydantic `response_model` that you declared in the *path operation decorator*. But the data won't be serialized to JSON bytes with Pydantic, instead it will be converted with the `jsonable_encoder` and then passed to the `JSONResponse` class, which will serialize it to bytes using the standard JSON library in Python.
-```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001b.py!}
-```
-
-!!! info
- The parameter `response_class` will also be used to define the "media type" of the response.
-
- In this case, the HTTP header `Content-Type` will be set to `application/json`.
+### JSON Performance { #json-performance }
- And it will be documented as such in OpenAPI.
+In short, if you want the maximum performance, use a [Response Model](../tutorial/response-model.md) and don't declare a `response_class` in the *path operation decorator*.
-!!! tip
- The `ORJSONResponse` is currently only available in FastAPI, not in Starlette.
+{* ../../docs_src/response_model/tutorial001_01_py310.py ln[15:17] hl[16] *}
-## HTML Response
+## HTML Response { #html-response }
To return a response with HTML directly from **FastAPI**, use `HTMLResponse`.
* Import `HTMLResponse`.
* Pass `HTMLResponse` as the parameter `response_class` of your *path operation decorator*.
-```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial002.py!}
-```
+{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}
+
+/// info
-!!! info
- The parameter `response_class` will also be used to define the "media type" of the response.
+The parameter `response_class` will also be used to define the "media type" of the response.
- In this case, the HTTP header `Content-Type` will be set to `text/html`.
+In this case, the HTTP header `Content-Type` will be set to `text/html`.
- And it will be documented as such in OpenAPI.
+And it will be documented as such in OpenAPI.
-### Return a `Response`
+///
-As seen in [Return a Response directly](response-directly.md){.internal-link target=_blank}, you can also override the response directly in your *path operation*, by returning it.
+### Return a `Response` { #return-a-response }
+
+As seen in [Return a Response directly](response-directly.md), you can also override the response directly in your *path operation*, by returning it.
The same example from above, returning an `HTMLResponse`, could look like:
-```Python hl_lines="2 7 19"
-{!../../../docs_src/custom_response/tutorial003.py!}
-```
+{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}
+
+/// warning
+
+A `Response` returned directly by your *path operation function* won't be documented in OpenAPI (for example, the `Content-Type` won't be documented) and won't be visible in the automatic interactive docs.
-!!! warning
- A `Response` returned directly by your *path operation function* won't be documented in OpenAPI (for example, the `Content-Type` won't be documented) and won't be visible in the automatic interactive docs.
+///
-!!! info
- Of course, the actual `Content-Type` header, status code, etc, will come from the `Response` object your returned.
+/// info
-### Document in OpenAPI and override `Response`
+Of course, the actual `Content-Type` header, status code, etc, will come from the `Response` object you returned.
+
+///
+
+### Document in OpenAPI and override `Response` { #document-in-openapi-and-override-response }
If you want to override the response from inside of the function but at the same time document the "media type" in OpenAPI, you can use the `response_class` parameter AND return a `Response` object.
The `response_class` will then be used only to document the OpenAPI *path operation*, but your `Response` will be used as is.
-#### Return an `HTMLResponse` directly
+#### Return an `HTMLResponse` directly { #return-an-htmlresponse-directly }
For example, it could be something like:
-```Python hl_lines="7 21 23"
-{!../../../docs_src/custom_response/tutorial004.py!}
-```
+{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}
In this example, the function `generate_html_response()` already generates and returns a `Response` instead of returning the HTML in a `str`.
@@ -97,18 +91,21 @@ But as you passed the `HTMLResponse` in the `response_class` too, **FastAPI** wi
-## Available responses
+## Available responses { #available-responses }
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`.
-!!! note "Technical Details"
- You could also use `from starlette.responses import HTMLResponse`.
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+///
-### `Response`
+### `Response` { #response }
The main `Response` class, all the other responses inherit from it.
@@ -121,66 +118,48 @@ It accepts the following parameters:
* `headers` - A `dict` of strings.
* `media_type` - A `str` giving the media type. E.g. `"text/html"`.
-FastAPI (actually Starlette) will automatically include a Content-Length header. It will also include a Content-Type header, based on the media_type and appending a charset for text types.
+FastAPI (actually Starlette) will automatically include a Content-Length header. It will also include a Content-Type header, based on the `media_type` and appending a charset for text types.
-```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
-```
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
-### `HTMLResponse`
+### `HTMLResponse` { #htmlresponse }
Takes some text or bytes and returns an HTML response, as you read above.
-### `PlainTextResponse`
+### `PlainTextResponse` { #plaintextresponse }
-Takes some text or bytes and returns an plain text response.
+Takes some text or bytes and returns a plain text response.
-```Python hl_lines="2 7 9"
-{!../../../docs_src/custom_response/tutorial005.py!}
-```
+{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}
-### `JSONResponse`
+### `JSONResponse` { #jsonresponse }
Takes some data and returns an `application/json` encoded response.
This is the default response used in **FastAPI**, as you read above.
-### `ORJSONResponse`
+/// note | Technical Details
-A fast alternative JSON response using `orjson`, as you read above.
+But if you declare a response model or return type, that will be used directly to serialize the data to JSON, and a response with the right media type for JSON will be returned directly, without using the `JSONResponse` class.
-### `UJSONResponse`
+This is the ideal way to get the best performance.
-An alternative JSON response using `ujson`.
+///
-!!! warning
- `ujson` is less careful than Python's built-in implementation in how it handles some edge-cases.
-
-```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001.py!}
-```
-
-!!! tip
- It's possible that `ORJSONResponse` might be a faster alternative.
-
-### `RedirectResponse`
+### `RedirectResponse` { #redirectresponse }
Returns an HTTP redirect. Uses a 307 status code (Temporary Redirect) by default.
You can return a `RedirectResponse` directly:
-```Python hl_lines="2 9"
-{!../../../docs_src/custom_response/tutorial006.py!}
-```
+{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}
---
Or you can use it in the `response_class` parameter:
-```Python hl_lines="2 7 9"
-{!../../../docs_src/custom_response/tutorial006b.py!}
-```
+{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}
If you do that, then you can return the URL directly from your *path operation* function.
@@ -190,79 +169,64 @@ In this case, the `status_code` used will be the default one for the `RedirectRe
You can also use the `status_code` parameter combined with the `response_class` parameter:
-```Python hl_lines="2 7 9"
-{!../../../docs_src/custom_response/tutorial006c.py!}
-```
+{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}
-### `StreamingResponse`
+### `StreamingResponse` { #streamingresponse }
-Takes an async generator or a normal generator/iterator and streams the response body.
+Takes an async generator or a normal generator/iterator (a function with `yield`) and streams the response body.
-```Python hl_lines="2 14"
-{!../../../docs_src/custom_response/tutorial007.py!}
-```
+{* ../../docs_src/custom_response/tutorial007_py310.py hl[3,16] *}
-#### Using `StreamingResponse` with file-like objects
+/// note | Technical Details
-If you have a file-like object (e.g. the object returned by `open()`), you can create a generator function to iterate over that file-like object.
+An `async` task can only be cancelled when it reaches an `await`. If there is no `await`, the generator (function with `yield`) can not be cancelled properly and may keep running even after cancellation is requested.
-That way, you don't have to read it all first in memory, and you can pass that generator function to the `StreamingResponse`, and return it.
+Since this small example does not need any `await` statements, we add an `await anyio.sleep(0)` to give the event loop a chance to handle cancellation.
-This includes many libraries to interact with cloud storage, video processing, and others.
+This would be even more important with large or infinite streams.
-```{ .python .annotate hl_lines="2 10-12 14" }
-{!../../../docs_src/custom_response/tutorial008.py!}
-```
+///
-1. This is the generator function. It's a "generator function" because it contains `yield` statements inside.
-2. By using a `with` block, we make sure that the file-like object is closed after the generator function is done. So, after it finishes sending the response.
-3. This `yield from` tells the function to iterate over that thing named `file_like`. And then, for each part iterated, yield that part as coming from this generator function.
+/// tip
- So, it is a generator function that transfers the "generating" work to something else internally.
+Instead of returning a `StreamingResponse` directly, you should probably follow the style in [Stream Data](./stream-data.md), it's much more convenient and handles cancellation behind the scenes for you.
- By doing it this way, we can put it in a `with` block, and that way, ensure that it is closed after finishing.
+If you are streaming JSON Lines, follow the [Stream JSON Lines](../tutorial/stream-json-lines.md) tutorial.
-!!! tip
- Notice that here as we are using standard `open()` that doesn't support `async` and `await`, we declare the path operation with normal `def`.
+///
-### `FileResponse`
+### `FileResponse` { #fileresponse }
Asynchronously streams a file as the response.
Takes a different set of arguments to instantiate than the other response types:
-* `path` - The filepath to the file to stream.
+* `path` - The file path to the file to stream.
* `headers` - Any custom headers to include, as a dictionary.
* `media_type` - A string giving the media type. If unset, the filename or path will be used to infer a media type.
* `filename` - If set, this will be included in the response `Content-Disposition`.
File responses will include appropriate `Content-Length`, `Last-Modified` and `ETag` headers.
-```Python hl_lines="2 10"
-{!../../../docs_src/custom_response/tutorial009.py!}
-```
+{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}
You can also use the `response_class` parameter:
-```Python hl_lines="2 8 10"
-{!../../../docs_src/custom_response/tutorial009b.py!}
-```
+{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}
In this case, you can return the file path directly from your *path operation* function.
-## Custom response class
+## Custom response class { #custom-response-class }
You can create your own custom response class, inheriting from `Response` and using it.
-For example, let's say that you want to use `orjson`, but with some custom settings not used in the included `ORJSONResponse` class.
+For example, let's say that you want to use [`orjson`](https://github.com/ijl/orjson) with some settings.
Let's say you want it to return indented and formatted JSON, so you want to use the orjson option `orjson.OPT_INDENT_2`.
You could create a `CustomORJSONResponse`. The main thing you have to do is create a `Response.render(content)` method that returns the content as `bytes`:
-```Python hl_lines="9-14 17"
-{!../../../docs_src/custom_response/tutorial009c.py!}
-```
+{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}
Now instead of returning:
@@ -280,21 +244,30 @@ Now instead of returning:
Of course, you will probably find much better ways to take advantage of this than formatting JSON. 😉
-## Default response class
+### `orjson` or Response Model { #orjson-or-response-model }
+
+If what you are looking for is performance, you are probably better off using a [Response Model](../tutorial/response-model.md) than an `orjson` response.
+
+With a response model, FastAPI will use Pydantic to serialize the data to JSON, without using intermediate steps, like converting it with `jsonable_encoder`, which would happen in any other case.
+
+And under the hood, Pydantic uses the same underlying Rust mechanisms as `orjson` to serialize to JSON, so you will already get the best performance with a response model.
+
+## Default response class { #default-response-class }
When creating a **FastAPI** class instance or an `APIRouter` you can specify which response class to use by default.
The parameter that defines this is `default_response_class`.
-In the example below, **FastAPI** will use `ORJSONResponse` by default, in all *path operations*, instead of `JSONResponse`.
+In the example below, **FastAPI** will use `HTMLResponse` by default, in all *path operations*, instead of JSON.
-```Python hl_lines="2 4"
-{!../../../docs_src/custom_response/tutorial010.py!}
-```
+{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}
+
+/// tip
+
+You can still override `response_class` in *path operations* as before.
-!!! tip
- You can still override `response_class` in *path operations* as before.
+///
-## Additional documentation
+## Additional documentation { #additional-documentation }
-You can also declare the media type and many other details in OpenAPI using `responses`: [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}.
+You can also declare the media type and many other details in OpenAPI using `responses`: [Additional Responses in OpenAPI](additional-responses.md).
diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md
index 72daca06ad9f7..52fe4ae7c83bd 100644
--- a/docs/en/docs/advanced/dataclasses.md
+++ b/docs/en/docs/advanced/dataclasses.md
@@ -1,14 +1,12 @@
-# Using Dataclasses
+# Using Dataclasses { #using-dataclasses }
FastAPI is built on top of **Pydantic**, and I have been showing you how to use Pydantic models to declare requests and responses.
-But FastAPI also supports using `dataclasses` the same way:
+But FastAPI also supports using [`dataclasses`](https://docs.python.org/3/library/dataclasses.html) the same way:
-```Python hl_lines="1 7-12 19-20"
-{!../../../docs_src/dataclasses/tutorial001.py!}
-```
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
-This is still supported thanks to **Pydantic**, as it has internal support for `dataclasses`.
+This is still supported thanks to **Pydantic**, as it has [internal support for `dataclasses`](https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel).
So, even with the code above that doesn't use Pydantic explicitly, FastAPI is using Pydantic to convert those standard dataclasses to Pydantic's own flavor of dataclasses.
@@ -20,20 +18,21 @@ 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.
+/// info
- So, you might still need to use Pydantic models.
+Keep in mind that dataclasses can't do everything Pydantic models can do.
- But if you have a bunch of dataclasses laying around, this is a nice trick to use them to power a web API using FastAPI. 🤓
+So, you might still need to use Pydantic models.
-## Dataclasses in `response_model`
+But if you have a bunch of dataclasses laying around, this is a nice trick to use them to power a web API using FastAPI. 🤓
+
+///
+
+## Dataclasses in `response_model` { #dataclasses-in-response-model }
You can also use `dataclasses` in the `response_model` parameter:
-```Python hl_lines="1 7-13 19"
-{!../../../docs_src/dataclasses/tutorial002.py!}
-```
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
The dataclass will be automatically converted to a Pydantic dataclass.
@@ -41,7 +40,7 @@ This way, its schema will show up in the API docs user interface:
-## Dataclasses in Nested Data Structures
+## Dataclasses in Nested Data Structures { #dataclasses-in-nested-data-structures }
You can also combine `dataclasses` with other type annotations to make nested data structures.
@@ -49,9 +48,7 @@ In some cases, you might still have to use Pydantic's version of `dataclasses`.
In that case, you can simply swap the standard `dataclasses` with `pydantic.dataclasses`, which is a drop-in replacement:
-```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" }
-{!../../../docs_src/dataclasses/tutorial003.py!}
-```
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
1. We still import `field` from standard `dataclasses`.
@@ -67,7 +64,7 @@ In that case, you can simply swap the standard `dataclasses` with `pydantic.data
6. Here we are returning a dictionary that contains `items` which is a list of dataclasses.
- FastAPI is still capable of serializing the data to JSON.
+ FastAPI is still capable of serializing the data to JSON.
7. Here the `response_model` is using a type annotation of a list of `Author` dataclasses.
@@ -77,7 +74,7 @@ In that case, you can simply swap the standard `dataclasses` with `pydantic.data
As always, in FastAPI you can combine `def` and `async def` as needed.
- If you need a refresher about when to use which, check out the section _"In a hurry?"_ in the docs about `async` and `await`.
+ If you need a refresher about when to use which, check out the section _"In a hurry?"_ in the docs about [`async` and `await`](../async.md#in-a-hurry).
9. This *path operation function* is not returning dataclasses (although it could), but a list of dictionaries with internal data.
@@ -87,12 +84,12 @@ You can combine `dataclasses` with other type annotations in many different comb
Check the in-code annotation tips above to see more specific details.
-## Learn More
+## Learn More { #learn-more }
You can also combine `dataclasses` with other Pydantic models, inherit from them, include them in your own models, etc.
-To learn more, check the Pydantic docs about dataclasses.
+To learn more, check the [Pydantic docs about dataclasses](https://docs.pydantic.dev/latest/concepts/dataclasses/).
-## Version
+## Version { #version }
This is available since FastAPI version `0.67.0`. 🔖
diff --git a/docs/en/docs/advanced/events.md b/docs/en/docs/advanced/events.md
index 6b7de41309bbe..820f06d55b7cf 100644
--- a/docs/en/docs/advanced/events.md
+++ b/docs/en/docs/advanced/events.md
@@ -1,4 +1,4 @@
-# Lifespan Events
+# Lifespan Events { #lifespan-events }
You can define logic (code) that should be executed before the application **starts up**. This means that this code will be executed **once**, **before** the application **starts receiving requests**.
@@ -8,7 +8,7 @@ Because this code is executed before the application **starts** taking requests,
This can be very useful for setting up **resources** that you need to use for the whole app, and that are **shared** among requests, and/or that you need to **clean up** afterwards. For example, a database connection pool, or loading a shared machine learning model.
-## Use Case
+## Use Case { #use-case }
Let's start with an example **use case** and then see how to solve it with this.
@@ -22,7 +22,7 @@ You could load it at the top level of the module/file, but that would also mean
That's what we'll solve, let's load the model before the requests are handled, but only right before the application starts receiving requests, not while the code is being loaded.
-## Lifespan
+## Lifespan { #lifespan }
You can define this *startup* and *shutdown* logic using the `lifespan` parameter of the `FastAPI` app, and a "context manager" (I'll show you what that is in a second).
@@ -30,40 +30,37 @@ Let's start with an example and then see it in detail.
We create an async function `lifespan()` with `yield` like this:
-```Python hl_lines="16 19"
-{!../../../docs_src/events/tutorial003.py!}
-```
+{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}
Here we are simulating the expensive *startup* operation of loading the model by putting the (fake) model function in the dictionary with machine learning models before the `yield`. This code will be executed **before** the application **starts taking requests**, during the *startup*.
And then, right after the `yield`, we unload the model. This code will be executed **after** the application **finishes handling requests**, right before the *shutdown*. This could, for example, release resources like memory or a GPU.
-!!! tip
- The `shutdown` would happen when you are **stopping** the application.
+/// tip
+
+The `shutdown` would happen when you are **stopping** the application.
- Maybe you need to start a new version, or you just got tired of running it. 🤷
+Maybe you need to start a new version, or you just got tired of running it. 🤷
-### Lifespan function
+///
+
+### Lifespan function { #lifespan-function }
The first thing to notice, is that we are defining an async function with `yield`. This is very similar to Dependencies with `yield`.
-```Python hl_lines="14-19"
-{!../../../docs_src/events/tutorial003.py!}
-```
+{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}
The first part of the function, before the `yield`, will be executed **before** the application starts.
And the part after the `yield` will be executed **after** the application has finished.
-### Async Context Manager
+### Async Context Manager { #async-context-manager }
If you check, the function is decorated with an `@asynccontextmanager`.
That converts the function into something called an "**async context manager**".
-```Python hl_lines="1 13"
-{!../../../docs_src/events/tutorial003.py!}
-```
+{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}
A **context manager** in Python is something that you can use in a `with` statement, for example, `open()` can be used as a context manager:
@@ -85,16 +82,17 @@ In our code example above, we don't use it directly, but we pass it to FastAPI f
The `lifespan` parameter of the `FastAPI` app takes an **async context manager**, so we can pass our new `lifespan` async context manager to it.
-```Python hl_lines="22"
-{!../../../docs_src/events/tutorial003.py!}
-```
+{* ../../docs_src/events/tutorial003_py310.py hl[22] *}
+
+## Alternative Events (deprecated) { #alternative-events-deprecated }
+
+/// warning
-## Alternative Events (deprecated)
+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.
-!!! warning
- The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above.
+You can probably skip this part.
- You can probably skip this part.
+///
There's an alternative way to define this logic to be executed during *startup* and during *shutdown*.
@@ -102,13 +100,11 @@ You can define event handlers (functions) that need to be executed before the ap
These functions can be declared with `async def` or normal `def`.
-### `startup` event
+### `startup` event { #startup-event }
To add a function that should be run before the application starts, declare it with the event `"startup"`:
-```Python hl_lines="8"
-{!../../../docs_src/events/tutorial001.py!}
-```
+{* ../../docs_src/events/tutorial001_py310.py hl[8] *}
In this case, the `startup` event handler function will initialize the items "database" (just a `dict`) with some values.
@@ -116,29 +112,33 @@ You can add more than one event handler function.
And your application won't start receiving requests until all the `startup` event handlers have completed.
-### `shutdown` event
+### `shutdown` event { #shutdown-event }
To add a function that should be run when the application is shutting down, declare it with the event `"shutdown"`:
-```Python hl_lines="6"
-{!../../../docs_src/events/tutorial002.py!}
-```
+{* ../../docs_src/events/tutorial002_py310.py hl[6] *}
Here, the `shutdown` event handler function will write a text line `"Application shutdown"` to a file `log.txt`.
-!!! info
- In the `open()` function, the `mode="a"` means "append", so, the line will be added after whatever is on that file, without overwriting the previous contents.
+/// info
+
+In the `open()` function, the `mode="a"` means "append", so, the line will be added after whatever is on that file, without overwriting the previous contents.
+
+///
-!!! tip
- Notice that in this case we are using a standard Python `open()` function that interacts with a file.
+/// tip
- So, it involves I/O (input/output), that requires "waiting" for things to be written to disk.
+Notice that in this case we are using a standard Python `open()` function that interacts with a file.
- But `open()` doesn't use `async` and `await`.
+So, it involves I/O (input/output), that requires "waiting" for things to be written to disk.
- So, we declare the event handler function with standard `def` instead of `async def`.
+But `open()` doesn't use `async` and `await`.
-### `startup` and `shutdown` together
+So, we declare the event handler function with standard `def` instead of `async def`.
+
+///
+
+### `startup` and `shutdown` together { #startup-and-shutdown-together }
There's a high chance that the logic for your *startup* and *shutdown* is connected, you might want to start something and then finish it, acquire a resource and then release it, etc.
@@ -146,17 +146,20 @@ Doing that in separated functions that don't share logic or variables together i
Because of that, it's now recommended to instead use the `lifespan` as explained above.
-## Technical Details
+## Technical Details { #technical-details }
Just a technical detail for the curious nerds. 🤓
-Underneath, in the ASGI technical specification, this is part of the Lifespan Protocol, and it defines events called `startup` and `shutdown`.
+Underneath, in the ASGI technical specification, this is part of the [Lifespan Protocol](https://asgi.readthedocs.io/en/latest/specs/lifespan.html), and it defines events called `startup` and `shutdown`.
+
+/// info
+
+You can read more about the Starlette `lifespan` handlers in [Starlette's Lifespan' docs](https://www.starlette.dev/lifespan/).
-!!! info
- You can read more about the Starlette `lifespan` handlers in Starlette's Lifespan' docs.
+Including how to handle lifespan state that can be used in other areas of your code.
- Including how to handle lifespan state that can be used in other areas of your code.
+///
-## Sub Applications
+## Sub Applications { #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).
diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md
index f439ed93ab54b..1fff3c9dc5284 100644
--- a/docs/en/docs/advanced/generate-clients.md
+++ b/docs/en/docs/advanced/generate-clients.md
@@ -1,122 +1,75 @@
-# Generate Clients
+# Generating SDKs { #generating-sdks }
-As **FastAPI** is based on the OpenAPI specification, you get automatic compatibility with many tools, including the automatic API docs (provided by Swagger UI).
+Because **FastAPI** is based on the **OpenAPI** specification, its APIs can be described in a standard format that many tools understand.
-One particular advantage that is not necessarily obvious is that you can **generate clients** (sometimes called **SDKs** ) for your API, for many different **programming languages**.
+This makes it easy to generate up-to-date **documentation**, client libraries (**SDKs**) in multiple languages, and **testing** or **automation workflows** that stay in sync with your code.
-## OpenAPI Client Generators
+In this guide, you'll learn how to generate a **TypeScript SDK** for your FastAPI backend.
-There are many tools to generate clients from **OpenAPI**.
+## Open Source SDK Generators { #open-source-sdk-generators }
-A common tool is OpenAPI Generator.
+A versatile option is the [OpenAPI Generator](https://openapi-generator.tech/), which supports **many programming languages** and can generate SDKs from your OpenAPI specification.
-If you are building a **frontend**, a very interesting alternative is openapi-typescript-codegen.
+For **TypeScript clients**, [Hey API](https://heyapi.dev/) is a purpose-built solution, providing an optimized experience for the TypeScript ecosystem.
-## Client and SDK Generators - Sponsor
+You can discover more SDK generators on [OpenAPI.Tools](https://openapi.tools/#sdk).
-There are also some **company-backed** Client and SDK generators based on OpenAPI (FastAPI), in some cases they can offer you **additional features** on top of high-quality generated SDKs/clients.
+/// tip
-Some of them also ✨ [**sponsor FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, this ensures the continued and healthy **development** of FastAPI and its **ecosystem**.
+FastAPI automatically generates **OpenAPI 3.1** specifications, so any tool you use must support this version.
-And it shows their true commitment to FastAPI and its **community** (you), as they not only want to provide you a **good service** but also want to make sure you have a **good and healthy framework**, FastAPI. 🙇
+///
-You might want to try their services and follow their guides:
+## SDK Generators from FastAPI Sponsors { #sdk-generators-from-fastapi-sponsors }
-* Fern
-* Speakeasy
+This section highlights **venture-backed** and **company-supported** solutions from companies that sponsor FastAPI. These products provide **additional features** and **integrations** on top of high-quality generated SDKs.
-## Generate a TypeScript Frontend Client
+By ✨ [**sponsoring FastAPI**](../help-fastapi.md#sponsor-the-author) ✨, these companies help ensure the framework and its **ecosystem** remain healthy and **sustainable**.
-Let's start with a simple FastAPI application:
+Their sponsorship also demonstrates a strong commitment to the FastAPI **community** (you), showing that they care not only about offering a **great service** but also about supporting a **robust and thriving framework**, FastAPI. 🙇
+
+For example, you might want to try:
-=== "Python 3.9+"
+* [Stainless](https://www.stainless.com/?utm_source=fastapi&utm_medium=referral)
+* [liblab](https://developers.liblab.com/tutorials/sdk-for-fastapi?utm_source=fastapi)
- ```Python hl_lines="7-9 12-13 16-17 21"
- {!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
- ```
+Some of these solutions may also be open source or offer free tiers, so you can try them without a financial commitment. Other commercial SDK generators are available and can be found online. 🤓
-=== "Python 3.6+"
+## Create a TypeScript SDK { #create-a-typescript-sdk }
- ```Python hl_lines="9-11 14-15 18 19 23"
- {!> ../../../docs_src/generate_clients/tutorial001.py!}
- ```
+Let's start with a simple FastAPI application:
+
+{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}
Notice that the *path operations* define the models they use for request payload and response payload, using the models `Item` and `ResponseMessage`.
-### API Docs
+### API Docs { #api-docs }
-If you go to the API docs, you will see that it has the **schemas** for the data to be sent in requests and received in responses:
+If you go to `/docs`, you will see that it has the **schemas** for the data to be sent in requests and received in responses:
You can see those schemas because they were declared with the models in the app.
-That information is available in the app's **OpenAPI schema**, and then shown in the API docs (by Swagger UI).
-
-And that same information from the models that is included in OpenAPI is what can be used to **generate the client code**.
+That information is available in the app's **OpenAPI schema**, and then shown in the API docs.
-### Generate a TypeScript Client
+That same information from the models that is included in OpenAPI is what can be used to **generate the client code**.
-Now that we have the app with the models, we can generate the client code for the frontend.
+### Hey API { #hey-api }
-#### Install `openapi-typescript-codegen`
+Once we have a FastAPI app with the models, we can use Hey API to generate a TypeScript client. The fastest way to do that is via npx.
-You can install `openapi-typescript-codegen` in your frontend code with:
-
-
@@ -124,8 +77,11 @@ You will also get autocompletion for the payload to send:
-!!! tip
- Notice the autocompletion for `name` and `price`, that was defined in the FastAPI application, in the `Item` model.
+/// tip
+
+Notice the autocompletion for `name` and `price`, that was defined in the FastAPI application, in the `Item` model.
+
+///
You will have inline errors for the data that you send:
@@ -135,40 +91,30 @@ The response object will also have autocompletion:
-## FastAPI App with Tags
+## FastAPI App with Tags { #fastapi-app-with-tags }
-In many cases your FastAPI app will be bigger, and you will probably use tags to separate different groups of *path operations*.
+In many cases, your FastAPI app will be bigger, and you will probably use tags to separate different groups of *path operations*.
For example, you could have a section for **items** and another section for **users**, and they could be separated by tags:
-=== "Python 3.9+"
-
- ```Python hl_lines="21 26 34"
- {!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="23 28 36"
- {!> ../../../docs_src/generate_clients/tutorial002.py!}
- ```
+{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}
-### Generate a TypeScript Client with Tags
+### Generate a TypeScript Client with Tags { #generate-a-typescript-client-with-tags }
If you generate a client for a FastAPI app using tags, it will normally also separate the client code based on the tags.
-This way you will be able to have things ordered and grouped correctly for the client code:
+This way, you will be able to have things ordered and grouped correctly for the client code:
-In this case you have:
+In this case, you have:
* `ItemsService`
* `UsersService`
-### Client Method Names
+### Client Method Names { #client-method-names }
-Right now the generated method names like `createItemItemsPost` don't look very clean:
+Right now, the generated method names like `createItemItemsPost` don't look very clean:
```TypeScript
ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
@@ -180,17 +126,17 @@ OpenAPI requires that each operation ID is unique across all the *path operation
But I'll show you how to improve that next. 🤓
-## Custom Operation IDs and Better Method Names
+## Custom Operation IDs and Better Method Names { #custom-operation-ids-and-better-method-names }
You can **modify** the way these operation IDs are **generated** to make them simpler and have **simpler method names** in the clients.
-In this case you will have to ensure that each operation ID is **unique** in some other way.
+In this case, you will have to ensure that each operation ID is **unique** in some other way.
For example, you could make sure that each *path operation* has a tag, and then generate the operation ID based on the **tag** and the *path operation* **name** (the function name).
-### Custom Generate Unique ID Function
+### Custom Generate Unique ID Function { #custom-generate-unique-id-function }
-FastAPI uses a **unique ID** for each *path operation*, it is used for the **operation ID** and also for the names of any needed custom models, for requests or responses.
+FastAPI uses a **unique ID** for each *path operation*, which is used for the **operation ID** and also for the names of any needed custom models, for requests or responses.
You can customize that function. It takes an `APIRoute` and outputs a string.
@@ -198,27 +144,17 @@ For example, here it is using the first tag (you will probably have only one tag
You can then pass that custom function to **FastAPI** as the `generate_unique_id_function` parameter:
-=== "Python 3.9+"
+{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}
- ```Python hl_lines="6-7 10"
- {!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
- ```
+### Generate a TypeScript Client with Custom Operation IDs { #generate-a-typescript-client-with-custom-operation-ids }
-=== "Python 3.6+"
-
- ```Python hl_lines="8-9 12"
- {!> ../../../docs_src/generate_clients/tutorial003.py!}
- ```
-
-### Generate a TypeScript Client with Custom Operation IDs
-
-Now if you generate the client again, you will see that it has the improved method names:
+Now, if you generate the client again, you will see that it has the improved method names:
As you see, the method names now have the tag and then the function name, now they don't include information from the URL path and the HTTP operation.
-### Preprocess the OpenAPI Specification for the Client Generator
+### Preprocess the OpenAPI Specification for the Client Generator { #preprocess-the-openapi-specification-for-the-client-generator }
The generated code still has some **duplicated information**.
@@ -226,45 +162,37 @@ We already know that this method is related to the **items** because that word i
We will probably still want to keep it for OpenAPI in general, as that will ensure that the operation IDs are **unique**.
-But for the generated client we could **modify** the OpenAPI operation IDs right before generating the clients, just to make those method names nicer and **cleaner**.
+But for the generated client, we could **modify** the OpenAPI operation IDs right before generating the clients, just to make those method names nicer and **cleaner**.
We could download the OpenAPI JSON to a file `openapi.json` and then we could **remove that prefixed tag** with a script like this:
-```Python
-{!../../../docs_src/generate_clients/tutorial004.py!}
+{* ../../docs_src/generate_clients/tutorial004_py310.py *}
+
+//// tab | Node.js
+
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
```
+////
+
With that, the operation IDs would be renamed from things like `items-get_items` to just `get_items`, that way the client generator can generate simpler method names.
-### Generate a TypeScript Client with the Preprocessed OpenAPI
-
-Now as the end result is in a file `openapi.json`, you would modify the `package.json` to use that local file, for example:
-
-```JSON hl_lines="7"
-{
- "name": "frontend-app",
- "version": "1.0.0",
- "description": "",
- "main": "index.js",
- "scripts": {
- "generate-client": "openapi --input ./openapi.json --output ./src/client --client axios"
- },
- "author": "",
- "license": "",
- "devDependencies": {
- "openapi-typescript-codegen": "^0.20.1",
- "typescript": "^4.6.2"
- }
-}
+### Generate a TypeScript Client with the Preprocessed OpenAPI { #generate-a-typescript-client-with-the-preprocessed-openapi }
+
+Since the end result is now in an `openapi.json` file, you need to update your input location:
+
+```sh
+npx @hey-api/openapi-ts -i ./openapi.json -o src/client
```
After generating the new client, you would now have **clean method names**, with all the **autocompletion**, **inline errors**, etc:
-## Benefits
+## Benefits { #benefits }
-When using the automatically generated clients you would **autocompletion** for:
+When using the automatically generated clients, you would get **autocompletion** for:
* Methods.
* Request payloads in the body, query parameters, etc.
@@ -274,6 +202,6 @@ You would also have **inline errors** for everything.
And whenever you update the backend code, and **regenerate** the frontend, it would have any new *path operations* available as methods, the old ones removed, and any other change would be reflected on the generated code. 🤓
-This also means that if something changed it will be **reflected** on the client code automatically. And if you **build** the client it will error out if you have any **mismatch** in the data used.
+This also means that if something changed, it will be **reflected** on the client code automatically. And if you **build** the client, it will error out if you have any **mismatch** in the data used.
So, you would **detect many errors** very early in the development cycle instead of having to wait for the errors to show up to your final users in production and then trying to debug where the problem is. ✨
diff --git a/docs/en/docs/advanced/index.md b/docs/en/docs/advanced/index.md
index d8dcd4ca6790a..c8056ab54f6d6 100644
--- a/docs/en/docs/advanced/index.md
+++ b/docs/en/docs/advanced/index.md
@@ -1,33 +1,21 @@
-# Advanced User Guide
+# Advanced User Guide { #advanced-user-guide }
-## Additional Features
+## Additional Features { #additional-features }
-The main [Tutorial - User Guide](../tutorial/){.internal-link target=_blank} should be enough to give you a tour through all the main features of **FastAPI**.
+The main [Tutorial - User Guide](../tutorial/index.md) should be enough to give you a tour through all the main features of **FastAPI**.
In the next sections you will see other options, configurations, and additional features.
-!!! tip
- The next sections are **not necessarily "advanced"**.
+/// tip
- And it's possible that for your use case, the solution is in one of them.
+The next sections are **not necessarily "advanced"**.
-## Read the Tutorial first
+And it's possible that for your use case, the solution is in one of them.
-You could still use most of the features in **FastAPI** with the knowledge from the main [Tutorial - User Guide](../tutorial/){.internal-link target=_blank}.
+///
-And the next sections assume you already read it, and assume that you know those main ideas.
-
-## External Courses
-
-Although the [Tutorial - User Guide](../tutorial/){.internal-link target=_blank} and this **Advanced User Guide** are written as a guided tutorial (like a book) and should be enough for you to **learn FastAPI**, you might want to complement it with additional courses.
-
-Or it might be the case that you just prefer to take other courses because they adapt better to your learning style.
+## Read the Tutorial first { #read-the-tutorial-first }
-Some course providers ✨ [**sponsor FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, this ensures the continued and healthy **development** of FastAPI and its **ecosystem**.
+You could still use most of the features in **FastAPI** with the knowledge from the main [Tutorial - User Guide](../tutorial/index.md).
-And it shows their true commitment to FastAPI and its **community** (you), as they not only want to provide you a **good learning experience** but also want to make sure you have a **good and healthy framework**, FastAPI. 🙇
-
-You might want to try their courses:
-
-* Talk Python Training
-* Test-Driven Development
+And the next sections assume you already read it, and assume that you know those main ideas.
diff --git a/docs/en/docs/advanced/json-base64-bytes.md b/docs/en/docs/advanced/json-base64-bytes.md
new file mode 100644
index 0000000000000..9f0602c54f18f
--- /dev/null
+++ b/docs/en/docs/advanced/json-base64-bytes.md
@@ -0,0 +1,63 @@
+# JSON with Bytes as Base64 { #json-with-bytes-as-base64 }
+
+If your app needs to receive and send JSON data, but you need to include binary data in it, you can encode it as base64.
+
+## Base64 vs Files { #base64-vs-files }
+
+Consider first if you can use [Request Files](../tutorial/request-files.md) for uploading binary data and [Custom Response - FileResponse](./custom-response.md#fileresponse--fileresponse-) for sending binary data, instead of encoding it in JSON.
+
+JSON can only contain UTF-8 encoded strings, so it can't contain raw bytes.
+
+Base64 can encode binary data in strings, but to do it, it needs to use more characters than the original binary data, so it would normally be less efficient than regular files.
+
+Use base64 only if you definitely need to include binary data in JSON, and you can't use files for that.
+
+## Pydantic `bytes` { #pydantic-bytes }
+
+You can declare a Pydantic model with `bytes` fields, and then use `val_json_bytes` in the model config to tell it to use base64 to *validate* input JSON data, as part of that validation it will decode the base64 string into bytes.
+
+{* ../../docs_src/json_base64_bytes/tutorial001_py310.py ln[1:9,29:35] hl[9] *}
+
+If you check the `/docs`, they will show that the field `data` expects base64 encoded bytes:
+
+
+
diff --git a/docs/en/docs/advanced/openapi-webhooks.md b/docs/en/docs/advanced/openapi-webhooks.md
index 63cbdc6103c2f..3da42819a6cf8 100644
--- a/docs/en/docs/advanced/openapi-webhooks.md
+++ b/docs/en/docs/advanced/openapi-webhooks.md
@@ -1,4 +1,4 @@
-# OpenAPI Webhooks
+# OpenAPI Webhooks { #openapi-webhooks }
There are cases where you want to tell your API **users** that your app could call *their* app (sending a request) with some data, normally to **notify** of some type of **event**.
@@ -6,7 +6,7 @@ This means that instead of the normal process of your users sending requests to
This is normally called a **webhook**.
-## Webhooks steps
+## Webhooks steps { #webhooks-steps }
The process normally is that **you define** in your code what is the message that you will send, the **body of the request**.
@@ -16,35 +16,39 @@ And **your users** define in some way (for example in a web dashboard somewhere)
All the **logic** about how to register the URLs for webhooks and the code to actually send those requests is up to you. You write it however you want to in **your own code**.
-## Documenting webhooks with **FastAPI** and OpenAPI
+## Documenting webhooks with **FastAPI** and OpenAPI { #documenting-webhooks-with-fastapi-and-openapi }
With **FastAPI**, using OpenAPI, you can define the names of these webhooks, the types of HTTP operations that your app can send (e.g. `POST`, `PUT`, etc.) and the request **bodies** that your app would send.
This can make it a lot easier for your users to **implement their APIs** to receive your **webhook** requests, they might even be able to autogenerate some of their own API code.
-!!! info
- Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` and above.
+/// info
-## An app with webhooks
+Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` and above.
+
+///
+
+## An app with webhooks { #an-app-with-webhooks }
When you create a **FastAPI** application, there is a `webhooks` attribute that you can use to define *webhooks*, the same way you would define *path operations*, for example with `@app.webhooks.post()`.
-```Python hl_lines="9-13 36-53"
-{!../../../docs_src/openapi_webhooks/tutorial001.py!}
-```
+{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}
The webhooks that you define will end up in the **OpenAPI** schema and the automatic **docs UI**.
-!!! info
- The `app.webhooks` object is actually just an `APIRouter`, the same type you would use when structuring your app with multiple files.
+/// info
+
+The `app.webhooks` object is actually just an `APIRouter`, the same type you would use when structuring your app with multiple files.
+
+///
Notice that with webhooks you are actually not declaring a *path* (like `/items/`), the text you pass there is just an **identifier** of the webhook (the name of the event), for example in `@app.webhooks.post("new-subscription")`, the webhook name is `new-subscription`.
This is because it is expected that **your users** would define the actual **URL path** where they want to receive the webhook request in some other way (e.g. a web dashboard).
-### Check the docs
+### Check the docs { #check-the-docs }
-Now you can start your app with Uvicorn and go to http://127.0.0.1:8000/docs.
+Now you can start your app and go to [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).
You will see your docs have the normal *path operations* and now also some **webhooks**:
diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md
index 7ca88d43ed277..800bf305dc32e 100644
--- a/docs/en/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md
@@ -1,45 +1,48 @@
-# Path Operation Advanced Configuration
+# Path Operation Advanced Configuration { #path-operation-advanced-configuration }
-## OpenAPI operationId
+## OpenAPI operationId { #openapi-operationid }
-!!! warning
- If you are not an "expert" in OpenAPI, you probably don't need this.
+/// warning
+
+If you are not an "expert" in OpenAPI, you probably don't need this.
+
+///
You can set the OpenAPI `operationId` to be used in your *path operation* with the parameter `operation_id`.
You would have to make sure that it is unique for each operation.
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
-### Using the *path operation function* name as the operationId
+### Using the *path operation function* name as the operationId { #using-the-path-operation-function-name-as-the-operationid }
If you want to use your APIs' function names as `operationId`s, you can iterate over all of them and override each *path operation's* `operation_id` using their `APIRoute.name`.
You should do it after adding all your *path operations*.
-```Python hl_lines="2 12-21 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *}
+
+/// tip
+
+If you manually call `app.openapi()`, you should update the `operationId`s before that.
-!!! tip
- If you manually call `app.openapi()`, you should update the `operationId`s before that.
+///
-!!! warning
- If you do this, you have to make sure each one of your *path operation functions* has a unique name.
+/// warning
- Even if they are in different modules (Python files).
+If you do this, you have to make sure each one of your *path operation functions* has a unique name.
-## Exclude from OpenAPI
+Even if they are in different modules (Python files).
+
+///
+
+## Exclude from OpenAPI { #exclude-from-openapi }
To exclude a *path operation* from the generated OpenAPI schema (and thus, from the automatic documentation systems), use the parameter `include_in_schema` and set it to `False`:
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}
-## Advanced description from docstring
+## Advanced description from docstring { #advanced-description-from-docstring }
You can limit the lines used from the docstring of a *path operation function* for OpenAPI.
@@ -47,11 +50,9 @@ Adding an `\f` (an escaped "form feed" character) causes **FastAPI** to truncate
It won't show up in the documentation, but other tools (such as Sphinx) will be able to use the rest.
-```Python hl_lines="19-29"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}
-## Additional Responses
+## Additional Responses { #additional-responses }
You probably have seen how to declare the `response_model` and `status_code` for a *path operation*.
@@ -59,14 +60,17 @@ That defines the metadata about the main response of a *path operation*.
You can also declare additional responses with their models, status codes, etc.
-There's a whole chapter here in the documentation about it, you can read it at [Additional Responses in OpenAPI](./additional-responses.md){.internal-link target=_blank}.
+There's a whole chapter here in the documentation about it, you can read it at [Additional Responses in OpenAPI](additional-responses.md).
-## OpenAPI Extra
+## OpenAPI Extra { #openapi-extra }
When you declare a *path operation* in your application, **FastAPI** automatically generates the relevant metadata about that *path operation* to be included in the OpenAPI schema.
-!!! note "Technical details"
- In the OpenAPI specification it is called the Operation Object.
+/// note | Technical details
+
+In the OpenAPI specification it is called the [Operation Object](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object).
+
+///
It has all the information about the *path operation* and is used to generate the automatic documentation.
@@ -74,20 +78,21 @@ It includes the `tags`, `parameters`, `requestBody`, `responses`, etc.
This *path operation*-specific OpenAPI schema is normally generated automatically by **FastAPI**, but you can also extend it.
-!!! tip
- This is a low level extension point.
+/// tip
+
+This is a low level extension point.
+
+If you only need to declare additional responses, a more convenient way to do it is with [Additional Responses in OpenAPI](additional-responses.md).
- If you only need to declare additional responses, a more convenient way to do it is with [Additional Responses in OpenAPI](./additional-responses.md){.internal-link target=_blank}.
+///
You can extend the OpenAPI schema for a *path operation* using the parameter `openapi_extra`.
-### OpenAPI Extensions
+### OpenAPI Extensions { #openapi-extensions }
This `openapi_extra` can be helpful, for example, to declare [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py310.py hl[6] *}
If you open the automatic API docs, your extension will show up at the bottom of the specific *path operation*.
@@ -124,7 +129,7 @@ And if you see the resulting OpenAPI (at `/openapi.json` in your API), you will
}
```
-### Custom OpenAPI *path operation* schema
+### Custom OpenAPI *path operation* schema { #custom-openapi-path-operation-schema }
The dictionary in `openapi_extra` will be deeply merged with the automatically generated OpenAPI schema for the *path operation*.
@@ -134,15 +139,13 @@ For example, you could decide to read and validate the request with your own cod
You could do that with `openapi_extra`:
-```Python hl_lines="20-37 39-40"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py310.py hl[19:36, 39:40] *}
-In this example, we didn't declare any Pydantic model. In fact, the request body is not even parsed as JSON, it is read directly as `bytes`, and the function `magic_data_reader()` would be in charge of parsing it in some way.
+In this example, we didn't declare any Pydantic model. In fact, the request body is not even parsed as JSON, it is read directly as `bytes`, and the function `magic_data_reader()` would be in charge of parsing it in some way.
Nevertheless, we can declare the expected schema for the request body.
-### Custom OpenAPI content type
+### Custom OpenAPI content type { #custom-openapi-content-type }
Using this same trick, you could use a Pydantic model to define the JSON Schema that is then included in the custom OpenAPI schema section for the *path operation*.
@@ -150,20 +153,7 @@ And you could do this even if the data type in the request is not JSON.
For example, in this application we don't use FastAPI's integrated functionality to extract the JSON Schema from Pydantic models nor the automatic validation for JSON. In fact, we are declaring the request content type as YAML, not JSON:
-=== "Pydantic v2"
-
- ```Python hl_lines="17-22 24"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
- ```
-
-=== "Pydantic v1"
-
- ```Python hl_lines="17-22 24"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
- ```
-
-!!! 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()`.
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[15:20, 22] *}
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.
@@ -171,22 +161,12 @@ Then we use the request directly, and extract the body as `bytes`. This means th
And then in our code, we parse that YAML content directly, and then we are again using the same Pydantic model to validate the YAML content:
-=== "Pydantic v2"
-
- ```Python hl_lines="26-33"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
- ```
-
-=== "Pydantic v1"
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *}
- ```Python hl_lines="26-33"
- {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!}
- ```
+/// tip
-!!! info
- In Pydantic version 1 the method to parse and validate an object was `Item.parse_obj()`, in Pydantic version 2, the method is called `Item.model_validate()`.
+Here we reuse the same Pydantic model.
-!!! tip
- Here we re-use the same Pydantic model.
+But the same way, we could have validated it in some other way.
- But the same way, we could have validated it in some other way.
+///
diff --git a/docs/en/docs/advanced/response-change-status-code.md b/docs/en/docs/advanced/response-change-status-code.md
index 979cef3f05367..8efd631981a07 100644
--- a/docs/en/docs/advanced/response-change-status-code.md
+++ b/docs/en/docs/advanced/response-change-status-code.md
@@ -1,10 +1,10 @@
-# Response - Change Status Code
+# Response - Change Status Code { #response-change-status-code }
-You probably read before that you can set a default [Response Status Code](../tutorial/response-status-code.md){.internal-link target=_blank}.
+You probably read before that you can set a default [Response Status Code](../tutorial/response-status-code.md).
But in some cases you need to return a different status code than the default.
-## Use case
+## Use case { #use-case }
For example, imagine that you want to return an HTTP status code of "OK" `200` by default.
@@ -14,15 +14,13 @@ But you still want to be able to filter and convert the data you return with a `
For those cases, you can use a `Response` parameter.
-## Use a `Response` parameter
+## Use a `Response` parameter { #use-a-response-parameter }
You can declare a parameter of type `Response` in your *path operation function* (as you can do for cookies and headers).
And then you can set the `status_code` in that *temporal* response object.
-```Python hl_lines="1 9 12"
-{!../../../docs_src/response_change_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}
And then you can return any object you need, as you normally would (a `dict`, a database model, etc).
@@ -30,4 +28,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.
diff --git a/docs/en/docs/advanced/response-cookies.md b/docs/en/docs/advanced/response-cookies.md
index 9178ef81621db..a7ad90cad87cc 100644
--- a/docs/en/docs/advanced/response-cookies.md
+++ b/docs/en/docs/advanced/response-cookies.md
@@ -1,14 +1,12 @@
-# Response Cookies
+# Response Cookies { #response-cookies }
-## Use a `Response` parameter
+## Use a `Response` parameter { #use-a-response-parameter }
You can declare a parameter of type `Response` in your *path operation function*.
And then you can set cookies in that *temporal* response object.
-```Python hl_lines="1 8-9"
-{!../../../docs_src/response_cookies/tutorial002.py!}
-```
+{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}
And then you can return any object you need, as you normally would (a `dict`, a database model, etc).
@@ -18,32 +16,36 @@ And if you declared a `response_model`, it will still be used to filter and conv
You can also declare the `Response` parameter in dependencies, and set cookies (and headers) in them.
-## Return a `Response` directly
+## Return a `Response` directly { #return-a-response-directly }
You can also create cookies when returning a `Response` directly in your code.
-To do that, you can create a response as described in [Return a Response Directly](response-directly.md){.internal-link target=_blank}.
+To do that, you can create a response as described in [Return a Response Directly](response-directly.md).
Then set Cookies in it, and then return it:
-```Python hl_lines="10-12"
-{!../../../docs_src/response_cookies/tutorial001.py!}
-```
+{* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *}
-!!! tip
- Have in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly.
+/// tip
- 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`.
+Keep in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly.
- And also that you are not sending any data that should have been filtered by a `response_model`.
+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`.
-### More info
+And also that you are not sending any data that should have been filtered by a `response_model`.
-!!! note "Technical Details"
- You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`.
+///
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+### More info { #more-info }
- And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`.
+/// note | Technical Details
-To see all the available parameters and options, check the documentation in Starlette.
+You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`.
+
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+
+And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`.
+
+///
+
+To see all the available parameters and options, check the [documentation in Starlette](https://www.starlette.dev/responses/#set-cookie).
diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md
index 8836140ecf7ee..c9d18649fa35f 100644
--- a/docs/en/docs/advanced/response-directly.md
+++ b/docs/en/docs/advanced/response-directly.md
@@ -1,63 +1,83 @@
-# Return a Response Directly
+# Return a Response Directly { #return-a-response-directly }
When you create a **FastAPI** *path operation* you can normally return any data from it: a `dict`, a `list`, a Pydantic model, a database model, etc.
-By default, **FastAPI** would automatically convert that return value to JSON using the `jsonable_encoder` explained in [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank}.
+If you declare a [Response Model](../tutorial/response-model.md) FastAPI will use it to serialize the data to JSON, using Pydantic.
-Then, behind the scenes, it would put that JSON-compatible data (e.g. a `dict`) inside of a `JSONResponse` that would be used to send the response to the client.
+If you don't declare a response model, FastAPI will use the `jsonable_encoder` explained in [JSON Compatible Encoder](../tutorial/encoder.md) and put it in a `JSONResponse`.
-But you can return a `JSONResponse` directly from your *path operations*.
+You could also create a `JSONResponse` directly and return it.
-It might be useful, for example, to return custom headers or cookies.
+/// tip
-## Return a `Response`
+You will normally have much better performance using a [Response Model](../tutorial/response-model.md) than returning a `JSONResponse` directly, as that way it serializes the data using Pydantic, in Rust.
-In fact, you can return any `Response` or any sub-class of it.
+///
-!!! tip
- `JSONResponse` itself is a sub-class of `Response`.
+## Return a `Response` { #return-a-response }
+
+You can return a `Response` or any sub-class of it.
+
+/// info
+
+`JSONResponse` itself is a sub-class of `Response`.
+
+///
And when you return a `Response`, **FastAPI** will pass it directly.
It won't do any data conversion with Pydantic models, it won't convert the contents to any type, etc.
-This gives you a lot of flexibility. You can return any data type, override any data declaration or validation, etc.
+This gives you a lot of **flexibility**. You can return any data type, override any data declaration or validation, etc.
-## Using the `jsonable_encoder` in a `Response`
+It also gives you a lot of **responsibility**. You have to make sure that the data you return is correct, in the correct format, that it can be serialized, etc.
-Because **FastAPI** doesn't do any change to a `Response` you return, you have to make sure it's contents are ready for it.
+## Using the `jsonable_encoder` in a `Response` { #using-the-jsonable-encoder-in-a-response }
+
+Because **FastAPI** doesn't make any changes to a `Response` you return, you have to make sure its contents are ready for it.
For example, you cannot put a Pydantic model in a `JSONResponse` without first converting it to a `dict` with all the data types (like `datetime`, `UUID`, etc) converted to JSON-compatible types.
For those cases, you can use the `jsonable_encoder` to convert your data before passing it to a response:
-```Python hl_lines="6-7 21-22"
-{!../../../docs_src/response_directly/tutorial001.py!}
-```
+{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}
+
+/// note | Technical Details
+
+You could also use `from starlette.responses import JSONResponse`.
-!!! note "Technical Details"
- You could also use `from starlette.responses import JSONResponse`.
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+///
-## Returning a custom `Response`
+## Returning a custom `Response` { #returning-a-custom-response }
The example above shows all the parts you need, but it's not very useful yet, as you could have just returned the `item` directly, and **FastAPI** would put it in a `JSONResponse` for you, converting it to a `dict`, etc. All that by default.
Now, let's see how you could use that to return a custom response.
-Let's say that you want to return an XML response.
+Let's say that you want to return an [XML](https://en.wikipedia.org/wiki/XML) response.
+
+You could put your XML content in a string, put that in a `Response`, and return it:
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+## How a Response Model Works { #how-a-response-model-works }
+
+When you declare a [Response Model - Return Type](../tutorial/response-model.md) in a path operation, **FastAPI** will use it to serialize the data to JSON, using Pydantic.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+As that will happen on the Rust side, the performance will be much better than if it was done with regular Python and the `JSONResponse` class.
-You could put your XML content in a string, put it in a `Response`, and return it:
+When using a `response_model` or return type, FastAPI won't use the `jsonable_encoder` to convert the data (which would be slower) nor the `JSONResponse` class.
-```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
-```
+Instead it takes the JSON bytes generated with Pydantic using the response model (or return type) and returns a `Response` with the right media type for JSON directly (`application/json`).
-## Notes
+## Notes { #notes }
-When you return a `Response` directly its data is not validated, converted (serialized), nor documented automatically.
+When you return a `Response` directly its data is not validated, converted (serialized), or documented automatically.
-But you can still document it as described in [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}.
+But you can still document it as described in [Additional Responses in OpenAPI](additional-responses.md).
You can see in later sections how to use/declare these custom `Response`s while still having automatic data conversion, documentation, etc.
diff --git a/docs/en/docs/advanced/response-headers.md b/docs/en/docs/advanced/response-headers.md
index 758bd64556c85..d7738635dc373 100644
--- a/docs/en/docs/advanced/response-headers.md
+++ b/docs/en/docs/advanced/response-headers.md
@@ -1,14 +1,12 @@
-# Response Headers
+# Response Headers { #response-headers }
-## Use a `Response` parameter
+## Use a `Response` parameter { #use-a-response-parameter }
You can declare a parameter of type `Response` in your *path operation function* (as you can do for cookies).
And then you can set headers in that *temporal* response object.
-```Python hl_lines="1 7-8"
-{!../../../docs_src/response_headers/tutorial002.py!}
-```
+{* ../../docs_src/response_headers/tutorial002_py310.py hl[1, 7:8] *}
And then you can return any object you need, as you normally would (a `dict`, a database model, etc).
@@ -18,25 +16,26 @@ And if you declared a `response_model`, it will still be used to filter and conv
You can also declare the `Response` parameter in dependencies, and set headers (and cookies) in them.
-## Return a `Response` directly
+## Return a `Response` directly { #return-a-response-directly }
You can also add headers when you return a `Response` directly.
-Create a response as described in [Return a Response Directly](response-directly.md){.internal-link target=_blank} and pass the headers as an additional parameter:
+Create a response as described in [Return a Response Directly](response-directly.md) and pass the headers as an additional parameter:
-```Python hl_lines="10-12"
-{!../../../docs_src/response_headers/tutorial001.py!}
-```
+{* ../../docs_src/response_headers/tutorial001_py310.py hl[10:12] *}
-!!! note "Technical Details"
- You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`.
+/// note | Technical Details
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
+You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`.
- And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`.
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
-## Custom Headers
+And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`.
-Have in mind that custom proprietary headers can be added using the 'X-' prefix.
+///
-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 Starlette's CORS docs.
+## Custom Headers { #custom-headers }
+
+Keep in mind that custom proprietary headers can be added [using the `X-` prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers).
+
+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)), using the parameter `expose_headers` documented in [Starlette's CORS docs](https://www.starlette.dev/middleware/#corsmiddleware).
diff --git a/docs/en/docs/advanced/security/http-basic-auth.md b/docs/en/docs/advanced/security/http-basic-auth.md
index 8177a4b289209..01693e0a016a1 100644
--- a/docs/en/docs/advanced/security/http-basic-auth.md
+++ b/docs/en/docs/advanced/security/http-basic-auth.md
@@ -1,4 +1,4 @@
-# HTTP Basic Auth
+# HTTP Basic Auth { #http-basic-auth }
For the simplest cases, you can use HTTP Basic Auth.
@@ -12,7 +12,7 @@ That tells the browser to show the integrated prompt for a username and password
Then, when you type that username and password, the browser sends them in the header automatically.
-## Simple HTTP Basic Auth
+## Simple HTTP Basic Auth { #simple-http-basic-auth }
* Import `HTTPBasic` and `HTTPBasicCredentials`.
* Create a "`security` scheme" using `HTTPBasic`.
@@ -20,38 +20,19 @@ Then, when you type that username and password, the browser sends them in the he
* It returns an object of type `HTTPBasicCredentials`:
* It contains the `username` and `password` sent.
-=== "Python 3.9+"
-
- ```Python hl_lines="4 8 12"
- {!> ../../../docs_src/security/tutorial006_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="2 7 11"
- {!> ../../../docs_src/security/tutorial006_an.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="2 6 10"
- {!> ../../../docs_src/security/tutorial006.py!}
- ```
+{* ../../docs_src/security/tutorial006_an_py310.py hl[4,8,12] *}
When you try to open the URL for the first time (or click the "Execute" button in the docs) the browser will ask you for your username and password:
-## Check the username
+## Check the username { #check-the-username }
Here's a more complete example.
Use a dependency to check if the username and password are correct.
-For this, use the Python standard module `secrets` to check the username and password.
+For this, use the Python standard module [`secrets`](https://docs.python.org/3/library/secrets.html) to check the username and password.
`secrets.compare_digest()` needs to take `bytes` or a `str` that only contains ASCII characters (the ones in English), this means it wouldn't work with characters like `á`, as in `Sebastián`.
@@ -59,26 +40,7 @@ To handle that, we first convert the `username` and `password` to `bytes` encodi
Then we can use `secrets.compare_digest()` to ensure that `credentials.username` is `"stanleyjobson"`, and that `credentials.password` is `"swordfish"`.
-=== "Python 3.9+"
-
- ```Python hl_lines="1 12-24"
- {!> ../../../docs_src/security/tutorial007_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="1 12-24"
- {!> ../../../docs_src/security/tutorial007_an.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="1 11-21"
- {!> ../../../docs_src/security/tutorial007.py!}
- ```
+{* ../../docs_src/security/tutorial007_an_py310.py hl[1,12:24] *}
This would be similar to:
@@ -90,7 +52,7 @@ if not (credentials.username == "stanleyjobson") or not (credentials.password ==
But by using the `secrets.compare_digest()` it will be secure against a type of attacks called "timing attacks".
-### Timing Attacks
+### Timing Attacks { #timing-attacks }
But what's a "timing attack"?
@@ -105,7 +67,7 @@ if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
...
```
-But right at the moment Python compares the first `j` in `johndoe` to the first `s` in `stanleyjobson`, it will return `False`, because it already knows that those two strings are not the same, thinking that "there's no need to waste more computation comparing the rest of the letters". And your application will say "incorrect user or password".
+But right at the moment Python compares the first `j` in `johndoe` to the first `s` in `stanleyjobson`, it will return `False`, because it already knows that those two strings are not the same, thinking that "there's no need to waste more computation comparing the rest of the letters". And your application will say "Incorrect username or password".
But then the attackers try with username `stanleyjobsox` and password `love123`.
@@ -116,21 +78,21 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
...
```
-Python will have to compare the whole `stanleyjobso` in both `stanleyjobsox` and `stanleyjobson` before realizing that both strings are not the same. So it will take some extra microseconds to reply back "incorrect user or password".
+Python will have to compare the whole `stanleyjobso` in both `stanleyjobsox` and `stanleyjobson` before realizing that both strings are not the same. So it will take some extra microseconds to reply back "Incorrect username or password".
-#### The time to answer helps the attackers
+#### The time to answer helps the attackers { #the-time-to-answer-helps-the-attackers }
-At that point, by noticing that the server took some microseconds longer to send the "incorrect user or password" response, the attackers will know that they got _something_ right, some of the initial letters were right.
+At that point, by noticing that the server took some microseconds longer to send the "Incorrect username or password" response, the attackers will know that they got _something_ right, some of the initial letters were right.
And then they can try again knowing that it's probably something more similar to `stanleyjobsox` than to `johndoe`.
-#### A "professional" attack
+#### A "professional" attack { #a-professional-attack }
-Of course, the attackers would not try all this by hand, they would write a program to do it, possibly with thousands or millions of tests per second. And would get just one extra correct letter at a time.
+Of course, the attackers would not try all this by hand, they would write a program to do it, possibly with thousands or millions of tests per second. And they would get just one extra correct letter at a time.
But doing that, in some minutes or hours the attackers would have guessed the correct username and password, with the "help" of our application, just using the time taken to answer.
-#### Fix it with `secrets.compare_digest()`
+#### Fix it with `secrets.compare_digest()` { #fix-it-with-secrets-compare-digest }
But in our code we are actually using `secrets.compare_digest()`.
@@ -138,27 +100,8 @@ In short, it will take the same time to compare `stanleyjobsox` to `stanleyjobso
That way, using `secrets.compare_digest()` in your application code, it will be safe against this whole range of security attacks.
-### Return the error
+### Return the error { #return-the-error }
After detecting that the credentials are incorrect, return an `HTTPException` with a status code 401 (the same returned when no credentials are provided) and add the header `WWW-Authenticate` to make the browser show the login prompt again:
-=== "Python 3.9+"
-
- ```Python hl_lines="26-30"
- {!> ../../../docs_src/security/tutorial007_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="26-30"
- {!> ../../../docs_src/security/tutorial007_an.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="23-27"
- {!> ../../../docs_src/security/tutorial007.py!}
- ```
+{* ../../docs_src/security/tutorial007_an_py310.py hl[26:30] *}
diff --git a/docs/en/docs/advanced/security/index.md b/docs/en/docs/advanced/security/index.md
index c18baf64b0d27..4f6959a9a4c70 100644
--- a/docs/en/docs/advanced/security/index.md
+++ b/docs/en/docs/advanced/security/index.md
@@ -1,16 +1,19 @@
-# Advanced Security
+# Advanced Security { #advanced-security }
-## Additional Features
+## Additional Features { #additional-features }
-There are some extra features to handle security apart from the ones covered in the [Tutorial - User Guide: Security](../../tutorial/security/){.internal-link target=_blank}.
+There are some extra features to handle security apart from the ones covered in the [Tutorial - User Guide: Security](../../tutorial/security/index.md).
-!!! tip
- The next sections are **not necessarily "advanced"**.
+/// tip
- And it's possible that for your use case, the solution is in one of them.
+The next sections are **not necessarily "advanced"**.
-## Read the Tutorial first
+And it's possible that for your use case, the solution is in one of them.
-The next sections assume you already read the main [Tutorial - User Guide: Security](../../tutorial/security/){.internal-link target=_blank}.
+///
+
+## Read the Tutorial first { #read-the-tutorial-first }
+
+The next sections assume you already read the main [Tutorial - User Guide: Security](../../tutorial/security/index.md).
They are all based on the same concepts, but allow some extra functionalities.
diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md
index 41cd61683dbb3..459646bbd962c 100644
--- a/docs/en/docs/advanced/security/oauth2-scopes.md
+++ b/docs/en/docs/advanced/security/oauth2-scopes.md
@@ -1,29 +1,32 @@
-# OAuth2 scopes
+# OAuth2 scopes { #oauth2-scopes }
You can use OAuth2 scopes directly with **FastAPI**, they are integrated to work seamlessly.
This would allow you to have a more fine-grained permission system, following the OAuth2 standard, integrated into your OpenAPI application (and the API docs).
-OAuth2 with scopes is the mechanism used by many big authentication providers, like Facebook, Google, GitHub, Microsoft, Twitter, etc. They use it to provide specific permissions to users and applications.
+OAuth2 with scopes is the mechanism used by many big authentication providers, like Facebook, Google, GitHub, Microsoft, X (Twitter), etc. They use it to provide specific permissions to users and applications.
-Every time you "log in with" Facebook, Google, GitHub, Microsoft, Twitter, that application is using OAuth2 with scopes.
+Every time you "log in with" Facebook, Google, GitHub, Microsoft, X (Twitter), that application is using OAuth2 with scopes.
In this section you will see how to manage authentication and authorization with the same OAuth2 with scopes in your **FastAPI** application.
-!!! warning
- This is a more or less advanced section. If you are just starting, you can skip it.
+/// warning
- You don't necessarily need OAuth2 scopes, and you can handle authentication and authorization however you want.
+This is a more or less advanced section. If you are just starting, you can skip it.
- But OAuth2 with scopes can be nicely integrated into your API (with OpenAPI) and your API docs.
+You don't necessarily need OAuth2 scopes, and you can handle authentication and authorization however you want.
- Nevertheless, you still enforce those scopes, or any other security/authorization requirement, however you need, in your code.
+But OAuth2 with scopes can be nicely integrated into your API (with OpenAPI) and your API docs.
- In many cases, OAuth2 with scopes can be an overkill.
+Nevertheless, you still enforce those scopes, or any other security/authorization requirement, however you need, in your code.
- But if you know you need it, or you are curious, keep reading.
+In many cases, OAuth2 with scopes can be an overkill.
-## OAuth2 scopes and OpenAPI
+But if you know you need it, or you are curious, keep reading.
+
+///
+
+## OAuth2 scopes and OpenAPI { #oauth2-scopes-and-openapi }
The OAuth2 specification defines "scopes" as a list of strings separated by spaces.
@@ -43,117 +46,33 @@ They are normally used to declare specific security permissions, for example:
* `instagram_basic` is used by Facebook / Instagram.
* `https://www.googleapis.com/auth/drive` is used by Google.
-!!! info
- In OAuth2 a "scope" is just a string that declares a specific permission required.
-
- It doesn't matter if it has other characters like `:` or if it is a URL.
-
- Those details are implementation specific.
-
- For OAuth2 they are just strings.
-
-## Global view
-
-First, let's quickly see the parts that change from the examples in the main **Tutorial - User Guide** for [OAuth2 with Password (and hashing), Bearer with JWT tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Now using OAuth2 scopes:
-
-=== "Python 3.10+"
-
- ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
+/// info
- !!! tip
- Prefer to use the `Annotated` version if possible.
+In OAuth2 a "scope" is just a string that declares a specific permission required.
- ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 152"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+It doesn't matter if it has other characters like `:` or if it is a URL.
-=== "Python 3.9+ non-Annotated"
+Those details are implementation specific.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+For OAuth2 they are just strings.
- ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
+///
-=== "Python 3.6+ non-Annotated"
+## Global view { #global-view }
- !!! tip
- Prefer to use the `Annotated` version if possible.
+First, let's quickly see the parts that change from the examples in the main **Tutorial - User Guide** for [OAuth2 with Password (and hashing), Bearer with JWT tokens](../../tutorial/security/oauth2-jwt.md). Now using OAuth2 scopes:
- ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}
Now let's review those changes step by step.
-## OAuth2 Security scheme
+## OAuth2 Security scheme { #oauth2-security-scheme }
The first change is that now we are declaring the OAuth2 security scheme with two available scopes, `me` and `items`.
The `scopes` parameter receives a `dict` with each scope as a key and the description as the value:
-=== "Python 3.10+"
-
- ```Python hl_lines="62-65"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="62-65"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="63-66"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="61-64"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
-
-
-=== "Python 3.9+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="62-65"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="62-65"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
+{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *}
Because we are now declaring those scopes, they will show up in the API docs when you log-in/authorize.
@@ -163,7 +82,7 @@ This is the same mechanism used when you give permissions while logging in with
-## JWT token with scopes
+## JWT token with scopes { #jwt-token-with-scopes }
Now, modify the token *path operation* to return the scopes requested.
@@ -171,57 +90,17 @@ We are still using the same `OAuth2PasswordRequestForm`. It includes a property
And we return the scopes as part of the JWT token.
-!!! danger
- For simplicity, here we are just adding the scopes received directly to the token.
-
- But in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined.
-
-=== "Python 3.10+"
-
- ```Python hl_lines="155"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="155"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.6+"
+/// danger
- ```Python hl_lines="156"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+For simplicity, here we are just adding the scopes received directly to the token.
-=== "Python 3.10+ non-Annotated"
+But in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
- ```Python hl_lines="152"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}
-=== "Python 3.9+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="153"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="153"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
-
-## Declare scopes in *path operations* and dependencies
+## Declare scopes in *path operations* and dependencies { #declare-scopes-in-path-operations-and-dependencies }
Now we declare that the *path operation* for `/users/me/items/` requires the scope `items`.
@@ -237,70 +116,33 @@ And the dependency function `get_current_active_user` can also declare sub-depen
In this case, it requires the scope `me` (it could require more than one scope).
-!!! note
- You don't necessarily need to add different scopes in different places.
-
- We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels.
+/// note
-=== "Python 3.10+"
+You don't necessarily need to add different scopes in different places.
- ```Python hl_lines="4 139 170"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
+We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels.
-=== "Python 3.9+"
+///
- ```Python hl_lines="4 139 170"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}
-=== "Python 3.6+"
+/// info | Technical Details
- ```Python hl_lines="4 140 171"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+`Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later.
-=== "Python 3.10+ non-Annotated"
+But by using `Security` instead of `Depends`, **FastAPI** will know that it can declare security scopes, use them internally, and document the API with OpenAPI.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+But when you import `Query`, `Path`, `Depends`, `Security` and others from `fastapi`, those are actually functions that return special classes.
- ```Python hl_lines="3 138 165"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
+///
-=== "Python 3.9+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="4 139 166"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="4 139 166"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
-
-!!! info "Technical Details"
- `Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later.
-
- But by using `Security` instead of `Depends`, **FastAPI** will know that it can declare security scopes, use them internally, and document the API with OpenAPI.
-
- But when you import `Query`, `Path`, `Depends`, `Security` and others from `fastapi`, those are actually functions that return special classes.
-
-## Use `SecurityScopes`
+## Use `SecurityScopes` { #use-securityscopes }
Now update the dependency `get_current_user`.
This is the one used by the dependencies above.
-Here's were we are using the same OAuth2 scheme we created before, declaring it as a dependency: `oauth2_scheme`.
+Here's where we are using the same OAuth2 scheme we created before, declaring it as a dependency: `oauth2_scheme`.
Because this dependency function doesn't have any scope requirements itself, we can use `Depends` with `oauth2_scheme`, we don't have to use `Security` when we don't need to specify security scopes.
@@ -308,52 +150,9 @@ We also declare a special parameter of type `SecurityScopes`, imported from `fas
This `SecurityScopes` class is similar to `Request` (`Request` was used to get the request object directly).
-=== "Python 3.10+"
-
- ```Python hl_lines="8 105"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="8 105"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="8 106"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="7 104"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
-
-=== "Python 3.9+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="8 105"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="8 105"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
-
-## Use the `scopes`
+## Use the `scopes` { #use-the-scopes }
The parameter `security_scopes` will be of type `SecurityScopes`.
@@ -361,56 +160,13 @@ It will have a property `scopes` with a list containing all the scopes required
The `security_scopes` object (of class `SecurityScopes`) also provides a `scope_str` attribute with a single string, containing those scopes separated by spaces (we are going to use it).
-We create an `HTTPException` that we can re-use (`raise`) later at several points.
+We create an `HTTPException` that we can reuse (`raise`) later at several points.
In this exception, we include the scopes required (if any) as a string separated by spaces (using `scope_str`). We put that string containing the scopes in the `WWW-Authenticate` header (this is part of the spec).
-=== "Python 3.10+"
-
- ```Python hl_lines="105 107-115"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="105 107-115"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="106 108-116"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="104 106-114"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
-
-=== "Python 3.9+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="105 107-115"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="105 107-115"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
-
-## Verify the `username` and data shape
+## Verify the `username` and data shape { #verify-the-username-and-data-shape }
We verify that we get a `username`, and extract the scopes.
@@ -424,103 +180,17 @@ Instead of, for example, a `dict`, or something else, as it could break the appl
We also verify that we have a user with that username, and if not, we raise that same exception we created before.
-=== "Python 3.10+"
-
- ```Python hl_lines="46 116-127"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="46 116-127"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="47 117-128"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="45 115-126"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
-
-=== "Python 3.9+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="46 116-127"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="46 116-127"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
-
-## Verify the `scopes`
+## Verify the `scopes` { #verify-the-scopes }
We now verify that all the scopes required, by this dependency and all the dependants (including *path operations*), are included in the scopes provided in the token received, otherwise raise an `HTTPException`.
For this, we use `security_scopes.scopes`, that contains a `list` with all these scopes as `str`.
-=== "Python 3.10+"
-
- ```Python hl_lines="128-134"
- {!> ../../../docs_src/security/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="128-134"
- {!> ../../../docs_src/security/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="129-135"
- {!> ../../../docs_src/security/tutorial005_an.py!}
- ```
+{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="127-133"
- {!> ../../../docs_src/security/tutorial005_py310.py!}
- ```
-
-=== "Python 3.9+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="128-134"
- {!> ../../../docs_src/security/tutorial005_py39.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="128-134"
- {!> ../../../docs_src/security/tutorial005.py!}
- ```
-
-## Dependency tree and scopes
+## Dependency tree and scopes { #dependency-tree-and-scopes }
Let's review again this dependency tree and the scopes.
@@ -543,14 +213,17 @@ Here's how the hierarchy of dependencies and scopes looks like:
* This `security_scopes` parameter has a property `scopes` with a `list` containing all these scopes declared above, so:
* `security_scopes.scopes` will contain `["me", "items"]` for the *path operation* `read_own_items`.
* `security_scopes.scopes` will contain `["me"]` for the *path operation* `read_users_me`, because it is declared in the dependency `get_current_active_user`.
- * `security_scopes.scopes` will contain `[]` (nothing) for the *path operation* `read_system_status`, because it didn't declare any `Security` with `scopes`, and its dependency, `get_current_user`, doesn't declare any `scope` either.
+ * `security_scopes.scopes` will contain `[]` (nothing) for the *path operation* `read_system_status`, because it didn't declare any `Security` with `scopes`, and its dependency, `get_current_user`, doesn't declare any `scopes` either.
+
+/// tip
-!!! tip
- The important and "magic" thing here is that `get_current_user` will have a different list of `scopes` to check for each *path operation*.
+The important and "magic" thing here is that `get_current_user` will have a different list of `scopes` to check for each *path operation*.
- All depending on the `scopes` declared in each *path operation* and each dependency in the dependency tree for that specific *path operation*.
+All depending on the `scopes` declared in each *path operation* and each dependency in the dependency tree for that specific *path operation*.
-## More details about `SecurityScopes`
+///
+
+## More details about `SecurityScopes` { #more-details-about-securityscopes }
You can use `SecurityScopes` at any point, and in multiple places, it doesn't have to be at the "root" dependency.
@@ -560,7 +233,7 @@ Because the `SecurityScopes` will have all the scopes declared by dependants, yo
They will be checked independently for each *path operation*.
-## Check it
+## Check it { #check-it }
If you open the API docs, you can authenticate and specify which scopes you want to authorize.
@@ -572,7 +245,7 @@ And if you select the scope `me` but not the scope `items`, you will be able to
That's what would happen to a third party application that tried to access one of these *path operations* with a token provided by a user, depending on how many permissions the user gave the application.
-## About third party integrations
+## About third party integrations { #about-third-party-integrations }
In this example we are using the OAuth2 "password" flow.
@@ -584,15 +257,18 @@ But if you are building an OAuth2 application that others would connect to (i.e.
The most common is the implicit flow.
-The most secure is the code flow, but is more complex to implement as it requires more steps. As it is more complex, many providers end up suggesting the implicit flow.
+The most secure is the code flow, but it's more complex to implement as it requires more steps. As it is more complex, many providers end up suggesting the implicit flow.
+
+/// note
+
+It's common that each authentication provider names their flows in a different way, to make it part of their brand.
-!!! note
- It's common that each authentication provider names their flows in a different way, to make it part of their brand.
+But in the end, they are implementing the same OAuth2 standard.
- But in the end, they are implementing the same OAuth2 standard.
+///
**FastAPI** includes utilities for all these OAuth2 authentication flows in `fastapi.security.oauth2`.
-## `Security` in decorator `dependencies`
+## `Security` in decorator `dependencies` { #security-in-decorator-dependencies }
-The same way you can define a `list` of `Depends` in the decorator's `dependencies` parameter (as explained in [Dependencies in path operation decorators](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), you could also use `Security` with `scopes` there.
+The same way you can define a `list` of `Depends` in the decorator's `dependencies` parameter (as explained in [Dependencies in path operation decorators](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md)), you could also use `Security` with `scopes` there.
diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md
index 8f6c7da93ae47..f0f3bb41d0af5 100644
--- a/docs/en/docs/advanced/settings.md
+++ b/docs/en/docs/advanced/settings.md
@@ -1,4 +1,4 @@
-# Settings and Environment Variables
+# Settings and Environment Variables { #settings-and-environment-variables }
In many cases your application could need some external settings or configurations, for example secret keys, database credentials, credentials for email services, etc.
@@ -6,130 +6,25 @@ Most of these settings are variable (can change), like database URLs. And many c
For this reason it's common to provide them in environment variables that are read by the application.
-## Environment Variables
+/// tip
-!!! tip
- If you already know what "environment variables" are and how to use them, feel free to skip to the next section below.
+To understand environment variables you can read [Environment Variables](../environment-variables.md).
-An environment variable (also known as "env var") is a variable that lives outside of the Python code, in the operating system, and could be read by your Python code (or by other programs as well).
+///
-You can create and use environment variables in the shell, without needing Python:
-
-=== "Linux, macOS, Windows Bash"
-
-
-And then, open the docs for the sub-application, at http://127.0.0.1:8000/subapi/docs.
+And then, open the docs for the sub-application, at [http://127.0.0.1:8000/subapi/docs](http://127.0.0.1:8000/subapi/docs).
You will see the automatic API docs for the sub-application, including only its own _path operations_, all under the correct sub-path prefix `/subapi`:
@@ -62,7 +56,7 @@ You will see the automatic API docs for the sub-application, including only its
If you try interacting with any of the two user interfaces, they will work correctly, because the browser will be able to talk to each specific app or sub-app.
-### Technical Details: `root_path`
+### Technical Details: `root_path` { #technical-details-root-path }
When you mount a sub-application as described above, FastAPI will take care of communicating the mount path for the sub-application using a mechanism from the ASGI specification called a `root_path`.
@@ -70,4 +64,4 @@ That way, the sub-application will know to use that path prefix for the docs UI.
And the sub-application could also have its own mounted sub-applications and everything would work correctly, because FastAPI handles all these `root_path`s automatically.
-You will learn more about the `root_path` and how to use it explicitly in the section about [Behind a Proxy](./behind-a-proxy.md){.internal-link target=_blank}.
+You will learn more about the `root_path` and how to use it explicitly in the section about [Behind a Proxy](behind-a-proxy.md).
diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md
index 38618aeeb09cd..6570865e27ed0 100644
--- a/docs/en/docs/advanced/templates.md
+++ b/docs/en/docs/advanced/templates.md
@@ -1,4 +1,4 @@
-# Templates
+# Templates { #templates }
You can use any template engine you want with **FastAPI**.
@@ -6,9 +6,9 @@ A common choice is Jinja2, the same one used by Flask and other tools.
There are utilities to configure it easily that you can use directly in your **FastAPI** application (provided by Starlette).
-## Install dependencies
+## Install dependencies { #install-dependencies }
-Install `jinja2`:
+Make sure you create a [virtual environment](../virtual-environments.md), activate it, and install `jinja2`:
-## Handling disconnections and multiple clients
+## Handling disconnections and multiple clients { #handling-disconnections-and-multiple-clients }
When a WebSocket connection is closed, the `await websocket.receive_text()` will raise a `WebSocketDisconnect` exception, which you can then catch and handle like in this example.
-=== "Python 3.9+"
-
- ```Python hl_lines="79-81"
- {!> ../../../docs_src/websockets/tutorial003_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="81-83"
- {!> ../../../docs_src/websockets/tutorial003.py!}
- ```
+{* ../../docs_src/websockets_/tutorial003_py310.py hl[79:81] *}
To try it out:
@@ -209,16 +168,19 @@ That will raise the `WebSocketDisconnect` exception, and all the other clients w
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.
+/// tip
+
+The app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections.
+
+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.
- 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.
+If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check [encode/broadcaster](https://github.com/encode/broadcaster).
- If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check encode/broadcaster.
+///
-## More info
+## More info { #more-info }
To learn more about the options, check Starlette's documentation for:
-* The `WebSocket` class.
-* Class-based WebSocket handling.
+* [The `WebSocket` class](https://www.starlette.dev/websockets/).
+* [Class-based WebSocket handling](https://www.starlette.dev/endpoints/#websocketendpoint).
diff --git a/docs/en/docs/advanced/wsgi.md b/docs/en/docs/advanced/wsgi.md
index cfe3c78c11ca4..44807b7238ae7 100644
--- a/docs/en/docs/advanced/wsgi.md
+++ b/docs/en/docs/advanced/wsgi.md
@@ -1,34 +1,48 @@
-# Including WSGI - Flask, Django, others
+# Including WSGI - Flask, Django, others { #including-wsgi-flask-django-others }
-You can mount WSGI applications as you saw with [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](./behind-a-proxy.md){.internal-link target=_blank}.
+You can mount WSGI applications as you saw with [Sub Applications - Mounts](sub-applications.md), [Behind a Proxy](behind-a-proxy.md).
For that, you can use the `WSGIMiddleware` and use it to wrap your WSGI application, for example, Flask, Django, etc.
-## Using `WSGIMiddleware`
+## Using `WSGIMiddleware` { #using-wsgimiddleware }
-You need to import `WSGIMiddleware`.
+/// info
+
+This requires installing `a2wsgi` for example with `pip install a2wsgi`.
+
+///
+
+You need to import `WSGIMiddleware` from `a2wsgi`.
Then wrap the WSGI (e.g. Flask) app with the middleware.
And then mount that under a path.
-```Python hl_lines="2-3 23"
-{!../../../docs_src/wsgi/tutorial001.py!}
-```
+{* ../../docs_src/wsgi/tutorial001_py310.py hl[1,3,23] *}
+
+/// note
+
+Previously, it was recommended to use `WSGIMiddleware` from `fastapi.middleware.wsgi`, but it is now deprecated.
+
+It’s advised to use the `a2wsgi` package instead. The usage remains the same.
+
+Just ensure that you have the `a2wsgi` package installed and import `WSGIMiddleware` correctly from `a2wsgi`.
+
+///
-## Check it
+## Check it { #check-it }
Now, every request under the path `/v1/` will be handled by the Flask application.
And the rest will be handled by **FastAPI**.
-If you run it with Uvicorn and go to http://localhost:8000/v1/ you will see the response from Flask:
+If you run it and go to [http://localhost:8000/v1/](http://localhost:8000/v1/) you will see the response from Flask:
```txt
Hello, World from Flask!
```
-And if you go to http://localhost:8000/v2 you will see the response from FastAPI:
+And if you go to [http://localhost:8000/v2](http://localhost:8000/v2) you will see the response from FastAPI:
```JSON
{
diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md
index a777ddb98e0cd..bfaa7aa132dde 100644
--- a/docs/en/docs/alternatives.md
+++ b/docs/en/docs/alternatives.md
@@ -1,8 +1,8 @@
-# Alternatives, Inspiration and Comparisons
+# Alternatives, Inspiration and Comparisons { #alternatives-inspiration-and-comparisons }
-What inspired **FastAPI**, how it compares to other alternatives and what it learned from them.
+What inspired **FastAPI**, how it compares to alternatives and what it learned from them.
-## Intro
+## Intro { #intro }
**FastAPI** wouldn't exist if not for the previous work of others.
@@ -12,9 +12,9 @@ I have been avoiding the creation of a new framework for several years. First I
But at some point, there was no other option than creating something that provided all these features, taking the best ideas from previous tools, and combining them in the best way possible, using language features that weren't even available before (Python 3.6+ type hints).
-## Previous tools
+## Previous tools { #previous-tools }
-### Django
+### [Django](https://www.djangoproject.com/) { #django }
It's the most popular Python framework and is widely trusted. It is used to build systems like Instagram.
@@ -22,7 +22,7 @@ It's relatively tightly coupled with relational databases (like MySQL or Postgre
It was created to generate the HTML in the backend, not to create APIs used by a modern frontend (like React, Vue.js and Angular) or by other systems (like IoT devices) communicating with it.
-### Django REST Framework
+### [Django REST Framework](https://www.django-rest-framework.org/) { #django-rest-framework }
Django REST framework was created to be a flexible toolkit for building Web APIs using Django underneath, to improve its API capabilities.
@@ -30,14 +30,19 @@ It is used by many companies including Mozilla, Red Hat and Eventbrite.
It was one of the first examples of **automatic API documentation**, and this was specifically one of the first ideas that inspired "the search for" **FastAPI**.
-!!! note
- Django REST Framework was created by Tom Christie. The same creator of Starlette and Uvicorn, on which **FastAPI** is based.
+/// note
+Django REST Framework was created by Tom Christie. The same creator of Starlette and Uvicorn, on which **FastAPI** is based.
-!!! check "Inspired **FastAPI** to"
- Have an automatic API documentation web user interface.
+///
-### Flask
+/// check | Inspired **FastAPI** to
+
+Have an automatic API documentation web user interface.
+
+///
+
+### [Flask](https://flask.palletsprojects.com) { #flask }
Flask is a "microframework", it doesn't include database integrations nor many of the things that come by default in Django.
@@ -51,13 +56,15 @@ This decoupling of parts, and being a "microframework" that could be extended to
Given the simplicity of Flask, it seemed like a good match for building APIs. The next thing to find was a "Django REST Framework" for Flask.
-!!! check "Inspired **FastAPI** to"
- Be a micro-framework. Making it easy to mix and match the tools and parts needed.
+/// check | Inspired **FastAPI** to
- Have a simple and easy to use routing system.
+Be a micro-framework. Making it easy to mix and match the tools and parts needed.
+Have a simple and easy to use routing system.
-### Requests
+///
+
+### [Requests](https://requests.readthedocs.io) { #requests }
**FastAPI** is not actually an alternative to **Requests**. Their scope is very different.
@@ -91,13 +98,15 @@ def read_url():
See the similarities in `requests.get(...)` and `@app.get(...)`.
-!!! check "Inspired **FastAPI** to"
- * Have a simple and intuitive API.
- * Use HTTP method names (operations) directly, in a straightforward and intuitive way.
- * Have sensible defaults, but powerful customizations.
+/// check | Inspired **FastAPI** to
+
+* Have a simple and intuitive API.
+* Use HTTP method names (operations) directly, in a straightforward and intuitive way.
+* Have sensible defaults, but powerful customizations.
+///
-### Swagger / OpenAPI
+### [Swagger](https://swagger.io/) / [OpenAPI](https://github.com/OAI/OpenAPI-Specification/) { #swagger-openapi }
The main feature I wanted from Django REST Framework was the automatic API documentation.
@@ -109,25 +118,26 @@ At some point, Swagger was given to the Linux Foundation, to be renamed OpenAPI.
That's why when talking about version 2.0 it's common to say "Swagger", and for version 3+ "OpenAPI".
-!!! check "Inspired **FastAPI** to"
- Adopt and use an open standard for API specifications, instead of a custom schema.
+/// check | Inspired **FastAPI** to
+
+Adopt and use an open standard for API specifications, instead of a custom schema.
- And integrate standards-based user interface tools:
+And integrate standards-based user interface tools:
- * Swagger UI
- * ReDoc
+* [Swagger UI](https://github.com/swagger-api/swagger-ui)
+* [ReDoc](https://github.com/Rebilly/ReDoc)
- These two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of additional alternative user interfaces for OpenAPI (that you can use with **FastAPI**).
+These two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of alternative user interfaces for OpenAPI (that you can use with **FastAPI**).
- For example, you could try Fern which is also a FastAPI sponsor. 😎🎉
+///
-### Flask REST frameworks
+### Flask REST frameworks { #flask-rest-frameworks }
There are several Flask REST frameworks, but after investing the time and work into investigating them, I found that many are discontinued or abandoned, with several standing issues that made them unfit.
-### Marshmallow
+### [Marshmallow](https://marshmallow.readthedocs.io/en/stable/) { #marshmallow }
-One of the main features needed by API systems is data "serialization" which is taking data from the code (Python) and converting it into something that can be sent through the network. For example, converting an object containing data from a database into a JSON object. Converting `datetime` objects into strings, etc.
+One of the main features needed by API systems is data "serialization" which is taking data from the code (Python) and converting it into something that can be sent through the network. For example, converting an object containing data from a database into a JSON object. Converting `datetime` objects into strings, etc.
Another big feature needed by APIs is data validation, making sure that the data is valid, given certain parameters. For example, that some field is an `int`, and not some random string. This is especially useful for incoming data.
@@ -135,14 +145,17 @@ Without a data validation system, you would have to do all the checks by hand, i
These features are what Marshmallow was built to provide. It is a great library, and I have used it a lot before.
-But it was created before there existed Python type hints. So, to define every schema you need to use specific utils and classes provided by Marshmallow.
+But it was created before there existed Python type hints. So, to define every schema you need to use specific utils and classes provided by Marshmallow.
-!!! check "Inspired **FastAPI** to"
- Use code to define "schemas" that provide data types and validation, automatically.
+/// check | Inspired **FastAPI** to
-### Webargs
+Use code to define "schemas" that provide data types and validation, automatically.
-Another big feature required by APIs is parsing data from incoming requests.
+///
+
+### [Webargs](https://webargs.readthedocs.io/en/latest/) { #webargs }
+
+Another big feature required by APIs is parsing data from incoming requests.
Webargs is a tool that was made to provide that on top of several frameworks, including Flask.
@@ -150,13 +163,19 @@ It uses Marshmallow underneath to do the data validation. And it was created by
It's a great tool and I have used it a lot too, before having **FastAPI**.
-!!! info
- Webargs was created by the same Marshmallow developers.
+/// info
+
+Webargs was created by the same Marshmallow developers.
+
+///
+
+/// check | Inspired **FastAPI** to
+
+Have automatic validation of incoming request data.
-!!! check "Inspired **FastAPI** to"
- Have automatic validation of incoming request data.
+///
-### APISpec
+### [APISpec](https://apispec.readthedocs.io/en/stable/) { #apispec }
Marshmallow and Webargs provide validation, parsing and serialization as plug-ins.
@@ -174,46 +193,57 @@ But then, we have again the problem of having a micro-syntax, inside of a Python
The editor can't help much with that. And if we modify parameters or Marshmallow schemas and forget to also modify that YAML docstring, the generated schema would be obsolete.
-!!! info
- APISpec was created by the same Marshmallow developers.
+/// info
+APISpec was created by the same Marshmallow developers.
-!!! check "Inspired **FastAPI** to"
- Support the open standard for APIs, OpenAPI.
+///
-### Flask-apispec
+/// check | Inspired **FastAPI** to
+
+Support the open standard for APIs, OpenAPI.
+
+///
+
+### [Flask-apispec](https://flask-apispec.readthedocs.io/en/latest/) { #flask-apispec }
It's a Flask plug-in, that ties together Webargs, Marshmallow and APISpec.
It uses the information from Webargs and Marshmallow to automatically generate OpenAPI schemas, using APISpec.
-It's a great tool, very under-rated. It should be way more popular than many Flask plug-ins out there. It might be due to its documentation being too concise and abstract.
+It's a great tool, very underrated. It should be way more popular than many Flask plug-ins out there. It might be due to its documentation being too concise and abstract.
This solved having to write YAML (another syntax) inside of Python docstrings.
This combination of Flask, Flask-apispec with Marshmallow and Webargs was my favorite backend stack until building **FastAPI**.
-Using it led to the creation of several Flask full-stack generators. These are the main stack I (and several external teams) have been using up to now:
+Using it led to the creation of several Flask full-stack generators. These are the main stacks I (and several external teams) have been using up to now:
+
+* [https://github.com/tiangolo/full-stack](https://github.com/tiangolo/full-stack)
+* [https://github.com/tiangolo/full-stack-flask-couchbase](https://github.com/tiangolo/full-stack-flask-couchbase)
+* [https://github.com/tiangolo/full-stack-flask-couchdb](https://github.com/tiangolo/full-stack-flask-couchdb)
+
+And these same full-stack generators were the base of the [**FastAPI** Project Generators](project-generation.md).
+
+/// info
-* https://github.com/tiangolo/full-stack
-* https://github.com/tiangolo/full-stack-flask-couchbase
-* https://github.com/tiangolo/full-stack-flask-couchdb
+Flask-apispec was created by the same Marshmallow developers.
-And these same full-stack generators were the base of the [**FastAPI** Project Generators](project-generation.md){.internal-link target=_blank}.
+///
-!!! info
- Flask-apispec was created by the same Marshmallow developers.
+/// check | Inspired **FastAPI** to
-!!! check "Inspired **FastAPI** to"
- Generate the OpenAPI schema automatically, from the same code that defines serialization and validation.
+Generate the OpenAPI schema automatically, from the same code that defines serialization and validation.
-### NestJS (and Angular)
+///
+
+### [NestJS](https://nestjs.com/) (and [Angular](https://angular.io/)) { #nestjs-and-angular }
This isn't even Python, NestJS is a JavaScript (TypeScript) NodeJS framework inspired by Angular.
It achieves something somewhat similar to what can be done with Flask-apispec.
-It has an integrated dependency injection system, inspired by Angular two. It requires pre-registering the "injectables" (like all the other dependency injection systems I know), so, it adds to the verbosity and code repetition.
+It has an integrated dependency injection system, inspired by Angular 2. It requires pre-registering the "injectables" (like all the other dependency injection systems I know), so, it adds to the verbosity and code repetition.
As the parameters are described with TypeScript types (similar to Python type hints), editor support is quite good.
@@ -221,26 +251,35 @@ But as TypeScript data is not preserved after compilation to JavaScript, it cann
It can't handle nested models very well. So, if the JSON body in the request is a JSON object that has inner fields that in turn are nested JSON objects, it cannot be properly documented and validated.
-!!! check "Inspired **FastAPI** to"
- Use Python types to have great editor support.
+/// check | Inspired **FastAPI** to
+
+Use Python types to have great editor support.
+
+Have a powerful dependency injection system. Find a way to minimize code repetition.
- Have a powerful dependency injection system. Find a way to minimize code repetition.
+///
-### Sanic
+### [Sanic](https://sanic.readthedocs.io/en/latest/) { #sanic }
It was one of the first extremely fast Python frameworks based on `asyncio`. It was made to be very similar to Flask.
-!!! note "Technical Details"
- It used `uvloop` instead of the default Python `asyncio` loop. That's what made it so fast.
+/// note | Technical Details
+
+It used [`uvloop`](https://github.com/MagicStack/uvloop) instead of the default Python `asyncio` loop. That's what made it so fast.
+
+It clearly inspired Uvicorn and Starlette, that are currently faster than Sanic in open benchmarks.
- It clearly inspired Uvicorn and Starlette, that are currently faster than Sanic in open benchmarks.
+///
-!!! check "Inspired **FastAPI** to"
- Find a way to have a crazy performance.
+/// check | Inspired **FastAPI** to
- That's why **FastAPI** is based on Starlette, as it is the fastest framework available (tested by third-party benchmarks).
+Find a way to have a crazy performance.
-### Falcon
+That's why **FastAPI** is based on Starlette, as it is the fastest framework available (tested by third-party benchmarks).
+
+///
+
+### [Falcon](https://falconframework.org/) { #falcon }
Falcon is another high performance Python framework, it is designed to be minimal, and work as the foundation of other frameworks like Hug.
@@ -248,14 +287,17 @@ It is designed to have functions that receive two parameters, one "request" and
So, data validation, serialization, and documentation, have to be done in code, not automatically. Or they have to be implemented as a framework on top of Falcon, like Hug. This same distinction happens in other frameworks that are inspired by Falcon's design, of having one request object and one response object as parameters.
-!!! check "Inspired **FastAPI** to"
- Find ways to get great performance.
+/// check | Inspired **FastAPI** to
+
+Find ways to get great performance.
- Along with Hug (as Hug is based on Falcon) inspired **FastAPI** to declare a `response` parameter in functions.
+Along with Hug (as Hug is based on Falcon) inspired **FastAPI** to declare a `response` parameter in functions.
- Although in FastAPI it's optional, and is used mainly to set headers, cookies, and alternative status codes.
+Although in FastAPI it's optional, and is used mainly to set headers, cookies, and alternative status codes.
-### Molten
+///
+
+### [Molten](https://moltenframework.com/) { #molten }
I discovered Molten in the first stages of building **FastAPI**. And it has quite similar ideas:
@@ -265,18 +307,21 @@ I discovered Molten in the first stages of building **FastAPI**. And it has quit
It doesn't use a data validation, serialization and documentation third-party library like Pydantic, it has its own. So, these data type definitions would not be reusable as easily.
-It requires a little bit more verbose configurations. And as it is based on WSGI (instead of ASGI), it is not designed to take advantage of the high-performance provided by tools like Uvicorn, Starlette and Sanic.
+It requires a little bit more verbose configurations. And as it is based on WSGI (instead of ASGI), it is not designed to take advantage of the high performance provided by tools like Uvicorn, Starlette and Sanic.
The dependency injection system requires pre-registration of the dependencies and the dependencies are solved based on the declared types. So, it's not possible to declare more than one "component" that provides a certain type.
Routes are declared in a single place, using functions declared in other places (instead of using decorators that can be placed right on top of the function that handles the endpoint). This is closer to how Django does it than to how Flask (and Starlette) does it. It separates in the code things that are relatively tightly coupled.
-!!! check "Inspired **FastAPI** to"
- Define extra validations for data types using the "default" value of model attributes. This improves editor support, and it was not available in Pydantic before.
+/// check | Inspired **FastAPI** to
+
+Define extra validations for data types using the "default" value of model attributes. This improves editor support, and it was not available in Pydantic before.
+
+This actually inspired updating parts of Pydantic, to support the same validation declaration style (all this functionality is now already available in Pydantic).
- This actually inspired updating parts of Pydantic, to support the same validation declaration style (all this functionality is now already available in Pydantic).
+///
-### Hug
+### [Hug](https://github.com/hugapi/hug) { #hug }
Hug was one of the first frameworks to implement the declaration of API parameter types using Python type hints. This was a great idea that inspired other tools to do the same.
@@ -290,17 +335,23 @@ It has an interesting, uncommon feature: using the same framework, it's possible
As it is based on the previous standard for synchronous Python web frameworks (WSGI), it can't handle Websockets and other things, although it still has high performance too.
-!!! info
- Hug was created by Timothy Crosley, the same creator of `isort`, a great tool to automatically sort imports in Python files.
+/// info
-!!! check "Ideas inspired in **FastAPI**"
- Hug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar.
+Hug was created by Timothy Crosley, the same creator of [`isort`](https://github.com/timothycrosley/isort), a great tool to automatically sort imports in Python files.
- Hug helped inspiring **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically.
+///
- Hug inspired **FastAPI** to declare a `response` parameter in functions to set headers and cookies.
+/// check | Ideas inspiring **FastAPI**
-### APIStar (<= 0.5)
+Hug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar.
+
+Hug helped inspiring **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically.
+
+Hug inspired **FastAPI** to declare a `response` parameter in functions to set headers and cookies.
+
+///
+
+### [APIStar](https://github.com/encode/apistar) (<= 0.5) { #apistar-0-5 }
Right before deciding to build **FastAPI** I found **APIStar** server. It had almost everything I was looking for and had a great design.
@@ -324,27 +375,33 @@ It was no longer an API web framework, as the creator needed to focus on Starlet
Now APIStar is a set of tools to validate OpenAPI specifications, not a web framework.
-!!! info
- APIStar was created by Tom Christie. The same guy that created:
+/// info
+
+APIStar was created by Tom Christie. The same guy that created:
- * Django REST Framework
- * Starlette (in which **FastAPI** is based)
- * Uvicorn (used by Starlette and **FastAPI**)
+* Django REST Framework
+* Starlette (in which **FastAPI** is based)
+* Uvicorn (used by Starlette and **FastAPI**)
-!!! check "Inspired **FastAPI** to"
- Exist.
+///
- The idea of declaring multiple things (data validation, serialization and documentation) with the same Python types, that at the same time provided great editor support, was something I considered a brilliant idea.
+/// check | Inspired **FastAPI** to
- And after searching for a long time for a similar framework and testing many different alternatives, APIStar was the best option available.
+Exist.
- Then APIStar stopped to exist as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**.
+The idea of declaring multiple things (data validation, serialization and documentation) with the same Python types, that at the same time provided great editor support, was something I considered a brilliant idea.
- I consider **FastAPI** a "spiritual successor" to APIStar, while improving and increasing the features, typing system, and other parts, based on the learnings from all these previous tools.
+And after searching for a long time for a similar framework and testing many different alternatives, APIStar was the best option available.
-## Used by **FastAPI**
+Then APIStar stopped to exist as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**.
-### Pydantic
+I consider **FastAPI** a "spiritual successor" to APIStar, while improving and increasing the features, typing system, and other parts, based on the learnings from all these previous tools.
+
+///
+
+## Used by **FastAPI** { #used-by-fastapi }
+
+### [Pydantic](https://docs.pydantic.dev/) { #pydantic }
Pydantic is a library to define data validation, serialization and documentation (using JSON Schema) based on Python type hints.
@@ -352,14 +409,17 @@ That makes it extremely intuitive.
It is comparable to Marshmallow. Although it's faster than Marshmallow in benchmarks. And as it is based on the same Python type hints, the editor support is great.
-!!! check "**FastAPI** uses it to"
- Handle all the data validation, data serialization and automatic model documentation (based on JSON Schema).
+/// check | **FastAPI** uses it to
- **FastAPI** then takes that JSON Schema data and puts it in OpenAPI, apart from all the other things it does.
+Handle all the data validation, data serialization and automatic model documentation (based on JSON Schema).
-### Starlette
+**FastAPI** then takes that JSON Schema data and puts it in OpenAPI, apart from all the other things it does.
-Starlette is a lightweight ASGI framework/toolkit, which is ideal for building high-performance asyncio services.
+///
+
+### [Starlette](https://www.starlette.dev/) { #starlette }
+
+Starlette is a lightweight ASGI framework/toolkit, which is ideal for building high-performance asyncio services.
It is very simple and intuitive. It's designed to be easily extensible, and have modular components.
@@ -384,19 +444,25 @@ But it doesn't provide automatic data validation, serialization or documentation
That's one of the main things that **FastAPI** adds on top, all based on Python type hints (using Pydantic). That, plus the dependency injection system, security utilities, OpenAPI schema generation, etc.
-!!! note "Technical Details"
- ASGI is a new "standard" being developed by Django core team members. It is still not a "Python standard" (a PEP), although they are in the process of doing that.
+/// note | Technical Details
+
+ASGI is a new "standard" being developed by Django core team members. It is still not a "Python standard" (a PEP), although they are in the process of doing that.
- Nevertheless, it is already being used as a "standard" by several tools. This greatly improves interoperability, as you could switch Uvicorn for any other ASGI server (like Daphne or Hypercorn), or you could add ASGI compatible tools, like `python-socketio`.
+Nevertheless, it is already being used as a "standard" by several tools. This greatly improves interoperability, as you could switch Uvicorn for any other ASGI server (like Daphne or Hypercorn), or you could add ASGI compatible tools, like `python-socketio`.
-!!! check "**FastAPI** uses it to"
- Handle all the core web parts. Adding features on top.
+///
- The class `FastAPI` itself inherits directly from the class `Starlette`.
+/// check | **FastAPI** uses it to
- So, anything that you can do with Starlette, you can do it directly with **FastAPI**, as it is basically Starlette on steroids.
+Handle all the core web parts. Adding features on top.
-### Uvicorn
+The class `FastAPI` itself inherits directly from the class `Starlette`.
+
+So, anything that you can do with Starlette, you can do it directly with **FastAPI**, as it is basically Starlette on steroids.
+
+///
+
+### [Uvicorn](https://www.uvicorn.dev/) { #uvicorn }
Uvicorn is a lightning-fast ASGI server, built on uvloop and httptools.
@@ -404,13 +470,16 @@ It is not a web framework, but a server. For example, it doesn't provide tools f
It is the recommended server for Starlette and **FastAPI**.
-!!! check "**FastAPI** recommends it as"
- The main web server to run **FastAPI** applications.
+/// check | **FastAPI** recommends it as
+
+The main web server to run **FastAPI** applications.
+
+You can also use the `--workers` command line option to have an asynchronous multi-process server.
- You can combine it with Gunicorn, to have an asynchronous multi-process server.
+Check more details in the [Deployment](deployment/index.md) section.
- Check more details in the [Deployment](deployment/index.md){.internal-link target=_blank} section.
+///
-## Benchmarks and speed
+## Benchmarks and speed { #benchmarks-and-speed }
-To understand, compare, and see the difference between Uvicorn, Starlette and FastAPI, check the section about [Benchmarks](benchmarks.md){.internal-link target=_blank}.
+To understand, compare, and see the difference between Uvicorn, Starlette and FastAPI, check the section about [Benchmarks](benchmarks.md).
diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md
index 3d4b1956af477..8d445ace1b5eb 100644
--- a/docs/en/docs/async.md
+++ b/docs/en/docs/async.md
@@ -1,8 +1,8 @@
-# Concurrency and async / await
+# Concurrency and async / await { #concurrency-and-async-await }
Details about the `async def` syntax for *path operation functions* and some background about asynchronous code, concurrency, and parallelism.
-## In a hurry?
+## In a hurry? { #in-a-hurry }
TL;DR:
@@ -21,8 +21,11 @@ async def read_results():
return results
```
-!!! note
- You can only use `await` inside of functions created with `async def`.
+/// note
+
+You can only use `await` inside of functions created with `async def`.
+
+///
---
@@ -37,7 +40,7 @@ def results():
---
-If your application (somehow) doesn't have to communicate with anything else and wait for it to respond, use `async def`.
+If your application (somehow) doesn't have to communicate with anything else and wait for it to respond, use `async def`, even if you don't need to use `await` inside.
---
@@ -51,7 +54,7 @@ Anyway, in any of the cases above, FastAPI will still work asynchronously and be
But by following the steps above, it will be able to do some performance optimizations.
-## Technical Details
+## Technical Details { #technical-details }
Modern versions of Python have support for **"asynchronous code"** using something called **"coroutines"**, with **`async` and `await`** syntax.
@@ -61,7 +64,7 @@ Let's see that phrase by parts in the sections below:
* **`async` and `await`**
* **Coroutines**
-## Asynchronous Code
+## Asynchronous Code { #asynchronous-code }
Asynchronous code just means that the language 💬 has a way to tell the computer / program 🤖 that at some point in the code, it 🤖 will have to wait for *something else* to finish somewhere else. Let's say that *something else* is called "slow-file" 📝.
@@ -90,7 +93,7 @@ Instead of that, by being an "asynchronous" system, once finished, the task can
For "synchronous" (contrary to "asynchronous") they commonly also use the term "sequential", because the computer / program follows all the steps in sequence before switching to a different task, even if those steps involve waiting.
-### Concurrency and Burgers
+### Concurrency and Burgers { #concurrency-and-burgers }
This idea of **asynchronous** code described above is also sometimes called **"concurrency"**. It is different from **"parallelism"**.
@@ -100,7 +103,7 @@ But the details between *concurrency* and *parallelism* are quite different.
To see the difference, imagine the following story about burgers:
-### Concurrent Burgers
+### Concurrent Burgers { #concurrent-burgers }
You go with your crush to get fast food, you stand in line while the cashier takes the orders from the people in front of you. 😍
@@ -136,8 +139,11 @@ You and your crush eat the burgers and have a nice time. ✨
-!!! info
- Beautiful illustrations by Ketrina Thompson. 🎨
+/// info
+
+Beautiful illustrations by [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨
+
+///
---
@@ -157,7 +163,7 @@ So you wait for your crush to finish the story (finish the current work ⏯ / ta
Then you go to the counter 🔀, to the initial task that is now finished ⏯, pick the burgers, say thanks and take them to the table. That finishes that step / task of interaction with the counter ⏹. That in turn, creates a new task, of "eating burgers" 🔀 ⏯, but the previous one of "getting burgers" is finished ⏹.
-### Parallel Burgers
+### Parallel Burgers { #parallel-burgers }
Now let's imagine these aren't "Concurrent Burgers", but "Parallel Burgers".
@@ -199,8 +205,11 @@ You just eat them, and you are done. ⏹
There was not much talk or flirting as most of the time was spent waiting 🕙 in front of the counter. 😞
-!!! info
- Beautiful illustrations by Ketrina Thompson. 🎨
+/// info
+
+Beautiful illustrations by [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨
+
+///
---
@@ -222,9 +231,9 @@ All of the cashiers doing all the work with one client after the other 👨
And you have to wait 🕙 in the line for a long time or you lose your turn.
-You probably wouldn't want to take your crush 😍 with you to do errands at the bank 🏦.
+You probably wouldn't want to take your crush 😍 with you to run errands at the bank 🏦.
-### Burger Conclusion
+### Burger Conclusion { #burger-conclusion }
In this scenario of "fast food burgers with your crush", as there is a lot of waiting 🕙, it makes a lot more sense to have a concurrent system ⏸🔀⏯.
@@ -242,9 +251,9 @@ This kind of asynchronicity is what made NodeJS popular (even though NodeJS is n
And that's the same level of performance you get with **FastAPI**.
-And as you can have parallelism and asynchronicity at the same time, you get higher performance than most of the tested NodeJS frameworks and on par with Go, which is a compiled language closer to C (all thanks to Starlette).
+And as you can have parallelism and asynchronicity at the same time, you get higher performance than most of the tested NodeJS frameworks and on par with Go, which is a compiled language closer to C [(all thanks to Starlette)](https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=query&l=zijmkf-1).
-### Is concurrency better than parallelism?
+### Is concurrency better than parallelism? { #is-concurrency-better-than-parallelism }
Nope! That's not the moral of the story.
@@ -281,17 +290,17 @@ For example:
* **Machine Learning**: it normally requires lots of "matrix" and "vector" multiplications. Think of a huge spreadsheet with numbers and multiplying all of them together at the same time.
* **Deep Learning**: this is a sub-field of Machine Learning, so, the same applies. It's just that there is not a single spreadsheet of numbers to multiply, but a huge set of them, and in many cases, you use a special processor to build and / or use those models.
-### Concurrency + Parallelism: Web + Machine Learning
+### Concurrency + Parallelism: Web + Machine Learning { #concurrency-parallelism-web-machine-learning }
-With **FastAPI** you can take the advantage of concurrency that is very common for web development (the same main attraction of NodeJS).
+With **FastAPI** you can take advantage of concurrency that is very common for web development (the same main attraction of NodeJS).
But you can also exploit the benefits of parallelism and multiprocessing (having multiple processes running in parallel) for **CPU bound** workloads like those in Machine Learning systems.
That, plus the simple fact that Python is the main language for **Data Science**, Machine Learning and especially Deep Learning, make FastAPI a very good match for Data Science / Machine Learning web APIs and applications (among many others).
-To see how to achieve this parallelism in production see the section about [Deployment](deployment/index.md){.internal-link target=_blank}.
+To see how to achieve this parallelism in production see the section about [Deployment](deployment/index.md).
-## `async` and `await`
+## `async` and `await` { #async-and-await }
Modern versions of Python have a very intuitive way to define asynchronous code. This makes it look just like normal "sequential" code and do the "awaiting" for you at the right moments.
@@ -340,7 +349,7 @@ async def read_burgers():
return burgers
```
-### More technical details
+### More technical details { #more-technical-details }
You might have noticed that `await` can only be used inside of functions defined with `async def`.
@@ -352,15 +361,17 @@ If you are working with **FastAPI** you don't have to worry about that, because
But if you want to use `async` / `await` without FastAPI, you can do it as well.
-### Write your own async code
+### Write your own async code { #write-your-own-async-code }
+
+Starlette (and **FastAPI**) are based on [AnyIO](https://anyio.readthedocs.io/en/stable/), which makes it compatible with both Python's standard library [asyncio](https://docs.python.org/3/library/asyncio-task.html) and [Trio](https://trio.readthedocs.io/en/stable/).
-Starlette (and **FastAPI**) are based on AnyIO, which makes it compatible with both Python's standard library asyncio and Trio.
+In particular, you can directly use [AnyIO](https://anyio.readthedocs.io/en/stable/) for your advanced concurrency use cases that require more advanced patterns in your own code.
-In particular, you can directly use AnyIO for your advanced concurrency use cases that require more advanced patterns in your own code.
+And even if you were not using FastAPI, you could also write your own async applications with [AnyIO](https://anyio.readthedocs.io/en/stable/) to be highly compatible and get its benefits (e.g. *structured concurrency*).
-And even if you were not using FastAPI, you could also write your own async applications with AnyIO to be highly compatible and get its benefits (e.g. *structured concurrency*).
+I created another library on top of AnyIO, as a thin layer on top, to improve a bit the type annotations and get better **autocompletion**, **inline errors**, etc. It also has a friendly introduction and tutorial to help you **understand** and write **your own async code**: [Asyncer](https://asyncer.tiangolo.com/). It would be particularly useful if you need to **combine async code with regular** (blocking/synchronous) code.
-### Other forms of asynchronous code
+### Other forms of asynchronous code { #other-forms-of-asynchronous-code }
This style of using `async` and `await` is relatively new in the language.
@@ -370,17 +381,17 @@ This same syntax (or almost identical) was also included recently in modern vers
But before that, handling asynchronous code was quite more complex and difficult.
-In previous versions of Python, you could have used threads or Gevent. But the code is way more complex to understand, debug, and think about.
+In previous versions of Python, you could have used threads or [Gevent](https://www.gevent.org/). But the code is way more complex to understand, debug, and think about.
-In previous versions of NodeJS / Browser JavaScript, you would have used "callbacks". Which leads to callback hell.
+In previous versions of NodeJS / Browser JavaScript, you would have used "callbacks". Which leads to "callback hell".
-## Coroutines
+## Coroutines { #coroutines }
-**Coroutine** is just the very fancy term for the thing returned by an `async def` function. Python knows that it is something like a function that it can start and that it will end at some point, but that it might be paused ⏸ internally too, whenever there is an `await` inside of it.
+**Coroutine** is just the very fancy term for the thing returned by an `async def` function. Python knows that it is something like a function, that it can start and that it will end at some point, but that it might be paused ⏸ internally too, whenever there is an `await` inside of it.
But all this functionality of using asynchronous code with `async` and `await` is many times summarized as using "coroutines". It is comparable to the main key feature of Go, the "Goroutines".
-## Conclusion
+## Conclusion { #conclusion }
Let's see the same phrase from above:
@@ -390,32 +401,35 @@ That should make more sense now. ✨
All that is what powers FastAPI (through Starlette) and what makes it have such an impressive performance.
-## Very Technical Details
+## Very Technical Details { #very-technical-details }
+
+/// warning
+
+You can probably skip this.
-!!! warning
- You can probably skip this.
+These are very technical details of how **FastAPI** works underneath.
- These are very technical details of how **FastAPI** works underneath.
+If you have quite some technical knowledge (coroutines, threads, blocking, etc.) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead.
- If you have quite some technical knowledge (co-routines, threads, blocking, etc.) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead.
+///
-### Path operation functions
+### Path operation functions { #path-operation-functions }
When you declare a *path operation function* with normal `def` instead of `async def`, it is run in an external threadpool that is then awaited, instead of being called directly (as it would block the server).
If you are coming from another async framework that does not work in the way described above and you are used to defining trivial compute-only *path operation functions* with plain `def` for a tiny performance gain (about 100 nanoseconds), please note that in **FastAPI** the effect would be quite opposite. In these cases, it's better to use `async def` unless your *path operation functions* use code that performs blocking I/O.
-Still, in both situations, chances are that **FastAPI** will [still be faster](/#performance){.internal-link target=_blank} than (or at least comparable to) your previous framework.
+Still, in both situations, chances are that **FastAPI** will [still be faster](index.md#performance) than (or at least comparable to) your previous framework.
-### Dependencies
+### Dependencies { #dependencies }
-The same applies for [dependencies](/tutorial/dependencies/index.md){.internal-link target=_blank}. If a dependency is a standard `def` function instead of `async def`, it is run in the external threadpool.
+The same applies for [dependencies](tutorial/dependencies/index.md). If a dependency is a standard `def` function instead of `async def`, it is run in the external threadpool.
-### Sub-dependencies
+### Sub-dependencies { #sub-dependencies }
-You can have multiple dependencies and [sub-dependencies](/tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} requiring each other (as parameters of the function definitions), some of them might be created with `async def` and some with normal `def`. It would still work, and the ones created with normal `def` would be called on an external thread (from the threadpool) instead of being "awaited".
+You can have multiple dependencies and [sub-dependencies](tutorial/dependencies/sub-dependencies.md) requiring each other (as parameters of the function definitions), some of them might be created with `async def` and some with normal `def`. It would still work, and the ones created with normal `def` would be called on an external thread (from the threadpool) instead of being "awaited".
-### Other utility functions
+### Other utility functions { #other-utility-functions }
Any other utility function that you call directly can be created with normal `def` or `async def` and FastAPI won't affect the way you call it.
diff --git a/docs/en/docs/benchmarks.md b/docs/en/docs/benchmarks.md
index e05fec8406621..5b37877b32963 100644
--- a/docs/en/docs/benchmarks.md
+++ b/docs/en/docs/benchmarks.md
@@ -1,10 +1,10 @@
-# Benchmarks
+# Benchmarks { #benchmarks }
-Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)
+Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as [one of the fastest Python frameworks available](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7), 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
+## Benchmarks and speed { #benchmarks-and-speed }
When you check the benchmarks, it is common to see several tools of different types compared as equivalent.
diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md
index cfdb607d772e0..fe7318f6cd690 100644
--- a/docs/en/docs/contributing.md
+++ b/docs/en/docs/contributing.md
@@ -1,114 +1,19 @@
# Development - Contributing
-First, you might want to see the basic ways to [help FastAPI and get help](help-fastapi.md){.internal-link target=_blank}.
+First, you might want to see the basic ways to [help FastAPI and get help](help-fastapi.md).
## 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 [fastapi repository](https://github.com/fastapi/fastapi) and you want to deep dive in the code, here are some guidelines to set up your environment.
-### Virtual environment with `venv`
+### Install requirements
-You can create a virtual environment in a directory using Python's `venv` module:
+Create a virtual environment and install the required packages with [`uv`](https://github.com/astral-sh/uv):
+With great-powertools comes great responsibility. +
@@ -28,7 +28,7 @@ But at some point, there was no other option than creating something that provid-## Investigation +## Investigation { #investigation } By using all the previous alternatives I had the chance to learn from all of them, take ideas, and combine them in the best way I could find for myself and the teams of developers I have worked with. @@ -38,13 +38,13 @@ Also, the best approach was to use already existing standards. So, before even starting to code **FastAPI**, I spent several months studying the specs for OpenAPI, JSON Schema, OAuth2, etc. Understanding their relationship, overlap, and differences. -## Design +## Design { #design } Then I spent some time designing the developer "API" I wanted to have as a user (as a developer using FastAPI). I tested several ideas in the most popular Python editors: PyCharm, VS Code, Jedi based editors. -By the last Python Developer Survey, that covers about 80% of the users. +By the last [Python Developer Survey](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools), that covers about 80% of the users. It means that **FastAPI** was specifically tested with the editors used by 80% of the Python developers. And as most of the other editors tend to work similarly, all its benefits should work for virtually all editors. @@ -52,19 +52,19 @@ That way I could find the best ways to reduce code duplication as much as possib All in a way that provided the best development experience for all the developers. -## Requirements +## Requirements { #requirements } -After testing several alternatives, I decided that I was going to use **Pydantic** for its advantages. +After testing several alternatives, I decided that I was going to use [**Pydantic**](https://docs.pydantic.dev/) for its advantages. Then I contributed to it, to make it fully compliant with JSON Schema, to support different ways to define constraint declarations, and to improve editor support (type checks, autocompletion) based on the tests in several editors. -During the development, I also contributed to **Starlette**, the other key requirement. +During the development, I also contributed to [**Starlette**](https://www.starlette.dev/), the other key requirement. -## Development +## Development { #development } By the time I started creating **FastAPI** itself, most of the pieces were already in place, the design was defined, the requirements and tools were ready, and the knowledge about the standards and specifications was clear and fresh. -## Future +## Future { #future } By this point, it's already clear that **FastAPI** with its ideas is being useful for many people. @@ -76,4 +76,4 @@ But still, there are many improvements and features to come. **FastAPI** has a great future ahead. -And [your help](help-fastapi.md){.internal-link target=_blank} is greatly appreciated. +And [your help](help-fastapi.md) is greatly appreciated. diff --git a/docs/en/docs/how-to/async-sql-encode-databases.md b/docs/en/docs/how-to/async-sql-encode-databases.md deleted file mode 100644 index 697167f790267..0000000000000 --- a/docs/en/docs/how-to/async-sql-encode-databases.md +++ /dev/null @@ -1,169 +0,0 @@ -# Async SQL (Relational) Databases with Encode/Databases - -!!! info - These docs are about to be updated. 🎉 - - The current version assumes Pydantic v1. - - The new docs will include Pydantic v2 and will use SQLModel once it is updated to use Pydantic v2 as well. - -You can also use `encode/databases` with **FastAPI** to connect to databases using `async` and `await`. - -It is compatible with: - -* PostgreSQL -* MySQL -* SQLite - -In this example, we'll use **SQLite**, because it uses a single file and Python has integrated support. So, you can copy this example and run it as is. - -Later, for your production application, you might want to use a database server like **PostgreSQL**. - -!!! tip - You could adopt ideas from the section about SQLAlchemy ORM ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}), like using utility functions to perform operations in the database, independent of your **FastAPI** code. - - This section doesn't apply those ideas, to be equivalent to the counterpart in Starlette. - -## Import and set up `SQLAlchemy` - -* Import `SQLAlchemy`. -* Create a `metadata` object. -* Create a table `notes` using the `metadata` object. - -```Python hl_lines="4 14 16-22" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! tip - Notice that all this code is pure SQLAlchemy Core. - - `databases` is not doing anything here yet. - -## Import and set up `databases` - -* Import `databases`. -* Create a `DATABASE_URL`. -* Create a `database` object. - -```Python hl_lines="3 9 12" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! tip - If you were connecting to a different database (e.g. PostgreSQL), you would need to change the `DATABASE_URL`. - -## Create the tables - -In this case, we are creating the tables in the same Python file, but in production, you would probably want to create them with Alembic, integrated with migrations, etc. - -Here, this section would run directly, right before starting your **FastAPI** application. - -* Create an `engine`. -* Create all the tables from the `metadata` object. - -```Python hl_lines="25-28" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -## Create models - -Create Pydantic models for: - -* Notes to be created (`NoteIn`). -* Notes to be returned (`Note`). - -```Python hl_lines="31-33 36-39" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -By creating these Pydantic models, the input data will be validated, serialized (converted), and annotated (documented). - -So, you will be able to see it all in the interactive API docs. - -## Connect and disconnect - -* Create your `FastAPI` application. -* Create event handlers to connect and disconnect from the database. - -```Python hl_lines="42 45-47 50-52" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -## Read notes - -Create the *path operation function* to read notes: - -```Python hl_lines="55-58" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! Note - Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. - -### Notice the `response_model=List[Note]` - -It uses `typing.List`. - -That documents (and validates, serializes, filters) the output data, as a `list` of `Note`s. - -## Create notes - -Create the *path operation function* to create notes: - -```Python hl_lines="61-65" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! Note - Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. - -### About `{**note.dict(), "id": last_record_id}` - -`note` is a Pydantic `Note` object. - -`note.dict()` returns a `dict` with its data, something like: - -```Python -{ - "text": "Some note", - "completed": False, -} -``` - -but it doesn't have the `id` field. - -So we create a new `dict`, that contains the key-value pairs from `note.dict()` with: - -```Python -{**note.dict()} -``` - -`**note.dict()` "unpacks" the key value pairs directly, so, `{**note.dict()}` would be, more or less, a copy of `note.dict()`. - -And then, we extend that copy `dict`, adding another key-value pair: `"id": last_record_id`: - -```Python -{**note.dict(), "id": last_record_id} -``` - -So, the final result returned would be something like: - -```Python -{ - "id": 1, - "text": "Some note", - "completed": False, -} -``` - -## Check it - -You can copy this code as is, and see the docs at http://127.0.0.1:8000/docs. - -There you can see all your API documented and interact with it: - -
-
-## More info
-
-You can read more about `encode/databases` at its GitHub page.
diff --git a/docs/en/docs/how-to/authentication-error-status-code.md b/docs/en/docs/how-to/authentication-error-status-code.md
new file mode 100644
index 0000000000000..83b974e2dac01
--- /dev/null
+++ b/docs/en/docs/how-to/authentication-error-status-code.md
@@ -0,0 +1,17 @@
+# Use Old 403 Authentication Error Status Codes { #use-old-403-authentication-error-status-codes }
+
+Before FastAPI version `0.122.0`, when the integrated security utilities returned an error to the client after a failed authentication, they used the HTTP status code `403 Forbidden`.
+
+Starting with FastAPI version `0.122.0`, they use the more appropriate HTTP status code `401 Unauthorized`, and return a sensible `WWW-Authenticate` header in the response, following the HTTP specifications, [RFC 7235](https://datatracker.ietf.org/doc/html/rfc7235#section-3.1), [RFC 9110](https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized).
+
+But if for some reason your clients depend on the old behavior, you can revert to it by overriding the method `make_not_authenticated_error` in your security classes.
+
+For example, you can create a subclass of `HTTPBearer` that returns a `403 Forbidden` error instead of the default `401 Unauthorized` error:
+
+{* ../../docs_src/authentication_error_status_code/tutorial001_an_py310.py hl[9:13] *}
+
+/// tip
+
+Notice that the function returns the exception instance, it doesn't raise it. The raising is done in the rest of the internal code.
+
+///
diff --git a/docs/en/docs/how-to/conditional-openapi.md b/docs/en/docs/how-to/conditional-openapi.md
index add16fbec519e..2c0edf87f4d25 100644
--- a/docs/en/docs/how-to/conditional-openapi.md
+++ b/docs/en/docs/how-to/conditional-openapi.md
@@ -1,8 +1,8 @@
-# Conditional OpenAPI
+# Conditional OpenAPI { #conditional-openapi }
If you needed to, you could use settings and environment variables to configure OpenAPI conditionally depending on the environment, and even disable it entirely.
-## About security, APIs, and docs
+## About security, APIs, and docs { #about-security-apis-and-docs }
Hiding your documentation user interfaces in production *shouldn't* be the way to protect your API.
@@ -10,28 +10,26 @@ That doesn't add any extra security to your API, the *path operations* will stil
If there's a security flaw in your code, it will still exist.
-Hiding the documentation just makes it more difficult to understand how to interact with your API, and could make it more difficult for you to debug it in production. It could be considered simply a form of Security through obscurity.
+Hiding the documentation just makes it more difficult to understand how to interact with your API, and could make it more difficult for you to debug it in production. It could be considered simply a form of [Security through obscurity](https://en.wikipedia.org/wiki/Security_through_obscurity).
If you want to secure your API, there are several better things you can do, for example:
* Make sure you have well defined Pydantic models for your request bodies and responses.
* Configure any required permissions and roles using dependencies.
* Never store plaintext passwords, only password hashes.
-* Implement and use well-known cryptographic tools, like Passlib and JWT tokens, etc.
+* Implement and use well-known cryptographic tools, like pwdlib and JWT tokens, etc.
* Add more granular permission controls with OAuth2 scopes where needed.
* ...etc.
Nevertheless, you might have a very specific use case where you really need to disable the API docs for some environment (e.g. for production) or depending on configurations from environment variables.
-## Conditional OpenAPI from settings and env vars
+## Conditional OpenAPI from settings and env vars { #conditional-openapi-from-settings-and-env-vars }
You can easily use the same Pydantic settings to configure your generated OpenAPI and the docs UIs.
For example:
-```Python hl_lines="6 11"
-{!../../../docs_src/conditional_openapi/tutorial001.py!}
-```
+{* ../../docs_src/conditional_openapi/tutorial001_py310.py hl[6,11] *}
Here we declare the setting `openapi_url` with the same default of `"/openapi.json"`.
diff --git a/docs/en/docs/how-to/configure-swagger-ui.md b/docs/en/docs/how-to/configure-swagger-ui.md
index f36ba5ba8c230..7c3d9cb25a102 100644
--- a/docs/en/docs/how-to/configure-swagger-ui.md
+++ b/docs/en/docs/how-to/configure-swagger-ui.md
@@ -1,6 +1,6 @@
-# Configure Swagger UI
+# Configure Swagger UI { #configure-swagger-ui }
-You can configure some extra Swagger UI parameters.
+You can configure some extra [Swagger UI parameters](https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/).
To configure them, pass the `swagger_ui_parameters` argument when creating the `FastAPI()` app object or to the `get_swagger_ui_html()` function.
@@ -8,7 +8,7 @@ To configure them, pass the `swagger_ui_parameters` argument when creating the `
FastAPI converts the configurations to **JSON** to make them compatible with JavaScript, as that's what Swagger UI needs.
-## Disable Syntax Highlighting
+## Disable Syntax Highlighting { #disable-syntax-highlighting }
For example, you could disable syntax highlighting in Swagger UI.
@@ -18,49 +18,41 @@ Without changing the settings, syntax highlighting is enabled by default:
But you can disable it by setting `syntaxHighlight` to `False`:
-```Python hl_lines="3"
-{!../../../docs_src/configure_swagger_ui/tutorial001.py!}
-```
+{* ../../docs_src/configure_swagger_ui/tutorial001_py310.py hl[3] *}
...and then Swagger UI won't show the syntax highlighting anymore:
-## Change the Theme
+## Change the Theme { #change-the-theme }
The same way you could set the syntax highlighting theme with the key `"syntaxHighlight.theme"` (notice that it has a dot in the middle):
-```Python hl_lines="3"
-{!../../../docs_src/configure_swagger_ui/tutorial002.py!}
-```
+{* ../../docs_src/configure_swagger_ui/tutorial002_py310.py hl[3] *}
That configuration would change the syntax highlighting color theme:
-## Change Default Swagger UI Parameters
+## Change Default Swagger UI Parameters { #change-default-swagger-ui-parameters }
FastAPI includes some default configuration parameters appropriate for most of the use cases.
It includes these default configurations:
-```Python
-{!../../../fastapi/openapi/docs.py[ln:7-13]!}
-```
+{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}
You can override any of them by setting a different value in the argument `swagger_ui_parameters`.
For example, to disable `deepLinking` you could pass these settings to `swagger_ui_parameters`:
-```Python hl_lines="3"
-{!../../../docs_src/configure_swagger_ui/tutorial003.py!}
-```
+{* ../../docs_src/configure_swagger_ui/tutorial003_py310.py hl[3] *}
-## Other Swagger UI Parameters
+## Other Swagger UI Parameters { #other-swagger-ui-parameters }
-To see all the other possible configurations you can use, read the official docs for Swagger UI parameters.
+To see all the other possible configurations you can use, read the official [docs for Swagger UI parameters](https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/).
-## JavaScript-only settings
+## JavaScript-only settings { #javascript-only-settings }
Swagger UI also allows other configurations to be **JavaScript-only** objects (for example, JavaScript functions).
diff --git a/docs/en/docs/how-to/custom-docs-ui-assets.md b/docs/en/docs/how-to/custom-docs-ui-assets.md
index f263248692192..c9e5d8a152a72 100644
--- a/docs/en/docs/how-to/custom-docs-ui-assets.md
+++ b/docs/en/docs/how-to/custom-docs-ui-assets.md
@@ -1,4 +1,4 @@
-# Custom Docs UI Static Assets (Self-Hosting)
+# Custom Docs UI Static Assets (Self-Hosting) { #custom-docs-ui-static-assets-self-hosting }
The API docs use **Swagger UI** and **ReDoc**, and each of those need some JavaScript and CSS files.
@@ -6,27 +6,25 @@ By default, those files are served from a CDN, for example you want to use `https://unpkg.com/`.
This could be useful if for example you live in a country that restricts some URLs.
-### Disable the automatic docs
+### Disable the automatic docs { #disable-the-automatic-docs }
The first step is to disable the automatic docs, as by default, those use the default CDN.
To disable them, set their URLs to `None` when creating your `FastAPI` app:
-```Python hl_lines="8"
-{!../../../docs_src/custom_docs_ui/tutorial001.py!}
-```
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[8] *}
-### Include the custom docs
+### Include the custom docs { #include-the-custom-docs }
Now you can create the *path operations* for the custom docs.
-You can re-use FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments:
+You can reuse FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments:
* `openapi_url`: the URL where the HTML page for the docs can get the OpenAPI schema for your API. You can use here the attribute `app.openapi_url`.
* `title`: the title of your API.
@@ -36,36 +34,35 @@ You can re-use FastAPI's internal functions to create the HTML pages for the doc
And similarly for ReDoc...
-```Python hl_lines="2-6 11-19 22-24 27-33"
-{!../../../docs_src/custom_docs_ui/tutorial001.py!}
-```
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[2:6,11:19,22:24,27:33] *}
+
+/// tip
-!!! tip
- The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2.
+The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2.
- If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication.
+If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication.
- Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper.
+Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper.
-### Create a *path operation* to test it
+///
+
+### Create a *path operation* to test it { #create-a-path-operation-to-test-it }
Now, to be able to test that everything works, create a *path operation*:
-```Python hl_lines="36-38"
-{!../../../docs_src/custom_docs_ui/tutorial001.py!}
-```
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[36:38] *}
-### Test it
+### Test it { #test-it }
-Now, you should be able to go to your docs at http://127.0.0.1:8000/docs, and reload the page, it will load those assets from the new CDN.
+Now, you should be able to go to your docs at [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs), and reload the page, it will load those assets from the new CDN.
-## Self-hosting JavaScript and CSS for docs
+## Self-hosting JavaScript and CSS for docs { #self-hosting-javascript-and-css-for-docs }
Self-hosting the JavaScript and CSS could be useful if, for example, you need your app to keep working even while offline, without open Internet access, or in a local network.
Here you'll see how to serve those files yourself, in the same FastAPI app, and configure the docs to use them.
-### Project file structure
+### Project file structure { #project-file-structure }
Let's say your project file structure looks like this:
@@ -88,20 +85,20 @@ Your new file structure could look like this:
└── static/
```
-### Download the files
+### Download the files { #download-the-files }
Download the static files needed for the docs and put them on that `static/` directory.
-You can probably right-click each link and select an option similar to `Save link as...`.
+You can probably right-click each link and select an option similar to "Save link as...".
**Swagger UI** uses the files:
-* `swagger-ui-bundle.js`
-* `swagger-ui.css`
+* [`swagger-ui-bundle.js`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js)
+* [`swagger-ui.css`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css)
And **ReDoc** uses the file:
-* `redoc.standalone.js`
+* [`redoc.standalone.js`](https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js)
After that, your file structure could look like:
@@ -116,32 +113,24 @@ After that, your file structure could look like:
└── swagger-ui.css
```
-### Serve the static files
+### Serve the static files { #serve-the-static-files }
* Import `StaticFiles`.
* "Mount" a `StaticFiles()` instance in a specific path.
-```Python hl_lines="7 11"
-{!../../../docs_src/custom_docs_ui/tutorial002.py!}
-```
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[7,11] *}
-### Test the static files
+### Test the static files { #test-the-static-files }
-Start your application and go to http://127.0.0.1:8000/static/redoc.standalone.js.
+Start your application and go to [http://127.0.0.1:8000/static/redoc.standalone.js](http://127.0.0.1:8000/static/redoc.standalone.js).
You should see a very long JavaScript file for **ReDoc**.
It could start with something like:
```JavaScript
-/*!
- * ReDoc - OpenAPI/Swagger-generated API Reference Documentation
- * -------------------------------------------------------------
- * Version: "2.0.0-rc.18"
- * Repo: https://github.com/Redocly/redoc
- */
-!function(e,t){"object"==typeof exports&&"object"==typeof m
-
+/*! For license information please see redoc.standalone.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")):
...
```
@@ -149,21 +138,19 @@ That confirms that you are being able to serve static files from your app, and t
Now we can configure the app to use those static files for the docs.
-### Disable the automatic docs for static files
+### Disable the automatic docs for static files { #disable-the-automatic-docs-for-static-files }
The same as when using a custom CDN, the first step is to disable the automatic docs, as those use the CDN by default.
To disable them, set their URLs to `None` when creating your `FastAPI` app:
-```Python hl_lines="9"
-{!../../../docs_src/custom_docs_ui/tutorial002.py!}
-```
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[9] *}
-### Include the custom docs for static files
+### Include the custom docs for static files { #include-the-custom-docs-for-static-files }
And the same way as with a custom CDN, now you can create the *path operations* for the custom docs.
-Again, you can re-use FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments:
+Again, you can reuse FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments:
* `openapi_url`: the URL where the HTML page for the docs can get the OpenAPI schema for your API. You can use here the attribute `app.openapi_url`.
* `title`: the title of your API.
@@ -173,27 +160,26 @@ Again, you can re-use FastAPI's internal functions to create the HTML pages for
And similarly for ReDoc...
-```Python hl_lines="2-6 14-22 25-27 30-36"
-{!../../../docs_src/custom_docs_ui/tutorial002.py!}
-```
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[2:6,14:22,25:27,30:36] *}
-!!! tip
- The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2.
+/// tip
- If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication.
+The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2.
- Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper.
+If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication.
-### Create a *path operation* to test static files
+Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper.
+
+///
+
+### Create a *path operation* to test static files { #create-a-path-operation-to-test-static-files }
Now, to be able to test that everything works, create a *path operation*:
-```Python hl_lines="39-41"
-{!../../../docs_src/custom_docs_ui/tutorial002.py!}
-```
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[39:41] *}
-### Test Static Files UI
+### Test Static Files UI { #test-static-files-ui }
-Now, you should be able to disconnect your WiFi, go to your docs at http://127.0.0.1:8000/docs, and reload the page.
+Now, you should be able to disconnect your WiFi, go to your docs at [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs), and reload the page.
And even without Internet, you would be able to see the docs for your API and interact with it.
diff --git a/docs/en/docs/how-to/custom-request-and-route.md b/docs/en/docs/how-to/custom-request-and-route.md
index bca0c7603613d..bce232017e575 100644
--- a/docs/en/docs/how-to/custom-request-and-route.md
+++ b/docs/en/docs/how-to/custom-request-and-route.md
@@ -1,4 +1,4 @@
-# Custom Request and APIRoute class
+# Custom Request and APIRoute class { #custom-request-and-apiroute-class }
In some cases, you may want to override the logic used by the `Request` and `APIRoute` classes.
@@ -6,29 +6,35 @@ In particular, this may be a good alternative to logic in a middleware.
For example, if you want to read or manipulate the request body before it is processed by your application.
-!!! danger
- This is an "advanced" feature.
+/// danger
- If you are just starting with **FastAPI** you might want to skip this section.
+This is an "advanced" feature.
-## Use cases
+If you are just starting with **FastAPI** you might want to skip this section.
+
+///
+
+## Use cases { #use-cases }
Some use cases include:
-* Converting non-JSON request bodies to JSON (e.g. `msgpack`).
+* Converting non-JSON request bodies to JSON (e.g. [`msgpack`](https://msgpack.org/index.html)).
* Decompressing gzip-compressed request bodies.
* Automatically logging all request bodies.
-## Handling custom request body encodings
+## Handling custom request body encodings { #handling-custom-request-body-encodings }
Let's see how to make use of a custom `Request` subclass to decompress gzip requests.
And an `APIRoute` subclass to use that custom request class.
-### Create a custom `GzipRequest` class
+### Create a custom `GzipRequest` class { #create-a-custom-gziprequest-class }
+
+/// tip
+
+This is a toy example to demonstrate how it works, if you need Gzip support, you can use the provided [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware).
-!!! tip
- This is a toy example to demonstrate how it works, if you need Gzip support, you can use the provided [`GzipMiddleware`](./middleware.md#gzipmiddleware){.internal-link target=_blank}.
+///
First, we create a `GzipRequest` class, which will overwrite the `Request.body()` method to decompress the body in the presence of an appropriate header.
@@ -36,11 +42,9 @@ If there's no `gzip` in the header, it will not try to decompress the body.
That way, the same route class can handle gzip compressed or uncompressed requests.
-```Python hl_lines="8-15"
-{!../../../docs_src/custom_request_and_route/tutorial001.py!}
-```
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[9:16] *}
-### Create a custom `GzipRoute` class
+### Create a custom `GzipRoute` class { #create-a-custom-gziproute-class }
Next, we create a custom subclass of `fastapi.routing.APIRoute` that will make use of the `GzipRequest`.
@@ -50,20 +54,21 @@ This method returns a function. And that function is what will receive a request
Here we use it to create a `GzipRequest` from the original request.
-```Python hl_lines="18-26"
-{!../../../docs_src/custom_request_and_route/tutorial001.py!}
-```
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[19:27] *}
-!!! note "Technical Details"
- A `Request` has a `request.scope` attribute, that's just a Python `dict` containing the metadata related to the request.
+/// note | Technical Details
- A `Request` also has a `request.receive`, that's a function to "receive" the body of the request.
+A `Request` has a `request.scope` attribute, that's just a Python `dict` containing the metadata related to the request.
- The `scope` `dict` and `receive` function are both part of the ASGI specification.
+A `Request` also has a `request.receive`, that's a function to "receive" the body of the request.
- And those two things, `scope` and `receive`, are what is needed to create a new `Request` instance.
+The `scope` `dict` and `receive` function are both part of the ASGI specification.
- To learn more about the `Request` check Starlette's docs about Requests.
+And those two things, `scope` and `receive`, are what is needed to create a new `Request` instance.
+
+To learn more about the `Request` check [Starlette's docs about Requests](https://www.starlette.dev/requests/).
+
+///
The only thing the function returned by `GzipRequest.get_route_handler` does differently is convert the `Request` to a `GzipRequest`.
@@ -73,37 +78,32 @@ After that, all of the processing logic is the same.
But because of our changes in `GzipRequest.body`, the request body will be automatically decompressed when it is loaded by **FastAPI** when needed.
-## Accessing the request body in an exception handler
+## Accessing the request body in an exception handler { #accessing-the-request-body-in-an-exception-handler }
+
+/// tip
+
+To solve this same problem, it's probably a lot easier to use the `body` in a custom handler for `RequestValidationError` ([Handling Errors](../tutorial/handling-errors.md#use-the-requestvalidationerror-body)).
-!!! tip
- To solve this same problem, it's probably a lot easier to use the `body` in a custom handler for `RequestValidationError` ([Handling Errors](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}).
+But this example is still valid and it shows how to interact with the internal components.
- But this example is still valid and it shows how to interact with the internal components.
+///
We can also use this same approach to access the request body in an exception handler.
All we need to do is handle the request inside a `try`/`except` block:
-```Python hl_lines="13 15"
-{!../../../docs_src/custom_request_and_route/tutorial002.py!}
-```
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[14,16] *}
If an exception occurs, the`Request` instance will still be in scope, so we can read and make use of the request body when handling the error:
-```Python hl_lines="16-18"
-{!../../../docs_src/custom_request_and_route/tutorial002.py!}
-```
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[17:19] *}
-## Custom `APIRoute` class in a router
+## Custom `APIRoute` class in a router { #custom-apiroute-class-in-a-router }
You can also set the `route_class` parameter of an `APIRouter`:
-```Python hl_lines="26"
-{!../../../docs_src/custom_request_and_route/tutorial003.py!}
-```
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[26] *}
In this example, the *path operations* under the `router` will use the custom `TimedRoute` class, and will have an extra `X-Response-Time` header in the response with the time it took to generate the response:
-```Python hl_lines="13-20"
-{!../../../docs_src/custom_request_and_route/tutorial003.py!}
-```
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[13:20] *}
diff --git a/docs/en/docs/how-to/extending-openapi.md b/docs/en/docs/how-to/extending-openapi.md
index a18fd737e6b4e..c110a444f12ca 100644
--- a/docs/en/docs/how-to/extending-openapi.md
+++ b/docs/en/docs/how-to/extending-openapi.md
@@ -1,10 +1,10 @@
-# Extending OpenAPI
+# Extending OpenAPI { #extending-openapi }
There are some cases where you might need to modify the generated OpenAPI schema.
In this section you will see how.
-## The normal process
+## The normal process { #the-normal-process }
The normal (default) process, is as follows.
@@ -27,40 +27,37 @@ And that function `get_openapi()` receives as parameters:
* `description`: The description of your API, this can include markdown and will be shown in the docs.
* `routes`: A list of routes, these are each of the registered *path operations*. They are taken from `app.routes`.
-!!! info
- The parameter `summary` is available in OpenAPI 3.1.0 and above, supported by FastAPI 0.99.0 and above.
+/// info
-## Overriding the defaults
+The parameter `summary` is available in OpenAPI 3.1.0 and above, supported by FastAPI 0.99.0 and above.
+
+///
+
+## Overriding the defaults { #overriding-the-defaults }
Using the information above, you can use the same utility function to generate the OpenAPI schema and override each part that you need.
-For example, let's add ReDoc's OpenAPI extension to include a custom logo.
+For example, let's add [ReDoc's OpenAPI extension to include a custom logo](https://github.com/Rebilly/ReDoc/blob/master/docs/redoc-vendor-extensions.md#x-logo).
-### Normal **FastAPI**
+### Normal **FastAPI** { #normal-fastapi }
First, write all your **FastAPI** application as normally:
-```Python hl_lines="1 4 7-9"
-{!../../../docs_src/extending_openapi/tutorial001.py!}
-```
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[1,4,7:9] *}
-### Generate the OpenAPI schema
+### Generate the OpenAPI schema { #generate-the-openapi-schema }
Then, use the same utility function to generate the OpenAPI schema, inside a `custom_openapi()` function:
-```Python hl_lines="2 15-21"
-{!../../../docs_src/extending_openapi/tutorial001.py!}
-```
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[2,15:21] *}
-### Modify the OpenAPI schema
+### Modify the OpenAPI schema { #modify-the-openapi-schema }
Now you can add the ReDoc extension, adding a custom `x-logo` to the `info` "object" in the OpenAPI schema:
-```Python hl_lines="22-24"
-{!../../../docs_src/extending_openapi/tutorial001.py!}
-```
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[22:24] *}
-### Cache the OpenAPI schema
+### Cache the OpenAPI schema { #cache-the-openapi-schema }
You can use the property `.openapi_schema` as a "cache", to store your generated schema.
@@ -68,20 +65,16 @@ That way, your application won't have to generate the schema every time a user o
It will be generated only once, and then the same cached schema will be used for the next requests.
-```Python hl_lines="13-14 25-26"
-{!../../../docs_src/extending_openapi/tutorial001.py!}
-```
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[13:14,25:26] *}
-### Override the method
+### Override the method { #override-the-method }
Now you can replace the `.openapi()` method with your new function.
-```Python hl_lines="29"
-{!../../../docs_src/extending_openapi/tutorial001.py!}
-```
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[29] *}
-### Check it
+### Check it { #check-it }
-Once you go to http://127.0.0.1:8000/redoc you will see that you are using your custom logo (in this example, **FastAPI**'s logo):
+Once you go to [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) you will see that you are using your custom logo (in this example, **FastAPI**'s logo):
diff --git a/docs/en/docs/how-to/general.md b/docs/en/docs/how-to/general.md
index 04367c6b76353..da6738eb9b1ff 100644
--- a/docs/en/docs/how-to/general.md
+++ b/docs/en/docs/how-to/general.md
@@ -1,39 +1,43 @@
-# General - How To - Recipes
+# General - How To - Recipes { #general-how-to-recipes }
Here are several pointers to other places in the docs, for general or frequent questions.
-## Filter Data - Security
+## Filter Data - Security { #filter-data-security }
-To ensure that you don't return more data than you should, read the docs for [Tutorial - Response Model - Return Type](../tutorial/response-model.md){.internal-link target=_blank}.
+To ensure that you don't return more data than you should, read the docs for [Tutorial - Response Model - Return Type](../tutorial/response-model.md).
-## Documentation Tags - OpenAPI
+## Optimize Response Performance - Response Model - Return Type { #optimize-response-performance-response-model-return-type }
-To add tags to your *path operations*, and group them in the docs UI, read the docs for [Tutorial - Path Operation Configurations - Tags](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank}.
+To optimize performance when returning JSON data, use a return type or response model, that way Pydantic will handle the serialization to JSON on the Rust side, without going through Python. Read more in the docs for [Tutorial - Response Model - Return Type](../tutorial/response-model.md).
-## Documentation Summary and Description - OpenAPI
+## Documentation Tags - OpenAPI { #documentation-tags-openapi }
-To add a summary and description to your *path operations*, and show them in the docs UI, read the docs for [Tutorial - Path Operation Configurations - Summary and Description](../tutorial/path-operation-configuration.md#summary-and-description){.internal-link target=_blank}.
+To add tags to your *path operations*, and group them in the docs UI, read the docs for [Tutorial - Path Operation Configurations - Tags](../tutorial/path-operation-configuration.md#tags).
-## Documentation Response description - OpenAPI
+## Documentation Summary and Description - OpenAPI { #documentation-summary-and-description-openapi }
-To define the description of the response, shown in the docs UI, read the docs for [Tutorial - Path Operation Configurations - Response description](../tutorial/path-operation-configuration.md#response-description){.internal-link target=_blank}.
+To add a summary and description to your *path operations*, and show them in the docs UI, read the docs for [Tutorial - Path Operation Configurations - Summary and Description](../tutorial/path-operation-configuration.md#summary-and-description).
-## Documentation Deprecate a *Path Operation* - OpenAPI
+## Documentation Response description - OpenAPI { #documentation-response-description-openapi }
-To deprecate a *path operation*, and show it in the docs UI, read the docs for [Tutorial - Path Operation Configurations - Deprecation](../tutorial/path-operation-configuration.md#deprecate-a-path-operation){.internal-link target=_blank}.
+To define the description of the response, shown in the docs UI, read the docs for [Tutorial - Path Operation Configurations - Response description](../tutorial/path-operation-configuration.md#response-description).
-## Convert any Data to JSON-compatible
+## Documentation Deprecate a *Path Operation* - OpenAPI { #documentation-deprecate-a-path-operation-openapi }
-To convert any data to JSON-compatible, read the docs for [Tutorial - JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank}.
+To deprecate a *path operation*, and show it in the docs UI, read the docs for [Tutorial - Path Operation Configurations - Deprecation](../tutorial/path-operation-configuration.md#deprecate-a-path-operation).
-## OpenAPI Metadata - Docs
+## Convert any Data to JSON-compatible { #convert-any-data-to-json-compatible }
-To add metadata to your OpenAPI schema, including a license, version, contact, etc, read the docs for [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md){.internal-link target=_blank}.
+To convert any data to JSON-compatible, read the docs for [Tutorial - JSON Compatible Encoder](../tutorial/encoder.md).
-## OpenAPI Custom URL
+## OpenAPI Metadata - Docs { #openapi-metadata-docs }
-To customize the OpenAPI URL (or remove it), read the docs for [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#openapi-url){.internal-link target=_blank}.
+To add metadata to your OpenAPI schema, including a license, version, contact, etc, read the docs for [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md).
-## OpenAPI Docs URLs
+## OpenAPI Custom URL { #openapi-custom-url }
-To update the URLs used for the automatically generated docs user interfaces, read the docs for [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#docs-urls){.internal-link target=_blank}.
+To customize the OpenAPI URL (or remove it), read the docs for [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#openapi-url).
+
+## OpenAPI Docs URLs { #openapi-docs-urls }
+
+To update the URLs used for the automatically generated docs user interfaces, read the docs for [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#docs-urls).
diff --git a/docs/en/docs/how-to/graphql.md b/docs/en/docs/how-to/graphql.md
index 154606406a6a0..2d93876f35ce2 100644
--- a/docs/en/docs/how-to/graphql.md
+++ b/docs/en/docs/how-to/graphql.md
@@ -1,56 +1,60 @@
-# GraphQL
+# GraphQL { #graphql }
As **FastAPI** is based on the **ASGI** standard, it's very easy to integrate any **GraphQL** library also compatible with ASGI.
You can combine normal FastAPI *path operations* with GraphQL on the same application.
-!!! tip
- **GraphQL** solves some very specific use cases.
+/// tip
- It has **advantages** and **disadvantages** when compared to common **web APIs**.
+**GraphQL** solves some very specific use cases.
- Make sure you evaluate if the **benefits** for your use case compensate the **drawbacks**. 🤓
+It has **advantages** and **disadvantages** when compared to common **web APIs**.
-## GraphQL Libraries
+Make sure you evaluate if the **benefits** for your use case compensate the **drawbacks**. 🤓
+
+///
+
+## GraphQL Libraries { #graphql-libraries }
Here are some of the **GraphQL** libraries that have **ASGI** support. You could use them with **FastAPI**:
-* Strawberry 🍓
- * With docs for FastAPI
-* Ariadne
- * With docs for Starlette (that also apply to FastAPI)
-* Tartiflette
- * With Tartiflette ASGI to provide ASGI integration
-* Graphene
- * With starlette-graphene3
+* [Strawberry](https://strawberry.rocks/) 🍓
+ * With [docs for FastAPI](https://strawberry.rocks/docs/integrations/fastapi)
+* [Ariadne](https://ariadnegraphql.org/)
+ * With [docs for FastAPI](https://ariadnegraphql.org/docs/fastapi-integration)
+* [Tartiflette](https://tartiflette.io/)
+ * With [Tartiflette ASGI](https://tartiflette.github.io/tartiflette-asgi/) to provide ASGI integration
+* [Graphene](https://graphene-python.org/)
+ * With [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3)
-## GraphQL with Strawberry
+## GraphQL with Strawberry { #graphql-with-strawberry }
-If you need or want to work with **GraphQL**, **Strawberry** is the **recommended** library as it has the design closest to **FastAPI's** design, it's all based on **type annotations**.
+If you need or want to work with **GraphQL**, [**Strawberry**](https://strawberry.rocks/) is the **recommended** library as it has the design closest to **FastAPI's** design, it's all based on **type annotations**.
Depending on your use case, you might prefer to use a different library, but if you asked me, I would probably suggest you try **Strawberry**.
Here's a small preview of how you could integrate Strawberry with FastAPI:
-```Python hl_lines="3 22 25-26"
-{!../../../docs_src/graphql/tutorial001.py!}
-```
+{* ../../docs_src/graphql_/tutorial001_py310.py hl[3,22,25] *}
+
+You can learn more about Strawberry in the [Strawberry documentation](https://strawberry.rocks/).
+
+And also the docs about [Strawberry with FastAPI](https://strawberry.rocks/docs/integrations/fastapi).
-You can learn more about Strawberry in the Strawberry documentation.
+## Older `GraphQLApp` from Starlette { #older-graphqlapp-from-starlette }
-And also the docs about Strawberry with FastAPI.
+Previous versions of Starlette included a `GraphQLApp` class to integrate with [Graphene](https://graphene-python.org/).
-## Older `GraphQLApp` from Starlette
+It was deprecated from Starlette, but if you have code that used it, you can easily **migrate** to [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3), that covers the same use case and has an **almost identical interface**.
-Previous versions of Starlette included a `GraphQLApp` class to integrate with Graphene.
+/// tip
-It was deprecated from Starlette, but if you have code that used it, you can easily **migrate** to starlette-graphene3, that covers the same use case and has an **almost identical interface**.
+If you need GraphQL, I still would recommend you check out [Strawberry](https://strawberry.rocks/), as it's based on type annotations instead of custom classes and types.
-!!! tip
- If you need GraphQL, I still would recommend you check out Strawberry, as it's based on type annotations instead of custom classes and types.
+///
-## Learn More
+## Learn More { #learn-more }
-You can learn more about **GraphQL** in the official GraphQL documentation.
+You can learn more about **GraphQL** in the [official GraphQL documentation](https://graphql.org/).
You can also read more about each those libraries described above in their links.
diff --git a/docs/en/docs/how-to/index.md b/docs/en/docs/how-to/index.md
index ec7fd38f8f277..3d3696671ccd5 100644
--- a/docs/en/docs/how-to/index.md
+++ b/docs/en/docs/how-to/index.md
@@ -1,4 +1,4 @@
-# How To - Recipes
+# How To - Recipes { #how-to-recipes }
Here you will see different recipes or "how to" guides for **several topics**.
@@ -6,6 +6,8 @@ Most of these ideas would be more or less **independent**, and in most cases you
If something seems interesting and useful to your project, go ahead and check it, but otherwise, you might probably just skip them.
-!!! tip
+/// tip
- If you want to **learn FastAPI** in a structured way (recommended), go and read the [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} chapter by chapter instead.
+If you want to **learn FastAPI** in a structured way (recommended), go and read the [Tutorial - User Guide](../tutorial/index.md) chapter by chapter instead.
+
+///
diff --git a/docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
new file mode 100644
index 0000000000000..99d3835c38f5c
--- /dev/null
+++ b/docs/en/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -0,0 +1,135 @@
+# Migrate from Pydantic v1 to Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 }
+
+If you have an old FastAPI app, you might be using Pydantic version 1.
+
+FastAPI version 0.100.0 had support for either Pydantic v1 or v2. It would use whichever you had installed.
+
+FastAPI version 0.119.0 introduced partial support for Pydantic v1 from inside of Pydantic v2 (as `pydantic.v1`), to facilitate the migration to v2.
+
+FastAPI 0.126.0 dropped support for Pydantic v1, while still supporting `pydantic.v1` for a little while.
+
+/// warning
+
+The Pydantic team stopped support for Pydantic v1 for the latest versions of Python, starting with **Python 3.14**.
+
+This includes `pydantic.v1`, which is no longer supported in Python 3.14 and above.
+
+If you want to use the latest features of Python, you will need to make sure you use Pydantic v2.
+
+///
+
+If you have an old FastAPI app with Pydantic v1, here I'll show you how to migrate it to Pydantic v2, and the **features in FastAPI 0.119.0** to help you with a gradual migration.
+
+## Official Guide { #official-guide }
+
+Pydantic has an official [Migration Guide](https://docs.pydantic.dev/latest/migration/) from v1 to v2.
+
+It also includes what has changed, how validations are now more correct and strict, possible caveats, etc.
+
+You can read it to understand better what has changed.
+
+## Tests { #tests }
+
+Make sure you have [tests](../tutorial/testing.md) for your app and you run them on continuous integration (CI).
+
+This way, you can do the upgrade and make sure everything is still working as expected.
+
+## `bump-pydantic` { #bump-pydantic }
+
+In many cases, when you use regular Pydantic models without customizations, you will be able to automate most of the process of migrating from Pydantic v1 to Pydantic v2.
+
+You can use [`bump-pydantic`](https://github.com/pydantic/bump-pydantic) from the same Pydantic team.
+
+This tool will help you to automatically change most of the code that needs to be changed.
+
+After this, you can run the tests and check if everything works. If it does, you are done. 😎
+
+## Pydantic v1 in v2 { #pydantic-v1-in-v2 }
+
+Pydantic v2 includes everything from Pydantic v1 as a submodule `pydantic.v1`. But this is no longer supported in versions above Python 3.13.
+
+This means that you can install the latest version of Pydantic v2 and import and use the old Pydantic v1 components from this submodule, as if you had the old Pydantic v1 installed.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}
+
+### FastAPI support for Pydantic v1 in v2 { #fastapi-support-for-pydantic-v1-in-v2 }
+
+Since FastAPI 0.119.0, there's also partial support for Pydantic v1 from inside of Pydantic v2, to facilitate the migration to v2.
+
+So, you could upgrade Pydantic to the latest version 2, and change the imports to use the `pydantic.v1` submodule, and in many cases it would just work.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py hl[2,5,15] *}
+
+/// warning
+
+Have in mind that as the Pydantic team no longer supports Pydantic v1 in recent versions of Python, starting from Python 3.14, using `pydantic.v1` is also not supported in Python 3.14 and above.
+
+///
+
+### Pydantic v1 and v2 on the same app { #pydantic-v1-and-v2-on-the-same-app }
+
+It's **not supported** by Pydantic to have a model of Pydantic v2 with its own fields defined as Pydantic v1 models or vice versa.
+
+```mermaid
+graph TB
+ subgraph "❌ Not Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+...but, you can have separated models using Pydantic v1 and v2 in the same app.
+
+```mermaid
+graph TB
+ subgraph "✅ Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+In some cases, it's even possible to have both Pydantic v1 and v2 models in the same **path operation** in your FastAPI app:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}
+
+In this example above, the input model is a Pydantic v1 model, and the output model (defined in `response_model=ItemV2`) is a Pydantic v2 model.
+
+### Pydantic v1 parameters { #pydantic-v1-parameters }
+
+If you need to use some of the FastAPI-specific tools for parameters like `Body`, `Query`, `Form`, etc. with Pydantic v1 models, you can import them from `fastapi.temp_pydantic_v1_params` while you finish the migration to Pydantic v2:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py hl[4,18] *}
+
+### Migrate in steps { #migrate-in-steps }
+
+/// tip
+
+First try with `bump-pydantic`, if your tests pass and that works, then you're done in one command. ✨
+
+///
+
+If `bump-pydantic` doesn't work for your use case, you can use the support for both Pydantic v1 and v2 models in the same app to do the migration to Pydantic v2 gradually.
+
+You could fist upgrade Pydantic to use the latest version 2, and change the imports to use `pydantic.v1` for all your models.
+
+Then, you can start migrating your models from Pydantic v1 to v2 in groups, in gradual steps. 🚶
diff --git a/docs/en/docs/how-to/nosql-databases-couchbase.md b/docs/en/docs/how-to/nosql-databases-couchbase.md
deleted file mode 100644
index ae6ad604baa94..0000000000000
--- a/docs/en/docs/how-to/nosql-databases-couchbase.md
+++ /dev/null
@@ -1,163 +0,0 @@
-# NoSQL (Distributed / Big Data) Databases with Couchbase
-
-!!! info
- These docs are about to be updated. 🎉
-
- The current version assumes Pydantic v1.
-
- The new docs will hopefully use Pydantic v2 and will use ODMantic with MongoDB.
-
-**FastAPI** can also be integrated with any NoSQL.
-
-Here we'll see an example using **Couchbase**, a document based NoSQL database.
-
-You can adapt it to any other NoSQL database like:
-
-* **MongoDB**
-* **Cassandra**
-* **CouchDB**
-* **ArangoDB**
-* **ElasticSearch**, etc.
-
-!!! tip
- There is an official project generator with **FastAPI** and **Couchbase**, all based on **Docker**, including a frontend and more tools: https://github.com/tiangolo/full-stack-fastapi-couchbase
-
-## Import Couchbase components
-
-For now, don't pay attention to the rest, only the imports:
-
-```Python hl_lines="3-5"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-## Define a constant to use as a "document type"
-
-We will use it later as a fixed field `type` in our documents.
-
-This is not required by Couchbase, but is a good practice that will help you afterwards.
-
-```Python hl_lines="9"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-## Add a function to get a `Bucket`
-
-In **Couchbase**, a bucket is a set of documents, that can be of different types.
-
-They are generally all related to the same application.
-
-The analogy in the relational database world would be a "database" (a specific database, not the database server).
-
-The analogy in **MongoDB** would be a "collection".
-
-In the code, a `Bucket` represents the main entrypoint of communication with the database.
-
-This utility function will:
-
-* Connect to a **Couchbase** cluster (that might be a single machine).
- * Set defaults for timeouts.
-* Authenticate in the cluster.
-* Get a `Bucket` instance.
- * Set defaults for timeouts.
-* Return it.
-
-```Python hl_lines="12-21"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-## Create Pydantic models
-
-As **Couchbase** "documents" are actually just "JSON objects", we can model them with Pydantic.
-
-### `User` model
-
-First, let's create a `User` model:
-
-```Python hl_lines="24-28"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-We will use this model in our *path operation function*, so, we don't include in it the `hashed_password`.
-
-### `UserInDB` model
-
-Now, let's create a `UserInDB` model.
-
-This will have the data that is actually stored in the database.
-
-We don't create it as a subclass of Pydantic's `BaseModel` but as a subclass of our own `User`, because it will have all the attributes in `User` plus a couple more:
-
-```Python hl_lines="31-33"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-!!! note
- Notice that we have a `hashed_password` and a `type` field that will be stored in the database.
-
- But it is not part of the general `User` model (the one we will return in the *path operation*).
-
-## Get the user
-
-Now create a function that will:
-
-* Take a username.
-* Generate a document ID from it.
-* Get the document with that ID.
-* Put the contents of the document in a `UserInDB` model.
-
-By creating a function that is only dedicated to getting your user from a `username` (or any other parameter) independent of your *path operation function*, you can more easily re-use it in multiple parts and also add unit tests for it:
-
-```Python hl_lines="36-42"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-### f-strings
-
-If you are not familiar with the `f"userprofile::{username}"`, it is a Python "f-string".
-
-Any variable that is put inside of `{}` in an f-string will be expanded / injected in the string.
-
-### `dict` unpacking
-
-If you are not familiar with the `UserInDB(**result.value)`, it is using `dict` "unpacking".
-
-It will take the `dict` at `result.value`, and take each of its keys and values and pass them as key-values to `UserInDB` as keyword arguments.
-
-So, if the `dict` contains:
-
-```Python
-{
- "username": "johndoe",
- "hashed_password": "some_hash",
-}
-```
-
-It will be passed to `UserInDB` as:
-
-```Python
-UserInDB(username="johndoe", hashed_password="some_hash")
-```
-
-## Create your **FastAPI** code
-
-### Create the `FastAPI` app
-
-```Python hl_lines="46"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-### Create the *path operation function*
-
-As our code is calling Couchbase and we are not using the experimental Python await support, we should declare our function with normal `def` instead of `async def`.
-
-Also, Couchbase recommends not using a single `Bucket` object in multiple "threads", so, we can just get the bucket directly and pass it to our utility functions:
-
-```Python hl_lines="49-53"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-## Recap
-
-You can integrate any third party NoSQL database, just using their standard packages.
-
-The same applies to any other external tool, system or API.
diff --git a/docs/en/docs/how-to/separate-openapi-schemas.md b/docs/en/docs/how-to/separate-openapi-schemas.md
index d38be3c592ccb..d790c600bba66 100644
--- a/docs/en/docs/how-to/separate-openapi-schemas.md
+++ b/docs/en/docs/how-to/separate-openapi-schemas.md
@@ -1,124 +1,26 @@
-# Separate OpenAPI Schemas for Input and Output or Not
+# Separate OpenAPI Schemas for Input and Output or Not { #separate-openapi-schemas-for-input-and-output-or-not }
-When using **Pydantic v2**, the generated OpenAPI is a bit more exact and **correct** than before. 😎
+Since **Pydantic v2** was released, the generated OpenAPI is a bit more exact and **correct** than before. 😎
In fact, in some cases, it will even have **two JSON Schemas** in OpenAPI for the same Pydantic model, for input and output, depending on if they have **default values**.
Let's see how that works and how to change it if you need to do that.
-## Pydantic Models for Input and Output
+## Pydantic Models for Input and Output { #pydantic-models-for-input-and-output }
Let's say you have a Pydantic model with default values, like this one:
-=== "Python 3.10+"
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *}
- ```Python hl_lines="7"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!}
-
- # Code below omitted 👇
- ```
-
-
-### Model for Output
+### Model for Output { #model-for-output }
But if you use the same model as an output, like here:
-=== "Python 3.10+"
-
- ```Python hl_lines="19"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="21"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!}
- ```
-
-=== "Python 3.7+"
-
- ```Python hl_lines="21"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!}
- ```
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py hl[19] *}
...then because `description` has a default value, if you **don't return anything** for that field, it will still have that **default value**.
-### Model for Output Response Data
+### Model for Output Response Data { #model-for-output-response-data }
If you interact with the docs and check the response, even though the code didn't add anything in one of the `description` fields, the JSON response contains the default value (`null`):
@@ -169,7 +55,7 @@ Because of that, the JSON Schema for a model can be different depending on if it
* for **input** the `description` will **not be required**
* for **output** it will be **required** (and possibly `None`, or in JSON terms, `null`)
-### Model for Output in Docs
+### Model for Output in Docs { #model-for-output-in-docs }
You can check the output model in the docs too, **both** `name` and `description` are marked as **required** with a **red asterisk**:
@@ -177,7 +63,7 @@ You can check the output model in the docs too, **both** `name` and `description
-### Model for Input and Output in Docs
+### Model for Input and Output in Docs { #model-for-input-and-output-in-docs }
And if you check all the available Schemas (JSON Schemas) in OpenAPI, you will see that there are two, one `Item-Input` and one `Item-Output`.
@@ -191,7 +77,7 @@ But for `Item-Output`, `description` is **required**, it has a red asterisk.
With this feature from **Pydantic v2**, your API documentation is more **precise**, and if you have autogenerated clients and SDKs, they will be more precise too, with a better **developer experience** and consistency. 🎉
-## Do not Separate Schemas
+## Do not Separate Schemas { #do-not-separate-schemas }
Now, there are some cases where you might want to have the **same schema for input and output**.
@@ -199,33 +85,18 @@ Probably the main use case for this is if you already have some autogenerated cl
In that case, you can disable this feature in **FastAPI**, with the parameter `separate_input_output_schemas=False`.
-!!! info
- Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓
-
-=== "Python 3.10+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!}
- ```
+/// info
-=== "Python 3.9+"
+Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓
- ```Python hl_lines="12"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!}
- ```
+///
-=== "Python 3.7+"
+{* ../../docs_src/separate_openapi_schemas/tutorial002_py310.py hl[10] *}
- ```Python hl_lines="12"
- {!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!}
- ```
-
-### Same Schema for Input and Output Models in Docs
+### Same Schema for Input and Output Models in Docs { #same-schema-for-input-and-output-models-in-docs }
And now there will be one single schema for input and output for the model, only `Item`, and it will have `description` as **not required**:
-**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀
+## **Typer**, the FastAPI of CLIs { #typer-the-fastapi-of-clis }
-## Requirements
+uvicorn main:app --reload...fastapi dev...email_validator - for email validation.
-* pydantic-settings - for settings management.
-* pydantic-extra-types - for extra types to be used with Pydantic.
+* [`email-validator`](https://github.com/JoshData/python-email-validator) - for email validation.
Used by Starlette:
-* httpx - Required if you want to use the `TestClient`.
-* jinja2 - Required if you want to use the default template configuration.
-* python-multipart - Required if you want to support form "parsing", with `request.form()`.
-* itsdangerous - Required for `SessionMiddleware` support.
-* pyyaml - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
-* ujson - Required if you want to use `UJSONResponse`.
+* [`httpx`](https://www.python-httpx.org) - Required if you want to use the `TestClient`.
+* [`jinja2`](https://jinja.palletsprojects.com) - Required if you want to use the default template configuration.
+* [`python-multipart`](https://github.com/Kludex/python-multipart) - Required if you want to support form "parsing", with `request.form()`.
+
+Used by FastAPI:
+
+* [`uvicorn`](https://www.uvicorn.dev) - for the server that loads and serves your application. This includes `uvicorn[standard]`, which includes some dependencies (e.g. `uvloop`) needed for high performance serving.
+* `fastapi-cli[standard]` - to provide the `fastapi` command.
+ * This includes `fastapi-cloud-cli`, which allows you to deploy your FastAPI application to [FastAPI Cloud](https://fastapicloud.com).
+
+### Without `standard` Dependencies { #without-standard-dependencies }
+
+If you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install "fastapi[standard]"`.
+
+### Without `fastapi-cloud-cli` { #without-fastapi-cloud-cli }
+
+If you want to install FastAPI with the standard dependencies but without the `fastapi-cloud-cli`, you can install with `pip install "fastapi[standard-no-fastapi-cloud-cli]"`.
+
+### Additional Optional Dependencies { #additional-optional-dependencies }
+
+There are some additional dependencies you might want to install.
+
+Additional optional Pydantic dependencies:
-Used by FastAPI / Starlette:
+* [`pydantic-settings`](https://docs.pydantic.dev/latest/usage/pydantic_settings/) - for settings management.
+* [`pydantic-extra-types`](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/) - for extra types to be used with Pydantic.
-* uvicorn - for the server that loads and serves your application.
-* orjson - Required if you want to use `ORJSONResponse`.
+Additional optional FastAPI dependencies:
-You can install all of these with `pip install "fastapi[all]"`.
+* [`orjson`](https://github.com/ijl/orjson) - Required if you want to use `ORJSONResponse`.
+* [`ujson`](https://github.com/esnme/ultrajson) - Required if you want to use `UJSONResponse`.
-## License
+## License { #license }
This project is licensed under the terms of the MIT license.
diff --git a/docs/en/docs/js/chat.js b/docs/en/docs/js/chat.js
deleted file mode 100644
index debdef4dad5d0..0000000000000
--- a/docs/en/docs/js/chat.js
+++ /dev/null
@@ -1,3 +0,0 @@
-((window.gitter = {}).chat = {}).options = {
- room: 'tiangolo/fastapi'
-};
diff --git a/docs/en/docs/js/custom.js b/docs/en/docs/js/custom.js
index 8e3be4c130704..311995d7cd98e 100644
--- a/docs/en/docs/js/custom.js
+++ b/docs/en/docs/js/custom.js
@@ -1,25 +1,3 @@
-const div = document.querySelector('.github-topic-projects')
-
-async function getDataBatch(page) {
- const response = await fetch(`https://api.github.com/search/repositories?q=topic:fastapi&per_page=100&page=${page}`, { headers: { Accept: 'application/vnd.github.mercy-preview+json' } })
- const data = await response.json()
- return data
-}
-
-async function getData() {
- let page = 1
- let data = []
- let dataBatch = await getDataBatch(page)
- data = data.concat(dataBatch.items)
- const totalCount = dataBatch.total_count
- while (data.length < totalCount) {
- page += 1
- dataBatch = await getDataBatch(page)
- data = data.concat(dataBatch.items)
- }
- return data
-}
-
function setupTermynal() {
document.querySelectorAll(".use-termynal").forEach(node => {
node.style.display = "block";
@@ -35,7 +13,7 @@ function setupTermynal() {
function createTermynals() {
document
- .querySelectorAll(`.${termynalActivateClass} .highlight`)
+ .querySelectorAll(`.${termynalActivateClass} .highlight code`)
.forEach(node => {
const text = node.textContent;
const lines = text.split("\n");
@@ -103,8 +81,14 @@ function setupTermynal() {
}
}
saveBuffer();
+ const inputCommands = useLines
+ .filter(line => line.type === "input")
+ .map(line => line.value)
+ .join("\n");
+ node.textContent = inputCommands;
const div = document.createElement("div");
- node.replaceWith(div);
+ node.style.display = "none";
+ node.after(div);
const termynal = new Termynal(div, {
lineData: useLines,
noInit: true,
@@ -147,7 +131,7 @@ async function showRandomAnnouncement(groupId, timeInterval) {
children = shuffle(children)
let index = 0
const announceRandom = () => {
- children.forEach((el, i) => {el.style.display = "none"});
+ children.forEach((el, i) => { el.style.display = "none" });
children[index].style.display = "block"
index = (index + 1) % children.length
}
@@ -157,24 +141,72 @@ async function showRandomAnnouncement(groupId, timeInterval) {
}
}
-async function main() {
- if (div) {
- data = await getData()
- div.innerHTML = '
-### Add types
+### Add types { #add-types }
Let's modify a single line from the previous version.
@@ -79,9 +78,7 @@ That's it.
Those are the "type hints":
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
That is not the same as declaring default values like would be with:
@@ -105,13 +102,11 @@ With that, you can scroll, seeing the options, until you find the one that "ring
-## More motivation
+## More motivation { #more-motivation }
Check this function, it already has type hints:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
Because the editor knows the types of the variables, you don't only get completion, you also get error checks:
@@ -119,17 +114,15 @@ Because the editor knows the types of the variables, you don't only get completi
Now you know that you have to fix it, convert `age` to a string with `str(age)`:
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
-## Declaring types
+## Declaring types { #declaring-types }
You just saw the main place to declare type hints. As function parameters.
This is also the main place you would use them with **FastAPI**.
-### Simple types
+### Simple types { #simple-types }
You can declare all the standard Python types, not only `str`.
@@ -140,76 +133,55 @@ You can use, for example:
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
-```
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
-### Generic types with type parameters
+### `typing` module { #typing-module }
-There are some data structures that can contain other values, like `dict`, `list`, `set` and `tuple`. And the internal values can have their own type too.
+For some additional use cases, you might need to import some things from the standard library `typing` module, for example when you want to declare that something has "any type", you can use `Any` from `typing`:
-These types that have internal types are called "**generic**" types. And it's possible to declare them, even with their internal types.
+```python
+from typing import Any
-To declare those types and the internal types, you can use the standard Python module `typing`. It exists specifically to support these type hints.
-#### Newer versions of Python
-
-The syntax using `typing` is **compatible** with all versions, from Python 3.6 to the latest ones, including Python 3.9, Python 3.10, etc.
+def some_function(data: Any):
+ print(data)
+```
-As Python advances, **newer versions** come with improved support for these type annotations and in many cases you won't even need to import and use the `typing` module to declare the type annotations.
+### Generic types { #generic-types }
-If you can choose a more recent version of Python for your project, you will be able to take advantage of that extra simplicity.
+Some types can take "type parameters" in square brackets, to define their internal types, for example a "list of strings" would be declared `list[str]`.
-In all the docs there are examples compatible with each version of Python (when there's a difference).
+These types that can take type parameters are called **Generic types** or **Generics**.
-For example "**Python 3.6+**" means it's compatible with Python 3.6 or above (including 3.7, 3.8, 3.9, 3.10, etc). And "**Python 3.9+**" means it's compatible with Python 3.9 or above (including 3.10, etc).
+You can use the same builtin types as generics (with square brackets and types inside):
-If you can use the **latest versions of Python**, use the examples for the latest version, those will have the **best and simplest syntax**, for example, "**Python 3.10+**".
+* `list`
+* `tuple`
+* `set`
+* `dict`
-#### List
+#### List { #list }
For example, let's define a variable to be a `list` of `str`.
-=== "Python 3.9+"
-
- Declare the variable, with the same colon (`:`) syntax.
-
- As the type, put `list`.
-
- As the list is a type that contains some internal types, you put them in square brackets:
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
+Declare the variable, with the same colon (`:`) syntax.
-=== "Python 3.6+"
+As the type, put `list`.
- From `typing`, import `List` (with a capital `L`):
+As the list is a type that contains some internal types, you put them in square brackets:
- ``` Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
- Declare the variable, with the same colon (`:`) syntax.
+/// info
- As the type, put the `List` that you imported from `typing`.
+Those internal types in the square brackets are called "type parameters".
- As the list is a type that contains some internal types, you put them in square brackets:
+In this case, `str` is the type parameter passed to `list`.
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
-
-!!! info
- Those internal types in the square brackets are called "type parameters".
-
- In this case, `str` is the type parameter passed to `List` (or `list` in Python 3.9 and above).
+///
That means: "the variable `items` is a `list`, and each of the items in this list is a `str`".
-!!! tip
- If you use Python 3.9 or above, you don't have to import `List` from `typing`, you can use the same regular `list` type instead.
-
By doing that, your editor can provide support even while processing items from the list:
@@ -220,28 +192,18 @@ Notice that the variable `item` is one of the elements in the list `items`.
And still, the editor knows it is a `str`, and provides support for that.
-#### Tuple and Set
+#### Tuple and Set { #tuple-and-set }
You would do the same to declare `tuple`s and `set`s:
-=== "Python 3.9+"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
This means:
* The variable `items_t` is a `tuple` with 3 items, an `int`, another `int`, and a `str`.
* The variable `items_s` is a `set`, and each of its items is of type `bytes`.
-#### Dict
+#### Dict { #dict }
To define a `dict`, you pass 2 type parameters, separated by commas.
@@ -249,17 +211,7 @@ The first type parameter is for the keys of the `dict`.
The second type parameter is for the values of the `dict`:
-=== "Python 3.9+"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
This means:
@@ -267,162 +219,45 @@ This means:
* The keys of this `dict` are of type `str` (let's say, the name of each item).
* The values of this `dict` are of type `float` (let's say, the price of each item).
-#### Union
+#### Union { #union }
You can declare that a variable can be any of **several types**, for example, an `int` or a `str`.
-In Python 3.6 and above (including Python 3.10) you can use the `Union` type from `typing` and put inside the square brackets the possible types to accept.
-
-In Python 3.10 there's also a **new syntax** where you can put the possible types separated by a vertical bar (`|`).
-
-=== "Python 3.10+"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
- ```
-
-In both cases this means that `item` could be an `int` or a `str`.
-
-#### Possibly `None`
-
-You can declare that a value could have a type, like `str`, but that it could also be `None`.
-
-In Python 3.6 and above (including Python 3.10) you can declare it by importing and using `Optional` from the `typing` module.
-
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
-```
-
-Using `Optional[str]` instead of just `str` will let the editor help you detecting errors where you could be assuming that a value is always a `str`, when it could actually be `None` too.
-
-`Optional[Something]` is actually a shortcut for `Union[Something, None]`, they are equivalent.
-
-This also means that in Python 3.10, you can use `Something | None`:
-
-=== "Python 3.10+"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
- ```
+To define it you use the vertical bar (`|`) to separate both types.
-=== "Python 3.6+ alternative"
+This is called a "union", because the variable can be anything in the union of those two sets of types.
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
-
-#### Using `Union` or `Optional`
-
-If you are using a Python version below 3.10, here's a tip from my very **subjective** point of view:
-
-* 🚨 Avoid using `Optional[SomeType]`
-* Instead ✨ **use `Union[SomeType, None]`** ✨.
-
-Both are equivalent and underneath they are the same, but I would recommend `Union` instead of `Optional` because the word "**optional**" would seem to imply that the value is optional, and it actually means "it can be `None`", even if it's not optional and is still required.
-
-I think `Union[SomeType, None]` is more explicit about what it means.
-
-It's just about the words and names. But those words can affect how you and your teammates think about the code.
-
-As an example, let's take this function:
-
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c.py!}
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
```
-The parameter `name` is defined as `Optional[str]`, but it is **not optional**, you cannot call the function without the parameter:
-
-```Python
-say_hi() # Oh, no, this throws an error! 😱
-```
+This means that `item` could be an `int` or a `str`.
-The `name` parameter is **still required** (not *optional*) because it doesn't have a default value. Still, `name` accepts `None` as the value:
+#### Possibly `None` { #possibly-none }
-```Python
-say_hi(name=None) # This works, None is valid 🎉
-```
+You can declare that a value could have a type, like `str`, but that it could also be `None`.
-The good news is, once you are on Python 3.10 you won't have to worry about that, as you will be able to simply use `|` to define unions of types:
+//// tab | Python 3.10+
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c_py310.py!}
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
```
-And then you won't have to worry about names like `Optional` and `Union`. 😎
-
-#### Generic types
-
-These types that take type parameters in square brackets are called **Generic types** or **Generics**, for example:
-
-=== "Python 3.10+"
-
- You can use the same builtin types as generics (with square brackets and types inside):
-
- * `list`
- * `tuple`
- * `set`
- * `dict`
-
- And the same as with Python 3.6, from the `typing` module:
-
- * `Union`
- * `Optional` (the same as with Python 3.6)
- * ...and others.
+////
- In Python 3.10, as an alternative to using the generics `Union` and `Optional`, you can use the vertical bar (`|`) to declare unions of types, that's a lot better and simpler.
+Using `str | None` instead of just `str` will let the editor help you detect errors where you could be assuming that a value is always a `str`, when it could actually be `None` too.
-=== "Python 3.9+"
-
- You can use the same builtin types as generics (with square brackets and types inside):
-
- * `list`
- * `tuple`
- * `set`
- * `dict`
-
- And the same as with Python 3.6, from the `typing` module:
-
- * `Union`
- * `Optional`
- * ...and others.
-
-=== "Python 3.6+"
-
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ...and others.
-
-### Classes as types
+### Classes as types { #classes-as-types }
You can also declare a class as the type of a variable.
Let's say you have a class `Person`, with a name:
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
Then you can declare a variable to be of type `Person`:
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
And then, again, you get all the editor support:
@@ -432,9 +267,9 @@ Notice that this means "`one_person` is an **instance** of the class `Person`".
It doesn't mean "`one_person` is the **class** called `Person`".
-## Pydantic models
+## Pydantic models { #pydantic-models }
-Pydantic is a Python library to perform data validation.
+[Pydantic](https://docs.pydantic.dev/) is a Python library to perform data validation.
You declare the "shape" of the data as classes with attributes.
@@ -446,55 +281,25 @@ And you get all the editor support with that resulting object.
An example from the official Pydantic docs:
-=== "Python 3.10+"
-
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
-
-=== "Python 3.9+"
+{* ../../docs_src/python_types/tutorial011_py310.py *}
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+/// info
-=== "Python 3.6+"
+To learn more about [Pydantic, check its docs](https://docs.pydantic.dev/).
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
-
-!!! info
- To learn more about Pydantic, check its docs.
+///
**FastAPI** is all based on Pydantic.
-You will see a lot more of all this in practice in the [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}.
-
-!!! tip
- Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required Optional fields.
-
-## Type Hints with Metadata Annotations
-
-Python also has a feature that allows putting **additional metadata** in these type hints using `Annotated`.
-
-=== "Python 3.9+"
-
- In Python 3.9, `Annotated` is part of the standard library, so you can import it from `typing`.
+You will see a lot more of all this in practice in the [Tutorial - User Guide](tutorial/index.md).
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013_py39.py!}
- ```
+## Type Hints with Metadata Annotations { #type-hints-with-metadata-annotations }
-=== "Python 3.6+"
+Python also has a feature that allows putting **additional metadata** in these type hints using `Annotated`.
- In versions below Python 3.9, you import `Annotated` from `typing_extensions`.
+You can import `Annotated` from `typing`.
- It will already be installed with **FastAPI**.
-
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013.py!}
- ```
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
Python itself doesn't do anything with this `Annotated`. And for editors and other tools, the type is still `str`.
@@ -506,12 +311,15 @@ For now, you just need to know that `Annotated` exists, and that it's standard P
Later you will see how **powerful** it can be.
-!!! tip
- The fact that this is **standard Python** means that you will still get the **best possible developer experience** in your editor, with the tools you use to analyze and refactor your code, etc. ✨
+/// tip
+
+The fact that this is **standard Python** means that you will still get the **best possible developer experience** in your editor, with the tools you use to analyze and refactor your code, etc. ✨
+
+And also that your code will be very compatible with many other Python tools and libraries. 🚀
- And also that your code will be very compatible with many other Python tools and libraries. 🚀
+///
-## Type hints in **FastAPI**
+## Type hints in **FastAPI** { #type-hints-in-fastapi }
**FastAPI** takes advantage of these type hints to do several things.
@@ -529,9 +337,12 @@ With **FastAPI** you declare parameters with type hints and you get:
* **Document** the API using OpenAPI:
* which is then used by the automatic interactive documentation user interfaces.
-This might all sound abstract. Don't worry. You'll see all this in action in the [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}.
+This might all sound abstract. Don't worry. You'll see all this in action in the [Tutorial - User Guide](tutorial/index.md).
The important thing is that by using standard Python types, in a single place (instead of adding more classes, decorators, etc), **FastAPI** will do a lot of the work for you.
-!!! info
- If you already went through all the tutorial and came back to see more about types, a good resource is the "cheat sheet" from `mypy`.
+/// info
+
+If you already went through all the tutorial and came back to see more about types, a good resource is [the "cheat sheet" from `mypy`](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html).
+
+///
diff --git a/docs/en/docs/reference/apirouter.md b/docs/en/docs/reference/apirouter.md
new file mode 100644
index 0000000000000..d77364e45e851
--- /dev/null
+++ b/docs/en/docs/reference/apirouter.md
@@ -0,0 +1,24 @@
+# `APIRouter` class
+
+Here's the reference information for the `APIRouter` class, with all its parameters, attributes and methods.
+
+You can import the `APIRouter` class directly from `fastapi`:
+
+```python
+from fastapi import APIRouter
+```
+
+::: fastapi.APIRouter
+ options:
+ members:
+ - websocket
+ - include_router
+ - get
+ - put
+ - post
+ - delete
+ - options
+ - head
+ - patch
+ - trace
+ - on_event
diff --git a/docs/en/docs/reference/background.md b/docs/en/docs/reference/background.md
new file mode 100644
index 0000000000000..f65619590ecee
--- /dev/null
+++ b/docs/en/docs/reference/background.md
@@ -0,0 +1,11 @@
+# Background Tasks - `BackgroundTasks`
+
+You can declare a parameter in a *path operation function* or dependency function with the type `BackgroundTasks`, and then you can use it to schedule the execution of background tasks after the response is sent.
+
+You can import it directly from `fastapi`:
+
+```python
+from fastapi import BackgroundTasks
+```
+
+::: fastapi.BackgroundTasks
diff --git a/docs/en/docs/reference/dependencies.md b/docs/en/docs/reference/dependencies.md
new file mode 100644
index 0000000000000..2959a21daebc1
--- /dev/null
+++ b/docs/en/docs/reference/dependencies.md
@@ -0,0 +1,29 @@
+# Dependencies - `Depends()` and `Security()`
+
+## `Depends()`
+
+Dependencies are handled mainly with the special function `Depends()` that takes a callable.
+
+Here is the reference for it and its parameters.
+
+You can import it directly from `fastapi`:
+
+```python
+from fastapi import Depends
+```
+
+::: fastapi.Depends
+
+## `Security()`
+
+For many scenarios, you can handle security (authorization, authentication, etc.) with dependencies, using `Depends()`.
+
+But when you want to also declare OAuth2 scopes, you can use `Security()` instead of `Depends()`.
+
+You can import `Security()` directly from `fastapi`:
+
+```python
+from fastapi import Security
+```
+
+::: fastapi.Security
diff --git a/docs/en/docs/reference/encoders.md b/docs/en/docs/reference/encoders.md
new file mode 100644
index 0000000000000..28df2e43a2786
--- /dev/null
+++ b/docs/en/docs/reference/encoders.md
@@ -0,0 +1,3 @@
+# Encoders - `jsonable_encoder`
+
+::: fastapi.encoders.jsonable_encoder
diff --git a/docs/en/docs/reference/exceptions.md b/docs/en/docs/reference/exceptions.md
new file mode 100644
index 0000000000000..1392d2a80e3cf
--- /dev/null
+++ b/docs/en/docs/reference/exceptions.md
@@ -0,0 +1,20 @@
+# Exceptions - `HTTPException` and `WebSocketException`
+
+These are the exceptions that you can raise to show errors to the client.
+
+When you raise an exception, as would happen with normal Python, the rest of the execution is aborted. This way you can raise these exceptions from anywhere in the code to abort a request and show the error to the client.
+
+You can use:
+
+* `HTTPException`
+* `WebSocketException`
+
+These exceptions can be imported directly from `fastapi`:
+
+```python
+from fastapi import HTTPException, WebSocketException
+```
+
+::: fastapi.HTTPException
+
+::: fastapi.WebSocketException
diff --git a/docs/en/docs/reference/fastapi.md b/docs/en/docs/reference/fastapi.md
new file mode 100644
index 0000000000000..d5367ff347f62
--- /dev/null
+++ b/docs/en/docs/reference/fastapi.md
@@ -0,0 +1,31 @@
+# `FastAPI` class
+
+Here's the reference information for the `FastAPI` class, with all its parameters, attributes and methods.
+
+You can import the `FastAPI` class directly from `fastapi`:
+
+```python
+from fastapi import FastAPI
+```
+
+::: fastapi.FastAPI
+ options:
+ members:
+ - openapi_version
+ - webhooks
+ - state
+ - dependency_overrides
+ - openapi
+ - websocket
+ - include_router
+ - get
+ - put
+ - post
+ - delete
+ - options
+ - head
+ - patch
+ - trace
+ - on_event
+ - middleware
+ - exception_handler
diff --git a/docs/en/docs/reference/httpconnection.md b/docs/en/docs/reference/httpconnection.md
new file mode 100644
index 0000000000000..b7b87871a80c9
--- /dev/null
+++ b/docs/en/docs/reference/httpconnection.md
@@ -0,0 +1,11 @@
+# `HTTPConnection` class
+
+When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`.
+
+You can import it from `fastapi.requests`:
+
+```python
+from fastapi.requests import HTTPConnection
+```
+
+::: fastapi.requests.HTTPConnection
diff --git a/docs/en/docs/reference/index.md b/docs/en/docs/reference/index.md
new file mode 100644
index 0000000000000..b6dfdd063b8cd
--- /dev/null
+++ b/docs/en/docs/reference/index.md
@@ -0,0 +1,7 @@
+# Reference
+
+Here's the reference or code API, the classes, functions, parameters, attributes, and
+all the FastAPI parts you can use in your applications.
+
+If you want to **learn FastAPI** you are much better off reading the
+[FastAPI Tutorial](https://fastapi.tiangolo.com/tutorial/).
diff --git a/docs/en/docs/reference/middleware.md b/docs/en/docs/reference/middleware.md
new file mode 100644
index 0000000000000..48ff85158dd0f
--- /dev/null
+++ b/docs/en/docs/reference/middleware.md
@@ -0,0 +1,37 @@
+# Middleware
+
+There are several middlewares available provided by Starlette directly.
+
+Read more about them in the [FastAPI docs for Middleware](https://fastapi.tiangolo.com/advanced/middleware/).
+
+::: fastapi.middleware.cors.CORSMiddleware
+
+It can be imported from `fastapi`:
+
+```python
+from fastapi.middleware.cors import CORSMiddleware
+```
+
+::: fastapi.middleware.gzip.GZipMiddleware
+
+It can be imported from `fastapi`:
+
+```python
+from fastapi.middleware.gzip import GZipMiddleware
+```
+
+::: fastapi.middleware.httpsredirect.HTTPSRedirectMiddleware
+
+It can be imported from `fastapi`:
+
+```python
+from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
+```
+
+::: fastapi.middleware.trustedhost.TrustedHostMiddleware
+
+It can be imported from `fastapi`:
+
+```python
+from fastapi.middleware.trustedhost import TrustedHostMiddleware
+```
diff --git a/docs/en/docs/reference/openapi/docs.md b/docs/en/docs/reference/openapi/docs.md
new file mode 100644
index 0000000000000..ab620833ec99a
--- /dev/null
+++ b/docs/en/docs/reference/openapi/docs.md
@@ -0,0 +1,11 @@
+# OpenAPI `docs`
+
+Utilities to handle OpenAPI automatic UI documentation, including Swagger UI (by default at `/docs`) and ReDoc (by default at `/redoc`).
+
+::: fastapi.openapi.docs.get_swagger_ui_html
+
+::: fastapi.openapi.docs.get_redoc_html
+
+::: fastapi.openapi.docs.get_swagger_ui_oauth2_redirect_html
+
+::: fastapi.openapi.docs.swagger_ui_default_parameters
diff --git a/docs/en/docs/reference/openapi/index.md b/docs/en/docs/reference/openapi/index.md
new file mode 100644
index 0000000000000..e2b313f1509a1
--- /dev/null
+++ b/docs/en/docs/reference/openapi/index.md
@@ -0,0 +1,5 @@
+# OpenAPI
+
+There are several utilities to handle OpenAPI.
+
+You normally don't need to use them unless you have a specific advanced use case that requires it.
diff --git a/docs/en/docs/reference/openapi/models.md b/docs/en/docs/reference/openapi/models.md
new file mode 100644
index 0000000000000..4a6b0770edca0
--- /dev/null
+++ b/docs/en/docs/reference/openapi/models.md
@@ -0,0 +1,5 @@
+# OpenAPI `models`
+
+OpenAPI Pydantic models used to generate and validate the generated OpenAPI.
+
+::: fastapi.openapi.models
diff --git a/docs/en/docs/reference/parameters.md b/docs/en/docs/reference/parameters.md
new file mode 100644
index 0000000000000..d304c013c7a4e
--- /dev/null
+++ b/docs/en/docs/reference/parameters.md
@@ -0,0 +1,35 @@
+# Request Parameters
+
+Here's the reference information for the request parameters.
+
+These are the special functions that you can put in *path operation function* parameters or dependency functions with `Annotated` to get data from the request.
+
+It includes:
+
+* `Query()`
+* `Path()`
+* `Body()`
+* `Cookie()`
+* `Header()`
+* `Form()`
+* `File()`
+
+You can import them all directly from `fastapi`:
+
+```python
+from fastapi import Body, Cookie, File, Form, Header, Path, Query
+```
+
+::: fastapi.Query
+
+::: fastapi.Path
+
+::: fastapi.Body
+
+::: fastapi.Cookie
+
+::: fastapi.Header
+
+::: fastapi.Form
+
+::: fastapi.File
diff --git a/docs/en/docs/reference/request.md b/docs/en/docs/reference/request.md
new file mode 100644
index 0000000000000..7994bf8a88e0a
--- /dev/null
+++ b/docs/en/docs/reference/request.md
@@ -0,0 +1,19 @@
+# `Request` class
+
+You can declare a parameter in a *path operation function* or dependency to be of type `Request` and then you can access the raw request object directly, without any validation, etc.
+
+Read more about it in the [FastAPI docs about using Request directly](https://fastapi.tiangolo.com/advanced/using-request-directly/)
+
+You can import it directly from `fastapi`:
+
+```python
+from fastapi import Request
+```
+
+/// tip
+
+When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`.
+
+///
+
+::: fastapi.Request
diff --git a/docs/en/docs/reference/response.md b/docs/en/docs/reference/response.md
new file mode 100644
index 0000000000000..c9085766c92c6
--- /dev/null
+++ b/docs/en/docs/reference/response.md
@@ -0,0 +1,15 @@
+# `Response` class
+
+You can declare a parameter in a *path operation function* or dependency to be of type `Response` and then you can set data for the response like headers or cookies.
+
+You can also use it directly to create an instance of it and return it from your *path operations*.
+
+Read more about it in the [FastAPI docs about returning a custom Response](https://fastapi.tiangolo.com/advanced/response-directly/#returning-a-custom-response)
+
+You can import it directly from `fastapi`:
+
+```python
+from fastapi import Response
+```
+
+::: fastapi.Response
diff --git a/docs/en/docs/reference/responses.md b/docs/en/docs/reference/responses.md
new file mode 100644
index 0000000000000..2df53e9701797
--- /dev/null
+++ b/docs/en/docs/reference/responses.md
@@ -0,0 +1,172 @@
+# Custom Response Classes - File, HTML, Redirect, Streaming, etc.
+
+There are several custom response classes you can use to create an instance and return them directly from your *path operations*.
+
+Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/).
+
+You can import them directly from `fastapi.responses`:
+
+```python
+from fastapi.responses import (
+ FileResponse,
+ HTMLResponse,
+ JSONResponse,
+ ORJSONResponse,
+ PlainTextResponse,
+ RedirectResponse,
+ Response,
+ StreamingResponse,
+ UJSONResponse,
+)
+```
+
+## FastAPI Responses
+
+There were a couple of custom FastAPI response classes that were intended to optimize JSON performance.
+
+However, they are now deprecated as you will now get better performance by using a [Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/).
+
+That way, Pydantic will serialize the data into JSON bytes on the Rust side, which will achieve better performance than these custom JSON responses.
+
+Read more about it in [Custom Response - HTML, Stream, File, others - `orjson` or Response Model](https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model).
+
+::: fastapi.responses.UJSONResponse
+ options:
+ members:
+ - charset
+ - status_code
+ - media_type
+ - body
+ - background
+ - raw_headers
+ - render
+ - init_headers
+ - headers
+ - set_cookie
+ - delete_cookie
+
+::: fastapi.responses.ORJSONResponse
+ options:
+ members:
+ - charset
+ - status_code
+ - media_type
+ - body
+ - background
+ - raw_headers
+ - render
+ - init_headers
+ - headers
+ - set_cookie
+ - delete_cookie
+
+## Starlette Responses
+
+You can read more about all of them in the [FastAPI docs for Custom Response](https://fastapi.tiangolo.com/advanced/custom-response/) and in the [Starlette docs about Responses](https://starlette.dev/responses/).
+
+::: fastapi.responses.FileResponse
+ options:
+ members:
+ - chunk_size
+ - charset
+ - status_code
+ - media_type
+ - body
+ - background
+ - raw_headers
+ - render
+ - init_headers
+ - headers
+ - set_cookie
+ - delete_cookie
+
+::: fastapi.responses.HTMLResponse
+ options:
+ members:
+ - charset
+ - status_code
+ - media_type
+ - body
+ - background
+ - raw_headers
+ - render
+ - init_headers
+ - headers
+ - set_cookie
+ - delete_cookie
+
+::: fastapi.responses.JSONResponse
+ options:
+ members:
+ - charset
+ - status_code
+ - media_type
+ - body
+ - background
+ - raw_headers
+ - render
+ - init_headers
+ - headers
+ - set_cookie
+ - delete_cookie
+
+::: fastapi.responses.PlainTextResponse
+ options:
+ members:
+ - charset
+ - status_code
+ - media_type
+ - body
+ - background
+ - raw_headers
+ - render
+ - init_headers
+ - headers
+ - set_cookie
+ - delete_cookie
+
+::: fastapi.responses.RedirectResponse
+ options:
+ members:
+ - charset
+ - status_code
+ - media_type
+ - body
+ - background
+ - raw_headers
+ - render
+ - init_headers
+ - headers
+ - set_cookie
+ - delete_cookie
+
+::: fastapi.responses.Response
+ options:
+ members:
+ - charset
+ - status_code
+ - media_type
+ - body
+ - background
+ - raw_headers
+ - render
+ - init_headers
+ - headers
+ - set_cookie
+ - delete_cookie
+
+::: fastapi.responses.StreamingResponse
+ options:
+ members:
+ - body_iterator
+ - charset
+ - status_code
+ - media_type
+ - body
+ - background
+ - raw_headers
+ - render
+ - init_headers
+ - headers
+ - set_cookie
+ - delete_cookie
diff --git a/docs/en/docs/reference/security/index.md b/docs/en/docs/reference/security/index.md
new file mode 100644
index 0000000000000..8163aa2df2821
--- /dev/null
+++ b/docs/en/docs/reference/security/index.md
@@ -0,0 +1,75 @@
+# Security Tools
+
+When you need to declare dependencies with OAuth2 scopes you use `Security()`.
+
+But you still need to define what is the dependable, the callable that you pass as a parameter to `Depends()` or `Security()`.
+
+There are multiple tools that you can use to create those dependables, and they get integrated into OpenAPI so they are shown in the automatic docs UI, they can be used by automatically generated clients and SDKs, etc.
+
+You can import them from `fastapi.security`:
+
+```python
+from fastapi.security import (
+ APIKeyCookie,
+ APIKeyHeader,
+ APIKeyQuery,
+ HTTPAuthorizationCredentials,
+ HTTPBasic,
+ HTTPBasicCredentials,
+ HTTPBearer,
+ HTTPDigest,
+ OAuth2,
+ OAuth2AuthorizationCodeBearer,
+ OAuth2PasswordBearer,
+ OAuth2PasswordRequestForm,
+ OAuth2PasswordRequestFormStrict,
+ OpenIdConnect,
+ SecurityScopes,
+)
+```
+
+Read more about them in the [FastAPI docs about Security](https://fastapi.tiangolo.com/tutorial/security/).
+
+## API Key Security Schemes
+
+::: fastapi.security.APIKeyCookie
+
+::: fastapi.security.APIKeyHeader
+
+::: fastapi.security.APIKeyQuery
+
+## HTTP Authentication Schemes
+
+::: fastapi.security.HTTPBasic
+
+::: fastapi.security.HTTPBearer
+
+::: fastapi.security.HTTPDigest
+
+## HTTP Credentials
+
+::: fastapi.security.HTTPAuthorizationCredentials
+
+::: fastapi.security.HTTPBasicCredentials
+
+## OAuth2 Authentication
+
+::: fastapi.security.OAuth2
+
+::: fastapi.security.OAuth2AuthorizationCodeBearer
+
+::: fastapi.security.OAuth2PasswordBearer
+
+## OAuth2 Password Form
+
+::: fastapi.security.OAuth2PasswordRequestForm
+
+::: fastapi.security.OAuth2PasswordRequestFormStrict
+
+## OAuth2 Security Scopes in Dependencies
+
+::: fastapi.security.SecurityScopes
+
+## OpenID Connect
+
+::: fastapi.security.OpenIdConnect
diff --git a/docs/en/docs/reference/staticfiles.md b/docs/en/docs/reference/staticfiles.md
new file mode 100644
index 0000000000000..2712310783c62
--- /dev/null
+++ b/docs/en/docs/reference/staticfiles.md
@@ -0,0 +1,13 @@
+# Static Files - `StaticFiles`
+
+You can use the `StaticFiles` class to serve static files, like JavaScript, CSS, images, etc.
+
+Read more about it in the [FastAPI docs for Static Files](https://fastapi.tiangolo.com/tutorial/static-files/).
+
+You can import it directly from `fastapi.staticfiles`:
+
+```python
+from fastapi.staticfiles import StaticFiles
+```
+
+::: fastapi.staticfiles.StaticFiles
diff --git a/docs/en/docs/reference/status.md b/docs/en/docs/reference/status.md
new file mode 100644
index 0000000000000..6e0e816d33711
--- /dev/null
+++ b/docs/en/docs/reference/status.md
@@ -0,0 +1,36 @@
+# Status Codes
+
+You can import the `status` module from `fastapi`:
+
+```python
+from fastapi import status
+```
+
+`status` is provided directly by Starlette.
+
+It contains a group of named constants (variables) with integer status codes.
+
+For example:
+
+* 200: `status.HTTP_200_OK`
+* 403: `status.HTTP_403_FORBIDDEN`
+* etc.
+
+It can be convenient to quickly access HTTP (and WebSocket) status codes in your app, using autocompletion for the name without having to remember the integer status codes by memory.
+
+Read more about it in the [FastAPI docs about Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
+
+## Example
+
+```python
+from fastapi import FastAPI, status
+
+app = FastAPI()
+
+
+@app.get("/items/", status_code=status.HTTP_418_IM_A_TEAPOT)
+def read_items():
+ return [{"name": "Plumbus"}, {"name": "Portal Gun"}]
+```
+
+::: fastapi.status
diff --git a/docs/en/docs/reference/templating.md b/docs/en/docs/reference/templating.md
new file mode 100644
index 0000000000000..eedfe44d54d70
--- /dev/null
+++ b/docs/en/docs/reference/templating.md
@@ -0,0 +1,13 @@
+# Templating - `Jinja2Templates`
+
+You can use the `Jinja2Templates` class to render Jinja templates.
+
+Read more about it in the [FastAPI docs for Templates](https://fastapi.tiangolo.com/advanced/templates/).
+
+You can import it directly from `fastapi.templating`:
+
+```python
+from fastapi.templating import Jinja2Templates
+```
+
+::: fastapi.templating.Jinja2Templates
diff --git a/docs/en/docs/reference/testclient.md b/docs/en/docs/reference/testclient.md
new file mode 100644
index 0000000000000..2966ed792ccf9
--- /dev/null
+++ b/docs/en/docs/reference/testclient.md
@@ -0,0 +1,13 @@
+# Test Client - `TestClient`
+
+You can use the `TestClient` class to test FastAPI applications without creating an actual HTTP and socket connection, just communicating directly with the FastAPI code.
+
+Read more about it in the [FastAPI docs for Testing](https://fastapi.tiangolo.com/tutorial/testing/).
+
+You can import it directly from `fastapi.testclient`:
+
+```python
+from fastapi.testclient import TestClient
+```
+
+::: fastapi.testclient.TestClient
diff --git a/docs/en/docs/reference/uploadfile.md b/docs/en/docs/reference/uploadfile.md
new file mode 100644
index 0000000000000..43a75373036c5
--- /dev/null
+++ b/docs/en/docs/reference/uploadfile.md
@@ -0,0 +1,22 @@
+# `UploadFile` class
+
+You can define *path operation function* parameters to be of the type `UploadFile` to receive files from the request.
+
+You can import it directly from `fastapi`:
+
+```python
+from fastapi import UploadFile
+```
+
+::: fastapi.UploadFile
+ options:
+ members:
+ - file
+ - filename
+ - size
+ - headers
+ - content_type
+ - read
+ - write
+ - seek
+ - close
diff --git a/docs/en/docs/reference/websockets.md b/docs/en/docs/reference/websockets.md
new file mode 100644
index 0000000000000..bd9f438be65fe
--- /dev/null
+++ b/docs/en/docs/reference/websockets.md
@@ -0,0 +1,73 @@
+# WebSockets
+
+When defining WebSockets, you normally declare a parameter of type `WebSocket` and with it you can read data from the client and send data to it.
+
+Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/)
+
+It is provided directly by Starlette, but you can import it from `fastapi`:
+
+```python
+from fastapi import WebSocket
+```
+
+/// tip
+
+When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes an `HTTPConnection` instead of a `Request` or a `WebSocket`.
+
+///
+
+::: fastapi.WebSocket
+ options:
+ members:
+ - scope
+ - app
+ - url
+ - base_url
+ - headers
+ - query_params
+ - path_params
+ - cookies
+ - client
+ - state
+ - url_for
+ - client_state
+ - application_state
+ - receive
+ - send
+ - accept
+ - receive_text
+ - receive_bytes
+ - receive_json
+ - iter_text
+ - iter_bytes
+ - iter_json
+ - send_text
+ - send_bytes
+ - send_json
+ - close
+
+## WebSockets - additional classes
+
+Additional classes for handling WebSockets.
+
+Provided directly by Starlette, but you can import it from `fastapi`:
+
+```python
+from fastapi.websockets import WebSocketDisconnect, WebSocketState
+```
+
+::: fastapi.websockets.WebSocketDisconnect
+
+When a client disconnects, a `WebSocketDisconnect` exception is raised, you can catch it.
+
+You can import it directly form `fastapi`:
+
+```python
+from fastapi import WebSocketDisconnect
+```
+
+Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/#handling-disconnections-and-multiple-clients)
+
+::: fastapi.websockets.WebSocketState
+
+`WebSocketState` is an enumeration of the possible states of a WebSocket connection.
diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md
index 87476fd1e8f1f..ffff30400e0f1 100644
--- a/docs/en/docs/release-notes.md
+++ b/docs/en/docs/release-notes.md
@@ -1,9 +1,3453 @@
+---
+hide:
+ - navigation
+---
+
# Release Notes
## Latest Changes
-* 👥 Update FastAPI People. PR [#10363](https://github.com/tiangolo/fastapi/pull/10363) by [@tiangolo](https://github.com/tiangolo).
-## 0.103.2
+### Internal
+
+* ⬆ Bump pydantic-ai from 1.63.0 to 1.83.0. PR [#15417](https://github.com/fastapi/fastapi/pull/15417) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump prek from 0.3.2 to 0.3.9. PR [#15418](https://github.com/fastapi/fastapi/pull/15418) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump fastar from 0.9.0 to 0.11.0. PR [#15419](https://github.com/fastapi/fastapi/pull/15419) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump astral-sh/setup-uv from 7.6.0 to 8.1.0. PR [#15415](https://github.com/fastapi/fastapi/pull/15415) by [@dependabot[bot]](https://github.com/apps/dependabot).
+
+## 0.136.1 (2026-04-23)
+
+### Upgrades
+
+* ⬆️ Update Pydantic v2 code to address deprecations. PR [#15101](https://github.com/fastapi/fastapi/pull/15101) by [@svlandeg](https://github.com/svlandeg).
+
+### Internal
+
+* 🔨 Tweak translation script. PR [#15174](https://github.com/fastapi/fastapi/pull/15174) by [@YuriiMotov](https://github.com/YuriiMotov).
+* ⬆ Bump mkdocs-material from 9.7.1 to 9.7.6. PR [#15408](https://github.com/fastapi/fastapi/pull/15408) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump inline-snapshot from 0.31.1 to 0.32.6. PR [#15409](https://github.com/fastapi/fastapi/pull/15409) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pytest-codspeed from 4.3.0 to 4.4.0. PR [#15407](https://github.com/fastapi/fastapi/pull/15407) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pytest-cov from 7.0.0 to 7.1.0. PR [#15406](https://github.com/fastapi/fastapi/pull/15406) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump cloudflare/wrangler-action from 3.14.1 to 3.15.0. PR [#15405](https://github.com/fastapi/fastapi/pull/15405) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump mypy from 1.19.1 to 1.20.1. PR [#15410](https://github.com/fastapi/fastapi/pull/15410) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump python-dotenv from 1.2.1 to 1.2.2. PR [#15400](https://github.com/fastapi/fastapi/pull/15400) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump starlette from 0.52.1 to 1.0.0. PR [#15397](https://github.com/fastapi/fastapi/pull/15397) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pygithub from 2.8.1 to 2.9.1. PR [#15396](https://github.com/fastapi/fastapi/pull/15396) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pyjwt from 2.12.0 to 2.12.1. PR [#15393](https://github.com/fastapi/fastapi/pull/15393) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump zizmor from 1.23.1 to 1.24.1. PR [#15394](https://github.com/fastapi/fastapi/pull/15394) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump strawberry-graphql from 0.312.3 to 0.314.3. PR [#15395](https://github.com/fastapi/fastapi/pull/15395) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump python-multipart from 0.0.22 to 0.0.26. PR [#15360](https://github.com/fastapi/fastapi/pull/15360) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump authlib from 1.6.9 to 1.6.11. PR [#15373](https://github.com/fastapi/fastapi/pull/15373) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump aiohttp from 3.13.3 to 3.13.4. PR [#15282](https://github.com/fastapi/fastapi/pull/15282) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pygments from 2.19.2 to 2.20.0. PR [#15263](https://github.com/fastapi/fastapi/pull/15263) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pymdown-extensions from 10.20.1 to 10.21.2. PR [#15391](https://github.com/fastapi/fastapi/pull/15391) by [@YuriiMotov](https://github.com/YuriiMotov).
+* ⬆ Bump pillow from 12.1.1 to 12.2.0. PR [#15333](https://github.com/fastapi/fastapi/pull/15333) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pytest from 9.0.2 to 9.0.3. PR [#15334](https://github.com/fastapi/fastapi/pull/15334) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump actions/upload-artifact from 7.0.0 to 7.0.1. PR [#15374](https://github.com/fastapi/fastapi/pull/15374) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump actions/cache from 5.0.4 to 5.0.5. PR [#15385](https://github.com/fastapi/fastapi/pull/15385) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔧 Update sponsors: remove Zuplo. PR [#15369](https://github.com/fastapi/fastapi/pull/15369) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors: remove Speakeasy. PR [#15368](https://github.com/fastapi/fastapi/pull/15368) by [@tiangolo](https://github.com/tiangolo).
+* 🔒️ Add zizmor and fix audit findings. PR [#15316](https://github.com/fastapi/fastapi/pull/15316) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+## 0.136.0 (2026-04-16)
+
+### Upgrades
+
+* ⬆️ Support free-threaded Python 3.14t. PR [#15149](https://github.com/fastapi/fastapi/pull/15149) by [@svlandeg](https://github.com/svlandeg).
+
+## 0.135.4 (2026-04-16)
+
+### Refactors
+
+* 🔥 Remove April Fool's `@app.vibe()` 🤪. PR [#15363](https://github.com/fastapi/fastapi/pull/15363) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* ⬆ Bump cryptography from 46.0.5 to 46.0.7. PR [#15314](https://github.com/fastapi/fastapi/pull/15314) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump strawberry-graphql from 0.307.1 to 0.312.3. PR [#15309](https://github.com/fastapi/fastapi/pull/15309) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔨 Add pre-commit hook to ensure latest release header has date. PR [#15293](https://github.com/fastapi/fastapi/pull/15293) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+## 0.135.3 (2026-04-01)
+
+### Features
+
+* ✨ Add support for `@app.vibe()`. PR [#15280](https://github.com/fastapi/fastapi/pull/15280) by [@tiangolo](https://github.com/tiangolo).
+ * New docs: [Vibe Coding](https://fastapi.tiangolo.com/advanced/vibe/).
+
+### Docs
+
+* ✏️ Fix typo for `client_secret` in OAuth2 form docstrings. PR [#14946](https://github.com/fastapi/fastapi/pull/14946) by [@bysiber](https://github.com/bysiber).
+
+### Internal
+
+* 👥 Update FastAPI People - Experts. PR [#15279](https://github.com/fastapi/fastapi/pull/15279) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump orjson from 3.11.7 to 3.11.8. PR [#15276](https://github.com/fastapi/fastapi/pull/15276) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump ruff from 0.15.0 to 0.15.8. PR [#15277](https://github.com/fastapi/fastapi/pull/15277) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👥 Update FastAPI GitHub topic repositories. PR [#15274](https://github.com/fastapi/fastapi/pull/15274) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump fastmcp from 2.14.5 to 3.2.0. PR [#15267](https://github.com/fastapi/fastapi/pull/15267) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👥 Update FastAPI People - Contributors and Translators. PR [#15270](https://github.com/fastapi/fastapi/pull/15270) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump requests from 2.32.5 to 2.33.0. PR [#15228](https://github.com/fastapi/fastapi/pull/15228) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👷 Add ty check to `lint.sh`. PR [#15136](https://github.com/fastapi/fastapi/pull/15136) by [@svlandeg](https://github.com/svlandeg).
+
+## 0.135.2 (2026-03-01)
+
+### Upgrades
+
+* ⬆️ Increase lower bound to `pydantic >=2.9.0.` and fix the test suite. PR [#15139](https://github.com/fastapi/fastapi/pull/15139) by [@svlandeg](https://github.com/svlandeg).
+
+### Docs
+
+* 📝 Add missing last release notes dates. PR [#15202](https://github.com/fastapi/fastapi/pull/15202) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update docs for contributors and team members regarding translation PRs. PR [#15200](https://github.com/fastapi/fastapi/pull/15200) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 💄 Fix code blocks in reference docs overflowing table width. PR [#15094](https://github.com/fastapi/fastapi/pull/15094) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 📝 Fix duplicated words in docstrings. PR [#15116](https://github.com/fastapi/fastapi/pull/15116) by [@AhsanSheraz](https://github.com/AhsanSheraz).
+* 📝 Add docs for `pyproject.toml` with `entrypoint`. PR [#15075](https://github.com/fastapi/fastapi/pull/15075) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update links in docs to no longer use the classes external-link and internal-link. PR [#15061](https://github.com/fastapi/fastapi/pull/15061) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Add JS and CSS handling for automatic `target=_blank` for links in docs. PR [#15063](https://github.com/fastapi/fastapi/pull/15063) by [@tiangolo](https://github.com/tiangolo).
+* 💄 Update styles for internal and external links in new tab. PR [#15058](https://github.com/fastapi/fastapi/pull/15058) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Add documentation for the FastAPI VS Code extension. PR [#15008](https://github.com/fastapi/fastapi/pull/15008) by [@savannahostrowski](https://github.com/savannahostrowski).
+* 📝 Fix doctrings for `max_digits` and `decimal_places`. PR [#14944](https://github.com/fastapi/fastapi/pull/14944) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 📝 Add dates to release notes. PR [#15001](https://github.com/fastapi/fastapi/pull/15001) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+### Translations
+
+* 🌐 Update translations for zh (update-outdated). PR [#15177](https://github.com/fastapi/fastapi/pull/15177) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for zh-hant (update-outdated). PR [#15178](https://github.com/fastapi/fastapi/pull/15178) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for zh-hant (add-missing). PR [#15176](https://github.com/fastapi/fastapi/pull/15176) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for zh (add-missing). PR [#15175](https://github.com/fastapi/fastapi/pull/15175) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for ja (update-outdated). PR [#15171](https://github.com/fastapi/fastapi/pull/15171) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for ko (update-outdated). PR [#15170](https://github.com/fastapi/fastapi/pull/15170) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for tr (update-outdated). PR [#15172](https://github.com/fastapi/fastapi/pull/15172) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for ko (add-missing). PR [#15168](https://github.com/fastapi/fastapi/pull/15168) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for ja (add-missing). PR [#15167](https://github.com/fastapi/fastapi/pull/15167) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for tr (add-missing). PR [#15169](https://github.com/fastapi/fastapi/pull/15169) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for fr (update-outdated). PR [#15165](https://github.com/fastapi/fastapi/pull/15165) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for fr (add-missing). PR [#15163](https://github.com/fastapi/fastapi/pull/15163) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for uk (update-outdated). PR [#15160](https://github.com/fastapi/fastapi/pull/15160) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for uk (add-missing). PR [#15158](https://github.com/fastapi/fastapi/pull/15158) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for pt (add-missing). PR [#15157](https://github.com/fastapi/fastapi/pull/15157) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for pt (update-outdated). PR [#15159](https://github.com/fastapi/fastapi/pull/15159) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for es (update-outdated). PR [#15155](https://github.com/fastapi/fastapi/pull/15155) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for es (add-missing). PR [#15154](https://github.com/fastapi/fastapi/pull/15154) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for de (update-outdated). PR [#15156](https://github.com/fastapi/fastapi/pull/15156) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for ru (update-and-add). PR [#15152](https://github.com/fastapi/fastapi/pull/15152) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for de (add-missing). PR [#15153](https://github.com/fastapi/fastapi/pull/15153) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* 🔨 Exclude spam comments from statistics in `scripts/people.py`. PR [#15088](https://github.com/fastapi/fastapi/pull/15088) by [@YuriiMotov](https://github.com/YuriiMotov).
+* ⬆ Bump authlib from 1.6.7 to 1.6.9. PR [#15128](https://github.com/fastapi/fastapi/pull/15128) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pyasn1 from 0.6.2 to 0.6.3. PR [#15143](https://github.com/fastapi/fastapi/pull/15143) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump ujson from 5.11.0 to 5.12.0. PR [#15150](https://github.com/fastapi/fastapi/pull/15150) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔨 Tweak translation workflow and translation fixer tool. PR [#15166](https://github.com/fastapi/fastapi/pull/15166) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🔨 Fix `commit_in_place` passed via env variable in `translate.yml` workflow. PR [#15151](https://github.com/fastapi/fastapi/pull/15151) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🔨 Update translation general prompt to enforce link style in translation matches the original link style. PR [#15148](https://github.com/fastapi/fastapi/pull/15148) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 👷 Re-enable translation workflow run by cron in CI (twice a month). PR [#15145](https://github.com/fastapi/fastapi/pull/15145) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 👷 Add `ty` to precommit. PR [#15091](https://github.com/fastapi/fastapi/pull/15091) by [@svlandeg](https://github.com/svlandeg).
+* ⬆ Bump dorny/paths-filter from 3 to 4. PR [#15106](https://github.com/fastapi/fastapi/pull/15106) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump cairosvg from 2.8.2 to 2.9.0. PR [#15108](https://github.com/fastapi/fastapi/pull/15108) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pyjwt from 2.11.0 to 2.12.0. PR [#15110](https://github.com/fastapi/fastapi/pull/15110) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump black from 26.1.0 to 26.3.1. PR [#15100](https://github.com/fastapi/fastapi/pull/15100) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔨 Update script to autofix permalinks to account for headers with Markdown links. PR [#15062](https://github.com/fastapi/fastapi/pull/15062) by [@tiangolo](https://github.com/tiangolo).
+* 📌 Pin Click for MkDocs live reload. PR [#15057](https://github.com/fastapi/fastapi/pull/15057) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump werkzeug from 3.1.5 to 3.1.6. PR [#14948](https://github.com/fastapi/fastapi/pull/14948) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pydantic-ai from 1.62.0 to 1.63.0. PR [#15035](https://github.com/fastapi/fastapi/pull/15035) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pytest-codspeed from 4.2.0 to 4.3.0. PR [#15034](https://github.com/fastapi/fastapi/pull/15034) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump strawberry-graphql from 0.291.2 to 0.307.1. PR [#15033](https://github.com/fastapi/fastapi/pull/15033) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump typer from 0.21.1 to 0.24.1. PR [#15032](https://github.com/fastapi/fastapi/pull/15032) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump actions/download-artifact from 7 to 8. PR [#15020](https://github.com/fastapi/fastapi/pull/15020) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump actions/upload-artifact from 6 to 7. PR [#15019](https://github.com/fastapi/fastapi/pull/15019) by [@dependabot[bot]](https://github.com/apps/dependabot).
+
+## 0.135.1 (2026-03-01)
+
+### Fixes
+
+* 🐛 Fix, avoid yield from a TaskGroup, only as an async context manager, closed in the request async exit stack. PR [#15038](https://github.com/fastapi/fastapi/pull/15038) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* ✏️ Fix typo in `docs/en/docs/_llm-test.md`. PR [#15007](https://github.com/fastapi/fastapi/pull/15007) by [@adityagiri3600](https://github.com/adityagiri3600).
+* 📝 Update Skill, optimize context, trim and refactor into references. PR [#15031](https://github.com/fastapi/fastapi/pull/15031) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* 👥 Update FastAPI People - Experts. PR [#15037](https://github.com/fastapi/fastapi/pull/15037) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Contributors and Translators. PR [#15029](https://github.com/fastapi/fastapi/pull/15029) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI GitHub topic repositories. PR [#15036](https://github.com/fastapi/fastapi/pull/15036) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.135.0 (2026-03-01)
+
+### Features
+
+* ✨ Add support for Server Sent Events. PR [#15030](https://github.com/fastapi/fastapi/pull/15030) by [@tiangolo](https://github.com/tiangolo).
+ * New docs: [Server-Sent Events (SSE)](https://fastapi.tiangolo.com/tutorial/server-sent-events/).
+
+## 0.134.0 (2026-02-27)
+
+### Features
+
+* ✨ Add support for streaming JSON Lines and binary data with `yield`. PR [#15022](https://github.com/fastapi/fastapi/pull/15022) by [@tiangolo](https://github.com/tiangolo).
+ * This also upgrades Starlette from `>=0.40.0` to `>=0.46.0`, as it's needed to properly unrwap and re-raise exceptions from exception groups.
+ * New docs: [Stream JSON Lines](https://fastapi.tiangolo.com/tutorial/stream-json-lines/).
+ * And new docs: [Stream Data](https://fastapi.tiangolo.com/advanced/stream-data/).
+
+### Docs
+
+* 📝 Update Library Agent Skill with streaming responses. PR [#15024](https://github.com/fastapi/fastapi/pull/15024) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update docs for responses and new stream with `yield`. PR [#15023](https://github.com/fastapi/fastapi/pull/15023) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Add `await` in `StreamingResponse` code example to allow cancellation. PR [#14681](https://github.com/fastapi/fastapi/pull/14681) by [@casperdcl](https://github.com/casperdcl).
+* 📝 Rename `docs_src/websockets` to `docs_src/websockets_` to avoid import errors. PR [#14979](https://github.com/fastapi/fastapi/pull/14979) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+### Internal
+
+* 🔨 Run tests with `pytest-xdist` and `pytest-cov`. PR [#14992](https://github.com/fastapi/fastapi/pull/14992) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+## 0.133.1 (2026-02-25)
+
+### Features
+
+* 🔧 Add FastAPI Agents Skill. PR [#14982](https://github.com/fastapi/fastapi/pull/14982) by [@tiangolo](https://github.com/tiangolo).
+ * Read more about it in [Library Agent Skills](https://tiangolo.com/ideas/library-agent-skills/).
+
+### Internal
+
+* ✅ Fix all tests are skipped on Windows. PR [#14994](https://github.com/fastapi/fastapi/pull/14994) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+## 0.133.0 (2026-02-24)
+
+### Upgrades
+
+* ⬆️ Add support for Starlette 1.0.0+. PR [#14987](https://github.com/fastapi/fastapi/pull/14987) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.132.1 (2026-02-24)
+
+### Refactors
+
+* ♻️ Refactor logic to handle OpenAPI and Swagger UI escaping data. PR [#14986](https://github.com/fastapi/fastapi/pull/14986) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* 👥 Update FastAPI People - Experts. PR [#14972](https://github.com/fastapi/fastapi/pull/14972) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Allow skipping `benchmark` job in `test` workflow. PR [#14974](https://github.com/fastapi/fastapi/pull/14974) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+## 0.132.0 (2026-02-23)
+
+### Breaking Changes
+
+* 🔒️ Add `strict_content_type` checking for JSON requests. PR [#14978](https://github.com/fastapi/fastapi/pull/14978) by [@tiangolo](https://github.com/tiangolo).
+ * Now FastAPI checks, by default, that JSON requests have a `Content-Type` header with a valid JSON value, like `application/json`, and rejects requests that don't.
+ * If the clients for your app don't send a valid `Content-Type` header you can disable this with `strict_content_type=False`.
+ * Check the new docs: [Strict Content-Type Checking](https://fastapi.tiangolo.com/advanced/strict-content-type/).
+
+### Internal
+
+* ⬆ Bump flask from 3.1.2 to 3.1.3. PR [#14949](https://github.com/fastapi/fastapi/pull/14949) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Update all dependencies to use `griffelib` instead of `griffe`. PR [#14973](https://github.com/fastapi/fastapi/pull/14973) by [@svlandeg](https://github.com/svlandeg).
+* 🔨 Fix `FastAPI People` workflow. PR [#14951](https://github.com/fastapi/fastapi/pull/14951) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 👷 Do not run codspeed with coverage as it's not tracked. PR [#14966](https://github.com/fastapi/fastapi/pull/14966) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Do not include benchmark tests in coverage to speed up coverage processing. PR [#14965](https://github.com/fastapi/fastapi/pull/14965) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.131.0 (2026-02-22)
+
+### Breaking Changes
+
+* 🗑️ Deprecate `ORJSONResponse` and `UJSONResponse`. PR [#14964](https://github.com/fastapi/fastapi/pull/14964) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.130.0 (2026-02-22)
+
+### Features
+
+* ✨ Serialize JSON response with Pydantic (in Rust), when there's a Pydantic return type or response model. PR [#14962](https://github.com/fastapi/fastapi/pull/14962) by [@tiangolo](https://github.com/tiangolo).
+ * This results in 2x (or more) performance increase for JSON responses.
+ * New docs: [Custom Response - JSON Performance](https://fastapi.tiangolo.com/advanced/custom-response/#json-performance).
+
+## 0.129.2 (2026-02-21)
+
+### Internal
+
+* ⬆️ Upgrade pytest. PR [#14959](https://github.com/fastapi/fastapi/pull/14959) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Fix CI, do not attempt to publish `fastapi-slim`. PR [#14958](https://github.com/fastapi/fastapi/pull/14958) by [@tiangolo](https://github.com/tiangolo).
+* ➖ Drop support for `fastapi-slim`, no more versions will be released, use only `"fastapi[standard]"` or `fastapi`. PR [#14957](https://github.com/fastapi/fastapi/pull/14957) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update pyproject.toml, remove unneeded lines. PR [#14956](https://github.com/fastapi/fastapi/pull/14956) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.129.1 (2026-02-21)
+
+### Fixes
+
+* ♻️ Fix JSON Schema for bytes, use `"contentMediaType": "application/octet-stream"` instead of `"format": "binary"`. PR [#14953](https://github.com/fastapi/fastapi/pull/14953) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 🔨 Add Kapa.ai widget (AI chatbot). PR [#14938](https://github.com/fastapi/fastapi/pull/14938) by [@tiangolo](https://github.com/tiangolo).
+* 🔥 Remove Python 3.9 specific files, no longer needed after updating translations. PR [#14931](https://github.com/fastapi/fastapi/pull/14931) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update docs for JWT to prevent timing attacks. PR [#14908](https://github.com/fastapi/fastapi/pull/14908) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* ✏️ Fix several typos in ru translations. PR [#14934](https://github.com/fastapi/fastapi/pull/14934) by [@argoarsiks](https://github.com/argoarsiks).
+* 🌐 Update translations for ko (update-all and add-missing). PR [#14923](https://github.com/fastapi/fastapi/pull/14923) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Update translations for uk (add-missing). PR [#14922](https://github.com/fastapi/fastapi/pull/14922) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Update translations for zh-hant (update-all and add-missing). PR [#14921](https://github.com/fastapi/fastapi/pull/14921) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Update translations for fr (update-all and add-missing). PR [#14920](https://github.com/fastapi/fastapi/pull/14920) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Update translations for de (update-all) . PR [#14910](https://github.com/fastapi/fastapi/pull/14910) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Update translations for ja (update-all). PR [#14916](https://github.com/fastapi/fastapi/pull/14916) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Update translations for pt (update-all). PR [#14912](https://github.com/fastapi/fastapi/pull/14912) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Update translations for es (update-all and add-missing). PR [#14911](https://github.com/fastapi/fastapi/pull/14911) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Update translations for zh (update-all). PR [#14917](https://github.com/fastapi/fastapi/pull/14917) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Update translations for uk (update-all). PR [#14914](https://github.com/fastapi/fastapi/pull/14914) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Update translations for tr (update-all). PR [#14913](https://github.com/fastapi/fastapi/pull/14913) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Update translations for ru (update-outdated). PR [#14909](https://github.com/fastapi/fastapi/pull/14909) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+### Internal
+
+* 👷 Always run tests on push to `master` branch and when run by scheduler. PR [#14940](https://github.com/fastapi/fastapi/pull/14940) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🎨 Upgrade typing syntax for Python 3.10. PR [#14932](https://github.com/fastapi/fastapi/pull/14932) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump cryptography from 46.0.4 to 46.0.5. PR [#14892](https://github.com/fastapi/fastapi/pull/14892) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pillow from 12.1.0 to 12.1.1. PR [#14899](https://github.com/fastapi/fastapi/pull/14899) by [@dependabot[bot]](https://github.com/apps/dependabot).
+
+## 0.129.0 (2026-02-12)
+
+### Breaking Changes
+
+* ➖ Drop support for Python 3.9. PR [#14897](https://github.com/fastapi/fastapi/pull/14897) by [@tiangolo](https://github.com/tiangolo).
+
+### Refactors
+
+* 🎨 Update internal types for Python 3.10. PR [#14898](https://github.com/fastapi/fastapi/pull/14898) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Update highlights in webhooks docs. PR [#14905](https://github.com/fastapi/fastapi/pull/14905) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update source examples and docs from Python 3.9 to 3.10. PR [#14900](https://github.com/fastapi/fastapi/pull/14900) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* 🔨 Update docs.py scripts to migrate Python 3.9 to Python 3.10. PR [#14906](https://github.com/fastapi/fastapi/pull/14906) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.128.8 (2026-02-11)
+
+### Docs
+
+* 📝 Fix grammar in `docs/en/docs/tutorial/first-steps.md`. PR [#14708](https://github.com/fastapi/fastapi/pull/14708) by [@SanjanaS10](https://github.com/SanjanaS10).
+
+### Internal
+
+* 🔨 Tweak PDM hook script. PR [#14895](https://github.com/fastapi/fastapi/pull/14895) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Update build setup for `fastapi-slim`, deprecate it, and make it only depend on `fastapi`. PR [#14894](https://github.com/fastapi/fastapi/pull/14894) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.128.7 (2026-02-10)
+
+### Features
+
+* ✨ Show a clear error on attempt to include router into itself. PR [#14258](https://github.com/fastapi/fastapi/pull/14258) by [@JavierSanchezCastro](https://github.com/JavierSanchezCastro).
+* ✨ Replace `dict` by `Mapping` on `HTTPException.headers`. PR [#12997](https://github.com/fastapi/fastapi/pull/12997) by [@rijenkii](https://github.com/rijenkii).
+
+### Refactors
+
+* ♻️ Simplify reading files in memory, do it sequentially instead of (fake) parallel. PR [#14884](https://github.com/fastapi/fastapi/pull/14884) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Use `dfn` tag for definitions instead of `abbr` in docs. PR [#14744](https://github.com/fastapi/fastapi/pull/14744) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+### Internal
+
+* ✅ Tweak comment in test to reference PR. PR [#14885](https://github.com/fastapi/fastapi/pull/14885) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update LLM-prompt for `abbr` and `dfn` tags. PR [#14747](https://github.com/fastapi/fastapi/pull/14747) by [@YuriiMotov](https://github.com/YuriiMotov).
+* ✅ Test order for the submitted byte Files. PR [#14828](https://github.com/fastapi/fastapi/pull/14828) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🔧 Configure `test` workflow to run tests with `inline-snapshot=review`. PR [#14876](https://github.com/fastapi/fastapi/pull/14876) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+## 0.128.6 (2026-02-09)
+
+### Fixes
+
+* 🐛 Fix `on_startup` and `on_shutdown` parameters of `APIRouter`. PR [#14873](https://github.com/fastapi/fastapi/pull/14873) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+### Translations
+
+* 🌐 Update translations for zh (update-outdated). PR [#14843](https://github.com/fastapi/fastapi/pull/14843) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* ✅ Fix parameterized tests with snapshots. PR [#14875](https://github.com/fastapi/fastapi/pull/14875) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+## 0.128.5 (2026-02-08)
+
+### Refactors
+
+* ♻️ Refactor and simplify Pydantic v2 (and v1) compatibility internal utils. PR [#14862](https://github.com/fastapi/fastapi/pull/14862) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* ✅ Add inline snapshot tests for OpenAPI before changes from Pydantic v2. PR [#14864](https://github.com/fastapi/fastapi/pull/14864) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.128.4 (2026-02-07)
+
+### Refactors
+
+* ♻️ Refactor internals, simplify Pydantic v2/v1 utils, `create_model_field`, better types for `lenient_issubclass`. PR [#14860](https://github.com/fastapi/fastapi/pull/14860) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Simplify internals, remove Pydantic v1 only logic, no longer needed. PR [#14857](https://github.com/fastapi/fastapi/pull/14857) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Refactor internals, cleanup unneeded Pydantic v1 specific logic. PR [#14856](https://github.com/fastapi/fastapi/pull/14856) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Update translations for fr (outdated pages). PR [#14839](https://github.com/fastapi/fastapi/pull/14839) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Update translations for tr (outdated and missing). PR [#14838](https://github.com/fastapi/fastapi/pull/14838) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+### Internal
+
+* ⬆️ Upgrade development dependencies. PR [#14854](https://github.com/fastapi/fastapi/pull/14854) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.128.3 (2026-02-06)
+
+### Refactors
+
+* ♻️ Re-implement `on_event` in FastAPI for compatibility with the next Starlette, while keeping backwards compatibility. PR [#14851](https://github.com/fastapi/fastapi/pull/14851) by [@tiangolo](https://github.com/tiangolo).
+
+### Upgrades
+
+* ⬆️ Upgrade Starlette supported version range to `starlette>=0.40.0,<1.0.0`. PR [#14853](https://github.com/fastapi/fastapi/pull/14853) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Update translations for ru (update-outdated). PR [#14834](https://github.com/fastapi/fastapi/pull/14834) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* 👷 Run tests with Starlette from git. PR [#14849](https://github.com/fastapi/fastapi/pull/14849) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Run tests with lower bound uv sync, upgrade `fastapi[all]` minimum dependencies: `ujson >=5.8.0`, `orjson >=3.9.3`. PR [#14846](https://github.com/fastapi/fastapi/pull/14846) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.128.2 (2026-02-05)
+
+### Features
+
+* ✨ Add support for PEP695 `TypeAliasType`. PR [#13920](https://github.com/fastapi/fastapi/pull/13920) by [@cstruct](https://github.com/cstruct).
+* ✨ Allow `Response` type hint as dependency annotation. PR [#14794](https://github.com/fastapi/fastapi/pull/14794) by [@jonathan-fulton](https://github.com/jonathan-fulton).
+
+### Fixes
+
+* 🐛 Fix using `Json[list[str]]` type (issue #10997). PR [#14616](https://github.com/fastapi/fastapi/pull/14616) by [@mkanetsuna](https://github.com/mkanetsuna).
+
+### Docs
+
+* 📝 Update docs for translations. PR [#14830](https://github.com/fastapi/fastapi/pull/14830) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Fix duplicate word in `advanced-dependencies.md`. PR [#14815](https://github.com/fastapi/fastapi/pull/14815) by [@Rayyan-Oumlil](https://github.com/Rayyan-Oumlil).
+
+### Translations
+
+* 🌐 Enable Traditional Chinese translations. PR [#14842](https://github.com/fastapi/fastapi/pull/14842) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Enable French docs translations. PR [#14841](https://github.com/fastapi/fastapi/pull/14841) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for fr (translate-page). PR [#14837](https://github.com/fastapi/fastapi/pull/14837) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for de (update-outdated). PR [#14836](https://github.com/fastapi/fastapi/pull/14836) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for pt (update-outdated). PR [#14833](https://github.com/fastapi/fastapi/pull/14833) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for ko (update-outdated). PR [#14835](https://github.com/fastapi/fastapi/pull/14835) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for es (update-outdated). PR [#14832](https://github.com/fastapi/fastapi/pull/14832) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for tr (update-outdated). PR [#14831](https://github.com/fastapi/fastapi/pull/14831) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for tr (add-missing). PR [#14790](https://github.com/fastapi/fastapi/pull/14790) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for fr (update-outdated). PR [#14826](https://github.com/fastapi/fastapi/pull/14826) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for zh-hant (update-outdated). PR [#14825](https://github.com/fastapi/fastapi/pull/14825) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for uk (update-outdated). PR [#14822](https://github.com/fastapi/fastapi/pull/14822) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Update docs and translations scripts, enable Turkish. PR [#14824](https://github.com/fastapi/fastapi/pull/14824) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* 🔨 Add max pages to translate to configs. PR [#14840](https://github.com/fastapi/fastapi/pull/14840) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.128.1 (2026-02-04)
+
+### Features
+
+* ✨ Add `viewport` meta tag to improve Swagger UI on mobile devices. PR [#14777](https://github.com/fastapi/fastapi/pull/14777) by [@Joab0](https://github.com/Joab0).
+* 🚸 Improve error message for invalid query parameter type annotations. PR [#14479](https://github.com/fastapi/fastapi/pull/14479) by [@retwish](https://github.com/retwish).
+
+### Fixes
+
+* 🐛 Update `ValidationError` schema to include `input` and `ctx`. PR [#14791](https://github.com/fastapi/fastapi/pull/14791) by [@jonathan-fulton](https://github.com/jonathan-fulton).
+* 🐛 Fix TYPE_CHECKING annotations for Python 3.14 (PEP 649). PR [#14789](https://github.com/fastapi/fastapi/pull/14789) by [@mgu](https://github.com/mgu).
+* 🐛 Strip whitespaces from `Authorization` header credentials. PR [#14786](https://github.com/fastapi/fastapi/pull/14786) by [@WaveTheory1](https://github.com/WaveTheory1).
+* 🐛 Fix OpenAPI duplication of `anyOf` refs for app-level responses with specified `content` and `model` as `Union`. PR [#14463](https://github.com/fastapi/fastapi/pull/14463) by [@DJMcoder](https://github.com/DJMcoder).
+
+### Refactors
+
+* 🎨 Tweak types for mypy. PR [#14816](https://github.com/fastapi/fastapi/pull/14816) by [@tiangolo](https://github.com/tiangolo).
+* 🏷️ Re-export `IncEx` type from Pydantic instead of duplicating it. PR [#14641](https://github.com/fastapi/fastapi/pull/14641) by [@mvanderlee](https://github.com/mvanderlee).
+* 💡 Update comment for Pydantic internals. PR [#14814](https://github.com/fastapi/fastapi/pull/14814) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Update docs for contributing translations, simplify title. PR [#14817](https://github.com/fastapi/fastapi/pull/14817) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Fix typing issue in `docs_src/app_testing/app_b` code example. PR [#14573](https://github.com/fastapi/fastapi/pull/14573) by [@timakaa](https://github.com/timakaa).
+* 📝 Fix example of license identifier in documentation. PR [#14492](https://github.com/fastapi/fastapi/pull/14492) by [@johnson-earls](https://github.com/johnson-earls).
+* 📝 Add banner to translated pages. PR [#14809](https://github.com/fastapi/fastapi/pull/14809) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 📝 Add links to related sections of docs to docstrings. PR [#14776](https://github.com/fastapi/fastapi/pull/14776) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 📝 Update embedded code examples to Python 3.10 syntax. PR [#14758](https://github.com/fastapi/fastapi/pull/14758) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 📝 Fix dependency installation command in `docs/en/docs/contributing.md`. PR [#14757](https://github.com/fastapi/fastapi/pull/14757) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 📝 Use return type annotation instead of `response_model` when possible. PR [#14753](https://github.com/fastapi/fastapi/pull/14753) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 📝 Use `WSGIMiddleware` from `a2wsgi` instead of deprecated `fastapi.middleware.wsgi.WSGIMiddleware`. PR [#14756](https://github.com/fastapi/fastapi/pull/14756) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 📝 Fix minor typos in release notes. PR [#14780](https://github.com/fastapi/fastapi/pull/14780) by [@whyvineet](https://github.com/whyvineet).
+* 🐛 Fix copy button in custom.js. PR [#14722](https://github.com/fastapi/fastapi/pull/14722) by [@fcharrier](https://github.com/fcharrier).
+* 📝 Add contribution instructions about LLM generated code and comments and automated tools for PRs. PR [#14706](https://github.com/fastapi/fastapi/pull/14706) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update docs for management tasks. PR [#14705](https://github.com/fastapi/fastapi/pull/14705) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update docs about managing translations. PR [#14704](https://github.com/fastapi/fastapi/pull/14704) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update docs for contributing with translations. PR [#14701](https://github.com/fastapi/fastapi/pull/14701) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Specify language code for code block. PR [#14656](https://github.com/fastapi/fastapi/pull/14656) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+### Translations
+
+* 🌐 Improve LLM prompt of `uk` documentation. PR [#14795](https://github.com/fastapi/fastapi/pull/14795) by [@roli2py](https://github.com/roli2py).
+* 🌐 Update translations for ja (update-outdated). PR [#14588](https://github.com/fastapi/fastapi/pull/14588) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for uk (update outdated, found by fixer tool). PR [#14739](https://github.com/fastapi/fastapi/pull/14739) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Update translations for tr (update-outdated). PR [#14745](https://github.com/fastapi/fastapi/pull/14745) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update `llm-prompt.md` for Korean language. PR [#14763](https://github.com/fastapi/fastapi/pull/14763) by [@seuthootDev](https://github.com/seuthootDev).
+* 🌐 Update translations for ko (update outdated, found by fixer tool). PR [#14738](https://github.com/fastapi/fastapi/pull/14738) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Update translations for de (update-outdated). PR [#14690](https://github.com/fastapi/fastapi/pull/14690) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update LLM prompt for Russian translations. PR [#14733](https://github.com/fastapi/fastapi/pull/14733) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Update translations for ru (update-outdated). PR [#14693](https://github.com/fastapi/fastapi/pull/14693) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for pt (update-outdated). PR [#14724](https://github.com/fastapi/fastapi/pull/14724) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update Korean LLM prompt. PR [#14740](https://github.com/fastapi/fastapi/pull/14740) by [@hard-coders](https://github.com/hard-coders).
+* 🌐 Improve LLM prompt for Turkish translations. PR [#14728](https://github.com/fastapi/fastapi/pull/14728) by [@Kadermiyanyedi](https://github.com/Kadermiyanyedi).
+* 🌐 Update portuguese llm-prompt.md. PR [#14702](https://github.com/fastapi/fastapi/pull/14702) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Update LLM prompt instructions file for French. PR [#14618](https://github.com/fastapi/fastapi/pull/14618) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for ko (add-missing). PR [#14699](https://github.com/fastapi/fastapi/pull/14699) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for ko (update-outdated). PR [#14589](https://github.com/fastapi/fastapi/pull/14589) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for uk (update-outdated). PR [#14587](https://github.com/fastapi/fastapi/pull/14587) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for es (update-outdated). PR [#14686](https://github.com/fastapi/fastapi/pull/14686) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Add LLM prompt file for Turkish, generated from the existing translations. PR [#14547](https://github.com/fastapi/fastapi/pull/14547) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Add LLM prompt file for Traditional Chinese, generated from the existing translations. PR [#14550](https://github.com/fastapi/fastapi/pull/14550) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Add LLM prompt file for Simplified Chinese, generated from the existing translations. PR [#14549](https://github.com/fastapi/fastapi/pull/14549) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* ⬇️ Downgrade LLM translations model to GPT-5 to reduce mistakes. PR [#14823](https://github.com/fastapi/fastapi/pull/14823) by [@tiangolo](https://github.com/tiangolo).
+* 🐛 Fix translation script commit in place. PR [#14818](https://github.com/fastapi/fastapi/pull/14818) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Update translation script to retry if LLM-response doesn't pass validation with Translation Fixer tool. PR [#14749](https://github.com/fastapi/fastapi/pull/14749) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 👷 Run tests only on relevant code changes (not on docs). PR [#14813](https://github.com/fastapi/fastapi/pull/14813) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Run mypy by pre-commit. PR [#14806](https://github.com/fastapi/fastapi/pull/14806) by [@YuriiMotov](https://github.com/YuriiMotov).
+* ⬆ Bump ruff from 0.14.3 to 0.14.14. PR [#14798](https://github.com/fastapi/fastapi/pull/14798) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pyasn1 from 0.6.1 to 0.6.2. PR [#14804](https://github.com/fastapi/fastapi/pull/14804) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump sqlmodel from 0.0.27 to 0.0.31. PR [#14802](https://github.com/fastapi/fastapi/pull/14802) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump mkdocs-macros-plugin from 1.4.1 to 1.5.0. PR [#14801](https://github.com/fastapi/fastapi/pull/14801) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump gitpython from 3.1.45 to 3.1.46. PR [#14800](https://github.com/fastapi/fastapi/pull/14800) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump typer from 0.16.0 to 0.21.1. PR [#14799](https://github.com/fastapi/fastapi/pull/14799) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👥 Update FastAPI GitHub topic repositories. PR [#14803](https://github.com/fastapi/fastapi/pull/14803) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Contributors and Translators. PR [#14796](https://github.com/fastapi/fastapi/pull/14796) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Ensure that an edit to `uv.lock` gets the `internal` label. PR [#14759](https://github.com/fastapi/fastapi/pull/14759) by [@svlandeg](https://github.com/svlandeg).
+* 🔧 Update sponsors: remove Requestly. PR [#14735](https://github.com/fastapi/fastapi/pull/14735) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors, LambdaTest changes to TestMu AI. PR [#14734](https://github.com/fastapi/fastapi/pull/14734) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump actions/cache from 4 to 5. PR [#14511](https://github.com/fastapi/fastapi/pull/14511) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump actions/upload-artifact from 5 to 6. PR [#14525](https://github.com/fastapi/fastapi/pull/14525) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump actions/download-artifact from 6 to 7. PR [#14526](https://github.com/fastapi/fastapi/pull/14526) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👷 Tweak CI input names. PR [#14688](https://github.com/fastapi/fastapi/pull/14688) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Refactor translation script to allow committing in place. PR [#14687](https://github.com/fastapi/fastapi/pull/14687) by [@tiangolo](https://github.com/tiangolo).
+* 🐛 Fix translation script path. PR [#14685](https://github.com/fastapi/fastapi/pull/14685) by [@tiangolo](https://github.com/tiangolo).
+* ✅ Enable tests in CI for scripts. PR [#14684](https://github.com/fastapi/fastapi/pull/14684) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Add pre-commit local script to fix language translations. PR [#14683](https://github.com/fastapi/fastapi/pull/14683) by [@tiangolo](https://github.com/tiangolo).
+* ⬆️ Migrate to uv. PR [#14676](https://github.com/fastapi/fastapi/pull/14676) by [@DoctorJohn](https://github.com/DoctorJohn).
+* 🔨 Add LLM translations tool fixer. PR [#14652](https://github.com/fastapi/fastapi/pull/14652) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 👥 Update FastAPI People - Sponsors. PR [#14626](https://github.com/fastapi/fastapi/pull/14626) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI GitHub topic repositories. PR [#14630](https://github.com/fastapi/fastapi/pull/14630) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Contributors and Translators. PR [#14625](https://github.com/fastapi/fastapi/pull/14625) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translation prompts. PR [#14619](https://github.com/fastapi/fastapi/pull/14619) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Update LLM translation script to guide reviewers to change the prompt. PR [#14614](https://github.com/fastapi/fastapi/pull/14614) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Do not run translations on cron while finishing updating existing languages. PR [#14613](https://github.com/fastapi/fastapi/pull/14613) by [@tiangolo](https://github.com/tiangolo).
+* 🔥 Remove test variants for Pydantic v1 in test_request_params. PR [#14612](https://github.com/fastapi/fastapi/pull/14612) by [@tiangolo](https://github.com/tiangolo).
+* 🔥 Remove Pydantic v1 specific test variants. PR [#14611](https://github.com/fastapi/fastapi/pull/14611) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.128.0 (2025-12-27)
+
+### Breaking Changes
+
+* ➖ Drop support for `pydantic.v1`. PR [#14609](https://github.com/fastapi/fastapi/pull/14609) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* ✅ Run performance tests only on Pydantic v2. PR [#14608](https://github.com/fastapi/fastapi/pull/14608) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.127.1 (2025-12-26)
+
+### Refactors
+
+* 🔊 Add a custom `FastAPIDeprecationWarning`. PR [#14605](https://github.com/fastapi/fastapi/pull/14605) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Add documentary to website. PR [#14600](https://github.com/fastapi/fastapi/pull/14600) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Update translations for de (update-outdated). PR [#14602](https://github.com/fastapi/fastapi/pull/14602) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Update translations for de (update-outdated). PR [#14581](https://github.com/fastapi/fastapi/pull/14581) by [@nilslindemann](https://github.com/nilslindemann).
+
+### Internal
+
+* 🔧 Update pre-commit to use local Ruff instead of hook. PR [#14604](https://github.com/fastapi/fastapi/pull/14604) by [@tiangolo](https://github.com/tiangolo).
+* ✅ Add missing tests for code examples. PR [#14569](https://github.com/fastapi/fastapi/pull/14569) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 👷 Remove `lint` job from `test` CI workflow. PR [#14593](https://github.com/fastapi/fastapi/pull/14593) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 👷 Update secrets check. PR [#14592](https://github.com/fastapi/fastapi/pull/14592) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Run CodSpeed tests in parallel to other tests to speed up CI. PR [#14586](https://github.com/fastapi/fastapi/pull/14586) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Update scripts and pre-commit to autofix files. PR [#14585](https://github.com/fastapi/fastapi/pull/14585) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.127.0 (2025-12-21)
+
+### Breaking Changes
+
+* 🔊 Add deprecation warnings when using `pydantic.v1`. PR [#14583](https://github.com/fastapi/fastapi/pull/14583) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🔧 Add LLM prompt file for Korean, generated from the existing translations. PR [#14546](https://github.com/fastapi/fastapi/pull/14546) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Add LLM prompt file for Japanese, generated from the existing translations. PR [#14545](https://github.com/fastapi/fastapi/pull/14545) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* ⬆️ Upgrade OpenAI model for translations to gpt-5.2. PR [#14579](https://github.com/fastapi/fastapi/pull/14579) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.126.0 (2025-12-20)
+
+### Upgrades
+
+* ➖ Drop support for Pydantic v1, keeping short temporary support for Pydantic v2's `pydantic.v1`. PR [#14575](https://github.com/fastapi/fastapi/pull/14575) by [@tiangolo](https://github.com/tiangolo).
+ * The minimum version of Pydantic installed is now `pydantic >=2.7.0`.
+ * The `standard` dependencies now include `pydantic-settings >=2.0.0` and `pydantic-extra-types >=2.0.0`.
+
+### Docs
+
+* 📝 Fix duplicated variable in `docs_src/python_types/tutorial005_py39.py`. PR [#14565](https://github.com/fastapi/fastapi/pull/14565) by [@paras-verma7454](https://github.com/paras-verma7454).
+
+### Translations
+
+* 🔧 Add LLM prompt file for Ukrainian, generated from the existing translations. PR [#14548](https://github.com/fastapi/fastapi/pull/14548) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* 🔧 Tweak pre-commit to allow committing release-notes. PR [#14577](https://github.com/fastapi/fastapi/pull/14577) by [@tiangolo](https://github.com/tiangolo).
+* ⬆️ Use prek as a pre-commit alternative. PR [#14572](https://github.com/fastapi/fastapi/pull/14572) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Add performance tests with CodSpeed. PR [#14558](https://github.com/fastapi/fastapi/pull/14558) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.125.0 (2025-12-17)
+
+### Breaking Changes
+
+* 🔧 Drop support for Python 3.8. PR [#14563](https://github.com/fastapi/fastapi/pull/14563) by [@tiangolo](https://github.com/tiangolo).
+ * This would actually not be a _breaking_ change as no code would really break. Any Python 3.8 installer would just refuse to install the latest version of FastAPI and would only install 0.124.4. Only marking it as a "breaking change" to make it visible.
+
+### Refactors
+
+* ♻️ Upgrade internal syntax to Python 3.9+ 🎉. PR [#14564](https://github.com/fastapi/fastapi/pull/14564) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* ⚰️ Remove Python 3.8 from CI and remove Python 3.8 examples from source docs. PR [#14559](https://github.com/fastapi/fastapi/pull/14559) by [@YuriiMotov](https://github.com/YuriiMotov) and [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Update translations for pt (add-missing). PR [#14539](https://github.com/fastapi/fastapi/pull/14539) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Add LLM prompt file for French, generated from the existing French docs. PR [#14544](https://github.com/fastapi/fastapi/pull/14544) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Sync Portuguese docs (pages found with script). PR [#14554](https://github.com/fastapi/fastapi/pull/14554) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Sync Spanish docs (outdated pages found with script). PR [#14553](https://github.com/fastapi/fastapi/pull/14553) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Sync German docs. PR [#14519](https://github.com/fastapi/fastapi/pull/14519) by [@nilslindemann](https://github.com/nilslindemann).
+* 🔥 Remove inactive/scarce translations to Vietnamese. PR [#14543](https://github.com/fastapi/fastapi/pull/14543) by [@tiangolo](https://github.com/tiangolo).
+* 🔥 Remove inactive/scarce translations to Persian. PR [#14542](https://github.com/fastapi/fastapi/pull/14542) by [@tiangolo](https://github.com/tiangolo).
+* 🔥 Remove translation to emoji to simplify the new setup with LLM autotranslations. PR [#14541](https://github.com/fastapi/fastapi/pull/14541) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for pt (update-outdated). PR [#14537](https://github.com/fastapi/fastapi/pull/14537) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for es (update-outdated). PR [#14532](https://github.com/fastapi/fastapi/pull/14532) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update translations for es (add-missing). PR [#14533](https://github.com/fastapi/fastapi/pull/14533) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Remove translations for removed docs. PR [#14516](https://github.com/fastapi/fastapi/pull/14516) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* ⬆ Bump `markdown-include-variants` from 0.0.7 to 0.0.8. PR [#14556](https://github.com/fastapi/fastapi/pull/14556) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🔧 Temporarily disable translations still in progress, being migrated to the new LLM setup. PR [#14555](https://github.com/fastapi/fastapi/pull/14555) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🔧 Update test workflow config, remove commented code. PR [#14540](https://github.com/fastapi/fastapi/pull/14540) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Configure coverage, error on main tests, don't wait for Smokeshow. PR [#14536](https://github.com/fastapi/fastapi/pull/14536) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Run Smokeshow always, even on test failures. PR [#14538](https://github.com/fastapi/fastapi/pull/14538) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Make Pydantic versions customizable in CI. PR [#14535](https://github.com/fastapi/fastapi/pull/14535) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Fix checkout GitHub Action fetch-depth for LLM translations, enable cron monthly. PR [#14531](https://github.com/fastapi/fastapi/pull/14531) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Fix Typer command for CI LLM translations. PR [#14530](https://github.com/fastapi/fastapi/pull/14530) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update LLM translation CI, add language matrix and extra commands, prepare for scheduled run. PR [#14529](https://github.com/fastapi/fastapi/pull/14529) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update github-actions user for GitHub Actions workflows. PR [#14528](https://github.com/fastapi/fastapi/pull/14528) by [@tiangolo](https://github.com/tiangolo).
+* ➕ Add requirements for translations. PR [#14515](https://github.com/fastapi/fastapi/pull/14515) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.124.4 (2025-12-12)
+
+### Fixes
+
+* 🐛 Fix parameter aliases. PR [#14371](https://github.com/fastapi/fastapi/pull/14371) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+## 0.124.3 (2025-12-12)
+
+### Fixes
+
+* 🐛 Fix support for tagged union with discriminator inside of `Annotated` with `Body()`. PR [#14512](https://github.com/fastapi/fastapi/pull/14512) by [@tiangolo](https://github.com/tiangolo).
+
+### Refactors
+
+* ✅ Add set of tests for request parameters and alias. PR [#14358](https://github.com/fastapi/fastapi/pull/14358) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+### Docs
+
+* 📝 Tweak links format. PR [#14505](https://github.com/fastapi/fastapi/pull/14505) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update docs about re-raising validation errors, do not include string as is to not leak information. PR [#14487](https://github.com/fastapi/fastapi/pull/14487) by [@tiangolo](https://github.com/tiangolo).
+* 🔥 Remove external links section. PR [#14486](https://github.com/fastapi/fastapi/pull/14486) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Sync Russian docs. PR [#14509](https://github.com/fastapi/fastapi/pull/14509) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Sync German docs. PR [#14488](https://github.com/fastapi/fastapi/pull/14488) by [@nilslindemann](https://github.com/nilslindemann).
+
+### Internal
+
+* 👷 Tweak coverage to not pass Smokeshow max file size limit. PR [#14507](https://github.com/fastapi/fastapi/pull/14507) by [@tiangolo](https://github.com/tiangolo).
+* ✅ Expand test matrix to include Windows and MacOS. PR [#14171](https://github.com/fastapi/fastapi/pull/14171) by [@svlandeg](https://github.com/svlandeg).
+
+## 0.124.2 (2025-12-10)
+
+### Fixes
+
+* 🐛 Fix support for `if TYPE_CHECKING`, non-evaluated stringified annotations. PR [#14485](https://github.com/fastapi/fastapi/pull/14485) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.124.1 (2025-12-10)
+
+### Fixes
+
+* 🐛 Fix handling arbitrary types when using `arbitrary_types_allowed=True`. PR [#14482](https://github.com/fastapi/fastapi/pull/14482) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Add variants for code examples in "Advanced User Guide". PR [#14413](https://github.com/fastapi/fastapi/pull/14413) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 📝 Update tech stack in project generation docs. PR [#14472](https://github.com/fastapi/fastapi/pull/14472) by [@alejsdev](https://github.com/alejsdev).
+
+### Internal
+
+* ✅ Add test for Pydantic v2, dataclasses, UUID, and `__annotations__`. PR [#14477](https://github.com/fastapi/fastapi/pull/14477) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.124.0 (2025-12-06)
+
+### Features
+
+* 🚸 Improve tracebacks by adding endpoint metadata. PR [#14306](https://github.com/fastapi/fastapi/pull/14306) by [@savannahostrowski](https://github.com/savannahostrowski).
+
+### Internal
+
+* ✏️ Fix typo in `scripts/mkdocs_hooks.py`. PR [#14457](https://github.com/fastapi/fastapi/pull/14457) by [@yujiteshima](https://github.com/yujiteshima).
+
+## 0.123.10 (2025-12-05)
+
+### Fixes
+
+* 🐛 Fix using class (not instance) dependency that has `__call__` method. PR [#14458](https://github.com/fastapi/fastapi/pull/14458) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🐛 Fix `separate_input_output_schemas=False` with `computed_field`. PR [#14453](https://github.com/fastapi/fastapi/pull/14453) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+## 0.123.9 (2025-12-04)
+
+### Fixes
+
+* 🐛 Fix OAuth2 scopes in OpenAPI in extra corner cases, parent dependency with scopes, sub-dependency security scheme without scopes. PR [#14459](https://github.com/fastapi/fastapi/pull/14459) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.123.8 (2025-12-04)
+
+### Fixes
+
+* 🐛 Fix OpenAPI security scheme OAuth2 scopes declaration, deduplicate security schemes with different scopes. PR [#14455](https://github.com/fastapi/fastapi/pull/14455) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.123.7 (2025-12-04)
+
+### Fixes
+
+* 🐛 Fix evaluating stringified annotations in Python 3.10. PR [#11355](https://github.com/fastapi/fastapi/pull/11355) by [@chaen](https://github.com/chaen).
+
+## 0.123.6 (2025-12-04)
+
+### Fixes
+
+* 🐛 Fix support for functools wraps and partial combined, for async and regular functions and classes in path operations and dependencies. PR [#14448](https://github.com/fastapi/fastapi/pull/14448) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.123.5 (2025-12-02)
+
+### Features
+
+* ✨ Allow using dependables with `functools.partial()`. PR [#9753](https://github.com/fastapi/fastapi/pull/9753) by [@lieryan](https://github.com/lieryan).
+* ✨ Add support for wrapped functions (e.g. `@functools.wraps()`) used with forward references. PR [#5077](https://github.com/fastapi/fastapi/pull/5077) by [@lucaswiman](https://github.com/lucaswiman).
+* ✨ Handle wrapped dependencies. PR [#9555](https://github.com/fastapi/fastapi/pull/9555) by [@phy1729](https://github.com/phy1729).
+
+### Fixes
+
+* 🐛 Fix optional sequence handling with new union syntax from Python 3.10. PR [#14430](https://github.com/fastapi/fastapi/pull/14430) by [@Viicos](https://github.com/Viicos).
+
+### Refactors
+
+* 🔥 Remove dangling extra conditional no longer needed. PR [#14435](https://github.com/fastapi/fastapi/pull/14435) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Refactor internals, update `is_coroutine` check to reuse internal supported variants (unwrap, check class). PR [#14434](https://github.com/fastapi/fastapi/pull/14434) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Sync German docs. PR [#14367](https://github.com/fastapi/fastapi/pull/14367) by [@nilslindemann](https://github.com/nilslindemann).
+
+## 0.123.4 (2025-12-02)
+
+### Fixes
+
+* 🐛 Fix OpenAPI schema support for computed fields when using `separate_input_output_schemas=False`. PR [#13207](https://github.com/fastapi/fastapi/pull/13207) by [@vgrafe](https://github.com/vgrafe).
+
+### Docs
+
+* 📝 Fix docstring of `servers` parameter. PR [#14405](https://github.com/fastapi/fastapi/pull/14405) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+## 0.123.3 (2025-12-02)
+
+### Fixes
+
+* 🐛 Fix Query\Header\Cookie parameter model alias. PR [#14360](https://github.com/fastapi/fastapi/pull/14360) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🐛 Fix optional sequence handling in `serialize sequence value` with Pydantic V2. PR [#14297](https://github.com/fastapi/fastapi/pull/14297) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+## 0.123.2 (2025-12-02)
+
+### Fixes
+
+* 🐛 Fix unformatted `{type_}` in FastAPIError. PR [#14416](https://github.com/fastapi/fastapi/pull/14416) by [@Just-Helpful](https://github.com/Just-Helpful).
+* 🐛 Fix parsing extra non-body parameter list. PR [#14356](https://github.com/fastapi/fastapi/pull/14356) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🐛 Fix parsing extra `Form` parameter list. PR [#14303](https://github.com/fastapi/fastapi/pull/14303) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🐛 Fix support for form values with empty strings interpreted as missing (`None` if that's the default), for compatibility with HTML forms. PR [#13537](https://github.com/fastapi/fastapi/pull/13537) by [@MarinPostma](https://github.com/MarinPostma).
+
+### Docs
+
+* 📝 Add tip on how to install `pip` in case of `No module named pip` error in `virtual-environments.md`. PR [#14211](https://github.com/fastapi/fastapi/pull/14211) by [@zadevhub](https://github.com/zadevhub).
+* 📝 Update Primary Key notes for the SQL databases tutorial to avoid confusion. PR [#14120](https://github.com/fastapi/fastapi/pull/14120) by [@FlaviusRaducu](https://github.com/FlaviusRaducu).
+* 📝 Clarify estimation note in documentation. PR [#14070](https://github.com/fastapi/fastapi/pull/14070) by [@SaisakthiM](https://github.com/SaisakthiM).
+
+## 0.123.1 (2025-12-02)
+
+### Fixes
+
+* 🐛 Avoid accessing non-existing "$ref" key for Pydantic v2 compat remapping. PR [#14361](https://github.com/fastapi/fastapi/pull/14361) by [@svlandeg](https://github.com/svlandeg).
+* 🐛 Fix `TypeError` when encoding a decimal with a `NaN` or `Infinity` value. PR [#12935](https://github.com/fastapi/fastapi/pull/12935) by [@kentwelcome](https://github.com/kentwelcome).
+
+### Internal
+
+* 🐛 Fix Windows UnicodeEncodeError in CLI test. PR [#14295](https://github.com/fastapi/fastapi/pull/14295) by [@hemanth-thirthahalli](https://github.com/hemanth-thirthahalli).
+* 🔧 Update sponsors: add Greptile. PR [#14429](https://github.com/fastapi/fastapi/pull/14429) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI GitHub topic repositories. PR [#14426](https://github.com/fastapi/fastapi/pull/14426) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump markdown-include-variants from 0.0.6 to 0.0.7. PR [#14423](https://github.com/fastapi/fastapi/pull/14423) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 👥 Update FastAPI People - Sponsors. PR [#14422](https://github.com/fastapi/fastapi/pull/14422) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Contributors and Translators. PR [#14420](https://github.com/fastapi/fastapi/pull/14420) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.123.0 (2025-11-30)
+
+### Fixes
+
+* 🐛 Cache dependencies that don't use scopes and don't have sub-dependencies with scopes. PR [#14419](https://github.com/fastapi/fastapi/pull/14419) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.122.1 (2025-11-30)
+
+### Fixes
+
+* 🐛 Fix hierarchical security scope propagation. PR [#5624](https://github.com/fastapi/fastapi/pull/5624) by [@kristjanvalur](https://github.com/kristjanvalur).
+
+### Docs
+
+* 💅 Update CSS to explicitly use emoji font. PR [#14415](https://github.com/fastapi/fastapi/pull/14415) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* ⬆ Bump markdown-include-variants from 0.0.5 to 0.0.6. PR [#14418](https://github.com/fastapi/fastapi/pull/14418) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+## 0.122.0 (2025-11-24)
+
+### Fixes
+
+* 🐛 Use `401` status code in security classes when credentials are missing. PR [#13786](https://github.com/fastapi/fastapi/pull/13786) by [@YuriiMotov](https://github.com/YuriiMotov).
+ * If your code depended on these classes raising the old (less correct) `403` status code, check the new docs about how to override the classes, to use the same old behavior: [Use Old 403 Authentication Error Status Codes](https://fastapi.tiangolo.com/how-to/authentication-error-status-code/).
+
+### Internal
+
+* 🔧 Configure labeler to exclude files that start from underscore for `lang-all` label. PR [#14213](https://github.com/fastapi/fastapi/pull/14213) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 👷 Add pre-commit config with local script for permalinks. PR [#14398](https://github.com/fastapi/fastapi/pull/14398) by [@tiangolo](https://github.com/tiangolo).
+* 💄 Use font Fira Code to fix display of Rich panels in docs in Windows. PR [#14387](https://github.com/fastapi/fastapi/pull/14387) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Add custom pre-commit CI. PR [#14397](https://github.com/fastapi/fastapi/pull/14397) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump actions/checkout from 5 to 6. PR [#14381](https://github.com/fastapi/fastapi/pull/14381) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👷 Upgrade `latest-changes` GitHub Action and pin `actions/checkout@v5`. PR [#14403](https://github.com/fastapi/fastapi/pull/14403) by [@svlandeg](https://github.com/svlandeg).
+* 🛠️ Add `add-permalinks` and `add-permalinks-page` to `scripts/docs.py`. PR [#14033](https://github.com/fastapi/fastapi/pull/14033) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🔧 Upgrade Material for MkDocs and remove insiders. PR [#14375](https://github.com/fastapi/fastapi/pull/14375) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.121.3 (2025-11-19)
+
+### Refactors
+
+* ♻️ Make the result of `Depends()` and `Security()` hashable, as a workaround for other tools interacting with these internal parts. PR [#14372](https://github.com/fastapi/fastapi/pull/14372) by [@tiangolo](https://github.com/tiangolo).
+
+### Upgrades
+
+* ⬆️ Bump Starlette to <`0.51.0`. PR [#14282](https://github.com/fastapi/fastapi/pull/14282) by [@musicinmybrain](https://github.com/musicinmybrain).
+
+### Docs
+
+* 📝 Add missing hash part. PR [#14369](https://github.com/fastapi/fastapi/pull/14369) by [@nilslindemann](https://github.com/nilslindemann).
+* 📝 Fix typos in code comments. PR [#14364](https://github.com/fastapi/fastapi/pull/14364) by [@Edge-Seven](https://github.com/Edge-Seven).
+* 📝 Add docs for using FastAPI Cloud. PR [#14359](https://github.com/fastapi/fastapi/pull/14359) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.121.2 (2025-11-13)
+
+### Fixes
+
+* 🐛 Fix handling of JSON Schema attributes named "$ref". PR [#14349](https://github.com/fastapi/fastapi/pull/14349) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Add EuroPython talk & podcast episode with Sebastián Ramírez. PR [#14260](https://github.com/fastapi/fastapi/pull/14260) by [@clytaemnestra](https://github.com/clytaemnestra).
+* ✏️ Fix links and add missing permalink in docs. PR [#14217](https://github.com/fastapi/fastapi/pull/14217) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+### Translations
+
+* 🌐 Update Portuguese translations with LLM prompt. PR [#14228](https://github.com/fastapi/fastapi/pull/14228) by [@ceb10n](https://github.com/ceb10n).
+* 🔨 Add Portuguese translations LLM prompt. PR [#14208](https://github.com/fastapi/fastapi/pull/14208) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Sync Russian docs. PR [#14331](https://github.com/fastapi/fastapi/pull/14331) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Sync German docs. PR [#14317](https://github.com/fastapi/fastapi/pull/14317) by [@nilslindemann](https://github.com/nilslindemann).
+
+## 0.121.1 (2025-11-08)
+
+### Fixes
+
+* 🐛 Fix `Depends(func, scope='function')` for top level (parameterless) dependencies. PR [#14301](https://github.com/fastapi/fastapi/pull/14301) by [@luzzodev](https://github.com/luzzodev).
+
+### Docs
+
+* 📝 Update docs for advanced dependencies with `yield`, noting the changes in 0.121.0, adding `scope`. PR [#14287](https://github.com/fastapi/fastapi/pull/14287) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* ⬆ Bump ruff from 0.13.2 to 0.14.3. PR [#14276](https://github.com/fastapi/fastapi/pull/14276) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#14289](https://github.com/fastapi/fastapi/pull/14289) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+
+## 0.121.0 (2025-11-03)
+
+### Features
+
+* ✨ Add support for dependencies with scopes, support `scope="request"` for dependencies with `yield` that exit before the response is sent. PR [#14262](https://github.com/fastapi/fastapi/pull/14262) by [@tiangolo](https://github.com/tiangolo).
+ * New docs: [Dependencies with `yield` - Early exit and `scope`](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#early-exit-and-scope).
+
+### Internal
+
+* 👥 Update FastAPI People - Contributors and Translators. PR [#14273](https://github.com/fastapi/fastapi/pull/14273) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Sponsors. PR [#14274](https://github.com/fastapi/fastapi/pull/14274) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI GitHub topic repositories. PR [#14280](https://github.com/fastapi/fastapi/pull/14280) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump mkdocs-macros-plugin from 1.4.0 to 1.4.1. PR [#14277](https://github.com/fastapi/fastapi/pull/14277) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump mkdocstrings[python] from 0.26.1 to 0.30.1. PR [#14279](https://github.com/fastapi/fastapi/pull/14279) by [@dependabot[bot]](https://github.com/apps/dependabot).
+
+## 0.120.4 (2025-10-31)
+
+### Fixes
+
+* 🐛 Fix security schemes in OpenAPI when added at the top level app. PR [#14266](https://github.com/fastapi/fastapi/pull/14266) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+## 0.120.3 (2025-10-30)
+
+### Refactors
+
+* ♻️ Reduce internal cyclic recursion in dependencies, from 2 functions calling each other to 1 calling itself. PR [#14256](https://github.com/fastapi/fastapi/pull/14256) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Refactor internals of dependencies, simplify code and remove `get_param_sub_dependant`. PR [#14255](https://github.com/fastapi/fastapi/pull/14255) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Refactor internals of dependencies, simplify using dataclasses. PR [#14254](https://github.com/fastapi/fastapi/pull/14254) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Update note for untranslated pages. PR [#14257](https://github.com/fastapi/fastapi/pull/14257) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+## 0.120.2 (2025-10-29)
+
+### Fixes
+
+* 🐛 Fix separation of schemas with nested models introduced in 0.119.0. PR [#14246](https://github.com/fastapi/fastapi/pull/14246) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* 🔧 Add sponsor: SerpApi. PR [#14248](https://github.com/fastapi/fastapi/pull/14248) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump actions/download-artifact from 5 to 6. PR [#14236](https://github.com/fastapi/fastapi/pull/14236) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#14237](https://github.com/fastapi/fastapi/pull/14237) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ⬆ Bump actions/upload-artifact from 4 to 5. PR [#14235](https://github.com/fastapi/fastapi/pull/14235) by [@dependabot[bot]](https://github.com/apps/dependabot).
+
+## 0.120.1 (2025-10-27)
+
+### Upgrades
+
+* ⬆️ Bump Starlette to <`0.50.0`. PR [#14234](https://github.com/fastapi/fastapi/pull/14234) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+### Internal
+
+* 🔧 Add `license` and `license-files` to `pyproject.toml`, remove `License` from `classifiers`. PR [#14230](https://github.com/fastapi/fastapi/pull/14230) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+## 0.120.0 (2025-10-23)
+
+There are no major nor breaking changes in this release. ☕️
+
+The internal reference documentation now uses `annotated_doc.Doc` instead of `typing_extensions.Doc`, this adds a new (very small) dependency on [`annotated-doc`](https://github.com/fastapi/annotated-doc), a package made just to provide that `Doc` documentation utility class.
+
+I would expect `typing_extensions.Doc` to be deprecated and then removed at some point from `typing_extensions`, for that reason there's the new `annotated-doc` micro-package. If you are curious about this, you can read more in the repo for [`annotated-doc`](https://github.com/fastapi/annotated-doc).
+
+This new version `0.120.0` only contains that transition to the new home package for that utility class `Doc`.
+
+### Translations
+
+* 🌐 Sync German docs. PR [#14188](https://github.com/fastapi/fastapi/pull/14188) by [@nilslindemann](https://github.com/nilslindemann).
+
+### Internal
+
+* ➕ Migrate internal reference documentation from `typing_extensions.Doc` to `annotated_doc.Doc`. PR [#14222](https://github.com/fastapi/fastapi/pull/14222) by [@tiangolo](https://github.com/tiangolo).
+* 🛠️ Update German LLM prompt and test file. PR [#14189](https://github.com/fastapi/fastapi/pull/14189) by [@nilslindemann](https://github.com/nilslindemann).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#14181](https://github.com/fastapi/fastapi/pull/14181) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+
+## 0.119.1 (2025-10-20)
+
+### Fixes
+
+* 🐛 Fix internal Pydantic v1 compatibility (warnings) for Python 3.14 and Pydantic 2.12.1. PR [#14186](https://github.com/fastapi/fastapi/pull/14186) by [@svlandeg](https://github.com/svlandeg).
+
+### Docs
+
+* 📝 Replace `starlette.io` by `starlette.dev` and `uvicorn.org` by `uvicorn.dev`. PR [#14176](https://github.com/fastapi/fastapi/pull/14176) by [@Kludex](https://github.com/Kludex).
+
+### Internal
+
+* 🔧 Add sponsor Requestly. PR [#14205](https://github.com/fastapi/fastapi/pull/14205) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Configure reminder for `waiting` label in `issue-manager`. PR [#14156](https://github.com/fastapi/fastapi/pull/14156) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+## 0.119.0 (2025-10-11)
+
+FastAPI now (temporarily) supports both Pydantic v2 models and `pydantic.v1` models at the same time in the same app, to make it easier for any FastAPI apps still using Pydantic v1 to gradually but quickly **migrate to Pydantic v2**.
+
+```Python
+from fastapi import FastAPI
+from pydantic import BaseModel as BaseModelV2
+from pydantic.v1 import BaseModel
+
+
+class Item(BaseModel):
+ name: str
+ description: str | None = None
+
+
+class ItemV2(BaseModelV2):
+ title: str
+ summary: str | None = None
+
+
+app = FastAPI()
+
+
+@app.post("/items/", response_model=ItemV2)
+def create_item(item: Item):
+ return {"title": item.name, "summary": item.description}
+```
+
+Adding this feature was a big effort with the main objective of making it easier for the few applications still stuck in Pydantic v1 to migrate to Pydantic v2.
+
+And with this, support for **Pydantic v1 is now deprecated** and will be **removed** from FastAPI in a future version soon.
+
+**Note**: have in mind that the Pydantic team already stopped supporting Pydantic v1 for recent versions of Python, starting with Python 3.14.
+
+You can read in the docs more about how to [Migrate from Pydantic v1 to Pydantic v2](https://fastapi.tiangolo.com/how-to/migrate-from-pydantic-v1-to-pydantic-v2/).
+
+### Features
+
+* ✨ Add support for `from pydantic.v1 import BaseModel`, mixed Pydantic v1 and v2 models in the same app. PR [#14168](https://github.com/fastapi/fastapi/pull/14168) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.118.3 (2025-10-10)
+
+### Upgrades
+
+* ⬆️ Add support for Python 3.14. PR [#14165](https://github.com/fastapi/fastapi/pull/14165) by [@svlandeg](https://github.com/svlandeg).
+
+## 0.118.2 (2025-10-08)
+
+### Fixes
+
+* 🐛 Fix tagged discriminated union not recognized as body field. PR [#12942](https://github.com/fastapi/fastapi/pull/12942) by [@frankie567](https://github.com/frankie567).
+
+### Internal
+
+* ⬆ Bump astral-sh/setup-uv from 6 to 7. PR [#14167](https://github.com/fastapi/fastapi/pull/14167) by [@dependabot[bot]](https://github.com/apps/dependabot).
+
+## 0.118.1 (2025-10-08)
+
+### Upgrades
+
+* 👽️ Ensure compatibility with Pydantic 2.12.0. PR [#14036](https://github.com/fastapi/fastapi/pull/14036) by [@cjwatson](https://github.com/cjwatson).
+
+### Docs
+
+* 📝 Add External Link: Getting started with logging in FastAPI. PR [#14152](https://github.com/fastapi/fastapi/pull/14152) by [@itssimon](https://github.com/itssimon).
+
+### Translations
+
+* 🔨 Add Russian translations LLM prompt. PR [#13936](https://github.com/fastapi/fastapi/pull/13936) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Sync German docs. PR [#14149](https://github.com/fastapi/fastapi/pull/14149) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add Russian translations for missing pages (LLM-generated). PR [#14135](https://github.com/fastapi/fastapi/pull/14135) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Update Russian translations for existing pages (LLM-generated). PR [#14123](https://github.com/fastapi/fastapi/pull/14123) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🌐 Remove configuration files for inactive translations. PR [#14130](https://github.com/fastapi/fastapi/pull/14130) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* 🔨 Move local coverage logic to its own script. PR [#14166](https://github.com/fastapi/fastapi/pull/14166) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#14161](https://github.com/fastapi/fastapi/pull/14161) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ⬆ Bump griffe-typingdoc from 0.2.8 to 0.2.9. PR [#14144](https://github.com/fastapi/fastapi/pull/14144) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump mkdocs-macros-plugin from 1.3.9 to 1.4.0. PR [#14145](https://github.com/fastapi/fastapi/pull/14145) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump markdown-include-variants from 0.0.4 to 0.0.5. PR [#14146](https://github.com/fastapi/fastapi/pull/14146) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#14126](https://github.com/fastapi/fastapi/pull/14126) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* 👥 Update FastAPI GitHub topic repositories. PR [#14150](https://github.com/fastapi/fastapi/pull/14150) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Sponsors. PR [#14139](https://github.com/fastapi/fastapi/pull/14139) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Contributors and Translators. PR [#14138](https://github.com/fastapi/fastapi/pull/14138) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump ruff from 0.12.7 to 0.13.2. PR [#14147](https://github.com/fastapi/fastapi/pull/14147) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump sqlmodel from 0.0.24 to 0.0.25. PR [#14143](https://github.com/fastapi/fastapi/pull/14143) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump tiangolo/issue-manager from 0.5.1 to 0.6.0. PR [#14148](https://github.com/fastapi/fastapi/pull/14148) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👷 Update docs previews comment, single comment, add failure status. PR [#14129](https://github.com/fastapi/fastapi/pull/14129) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Modify `mkdocs_hooks.py` to add `title` to page's metadata (remove permalinks in social cards). PR [#14125](https://github.com/fastapi/fastapi/pull/14125) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+## 0.118.0 (2025-09-29)
+
+### Fixes
+
+* 🐛 Fix support for `StreamingResponse`s with dependencies with `yield` or `UploadFile`s, close after the response is done. PR [#14099](https://github.com/fastapi/fastapi/pull/14099) by [@tiangolo](https://github.com/tiangolo).
+
+Before FastAPI 0.118.0, if you used a dependency with `yield`, it would run the exit code after the *path operation function* returned but right before sending the response.
+
+This change also meant that if you returned a `StreamingResponse`, the exit code of the dependency with `yield` would have been already run.
+
+For example, if you had a database session in a dependency with `yield`, the `StreamingResponse` would not be able to use that session while streaming data because the session would have already been closed in the exit code after `yield`.
+
+This behavior was reverted in 0.118.0, to make the exit code after `yield` be executed after the response is sent.
+
+You can read more about it in the docs for [Advanced Dependencies - Dependencies with `yield`, `HTTPException`, `except` and Background Tasks](https://fastapi.tiangolo.com/advanced/advanced-dependencies#dependencies-with-yield-httpexception-except-and-background-tasks). Including what you could do if you wanted to close a database session earlier, before returning the response to the client.
+
+### Docs
+
+* 📝 Update `tutorial/security/oauth2-jwt/` to use `pwdlib` with Argon2 instead of `passlib`. PR [#13917](https://github.com/fastapi/fastapi/pull/13917) by [@Neizvestnyj](https://github.com/Neizvestnyj).
+* ✏️ Fix typos in OAuth2 password request forms. PR [#14112](https://github.com/fastapi/fastapi/pull/14112) by [@alv2017](https://github.com/alv2017).
+* 📝 Update contributing guidelines for installing requirements. PR [#14095](https://github.com/fastapi/fastapi/pull/14095) by [@alejsdev](https://github.com/alejsdev).
+
+### Translations
+
+* 🌐 Sync German docs. PR [#14098](https://github.com/fastapi/fastapi/pull/14098) by [@nilslindemann](https://github.com/nilslindemann).
+
+### Internal
+
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#14103](https://github.com/fastapi/fastapi/pull/14103) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ♻️ Refactor sponsor image handling. PR [#14102](https://github.com/fastapi/fastapi/pull/14102) by [@alejsdev](https://github.com/alejsdev).
+* 🐛 Fix sponsor display issue by hiding element on image error. PR [#14097](https://github.com/fastapi/fastapi/pull/14097) by [@alejsdev](https://github.com/alejsdev).
+* 🐛 Hide sponsor badge when sponsor image is not displayed. PR [#14096](https://github.com/fastapi/fastapi/pull/14096) by [@alejsdev](https://github.com/alejsdev).
+
+## 0.117.1 (2025-09-20)
+
+### Fixes
+
+* 🐛 Fix validation error when `File` is declared after `Form` parameter. PR [#11194](https://github.com/fastapi/fastapi/pull/11194) by [@thomasleveil](https://github.com/thomasleveil).
+
+## 0.117.0 (2025-09-20)
+
+### Features
+
+* ✨ Allow `None` as return type for bodiless responses. PR [#9425](https://github.com/fastapi/fastapi/pull/9425) by [@hofrob](https://github.com/hofrob).
+* ✨ Allow array values for OpenAPI schema `type` field. PR [#13639](https://github.com/fastapi/fastapi/pull/13639) by [@sammasak](https://github.com/sammasak).
+* ✨ Add OpenAPI `external_docs` parameter to `FastAPI`. PR [#13713](https://github.com/fastapi/fastapi/pull/13713) by [@cmtoro](https://github.com/cmtoro).
+
+### Fixes
+
+* ⚡️ Fix `default_factory` for response model field with Pydantic V1. PR [#9704](https://github.com/fastapi/fastapi/pull/9704) by [@vvanglro](https://github.com/vvanglro).
+* 🐛 Fix inconsistent processing of model docstring formfeed char with Pydantic V1. PR [#6039](https://github.com/fastapi/fastapi/pull/6039) by [@MaxwellPayne](https://github.com/MaxwellPayne).
+* 🐛 Fix `jsonable_encoder` alters `json_encoders` of Pydantic v1 objects. PR [#4972](https://github.com/fastapi/fastapi/pull/4972) by [@aboubacs](https://github.com/aboubacs).
+* 🐛 Reenable `allow_arbitrary_types` when only 1 argument is used on the API endpoint. PR [#13694](https://github.com/fastapi/fastapi/pull/13694) by [@rmawatson](https://github.com/rmawatson).
+* 🐛 Fix `inspect.getcoroutinefunction()` can break testing with `unittest.mock.patch()`. PR [#14022](https://github.com/fastapi/fastapi/pull/14022) by [@secrett2633](https://github.com/secrett2633).
+
+### Refactors
+
+* ♻️ Create `dependency-cache` dict in `solve_dependencies` only if `None` (don't re-create if empty). PR [#13689](https://github.com/fastapi/fastapi/pull/13689) by [@bokshitsky](https://github.com/bokshitsky).
+* ✅ Enable test case for duplicated headers in `test_tutorial/test_header_params/test_tutorial003.py`. PR [#13864](https://github.com/fastapi/fastapi/pull/13864) by [@Amogha-ark](https://github.com/Amogha-ark).
+* 📌 Pin `httpx` to `>=0.23.0,<1.0.0`. PR [#14086](https://github.com/fastapi/fastapi/pull/14086) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+### Docs
+
+* 📝 Add note about Cookies and JavaScript on `tutorial/cookie-params.md`. PR [#13510](https://github.com/fastapi/fastapi/pull/13510) by [@Kludex](https://github.com/Kludex).
+* 📝 Remove outdated formatting from `path-params-numeric-validations.md` for languages `en`, `es` and `uk`.. PR [#14059](https://github.com/fastapi/fastapi/pull/14059) by [@svlandeg](https://github.com/svlandeg).
+* 📝 Fix and Improve English Documentation. PR [#14048](https://github.com/fastapi/fastapi/pull/14048) by [@nilslindemann](https://github.com/nilslindemann).
+
+### Translations
+
+* 📝 Update prompts and German translation. PR [#14015](https://github.com/fastapi/fastapi/pull/14015) by [@nilslindemann](https://github.com/nilslindemann).
+
+### Internal
+
+* ✅ Simplify tests for response_model. PR [#14062](https://github.com/fastapi/fastapi/pull/14062) by [@dynamicy](https://github.com/dynamicy).
+* 🚨 Install pydantic.mypy plugin. PR [#14081](https://github.com/fastapi/fastapi/pull/14081) by [@svlandeg](https://github.com/svlandeg).
+* ✅ Add LLM test file. PR [#14049](https://github.com/fastapi/fastapi/pull/14049) by [@nilslindemann](https://github.com/nilslindemann).
+* 🔨 Update translations script. PR [#13968](https://github.com/fastapi/fastapi/pull/13968) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🛠️ Update `docs.py generate-readme` command to remove permalinks from headers. PR [#14055](https://github.com/fastapi/fastapi/pull/14055) by [@YuriiMotov](https://github.com/YuriiMotov).
+* ⬆️ Update mypy to 1.14.1. PR [#12970](https://github.com/fastapi/fastapi/pull/12970) by [@tamird](https://github.com/tamird).
+
+## 0.116.2 (2025-09-16)
+
+### Upgrades
+
+* ⬆️ Upgrade Starlette supported version range to >=0.40.0,<0.49.0. PR [#14077](https://github.com/fastapi/fastapi/pull/14077) by [@musicinmybrain](https://github.com/musicinmybrain).
+
+### Docs
+
+* 📝 Add documentation for Behind a Proxy - Proxy Forwarded Headers, using `--forwarded-allow-ips="*"`. PR [#14028](https://github.com/fastapi/fastapi/pull/14028) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Add deprecation info block about `dict()` in `docs/tutorial/body.md`. PR [#13906](https://github.com/fastapi/fastapi/pull/13906) by [@jomkv](https://github.com/jomkv).
+* 📝 Fix Twitter to be X (Twitter) everywhere in documentation. PR [#13809](https://github.com/fastapi/fastapi/pull/13809) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🐛 Prevent scroll-to-top on restart/fast buttons in `termynal.js`. PR [#13714](https://github.com/fastapi/fastapi/pull/13714) by [@Ashish-Pandey62](https://github.com/Ashish-Pandey62).
+* 📝 Update testing events documentation. PR [#13259](https://github.com/fastapi/fastapi/pull/13259) by [@z0z0r4](https://github.com/z0z0r4).
+* 📝 Remove obsolete `url` field in error responses in docs. PR [#13655](https://github.com/fastapi/fastapi/pull/13655) by [@Taoup](https://github.com/Taoup).
+* 📝 Bring the `scope` claim in line with the standard in `docs_src/security/tutorial005.py`. PR [#11189](https://github.com/fastapi/fastapi/pull/11189) by [@DurandA](https://github.com/DurandA).
+* 📝 Update TrustedHostMiddleware Documentation. PR [#11441](https://github.com/fastapi/fastapi/pull/11441) by [@soulee-dev](https://github.com/soulee-dev).
+* 📝 Remove links to site callbackhell.com that doesn't exist anymore. PR [#14006](https://github.com/fastapi/fastapi/pull/14006) by [@dennybiasiolli](https://github.com/dennybiasiolli).
+* 📝 Add permalinks to headers in English docs. PR [#13993](https://github.com/fastapi/fastapi/pull/13993) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 📝 Update `docs/en/docs/advanced/generate-clients.md`. PR [#13793](https://github.com/fastapi/fastapi/pull/13793) by [@mrlubos](https://github.com/mrlubos).
+* 📝 Add discussion template for new language translation requests. PR [#13535](https://github.com/fastapi/fastapi/pull/13535) by [@alejsdev](https://github.com/alejsdev).
+
+### Translations
+
+* 📝 Fix code include for Pydantic models example in `docs/zh/docs/python-types.md`. PR [#13997](https://github.com/fastapi/fastapi/pull/13997) by [@anfreshman](https://github.com/anfreshman).
+* 🌐 Update Portuguese Translation for `docs/pt/docs/async.md`. PR [#13863](https://github.com/fastapi/fastapi/pull/13863) by [@EdmilsonRodrigues](https://github.com/EdmilsonRodrigues).
+* 📝 Fix highlight line in `docs/ja/docs/tutorial/body.md`. PR [#13927](https://github.com/fastapi/fastapi/pull/13927) by [@KoyoMiyazaki](https://github.com/KoyoMiyazaki).
+* 🌐 Add Persian translation for `docs/fa/docs/environment-variables.md`. PR [#13923](https://github.com/fastapi/fastapi/pull/13923) by [@Mohammad222PR](https://github.com/Mohammad222PR).
+* 🌐 Add Persian translation for `docs/fa/docs/python-types.md`. PR [#13524](https://github.com/fastapi/fastapi/pull/13524) by [@Mohammad222PR](https://github.com/Mohammad222PR).
+* 🌐 Update Portuguese Translation for `docs/pt/docs/project-generation.md`. PR [#13875](https://github.com/fastapi/fastapi/pull/13875) by [@EdmilsonRodrigues](https://github.com/EdmilsonRodrigues).
+* 🌐 Add Persian translation for `docs/fa/docs/async.md`. PR [#13541](https://github.com/fastapi/fastapi/pull/13541) by [@Mohammad222PR](https://github.com/Mohammad222PR).
+* 🌐 Add Bangali translation for `docs/bn/about/index.md`. PR [#13882](https://github.com/fastapi/fastapi/pull/13882) by [@sajjadrahman56](https://github.com/sajjadrahman56).
+
+### Internal
+
+* ⬆ Bump pyjwt from 2.8.0 to 2.9.0. PR [#13960](https://github.com/fastapi/fastapi/pull/13960) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#14080](https://github.com/fastapi/fastapi/pull/14080) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ⬆ Bump actions/setup-python from 5 to 6. PR [#14042](https://github.com/fastapi/fastapi/pull/14042) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump actions/labeler from 5 to 6. PR [#14046](https://github.com/fastapi/fastapi/pull/14046) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#14056](https://github.com/fastapi/fastapi/pull/14056) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#14035](https://github.com/fastapi/fastapi/pull/14035) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.12.4 to 1.13.0. PR [#14041](https://github.com/fastapi/fastapi/pull/14041) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👥 Update FastAPI People - Contributors and Translators. PR [#14029](https://github.com/fastapi/fastapi/pull/14029) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Sponsors. PR [#14030](https://github.com/fastapi/fastapi/pull/14030) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI GitHub topic repositories. PR [#14031](https://github.com/fastapi/fastapi/pull/14031) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Experts. PR [#14034](https://github.com/fastapi/fastapi/pull/14034) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Detect and label merge conflicts on PRs automatically. PR [#14045](https://github.com/fastapi/fastapi/pull/14045) by [@svlandeg](https://github.com/svlandeg).
+* 🔧 Update sponsors: remove Platform.sh. PR [#14027](https://github.com/fastapi/fastapi/pull/14027) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors: remove Mobb. PR [#14026](https://github.com/fastapi/fastapi/pull/14026) by [@tiangolo](https://github.com/tiangolo).
+* 🛠️ Update `mkdocs_hooks` to handle headers with permalinks when building docs. PR [#14025](https://github.com/fastapi/fastapi/pull/14025) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#14016](https://github.com/fastapi/fastapi/pull/14016) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ⬆ Bump `mkdocs-macros-plugin` from 1.3.7 to 1.3.9. PR [#14003](https://github.com/fastapi/fastapi/pull/14003) by [@YuriiMotov](https://github.com/YuriiMotov).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13999](https://github.com/fastapi/fastapi/pull/13999) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13983](https://github.com/fastapi/fastapi/pull/13983) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ⬆ Bump actions/checkout from 4 to 5. PR [#13986](https://github.com/fastapi/fastapi/pull/13986) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔧 Update Speakeasy sponsor graphic. PR [#13971](https://github.com/fastapi/fastapi/pull/13971) by [@chailandau](https://github.com/chailandau).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13969](https://github.com/fastapi/fastapi/pull/13969) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ⬆ Bump actions/download-artifact from 4 to 5. PR [#13975](https://github.com/fastapi/fastapi/pull/13975) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👥 Update FastAPI People - Experts. PR [#13963](https://github.com/fastapi/fastapi/pull/13963) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump ruff from 0.11.2 to 0.12.7. PR [#13957](https://github.com/fastapi/fastapi/pull/13957) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump cairosvg from 2.7.1 to 2.8.2. PR [#13959](https://github.com/fastapi/fastapi/pull/13959) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pydantic-ai from 0.0.30 to 0.4.10. PR [#13958](https://github.com/fastapi/fastapi/pull/13958) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👥 Update FastAPI GitHub topic repositories. PR [#13962](https://github.com/fastapi/fastapi/pull/13962) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump mkdocs-material from 9.6.15 to 9.6.16. PR [#13961](https://github.com/fastapi/fastapi/pull/13961) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump tiangolo/latest-changes from 0.3.2 to 0.4.0. PR [#13952](https://github.com/fastapi/fastapi/pull/13952) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👥 Update FastAPI People - Sponsors. PR [#13956](https://github.com/fastapi/fastapi/pull/13956) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Contributors and Translators. PR [#13955](https://github.com/fastapi/fastapi/pull/13955) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors: Databento link and sponsors_badge data. PR [#13954](https://github.com/fastapi/fastapi/pull/13954) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors: Add Railway. PR [#13953](https://github.com/fastapi/fastapi/pull/13953) by [@tiangolo](https://github.com/tiangolo).
+* ⚒️ Update translate script, update prompt to minimize generated diff. PR [#13947](https://github.com/fastapi/fastapi/pull/13947) by [@YuriiMotov](https://github.com/YuriiMotov).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13943](https://github.com/fastapi/fastapi/pull/13943) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ⚒️ Tweak translate script and CI. PR [#13939](https://github.com/fastapi/fastapi/pull/13939) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Add CI to translate with LLMs. PR [#13937](https://github.com/fastapi/fastapi/pull/13937) by [@tiangolo](https://github.com/tiangolo).
+* ⚒️ Update translate script, show and update outdated translations. PR [#13933](https://github.com/fastapi/fastapi/pull/13933) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Refactor translate script with extra feedback (prints). PR [#13932](https://github.com/fastapi/fastapi/pull/13932) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Update translations script to remove old (removed) files. PR [#13928](https://github.com/fastapi/fastapi/pull/13928) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13894](https://github.com/fastapi/fastapi/pull/13894) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ⬆ Update httpx requirement to >=0.23.0,<0.29.0. PR [#13114](https://github.com/fastapi/fastapi/pull/13114) by [@yan12125](https://github.com/yan12125).
+* 🔧 Update sponsors: Add Mobb. PR [#13916](https://github.com/fastapi/fastapi/pull/13916) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Experts. PR [#13889](https://github.com/fastapi/fastapi/pull/13889) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Update FastAPI People sleep interval, use external settings. PR [#13888](https://github.com/fastapi/fastapi/pull/13888) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.116.1 (2025-07-11)
+
+### Upgrades
+
+* ⬆️ Upgrade Starlette supported version range to `>=0.40.0,<0.48.0`. PR [#13884](https://github.com/fastapi/fastapi/pull/13884) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Add notification about impending changes in Translations to `docs/en/docs/contributing.md`. PR [#13886](https://github.com/fastapi/fastapi/pull/13886) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+### Internal
+
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13871](https://github.com/fastapi/fastapi/pull/13871) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+
+## 0.116.0 (2025-07-07)
+
+### Features
+
+* ✨ Add support for deploying to FastAPI Cloud with `fastapi deploy`. PR [#13870](https://github.com/fastapi/fastapi/pull/13870) by [@tiangolo](https://github.com/tiangolo).
+
+Installing `fastapi[standard]` now includes `fastapi-cloud-cli`.
+
+This will allow you to deploy to [FastAPI Cloud](https://fastapicloud.com) with the `fastapi deploy` command.
+
+If you want to install `fastapi` with the standard dependencies but without `fastapi-cloud-cli`, you can install instead `fastapi[standard-no-fastapi-cloud-cli]`.
+
+### Translations
+
+* 🌐 Add Russian translation for `docs/ru/docs/advanced/response-directly.md`. PR [#13801](https://github.com/fastapi/fastapi/pull/13801) by [@NavesSapnis](https://github.com/NavesSapnis).
+* 🌐 Add Russian translation for `docs/ru/docs/advanced/additional-status-codes.md`. PR [#13799](https://github.com/fastapi/fastapi/pull/13799) by [@NavesSapnis](https://github.com/NavesSapnis).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-updates.md`. PR [#13804](https://github.com/fastapi/fastapi/pull/13804) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+
+### Internal
+
+* ⬆ Bump pillow from 11.1.0 to 11.3.0. PR [#13852](https://github.com/fastapi/fastapi/pull/13852) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👥 Update FastAPI People - Sponsors. PR [#13846](https://github.com/fastapi/fastapi/pull/13846) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI GitHub topic repositories. PR [#13848](https://github.com/fastapi/fastapi/pull/13848) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump mkdocs-material from 9.6.1 to 9.6.15. PR [#13849](https://github.com/fastapi/fastapi/pull/13849) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13843](https://github.com/fastapi/fastapi/pull/13843) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* 👥 Update FastAPI People - Contributors and Translators. PR [#13845](https://github.com/fastapi/fastapi/pull/13845) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.115.14 (2025-06-26)
+
+### Fixes
+
+* 🐛 Fix support for unions when using `Form`. PR [#13827](https://github.com/fastapi/fastapi/pull/13827) by [@patrick91](https://github.com/patrick91).
+
+### Docs
+
+* ✏️ Fix grammar mistake in `docs/en/docs/advanced/response-directly.md`. PR [#13800](https://github.com/fastapi/fastapi/pull/13800) by [@NavesSapnis](https://github.com/NavesSapnis).
+* 📝 Update Speakeasy URL to Speakeasy Sandbox. PR [#13697](https://github.com/fastapi/fastapi/pull/13697) by [@ndimares](https://github.com/ndimares).
+
+### Translations
+
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/response-model.md`. PR [#13792](https://github.com/fastapi/fastapi/pull/13792) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/security/index.md`. PR [#13805](https://github.com/fastapi/fastapi/pull/13805) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* ✏️ Fix typo in `docs/ja/docs/tutorial/encoder.md`. PR [#13815](https://github.com/fastapi/fastapi/pull/13815) by [@ruzia](https://github.com/ruzia).
+* ✏️ Fix typo in `docs/ja/docs/tutorial/handling-errors.md`. PR [#13814](https://github.com/fastapi/fastapi/pull/13814) by [@ruzia](https://github.com/ruzia).
+* ✏️ Fix typo in `docs/ja/docs/tutorial/body-fields.md`. PR [#13802](https://github.com/fastapi/fastapi/pull/13802) by [@ruzia](https://github.com/ruzia).
+* 🌐 Add Russian translation for `docs/ru/docs/advanced/index.md`. PR [#13797](https://github.com/fastapi/fastapi/pull/13797) by [@NavesSapnis](https://github.com/NavesSapnis).
+
+### Internal
+
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13823](https://github.com/fastapi/fastapi/pull/13823) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+
+## 0.115.13 (2025-06-17)
+
+### Fixes
+
+* 🐛 Fix truncating the model's description with form feed (`\f`) character for Pydantic V2. PR [#13698](https://github.com/fastapi/fastapi/pull/13698) by [@YuriiMotov](https://github.com/YuriiMotov).
+
+### Refactors
+
+* ✨ Add `refreshUrl` parameter in `OAuth2PasswordBearer`. PR [#11460](https://github.com/fastapi/fastapi/pull/11460) by [@snosratiershad](https://github.com/snosratiershad).
+* 🚸 Set format to password for fields `password` and `client_secret` in `OAuth2PasswordRequestForm`, make docs show password fields for passwords. PR [#11032](https://github.com/fastapi/fastapi/pull/11032) by [@Thodoris1999](https://github.com/Thodoris1999).
+* ✅ Simplify tests for `settings`. PR [#13505](https://github.com/fastapi/fastapi/pull/13505) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* ✅ Simplify tests for `validate_response_recursive`. PR [#13507](https://github.com/fastapi/fastapi/pull/13507) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+
+### Upgrades
+
+* ⬆️ Update ReDoc to version 2.x. PR [#9700](https://github.com/fastapi/fastapi/pull/9700) by [@joakimnordling](https://github.com/joakimnordling).
+
+### Docs
+
+* 📝 Add annotations to HTTP middleware example. PR [#11530](https://github.com/fastapi/fastapi/pull/11530) by [@Kilo59](https://github.com/Kilo59).
+* 📝 Clarify in CORS docs that wildcards and credentials are mutually exclusive. PR [#9829](https://github.com/fastapi/fastapi/pull/9829) by [@dfioravanti](https://github.com/dfioravanti).
+* ✏️ Fix typo in docstring. PR [#13532](https://github.com/fastapi/fastapi/pull/13532) by [@comp64](https://github.com/comp64).
+* 📝 Clarify guidance on using `async def` without `await`. PR [#13642](https://github.com/fastapi/fastapi/pull/13642) by [@swastikpradhan1999](https://github.com/swastikpradhan1999).
+* 📝 Update exclude-parameters-from-openapi documentation links. PR [#13600](https://github.com/fastapi/fastapi/pull/13600) by [@timonrieger](https://github.com/timonrieger).
+* 📝 Clarify the middleware execution order in docs. PR [#13699](https://github.com/fastapi/fastapi/pull/13699) by [@YuriiMotov](https://github.com/YuriiMotov).
+* 🍱 Update Drawio diagrams SVGs, single file per diagram, sans-serif font. PR [#13706](https://github.com/fastapi/fastapi/pull/13706) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update docs for "Help FastAPI", simplify and reduce "sponsor" section. PR [#13670](https://github.com/fastapi/fastapi/pull/13670) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Remove unnecessary bullet from docs. PR [#13641](https://github.com/fastapi/fastapi/pull/13641) by [@Adamowoc](https://github.com/Adamowoc).
+* ✏️ Fix syntax error in `docs/en/docs/tutorial/handling-errors.md`. PR [#13623](https://github.com/fastapi/fastapi/pull/13623) by [@gsheni](https://github.com/gsheni).
+* 📝 Fix typo in documentation. PR [#13599](https://github.com/fastapi/fastapi/pull/13599) by [@Taoup](https://github.com/Taoup).
+* 📝 Fix liblab client generation doc link. PR [#13571](https://github.com/fastapi/fastapi/pull/13571) by [@EFord36](https://github.com/EFord36).
+* ✏️ Fix talk information typo. PR [#13544](https://github.com/fastapi/fastapi/pull/13544) by [@blueswen](https://github.com/blueswen).
+* 📝 Add External Link: Taiwanese talk on FastAPI with observability . PR [#13527](https://github.com/fastapi/fastapi/pull/13527) by [@blueswen](https://github.com/blueswen).
+
+### Translations
+
+* 🌐 Add Russian Translation for `docs/ru/docs/advanced/response-change-status-code.md`. PR [#13791](https://github.com/fastapi/fastapi/pull/13791) by [@NavesSapnis](https://github.com/NavesSapnis).
+* 🌐 Add Persian translation for `docs/fa/docs/learn/index.md`. PR [#13518](https://github.com/fastapi/fastapi/pull/13518) by [@Mohammad222PR](https://github.com/Mohammad222PR).
+* 🌐 Add Korean translation for `docs/ko/docs/advanced/sub-applications.md`. PR [#4543](https://github.com/fastapi/fastapi/pull/4543) by [@NinaHwang](https://github.com/NinaHwang).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/schema-extra-example.md`. PR [#13769](https://github.com/fastapi/fastapi/pull/13769) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* ✏️ Remove redundant words in docs/zh/docs/python-types.md. PR [#13774](https://github.com/fastapi/fastapi/pull/13774) by [@CharleeWa](https://github.com/CharleeWa).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/query-param-models.md`. PR [#13748](https://github.com/fastapi/fastapi/pull/13748) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Bengali translation for `docs/bn/docs/environment-variables.md`. PR [#13629](https://github.com/fastapi/fastapi/pull/13629) by [@SakibSibly](https://github.com/SakibSibly).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/query-params-str-validations.md` page. PR [#13546](https://github.com/fastapi/fastapi/pull/13546) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/cookie-param-models.md`. PR [#13616](https://github.com/fastapi/fastapi/pull/13616) by [@EgorOnishchuk](https://github.com/EgorOnishchuk).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/extra-models.md`. PR [#13063](https://github.com/fastapi/fastapi/pull/13063) by [@timothy-jeong](https://github.com/timothy-jeong).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/path-params-numeric-validations.md` page. PR [#13548](https://github.com/fastapi/fastapi/pull/13548) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/middleware.md` page. PR [#13520](https://github.com/fastapi/fastapi/pull/13520) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/background-tasks.md` page. PR [#13502](https://github.com/fastapi/fastapi/pull/13502) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/cors.md` page. PR [#13519](https://github.com/fastapi/fastapi/pull/13519) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Update Korean translation for `docs/ko/docs/advanced/events.md`. PR [#13487](https://github.com/fastapi/fastapi/pull/13487) by [@bom1215](https://github.com/bom1215).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/handling-errors.md` page. PR [#13420](https://github.com/fastapi/fastapi/pull/13420) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/request-form-models.md`. PR [#13552](https://github.com/fastapi/fastapi/pull/13552) by [@EgorOnishchuk](https://github.com/EgorOnishchuk).
+* 📝 Fix internal anchor link in Spanish deployment docs. PR [#13737](https://github.com/fastapi/fastapi/pull/13737) by [@fabianfalon](https://github.com/fabianfalon).
+* 🌐 Update Korean translation for `docs/ko/docs/virtual-environments.md`. PR [#13630](https://github.com/fastapi/fastapi/pull/13630) by [@sungchan1](https://github.com/sungchan1).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/header-param-models.md`. PR [#13526](https://github.com/fastapi/fastapi/pull/13526) by [@minaton-ru](https://github.com/minaton-ru).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/index.md`. PR [#13374](https://github.com/fastapi/fastapi/pull/13374) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng).
+* 🌐 Update Chinese translation for `docs/zh/docs/deployment/manually.md`. PR [#13324](https://github.com/fastapi/fastapi/pull/13324) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng).
+* 🌐 Update Chinese translation for `docs/zh/docs/deployment/server-workers.md`. PR [#13292](https://github.com/fastapi/fastapi/pull/13292) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/first-steps.md`. PR [#13348](https://github.com/fastapi/fastapi/pull/13348) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng).
+
+### Internal
+
+* 🔨 Resolve Pydantic deprecation warnings in internal script. PR [#13696](https://github.com/fastapi/fastapi/pull/13696) by [@emmanuel-ferdman](https://github.com/emmanuel-ferdman).
+* 🔧 Update sponsors: remove Porter. PR [#13783](https://github.com/fastapi/fastapi/pull/13783) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13781](https://github.com/fastapi/fastapi/pull/13781) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13757](https://github.com/fastapi/fastapi/pull/13757) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ⬆ Bump griffe-typingdoc from 0.2.7 to 0.2.8. PR [#13751](https://github.com/fastapi/fastapi/pull/13751) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🍱 Update sponsors: Dribia badge size. PR [#13773](https://github.com/fastapi/fastapi/pull/13773) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors: add Dribia. PR [#13771](https://github.com/fastapi/fastapi/pull/13771) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump typer from 0.15.3 to 0.16.0. PR [#13752](https://github.com/fastapi/fastapi/pull/13752) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👥 Update FastAPI GitHub topic repositories. PR [#13754](https://github.com/fastapi/fastapi/pull/13754) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Sponsors. PR [#13750](https://github.com/fastapi/fastapi/pull/13750) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Contributors and Translators. PR [#13749](https://github.com/fastapi/fastapi/pull/13749) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13736](https://github.com/fastapi/fastapi/pull/13736) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* 🔧 Update sponsors: Add InterviewPal. PR [#13728](https://github.com/fastapi/fastapi/pull/13728) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Remove Google Analytics. PR [#13727](https://github.com/fastapi/fastapi/pull/13727) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors: remove MongoDB. PR [#13725](https://github.com/fastapi/fastapi/pull/13725) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13711](https://github.com/fastapi/fastapi/pull/13711) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* 🔧 Update sponsors: add Subtotal. PR [#13701](https://github.com/fastapi/fastapi/pull/13701) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors: remove deepset / Haystack. PR [#13700](https://github.com/fastapi/fastapi/pull/13700) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13688](https://github.com/fastapi/fastapi/pull/13688) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* 👥 Update FastAPI People - Experts. PR [#13671](https://github.com/fastapi/fastapi/pull/13671) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump typer from 0.12.5 to 0.15.3. PR [#13666](https://github.com/fastapi/fastapi/pull/13666) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump sqlmodel from 0.0.23 to 0.0.24. PR [#13665](https://github.com/fastapi/fastapi/pull/13665) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔧 Update Sponsors: Zuplo logo and alt text. PR [#13645](https://github.com/fastapi/fastapi/pull/13645) by [@martyndavies](https://github.com/martyndavies).
+* 👥 Update FastAPI GitHub topic repositories. PR [#13667](https://github.com/fastapi/fastapi/pull/13667) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update links for LinkedIn and bottom. PR [#13669](https://github.com/fastapi/fastapi/pull/13669) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors: remove Bump.sh and Coherence. PR [#13668](https://github.com/fastapi/fastapi/pull/13668) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Sponsors. PR [#13664](https://github.com/fastapi/fastapi/pull/13664) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Contributors and Translators. PR [#13662](https://github.com/fastapi/fastapi/pull/13662) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13656](https://github.com/fastapi/fastapi/pull/13656) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ✅ Use `inline-snapshot` to support different Pydantic versions in the test suite. PR [#12534](https://github.com/fastapi/fastapi/pull/12534) by [@15r10nk](https://github.com/15r10nk).
+* ⬆ Bump astral-sh/setup-uv from 5 to 6. PR [#13648](https://github.com/fastapi/fastapi/pull/13648) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13634](https://github.com/fastapi/fastapi/pull/13634) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13619](https://github.com/fastapi/fastapi/pull/13619) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13594](https://github.com/fastapi/fastapi/pull/13594) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* 👥 Update FastAPI People - Experts. PR [#13568](https://github.com/fastapi/fastapi/pull/13568) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI GitHub topic repositories. PR [#13565](https://github.com/fastapi/fastapi/pull/13565) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Sponsors. PR [#13559](https://github.com/fastapi/fastapi/pull/13559) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Contributors and Translators. PR [#13558](https://github.com/fastapi/fastapi/pull/13558) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump dirty-equals from 0.8.0 to 0.9.0. PR [#13561](https://github.com/fastapi/fastapi/pull/13561) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔧 Clean up `docs/en/mkdocs.yml` configuration file. PR [#13542](https://github.com/fastapi/fastapi/pull/13542) by [@svlandeg](https://github.com/svlandeg).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12986](https://github.com/fastapi/fastapi/pull/12986) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+
+## 0.115.12 (2025-03-23)
+
+### Fixes
+
+* 🐛 Fix `convert_underscores=False` for header Pydantic models. PR [#13515](https://github.com/fastapi/fastapi/pull/13515) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Update `docs/en/docs/tutorial/middleware.md`. PR [#13444](https://github.com/fastapi/fastapi/pull/13444) by [@Rishat-F](https://github.com/Rishat-F).
+* 👥 Update FastAPI People - Experts. PR [#13493](https://github.com/fastapi/fastapi/pull/13493) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/metadata.md` page. PR [#13459](https://github.com/fastapi/fastapi/pull/13459) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/response-status-code.md` page. PR [#13462](https://github.com/fastapi/fastapi/pull/13462) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/cookie-param-models.md` page. PR [#13460](https://github.com/fastapi/fastapi/pull/13460) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/header-param-models.md` page. PR [#13461](https://github.com/fastapi/fastapi/pull/13461) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Japanese translation for `docs/ja/docs/virtual-environments.md`. PR [#13304](https://github.com/fastapi/fastapi/pull/13304) by [@k94-ishi](https://github.com/k94-ishi).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/security/oauth2-jwt.md`. PR [#13333](https://github.com/fastapi/fastapi/pull/13333) by [@yes0ng](https://github.com/yes0ng).
+* 🌐 Add Vietnamese translation for `docs/vi/docs/deployment/cloud.md`. PR [#13407](https://github.com/fastapi/fastapi/pull/13407) by [@ptt3199](https://github.com/ptt3199).
+
+### Internal
+
+* ⬆ Bump pydantic-ai from 0.0.15 to 0.0.30. PR [#13438](https://github.com/fastapi/fastapi/pull/13438) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump sqlmodel from 0.0.22 to 0.0.23. PR [#13437](https://github.com/fastapi/fastapi/pull/13437) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump black from 24.10.0 to 25.1.0. PR [#13436](https://github.com/fastapi/fastapi/pull/13436) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump ruff to 0.9.4. PR [#13299](https://github.com/fastapi/fastapi/pull/13299) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔧 Update sponsors: pause TestDriven. PR [#13446](https://github.com/fastapi/fastapi/pull/13446) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.115.11 (2025-03-01)
+
+### Fixes
+
+* 🐛 Add docs examples and tests (support) for `Annotated` custom validations, like `AfterValidator`, revert [#13440](https://github.com/fastapi/fastapi/pull/13440). PR [#13442](https://github.com/fastapi/fastapi/pull/13442) by [@tiangolo](https://github.com/tiangolo).
+ * New docs: [Query Parameters and String Validations - Custom Validation](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#custom-validation).
+
+### Translations
+
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/middleware.md`. PR [#13412](https://github.com/fastapi/fastapi/pull/13412) by [@alv2017](https://github.com/alv2017).
+
+### Internal
+
+* 👥 Update FastAPI GitHub topic repositories. PR [#13439](https://github.com/fastapi/fastapi/pull/13439) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Contributors and Translators. PR [#13432](https://github.com/fastapi/fastapi/pull/13432) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Sponsors. PR [#13433](https://github.com/fastapi/fastapi/pull/13433) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.115.10 (2025-02-28)
+
+### Fixes
+
+* ♻️ Update internal annotation usage for compatibility with Pydantic 2.11. PR [#13314](https://github.com/fastapi/fastapi/pull/13314) by [@Viicos](https://github.com/Viicos).
+
+### Upgrades
+
+* ⬆️ Bump Starlette to allow up to 0.46.0: `>=0.40.0,<0.47.0`. PR [#13426](https://github.com/fastapi/fastapi/pull/13426) by [@musicinmybrain](https://github.com/musicinmybrain).
+
+### Translations
+
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/debugging.md`. PR [#13370](https://github.com/fastapi/fastapi/pull/13370) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/query-params.md`. PR [#13362](https://github.com/fastapi/fastapi/pull/13362) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/path-params.md`. PR [#13354](https://github.com/fastapi/fastapi/pull/13354) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/cookie-param-models.md`. PR [#13330](https://github.com/fastapi/fastapi/pull/13330) by [@k94-ishi](https://github.com/k94-ishi).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-multiple-params.md`. PR [#13408](https://github.com/fastapi/fastapi/pull/13408) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/query-param-models.md`. PR [#13323](https://github.com/fastapi/fastapi/pull/13323) by [@k94-ishi](https://github.com/k94-ishi).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-nested-models.md`. PR [#13409](https://github.com/fastapi/fastapi/pull/13409) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Vietnamese translation for `docs/vi/docs/deployment/versions.md`. PR [#13406](https://github.com/fastapi/fastapi/pull/13406) by [@ptt3199](https://github.com/ptt3199).
+* 🌐 Add Vietnamese translation for `docs/vi/docs/deployment/index.md`. PR [#13405](https://github.com/fastapi/fastapi/pull/13405) by [@ptt3199](https://github.com/ptt3199).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-forms.md`. PR [#13383](https://github.com/fastapi/fastapi/pull/13383) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/testing.md`. PR [#13371](https://github.com/fastapi/fastapi/pull/13371) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+
+## 0.115.9 (2025-02-27)
+
+### Fixes
+
+* 🐛 Ensure that `HTTPDigest` only raises an exception when `auto_error is True`. PR [#2939](https://github.com/fastapi/fastapi/pull/2939) by [@arthurio](https://github.com/arthurio).
+
+### Refactors
+
+* ✅ Simplify tests for `query_params_str_validations`. PR [#13218](https://github.com/fastapi/fastapi/pull/13218) by [@alv2017](https://github.com/alv2017).
+* ✅ Simplify tests for `app_testing`. PR [#13220](https://github.com/fastapi/fastapi/pull/13220) by [@alv2017](https://github.com/alv2017).
+* ✅ Simplify tests for `dependency_testing`. PR [#13223](https://github.com/fastapi/fastapi/pull/13223) by [@alv2017](https://github.com/alv2017).
+
+### Docs
+
+* 🍱 Update sponsors: CodeRabbit logo. PR [#13424](https://github.com/fastapi/fastapi/pull/13424) by [@tiangolo](https://github.com/tiangolo).
+* 🩺 Unify the badges across all tutorial translations. PR [#13329](https://github.com/fastapi/fastapi/pull/13329) by [@svlandeg](https://github.com/svlandeg).
+* 📝 Fix typos in virtual environments documentation. PR [#13396](https://github.com/fastapi/fastapi/pull/13396) by [@bullet-ant](https://github.com/bullet-ant).
+* 🐛 Fix issue with Swagger theme change example in the official tutorial. PR [#13289](https://github.com/fastapi/fastapi/pull/13289) by [@Zerohertz](https://github.com/Zerohertz).
+* 📝 Add more precise description of HTTP status code range in docs. PR [#13347](https://github.com/fastapi/fastapi/pull/13347) by [@DanielYang59](https://github.com/DanielYang59).
+* 🔥 Remove manual type annotations in JWT tutorial to avoid typing expectations (JWT doesn't provide more types). PR [#13378](https://github.com/fastapi/fastapi/pull/13378) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update docs for Query Params and String Validations, remove obsolete Ellipsis docs (`...`). PR [#13377](https://github.com/fastapi/fastapi/pull/13377) by [@tiangolo](https://github.com/tiangolo).
+* ✏️ Remove duplicate title in docs `body-multiple-params`. PR [#13345](https://github.com/fastapi/fastapi/pull/13345) by [@DanielYang59](https://github.com/DanielYang59).
+* 📝 Fix test badge. PR [#13313](https://github.com/fastapi/fastapi/pull/13313) by [@esadek](https://github.com/esadek).
+
+### Translations
+
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/header-params.md`. PR [#13381](https://github.com/fastapi/fastapi/pull/13381) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-files.md`. PR [#13395](https://github.com/fastapi/fastapi/pull/13395) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-form-models.md`. PR [#13384](https://github.com/fastapi/fastapi/pull/13384) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-forms-and-files.md`. PR [#13386](https://github.com/fastapi/fastapi/pull/13386) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Update Korean translation for `docs/ko/docs/help-fastapi.md`. PR [#13262](https://github.com/fastapi/fastapi/pull/13262) by [@Zerohertz](https://github.com/Zerohertz).
+* 🌐 Add Korean translation for `docs/ko/docs/advanced/custom-response.md`. PR [#13265](https://github.com/fastapi/fastapi/pull/13265) by [@11kkw](https://github.com/11kkw).
+* 🌐 Update Korean translation for `docs/ko/docs/tutorial/security/simple-oauth2.md`. PR [#13335](https://github.com/fastapi/fastapi/pull/13335) by [@yes0ng](https://github.com/yes0ng).
+* 🌐 Add Russian translation for `docs/ru/docs/advanced/response-cookies.md`. PR [#13327](https://github.com/fastapi/fastapi/pull/13327) by [@Stepakinoyan](https://github.com/Stepakinoyan).
+* 🌐 Add Vietnamese translation for `docs/vi/docs/tutorial/static-files.md`. PR [#11291](https://github.com/fastapi/fastapi/pull/11291) by [@ptt3199](https://github.com/ptt3199).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#13257](https://github.com/fastapi/fastapi/pull/13257) by [@11kkw](https://github.com/11kkw).
+* 🌐 Add Vietnamese translation for `docs/vi/docs/virtual-environments.md`. PR [#13282](https://github.com/fastapi/fastapi/pull/13282) by [@ptt3199](https://github.com/ptt3199).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/static-files.md`. PR [#13285](https://github.com/fastapi/fastapi/pull/13285) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Vietnamese translation for `docs/vi/docs/environment-variables.md`. PR [#13287](https://github.com/fastapi/fastapi/pull/13287) by [@ptt3199](https://github.com/ptt3199).
+* 🌐 Add Vietnamese translation for `docs/vi/docs/fastapi-cli.md`. PR [#13294](https://github.com/fastapi/fastapi/pull/13294) by [@ptt3199](https://github.com/ptt3199).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/features.md`. PR [#13308](https://github.com/fastapi/fastapi/pull/13308) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/learn/index.md`. PR [#13306](https://github.com/fastapi/fastapi/pull/13306) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
+* 🌐 Update Portuguese Translation for `docs/pt/docs/deployment/https.md`. PR [#13317](https://github.com/fastapi/fastapi/pull/13317) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
+* 🌐 Update Portuguese Translation for `docs/pt/docs/index.md`. PR [#13328](https://github.com/fastapi/fastapi/pull/13328) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Russian translation for `docs/ru/docs/advanced/websockets.md`. PR [#13279](https://github.com/fastapi/fastapi/pull/13279) by [@Rishat-F](https://github.com/Rishat-F).
+
+### Internal
+
+* ✅ Fix a minor bug in the test `tests/test_modules_same_name_body/test_main.py`. PR [#13411](https://github.com/fastapi/fastapi/pull/13411) by [@alv2017](https://github.com/alv2017).
+* 👷 Use `wrangler-action` v3. PR [#13415](https://github.com/fastapi/fastapi/pull/13415) by [@joakimnordling](https://github.com/joakimnordling).
+* 🔧 Update sponsors: add CodeRabbit. PR [#13402](https://github.com/fastapi/fastapi/pull/13402) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update team: Add Ludovico. PR [#13390](https://github.com/fastapi/fastapi/pull/13390) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors: Add LambdaTest. PR [#13389](https://github.com/fastapi/fastapi/pull/13389) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump cloudflare/wrangler-action from 3.13 to 3.14. PR [#13350](https://github.com/fastapi/fastapi/pull/13350) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump mkdocs-material from 9.5.18 to 9.6.1. PR [#13301](https://github.com/fastapi/fastapi/pull/13301) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pillow from 11.0.0 to 11.1.0. PR [#13300](https://github.com/fastapi/fastapi/pull/13300) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👥 Update FastAPI People - Sponsors. PR [#13295](https://github.com/fastapi/fastapi/pull/13295) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Experts. PR [#13303](https://github.com/fastapi/fastapi/pull/13303) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI GitHub topic repositories. PR [#13302](https://github.com/fastapi/fastapi/pull/13302) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People - Contributors and Translators. PR [#13293](https://github.com/fastapi/fastapi/pull/13293) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump inline-snapshot from 0.18.1 to 0.19.3. PR [#13298](https://github.com/fastapi/fastapi/pull/13298) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔧 Update sponsors, add Permit. PR [#13288](https://github.com/fastapi/fastapi/pull/13288) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.115.8 (2025-01-30)
+
+### Fixes
+
+* 🐛 Fix `OAuth2PasswordRequestForm` and `OAuth2PasswordRequestFormStrict` fixed `grant_type` "password" RegEx. PR [#9783](https://github.com/fastapi/fastapi/pull/9783) by [@skarfie123](https://github.com/skarfie123).
+
+### Refactors
+
+* ✅ Simplify tests for body_multiple_params . PR [#13237](https://github.com/fastapi/fastapi/pull/13237) by [@alejsdev](https://github.com/alejsdev).
+* ♻️ Move duplicated code portion to a static method in the `APIKeyBase` super class. PR [#3142](https://github.com/fastapi/fastapi/pull/3142) by [@ShahriyarR](https://github.com/ShahriyarR).
+* ✅ Simplify tests for request_files. PR [#13182](https://github.com/fastapi/fastapi/pull/13182) by [@alejsdev](https://github.com/alejsdev).
+
+### Docs
+
+* 📝 Change the word "unwrap" to "unpack" in `docs/en/docs/tutorial/extra-models.md`. PR [#13061](https://github.com/fastapi/fastapi/pull/13061) by [@timothy-jeong](https://github.com/timothy-jeong).
+* 📝 Update Request Body's `tutorial002` to deal with `tax=0` case. PR [#13230](https://github.com/fastapi/fastapi/pull/13230) by [@togogh](https://github.com/togogh).
+* 👥 Update FastAPI People - Experts. PR [#13269](https://github.com/fastapi/fastapi/pull/13269) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Add Japanese translation for `docs/ja/docs/environment-variables.md`. PR [#13226](https://github.com/fastapi/fastapi/pull/13226) by [@k94-ishi](https://github.com/k94-ishi).
+* 🌐 Add Russian translation for `docs/ru/docs/advanced/async-tests.md`. PR [#13227](https://github.com/fastapi/fastapi/pull/13227) by [@Rishat-F](https://github.com/Rishat-F).
+* 🌐 Update Russian translation for `docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#13252](https://github.com/fastapi/fastapi/pull/13252) by [@Rishat-F](https://github.com/Rishat-F).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/bigger-applications.md`. PR [#13154](https://github.com/fastapi/fastapi/pull/13154) by [@alv2017](https://github.com/alv2017).
+
+### Internal
+
+* ⬆️ Add support for Python 3.13. PR [#13274](https://github.com/fastapi/fastapi/pull/13274) by [@tiangolo](https://github.com/tiangolo).
+* ⬆️ Upgrade AnyIO max version for tests, new range: `>=3.2.1,<5.0.0`. PR [#13273](https://github.com/fastapi/fastapi/pull/13273) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update Sponsors badges. PR [#13271](https://github.com/fastapi/fastapi/pull/13271) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Fix `notify_translations.py` empty env var handling for PR label events vs workflow_dispatch. PR [#13272](https://github.com/fastapi/fastapi/pull/13272) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Refactor and move `scripts/notify_translations.py`, no need for a custom GitHub Action. PR [#13270](https://github.com/fastapi/fastapi/pull/13270) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Update FastAPI People Experts script, refactor and optimize data fetching to handle rate limits. PR [#13267](https://github.com/fastapi/fastapi/pull/13267) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.12.3 to 1.12.4. PR [#13251](https://github.com/fastapi/fastapi/pull/13251) by [@dependabot[bot]](https://github.com/apps/dependabot).
+
+## 0.115.7 (2025-01-22)
+
+### Upgrades
+
+* ⬆️ Upgrade `python-multipart` to >=0.0.18. PR [#13219](https://github.com/fastapi/fastapi/pull/13219) by [@DanielKusyDev](https://github.com/DanielKusyDev).
+* ⬆️ Bump Starlette to allow up to 0.45.0: `>=0.40.0,<0.46.0`. PR [#13117](https://github.com/fastapi/fastapi/pull/13117) by [@Kludex](https://github.com/Kludex).
+* ⬆️ Upgrade `jinja2` to >=3.1.5. PR [#13194](https://github.com/fastapi/fastapi/pull/13194) by [@DanielKusyDev](https://github.com/DanielKusyDev).
+
+### Refactors
+
+* ✅ Simplify tests for websockets. PR [#13202](https://github.com/fastapi/fastapi/pull/13202) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for request_form_models . PR [#13183](https://github.com/fastapi/fastapi/pull/13183) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for separate_openapi_schemas. PR [#13201](https://github.com/fastapi/fastapi/pull/13201) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for security. PR [#13200](https://github.com/fastapi/fastapi/pull/13200) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for schema_extra_example. PR [#13197](https://github.com/fastapi/fastapi/pull/13197) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for request_model. PR [#13195](https://github.com/fastapi/fastapi/pull/13195) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for request_forms_and_files. PR [#13185](https://github.com/fastapi/fastapi/pull/13185) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for request_forms. PR [#13184](https://github.com/fastapi/fastapi/pull/13184) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for path_query_params. PR [#13181](https://github.com/fastapi/fastapi/pull/13181) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for path_operation_configurations. PR [#13180](https://github.com/fastapi/fastapi/pull/13180) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for header_params. PR [#13179](https://github.com/fastapi/fastapi/pull/13179) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for extra_models. PR [#13178](https://github.com/fastapi/fastapi/pull/13178) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for extra_data_types. PR [#13177](https://github.com/fastapi/fastapi/pull/13177) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for cookie_params. PR [#13176](https://github.com/fastapi/fastapi/pull/13176) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for dependencies. PR [#13174](https://github.com/fastapi/fastapi/pull/13174) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for body_updates. PR [#13172](https://github.com/fastapi/fastapi/pull/13172) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for body_nested_models. PR [#13171](https://github.com/fastapi/fastapi/pull/13171) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for body_multiple_params. PR [#13170](https://github.com/fastapi/fastapi/pull/13170) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for body_fields. PR [#13169](https://github.com/fastapi/fastapi/pull/13169) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for body. PR [#13168](https://github.com/fastapi/fastapi/pull/13168) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for bigger_applications. PR [#13167](https://github.com/fastapi/fastapi/pull/13167) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for background_tasks. PR [#13166](https://github.com/fastapi/fastapi/pull/13166) by [@alejsdev](https://github.com/alejsdev).
+* ✅ Simplify tests for additional_status_codes. PR [#13149](https://github.com/fastapi/fastapi/pull/13149) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* ✏️ Update Strawberry integration docs. PR [#13155](https://github.com/fastapi/fastapi/pull/13155) by [@kinuax](https://github.com/kinuax).
+* 🔥 Remove unused Peewee tutorial files. PR [#13158](https://github.com/fastapi/fastapi/pull/13158) by [@alejsdev](https://github.com/alejsdev).
+* 📝 Update image in body-nested-model docs. PR [#11063](https://github.com/fastapi/fastapi/pull/11063) by [@untilhamza](https://github.com/untilhamza).
+* 📝 Update `fastapi-cli` UI examples in docs. PR [#13107](https://github.com/fastapi/fastapi/pull/13107) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng).
+* 👷 Add new GitHub Action to update contributors, translators, and translation reviewers. PR [#13136](https://github.com/fastapi/fastapi/pull/13136) by [@tiangolo](https://github.com/tiangolo).
+* ✏️ Fix typo in `docs/en/docs/virtual-environments.md`. PR [#13124](https://github.com/fastapi/fastapi/pull/13124) by [@tiangolo](https://github.com/tiangolo).
+* ✏️ Fix error in `docs/en/docs/contributing.md`. PR [#12899](https://github.com/fastapi/fastapi/pull/12899) by [@kingsubin](https://github.com/kingsubin).
+* 📝 Minor corrections in `docs/en/docs/tutorial/sql-databases.md`. PR [#13081](https://github.com/fastapi/fastapi/pull/13081) by [@alv2017](https://github.com/alv2017).
+* 📝 Update includes in `docs/ru/docs/tutorial/query-param-models.md`. PR [#12994](https://github.com/fastapi/fastapi/pull/12994) by [@alejsdev](https://github.com/alejsdev).
+* ✏️ Fix typo in README installation instructions. PR [#13011](https://github.com/fastapi/fastapi/pull/13011) by [@dave-hay](https://github.com/dave-hay).
+* 📝 Update docs for `fastapi-cli`. PR [#13031](https://github.com/fastapi/fastapi/pull/13031) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Update Portuguese Translation for `docs/pt/docs/tutorial/request-forms.md`. PR [#13216](https://github.com/fastapi/fastapi/pull/13216) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
+* 🌐 Update Portuguese translation for `docs/pt/docs/advanced/settings.md`. PR [#13209](https://github.com/fastapi/fastapi/pull/13209) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/oauth2-jwt.md`. PR [#13205](https://github.com/fastapi/fastapi/pull/13205) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Indonesian translation for `docs/id/docs/index.md`. PR [#13191](https://github.com/fastapi/fastapi/pull/13191) by [@gerry-sabar](https://github.com/gerry-sabar).
+* 🌐 Add Indonesian translation for `docs/id/docs/tutorial/static-files.md`. PR [#13092](https://github.com/fastapi/fastapi/pull/13092) by [@guspan-tanadi](https://github.com/guspan-tanadi).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/get-current-user.md`. PR [#13188](https://github.com/fastapi/fastapi/pull/13188) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Remove Wrong Portuguese translations location for `docs/pt/docs/advanced/benchmarks.md`. PR [#13187](https://github.com/fastapi/fastapi/pull/13187) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Update Portuguese translations. PR [#13156](https://github.com/fastapi/fastapi/pull/13156) by [@nillvitor](https://github.com/nillvitor).
+* 🌐 Update Russian translation for `docs/ru/docs/tutorial/security/first-steps.md`. PR [#13159](https://github.com/fastapi/fastapi/pull/13159) by [@Yarous](https://github.com/Yarous).
+* ✏️ Delete unnecessary backspace in `docs/ja/docs/tutorial/path-params-numeric-validations.md`. PR [#12238](https://github.com/fastapi/fastapi/pull/12238) by [@FakeDocument](https://github.com/FakeDocument).
+* 🌐 Update Chinese translation for `docs/zh/docs/fastapi-cli.md`. PR [#13102](https://github.com/fastapi/fastapi/pull/13102) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng).
+* 🌐 Add new Spanish translations for all docs with new LLM-assisted system using PydanticAI. PR [#13122](https://github.com/fastapi/fastapi/pull/13122) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update existing Spanish translations using the new LLM-assisted system using PydanticAI. PR [#13118](https://github.com/fastapi/fastapi/pull/13118) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update Chinese translation for `docs/zh/docs/advanced/security/oauth2-scopes.md`. PR [#13110](https://github.com/fastapi/fastapi/pull/13110) by [@ChenPu2002](https://github.com/ChenPu2002).
+* 🌐 Add Indonesian translation for `docs/id/docs/tutorial/path-params.md`. PR [#13086](https://github.com/fastapi/fastapi/pull/13086) by [@gerry-sabar](https://github.com/gerry-sabar).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/sql-databases.md`. PR [#13093](https://github.com/fastapi/fastapi/pull/13093) by [@GeumBinLee](https://github.com/GeumBinLee).
+* 🌐 Update Chinese translation for `docs/zh/docs/async.md`. PR [#13095](https://github.com/fastapi/fastapi/pull/13095) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/openapi-webhooks.md`. PR [#13091](https://github.com/fastapi/fastapi/pull/13091) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/async-tests.md`. PR [#13074](https://github.com/fastapi/fastapi/pull/13074) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/fastapi-cli.md`. PR [#13020](https://github.com/fastapi/fastapi/pull/13020) by [@ykertytsky](https://github.com/ykertytsky).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/events.md`. PR [#12512](https://github.com/fastapi/fastapi/pull/12512) by [@ZhibangYue](https://github.com/ZhibangYue).
+* 🌐 Add Russian translation for `/docs/ru/docs/tutorial/sql-databases.md`. PR [#13079](https://github.com/fastapi/fastapi/pull/13079) by [@alv2017](https://github.com/alv2017).
+* 🌐 Update Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#13066](https://github.com/fastapi/fastapi/pull/13066) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng).
+* 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/tutorial/index.md`. PR [#13075](https://github.com/fastapi/fastapi/pull/13075) by [@codingjenny](https://github.com/codingjenny).
+* 🌐 Add Chinese translation for `docs/zh/docs/tutorial/sql-databases.md`. PR [#13051](https://github.com/fastapi/fastapi/pull/13051) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params-str-validations.md`. PR [#12928](https://github.com/fastapi/fastapi/pull/12928) by [@Vincy1230](https://github.com/Vincy1230).
+* 🌐 Add Chinese translation for `docs/zh/docs/tutorial/header-param-models.md`. PR [#13040](https://github.com/fastapi/fastapi/pull/13040) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/path-params.md`. PR [#12926](https://github.com/fastapi/fastapi/pull/12926) by [@Vincy1230](https://github.com/Vincy1230).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/first-steps.md`. PR [#12923](https://github.com/fastapi/fastapi/pull/12923) by [@Vincy1230](https://github.com/Vincy1230).
+* 🌐 Update Russian translation for `docs/ru/docs/deployment/docker.md`. PR [#13048](https://github.com/fastapi/fastapi/pull/13048) by [@anklav24](https://github.com/anklav24).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/generate-clients.md`. PR [#13030](https://github.com/fastapi/fastapi/pull/13030) by [@vitumenezes](https://github.com/vitumenezes).
+* 🌐 Add Indonesian translation for `docs/id/docs/tutorial/first-steps.md`. PR [#13042](https://github.com/fastapi/fastapi/pull/13042) by [@gerry-sabar](https://github.com/gerry-sabar).
+* 🌐 Add Chinese translation for `docs/zh/docs/tutorial/cookie-param-models.md`. PR [#13038](https://github.com/fastapi/fastapi/pull/13038) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng).
+* 🌐 Add Chinese translation for `docs/zh/docs/tutorial/request-form-models.md`. PR [#13045](https://github.com/fastapi/fastapi/pull/13045) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng).
+* 🌐 Add Russian translation for `docs/ru/docs/virtual-environments.md`. PR [#13026](https://github.com/fastapi/fastapi/pull/13026) by [@alv2017](https://github.com/alv2017).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/testing.md`. PR [#12968](https://github.com/fastapi/fastapi/pull/12968) by [@jts8257](https://github.com/jts8257).
+* 🌐 Add Korean translation for `docs/ko/docs/advanced/async-test.md`. PR [#12918](https://github.com/fastapi/fastapi/pull/12918) by [@icehongssii](https://github.com/icehongssii).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/security/oauth2-jwt.md`. PR [#10601](https://github.com/fastapi/fastapi/pull/10601) by [@AlertRED](https://github.com/AlertRED).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/security/simple-oauth2.md`. PR [#10599](https://github.com/fastapi/fastapi/pull/10599) by [@AlertRED](https://github.com/AlertRED).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/security/get-current-user.md`. PR [#10594](https://github.com/fastapi/fastapi/pull/10594) by [@AlertRED](https://github.com/AlertRED).
+* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/features.md`. PR [#12441](https://github.com/fastapi/fastapi/pull/12441) by [@codingjenny](https://github.com/codingjenny).
+* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/virtual-environments.md`. PR [#12791](https://github.com/fastapi/fastapi/pull/12791) by [@Vincy1230](https://github.com/Vincy1230).
+* 🌐 Add Korean translation for `docs/ko/docs/advanced/templates.md`. PR [#12726](https://github.com/fastapi/fastapi/pull/12726) by [@Heumhub](https://github.com/Heumhub).
+* 🌐 Add Russian translation for `docs/ru/docs/fastapi-cli.md`. PR [#13041](https://github.com/fastapi/fastapi/pull/13041) by [@alv2017](https://github.com/alv2017).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/cookie-param-models.md`. PR [#13000](https://github.com/fastapi/fastapi/pull/13000) by [@hard-coders](https://github.com/hard-coders).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/header-param-models.md`. PR [#13001](https://github.com/fastapi/fastapi/pull/13001) by [@hard-coders](https://github.com/hard-coders).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/request-form-models.md`. PR [#13002](https://github.com/fastapi/fastapi/pull/13002) by [@hard-coders](https://github.com/hard-coders).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/request-forms.md`. PR [#13003](https://github.com/fastapi/fastapi/pull/13003) by [@hard-coders](https://github.com/hard-coders).
+* 🌐 Add Korean translation for `docs/ko/docs/resources/index.md`. PR [#13004](https://github.com/fastapi/fastapi/pull/13004) by [@hard-coders](https://github.com/hard-coders).
+* 🌐 Add Korean translation for `docs/ko/docs/how-to/configure-swagger-ui.md`. PR [#12898](https://github.com/fastapi/fastapi/pull/12898) by [@nahyunkeem](https://github.com/nahyunkeem).
+* 🌐 Add Korean translation to `docs/ko/docs/advanced/additional-status-codes.md`. PR [#12715](https://github.com/fastapi/fastapi/pull/12715) by [@nahyunkeem](https://github.com/nahyunkeem).
+* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/tutorial/first-steps.md`. PR [#12467](https://github.com/fastapi/fastapi/pull/12467) by [@codingjenny](https://github.com/codingjenny).
+
+### Internal
+
+* 🔧 Add Pydantic 2 trove classifier. PR [#13199](https://github.com/fastapi/fastapi/pull/13199) by [@johnthagen](https://github.com/johnthagen).
+* 👥 Update FastAPI People - Sponsors. PR [#13231](https://github.com/fastapi/fastapi/pull/13231) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Refactor FastAPI People Sponsors to use 2 tokens. PR [#13228](https://github.com/fastapi/fastapi/pull/13228) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update token for FastAPI People - Sponsors. PR [#13225](https://github.com/fastapi/fastapi/pull/13225) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Add independent CI automation for FastAPI People - Sponsors. PR [#13221](https://github.com/fastapi/fastapi/pull/13221) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Add retries to Smokeshow. PR [#13151](https://github.com/fastapi/fastapi/pull/13151) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update Speakeasy sponsor graphic. PR [#13147](https://github.com/fastapi/fastapi/pull/13147) by [@chailandau](https://github.com/chailandau).
+* 👥 Update FastAPI GitHub topic repositories. PR [#13146](https://github.com/fastapi/fastapi/pull/13146) by [@tiangolo](https://github.com/tiangolo).
+* 👷♀️ Add script for GitHub Topic Repositories and update External Links. PR [#13135](https://github.com/fastapi/fastapi/pull/13135) by [@alejsdev](https://github.com/alejsdev).
+* 👥 Update FastAPI People - Contributors and Translators. PR [#13145](https://github.com/fastapi/fastapi/pull/13145) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump markdown-include-variants from 0.0.3 to 0.0.4. PR [#13129](https://github.com/fastapi/fastapi/pull/13129) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump inline-snapshot from 0.14.0 to 0.18.1. PR [#13132](https://github.com/fastapi/fastapi/pull/13132) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump mkdocs-macros-plugin from 1.0.5 to 1.3.7. PR [#13133](https://github.com/fastapi/fastapi/pull/13133) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔨 Add internal scripts to generate language translations with PydanticAI, include Spanish prompt. PR [#13123](https://github.com/fastapi/fastapi/pull/13123) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump astral-sh/setup-uv from 4 to 5. PR [#13096](https://github.com/fastapi/fastapi/pull/13096) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔧 Update sponsors: rename CryptAPI to BlockBee. PR [#13078](https://github.com/fastapi/fastapi/pull/13078) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.12.2 to 1.12.3. PR [#13055](https://github.com/fastapi/fastapi/pull/13055) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump types-ujson from 5.7.0.1 to 5.10.0.20240515. PR [#13018](https://github.com/fastapi/fastapi/pull/13018) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump black from 24.3.0 to 24.10.0. PR [#13014](https://github.com/fastapi/fastapi/pull/13014) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump inline-snapshot from 0.13.0 to 0.14.0. PR [#13017](https://github.com/fastapi/fastapi/pull/13017) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump dirty-equals from 0.6.0 to 0.8.0. PR [#13015](https://github.com/fastapi/fastapi/pull/13015) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump cloudflare/wrangler-action from 3.12 to 3.13. PR [#12996](https://github.com/fastapi/fastapi/pull/12996) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump astral-sh/setup-uv from 3 to 4. PR [#12982](https://github.com/fastapi/fastapi/pull/12982) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔧 Remove duplicate actions/checkout in `notify-translations.yml`. PR [#12915](https://github.com/fastapi/fastapi/pull/12915) by [@tinyboxvk](https://github.com/tinyboxvk).
+* 🔧 Update team members. PR [#13033](https://github.com/fastapi/fastapi/pull/13033) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update sponsors: remove Codacy. PR [#13032](https://github.com/fastapi/fastapi/pull/13032) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.115.6 (2024-12-03)
+
+### Fixes
+
+* 🐛 Preserve traceback when an exception is raised in sync dependency with `yield`. PR [#5823](https://github.com/fastapi/fastapi/pull/5823) by [@sombek](https://github.com/sombek).
+
+### Refactors
+
+* ♻️ Update tests and internals for compatibility with Pydantic >=2.10. PR [#12971](https://github.com/fastapi/fastapi/pull/12971) by [@tamird](https://github.com/tamird).
+
+### Docs
+
+* 📝 Update includes format in docs with an automated script. PR [#12950](https://github.com/fastapi/fastapi/pull/12950) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update includes for `docs/de/docs/advanced/using-request-directly.md`. PR [#12685](https://github.com/fastapi/fastapi/pull/12685) by [@alissadb](https://github.com/alissadb).
+* 📝 Update includes for `docs/de/docs/how-to/conditional-openapi.md`. PR [#12689](https://github.com/fastapi/fastapi/pull/12689) by [@alissadb](https://github.com/alissadb).
+
+### Translations
+
+* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/async.md`. PR [#12990](https://github.com/fastapi/fastapi/pull/12990) by [@ILoveSorasakiHina](https://github.com/ILoveSorasakiHina).
+* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/tutorial/query-param-models.md`. PR [#12932](https://github.com/fastapi/fastapi/pull/12932) by [@Vincy1230](https://github.com/Vincy1230).
+* 🌐 Add Korean translation for `docs/ko/docs/advanced/testing-dependencies.md`. PR [#12992](https://github.com/fastapi/fastapi/pull/12992) by [@Limsunoh](https://github.com/Limsunoh).
+* 🌐 Add Korean translation for `docs/ko/docs/advanced/websockets.md`. PR [#12991](https://github.com/fastapi/fastapi/pull/12991) by [@kwang1215](https://github.com/kwang1215).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/response-model.md`. PR [#12933](https://github.com/fastapi/fastapi/pull/12933) by [@AndreBBM](https://github.com/AndreBBM).
+* 🌐 Add Korean translation for `docs/ko/docs/advanced/middlewares.md`. PR [#12753](https://github.com/fastapi/fastapi/pull/12753) by [@nahyunkeem](https://github.com/nahyunkeem).
+* 🌐 Add Korean translation for `docs/ko/docs/advanced/openapi-webhooks.md`. PR [#12752](https://github.com/fastapi/fastapi/pull/12752) by [@saeye](https://github.com/saeye).
+* 🌐 Add Chinese translation for `docs/zh/docs/tutorial/query-param-models.md`. PR [#12931](https://github.com/fastapi/fastapi/pull/12931) by [@Vincy1230](https://github.com/Vincy1230).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/query-param-models.md`. PR [#12445](https://github.com/fastapi/fastapi/pull/12445) by [@gitgernit](https://github.com/gitgernit).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/query-param-models.md`. PR [#12940](https://github.com/fastapi/fastapi/pull/12940) by [@jts8257](https://github.com/jts8257).
+* 🔥 Remove obsolete tutorial translation to Chinese for `docs/zh/docs/tutorial/sql-databases.md`, it references files that are no longer on the repo. PR [#12949](https://github.com/fastapi/fastapi/pull/12949) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12954](https://github.com/fastapi/fastapi/pull/12954) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+
+## 0.115.5 (2024-11-12)
+
+### Refactors
+
+* ♻️ Update internal checks to support Pydantic 2.10. PR [#12914](https://github.com/fastapi/fastapi/pull/12914) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Update includes for `docs/en/docs/tutorial/body.md`. PR [#12757](https://github.com/fastapi/fastapi/pull/12757) by [@gsheni](https://github.com/gsheni).
+* 📝 Update includes in `docs/en/docs/advanced/testing-dependencies.md`. PR [#12647](https://github.com/fastapi/fastapi/pull/12647) by [@AyushSinghal1794](https://github.com/AyushSinghal1794).
+* 📝 Update includes for `docs/en/docs/tutorial/metadata.md`. PR [#12773](https://github.com/fastapi/fastapi/pull/12773) by [@Nimitha-jagadeesha](https://github.com/Nimitha-jagadeesha).
+* 📝 Update `docs/en/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#12045](https://github.com/fastapi/fastapi/pull/12045) by [@xuvjso](https://github.com/xuvjso).
+* 📝 Update includes for `docs/en/docs/tutorial/dependencies/global-dependencies.md`. PR [#12653](https://github.com/fastapi/fastapi/pull/12653) by [@vishnuvskvkl](https://github.com/vishnuvskvkl).
+* 📝 Update includes for `docs/en/docs/tutorial/body-updates.md`. PR [#12712](https://github.com/fastapi/fastapi/pull/12712) by [@davioc](https://github.com/davioc).
+* 📝 Remove mention of Celery in the project generators. PR [#12742](https://github.com/fastapi/fastapi/pull/12742) by [@david-caro](https://github.com/david-caro).
+* 📝 Update includes in `docs/en/docs/tutorial/header-param-models.md`. PR [#12814](https://github.com/fastapi/fastapi/pull/12814) by [@zhaohan-dong](https://github.com/zhaohan-dong).
+* 📝 Update `contributing.md` docs, include note to not translate this page. PR [#12841](https://github.com/fastapi/fastapi/pull/12841) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update includes in `docs/en/docs/tutorial/request-forms.md`. PR [#12648](https://github.com/fastapi/fastapi/pull/12648) by [@vishnuvskvkl](https://github.com/vishnuvskvkl).
+* 📝 Update includes in `docs/en/docs/tutorial/request-form-models.md`. PR [#12649](https://github.com/fastapi/fastapi/pull/12649) by [@vishnuvskvkl](https://github.com/vishnuvskvkl).
+* 📝 Update includes in `docs/en/docs/tutorial/security/oauth2-jwt.md`. PR [#12650](https://github.com/fastapi/fastapi/pull/12650) by [@OCE1960](https://github.com/OCE1960).
+* 📝 Update includes in `docs/vi/docs/tutorial/first-steps.md`. PR [#12754](https://github.com/fastapi/fastapi/pull/12754) by [@MxPy](https://github.com/MxPy).
+* 📝 Update includes for `docs/pt/docs/advanced/wsgi.md`. PR [#12769](https://github.com/fastapi/fastapi/pull/12769) by [@Nimitha-jagadeesha](https://github.com/Nimitha-jagadeesha).
+* 📝 Update includes for `docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#12815](https://github.com/fastapi/fastapi/pull/12815) by [@handabaldeep](https://github.com/handabaldeep).
+* 📝 Update includes for `docs/en/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#12813](https://github.com/fastapi/fastapi/pull/12813) by [@handabaldeep](https://github.com/handabaldeep).
+* ✏️ Fix error in `docs/en/docs/tutorial/middleware.md`. PR [#12819](https://github.com/fastapi/fastapi/pull/12819) by [@alejsdev](https://github.com/alejsdev).
+* 📝 Update includes for `docs/en/docs/tutorial/security/get-current-user.md`. PR [#12645](https://github.com/fastapi/fastapi/pull/12645) by [@OCE1960](https://github.com/OCE1960).
+* 📝 Update includes for `docs/en/docs/tutorial/security/first-steps.md`. PR [#12643](https://github.com/fastapi/fastapi/pull/12643) by [@OCE1960](https://github.com/OCE1960).
+* 📝 Update includes in `docs/de/docs/advanced/additional-responses.md`. PR [#12821](https://github.com/fastapi/fastapi/pull/12821) by [@zhaohan-dong](https://github.com/zhaohan-dong).
+* 📝 Update includes in `docs/en/docs/advanced/generate-clients.md`. PR [#12642](https://github.com/fastapi/fastapi/pull/12642) by [@AyushSinghal1794](https://github.com/AyushSinghal1794).
+* 📝 Fix admonition double quotes with new syntax. PR [#12835](https://github.com/fastapi/fastapi/pull/12835) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update includes in `docs/zh/docs/advanced/additional-responses.md`. PR [#12828](https://github.com/fastapi/fastapi/pull/12828) by [@zhaohan-dong](https://github.com/zhaohan-dong).
+* 📝 Update includes in `docs/en/docs/tutorial/path-params-numeric-validations.md`. PR [#12825](https://github.com/fastapi/fastapi/pull/12825) by [@zhaohan-dong](https://github.com/zhaohan-dong).
+* 📝 Update includes for `docs/en/docs/advanced/testing-websockets.md`. PR [#12761](https://github.com/fastapi/fastapi/pull/12761) by [@hamidrasti](https://github.com/hamidrasti).
+* 📝 Update includes for `docs/en/docs/advanced/using-request-directly.md`. PR [#12760](https://github.com/fastapi/fastapi/pull/12760) by [@hamidrasti](https://github.com/hamidrasti).
+* 📝 Update includes for `docs/advanced/wsgi.md`. PR [#12758](https://github.com/fastapi/fastapi/pull/12758) by [@hamidrasti](https://github.com/hamidrasti).
+* 📝 Update includes in `docs/de/docs/tutorial/middleware.md`. PR [#12729](https://github.com/fastapi/fastapi/pull/12729) by [@paintdog](https://github.com/paintdog).
+* 📝 Update includes for `docs/en/docs/tutorial/schema-extra-example.md`. PR [#12822](https://github.com/fastapi/fastapi/pull/12822) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update includes in `docs/fr/docs/advanced/additional-responses.md`. PR [#12634](https://github.com/fastapi/fastapi/pull/12634) by [@fegmorte](https://github.com/fegmorte).
+* 📝 Update includes in `docs/fr/docs/advanced/path-operation-advanced-configuration.md`. PR [#12633](https://github.com/fastapi/fastapi/pull/12633) by [@kantandane](https://github.com/kantandane).
+* 📝 Update includes in `docs/fr/docs/advanced/response-directly.md`. PR [#12632](https://github.com/fastapi/fastapi/pull/12632) by [@kantandane](https://github.com/kantandane).
+* 📝 Update includes for `docs/en/docs/tutorial/header-params.md`. PR [#12640](https://github.com/fastapi/fastapi/pull/12640) by [@vishnuvskvkl](https://github.com/vishnuvskvkl).
+* 📝 Update includes in `docs/en/docs/tutorial/cookie-param-models.md`. PR [#12639](https://github.com/fastapi/fastapi/pull/12639) by [@vishnuvskvkl](https://github.com/vishnuvskvkl).
+* 📝 Update includes for `docs/en/docs/tutorial/extra-models.md`. PR [#12638](https://github.com/fastapi/fastapi/pull/12638) by [@vishnuvskvkl](https://github.com/vishnuvskvkl).
+* 📝 Update includes for `docs/en/docs/tutorial/cors.md`. PR [#12637](https://github.com/fastapi/fastapi/pull/12637) by [@vishnuvskvkl](https://github.com/vishnuvskvkl).
+* 📝 Update includes for `docs/en/docs/tutorial/dependencies/sub-dependencies.md`. PR [#12810](https://github.com/fastapi/fastapi/pull/12810) by [@handabaldeep](https://github.com/handabaldeep).
+* 📝 Update includes in `docs/en/docs/tutorial/body-nested-models.md`. PR [#12812](https://github.com/fastapi/fastapi/pull/12812) by [@zhaohan-dong](https://github.com/zhaohan-dong).
+* 📝 Update includes in `docs/en/docs/tutorial/path-operation-configuration.md`. PR [#12809](https://github.com/fastapi/fastapi/pull/12809) by [@AlexWendland](https://github.com/AlexWendland).
+* 📝 Update includes in `docs/en/docs/tutorial/request-files.md`. PR [#12818](https://github.com/fastapi/fastapi/pull/12818) by [@zhaohan-dong](https://github.com/zhaohan-dong).
+* 📝 Update includes for `docs/en/docs/tutorial/query-param-models.md`. PR [#12817](https://github.com/fastapi/fastapi/pull/12817) by [@handabaldeep](https://github.com/handabaldeep).
+* 📝 Update includes in `docs/en/docs/tutorial/path-params.md`. PR [#12811](https://github.com/fastapi/fastapi/pull/12811) by [@AlexWendland](https://github.com/AlexWendland).
+* 📝 Update includes in `docs/en/docs/tutorial/response-model.md`. PR [#12621](https://github.com/fastapi/fastapi/pull/12621) by [@kantandane](https://github.com/kantandane).
+* 📝 Update includes in `docs/en/docs/advanced/websockets.md`. PR [#12606](https://github.com/fastapi/fastapi/pull/12606) by [@vishnuvskvkl](https://github.com/vishnuvskvkl).
+* 📝 Updates include for `docs/en/docs/tutorial/cookie-params.md`. PR [#12808](https://github.com/fastapi/fastapi/pull/12808) by [@handabaldeep](https://github.com/handabaldeep).
+* 📝 Update includes in `docs/en/docs/tutorial/middleware.md`. PR [#12807](https://github.com/fastapi/fastapi/pull/12807) by [@AlexWendland](https://github.com/AlexWendland).
+* 📝 Update includes in `docs/en/docs/advanced/sub-applications.md`. PR [#12806](https://github.com/fastapi/fastapi/pull/12806) by [@zhaohan-dong](https://github.com/zhaohan-dong).
+* 📝 Update includes in `docs/en/docs/advanced/response-headers.md`. PR [#12805](https://github.com/fastapi/fastapi/pull/12805) by [@zhaohan-dong](https://github.com/zhaohan-dong).
+* 📝 Update includes in `docs/fr/docs/tutorial/first-steps.md`. PR [#12594](https://github.com/fastapi/fastapi/pull/12594) by [@kantandane](https://github.com/kantandane).
+* 📝 Update includes in `docs/en/docs/advanced/response-cookies.md`. PR [#12804](https://github.com/fastapi/fastapi/pull/12804) by [@zhaohan-dong](https://github.com/zhaohan-dong).
+* 📝 Update includes in `docs/en/docs/advanced/path-operation-advanced-configuration.md`. PR [#12802](https://github.com/fastapi/fastapi/pull/12802) by [@zhaohan-dong](https://github.com/zhaohan-dong).
+* 📝 Update includes for `docs/en/docs/advanced/response-directly.md`. PR [#12803](https://github.com/fastapi/fastapi/pull/12803) by [@handabaldeep](https://github.com/handabaldeep).
+* 📝 Update includes in `docs/zh/docs/tutorial/background-tasks.md`. PR [#12798](https://github.com/fastapi/fastapi/pull/12798) by [@zhaohan-dong](https://github.com/zhaohan-dong).
+* 📝 Update includes for `docs/de/docs/tutorial/body-multiple-params.md`. PR [#12699](https://github.com/fastapi/fastapi/pull/12699) by [@alissadb](https://github.com/alissadb).
+* 📝 Update includes in `docs/em/docs/tutorial/body-updates.md`. PR [#12799](https://github.com/fastapi/fastapi/pull/12799) by [@AlexWendland](https://github.com/AlexWendland).
+* 📝 Update includes `docs/en/docs/advanced/response-change-status-code.md`. PR [#12801](https://github.com/fastapi/fastapi/pull/12801) by [@handabaldeep](https://github.com/handabaldeep).
+* 📝 Update includes `docs/en/docs/advanced/openapi-callbacks.md`. PR [#12800](https://github.com/fastapi/fastapi/pull/12800) by [@handabaldeep](https://github.com/handabaldeep).
+* 📝 Update includes in `docs/fr/docs/tutorial/body-multiple-params.md`. PR [#12598](https://github.com/fastapi/fastapi/pull/12598) by [@kantandane](https://github.com/kantandane).
+* 📝 Update includes in `docs/en/docs/tutorial/body-multiple-params.md`. PR [#12593](https://github.com/fastapi/fastapi/pull/12593) by [@Tashanam-Shahbaz](https://github.com/Tashanam-Shahbaz).
+* 📝 Update includes in `docs/pt/docs/tutorial/background-tasks.md`. PR [#12736](https://github.com/fastapi/fastapi/pull/12736) by [@bhunao](https://github.com/bhunao).
+* 📝 Update includes for `docs/en/docs/advanced/custom-response.md`. PR [#12797](https://github.com/fastapi/fastapi/pull/12797) by [@handabaldeep](https://github.com/handabaldeep).
+* 📝 Update includes for `docs/pt/docs/python-types.md`. PR [#12671](https://github.com/fastapi/fastapi/pull/12671) by [@ceb10n](https://github.com/ceb10n).
+* 📝 Update includes for `docs/de/docs/python-types.md`. PR [#12660](https://github.com/fastapi/fastapi/pull/12660) by [@alissadb](https://github.com/alissadb).
+* 📝 Update includes for `docs/de/docs/advanced/dataclasses.md`. PR [#12658](https://github.com/fastapi/fastapi/pull/12658) by [@alissadb](https://github.com/alissadb).
+* 📝 Update includes in `docs/fr/docs/tutorial/path-params.md`. PR [#12592](https://github.com/fastapi/fastapi/pull/12592) by [@kantandane](https://github.com/kantandane).
+* 📝 Update includes for `docs/de/docs/how-to/configure-swagger-ui.md`. PR [#12690](https://github.com/fastapi/fastapi/pull/12690) by [@alissadb](https://github.com/alissadb).
+* 📝 Update includes in `docs/en/docs/advanced/security/oauth2-scopes.md`. PR [#12572](https://github.com/fastapi/fastapi/pull/12572) by [@krishnamadhavan](https://github.com/krishnamadhavan).
+* 📝 Update includes for `docs/en/docs/how-to/conditional-openapi.md`. PR [#12624](https://github.com/fastapi/fastapi/pull/12624) by [@rabinlamadong](https://github.com/rabinlamadong).
+* 📝 Update includes in `docs/en/docs/tutorial/dependencies/index.md`. PR [#12615](https://github.com/fastapi/fastapi/pull/12615) by [@bharara](https://github.com/bharara).
+* 📝 Update includes in `docs/en/docs/tutorial/response-status-code.md`. PR [#12620](https://github.com/fastapi/fastapi/pull/12620) by [@kantandane](https://github.com/kantandane).
+* 📝 Update includes in `docs/en/docs/how-to/custom-docs-ui-assets.md`. PR [#12623](https://github.com/fastapi/fastapi/pull/12623) by [@rabinlamadong](https://github.com/rabinlamadong).
+* 📝 Update includes in `docs/en/docs/advanced/openapi-webhooks.md`. PR [#12605](https://github.com/fastapi/fastapi/pull/12605) by [@salmantec](https://github.com/salmantec).
+* 📝 Update includes in `docs/en/docs/advanced/events.md`. PR [#12604](https://github.com/fastapi/fastapi/pull/12604) by [@salmantec](https://github.com/salmantec).
+* 📝 Update includes in `docs/en/docs/advanced/dataclasses.md`. PR [#12603](https://github.com/fastapi/fastapi/pull/12603) by [@salmantec](https://github.com/salmantec).
+* 📝 Update includes in `docs/es/docs/tutorial/cookie-params.md`. PR [#12602](https://github.com/fastapi/fastapi/pull/12602) by [@antonyare93](https://github.com/antonyare93).
+* 📝 Update includes in `docs/fr/docs/tutorial/path-params-numeric-validations.md`. PR [#12601](https://github.com/fastapi/fastapi/pull/12601) by [@kantandane](https://github.com/kantandane).
+* 📝 Update includes in `docs/fr/docs/tutorial/background-tasks.md`. PR [#12600](https://github.com/fastapi/fastapi/pull/12600) by [@kantandane](https://github.com/kantandane).
+* 📝 Update includes in `docs/en/docs/tutorial/encoder.md`. PR [#12597](https://github.com/fastapi/fastapi/pull/12597) by [@tonyjly](https://github.com/tonyjly).
+* 📝 Update includes in `docs/en/docs/how-to/custom-docs-ui-assets.md`. PR [#12557](https://github.com/fastapi/fastapi/pull/12557) by [@philipokiokio](https://github.com/philipokiokio).
+* 🎨 Adjust spacing. PR [#12635](https://github.com/fastapi/fastapi/pull/12635) by [@alejsdev](https://github.com/alejsdev).
+* 📝 Update includes in `docs/en/docs/how-to/custom-request-and-route.md`. PR [#12560](https://github.com/fastapi/fastapi/pull/12560) by [@philipokiokio](https://github.com/philipokiokio).
+
+### Translations
+
+* 🌐 Add Korean translation for `docs/ko/docs/advanced/testing-websockets.md`. PR [#12739](https://github.com/fastapi/fastapi/pull/12739) by [@Limsunoh](https://github.com/Limsunoh).
+* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/environment-variables.md`. PR [#12785](https://github.com/fastapi/fastapi/pull/12785) by [@Vincy1230](https://github.com/Vincy1230).
+* 🌐 Add Chinese translation for `docs/zh/docs/environment-variables.md`. PR [#12784](https://github.com/fastapi/fastapi/pull/12784) by [@Vincy1230](https://github.com/Vincy1230).
+* 🌐 Add Korean translation for `ko/docs/advanced/response-headers.md`. PR [#12740](https://github.com/fastapi/fastapi/pull/12740) by [@kwang1215](https://github.com/kwang1215).
+* 🌐 Add Chinese translation for `docs/zh/docs/virtual-environments.md`. PR [#12790](https://github.com/fastapi/fastapi/pull/12790) by [@Vincy1230](https://github.com/Vincy1230).
+* 🌐 Add Korean translation for `/docs/ko/docs/environment-variables.md`. PR [#12526](https://github.com/fastapi/fastapi/pull/12526) by [@Tolerblanc](https://github.com/Tolerblanc).
+* 🌐 Add Korean translation for `docs/ko/docs/history-design-future.md`. PR [#12646](https://github.com/fastapi/fastapi/pull/12646) by [@saeye](https://github.com/saeye).
+* 🌐 Add Korean translation for `docs/ko/docs/advanced/advanced-dependencies.md`. PR [#12675](https://github.com/fastapi/fastapi/pull/12675) by [@kim-sangah](https://github.com/kim-sangah).
+* 🌐 Add Korean translation for `docs/ko/docs/how-to/conditional-openapi.md`. PR [#12731](https://github.com/fastapi/fastapi/pull/12731) by [@sptcnl](https://github.com/sptcnl).
+* 🌐 Add Korean translation for `docs/ko/docs/advanced/using_request_directly.md`. PR [#12738](https://github.com/fastapi/fastapi/pull/12738) by [@kwang1215](https://github.com/kwang1215).
+* 🌐 Add Korean translation for `docs/ko/docs/advanced/testing-events.md`. PR [#12741](https://github.com/fastapi/fastapi/pull/12741) by [@9zimin9](https://github.com/9zimin9).
+* 🌐 Add Korean translation for `docs/ko/docs/security/index.md`. PR [#12743](https://github.com/fastapi/fastapi/pull/12743) by [@kim-sangah](https://github.com/kim-sangah).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/path-operation-advanced-configuration.md`. PR [#12762](https://github.com/fastapi/fastapi/pull/12762) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
+* 🌐 Add Korean translation for `docs/ko/docs/advanced/wsgi.md`. PR [#12659](https://github.com/fastapi/fastapi/pull/12659) by [@Limsunoh](https://github.com/Limsunoh).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/websockets.md`. PR [#12703](https://github.com/fastapi/fastapi/pull/12703) by [@devfernandoa](https://github.com/devfernandoa).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/simple-oauth2.md`. PR [#12520](https://github.com/fastapi/fastapi/pull/12520) by [@LidiaDomingos](https://github.com/LidiaDomingos).
+* 🌐 Add Korean translation for `docs/ko/docs/advanced/response-directly.md`. PR [#12674](https://github.com/fastapi/fastapi/pull/12674) by [@9zimin9](https://github.com/9zimin9).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/middleware.md`. PR [#12704](https://github.com/fastapi/fastapi/pull/12704) by [@devluisrodrigues](https://github.com/devluisrodrigues).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/openapi-callbacks.md`. PR [#12705](https://github.com/fastapi/fastapi/pull/12705) by [@devfernandoa](https://github.com/devfernandoa).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/request-files.md`. PR [#12706](https://github.com/fastapi/fastapi/pull/12706) by [@devluisrodrigues](https://github.com/devluisrodrigues).
+* 🌐 Add Portuguese Translation for `docs/pt/docs/advanced/custom-response.md`. PR [#12631](https://github.com/fastapi/fastapi/pull/12631) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/metadata.md`. PR [#12538](https://github.com/fastapi/fastapi/pull/12538) by [@LinkolnR](https://github.com/LinkolnR).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/metadata.md`. PR [#12541](https://github.com/fastapi/fastapi/pull/12541) by [@kwang1215](https://github.com/kwang1215).
+* 🌐 Add Korean Translation for `docs/ko/docs/advanced/response-cookies.md`. PR [#12546](https://github.com/fastapi/fastapi/pull/12546) by [@kim-sangah](https://github.com/kim-sangah).
+* 🌐 Add Korean translation for `docs/ko/docs/fastapi-cli.md`. PR [#12515](https://github.com/fastapi/fastapi/pull/12515) by [@dhdld](https://github.com/dhdld).
+* 🌐 Add Korean Translation for `docs/ko/docs/advanced/response-change-status-code.md`. PR [#12547](https://github.com/fastapi/fastapi/pull/12547) by [@9zimin9](https://github.com/9zimin9).
+
+### Internal
+
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12907](https://github.com/fastapi/fastapi/pull/12907) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* 🔨 Update docs preview script to show previous version and English version. PR [#12856](https://github.com/fastapi/fastapi/pull/12856) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump tiangolo/latest-changes from 0.3.1 to 0.3.2. PR [#12794](https://github.com/fastapi/fastapi/pull/12794) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.12.0 to 1.12.2. PR [#12788](https://github.com/fastapi/fastapi/pull/12788) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.11.0 to 1.12.0. PR [#12781](https://github.com/fastapi/fastapi/pull/12781) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump cloudflare/wrangler-action from 3.11 to 3.12. PR [#12777](https://github.com/fastapi/fastapi/pull/12777) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12766](https://github.com/fastapi/fastapi/pull/12766) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.10.3 to 1.11.0. PR [#12721](https://github.com/fastapi/fastapi/pull/12721) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Update pre-commit requirement from <4.0.0,>=2.17.0 to >=2.17.0,<5.0.0. PR [#12749](https://github.com/fastapi/fastapi/pull/12749) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump typer from 0.12.3 to 0.12.5. PR [#12748](https://github.com/fastapi/fastapi/pull/12748) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Update flask requirement from <3.0.0,>=1.1.2 to >=1.1.2,<4.0.0. PR [#12747](https://github.com/fastapi/fastapi/pull/12747) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pillow from 10.4.0 to 11.0.0. PR [#12746](https://github.com/fastapi/fastapi/pull/12746) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Update pytest requirement from <8.0.0,>=7.1.3 to >=7.1.3,<9.0.0. PR [#12745](https://github.com/fastapi/fastapi/pull/12745) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔧 Update sponsors: add Render. PR [#12733](https://github.com/fastapi/fastapi/pull/12733) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12707](https://github.com/fastapi/fastapi/pull/12707) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+
+## 0.115.4 (2024-10-27)
+
+### Refactors
+
+* ♻️ Update logic to import and check `python-multipart` for compatibility with newer version. PR [#12627](https://github.com/fastapi/fastapi/pull/12627) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Update includes in `docs/fr/docs/tutorial/body.md`. PR [#12596](https://github.com/fastapi/fastapi/pull/12596) by [@kantandane](https://github.com/kantandane).
+* 📝 Update includes in `docs/fr/docs/tutorial/debugging.md`. PR [#12595](https://github.com/fastapi/fastapi/pull/12595) by [@kantandane](https://github.com/kantandane).
+* 📝 Update includes in `docs/fr/docs/tutorial/query-params-str-validations.md`. PR [#12591](https://github.com/fastapi/fastapi/pull/12591) by [@kantandane](https://github.com/kantandane).
+* 📝 Update includes in `docs/fr/docs/tutorial/query-params.md`. PR [#12589](https://github.com/fastapi/fastapi/pull/12589) by [@kantandane](https://github.com/kantandane).
+* 📝 Update includes in `docs/en/tutorial/body-fields.md`. PR [#12588](https://github.com/fastapi/fastapi/pull/12588) by [@lucaromagnoli](https://github.com/lucaromagnoli).
+* 📝 Update includes in `docs/de/docs/tutorial/response-status-code.md`. PR [#12585](https://github.com/fastapi/fastapi/pull/12585) by [@abejaranoh](https://github.com/abejaranoh).
+* 📝 Update includes in `docs/en/docs/tutorial/body.md`. PR [#12586](https://github.com/fastapi/fastapi/pull/12586) by [@lucaromagnoli](https://github.com/lucaromagnoli).
+* 📝 Update includes in `docs/en/docs/advanced/behind-a-proxy.md`. PR [#12583](https://github.com/fastapi/fastapi/pull/12583) by [@imjuanleonard](https://github.com/imjuanleonard).
+* 📝 Update includes syntax for `docs/pl/docs/tutorial/first-steps.md`. PR [#12584](https://github.com/fastapi/fastapi/pull/12584) by [@sebkozlo](https://github.com/sebkozlo).
+* 📝 Update includes in `docs/en/docs/advanced/middleware.md`. PR [#12582](https://github.com/fastapi/fastapi/pull/12582) by [@montanarograziano](https://github.com/montanarograziano).
+* 📝 Update includes in `docs/en/docs/advanced/additional-status-codes.md`. PR [#12577](https://github.com/fastapi/fastapi/pull/12577) by [@krishnamadhavan](https://github.com/krishnamadhavan).
+* 📝 Update includes in `docs/en/docs/advanced/advanced-dependencies.md`. PR [#12578](https://github.com/fastapi/fastapi/pull/12578) by [@krishnamadhavan](https://github.com/krishnamadhavan).
+* 📝 Update includes in `docs/en/docs/advanced/additional-responses.md`. PR [#12576](https://github.com/fastapi/fastapi/pull/12576) by [@krishnamadhavan](https://github.com/krishnamadhavan).
+* 📝 Update includes in `docs/en/docs/tutorial/static-files.md`. PR [#12575](https://github.com/fastapi/fastapi/pull/12575) by [@lucaromagnoli](https://github.com/lucaromagnoli).
+* 📝 Update includes in `docs/en/docs/advanced/async-tests.md`. PR [#12568](https://github.com/fastapi/fastapi/pull/12568) by [@krishnamadhavan](https://github.com/krishnamadhavan).
+* 📝 Update includes in `docs/pt/docs/advanced/behind-a-proxy.md`. PR [#12563](https://github.com/fastapi/fastapi/pull/12563) by [@asmioglou](https://github.com/asmioglou).
+* 📝 Update includes in `docs/de/docs/advanced/security/http-basic-auth.md`. PR [#12561](https://github.com/fastapi/fastapi/pull/12561) by [@Nimitha-jagadeesha](https://github.com/Nimitha-jagadeesha).
+* 📝 Update includes in `docs/en/docs/tutorial/background-tasks.md`. PR [#12559](https://github.com/fastapi/fastapi/pull/12559) by [@FarhanAliRaza](https://github.com/FarhanAliRaza).
+* 📝 Update includes in `docs/fr/docs/python-types.md`. PR [#12558](https://github.com/fastapi/fastapi/pull/12558) by [@Ismailtlem](https://github.com/Ismailtlem).
+* 📝 Update includes in `docs/en/docs/how-to/graphql.md`. PR [#12564](https://github.com/fastapi/fastapi/pull/12564) by [@philipokiokio](https://github.com/philipokiokio).
+* 📝 Update includes in `docs/en/docs/how-to/extending-openapi.md`. PR [#12562](https://github.com/fastapi/fastapi/pull/12562) by [@philipokiokio](https://github.com/philipokiokio).
+* 📝 Update includes for `docs/en/docs/how-to/configure-swagger-ui.md`. PR [#12556](https://github.com/fastapi/fastapi/pull/12556) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update includes for `docs/en/docs/how-to/separate-openapi-schemas.md`. PR [#12555](https://github.com/fastapi/fastapi/pull/12555) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update includes for `docs/en/docs/advanced/security/http-basic-auth.md`. PR [#12553](https://github.com/fastapi/fastapi/pull/12553) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update includes in `docs/en/docs/tutorial/first-steps.md`. PR [#12552](https://github.com/fastapi/fastapi/pull/12552) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update includes in `docs/en/docs/python-types.md`. PR [#12551](https://github.com/fastapi/fastapi/pull/12551) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Fix link in OAuth2 docs. PR [#12550](https://github.com/fastapi/fastapi/pull/12550) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Add External Link: FastAPI do Zero. PR [#12533](https://github.com/fastapi/fastapi/pull/12533) by [@rennerocha](https://github.com/rennerocha).
+* 📝 Fix minor typos. PR [#12516](https://github.com/fastapi/fastapi/pull/12516) by [@kkirsche](https://github.com/kkirsche).
+* 🌐 Fix rendering issue in translations. PR [#12509](https://github.com/fastapi/fastapi/pull/12509) by [@alejsdev](https://github.com/alejsdev).
+
+### Translations
+
+* 📝 Update includes in `docs/de/docs/advanced/async-tests.md`. PR [#12567](https://github.com/fastapi/fastapi/pull/12567) by [@imjuanleonard](https://github.com/imjuanleonard).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/sql-databases.md`. PR [#12530](https://github.com/fastapi/fastapi/pull/12530) by [@ilacftemp](https://github.com/ilacftemp).
+* 🌐 Add Korean translation for `docs/ko/docs/benchmarks.md`. PR [#12540](https://github.com/fastapi/fastapi/pull/12540) by [@Limsunoh](https://github.com/Limsunoh).
+* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/separate-openapi-schemas.md`. PR [#12518](https://github.com/fastapi/fastapi/pull/12518) by [@ilacftemp](https://github.com/ilacftemp).
+* 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/deployment/index.md`. PR [#12521](https://github.com/fastapi/fastapi/pull/12521) by [@codingjenny](https://github.com/codingjenny).
+* 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/deployment/cloud.md`. PR [#12522](https://github.com/fastapi/fastapi/pull/12522) by [@codingjenny](https://github.com/codingjenny).
+* 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/how-to/index.md`. PR [#12523](https://github.com/fastapi/fastapi/pull/12523) by [@codingjenny](https://github.com/codingjenny).
+* 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/tutorial/index.md`. PR [#12524](https://github.com/fastapi/fastapi/pull/12524) by [@codingjenny](https://github.com/codingjenny).
+* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/how-to/index.md`. PR [#12468](https://github.com/fastapi/fastapi/pull/12468) by [@codingjenny](https://github.com/codingjenny).
+* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/tutorial/index.md`. PR [#12466](https://github.com/fastapi/fastapi/pull/12466) by [@codingjenny](https://github.com/codingjenny).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/header-param-models.md`. PR [#12437](https://github.com/fastapi/fastapi/pull/12437) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
+* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/extending-openapi.md`. PR [#12470](https://github.com/fastapi/fastapi/pull/12470) by [@ilacftemp](https://github.com/ilacftemp).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/dataclasses.md`. PR [#12475](https://github.com/fastapi/fastapi/pull/12475) by [@leoscarlato](https://github.com/leoscarlato).
+* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/custom-request-and-route.md`. PR [#12483](https://github.com/fastapi/fastapi/pull/12483) by [@devfernandoa](https://github.com/devfernandoa).
+
+### Internal
+
+* ⬆ Bump cloudflare/wrangler-action from 3.9 to 3.11. PR [#12544](https://github.com/fastapi/fastapi/pull/12544) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👷 Update GitHub Action to deploy docs previews to handle missing deploy comments. PR [#12527](https://github.com/fastapi/fastapi/pull/12527) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12505](https://github.com/fastapi/fastapi/pull/12505) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+
+## 0.115.3 (2024-10-22)
+
+### Upgrades
+
+* ⬆️ Upgrade Starlette to `>=0.40.0,<0.42.0`. PR [#12469](https://github.com/fastapi/fastapi/pull/12469) by [@defnull](https://github.com/defnull).
+
+### Docs
+
+* 📝 Fix broken link in docs. PR [#12495](https://github.com/fastapi/fastapi/pull/12495) by [@eltonjncorreia](https://github.com/eltonjncorreia).
+
+### Translations
+
+* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/fastapi-cli.md`. PR [#12444](https://github.com/fastapi/fastapi/pull/12444) by [@codingjenny](https://github.com/codingjenny).
+* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/deployment/index.md`. PR [#12439](https://github.com/fastapi/fastapi/pull/12439) by [@codingjenny](https://github.com/codingjenny).
+* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/testing-database.md`. PR [#12472](https://github.com/fastapi/fastapi/pull/12472) by [@GuilhermeRameh](https://github.com/GuilhermeRameh).
+* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/custom-docs-ui-assets.md`. PR [#12473](https://github.com/fastapi/fastapi/pull/12473) by [@devluisrodrigues](https://github.com/devluisrodrigues).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-headers.md`. PR [#12458](https://github.com/fastapi/fastapi/pull/12458) by [@leonardopaloschi](https://github.com/leonardopaloschi).
+* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/deployment/cloud.md`. PR [#12440](https://github.com/fastapi/fastapi/pull/12440) by [@codingjenny](https://github.com/codingjenny).
+* 🌐 Update Portuguese translation for `docs/pt/docs/python-types.md`. PR [#12428](https://github.com/fastapi/fastapi/pull/12428) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Russian translation for `docs/ru/docs/environment-variables.md`. PR [#12436](https://github.com/fastapi/fastapi/pull/12436) by [@wisderfin](https://github.com/wisderfin).
+* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/resources/index.md`. PR [#12443](https://github.com/fastapi/fastapi/pull/12443) by [@codingjenny](https://github.com/codingjenny).
+* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/about/index.md`. PR [#12438](https://github.com/fastapi/fastapi/pull/12438) by [@codingjenny](https://github.com/codingjenny).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/query-param-models.md`. PR [#12414](https://github.com/fastapi/fastapi/pull/12414) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Remove Portuguese translation for `docs/pt/docs/deployment.md`. PR [#12427](https://github.com/fastapi/fastapi/pull/12427) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/body-updates.md`. PR [#12381](https://github.com/fastapi/fastapi/pull/12381) by [@andersonrocha0](https://github.com/andersonrocha0).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-cookies.md`. PR [#12417](https://github.com/fastapi/fastapi/pull/12417) by [@Paulofalcao2002](https://github.com/Paulofalcao2002).
+
+### Internal
+
+* 👷 Update issue manager workflow . PR [#12457](https://github.com/fastapi/fastapi/pull/12457) by [@alejsdev](https://github.com/alejsdev).
+* 🔧 Update team, include YuriiMotov 🚀. PR [#12453](https://github.com/fastapi/fastapi/pull/12453) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Refactor label-approved, make it an internal script instead of an external GitHub Action. PR [#12280](https://github.com/fastapi/fastapi/pull/12280) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Fix smokeshow, checkout files on CI. PR [#12434](https://github.com/fastapi/fastapi/pull/12434) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Use uv in CI. PR [#12281](https://github.com/fastapi/fastapi/pull/12281) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Update httpx requirement from <0.25.0,>=0.23.0 to >=0.23.0,<0.28.0. PR [#11509](https://github.com/fastapi/fastapi/pull/11509) by [@dependabot[bot]](https://github.com/apps/dependabot).
+
+## 0.115.2 (2024-10-12)
+
+### Upgrades
+
+* ⬆️ Upgrade Starlette to `>=0.37.2,<0.41.0`. PR [#12431](https://github.com/fastapi/fastapi/pull/12431) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.115.1 (2024-10-12)
+
+### Fixes
+
+* 🐛 Fix openapi generation with responses kwarg. PR [#10895](https://github.com/fastapi/fastapi/pull/10895) by [@flxdot](https://github.com/flxdot).
+* 🐛 Remove `Required` shadowing from fastapi using Pydantic v2. PR [#12197](https://github.com/fastapi/fastapi/pull/12197) by [@pachewise](https://github.com/pachewise).
+
+### Refactors
+
+* ♻️ Update type annotations for improved `python-multipart`. PR [#12407](https://github.com/fastapi/fastapi/pull/12407) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* ✨ Add new tutorial for SQL databases with SQLModel. PR [#12285](https://github.com/fastapi/fastapi/pull/12285) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Add External Link: How to profile a FastAPI asynchronous request. PR [#12389](https://github.com/fastapi/fastapi/pull/12389) by [@brouberol](https://github.com/brouberol).
+* 🔧 Remove `base_path` for `mdx_include` Markdown extension in MkDocs. PR [#12391](https://github.com/fastapi/fastapi/pull/12391) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update link to Swagger UI configuration docs. PR [#12264](https://github.com/fastapi/fastapi/pull/12264) by [@makisukurisu](https://github.com/makisukurisu).
+* 📝 Adding links for Playwright and Vite in `docs/project-generation.md`. PR [#12274](https://github.com/fastapi/fastapi/pull/12274) by [@kayqueGovetri](https://github.com/kayqueGovetri).
+* 📝 Fix small typos in the documentation. PR [#12213](https://github.com/fastapi/fastapi/pull/12213) by [@svlandeg](https://github.com/svlandeg).
+
+### Translations
+
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/cookie-param-models.md`. PR [#12298](https://github.com/fastapi/fastapi/pull/12298) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/graphql.md`. PR [#12215](https://github.com/fastapi/fastapi/pull/12215) by [@AnandaCampelo](https://github.com/AnandaCampelo).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/security/oauth2-scopes.md`. PR [#12263](https://github.com/fastapi/fastapi/pull/12263) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Portuguese translation for `docs/pt/docs/deployment/concepts.md`. PR [#12219](https://github.com/fastapi/fastapi/pull/12219) by [@marcelomarkus](https://github.com/marcelomarkus).
+* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/conditional-openapi.md`. PR [#12221](https://github.com/fastapi/fastapi/pull/12221) by [@marcelomarkus](https://github.com/marcelomarkus).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-directly.md`. PR [#12266](https://github.com/fastapi/fastapi/pull/12266) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
+* 🌐 Update Portuguese translation for `docs/pt/docs/tutorial/cookie-params.md`. PR [#12297](https://github.com/fastapi/fastapi/pull/12297) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Fix Korean translation for `docs/ko/docs/tutorial/index.md`. PR [#12278](https://github.com/fastapi/fastapi/pull/12278) by [@kkotipy](https://github.com/kkotipy).
+* 🌐 Update Portuguese translation for `docs/pt/docs/advanced/security/http-basic-auth.md`. PR [#12275](https://github.com/fastapi/fastapi/pull/12275) by [@andersonrocha0](https://github.com/andersonrocha0).
+* 🌐 Add Portuguese translation for `docs/pt/docs/deployment/cloud.md`. PR [#12217](https://github.com/fastapi/fastapi/pull/12217) by [@marcelomarkus](https://github.com/marcelomarkus).
+* ✏️ Fix typo in `docs/es/docs/python-types.md`. PR [#12235](https://github.com/fastapi/fastapi/pull/12235) by [@JavierSanchezCastro](https://github.com/JavierSanchezCastro).
+* 🌐 Add Dutch translation for `docs/nl/docs/environment-variables.md`. PR [#12200](https://github.com/fastapi/fastapi/pull/12200) by [@maxscheijen](https://github.com/maxscheijen).
+* 🌐 Add Portuguese translation for `docs/pt/docs/deployment/manually.md`. PR [#12210](https://github.com/fastapi/fastapi/pull/12210) by [@JoaoGustavoRogel](https://github.com/JoaoGustavoRogel).
+* 🌐 Add Portuguese translation for `docs/pt/docs/deployment/server-workers.md`. PR [#12220](https://github.com/fastapi/fastapi/pull/12220) by [@marcelomarkus](https://github.com/marcelomarkus).
+* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/configure-swagger-ui.md`. PR [#12222](https://github.com/fastapi/fastapi/pull/12222) by [@marcelomarkus](https://github.com/marcelomarkus).
+
+### Internal
+
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12396](https://github.com/fastapi/fastapi/pull/12396) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* 🔨 Add script to generate variants of files. PR [#12405](https://github.com/fastapi/fastapi/pull/12405) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Add speakeasy-api to `sponsors_badge.yml`. PR [#12404](https://github.com/fastapi/fastapi/pull/12404) by [@tiangolo](https://github.com/tiangolo).
+* ➕ Add docs dependency: markdown-include-variants. PR [#12399](https://github.com/fastapi/fastapi/pull/12399) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Fix extra mdx-base-path paths. PR [#12397](https://github.com/fastapi/fastapi/pull/12397) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Tweak labeler to not override custom labels. PR [#12398](https://github.com/fastapi/fastapi/pull/12398) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update worfkow deploy-docs-notify URL. PR [#12392](https://github.com/fastapi/fastapi/pull/12392) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update Cloudflare GitHub Action. PR [#12387](https://github.com/fastapi/fastapi/pull/12387) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.10.1 to 1.10.3. PR [#12386](https://github.com/fastapi/fastapi/pull/12386) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump mkdocstrings[python] from 0.25.1 to 0.26.1. PR [#12371](https://github.com/fastapi/fastapi/pull/12371) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump griffe-typingdoc from 0.2.6 to 0.2.7. PR [#12370](https://github.com/fastapi/fastapi/pull/12370) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12331](https://github.com/fastapi/fastapi/pull/12331) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* 🔧 Update sponsors, remove Fine.dev. PR [#12271](https://github.com/fastapi/fastapi/pull/12271) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12253](https://github.com/fastapi/fastapi/pull/12253) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ✏️ Fix docstring typos in http security. PR [#12223](https://github.com/fastapi/fastapi/pull/12223) by [@albertvillanova](https://github.com/albertvillanova).
+
+## 0.115.0 (2024-09-17)
+
+### Highlights
+
+Now you can declare `Query`, `Header`, and `Cookie` parameters with Pydantic models. 🎉
+
+#### `Query` Parameter Models
+
+Use Pydantic models for `Query` parameters:
+
+```python
+from typing import Annotated, Literal
+
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: Annotated[FilterParams, Query()]):
+ return filter_query
+```
+
+Read the new docs: [Query Parameter Models](https://fastapi.tiangolo.com/tutorial/query-param-models/).
+
+#### `Header` Parameter Models
+
+Use Pydantic models for `Header` parameters:
+
+```python
+from typing import Annotated
+
+from fastapi import FastAPI, Header
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class CommonHeaders(BaseModel):
+ host: str
+ save_data: bool
+ if_modified_since: str | None = None
+ traceparent: str | None = None
+ x_tag: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(headers: Annotated[CommonHeaders, Header()]):
+ return headers
+```
+
+Read the new docs: [Header Parameter Models](https://fastapi.tiangolo.com/tutorial/header-param-models/).
+
+#### `Cookie` Parameter Models
+
+Use Pydantic models for `Cookie` parameters:
+
+```python
+from typing import Annotated
+
+from fastapi import Cookie, FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Cookies(BaseModel):
+ session_id: str
+ fatebook_tracker: str | None = None
+ googall_tracker: str | None = None
+
+
+@app.get("/items/")
+async def read_items(cookies: Annotated[Cookies, Cookie()]):
+ return cookies
+```
+
+Read the new docs: [Cookie Parameter Models](https://fastapi.tiangolo.com/tutorial/cookie-param-models/).
+
+#### Forbid Extra Query (Cookie, Header) Parameters
+
+Use Pydantic models to restrict extra values for `Query` parameters (also applies to `Header` and `Cookie` parameters).
+
+To achieve it, use Pydantic's `model_config = {"extra": "forbid"}`:
+
+```python
+from typing import Annotated, Literal
+
+from fastapi import FastAPI, Query
+from pydantic import BaseModel, Field
+
+app = FastAPI()
+
+
+class FilterParams(BaseModel):
+ model_config = {"extra": "forbid"}
+
+ limit: int = Field(100, gt=0, le=100)
+ offset: int = Field(0, ge=0)
+ order_by: Literal["created_at", "updated_at"] = "created_at"
+ tags: list[str] = []
+
+
+@app.get("/items/")
+async def read_items(filter_query: Annotated[FilterParams, Query()]):
+ return filter_query
+```
+
+This applies to `Query`, `Header`, and `Cookie` parameters, read the new docs:
+
+* [Forbid Extra Query Parameters](https://fastapi.tiangolo.com/tutorial/query-param-models/#forbid-extra-query-parameters)
+* [Forbid Extra Headers](https://fastapi.tiangolo.com/tutorial/header-param-models/#forbid-extra-headers)
+* [Forbid Extra Cookies](https://fastapi.tiangolo.com/tutorial/cookie-param-models/#forbid-extra-cookies)
+
+### Features
+
+* ✨ Add support for Pydantic models for parameters using `Query`, `Cookie`, `Header`. PR [#12199](https://github.com/fastapi/fastapi/pull/12199) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/security/http-basic-auth.md`. PR [#12195](https://github.com/fastapi/fastapi/pull/12195) by [@ceb10n](https://github.com/ceb10n).
+
+### Internal
+
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12204](https://github.com/fastapi/fastapi/pull/12204) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+
+## 0.114.2 (2024-09-13)
+
+### Fixes
+
+* 🐛 Fix form field regression with `alias`. PR [#12194](https://github.com/fastapi/fastapi/pull/12194) by [@Wurstnase](https://github.com/Wurstnase).
+
+### Translations
+
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/request-form-models.md`. PR [#12175](https://github.com/fastapi/fastapi/pull/12175) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Chinese translation for `docs/zh/docs/project-generation.md`. PR [#12170](https://github.com/fastapi/fastapi/pull/12170) by [@waketzheng](https://github.com/waketzheng).
+* 🌐 Add Dutch translation for `docs/nl/docs/python-types.md`. PR [#12158](https://github.com/fastapi/fastapi/pull/12158) by [@maxscheijen](https://github.com/maxscheijen).
+
+### Internal
+
+* 💡 Add comments with instructions for Playwright screenshot scripts. PR [#12193](https://github.com/fastapi/fastapi/pull/12193) by [@tiangolo](https://github.com/tiangolo).
+* ➕ Add inline-snapshot for tests. PR [#12189](https://github.com/fastapi/fastapi/pull/12189) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.114.1 (2024-09-11)
+
+### Refactors
+
+* ⚡️ Improve performance in request body parsing with a cache for internal model fields. PR [#12184](https://github.com/fastapi/fastapi/pull/12184) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Remove duplicate line in docs for `docs/en/docs/environment-variables.md`. PR [#12169](https://github.com/fastapi/fastapi/pull/12169) by [@prometek](https://github.com/prometek).
+
+### Translations
+
+* 🌐 Add Portuguese translation for `docs/pt/docs/virtual-environments.md`. PR [#12163](https://github.com/fastapi/fastapi/pull/12163) by [@marcelomarkus](https://github.com/marcelomarkus).
+* 🌐 Add Portuguese translation for `docs/pt/docs/environment-variables.md`. PR [#12162](https://github.com/fastapi/fastapi/pull/12162) by [@marcelomarkus](https://github.com/marcelomarkus).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/testing.md`. PR [#12164](https://github.com/fastapi/fastapi/pull/12164) by [@marcelomarkus](https://github.com/marcelomarkus).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/debugging.md`. PR [#12165](https://github.com/fastapi/fastapi/pull/12165) by [@marcelomarkus](https://github.com/marcelomarkus).
+* 🌐 Add Korean translation for `docs/ko/docs/project-generation.md`. PR [#12157](https://github.com/fastapi/fastapi/pull/12157) by [@BORA040126](https://github.com/BORA040126).
+
+### Internal
+
+* ⬆ Bump tiangolo/issue-manager from 0.5.0 to 0.5.1. PR [#12173](https://github.com/fastapi/fastapi/pull/12173) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12176](https://github.com/fastapi/fastapi/pull/12176) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* 👷 Update `issue-manager.yml`. PR [#12159](https://github.com/fastapi/fastapi/pull/12159) by [@tiangolo](https://github.com/tiangolo).
+* ✏️ Fix typo in `fastapi/params.py`. PR [#12143](https://github.com/fastapi/fastapi/pull/12143) by [@surreal30](https://github.com/surreal30).
+
+## 0.114.0 (2024-09-06)
+
+You can restrict form fields to only include those declared in a Pydantic model and forbid any extra field sent in the request using Pydantic's `model_config = {"extra": "forbid"}`:
+
+```python
+from typing import Annotated
+
+from fastapi import FastAPI, Form
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class FormData(BaseModel):
+ username: str
+ password: str
+ model_config = {"extra": "forbid"}
+
+
+@app.post("/login/")
+async def login(data: Annotated[FormData, Form()]):
+ return data
+```
+
+Read the new docs: [Form Models - Forbid Extra Form Fields](https://fastapi.tiangolo.com/tutorial/request-form-models/#forbid-extra-form-fields).
+
+### Features
+
+* ✨ Add support for forbidding extra form fields with Pydantic models. PR [#12134](https://github.com/fastapi/fastapi/pull/12134) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Update docs, Form Models section title, to match config name. PR [#12152](https://github.com/fastapi/fastapi/pull/12152) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* ✅ Update internal tests for latest Pydantic, including CI tweaks to install the latest Pydantic. PR [#12147](https://github.com/fastapi/fastapi/pull/12147) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.113.0 (2024-09-05)
+
+Now you can declare form fields with Pydantic models:
+
+```python
+from typing import Annotated
+
+from fastapi import FastAPI, Form
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class FormData(BaseModel):
+ username: str
+ password: str
+
+
+@app.post("/login/")
+async def login(data: Annotated[FormData, Form()]):
+ return data
+```
+
+Read the new docs: [Form Models](https://fastapi.tiangolo.com/tutorial/request-form-models/).
+
+### Features
+
+* ✨ Add support for Pydantic models in `Form` parameters. PR [#12129](https://github.com/fastapi/fastapi/pull/12129) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* 🔧 Update sponsors: Coherence link. PR [#12130](https://github.com/fastapi/fastapi/pull/12130) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.112.4 (2024-09-05)
+
+This release is mainly a big internal refactor to enable adding support for Pydantic models for `Form` fields, but that feature comes in the next release.
+
+This release shouldn't affect apps using FastAPI in any way. You don't even have to upgrade to this version yet. It's just a checkpoint. 🤓
+
+### Refactors
+
+* ♻️ Refactor deciding if `embed` body fields, do not overwrite fields, compute once per router, refactor internals in preparation for Pydantic models in `Form`, `Query` and others. PR [#12117](https://github.com/fastapi/fastapi/pull/12117) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* ⏪️ Temporarily revert "✨ Add support for Pydantic models in `Form` parameters" to make a checkpoint release. PR [#12128](https://github.com/fastapi/fastapi/pull/12128) by [@tiangolo](https://github.com/tiangolo). Restored by PR [#12129](https://github.com/fastapi/fastapi/pull/12129).
+* ✨ Add support for Pydantic models in `Form` parameters. PR [#12127](https://github.com/fastapi/fastapi/pull/12127) by [@tiangolo](https://github.com/tiangolo). Reverted by PR [#12128](https://github.com/fastapi/fastapi/pull/12128) to make a checkpoint release with only refactors. Restored by PR [#12129](https://github.com/fastapi/fastapi/pull/12129).
+
+## 0.112.3 (2024-09-05)
+
+This release is mainly internal refactors, it shouldn't affect apps using FastAPI in any way. You don't even have to upgrade to this version yet. There are a few bigger releases coming right after. 🚀
+
+### Refactors
+
+* ♻️ Refactor internal `check_file_field()`, rename to `ensure_multipart_is_installed()` to clarify its purpose. PR [#12106](https://github.com/fastapi/fastapi/pull/12106) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Rename internal `create_response_field()` to `create_model_field()` as it's used for more than response models. PR [#12103](https://github.com/fastapi/fastapi/pull/12103) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Refactor and simplify internal data from `solve_dependencies()` using dataclasses. PR [#12100](https://github.com/fastapi/fastapi/pull/12100) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Refactor and simplify internal `analyze_param()` to structure data with dataclasses instead of tuple. PR [#12099](https://github.com/fastapi/fastapi/pull/12099) by [@tiangolo](https://github.com/tiangolo).
+* ♻️ Refactor and simplify dependencies data structures with dataclasses. PR [#12098](https://github.com/fastapi/fastapi/pull/12098) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Add External Link: Techniques and applications of SQLAlchemy global filters in FastAPI. PR [#12109](https://github.com/fastapi/fastapi/pull/12109) by [@TheShubhendra](https://github.com/TheShubhendra).
+* 📝 Add note about `time.perf_counter()` in middlewares. PR [#12095](https://github.com/fastapi/fastapi/pull/12095) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Tweak middleware code sample `time.time()` to `time.perf_counter()`. PR [#11957](https://github.com/fastapi/fastapi/pull/11957) by [@domdent](https://github.com/domdent).
+* 🔧 Update sponsors: Coherence. PR [#12093](https://github.com/fastapi/fastapi/pull/12093) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Fix async test example not to trigger DeprecationWarning. PR [#12084](https://github.com/fastapi/fastapi/pull/12084) by [@marcinsulikowski](https://github.com/marcinsulikowski).
+* 📝 Update `docs_src/path_params_numeric_validations/tutorial006.py`. PR [#11478](https://github.com/fastapi/fastapi/pull/11478) by [@MuhammadAshiqAmeer](https://github.com/MuhammadAshiqAmeer).
+* 📝 Update comma in `docs/en/docs/async.md`. PR [#12062](https://github.com/fastapi/fastapi/pull/12062) by [@Alec-Gillis](https://github.com/Alec-Gillis).
+* 📝 Update docs about serving FastAPI: ASGI servers, Docker containers, etc.. PR [#12069](https://github.com/fastapi/fastapi/pull/12069) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Clarify `response_class` parameter, validations, and returning a response directly. PR [#12067](https://github.com/fastapi/fastapi/pull/12067) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg).
+* 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla).
+
+### Translations
+
+* 🌐 Add Dutch translation for `docs/nl/docs/features.md`. PR [#12101](https://github.com/fastapi/fastapi/pull/12101) by [@maxscheijen](https://github.com/maxscheijen).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-events.md`. PR [#12108](https://github.com/fastapi/fastapi/pull/12108) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/security/index.md`. PR [#12114](https://github.com/fastapi/fastapi/pull/12114) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Dutch translation for `docs/nl/docs/index.md`. PR [#12042](https://github.com/fastapi/fastapi/pull/12042) by [@svlandeg](https://github.com/svlandeg).
+* 🌐 Update Chinese translation for `docs/zh/docs/how-to/index.md`. PR [#12070](https://github.com/fastapi/fastapi/pull/12070) by [@synthpop123](https://github.com/synthpop123).
+
+### Internal
+
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12115](https://github.com/fastapi/fastapi/pull/12115) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.10.0 to 1.10.1. PR [#12120](https://github.com/fastapi/fastapi/pull/12120) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pillow from 10.3.0 to 10.4.0. PR [#12105](https://github.com/fastapi/fastapi/pull/12105) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 💚 Set `include-hidden-files` to `True` when using the `upload-artifact` GH action. PR [#12118](https://github.com/fastapi/fastapi/pull/12118) by [@svlandeg](https://github.com/svlandeg).
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.9.0 to 1.10.0. PR [#12112](https://github.com/fastapi/fastapi/pull/12112) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔧 Update sponsors link: Coherence. PR [#12097](https://github.com/fastapi/fastapi/pull/12097) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update labeler config to handle sponsorships data. PR [#12096](https://github.com/fastapi/fastapi/pull/12096) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors, remove Kong. PR [#12085](https://github.com/fastapi/fastapi/pull/12085) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12076](https://github.com/fastapi/fastapi/pull/12076) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* 👷 Update `latest-changes` GitHub Action. PR [#12073](https://github.com/fastapi/fastapi/pull/12073) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.112.2 (2024-08-24)
+
+### Fixes
+
+* 🐛 Fix `allow_inf_nan` option for Param and Body classes. PR [#11867](https://github.com/fastapi/fastapi/pull/11867) by [@giunio-prc](https://github.com/giunio-prc).
+* 🐛 Ensure that `app.include_router` merges nested lifespans. PR [#9630](https://github.com/fastapi/fastapi/pull/9630) by [@Lancetnik](https://github.com/Lancetnik).
+
+### Refactors
+
+* 🎨 Fix typing annotation for semi-internal `FastAPI.add_api_route()`. PR [#10240](https://github.com/fastapi/fastapi/pull/10240) by [@ordinary-jamie](https://github.com/ordinary-jamie).
+* ⬆️ Upgrade version of Ruff and reformat. PR [#12032](https://github.com/fastapi/fastapi/pull/12032) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Fix a typo in `docs/en/docs/virtual-environments.md`. PR [#12064](https://github.com/fastapi/fastapi/pull/12064) by [@aymenkrifa](https://github.com/aymenkrifa).
+* 📝 Add docs about Environment Variables and Virtual Environments. PR [#12054](https://github.com/fastapi/fastapi/pull/12054) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Add Asyncer mention in async docs. PR [#12037](https://github.com/fastapi/fastapi/pull/12037) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Move the Features docs to the top level to improve the main page menu. PR [#12036](https://github.com/fastapi/fastapi/pull/12036) by [@tiangolo](https://github.com/tiangolo).
+* ✏️ Fix import typo in reference example for `Security`. PR [#11168](https://github.com/fastapi/fastapi/pull/11168) by [@0shah0](https://github.com/0shah0).
+* 📝 Highlight correct line in tutorial `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11978](https://github.com/fastapi/fastapi/pull/11978) by [@svlandeg](https://github.com/svlandeg).
+* 🔥 Remove Sentry link from Advanced Middleware docs. PR [#12031](https://github.com/fastapi/fastapi/pull/12031) by [@alejsdev](https://github.com/alejsdev).
+* 📝 Clarify management tasks for translations, multiples files in one PR. PR [#12030](https://github.com/fastapi/fastapi/pull/12030) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Edit the link to the OpenAPI "Responses Object" and "Response Object" sections in the "Additional Responses in OpenAPI" section. PR [#11996](https://github.com/fastapi/fastapi/pull/11996) by [@VaitoSoi](https://github.com/VaitoSoi).
+* 🔨 Specify `email-validator` dependency with dash. PR [#11515](https://github.com/fastapi/fastapi/pull/11515) by [@jirikuncar](https://github.com/jirikuncar).
+* 🌐 Add Spanish translation for `docs/es/docs/project-generation.md`. PR [#11947](https://github.com/fastapi/fastapi/pull/11947) by [@alejsdev](https://github.com/alejsdev).
+* 📝 Fix minor typo. PR [#12026](https://github.com/fastapi/fastapi/pull/12026) by [@MicaelJarniac](https://github.com/MicaelJarniac).
+* 📝 Several docs improvements, tweaks, and clarifications. PR [#11390](https://github.com/fastapi/fastapi/pull/11390) by [@nilslindemann](https://github.com/nilslindemann).
+* 📝 Add missing `compresslevel` parameter on docs for `GZipMiddleware`. PR [#11350](https://github.com/fastapi/fastapi/pull/11350) by [@junah201](https://github.com/junah201).
+* 📝 Fix inconsistent response code when item already exists in docs for testing. PR [#11818](https://github.com/fastapi/fastapi/pull/11818) by [@lokomilo](https://github.com/lokomilo).
+* 📝 Update `docs/en/docs/tutorial/body.md` with Python 3.10 union type example. PR [#11415](https://github.com/fastapi/fastapi/pull/11415) by [@rangzen](https://github.com/rangzen).
+
+### Translations
+
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/request_file.md`. PR [#12018](https://github.com/fastapi/fastapi/pull/12018) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
+* 🌐 Add Japanese translation for `docs/ja/docs/learn/index.md`. PR [#11592](https://github.com/fastapi/fastapi/pull/11592) by [@ukwhatn](https://github.com/ukwhatn).
+* 📝 Update Spanish translation docs for consistency. PR [#12044](https://github.com/fastapi/fastapi/pull/12044) by [@alejsdev](https://github.com/alejsdev).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso).
+* 📝 Update FastAPI People, do not translate to have the most recent info. PR [#12034](https://github.com/fastapi/fastapi/pull/12034) by [@tiangolo](https://github.com/tiangolo).
+* 🌐 Update Urdu translation for `docs/ur/docs/benchmarks.md`. PR [#10046](https://github.com/fastapi/fastapi/pull/10046) by [@AhsanSheraz](https://github.com/AhsanSheraz).
+
+### Internal
+
+* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12046](https://github.com/fastapi/fastapi/pull/12046) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
+* 🔧 Update coverage config files. PR [#12035](https://github.com/fastapi/fastapi/pull/12035) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Standardize shebang across shell scripts. PR [#11942](https://github.com/fastapi/fastapi/pull/11942) by [@gitworkflows](https://github.com/gitworkflows).
+* ⬆ Update sqlalchemy requirement from <1.4.43,>=1.3.18 to >=1.3.18,<2.0.33. PR [#11979](https://github.com/fastapi/fastapi/pull/11979) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔊 Remove old ignore warnings. PR [#11950](https://github.com/fastapi/fastapi/pull/11950) by [@tiangolo](https://github.com/tiangolo).
+* ⬆️ Upgrade griffe-typingdoc for the docs. PR [#12029](https://github.com/fastapi/fastapi/pull/12029) by [@tiangolo](https://github.com/tiangolo).
+* 🙈 Add .coverage* to `.gitignore`. PR [#11940](https://github.com/fastapi/fastapi/pull/11940) by [@gitworkflows](https://github.com/gitworkflows).
+* ⚙️ Record and show test coverage contexts (what test covers which line). PR [#11518](https://github.com/fastapi/fastapi/pull/11518) by [@slafs](https://github.com/slafs).
+
+## 0.112.1 (2024-08-15)
+
+### Upgrades
+
+* ⬆️ Allow Starlette 0.38.x, update the pin to `>=0.37.2,<0.39.0`. PR [#11876](https://github.com/fastapi/fastapi/pull/11876) by [@musicinmybrain](https://github.com/musicinmybrain).
+
+### Docs
+
+* 📝 Update docs section about "Don't Translate these Pages". PR [#12022](https://github.com/fastapi/fastapi/pull/12022) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Add documentation for non-translated pages and scripts to verify them. PR [#12020](https://github.com/fastapi/fastapi/pull/12020) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update docs about discussions questions. PR [#11985](https://github.com/fastapi/fastapi/pull/11985) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/bigger-applications.md`. PR [#11971](https://github.com/fastapi/fastapi/pull/11971) by [@marcelomarkus](https://github.com/marcelomarkus).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-websockets.md`. PR [#11994](https://github.com/fastapi/fastapi/pull/11994) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-dependencies.md`. PR [#11995](https://github.com/fastapi/fastapi/pull/11995) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/using-request-directly.md`. PR [#11956](https://github.com/fastapi/fastapi/pull/11956) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add French translation for `docs/fr/docs/tutorial/body-multiple-params.md`. PR [#11796](https://github.com/fastapi/fastapi/pull/11796) by [@pe-brian](https://github.com/pe-brian).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#11557](https://github.com/fastapi/fastapi/pull/11557) by [@caomingpei](https://github.com/caomingpei).
+* 🌐 Update typo in Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#11944](https://github.com/fastapi/fastapi/pull/11944) by [@bestony](https://github.com/bestony).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/sub-applications.md` and `docs/pt/docs/advanced/behind-a-proxy.md`. PR [#11856](https://github.com/fastapi/fastapi/pull/11856) by [@marcelomarkus](https://github.com/marcelomarkus).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/cors.md` and `docs/pt/docs/tutorial/middleware.md`. PR [#11916](https://github.com/fastapi/fastapi/pull/11916) by [@wesinalves](https://github.com/wesinalves).
+* 🌐 Add French translation for `docs/fr/docs/tutorial/path-params-numeric-validations.md`. PR [#11788](https://github.com/fastapi/fastapi/pull/11788) by [@pe-brian](https://github.com/pe-brian).
+
+### Internal
+
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.8.14 to 1.9.0. PR [#11727](https://github.com/fastapi/fastapi/pull/11727) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔧 Add changelog URL to `pyproject.toml`, shows in PyPI. PR [#11152](https://github.com/fastapi/fastapi/pull/11152) by [@Pierre-VF](https://github.com/Pierre-VF).
+* 👷 Do not sync labels as it overrides manually added labels. PR [#12024](https://github.com/fastapi/fastapi/pull/12024) by [@tiangolo](https://github.com/tiangolo).
+* 👷🏻 Update Labeler GitHub Actions. PR [#12019](https://github.com/fastapi/fastapi/pull/12019) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update configs for MkDocs for languages and social cards. PR [#12016](https://github.com/fastapi/fastapi/pull/12016) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update permissions and config for labeler GitHub Action. PR [#12008](https://github.com/fastapi/fastapi/pull/12008) by [@tiangolo](https://github.com/tiangolo).
+* 👷🏻 Add GitHub Action label-checker. PR [#12005](https://github.com/fastapi/fastapi/pull/12005) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Add label checker GitHub Action. PR [#12004](https://github.com/fastapi/fastapi/pull/12004) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update GitHub Action add-to-project. PR [#12002](https://github.com/fastapi/fastapi/pull/12002) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update labeler GitHub Action. PR [#12001](https://github.com/fastapi/fastapi/pull/12001) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Add GitHub Action labeler. PR [#12000](https://github.com/fastapi/fastapi/pull/12000) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Add GitHub Action add-to-project. PR [#11999](https://github.com/fastapi/fastapi/pull/11999) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update admonitions in docs missing. PR [#11998](https://github.com/fastapi/fastapi/pull/11998) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Update docs.py script to enable dirty reload conditionally. PR [#11986](https://github.com/fastapi/fastapi/pull/11986) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update MkDocs instant previews. PR [#11982](https://github.com/fastapi/fastapi/pull/11982) by [@tiangolo](https://github.com/tiangolo).
+* 🐛 Fix deploy docs previews script to handle mkdocs.yml files. PR [#11984](https://github.com/fastapi/fastapi/pull/11984) by [@tiangolo](https://github.com/tiangolo).
+* 💡 Add comment about custom Termynal line-height. PR [#11976](https://github.com/fastapi/fastapi/pull/11976) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Add alls-green for test-redistribute. PR [#11974](https://github.com/fastapi/fastapi/pull/11974) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update docs-previews to handle no docs changes. PR [#11975](https://github.com/fastapi/fastapi/pull/11975) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Refactor script `deploy_docs_status.py` to account for deploy URLs with or without trailing slash. PR [#11965](https://github.com/fastapi/fastapi/pull/11965) by [@tiangolo](https://github.com/tiangolo).
+* 🔒️ Update permissions for deploy-docs action. PR [#11964](https://github.com/fastapi/fastapi/pull/11964) by [@tiangolo](https://github.com/tiangolo).
+* 👷🏻 Add deploy docs status and preview links to PRs. PR [#11961](https://github.com/fastapi/fastapi/pull/11961) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update docs setup with latest configs and plugins. PR [#11953](https://github.com/fastapi/fastapi/pull/11953) by [@tiangolo](https://github.com/tiangolo).
+* 🔇 Ignore warning from attrs in Trio. PR [#11949](https://github.com/fastapi/fastapi/pull/11949) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.112.0 (2024-08-02)
+
+### Breaking Changes
+
+* ♻️ Add support for `pip install "fastapi[standard]"` with standard dependencies and `python -m fastapi`. PR [#11935](https://github.com/fastapi/fastapi/pull/11935) by [@tiangolo](https://github.com/tiangolo).
+
+#### Summary
+
+Install with:
+
+```bash
+pip install "fastapi[standard]"
+```
+
+#### Other Changes
+
+* This adds support for calling the CLI as:
+
+```bash
+python -m fastapi
+```
+
+* And it upgrades `fastapi-cli[standard] >=0.0.5`.
+
+#### Technical Details
+
+Before this, `fastapi` would include the standard dependencies, with Uvicorn and the `fastapi-cli`, etc.
+
+And `fastapi-slim` would not include those standard dependencies.
+
+Now `fastapi` doesn't include those standard dependencies unless you install with `pip install "fastapi[standard]"`.
+
+Before, you would install `pip install fastapi`, now you should include the `standard` optional dependencies (unless you want to exclude one of those): `pip install "fastapi[standard]"`.
+
+This change is because having the standard optional dependencies installed by default was being inconvenient to several users, and having to install instead `fastapi-slim` was not being a feasible solution.
+
+Discussed here: [#11522](https://github.com/fastapi/fastapi/pull/11522) and here: [#11525](https://github.com/fastapi/fastapi/discussions/11525)
+
+### Docs
+
+* ✏️ Fix typos in docs. PR [#11926](https://github.com/fastapi/fastapi/pull/11926) by [@jianghuyiyuan](https://github.com/jianghuyiyuan).
+* 📝 Tweak management docs. PR [#11918](https://github.com/fastapi/fastapi/pull/11918) by [@tiangolo](https://github.com/tiangolo).
+* 🚚 Rename GitHub links from tiangolo/fastapi to fastapi/fastapi. PR [#11913](https://github.com/fastapi/fastapi/pull/11913) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Add docs about FastAPI team and project management. PR [#11908](https://github.com/tiangolo/fastapi/pull/11908) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Re-structure docs main menu. PR [#11904](https://github.com/tiangolo/fastapi/pull/11904) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update Speakeasy URL. PR [#11871](https://github.com/tiangolo/fastapi/pull/11871) by [@ndimares](https://github.com/ndimares).
+
+### Translations
+
+* 🌐 Update Portuguese translation for `docs/pt/docs/alternatives.md`. PR [#11931](https://github.com/fastapi/fastapi/pull/11931) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/sub-dependencies.md`. PR [#10515](https://github.com/tiangolo/fastapi/pull/10515) by [@AlertRED](https://github.com/AlertRED).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-change-status-code.md`. PR [#11863](https://github.com/tiangolo/fastapi/pull/11863) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Portuguese translation for `docs/pt/docs/reference/background.md`. PR [#11849](https://github.com/tiangolo/fastapi/pull/11849) by [@lucasbalieiro](https://github.com/lucasbalieiro).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#11848](https://github.com/tiangolo/fastapi/pull/11848) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
+* 🌐 Add Portuguese translation for `docs/pt/docs/reference/apirouter.md`. PR [#11843](https://github.com/tiangolo/fastapi/pull/11843) by [@lucasbalieiro](https://github.com/lucasbalieiro).
+
+### Internal
+
+* 🔧 Update sponsors: add liblab. PR [#11934](https://github.com/fastapi/fastapi/pull/11934) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update GitHub Action label-approved permissions. PR [#11933](https://github.com/fastapi/fastapi/pull/11933) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Refactor GitHub Action to comment docs deployment URLs and update token. PR [#11925](https://github.com/fastapi/fastapi/pull/11925) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update tokens for GitHub Actions. PR [#11924](https://github.com/fastapi/fastapi/pull/11924) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update token permissions to comment deployment URL in docs. PR [#11917](https://github.com/fastapi/fastapi/pull/11917) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update token permissions for GitHub Actions. PR [#11915](https://github.com/fastapi/fastapi/pull/11915) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update GitHub Actions token usage. PR [#11914](https://github.com/fastapi/fastapi/pull/11914) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update GitHub Action to notify translations with label `approved-1`. PR [#11907](https://github.com/tiangolo/fastapi/pull/11907) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors, remove Reflex. PR [#11875](https://github.com/tiangolo/fastapi/pull/11875) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors: remove TalkPython. PR [#11861](https://github.com/tiangolo/fastapi/pull/11861) by [@tiangolo](https://github.com/tiangolo).
+* 🔨 Update docs Termynal scripts to not include line nums for local dev. PR [#11854](https://github.com/tiangolo/fastapi/pull/11854) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.111.1 (2024-07-14)
+
+### Upgrades
+
+* ➖ Remove `orjson` and `ujson` from default dependencies. PR [#11842](https://github.com/tiangolo/fastapi/pull/11842) by [@tiangolo](https://github.com/tiangolo).
+ * These dependencies are still installed when you install with `pip install "fastapi[all]"`. But they are not included in `pip install fastapi`.
+* 📝 Restored Swagger-UI links to use the latest version possible. PR [#11459](https://github.com/tiangolo/fastapi/pull/11459) by [@UltimateLobster](https://github.com/UltimateLobster).
+
+### Docs
+
+* ✏️ Rewording in `docs/en/docs/fastapi-cli.md`. PR [#11716](https://github.com/tiangolo/fastapi/pull/11716) by [@alejsdev](https://github.com/alejsdev).
+* 📝 Update Hypercorn links in all the docs. PR [#11744](https://github.com/tiangolo/fastapi/pull/11744) by [@kittydoor](https://github.com/kittydoor).
+* 📝 Update docs with Ariadne reference from Starlette to FastAPI. PR [#11797](https://github.com/tiangolo/fastapi/pull/11797) by [@DamianCzajkowski](https://github.com/DamianCzajkowski).
+* 📝 Update fastapi instrumentation external link. PR [#11317](https://github.com/tiangolo/fastapi/pull/11317) by [@softwarebloat](https://github.com/softwarebloat).
+* ✏️ Fix links to alembic example repo in docs. PR [#11628](https://github.com/tiangolo/fastapi/pull/11628) by [@augiwan](https://github.com/augiwan).
+* ✏️ Update `docs/en/docs/fastapi-cli.md`. PR [#11715](https://github.com/tiangolo/fastapi/pull/11715) by [@alejsdev](https://github.com/alejsdev).
+* 📝 Update External Links . PR [#11500](https://github.com/tiangolo/fastapi/pull/11500) by [@devon2018](https://github.com/devon2018).
+* 📝 Add External Link: Tutorial de FastAPI, ¿el mejor framework de Python?. PR [#11618](https://github.com/tiangolo/fastapi/pull/11618) by [@EduardoZepeda](https://github.com/EduardoZepeda).
+* 📝 Fix typo in `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11698](https://github.com/tiangolo/fastapi/pull/11698) by [@mwb-u](https://github.com/mwb-u).
+* 📝 Add External Link: Deploy a Serverless FastAPI App with Neon Postgres and AWS App Runner at any scale. PR [#11633](https://github.com/tiangolo/fastapi/pull/11633) by [@ananis25](https://github.com/ananis25).
+* 📝 Update `security/first-steps.md`. PR [#11674](https://github.com/tiangolo/fastapi/pull/11674) by [@alejsdev](https://github.com/alejsdev).
+* 📝 Update `security/first-steps.md`. PR [#11673](https://github.com/tiangolo/fastapi/pull/11673) by [@alejsdev](https://github.com/alejsdev).
+* 📝 Update note in `path-params-numeric-validations.md`. PR [#11672](https://github.com/tiangolo/fastapi/pull/11672) by [@alejsdev](https://github.com/alejsdev).
+* 📝 Tweak intro docs about `Annotated` and `Query()` params. PR [#11664](https://github.com/tiangolo/fastapi/pull/11664) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update JWT auth documentation to use PyJWT instead of pyhon-jose. PR [#11589](https://github.com/tiangolo/fastapi/pull/11589) by [@estebanx64](https://github.com/estebanx64).
+* 📝 Update docs. PR [#11603](https://github.com/tiangolo/fastapi/pull/11603) by [@alejsdev](https://github.com/alejsdev).
+* ✏️ Fix typo: convert every 're-use' to 'reuse'.. PR [#11598](https://github.com/tiangolo/fastapi/pull/11598) by [@hasansezertasan](https://github.com/hasansezertasan).
+* ✏️ Fix typo in `fastapi/applications.py`. PR [#11593](https://github.com/tiangolo/fastapi/pull/11593) by [@petarmaric](https://github.com/petarmaric).
+* ✏️ Fix link in `fastapi-cli.md`. PR [#11524](https://github.com/tiangolo/fastapi/pull/11524) by [@svlandeg](https://github.com/svlandeg).
+
+### Translations
+
+* 🌐 Add Spanish translation for `docs/es/docs/how-to/graphql.md`. PR [#11697](https://github.com/tiangolo/fastapi/pull/11697) by [@camigomezdev](https://github.com/camigomezdev).
+* 🌐 Add Portuguese translation for `docs/pt/docs/reference/index.md`. PR [#11840](https://github.com/tiangolo/fastapi/pull/11840) by [@lucasbalieiro](https://github.com/lucasbalieiro).
+* 🌐 Fix link in German translation. PR [#11836](https://github.com/tiangolo/fastapi/pull/11836) by [@anitahammer](https://github.com/anitahammer).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/sub-dependencies.md`. PR [#11792](https://github.com/tiangolo/fastapi/pull/11792) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
+* 🌐 Add Turkish translation for `docs/tr/docs/tutorial/request-forms.md`. PR [#11553](https://github.com/tiangolo/fastapi/pull/11553) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Add Portuguese translation for `docs/pt/docs/reference/exceptions.md`. PR [#11834](https://github.com/tiangolo/fastapi/pull/11834) by [@lucasbalieiro](https://github.com/lucasbalieiro).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/global-dependencies.md`. PR [#11826](https://github.com/tiangolo/fastapi/pull/11826) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
+* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/general.md`. PR [#11825](https://github.com/tiangolo/fastapi/pull/11825) by [@lucasbalieiro](https://github.com/lucasbalieiro).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/async-tests.md`. PR [#11808](https://github.com/tiangolo/fastapi/pull/11808) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/first-steps.md`. PR [#11809](https://github.com/tiangolo/fastapi/pull/11809) by [@vkhoroshchak](https://github.com/vkhoroshchak).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-operators.md`. PR [#11804](https://github.com/tiangolo/fastapi/pull/11804) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
+* 🌐 Add Chinese translation for `docs/zh/docs/fastapi-cli.md`. PR [#11786](https://github.com/tiangolo/fastapi/pull/11786) by [@logan2d5](https://github.com/logan2d5).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/openapi-webhooks.md`. PR [#11791](https://github.com/tiangolo/fastapi/pull/11791) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Update Chinese translation for `docs/tutorial/security/oauth2-jwt.md`. PR [#11781](https://github.com/tiangolo/fastapi/pull/11781) by [@logan2d5](https://github.com/logan2d5).
+* 📝 Fix image missing in French translation for `docs/fr/docs/async.md` . PR [#11787](https://github.com/tiangolo/fastapi/pull/11787) by [@pe-brian](https://github.com/pe-brian).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/advanced-dependencies.md`. PR [#11775](https://github.com/tiangolo/fastapi/pull/11775) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#11768](https://github.com/tiangolo/fastapi/pull/11768) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/additional-status-codes.md`. PR [#11753](https://github.com/tiangolo/fastapi/pull/11753) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/index.md`. PR [#11757](https://github.com/tiangolo/fastapi/pull/11757) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/settings.md`. PR [#11739](https://github.com/tiangolo/fastapi/pull/11739) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda).
+* 🌐 Add French translation for `docs/fr/docs/learn/index.md`. PR [#11712](https://github.com/tiangolo/fastapi/pull/11712) by [@benjaminvandammeholberton](https://github.com/benjaminvandammeholberton).
+* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/index.md`. PR [#11731](https://github.com/tiangolo/fastapi/pull/11731) by [@vhsenna](https://github.com/vhsenna).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/additional-responses.md`. PR [#11736](https://github.com/tiangolo/fastapi/pull/11736) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/benchmarks.md`. PR [#11713](https://github.com/tiangolo/fastapi/pull/11713) by [@ceb10n](https://github.com/ceb10n).
+* 🌐 Fix Korean translation for `docs/ko/docs/tutorial/response-status-code.md`. PR [#11718](https://github.com/tiangolo/fastapi/pull/11718) by [@nayeonkinn](https://github.com/nayeonkinn).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/extra-data-types.md`. PR [#11711](https://github.com/tiangolo/fastapi/pull/11711) by [@nayeonkinn](https://github.com/nayeonkinn).
+* 🌐 Fix Korean translation for `docs/ko/docs/tutorial/body-nested-models.md`. PR [#11710](https://github.com/tiangolo/fastapi/pull/11710) by [@nayeonkinn](https://github.com/nayeonkinn).
+* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/fastapi-cli.md`. PR [#11641](https://github.com/tiangolo/fastapi/pull/11641) by [@ayr-ton](https://github.com/ayr-ton).
+* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/fastapi-people.md`. PR [#11639](https://github.com/tiangolo/fastapi/pull/11639) by [@hsuanchi](https://github.com/hsuanchi).
+* 🌐 Add Turkish translation for `docs/tr/docs/advanced/index.md`. PR [#11606](https://github.com/tiangolo/fastapi/pull/11606) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Add Turkish translation for `docs/tr/docs/deployment/cloud.md`. PR [#11610](https://github.com/tiangolo/fastapi/pull/11610) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Add Turkish translation for `docs/tr/docs/advanced/security/index.md`. PR [#11609](https://github.com/tiangolo/fastapi/pull/11609) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Add Turkish translation for `docs/tr/docs/advanced/testing-websockets.md`. PR [#11608](https://github.com/tiangolo/fastapi/pull/11608) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Add Turkish translation for `docs/tr/docs/how-to/general.md`. PR [#11607](https://github.com/tiangolo/fastapi/pull/11607) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Update Chinese translation for `docs/zh/docs/advanced/templates.md`. PR [#11620](https://github.com/tiangolo/fastapi/pull/11620) by [@chaoless](https://github.com/chaoless).
+* 🌐 Add Turkish translation for `docs/tr/docs/deployment/index.md`. PR [#11605](https://github.com/tiangolo/fastapi/pull/11605) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Add Turkish translation for `docs/tr/docs/tutorial/static-files.md`. PR [#11599](https://github.com/tiangolo/fastapi/pull/11599) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Polish translation for `docs/pl/docs/fastapi-people.md`. PR [#10196](https://github.com/tiangolo/fastapi/pull/10196) by [@isulim](https://github.com/isulim).
+* 🌐 Add Turkish translation for `docs/tr/docs/advanced/wsgi.md`. PR [#11575](https://github.com/tiangolo/fastapi/pull/11575) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Add Turkish translation for `docs/tr/docs/tutorial/cookie-params.md`. PR [#11561](https://github.com/tiangolo/fastapi/pull/11561) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Add Russian translation for `docs/ru/docs/about/index.md`. PR [#10961](https://github.com/tiangolo/fastapi/pull/10961) by [@s111d](https://github.com/s111d).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/sql-databases.md`. PR [#11539](https://github.com/tiangolo/fastapi/pull/11539) by [@chaoless](https://github.com/chaoless).
+* 🌐 Add Chinese translation for `docs/zh/docs/how-to/configure-swagger-ui.md`. PR [#11501](https://github.com/tiangolo/fastapi/pull/11501) by [@Lucas-lyh](https://github.com/Lucas-lyh).
+* 🌐 Update Chinese translation for `/docs/advanced/security/http-basic-auth.md`. PR [#11512](https://github.com/tiangolo/fastapi/pull/11512) by [@nick-cjyx9](https://github.com/nick-cjyx9).
+
+### Internal
+
+* ♻️ Simplify internal docs script. PR [#11777](https://github.com/tiangolo/fastapi/pull/11777) by [@gitworkflows](https://github.com/gitworkflows).
+* 🔧 Update sponsors: add Fine. PR [#11784](https://github.com/tiangolo/fastapi/pull/11784) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Tweak sponsors: Kong URL. PR [#11765](https://github.com/tiangolo/fastapi/pull/11765) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Tweak sponsors: Kong URL. PR [#11764](https://github.com/tiangolo/fastapi/pull/11764) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors, add Stainless. PR [#11763](https://github.com/tiangolo/fastapi/pull/11763) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors, add Zuplo. PR [#11729](https://github.com/tiangolo/fastapi/pull/11729) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update Sponsor link: Coherence. PR [#11730](https://github.com/tiangolo/fastapi/pull/11730) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People. PR [#11669](https://github.com/tiangolo/fastapi/pull/11669) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Add sponsor Kong. PR [#11662](https://github.com/tiangolo/fastapi/pull/11662) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update Smokeshow, fix sync download artifact and smokeshow configs. PR [#11563](https://github.com/tiangolo/fastapi/pull/11563) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update Smokeshow download artifact GitHub Action. PR [#11562](https://github.com/tiangolo/fastapi/pull/11562) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update GitHub actions to download and upload artifacts to v4, for docs and coverage. PR [#11550](https://github.com/tiangolo/fastapi/pull/11550) by [@tamird](https://github.com/tamird).
+* 👷 Tweak CI for test-redistribute, add needed env vars for slim. PR [#11549](https://github.com/tiangolo/fastapi/pull/11549) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People. PR [#11511](https://github.com/tiangolo/fastapi/pull/11511) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.111.0 (2024-05-03)
+
+### Features
+
+* ✨ Add FastAPI CLI, the new `fastapi` command. PR [#11522](https://github.com/tiangolo/fastapi/pull/11522) by [@tiangolo](https://github.com/tiangolo).
+ * New docs: [FastAPI CLI](https://fastapi.tiangolo.com/fastapi-cli/).
+
+Try it out with:
+
+```console
+$ pip install --upgrade fastapi
+
+$ fastapi dev main.py
+
+
+ ╭────────── FastAPI CLI - Development mode ───────────╮
+ │ │
+ │ Serving at: http://127.0.0.1:8000 │
+ │ │
+ │ API docs: http://127.0.0.1:8000/docs │
+ │ │
+ │ Running in development mode, for production use: │
+ │ │
+ │ fastapi run │
+ │ │
+ ╰─────────────────────────────────────────────────────╯
+
+INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp']
+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
+INFO: Started reloader process [2248755] using WatchFiles
+INFO: Started server process [2248757]
+INFO: Waiting for application startup.
+INFO: Application startup complete.
+```
+
+### Refactors
+
+* 🔧 Add configs and setup for `fastapi-slim` including optional extras `fastapi-slim[standard]`, and `fastapi` including by default the same `standard` extras. PR [#11503](https://github.com/tiangolo/fastapi/pull/11503) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.110.3 (2024-04-30)
+
+### Docs
+
+* 📝 Update references to Python version, FastAPI supports all the current versions, no need to make the version explicit. PR [#11496](https://github.com/tiangolo/fastapi/pull/11496) by [@tiangolo](https://github.com/tiangolo).
+* ✏️ Fix typo in `fastapi/security/api_key.py`. PR [#11481](https://github.com/tiangolo/fastapi/pull/11481) by [@ch33zer](https://github.com/ch33zer).
+* ✏️ Fix typo in `security/http.py`. PR [#11455](https://github.com/tiangolo/fastapi/pull/11455) by [@omarmoo5](https://github.com/omarmoo5).
+
+### Translations
+
+* 🌐 Add Traditional Chinese translation for `docs/zh-hant/benchmarks.md`. PR [#11484](https://github.com/tiangolo/fastapi/pull/11484) by [@KNChiu](https://github.com/KNChiu).
+* 🌐 Update Chinese translation for `docs/zh/docs/fastapi-people.md`. PR [#11476](https://github.com/tiangolo/fastapi/pull/11476) by [@billzhong](https://github.com/billzhong).
+* 🌐 Add Chinese translation for `docs/zh/docs/how-to/index.md` and `docs/zh/docs/how-to/general.md`. PR [#11443](https://github.com/tiangolo/fastapi/pull/11443) by [@billzhong](https://github.com/billzhong).
+* 🌐 Add Spanish translation for cookie-params `docs/es/docs/tutorial/cookie-params.md`. PR [#11410](https://github.com/tiangolo/fastapi/pull/11410) by [@fabianfalon](https://github.com/fabianfalon).
+
+### Internal
+
+* ⬆ Bump mkdocstrings[python] from 0.23.0 to 0.24.3. PR [#11469](https://github.com/tiangolo/fastapi/pull/11469) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔨 Update internal scripts and remove unused ones. PR [#11499](https://github.com/tiangolo/fastapi/pull/11499) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Migrate from Hatch to PDM for the internal build. PR [#11498](https://github.com/tiangolo/fastapi/pull/11498) by [@tiangolo](https://github.com/tiangolo).
+* ⬆️ Upgrade MkDocs Material and re-enable cards. PR [#11466](https://github.com/tiangolo/fastapi/pull/11466) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump pillow from 10.2.0 to 10.3.0. PR [#11403](https://github.com/tiangolo/fastapi/pull/11403) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔧 Ungroup dependabot updates. PR [#11465](https://github.com/tiangolo/fastapi/pull/11465) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.110.2 (2024-04-19)
+
+### Fixes
+
+* 🐛 Fix support for query parameters with list types, handle JSON encoding Pydantic `UndefinedType`. PR [#9929](https://github.com/tiangolo/fastapi/pull/9929) by [@arjwilliams](https://github.com/arjwilliams).
+
+### Refactors
+
+* ♻️ Simplify Pydantic configs in OpenAPI models in `fastapi/openapi/models.py`. PR [#10886](https://github.com/tiangolo/fastapi/pull/10886) by [@JoeTanto2](https://github.com/JoeTanto2).
+* ✨ Add support for Pydantic's 2.7 new deprecated Field parameter, remove URL from validation errors response. PR [#11461](https://github.com/tiangolo/fastapi/pull/11461) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Fix types in examples under `docs_src/extra_data_types`. PR [#10535](https://github.com/tiangolo/fastapi/pull/10535) by [@nilslindemann](https://github.com/nilslindemann).
+* 📝 Update references to UJSON. PR [#11464](https://github.com/tiangolo/fastapi/pull/11464) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Tweak docs and translations links, typos, format. PR [#11389](https://github.com/tiangolo/fastapi/pull/11389) by [@nilslindemann](https://github.com/nilslindemann).
+* 📝 Fix typo in `docs/es/docs/async.md`. PR [#11400](https://github.com/tiangolo/fastapi/pull/11400) by [@fabianfalon](https://github.com/fabianfalon).
+* 📝 Update OpenAPI client generation docs to use `@hey-api/openapi-ts`. PR [#11339](https://github.com/tiangolo/fastapi/pull/11339) by [@jordanshatford](https://github.com/jordanshatford).
+
+### Translations
+
+* 🌐 Update Chinese translation for `docs/zh/docs/index.html`. PR [#11430](https://github.com/tiangolo/fastapi/pull/11430) by [@waketzheng](https://github.com/waketzheng).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#11411](https://github.com/tiangolo/fastapi/pull/11411) by [@anton2yakovlev](https://github.com/anton2yakovlev).
+* 🌐 Add Portuguese translations for `learn/index.md` `resources/index.md` `help/index.md` `about/index.md`. PR [#10807](https://github.com/tiangolo/fastapi/pull/10807) by [@nazarepiedady](https://github.com/nazarepiedady).
+* 🌐 Update Russian translations for deployments docs. PR [#11271](https://github.com/tiangolo/fastapi/pull/11271) by [@Lufa1u](https://github.com/Lufa1u).
+* 🌐 Add Bengali translations for `docs/bn/docs/python-types.md`. PR [#11376](https://github.com/tiangolo/fastapi/pull/11376) by [@imtiaz101325](https://github.com/imtiaz101325).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/security/simple-oauth2.md`. PR [#5744](https://github.com/tiangolo/fastapi/pull/5744) by [@KdHyeon0661](https://github.com/KdHyeon0661).
+* 🌐 Add Korean translation for `docs/ko/docs/help-fastapi.md`. PR [#4139](https://github.com/tiangolo/fastapi/pull/4139) by [@kty4119](https://github.com/kty4119).
+* 🌐 Add Korean translation for `docs/ko/docs/advanced/events.md`. PR [#5087](https://github.com/tiangolo/fastapi/pull/5087) by [@pers0n4](https://github.com/pers0n4).
+* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/path-operation-configuration.md`. PR [#1954](https://github.com/tiangolo/fastapi/pull/1954) by [@SwftAlpc](https://github.com/SwftAlpc).
+* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/request-forms-and-files.md`. PR [#1946](https://github.com/tiangolo/fastapi/pull/1946) by [@SwftAlpc](https://github.com/SwftAlpc).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10532](https://github.com/tiangolo/fastapi/pull/10532) by [@AlertRED](https://github.com/AlertRED).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/debugging.md`. PR [#5695](https://github.com/tiangolo/fastapi/pull/5695) by [@JungWooGeon](https://github.com/JungWooGeon).
+
+### Internal
+
+* ⬆️ Upgrade version of typer for docs. PR [#11393](https://github.com/tiangolo/fastapi/pull/11393) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.110.1 (2024-04-02)
+
+### Fixes
+
+* 🐛 Fix parameterless `Depends()` with generics. PR [#9479](https://github.com/tiangolo/fastapi/pull/9479) by [@nzig](https://github.com/nzig).
+
+### Refactors
+
+* ♻️ Update mypy. PR [#11049](https://github.com/tiangolo/fastapi/pull/11049) by [@k0t3n](https://github.com/k0t3n).
+* ♻️ Simplify string format with f-strings in `fastapi/applications.py`. PR [#11335](https://github.com/tiangolo/fastapi/pull/11335) by [@igeni](https://github.com/igeni).
+
+### Upgrades
+
+* ⬆️ Upgrade Starlette to >=0.37.2,<0.38.0, remove Starlette filterwarning for internal tests. PR [#11266](https://github.com/tiangolo/fastapi/pull/11266) by [@nothielf](https://github.com/nothielf).
+
+### Docs
+
+* 📝 Tweak docs and translations links and remove old docs translations. PR [#11381](https://github.com/tiangolo/fastapi/pull/11381) by [@tiangolo](https://github.com/tiangolo).
+* ✏️ Fix typo in `fastapi/security/oauth2.py`. PR [#11368](https://github.com/tiangolo/fastapi/pull/11368) by [@shandongbinzhou](https://github.com/shandongbinzhou).
+* 📝 Update links to Pydantic docs to point to new website. PR [#11328](https://github.com/tiangolo/fastapi/pull/11328) by [@alejsdev](https://github.com/alejsdev).
+* ✏️ Fix typo in `docs/en/docs/tutorial/extra-models.md`. PR [#11329](https://github.com/tiangolo/fastapi/pull/11329) by [@alejsdev](https://github.com/alejsdev).
+* 📝 Update `project-generation.md`. PR [#11326](https://github.com/tiangolo/fastapi/pull/11326) by [@alejsdev](https://github.com/alejsdev).
+* 📝 Update External Links. PR [#11327](https://github.com/tiangolo/fastapi/pull/11327) by [@alejsdev](https://github.com/alejsdev).
+* 🔥 Remove link to Pydantic's benchmark, on other i18n pages.. PR [#11224](https://github.com/tiangolo/fastapi/pull/11224) by [@hirotoKirimaru](https://github.com/hirotoKirimaru).
+* ✏️ Fix typos in docstrings. PR [#11295](https://github.com/tiangolo/fastapi/pull/11295) by [@davidhuser](https://github.com/davidhuser).
+* 🛠️ Improve Node.js script in docs to generate TypeScript clients. PR [#11293](https://github.com/tiangolo/fastapi/pull/11293) by [@alejsdev](https://github.com/alejsdev).
+* 📝 Update examples for tests to replace "inexistent" for "nonexistent". PR [#11220](https://github.com/tiangolo/fastapi/pull/11220) by [@Homesteady](https://github.com/Homesteady).
+* 📝 Update `python-multipart` GitHub link in all docs from `https://andrew-d.github.io/python-multipart/` to `https://github.com/Kludex/python-multipart`. PR [#11239](https://github.com/tiangolo/fastapi/pull/11239) by [@joshjhans](https://github.com/joshjhans).
+
+### Translations
+
+* 🌐 Add German translation for `docs/de/docs/tutorial/response-status-code.md`. PR [#10357](https://github.com/tiangolo/fastapi/pull/10357) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#3480](https://github.com/tiangolo/fastapi/pull/3480) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/body.md`. PR [#3481](https://github.com/tiangolo/fastapi/pull/3481) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/path-params.md`. PR [#3479](https://github.com/tiangolo/fastapi/pull/3479) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Update Chinese translation for `docs/tutorial/body-fields.md`. PR [#3496](https://github.com/tiangolo/fastapi/pull/3496) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Update Chinese translation for `docs/tutorial/extra-models.md`. PR [#3497](https://github.com/tiangolo/fastapi/pull/3497) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/metadata.md`. PR [#2667](https://github.com/tiangolo/fastapi/pull/2667) by [@tokusumi](https://github.com/tokusumi).
+* 🌐 Add German translation for `docs/de/docs/contributing.md`. PR [#10487](https://github.com/tiangolo/fastapi/pull/10487) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Update Japanese translation of `docs/ja/docs/tutorial/query-params.md`. PR [#10808](https://github.com/tiangolo/fastapi/pull/10808) by [@urushio](https://github.com/urushio).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/security/get-current-user.md`. PR [#3842](https://github.com/tiangolo/fastapi/pull/3842) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/openapi-callbacks.md`. PR [#3825](https://github.com/tiangolo/fastapi/pull/3825) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/extending-openapi.md`. PR [#3823](https://github.com/tiangolo/fastapi/pull/3823) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#3819](https://github.com/tiangolo/fastapi/pull/3819) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/custom-request-and-route.md`. PR [#3816](https://github.com/tiangolo/fastapi/pull/3816) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/external-links.md`. PR [#3833](https://github.com/tiangolo/fastapi/pull/3833) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/templates.md`. PR [#3812](https://github.com/tiangolo/fastapi/pull/3812) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/sub-applications.md`. PR [#3811](https://github.com/tiangolo/fastapi/pull/3811) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/async-sql-databases.md`. PR [#3805](https://github.com/tiangolo/fastapi/pull/3805) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/middleware.md`. PR [#3804](https://github.com/tiangolo/fastapi/pull/3804) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/dataclasses.md`. PR [#3803](https://github.com/tiangolo/fastapi/pull/3803) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/using-request-directly.md`. PR [#3802](https://github.com/tiangolo/fastapi/pull/3802) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/security/http-basic-auth.md`. PR [#3801](https://github.com/tiangolo/fastapi/pull/3801) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/security/oauth2-scopes.md`. PR [#3800](https://github.com/tiangolo/fastapi/pull/3800) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/cookie-params.md`. PR [#3486](https://github.com/tiangolo/fastapi/pull/3486) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/header-params.md`. PR [#3487](https://github.com/tiangolo/fastapi/pull/3487) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Update Chinese translation for `docs/tutorial/response-status-code.md`. PR [#3498](https://github.com/tiangolo/fastapi/pull/3498) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add German translation for `docs/de/docs/tutorial/security/first-steps.md`. PR [#10432](https://github.com/tiangolo/fastapi/pull/10432) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/events.md`. PR [#10693](https://github.com/tiangolo/fastapi/pull/10693) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/deployment/cloud.md`. PR [#10746](https://github.com/tiangolo/fastapi/pull/10746) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/behind-a-proxy.md`. PR [#10675](https://github.com/tiangolo/fastapi/pull/10675) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/help-fastapi.md`. PR [#10455](https://github.com/tiangolo/fastapi/pull/10455) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Update German translation for `docs/de/docs/python-types.md`. PR [#10287](https://github.com/tiangolo/fastapi/pull/10287) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/path-params.md`. PR [#10290](https://github.com/tiangolo/fastapi/pull/10290) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/handling-errors.md`. PR [#10379](https://github.com/tiangolo/fastapi/pull/10379) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Update German translation for `docs/de/docs/index.md`. PR [#10283](https://github.com/tiangolo/fastapi/pull/10283) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/security/http-basic-auth.md`. PR [#10651](https://github.com/tiangolo/fastapi/pull/10651) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/bigger-applications.md`. PR [#10554](https://github.com/tiangolo/fastapi/pull/10554) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/path-operation-advanced-configuration.md`. PR [#10612](https://github.com/tiangolo/fastapi/pull/10612) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/static-files.md`. PR [#10584](https://github.com/tiangolo/fastapi/pull/10584) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/security/oauth2-jwt.md`. PR [#10522](https://github.com/tiangolo/fastapi/pull/10522) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/response-model.md`. PR [#10345](https://github.com/tiangolo/fastapi/pull/10345) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/extra-models.md`. PR [#10351](https://github.com/tiangolo/fastapi/pull/10351) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/body-updates.md`. PR [#10396](https://github.com/tiangolo/fastapi/pull/10396) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/alternatives.md`. PR [#10855](https://github.com/tiangolo/fastapi/pull/10855) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/templates.md`. PR [#10678](https://github.com/tiangolo/fastapi/pull/10678) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/security/oauth2-scopes.md`. PR [#10643](https://github.com/tiangolo/fastapi/pull/10643) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/async-tests.md`. PR [#10708](https://github.com/tiangolo/fastapi/pull/10708) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/metadata.md`. PR [#10581](https://github.com/tiangolo/fastapi/pull/10581) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/testing.md`. PR [#10586](https://github.com/tiangolo/fastapi/pull/10586) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/schema-extra-example.md`. PR [#10597](https://github.com/tiangolo/fastapi/pull/10597) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/index.md`. PR [#10611](https://github.com/tiangolo/fastapi/pull/10611) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/response-directly.md`. PR [#10618](https://github.com/tiangolo/fastapi/pull/10618) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/additional-responses.md`. PR [#10626](https://github.com/tiangolo/fastapi/pull/10626) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/response-cookies.md`. PR [#10627](https://github.com/tiangolo/fastapi/pull/10627) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/response-headers.md`. PR [#10628](https://github.com/tiangolo/fastapi/pull/10628) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/response-change-status-code.md`. PR [#10632](https://github.com/tiangolo/fastapi/pull/10632) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/advanced-dependencies.md`. PR [#10633](https://github.com/tiangolo/fastapi/pull/10633) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/security/index.md`. PR [#10635](https://github.com/tiangolo/fastapi/pull/10635) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/using-request-directly.md`. PR [#10653](https://github.com/tiangolo/fastapi/pull/10653) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/dataclasses.md`. PR [#10667](https://github.com/tiangolo/fastapi/pull/10667) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/middleware.md`. PR [#10668](https://github.com/tiangolo/fastapi/pull/10668) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/sub-applications.md`. PR [#10671](https://github.com/tiangolo/fastapi/pull/10671) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/websockets.md`. PR [#10687](https://github.com/tiangolo/fastapi/pull/10687) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/testing-websockets.md`. PR [#10703](https://github.com/tiangolo/fastapi/pull/10703) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/testing-events.md`. PR [#10704](https://github.com/tiangolo/fastapi/pull/10704) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/testing-dependencies.md`. PR [#10706](https://github.com/tiangolo/fastapi/pull/10706) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/openapi-callbacks.md`. PR [#10710](https://github.com/tiangolo/fastapi/pull/10710) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/settings.md`. PR [#10709](https://github.com/tiangolo/fastapi/pull/10709) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/wsgi.md`. PR [#10713](https://github.com/tiangolo/fastapi/pull/10713) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/deployment/index.md`. PR [#10733](https://github.com/tiangolo/fastapi/pull/10733) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/deployment/https.md`. PR [#10737](https://github.com/tiangolo/fastapi/pull/10737) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/deployment/manually.md`. PR [#10738](https://github.com/tiangolo/fastapi/pull/10738) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/deployment/concepts.md`. PR [#10744](https://github.com/tiangolo/fastapi/pull/10744) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Update German translation for `docs/de/docs/features.md`. PR [#10284](https://github.com/tiangolo/fastapi/pull/10284) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/deployment/server-workers.md`. PR [#10747](https://github.com/tiangolo/fastapi/pull/10747) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/deployment/docker.md`. PR [#10759](https://github.com/tiangolo/fastapi/pull/10759) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/how-to/index.md`. PR [#10769](https://github.com/tiangolo/fastapi/pull/10769) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/how-to/general.md`. PR [#10770](https://github.com/tiangolo/fastapi/pull/10770) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/how-to/graphql.md`. PR [#10788](https://github.com/tiangolo/fastapi/pull/10788) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/how-to/custom-request-and-route.md`. PR [#10789](https://github.com/tiangolo/fastapi/pull/10789) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/how-to/conditional-openapi.md`. PR [#10790](https://github.com/tiangolo/fastapi/pull/10790) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/how-to/separate-openapi-schemas.md`. PR [#10796](https://github.com/tiangolo/fastapi/pull/10796) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/how-to/configure-swagger-ui.md`. PR [#10804](https://github.com/tiangolo/fastapi/pull/10804) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/how-to/custom-docs-ui-assets.md`. PR [#10803](https://github.com/tiangolo/fastapi/pull/10803) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/reference/parameters.md`. PR [#10814](https://github.com/tiangolo/fastapi/pull/10814) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/reference/status.md`. PR [#10815](https://github.com/tiangolo/fastapi/pull/10815) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/reference/uploadfile.md`. PR [#10816](https://github.com/tiangolo/fastapi/pull/10816) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/reference/exceptions.md`. PR [#10817](https://github.com/tiangolo/fastapi/pull/10817) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/reference/dependencies.md`. PR [#10818](https://github.com/tiangolo/fastapi/pull/10818) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/reference/apirouter.md`. PR [#10819](https://github.com/tiangolo/fastapi/pull/10819) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/reference/websockets.md`. PR [#10822](https://github.com/tiangolo/fastapi/pull/10822) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/reference/httpconnection.md`. PR [#10823](https://github.com/tiangolo/fastapi/pull/10823) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/reference/response.md`. PR [#10824](https://github.com/tiangolo/fastapi/pull/10824) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/reference/middleware.md`. PR [#10837](https://github.com/tiangolo/fastapi/pull/10837) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/reference/openapi/*.md`. PR [#10838](https://github.com/tiangolo/fastapi/pull/10838) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/reference/security/index.md`. PR [#10839](https://github.com/tiangolo/fastapi/pull/10839) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/reference/staticfiles.md`. PR [#10841](https://github.com/tiangolo/fastapi/pull/10841) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/reference/testclient.md`. PR [#10843](https://github.com/tiangolo/fastapi/pull/10843) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/project-generation.md`. PR [#10851](https://github.com/tiangolo/fastapi/pull/10851) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/history-design-future.md`. PR [#10865](https://github.com/tiangolo/fastapi/pull/10865) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10422](https://github.com/tiangolo/fastapi/pull/10422) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/global-dependencies.md`. PR [#10420](https://github.com/tiangolo/fastapi/pull/10420) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Update German translation for `docs/de/docs/fastapi-people.md`. PR [#10285](https://github.com/tiangolo/fastapi/pull/10285) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/sub-dependencies.md`. PR [#10409](https://github.com/tiangolo/fastapi/pull/10409) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/security/index.md`. PR [#10429](https://github.com/tiangolo/fastapi/pull/10429) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#10411](https://github.com/tiangolo/fastapi/pull/10411) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/extra-data-types.md`. PR [#10534](https://github.com/tiangolo/fastapi/pull/10534) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/security/simple-oauth2.md`. PR [#10504](https://github.com/tiangolo/fastapi/pull/10504) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/security/get-current-user.md`. PR [#10439](https://github.com/tiangolo/fastapi/pull/10439) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/request-forms-and-files.md`. PR [#10368](https://github.com/tiangolo/fastapi/pull/10368) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/encoder.md`. PR [#10385](https://github.com/tiangolo/fastapi/pull/10385) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/request-forms.md`. PR [#10361](https://github.com/tiangolo/fastapi/pull/10361) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/deployment/versions.md`. PR [#10491](https://github.com/tiangolo/fastapi/pull/10491) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/async.md`. PR [#10449](https://github.com/tiangolo/fastapi/pull/10449) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/cookie-params.md`. PR [#10323](https://github.com/tiangolo/fastapi/pull/10323) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10407](https://github.com/tiangolo/fastapi/pull/10407) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/dependencies/index.md`. PR [#10399](https://github.com/tiangolo/fastapi/pull/10399) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/header-params.md`. PR [#10326](https://github.com/tiangolo/fastapi/pull/10326) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/path-params-numeric-validations.md`. PR [#10307](https://github.com/tiangolo/fastapi/pull/10307) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/query-params-str-validations.md`. PR [#10304](https://github.com/tiangolo/fastapi/pull/10304) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/request-files.md`. PR [#10364](https://github.com/tiangolo/fastapi/pull/10364) by [@nilslindemann](https://github.com/nilslindemann).
+* :globe_with_meridians: Add Portuguese translation for `docs/pt/docs/advanced/templates.md`. PR [#11338](https://github.com/tiangolo/fastapi/pull/11338) by [@SamuelBFavarin](https://github.com/SamuelBFavarin).
+* 🌐 Add Bengali translations for `docs/bn/docs/learn/index.md`. PR [#11337](https://github.com/tiangolo/fastapi/pull/11337) by [@imtiaz101325](https://github.com/imtiaz101325).
+* 🌐 Fix Korean translation for `docs/ko/docs/index.md`. PR [#11296](https://github.com/tiangolo/fastapi/pull/11296) by [@choi-haram](https://github.com/choi-haram).
+* 🌐 Add Korean translation for `docs/ko/docs/about/index.md`. PR [#11299](https://github.com/tiangolo/fastapi/pull/11299) by [@choi-haram](https://github.com/choi-haram).
+* 🌐 Add Korean translation for `docs/ko/docs/advanced/index.md`. PR [#9613](https://github.com/tiangolo/fastapi/pull/9613) by [@ElliottLarsen](https://github.com/ElliottLarsen).
+* 🌐 Add German translation for `docs/de/docs/how-to/extending-openapi.md`. PR [#10794](https://github.com/tiangolo/fastapi/pull/10794) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/metadata.md`. PR [#11286](https://github.com/tiangolo/fastapi/pull/11286) by [@jackleeio](https://github.com/jackleeio).
+* 🌐 Update Chinese translation for `docs/zh/docs/contributing.md`. PR [#10887](https://github.com/tiangolo/fastapi/pull/10887) by [@Aruelius](https://github.com/Aruelius).
+* 🌐 Add Azerbaijani translation for `docs/az/docs/fastapi-people.md`. PR [#11195](https://github.com/tiangolo/fastapi/pull/11195) by [@vusallyv](https://github.com/vusallyv).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/index.md`. PR [#11223](https://github.com/tiangolo/fastapi/pull/11223) by [@kohiry](https://github.com/kohiry).
+* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params.md`. PR [#11242](https://github.com/tiangolo/fastapi/pull/11242) by [@jackleeio](https://github.com/jackleeio).
+* 🌐 Add Azerbaijani translation for `docs/az/learn/index.md`. PR [#11192](https://github.com/tiangolo/fastapi/pull/11192) by [@vusallyv](https://github.com/vusallyv).
+
+### Internal
+
+* 👥 Update FastAPI People. PR [#11387](https://github.com/tiangolo/fastapi/pull/11387) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump actions/cache from 3 to 4. PR [#10988](https://github.com/tiangolo/fastapi/pull/10988) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.8.11 to 1.8.14. PR [#11318](https://github.com/tiangolo/fastapi/pull/11318) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pillow from 10.1.0 to 10.2.0. PR [#11011](https://github.com/tiangolo/fastapi/pull/11011) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump black from 23.3.0 to 24.3.0. PR [#11325](https://github.com/tiangolo/fastapi/pull/11325) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👷 Add cron to run test once a week on monday. PR [#11377](https://github.com/tiangolo/fastapi/pull/11377) by [@estebanx64](https://github.com/estebanx64).
+* ➕ Replace mkdocs-markdownextradata-plugin with mkdocs-macros-plugin. PR [#11383](https://github.com/tiangolo/fastapi/pull/11383) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Disable MkDocs insiders social plugin while an issue in MkDocs Material is handled. PR [#11373](https://github.com/tiangolo/fastapi/pull/11373) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Fix logic for when to install and use MkDocs Insiders. PR [#11372](https://github.com/tiangolo/fastapi/pull/11372) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Do not use Python packages cache for publish. PR [#11366](https://github.com/tiangolo/fastapi/pull/11366) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Add CI to test sdists for redistribution (e.g. Linux distros). PR [#11365](https://github.com/tiangolo/fastapi/pull/11365) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update build-docs GitHub Action path filter. PR [#11354](https://github.com/tiangolo/fastapi/pull/11354) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update Ruff config, add extra ignore rule from SQLModel. PR [#11353](https://github.com/tiangolo/fastapi/pull/11353) by [@tiangolo](https://github.com/tiangolo).
+* ⬆️ Upgrade configuration for Ruff v0.2.0. PR [#11075](https://github.com/tiangolo/fastapi/pull/11075) by [@charliermarsh](https://github.com/charliermarsh).
+* 🔧 Update sponsors, add MongoDB. PR [#11346](https://github.com/tiangolo/fastapi/pull/11346) by [@tiangolo](https://github.com/tiangolo).
+* ⬆ Bump dorny/paths-filter from 2 to 3. PR [#11028](https://github.com/tiangolo/fastapi/pull/11028) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump dawidd6/action-download-artifact from 3.0.0 to 3.1.4. PR [#11310](https://github.com/tiangolo/fastapi/pull/11310) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ♻️ Refactor computing FastAPI People, include 3 months, 6 months, 1 year, based on comment date, not discussion date. PR [#11304](https://github.com/tiangolo/fastapi/pull/11304) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People. PR [#11228](https://github.com/tiangolo/fastapi/pull/11228) by [@tiangolo](https://github.com/tiangolo).
+* 🔥 Remove Jina AI QA Bot from the docs. PR [#11268](https://github.com/tiangolo/fastapi/pull/11268) by [@nan-wang](https://github.com/nan-wang).
+* 🔧 Update sponsors, remove Jina, remove Powens, move TestDriven.io. PR [#11213](https://github.com/tiangolo/fastapi/pull/11213) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.110.0 (2024-02-24)
+
+### Breaking Changes
+
+* 🐛 Fix unhandled growing memory for internal server errors, refactor dependencies with `yield` and `except` to require raising again as in regular Python. PR [#11191](https://github.com/tiangolo/fastapi/pull/11191) by [@tiangolo](https://github.com/tiangolo).
+ * This is a breaking change (and only slightly) if you used dependencies with `yield`, used `except` in those dependencies, and didn't raise again.
+ * This was reported internally by [@rushilsrivastava](https://github.com/rushilsrivastava) as a memory leak when the server had unhandled exceptions that would produce internal server errors, the memory allocated before that point would not be released.
+ * Read the new docs: [Dependencies with `yield` and `except`](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-except).
+
+In short, if you had dependencies that looked like:
+
+```Python
+def my_dep():
+ try:
+ yield
+ except SomeException:
+ pass
+```
+
+Now you need to make sure you raise again after `except`, just as you would in regular Python:
+
+```Python
+def my_dep():
+ try:
+ yield
+ except SomeException:
+ raise
+```
+
+### Docs
+
+* ✏️ Fix minor typos in `docs/ko/docs/`. PR [#11126](https://github.com/tiangolo/fastapi/pull/11126) by [@KaniKim](https://github.com/KaniKim).
+* ✏️ Fix minor typo in `fastapi/applications.py`. PR [#11099](https://github.com/tiangolo/fastapi/pull/11099) by [@JacobHayes](https://github.com/JacobHayes).
+
+### Translations
+
+* 🌐 Add German translation for `docs/de/docs/reference/background.md`. PR [#10820](https://github.com/tiangolo/fastapi/pull/10820) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/reference/templating.md`. PR [#10842](https://github.com/tiangolo/fastapi/pull/10842) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/external-links.md`. PR [#10852](https://github.com/tiangolo/fastapi/pull/10852) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Update Turkish translation for `docs/tr/docs/tutorial/query-params.md`. PR [#11162](https://github.com/tiangolo/fastapi/pull/11162) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Add German translation for `docs/de/docs/reference/encoders.md`. PR [#10840](https://github.com/tiangolo/fastapi/pull/10840) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/reference/responses.md`. PR [#10825](https://github.com/tiangolo/fastapi/pull/10825) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/reference/request.md`. PR [#10821](https://github.com/tiangolo/fastapi/pull/10821) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add Turkish translation for `docs/tr/docs/tutorial/query-params.md`. PR [#11078](https://github.com/tiangolo/fastapi/pull/11078) by [@emrhnsyts](https://github.com/emrhnsyts).
+* 🌐 Add German translation for `docs/de/docs/reference/fastapi.md`. PR [#10813](https://github.com/tiangolo/fastapi/pull/10813) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/newsletter.md`. PR [#10853](https://github.com/tiangolo/fastapi/pull/10853) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/learn/index.md`. PR [#11142](https://github.com/tiangolo/fastapi/pull/11142) by [@hsuanchi](https://github.com/hsuanchi).
+* 🌐 Add Korean translation for `/docs/ko/docs/tutorial/dependencies/global-dependencies.md`. PR [#11123](https://github.com/tiangolo/fastapi/pull/11123) by [@riroan](https://github.com/riroan).
+* 🌐 Add Korean translation for `/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#11124](https://github.com/tiangolo/fastapi/pull/11124) by [@riroan](https://github.com/riroan).
+* 🌐 Add Korean translation for `/docs/ko/docs/tutorial/schema-extra-example.md`. PR [#11121](https://github.com/tiangolo/fastapi/pull/11121) by [@KaniKim](https://github.com/KaniKim).
+* 🌐 Add Korean translation for `/docs/ko/docs/tutorial/body-fields.md`. PR [#11112](https://github.com/tiangolo/fastapi/pull/11112) by [@KaniKim](https://github.com/KaniKim).
+* 🌐 Add Korean translation for `/docs/ko/docs/tutorial/cookie-params.md`. PR [#11118](https://github.com/tiangolo/fastapi/pull/11118) by [@riroan](https://github.com/riroan).
+* 🌐 Update Korean translation for `/docs/ko/docs/dependencies/index.md`. PR [#11114](https://github.com/tiangolo/fastapi/pull/11114) by [@KaniKim](https://github.com/KaniKim).
+* 🌐 Update Korean translation for `/docs/ko/docs/deployment/docker.md`. PR [#11113](https://github.com/tiangolo/fastapi/pull/11113) by [@KaniKim](https://github.com/KaniKim).
+* 🌐 Update Turkish translation for `docs/tr/docs/tutorial/first-steps.md`. PR [#11094](https://github.com/tiangolo/fastapi/pull/11094) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Add Spanish translation for `docs/es/docs/advanced/security/index.md`. PR [#2278](https://github.com/tiangolo/fastapi/pull/2278) by [@Xaraxx](https://github.com/Xaraxx).
+* 🌐 Add Spanish translation for `docs/es/docs/advanced/response-headers.md`. PR [#2276](https://github.com/tiangolo/fastapi/pull/2276) by [@Xaraxx](https://github.com/Xaraxx).
+* 🌐 Add Spanish translation for `docs/es/docs/deployment/index.md` and `~/deployment/versions.md`. PR [#9669](https://github.com/tiangolo/fastapi/pull/9669) by [@pabloperezmoya](https://github.com/pabloperezmoya).
+* 🌐 Add Spanish translation for `docs/es/docs/benchmarks.md`. PR [#10928](https://github.com/tiangolo/fastapi/pull/10928) by [@pablocm83](https://github.com/pablocm83).
+* 🌐 Add Spanish translation for `docs/es/docs/advanced/response-change-status-code.md`. PR [#11100](https://github.com/tiangolo/fastapi/pull/11100) by [@alejsdev](https://github.com/alejsdev).
+
+## 0.109.2 (2024-02-04)
+
+### Upgrades
+
+* ⬆️ Upgrade version of Starlette to `>= 0.36.3`. PR [#11086](https://github.com/tiangolo/fastapi/pull/11086) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Update Turkish translation for `docs/tr/docs/fastapi-people.md`. PR [#10547](https://github.com/tiangolo/fastapi/pull/10547) by [@alperiox](https://github.com/alperiox).
+
+### Internal
+
+* 🍱 Add new FastAPI logo. PR [#11090](https://github.com/tiangolo/fastapi/pull/11090) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.109.1 (2024-02-03)
+
+### Security fixes
+
+* ⬆️ Upgrade minimum version of `python-multipart` to `>=0.0.7` to fix a vulnerability when using form data with a ReDos attack. You can also simply upgrade `python-multipart`.
+
+Read more in the [advisory: Content-Type Header ReDoS](https://github.com/tiangolo/fastapi/security/advisories/GHSA-qf9m-vfgh-m389).
+
+### 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
+
+* 📝 Tweak wording in `help-fastapi.md`. PR [#11040](https://github.com/tiangolo/fastapi/pull/11040) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Tweak docs for Behind a Proxy. PR [#11038](https://github.com/tiangolo/fastapi/pull/11038) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Add External Link: 10 Tips for adding SQLAlchemy to FastAPI. PR [#11036](https://github.com/tiangolo/fastapi/pull/11036) by [@Donnype](https://github.com/Donnype).
+* 📝 Add External Link: Tips on migrating from Flask to FastAPI and vice-versa. PR [#11029](https://github.com/tiangolo/fastapi/pull/11029) by [@jtemporal](https://github.com/jtemporal).
+* 📝 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).
+* ✏️ 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).
+
+### Translations
+
+* 🌐 Add Spanish translation for `docs/es/docs/external-links.md`. PR [#10933](https://github.com/tiangolo/fastapi/pull/10933) by [@pablocm83](https://github.com/pablocm83).
+* 🌐 Update Korean translation for `docs/ko/docs/tutorial/first-steps.md`, `docs/ko/docs/tutorial/index.md`, `docs/ko/docs/tutorial/path-params.md`, and `docs/ko/docs/tutorial/query-params.md`. PR [#4218](https://github.com/tiangolo/fastapi/pull/4218) by [@SnowSuno](https://github.com/SnowSuno).
+* 🌐 Add Chinese translation for `docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10870](https://github.com/tiangolo/fastapi/pull/10870) by [@zhiquanchi](https://github.com/zhiquanchi).
+* 🌐 Add Chinese translation for `docs/zh/docs/deployment/concepts.md`. PR [#10282](https://github.com/tiangolo/fastapi/pull/10282) by [@xzmeng](https://github.com/xzmeng).
+* 🌐 Add Azerbaijani translation for `docs/az/docs/index.md`. PR [#11047](https://github.com/tiangolo/fastapi/pull/11047) by [@aykhans](https://github.com/aykhans).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/middleware.md`. PR [#2829](https://github.com/tiangolo/fastapi/pull/2829) by [@JeongHyeongKim](https://github.com/JeongHyeongKim).
+* 🌐 Add German translation for `docs/de/docs/tutorial/body-nested-models.md`. PR [#10313](https://github.com/tiangolo/fastapi/pull/10313) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add Persian translation for `docs/fa/docs/tutorial/middleware.md`. PR [#9695](https://github.com/tiangolo/fastapi/pull/9695) by [@mojtabapaso](https://github.com/mojtabapaso).
+* 🌐 Update Farsi translation for `docs/fa/docs/index.md`. PR [#10216](https://github.com/tiangolo/fastapi/pull/10216) by [@theonlykingpin](https://github.com/theonlykingpin).
+* 🌐 Add German translation for `docs/de/docs/tutorial/body-fields.md`. PR [#10310](https://github.com/tiangolo/fastapi/pull/10310) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/body.md`. PR [#10295](https://github.com/tiangolo/fastapi/pull/10295) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/body-multiple-params.md`. PR [#10308](https://github.com/tiangolo/fastapi/pull/10308) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/security/get-current-user.md`. PR [#2681](https://github.com/tiangolo/fastapi/pull/2681) by [@sh0nk](https://github.com/sh0nk).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/advanced-dependencies.md`. PR [#3798](https://github.com/tiangolo/fastapi/pull/3798) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/events.md`. PR [#3815](https://github.com/tiangolo/fastapi/pull/3815) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/behind-a-proxy.md`. PR [#3820](https://github.com/tiangolo/fastapi/pull/3820) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/testing-events.md`. PR [#3818](https://github.com/tiangolo/fastapi/pull/3818) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/testing-websockets.md`. PR [#3817](https://github.com/tiangolo/fastapi/pull/3817) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/testing-database.md`. PR [#3821](https://github.com/tiangolo/fastapi/pull/3821) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/deployment/deta.md`. PR [#3837](https://github.com/tiangolo/fastapi/pull/3837) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/history-design-future.md`. PR [#3832](https://github.com/tiangolo/fastapi/pull/3832) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/project-generation.md`. PR [#3831](https://github.com/tiangolo/fastapi/pull/3831) by [@jaystone776](https://github.com/jaystone776).
+* 🌐 Add Chinese translation for `docs/zh/docs/deployment/docker.md`. PR [#10296](https://github.com/tiangolo/fastapi/pull/10296) by [@xzmeng](https://github.com/xzmeng).
+* 🌐 Update Spanish translation for `docs/es/docs/features.md`. PR [#10884](https://github.com/tiangolo/fastapi/pull/10884) by [@pablocm83](https://github.com/pablocm83).
+* 🌐 Add Spanish translation for `docs/es/docs/newsletter.md`. PR [#10922](https://github.com/tiangolo/fastapi/pull/10922) by [@pablocm83](https://github.com/pablocm83).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/background-tasks.md`. PR [#5910](https://github.com/tiangolo/fastapi/pull/5910) by [@junah201](https://github.com/junah201).
+* :globe_with_meridians: Add Turkish translation for `docs/tr/docs/alternatives.md`. PR [#10502](https://github.com/tiangolo/fastapi/pull/10502) by [@alperiox](https://github.com/alperiox).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/dependencies/index.md`. PR [#10989](https://github.com/tiangolo/fastapi/pull/10989) by [@KaniKim](https://github.com/KaniKim).
+* 🌐 Add Korean translation for `/docs/ko/docs/tutorial/body.md`. PR [#11000](https://github.com/tiangolo/fastapi/pull/11000) by [@KaniKim](https://github.com/KaniKim).
+* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/schema-extra-example.md`. PR [#4065](https://github.com/tiangolo/fastapi/pull/4065) by [@luccasmmg](https://github.com/luccasmmg).
+* 🌐 Add Turkish translation for `docs/tr/docs/history-design-future.md`. PR [#11012](https://github.com/tiangolo/fastapi/pull/11012) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Add Turkish translation for `docs/tr/docs/resources/index.md`. PR [#11020](https://github.com/tiangolo/fastapi/pull/11020) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Add Turkish translation for `docs/tr/docs/how-to/index.md`. PR [#11021](https://github.com/tiangolo/fastapi/pull/11021) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Add German translation for `docs/de/docs/tutorial/query-params.md`. PR [#10293](https://github.com/tiangolo/fastapi/pull/10293) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/benchmarks.md`. PR [#10866](https://github.com/tiangolo/fastapi/pull/10866) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add Turkish translation for `docs/tr/docs/learn/index.md`. PR [#11014](https://github.com/tiangolo/fastapi/pull/11014) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Add Persian translation for `docs/fa/docs/tutorial/security/index.md`. PR [#9945](https://github.com/tiangolo/fastapi/pull/9945) by [@mojtabapaso](https://github.com/mojtabapaso).
+* 🌐 Add Turkish translation for `docs/tr/docs/help/index.md`. PR [#11013](https://github.com/tiangolo/fastapi/pull/11013) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Add Turkish translation for `docs/tr/docs/about/index.md`. PR [#11006](https://github.com/tiangolo/fastapi/pull/11006) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Update Turkish translation for `docs/tr/docs/benchmarks.md`. PR [#11005](https://github.com/tiangolo/fastapi/pull/11005) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Add Italian translation for `docs/it/docs/index.md`. PR [#5233](https://github.com/tiangolo/fastapi/pull/5233) by [@matteospanio](https://github.com/matteospanio).
+* 🌐 Add Korean translation for `docs/ko/docs/help/index.md`. PR [#10983](https://github.com/tiangolo/fastapi/pull/10983) by [@KaniKim](https://github.com/KaniKim).
+* 🌐 Add Korean translation for `docs/ko/docs/features.md`. PR [#10976](https://github.com/tiangolo/fastapi/pull/10976) by [@KaniKim](https://github.com/KaniKim).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/security/get-current-user.md`. PR [#5737](https://github.com/tiangolo/fastapi/pull/5737) by [@KdHyeon0661](https://github.com/KdHyeon0661).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/security/first-steps.md`. PR [#10541](https://github.com/tiangolo/fastapi/pull/10541) by [@AlertRED](https://github.com/AlertRED).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/handling-errors.md`. PR [#10375](https://github.com/tiangolo/fastapi/pull/10375) by [@AlertRED](https://github.com/AlertRED).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/encoder.md`. PR [#10374](https://github.com/tiangolo/fastapi/pull/10374) by [@AlertRED](https://github.com/AlertRED).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/body-updates.md`. PR [#10373](https://github.com/tiangolo/fastapi/pull/10373) by [@AlertRED](https://github.com/AlertRED).
+* 🌐 Russian translation: updated `fastapi-people.md`.. PR [#10255](https://github.com/tiangolo/fastapi/pull/10255) by [@NiKuma0](https://github.com/NiKuma0).
+* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/security/index.md`. PR [#5798](https://github.com/tiangolo/fastapi/pull/5798) by [@3w36zj6](https://github.com/3w36zj6).
+* 🌐 Add German translation for `docs/de/docs/advanced/generate-clients.md`. PR [#10725](https://github.com/tiangolo/fastapi/pull/10725) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/openapi-webhooks.md`. PR [#10712](https://github.com/tiangolo/fastapi/pull/10712) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/custom-response.md`. PR [#10624](https://github.com/tiangolo/fastapi/pull/10624) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/advanced/additional-status-codes.md`. PR [#10617](https://github.com/tiangolo/fastapi/pull/10617) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add German translation for `docs/de/docs/tutorial/middleware.md`. PR [#10391](https://github.com/tiangolo/fastapi/pull/10391) by [@JohannesJungbluth](https://github.com/JohannesJungbluth).
+* 🌐 Add German translation for introduction documents. PR [#10497](https://github.com/tiangolo/fastapi/pull/10497) by [@nilslindemann](https://github.com/nilslindemann).
+* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/encoder.md`. PR [#1955](https://github.com/tiangolo/fastapi/pull/1955) by [@SwftAlpc](https://github.com/SwftAlpc).
+* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/extra-data-types.md`. PR [#1932](https://github.com/tiangolo/fastapi/pull/1932) by [@SwftAlpc](https://github.com/SwftAlpc).
+* 🌐 Add Turkish translation for `docs/tr/docs/async.md`. PR [#5191](https://github.com/tiangolo/fastapi/pull/5191) by [@BilalAlpaslan](https://github.com/BilalAlpaslan).
+* 🌐 Add Turkish translation for `docs/tr/docs/project-generation.md`. PR [#5192](https://github.com/tiangolo/fastapi/pull/5192) by [@BilalAlpaslan](https://github.com/BilalAlpaslan).
+* 🌐 Add Korean translation for `docs/ko/docs/deployment/docker.md`. PR [#5657](https://github.com/tiangolo/fastapi/pull/5657) by [@nearnear](https://github.com/nearnear).
+* 🌐 Add Korean translation for `docs/ko/docs/deployment/server-workers.md`. PR [#4935](https://github.com/tiangolo/fastapi/pull/4935) by [@jujumilk3](https://github.com/jujumilk3).
+* 🌐 Add Korean translation for `docs/ko/docs/deployment/index.md`. PR [#4561](https://github.com/tiangolo/fastapi/pull/4561) by [@jujumilk3](https://github.com/jujumilk3).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/path-operation-configuration.md`. PR [#3639](https://github.com/tiangolo/fastapi/pull/3639) by [@jungsu-kwon](https://github.com/jungsu-kwon).
+* 🌐 Modify the description of `zh` - Traditional Chinese. PR [#10889](https://github.com/tiangolo/fastapi/pull/10889) by [@cherinyy](https://github.com/cherinyy).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/static-files.md`. PR [#2957](https://github.com/tiangolo/fastapi/pull/2957) by [@jeesang7](https://github.com/jeesang7).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/response-model.md`. PR [#2766](https://github.com/tiangolo/fastapi/pull/2766) by [@hard-coders](https://github.com/hard-coders).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/body-multiple-params.md`. PR [#2461](https://github.com/tiangolo/fastapi/pull/2461) by [@PandaHun](https://github.com/PandaHun).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/query-params-str-validations.md`. PR [#2415](https://github.com/tiangolo/fastapi/pull/2415) by [@hard-coders](https://github.com/hard-coders).
+* 🌐 Add Korean translation for `docs/ko/docs/python-types.md`. PR [#2267](https://github.com/tiangolo/fastapi/pull/2267) by [@jrim](https://github.com/jrim).
+* 🌐 Add Korean translation for `docs/ko/docs/tutorial/body-nested-models.md`. PR [#2506](https://github.com/tiangolo/fastapi/pull/2506) by [@hard-coders](https://github.com/hard-coders).
+* 🌐 Add Korean translation for `docs/ko/docs/learn/index.md`. PR [#10977](https://github.com/tiangolo/fastapi/pull/10977) by [@KaniKim](https://github.com/KaniKim).
+* 🌐 Initialize translations for Traditional Chinese. PR [#10505](https://github.com/tiangolo/fastapi/pull/10505) by [@hsuanchi](https://github.com/hsuanchi).
+* ✏️ 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 translation 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
+
+* 👥 Update FastAPI People. PR [#11074](https://github.com/tiangolo/fastapi/pull/11074) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors: add Coherence. PR [#11066](https://github.com/tiangolo/fastapi/pull/11066) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Upgrade GitHub Action issue-manager. PR [#11056](https://github.com/tiangolo/fastapi/pull/11056) by [@tiangolo](https://github.com/tiangolo).
+* 🍱 Update sponsors: TalkPython badge. PR [#11052](https://github.com/tiangolo/fastapi/pull/11052) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors: TalkPython badge image. PR [#11048](https://github.com/tiangolo/fastapi/pull/11048) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors, remove Deta. PR [#11041](https://github.com/tiangolo/fastapi/pull/11041) by [@tiangolo](https://github.com/tiangolo).
+* 💄 Fix CSS breaking RTL languages (erroneously introduced by a previous RTL PR). PR [#11039](https://github.com/tiangolo/fastapi/pull/11039) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Add Italian to `mkdocs.yml`. PR [#11016](https://github.com/tiangolo/fastapi/pull/11016) by [@alejsdev](https://github.com/alejsdev).
+* 🔨 Verify `mkdocs.yml` languages in CI, update `docs.py`. PR [#11009](https://github.com/tiangolo/fastapi/pull/11009) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update config in `label-approved.yml` to accept translations with 1 reviewer. PR [#11007](https://github.com/tiangolo/fastapi/pull/11007) by [@alejsdev](https://github.com/alejsdev).
+* 👷 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 (2024-01-11)
+
+### Features
+
+* ✨ Add support for Python 3.12. PR [#10666](https://github.com/tiangolo/fastapi/pull/10666) by [@Jamim](https://github.com/Jamim).
+
+### Upgrades
+
+* ⬆️ Upgrade Starlette to >=0.35.0,<0.36.0. PR [#10938](https://github.com/tiangolo/fastapi/pull/10938) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* ✏️ Fix typo in `docs/en/docs/alternatives.md`. PR [#10931](https://github.com/tiangolo/fastapi/pull/10931) by [@s111d](https://github.com/s111d).
+* 📝 Replace `email` with `username` in `docs_src/security/tutorial007` code examples. PR [#10649](https://github.com/tiangolo/fastapi/pull/10649) by [@nilslindemann](https://github.com/nilslindemann).
+* 📝 Add VS Code tutorial link. PR [#10592](https://github.com/tiangolo/fastapi/pull/10592) by [@nilslindemann](https://github.com/nilslindemann).
+* 📝 Add notes about Pydantic v2's new `.model_dump()`. PR [#10929](https://github.com/tiangolo/fastapi/pull/10929) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Fix broken link in `docs/en/docs/tutorial/sql-databases.md`. PR [#10765](https://github.com/tiangolo/fastapi/pull/10765) by [@HurSungYun](https://github.com/HurSungYun).
+* 📝 Add External Link: FastAPI application monitoring made easy. PR [#10917](https://github.com/tiangolo/fastapi/pull/10917) by [@tiangolo](https://github.com/tiangolo).
+* ✨ Generate automatic language names for docs translations. PR [#5354](https://github.com/tiangolo/fastapi/pull/5354) by [@jakul](https://github.com/jakul).
+* ✏️ Fix typos in `docs/en/docs/alternatives.md` and `docs/en/docs/tutorial/dependencies/index.md`. PR [#10906](https://github.com/tiangolo/fastapi/pull/10906) by [@s111d](https://github.com/s111d).
+* ✏️ Fix typos in `docs/en/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10834](https://github.com/tiangolo/fastapi/pull/10834) by [@Molkree](https://github.com/Molkree).
+* 📝 Add article: "Building a RESTful API with FastAPI: Secure Signup and Login Functionality Included". PR [#9733](https://github.com/tiangolo/fastapi/pull/9733) by [@dxphilo](https://github.com/dxphilo).
+* 📝 Add warning about lifecycle events with `AsyncClient`. PR [#4167](https://github.com/tiangolo/fastapi/pull/4167) by [@andrew-chang-dewitt](https://github.com/andrew-chang-dewitt).
+* ✏️ Fix typos in `/docs/reference/exceptions.md` and `/en/docs/reference/status.md`. PR [#10809](https://github.com/tiangolo/fastapi/pull/10809) by [@clarencepenz](https://github.com/clarencepenz).
+* ✏️ Fix typo in `openapi-callbacks.md`. PR [#10673](https://github.com/tiangolo/fastapi/pull/10673) by [@kayjan](https://github.com/kayjan).
+* ✏️ Fix typo in `fastapi/routing.py` . PR [#10520](https://github.com/tiangolo/fastapi/pull/10520) by [@sepsh](https://github.com/sepsh).
+* 📝 Replace HTTP code returned in case of existing user error in docs for testing. PR [#4482](https://github.com/tiangolo/fastapi/pull/4482) by [@TristanMarion](https://github.com/TristanMarion).
+* 📝 Add blog for FastAPI & Supabase. PR [#6018](https://github.com/tiangolo/fastapi/pull/6018) by [@theinfosecguy](https://github.com/theinfosecguy).
+* 📝 Update example source files for SQL databases with SQLAlchemy. PR [#9508](https://github.com/tiangolo/fastapi/pull/9508) by [@s-mustafa](https://github.com/s-mustafa).
+* 📝 Update code examples in docs for body, replace name `create_item` with `update_item` when appropriate. PR [#5913](https://github.com/tiangolo/fastapi/pull/5913) by [@OttoAndrey](https://github.com/OttoAndrey).
+* ✏️ Fix typo in dependencies with yield source examples. PR [#10847](https://github.com/tiangolo/fastapi/pull/10847) by [@tiangolo](https://github.com/tiangolo).
+
+### Translations
+
+* 🌐 Add Bengali translation for `docs/bn/docs/index.md`. PR [#9177](https://github.com/tiangolo/fastapi/pull/9177) by [@Fahad-Md-Kamal](https://github.com/Fahad-Md-Kamal).
+* ✏️ Update Python version in `index.md` in several languages. PR [#10711](https://github.com/tiangolo/fastapi/pull/10711) by [@tamago3keran](https://github.com/tamago3keran).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/request-forms-and-files.md`. PR [#10347](https://github.com/tiangolo/fastapi/pull/10347) by [@AlertRED](https://github.com/AlertRED).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/index.md`. PR [#10362](https://github.com/tiangolo/fastapi/pull/10362) by [@rostik1410](https://github.com/rostik1410).
+* ✏️ Update Python version in `docs/ko/docs/index.md`. PR [#10680](https://github.com/tiangolo/fastapi/pull/10680) by [@Eeap](https://github.com/Eeap).
+* 🌐 Add Persian translation for `docs/fa/docs/features.md`. PR [#5887](https://github.com/tiangolo/fastapi/pull/5887) by [@amirilf](https://github.com/amirilf).
+* 🌐 Add Chinese translation for `docs/zh/docs/advanced/additional-responses.md`. PR [#10325](https://github.com/tiangolo/fastapi/pull/10325) by [@ShuibeiC](https://github.com/ShuibeiC).
+* 🌐 Fix typos in Russian translations for `docs/ru/docs/tutorial/background-tasks.md`, `docs/ru/docs/tutorial/body-nested-models.md`, `docs/ru/docs/tutorial/debugging.md`, `docs/ru/docs/tutorial/testing.md`. PR [#10311](https://github.com/tiangolo/fastapi/pull/10311) by [@AlertRED](https://github.com/AlertRED).
+* 🌐 Add Russian translation for `docs/ru/docs/tutorial/request-files.md`. PR [#10332](https://github.com/tiangolo/fastapi/pull/10332) by [@AlertRED](https://github.com/AlertRED).
+* 🌐 Add Chinese translation for `docs/zh/docs/deployment/server-workers.md`. PR [#10292](https://github.com/tiangolo/fastapi/pull/10292) by [@xzmeng](https://github.com/xzmeng).
+* 🌐 Add Chinese translation for `docs/zh/docs/deployment/cloud.md`. PR [#10291](https://github.com/tiangolo/fastapi/pull/10291) by [@xzmeng](https://github.com/xzmeng).
+* 🌐 Add Chinese translation for `docs/zh/docs/deployment/manually.md`. PR [#10279](https://github.com/tiangolo/fastapi/pull/10279) by [@xzmeng](https://github.com/xzmeng).
+* 🌐 Add Chinese translation for `docs/zh/docs/deployment/https.md`. PR [#10277](https://github.com/tiangolo/fastapi/pull/10277) by [@xzmeng](https://github.com/xzmeng).
+* 🌐 Add Chinese translation for `docs/zh/docs/deployment/index.md`. PR [#10275](https://github.com/tiangolo/fastapi/pull/10275) by [@xzmeng](https://github.com/xzmeng).
+* 🌐 Add German translation for `docs/de/docs/tutorial/first-steps.md`. PR [#9530](https://github.com/tiangolo/fastapi/pull/9530) by [@fhabers21](https://github.com/fhabers21).
+* 🌐 Update Turkish translation for `docs/tr/docs/index.md`. PR [#10444](https://github.com/tiangolo/fastapi/pull/10444) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Add Chinese translation for `docs/zh/docs/learn/index.md`. PR [#10479](https://github.com/tiangolo/fastapi/pull/10479) by [@KAZAMA-DREAM](https://github.com/KAZAMA-DREAM).
+* 🌐 Add Russian translation for `docs/ru/docs/learn/index.md`. PR [#10539](https://github.com/tiangolo/fastapi/pull/10539) by [@AlertRED](https://github.com/AlertRED).
+* 🌐 Update SQLAlchemy instruction in Chinese translation `docs/zh/docs/tutorial/sql-databases.md`. PR [#9712](https://github.com/tiangolo/fastapi/pull/9712) by [@Royc30ne](https://github.com/Royc30ne).
+* 🌐 Add Turkish translation for `docs/tr/docs/external-links.md`. PR [#10549](https://github.com/tiangolo/fastapi/pull/10549) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Add Spanish translation for `docs/es/docs/learn/index.md`. PR [#10885](https://github.com/tiangolo/fastapi/pull/10885) by [@pablocm83](https://github.com/pablocm83).
+* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-fields.md`. PR [#10670](https://github.com/tiangolo/fastapi/pull/10670) by [@ArtemKhymenko](https://github.com/ArtemKhymenko).
+* 🌐 Add Hungarian translation for `/docs/hu/docs/index.md`. PR [#10812](https://github.com/tiangolo/fastapi/pull/10812) by [@takacs](https://github.com/takacs).
+* 🌐 Add Turkish translation for `docs/tr/docs/newsletter.md`. PR [#10550](https://github.com/tiangolo/fastapi/pull/10550) by [@hasansezertasan](https://github.com/hasansezertasan).
+* 🌐 Add Spanish translation for `docs/es/docs/help/index.md`. PR [#10907](https://github.com/tiangolo/fastapi/pull/10907) by [@pablocm83](https://github.com/pablocm83).
+* 🌐 Add Spanish translation for `docs/es/docs/about/index.md`. PR [#10908](https://github.com/tiangolo/fastapi/pull/10908) by [@pablocm83](https://github.com/pablocm83).
+* 🌐 Add Spanish translation for `docs/es/docs/resources/index.md`. PR [#10909](https://github.com/tiangolo/fastapi/pull/10909) by [@pablocm83](https://github.com/pablocm83).
+
+### Internal
+
+* 👥 Update FastAPI People. PR [#10871](https://github.com/tiangolo/fastapi/pull/10871) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Upgrade custom GitHub Action comment-docs-preview-in-pr. PR [#10916](https://github.com/tiangolo/fastapi/pull/10916) by [@tiangolo](https://github.com/tiangolo).
+* ⬆️ Upgrade GitHub Action latest-changes. PR [#10915](https://github.com/tiangolo/fastapi/pull/10915) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Upgrade GitHub Action label-approved. PR [#10913](https://github.com/tiangolo/fastapi/pull/10913) by [@tiangolo](https://github.com/tiangolo).
+* ⬆️ Upgrade GitHub Action label-approved. PR [#10905](https://github.com/tiangolo/fastapi/pull/10905) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.108.0 (2023-12-26)
+
+### Upgrades
+
+* ⬆️ Upgrade Starlette to `>=0.29.0,<0.33.0`, update docs and usage of templates with new Starlette arguments. Remove pin of AnyIO `>=3.7.1,<4.0.0`, add support for AnyIO 4.x.x. PR [#10846](https://github.com/tiangolo/fastapi/pull/10846) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.107.0 (2023-12-26)
+
+### Upgrades
+
+* ⬆️ Upgrade Starlette to 0.28.0. PR [#9636](https://github.com/tiangolo/fastapi/pull/9636) by [@adriangb](https://github.com/adriangb).
+
+### Docs
+
+* 📝 Add docs: Node.js script alternative to update OpenAPI for generated clients. PR [#10845](https://github.com/tiangolo/fastapi/pull/10845) by [@alejsdev](https://github.com/alejsdev).
+* 📝 Restructure Docs section in Contributing page. PR [#10844](https://github.com/tiangolo/fastapi/pull/10844) by [@alejsdev](https://github.com/alejsdev).
+
+## 0.106.0 (2023-12-25)
+
+### Breaking Changes
+
+Using resources from dependencies with `yield` in background tasks is no longer supported.
+
+This change is what supports the new features, read below. 🤓
+
+### Dependencies with `yield`, `HTTPException` and Background Tasks
+
+Dependencies with `yield` now can raise `HTTPException` and other exceptions after `yield`. 🎉
+
+Read the new docs here: [Dependencies with `yield` and `HTTPException`](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception).
+
+```Python
+from fastapi import Depends, FastAPI, HTTPException
+from typing_extensions import Annotated
+
+app = FastAPI()
+
+
+data = {
+ "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"},
+ "portal-gun": {"description": "Gun to create portals", "owner": "Rick"},
+}
+
+
+class OwnerError(Exception):
+ pass
+
+
+def get_username():
+ try:
+ yield "Rick"
+ except OwnerError as e:
+ raise HTTPException(status_code=400, detail=f"Owner error: {e}")
+
+
+@app.get("/items/{item_id}")
+def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
+ if item_id not in data:
+ raise HTTPException(status_code=404, detail="Item not found")
+ item = data[item_id]
+ if item["owner"] != username:
+ raise OwnerError(username)
+ return item
+```
+
+---
+
+Before FastAPI 0.106.0, raising exceptions after `yield` was not possible, the exit code in dependencies with `yield` was executed *after* the response was sent, so [Exception Handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers) would have already run.
+
+This was designed this way mainly to allow using the same objects "yielded" by dependencies inside of background tasks, because the exit code would be executed after the background tasks were finished.
+
+Nevertheless, as this would mean waiting for the response to travel through the network while unnecessarily holding a resource in a dependency with yield (for example a database connection), this was changed in FastAPI 0.106.0.
+
+Additionally, a background task is normally an independent set of logic that should be handled separately, with its own resources (e.g. its own database connection).
+
+If you used to rely on this behavior, now you should create the resources for background tasks inside the background task itself, and use internally only data that doesn't depend on the resources of dependencies with `yield`.
+
+For example, instead of using the same database session, you would create a new database session inside of the background task, and you would obtain the objects from the database using this new session. And then instead of passing the object from the database as a parameter to the background task function, you would pass the ID of that object and then obtain the object again inside the background task function.
+
+The sequence of execution before FastAPI 0.106.0 was like this diagram:
+
+Time flows from top to bottom. And each column is one of the parts interacting or executing code.
+
+```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 -->> dep: Raise HTTPException
+ dep -->> handler: Auto forward exception
+ handler -->> client: HTTP error response
+ operation -->> dep: Raise other exception
+ dep -->> handler: Auto forward 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
+```
+
+The new execution flow can be found in the docs: [Execution of dependencies with `yield`](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#execution-of-dependencies-with-yield).
+
+### Features
+
+* ✨ Add support for raising exceptions (including `HTTPException`) in dependencies with `yield` in the exit code, do not support them in background tasks. PR [#10831](https://github.com/tiangolo/fastapi/pull/10831) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* 👥 Update FastAPI People. PR [#10567](https://github.com/tiangolo/fastapi/pull/10567) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.105.0 (2023-12-12)
+
+### Features
+
+* ✨ Add support for multiple Annotated annotations, e.g. `Annotated[str, Field(), Query()]`. PR [#10773](https://github.com/tiangolo/fastapi/pull/10773) by [@tiangolo](https://github.com/tiangolo).
+
+### Refactors
+
+* 🔥 Remove unused NoneType. PR [#10774](https://github.com/tiangolo/fastapi/pull/10774) by [@tiangolo](https://github.com/tiangolo).
+
+### Docs
+
+* 📝 Tweak default suggested configs for generating clients. PR [#10736](https://github.com/tiangolo/fastapi/pull/10736) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* 🔧 Update sponsors, add Scalar. PR [#10728](https://github.com/tiangolo/fastapi/pull/10728) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors, add PropelAuth. PR [#10760](https://github.com/tiangolo/fastapi/pull/10760) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Update build docs, verify README on CI. PR [#10750](https://github.com/tiangolo/fastapi/pull/10750) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors, remove Fern. PR [#10729](https://github.com/tiangolo/fastapi/pull/10729) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors, add Codacy. PR [#10677](https://github.com/tiangolo/fastapi/pull/10677) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors, add Reflex. PR [#10676](https://github.com/tiangolo/fastapi/pull/10676) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Update release notes, move and check latest-changes. PR [#10588](https://github.com/tiangolo/fastapi/pull/10588) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Upgrade latest-changes GitHub Action. PR [#10587](https://github.com/tiangolo/fastapi/pull/10587) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.104.1 (2023-10-30)
+
+### Fixes
+
+* 📌 Pin Swagger UI version to 5.9.0 temporarily to handle a bug crashing it in 5.9.1. PR [#10529](https://github.com/tiangolo/fastapi/pull/10529) by [@alejandraklachquin](https://github.com/alejandraklachquin).
+ * This is not really a bug in FastAPI but in Swagger UI, nevertheless pinning the version will work while a solution is found on the [Swagger UI side](https://github.com/swagger-api/swagger-ui/issues/9337).
+
+### Docs
+
+* 📝 Update data structure and render for external-links. PR [#10495](https://github.com/tiangolo/fastapi/pull/10495) by [@tiangolo](https://github.com/tiangolo).
+* ✏️ Fix link to SPDX license identifier in `docs/en/docs/tutorial/metadata.md`. PR [#10433](https://github.com/tiangolo/fastapi/pull/10433) by [@worldworm](https://github.com/worldworm).
+* 📝 Update example validation error from Pydantic v1 to match Pydantic v2 in `docs/en/docs/tutorial/path-params.md`. PR [#10043](https://github.com/tiangolo/fastapi/pull/10043) by [@giuliowaitforitdavide](https://github.com/giuliowaitforitdavide).
+* ✏️ Fix typos in emoji docs and in some source examples. PR [#10438](https://github.com/tiangolo/fastapi/pull/10438) by [@afuetterer](https://github.com/afuetterer).
+* ✏️ Fix typo in `docs/en/docs/reference/dependencies.md`. PR [#10465](https://github.com/tiangolo/fastapi/pull/10465) by [@suravshresth](https://github.com/suravshresth).
+* ✏️ Fix typos and rewordings in `docs/en/docs/tutorial/body-nested-models.md`. PR [#10468](https://github.com/tiangolo/fastapi/pull/10468) by [@yogabonito](https://github.com/yogabonito).
+* 📝 Update docs, remove references to removed `pydantic.Required` in `docs/en/docs/tutorial/query-params-str-validations.md`. PR [#10469](https://github.com/tiangolo/fastapi/pull/10469) by [@yogabonito](https://github.com/yogabonito).
+* ✏️ Fix typo in `docs/en/docs/reference/index.md`. PR [#10467](https://github.com/tiangolo/fastapi/pull/10467) by [@tarsil](https://github.com/tarsil).
+* 🔥 Remove unnecessary duplicated docstrings. PR [#10484](https://github.com/tiangolo/fastapi/pull/10484) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* ✏️ Update Pydantic links to dotenv support. PR [#10511](https://github.com/tiangolo/fastapi/pull/10511) by [@White-Mask](https://github.com/White-Mask).
+* ✏️ Update links in `docs/en/docs/async.md` and `docs/zh/docs/async.md` to make them relative. PR [#10498](https://github.com/tiangolo/fastapi/pull/10498) by [@hasnatsajid](https://github.com/hasnatsajid).
+* ✏️ Fix links in `docs/em/docs/async.md`. PR [#10507](https://github.com/tiangolo/fastapi/pull/10507) by [@hasnatsajid](https://github.com/hasnatsajid).
+* ✏️ Fix typo in `docs/em/docs/index.md`, Python 3.8. PR [#10521](https://github.com/tiangolo/fastapi/pull/10521) by [@kerriop](https://github.com/kerriop).
+* ⬆ Bump pillow from 9.5.0 to 10.1.0. PR [#10446](https://github.com/tiangolo/fastapi/pull/10446) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Update mkdocs-material requirement from <9.0.0,>=8.1.4 to >=8.1.4,<10.0.0. PR [#5862](https://github.com/tiangolo/fastapi/pull/5862) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump mkdocs-material from 9.1.21 to 9.4.7. PR [#10545](https://github.com/tiangolo/fastapi/pull/10545) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 👷 Install MkDocs Material Insiders only when secrets are available, for Dependabot. PR [#10544](https://github.com/tiangolo/fastapi/pull/10544) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Update sponsors badges, Databento. PR [#10519](https://github.com/tiangolo/fastapi/pull/10519) by [@tiangolo](https://github.com/tiangolo).
+* 👷 Adopt Ruff format. PR [#10517](https://github.com/tiangolo/fastapi/pull/10517) by [@tiangolo](https://github.com/tiangolo).
+* 🔧 Add `CITATION.cff` file for academic citations. PR [#10496](https://github.com/tiangolo/fastapi/pull/10496) by [@tiangolo](https://github.com/tiangolo).
+* 🐛 Fix overriding MKDocs theme lang in hook. PR [#10490](https://github.com/tiangolo/fastapi/pull/10490) by [@tiangolo](https://github.com/tiangolo).
+* 🔥 Drop/close Gitter chat. Questions should go to GitHub Discussions, free conversations to Discord.. PR [#10485](https://github.com/tiangolo/fastapi/pull/10485) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.104.0 (2023-10-18)
+
+## Features
+
+* ✨ Add reference (code API) docs with PEP 727, add subclass with custom docstrings for `BackgroundTasks`, refactor docs structure. PR [#10392](https://github.com/tiangolo/fastapi/pull/10392) by [@tiangolo](https://github.com/tiangolo). New docs at [FastAPI Reference - Code API](https://fastapi.tiangolo.com/reference/).
+
+## Upgrades
+
+* ⬆️ Drop support for Python 3.7, require Python 3.8 or above. PR [#10442](https://github.com/tiangolo/fastapi/pull/10442) by [@tiangolo](https://github.com/tiangolo).
+
+### Internal
+
+* ⬆ Bump dawidd6/action-download-artifact from 2.27.0 to 2.28.0. PR [#10268](https://github.com/tiangolo/fastapi/pull/10268) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump actions/checkout from 3 to 4. PR [#10208](https://github.com/tiangolo/fastapi/pull/10208) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* ⬆ Bump pypa/gh-action-pypi-publish from 1.8.6 to 1.8.10. PR [#10061](https://github.com/tiangolo/fastapi/pull/10061) by [@dependabot[bot]](https://github.com/apps/dependabot).
+* 🔧 Update sponsors, Bump.sh images. PR [#10381](https://github.com/tiangolo/fastapi/pull/10381) by [@tiangolo](https://github.com/tiangolo).
+* 👥 Update FastAPI People. PR [#10363](https://github.com/tiangolo/fastapi/pull/10363) by [@tiangolo](https://github.com/tiangolo).
+
+## 0.103.2 (2023-09-28)
### Refactors
@@ -30,7 +3474,7 @@
* 🔧 Update sponsors, remove Svix. PR [#10228](https://github.com/tiangolo/fastapi/pull/10228) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update sponsors, add Bump.sh. PR [#10227](https://github.com/tiangolo/fastapi/pull/10227) by [@tiangolo](https://github.com/tiangolo).
-## 0.103.1
+## 0.103.1 (2023-09-02)
### Fixes
@@ -65,7 +3509,7 @@
* 👥 Update FastAPI People. PR [#10186](https://github.com/tiangolo/fastapi/pull/10186) by [@tiangolo](https://github.com/tiangolo).
-## 0.103.0
+## 0.103.0 (2023-08-26)
### Features
@@ -76,7 +3520,7 @@
* 📝 Add note to docs about Separate Input and Output Schemas with FastAPI version. PR [#10150](https://github.com/tiangolo/fastapi/pull/10150) by [@tiangolo](https://github.com/tiangolo).
-## 0.102.0
+## 0.102.0 (2023-08-25)
### Features
@@ -100,7 +3544,7 @@
* 🔧 Update sponsors, add Speakeasy. PR [#10098](https://github.com/tiangolo/fastapi/pull/10098) by [@tiangolo](https://github.com/tiangolo).
-## 0.101.1
+## 0.101.1 (2023-08-14)
### Fixes
@@ -137,7 +3581,7 @@
* ⬆ Bump mypy from 1.4.0 to 1.4.1. PR [#9756](https://github.com/tiangolo/fastapi/pull/9756) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump mkdocs-material from 9.1.17 to 9.1.21. PR [#9960](https://github.com/tiangolo/fastapi/pull/9960) by [@dependabot[bot]](https://github.com/apps/dependabot).
-## 0.101.0
+## 0.101.0 (2023-08-04)
### Features
@@ -172,7 +3616,7 @@
* 🔧 Update sponsor Fern. PR [#9979](https://github.com/tiangolo/fastapi/pull/9979) by [@tiangolo](https://github.com/tiangolo).
* 👷 Update CI debug mode with Tmate. PR [#9977](https://github.com/tiangolo/fastapi/pull/9977) by [@tiangolo](https://github.com/tiangolo).
-## 0.100.1
+## 0.100.1 (2023-07-27)
### Fixes
@@ -204,7 +3648,7 @@
* 👷 Update MkDocs Material token. PR [#9843](https://github.com/tiangolo/fastapi/pull/9843) by [@tiangolo](https://github.com/tiangolo).
* 👷 Update token for latest changes. PR [#9842](https://github.com/tiangolo/fastapi/pull/9842) by [@tiangolo](https://github.com/tiangolo).
-## 0.100.0
+## 0.100.0 (2023-07-07)
✨ Support for **Pydantic v2** ✨
@@ -275,14 +3719,14 @@ There are **tests for both Pydantic v1 and v2**, and test **coverage** is kept a
* The attribute `schema_extra` for the internal class `Config` has been replaced by the key `json_schema_extra` in the new `model_config` dict.
* You can read more about it in the docs for [Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/).
* When you install `"fastapi[all]"` it now also includes:
- * pydantic-settings - for settings management.
- * pydantic-extra-types - for extra types to be used with Pydantic.
+ * [`pydantic-settings`](https://docs.pydantic.dev/latest/usage/pydantic_settings/) - for settings management.
+ * [`pydantic-extra-types`](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/) - for extra types to be used with Pydantic.
* Now Pydantic Settings is an additional optional package (included in `"fastapi[all]"`). To use settings you should now import `from pydantic_settings import BaseSettings` instead of importing from `pydantic` directly.
* You can read more about it in the docs for [Settings and Environment Variables](https://fastapi.tiangolo.com/advanced/settings/).
* PR [#9816](https://github.com/tiangolo/fastapi/pull/9816) by [@tiangolo](https://github.com/tiangolo), included all the work done (in multiple PRs) on the beta branch (`main-pv2`).
-## 0.99.1
+## 0.99.1 (2023-07-02)
### Fixes
@@ -292,15 +3736,15 @@ There are **tests for both Pydantic v1 and v2**, and test **coverage** is kept a
* 📝 Update source examples to use new JSON Schema examples field. PR [#9776](https://github.com/tiangolo/fastapi/pull/9776) by [@tiangolo](https://github.com/tiangolo).
-## 0.99.0
+## 0.99.0 (2023-06-30)
### Features
* ✨ Add support for OpenAPI 3.1.0. PR [#9770](https://github.com/tiangolo/fastapi/pull/9770) by [@tiangolo](https://github.com/tiangolo).
- * New support for documenting **webhooks**, read the new docs here: Advanced User Guide: OpenAPI Webhooks.
+ * New support for documenting **webhooks**, read the new docs here: [Advanced User Guide: OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/).
* Upgrade OpenAPI 3.1.0, this uses JSON Schema 2020-12.
* Upgrade Swagger UI to version 5.x.x, that supports OpenAPI 3.1.0.
- * Updated `examples` field in `Query()`, `Cookie()`, `Body()`, etc. based on the latest JSON Schema and OpenAPI. Now it takes a list of examples and they are included directly in the JSON Schema, not outside. Read more about it (including the historical technical details) in the updated docs: Tutorial: Declare Request Example Data.
+ * Updated `examples` field in `Query()`, `Cookie()`, `Body()`, etc. based on the latest JSON Schema and OpenAPI. Now it takes a list of examples and they are included directly in the JSON Schema, not outside. Read more about it (including the historical technical details) in the updated docs: [Tutorial: Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/).
* ✨ Add support for `deque` objects and children in `jsonable_encoder`. PR [#9433](https://github.com/tiangolo/fastapi/pull/9433) by [@cranium](https://github.com/cranium).
@@ -331,7 +3775,7 @@ There are **tests for both Pydantic v1 and v2**, and test **coverage** is kept a
* ⬆️ Upgrade MkDocs and MkDocs Material. PR [#9729](https://github.com/tiangolo/fastapi/pull/9729) by [@tiangolo](https://github.com/tiangolo).
* 👷 Build and deploy docs only on docs changes. PR [#9728](https://github.com/tiangolo/fastapi/pull/9728) by [@tiangolo](https://github.com/tiangolo).
-## 0.98.0
+## 0.98.0 (2023-06-22)
### Features
@@ -375,7 +3819,7 @@ There are **tests for both Pydantic v1 and v2**, and test **coverage** is kept a
* 🔧 Update sponsors, add Flint. PR [#9699](https://github.com/tiangolo/fastapi/pull/9699) by [@tiangolo](https://github.com/tiangolo).
* 👷 Lint in CI only once, only with one version of Python, run tests with all of them. PR [#9686](https://github.com/tiangolo/fastapi/pull/9686) by [@tiangolo](https://github.com/tiangolo).
-## 0.97.0
+## 0.97.0 (2023-06-11)
### Features
@@ -397,7 +3841,7 @@ There are **tests for both Pydantic v1 and v2**, and test **coverage** is kept a
* 💚 Update CI cache to fix installs when dependencies change. PR [#9659](https://github.com/tiangolo/fastapi/pull/9659) by [@tiangolo](https://github.com/tiangolo).
* ⬇️ Separate requirements for development into their own requirements.txt files, they shouldn't be extras. PR [#9655](https://github.com/tiangolo/fastapi/pull/9655) by [@tiangolo](https://github.com/tiangolo).
-## 0.96.1
+## 0.96.1 (2023-06-10)
### Fixes
@@ -430,7 +3874,7 @@ There are **tests for both Pydantic v1 and v2**, and test **coverage** is kept a
* 👷 Add custom token to Smokeshow and Preview Docs for download-artifact, to prevent API rate limits. PR [#9646](https://github.com/tiangolo/fastapi/pull/9646) by [@tiangolo](https://github.com/tiangolo).
* 👷 Add custom tokens for GitHub Actions to avoid rate limits. PR [#9647](https://github.com/tiangolo/fastapi/pull/9647) by [@tiangolo](https://github.com/tiangolo).
-## 0.96.0
+## 0.96.0 (2023-06-03)
### Features
@@ -460,7 +3904,7 @@ There are **tests for both Pydantic v1 and v2**, and test **coverage** is kept a
* 👥 Update FastAPI People. PR [#9602](https://github.com/tiangolo/fastapi/pull/9602) by [@github-actions[bot]](https://github.com/apps/github-actions).
* 🔧 Update sponsors, remove InvestSuite. PR [#9612](https://github.com/tiangolo/fastapi/pull/9612) by [@tiangolo](https://github.com/tiangolo).
-## 0.95.2
+## 0.95.2 (2023-05-16)
* ⬆️ Upgrade Starlette version to `>=0.27.0` for a security release. PR [#9541](https://github.com/tiangolo/fastapi/pull/9541) by [@tiangolo](https://github.com/tiangolo). Details on [Starlette's security advisory](https://github.com/encode/starlette/security/advisories/GHSA-v5gw-mw7f-84px).
@@ -486,7 +3930,7 @@ There are **tests for both Pydantic v1 and v2**, and test **coverage** is kept a
* 💚 Disable setup-python pip cache in CI. PR [#9438](https://github.com/tiangolo/fastapi/pull/9438) by [@tiangolo](https://github.com/tiangolo).
* ⬆ Bump pypa/gh-action-pypi-publish from 1.6.4 to 1.8.5. PR [#9346](https://github.com/tiangolo/fastapi/pull/9346) by [@dependabot[bot]](https://github.com/apps/dependabot).
-## 0.95.1
+## 0.95.1 (2023-04-13)
### Fixes
@@ -523,7 +3967,7 @@ There are **tests for both Pydantic v1 and v2**, and test **coverage** is kept a
* 🔧 Update sponsors: remove Jina. PR [#9388](https://github.com/tiangolo/fastapi/pull/9388) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update sponsors, add databento, remove Ines's course and StriveWorks. PR [#9351](https://github.com/tiangolo/fastapi/pull/9351) by [@tiangolo](https://github.com/tiangolo).
-## 0.95.0
+## 0.95.0 (2023-03-18)
### Highlights
@@ -632,13 +4076,13 @@ Special thanks to [@nzig](https://github.com/nzig) for the core implementation a
* 📝 Update order of examples, latest Python version first, and simplify version tab names. PR [#9269](https://github.com/tiangolo/fastapi/pull/9269) by [@tiangolo](https://github.com/tiangolo).
* 📝 Update all docs to use `Annotated` as the main recommendation, with new examples and tests. PR [#9268](https://github.com/tiangolo/fastapi/pull/9268) by [@tiangolo](https://github.com/tiangolo).
-## 0.94.1
+## 0.94.1 (2023-03-14)
### Fixes
* 🎨 Fix types for lifespan, upgrade Starlette to 0.26.1. PR [#9245](https://github.com/tiangolo/fastapi/pull/9245) by [@tiangolo](https://github.com/tiangolo).
-## 0.94.0
+## 0.94.0 (2023-03-10)
### Upgrades
@@ -661,7 +4105,7 @@ Special thanks to [@nzig](https://github.com/nzig) for the core implementation a
* ⬆ Bump dawidd6/action-download-artifact from 2.24.3 to 2.26.0. PR [#6034](https://github.com/tiangolo/fastapi/pull/6034) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#5709](https://github.com/tiangolo/fastapi/pull/5709) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
-## 0.93.0
+## 0.93.0 (2023-03-07)
### Features
@@ -730,7 +4174,7 @@ Read more about it in the new docs: [Advanced User Guide: Lifespan Events](https
* ⬆️ Upgrade analytics. PR [#6025](https://github.com/tiangolo/fastapi/pull/6025) by [@tiangolo](https://github.com/tiangolo).
* ⬆️ Upgrade and re-enable installing Typer-CLI. PR [#6008](https://github.com/tiangolo/fastapi/pull/6008) by [@tiangolo](https://github.com/tiangolo).
-## 0.92.0
+## 0.92.0 (2023-02-14)
🚨 This is a security fix. Please upgrade as soon as possible.
@@ -741,7 +4185,7 @@ Read more about it in the new docs: [Advanced User Guide: Lifespan Events](https
* Only applications using forms (e.g. file uploads) could be affected.
* For most cases, upgrading won't have any breaking changes.
-## 0.91.0
+## 0.91.0 (2023-02-10)
### Upgrades
@@ -749,7 +4193,7 @@ Read more about it in the new docs: [Advanced User Guide: Lifespan Events](https
* This can solve nuanced errors when using middlewares. Before Starlette `0.24.0`, a new instance of each middleware class would be created when a new middleware was added. That normally was not a problem, unless the middleware class expected to be created only once, with only one instance, that happened in some cases. This upgrade would solve those cases (thanks [@adriangb](https://github.com/adriangb)! Starlette PR [#2017](https://github.com/encode/starlette/pull/2017)). Now the middleware class instances are created once, right before the first request (the first time the app is called).
* If you depended on that previous behavior, you might need to update your code. As always, make sure your tests pass before merging the upgrade.
-## 0.90.1
+## 0.90.1 (2023-02-09)
### Upgrades
@@ -769,7 +4213,7 @@ Read more about it in the new docs: [Advanced User Guide: Lifespan Events](https
* ✏ Update `zip-docs.sh` internal script, remove extra space. PR [#5931](https://github.com/tiangolo/fastapi/pull/5931) by [@JuanPerdomo00](https://github.com/JuanPerdomo00).
-## 0.90.0
+## 0.90.0 (2023-02-08)
### Upgrades
@@ -801,7 +4245,7 @@ Read more about it in the new docs: [Advanced User Guide: Lifespan Events](https
* 🔧 Update Sponsor Budget Insight to Powens. PR [#5916](https://github.com/tiangolo/fastapi/pull/5916) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update GitHub Sponsors badge data. PR [#5915](https://github.com/tiangolo/fastapi/pull/5915) by [@tiangolo](https://github.com/tiangolo).
-## 0.89.1
+## 0.89.1 (2023-01-10)
### Fixes
@@ -816,7 +4260,7 @@ Read more about it in the new docs: [Advanced User Guide: Lifespan Events](https
* 🌐 Add Turkish translation for `docs/tr/docs/tutorial/first_steps.md`. PR [#5691](https://github.com/tiangolo/fastapi/pull/5691) by [@Kadermiyanyedi](https://github.com/Kadermiyanyedi).
-## 0.89.0
+## 0.89.0 (2023-01-07)
### Features
@@ -886,7 +4330,7 @@ Read more about it in the new docs: [Response Model - Return Type](https://fasta
* 🔧 Update sponsors, disable course bundle. PR [#5713](https://github.com/tiangolo/fastapi/pull/5713) by [@tiangolo](https://github.com/tiangolo).
* ⬆ Update typer[all] requirement from <0.7.0,>=0.6.1 to >=0.6.1,<0.8.0. PR [#5639](https://github.com/tiangolo/fastapi/pull/5639) by [@dependabot[bot]](https://github.com/apps/dependabot).
-## 0.88.0
+## 0.88.0 (2022-11-27)
### Upgrades
@@ -911,7 +4355,7 @@ Read more about it in the new docs: [Response Model - Return Type](https://fasta
* 👷 Update `setup-python` action in tests to use new caching feature. PR [#5680](https://github.com/tiangolo/fastapi/pull/5680) by [@madkinsz](https://github.com/madkinsz).
* ⬆ Bump black from 22.8.0 to 22.10.0. PR [#5569](https://github.com/tiangolo/fastapi/pull/5569) by [@dependabot[bot]](https://github.com/apps/dependabot).
-## 0.87.0
+## 0.87.0 (2022-11-13)
Highlights of this release:
@@ -950,7 +4394,7 @@ Highlights of this release:
* ⬆ Bump dawidd6/action-download-artifact from 2.24.0 to 2.24.1. PR [#5603](https://github.com/tiangolo/fastapi/pull/5603) by [@dependabot[bot]](https://github.com/apps/dependabot).
* 📝 Update coverage badge to use Samuel Colvin's Smokeshow. PR [#5585](https://github.com/tiangolo/fastapi/pull/5585) by [@tiangolo](https://github.com/tiangolo).
-## 0.86.0
+## 0.86.0 (2022-11-03)
### Features
@@ -978,7 +4422,7 @@ Highlights of this release:
* 👷 Switch from Codecov to Smokeshow plus pytest-cov to pure coverage for internal tests. PR [#5583](https://github.com/tiangolo/fastapi/pull/5583) by [@tiangolo](https://github.com/tiangolo).
* 👥 Update FastAPI People. PR [#5571](https://github.com/tiangolo/fastapi/pull/5571) by [@github-actions[bot]](https://github.com/apps/github-actions).
-## 0.85.2
+## 0.85.2 (2022-10-31)
### Docs
@@ -1016,7 +4460,7 @@ Highlights of this release:
* ⬆️ Upgrade Typer to include Rich in scripts for docs. PR [#5502](https://github.com/tiangolo/fastapi/pull/5502) by [@tiangolo](https://github.com/tiangolo).
* 🐛 Fix calling `mkdocs` for languages as a subprocess to fix/enable MkDocs Material search plugin. PR [#5501](https://github.com/tiangolo/fastapi/pull/5501) by [@tiangolo](https://github.com/tiangolo).
-## 0.85.1
+## 0.85.1 (2022-10-14)
### Fixes
@@ -1032,7 +4476,7 @@ Highlights of this release:
* 🔧 Disable Material for MkDocs search plugin. PR [#5495](https://github.com/tiangolo/fastapi/pull/5495) by [@tiangolo](https://github.com/tiangolo).
* 🔇 Ignore Trio warning in tests for CI. PR [#5483](https://github.com/tiangolo/fastapi/pull/5483) by [@samuelcolvin](https://github.com/samuelcolvin).
-## 0.85.0
+## 0.85.0 (2022-09-15)
### Features
@@ -1047,7 +4491,7 @@ Highlights of this release:
* ⬆️ Upgrade mypy and tweak internal type annotations. PR [#5398](https://github.com/tiangolo/fastapi/pull/5398) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update test dependencies, upgrade Pytest, move dependencies from dev to test. PR [#5396](https://github.com/tiangolo/fastapi/pull/5396) by [@tiangolo](https://github.com/tiangolo).
-## 0.84.0
+## 0.84.0 (2022-09-14)
### Breaking Changes
@@ -1055,7 +4499,7 @@ This version of FastAPI drops support for Python 3.6. 🔥 Please upgrade to a s
* 🔧 Update package metadata, drop support for Python 3.6, move build internals from Flit to Hatch. PR [#5240](https://github.com/tiangolo/fastapi/pull/5240) by [@ofek](https://github.com/ofek).
-## 0.83.0
+## 0.83.0 (2022-09-11)
🚨 This is probably the last release (or one of the last releases) to support Python 3.6. 🔥
@@ -1070,7 +4514,7 @@ You hopefully updated to a supported version of Python a while ago. If you haven
### Fixes
* 🐛 Fix `RuntimeError` raised when `HTTPException` has a status code with no content. PR [#5365](https://github.com/tiangolo/fastapi/pull/5365) by [@iudeen](https://github.com/iudeen).
-* 🐛 Fix empty reponse body when default `status_code` is empty but the a `Response` parameter with `response.status_code` is set. PR [#5360](https://github.com/tiangolo/fastapi/pull/5360) by [@tmeckel](https://github.com/tmeckel).
+* 🐛 Fix empty response body when default `status_code` is empty but the a `Response` parameter with `response.status_code` is set. PR [#5360](https://github.com/tiangolo/fastapi/pull/5360) by [@tmeckel](https://github.com/tmeckel).
### Docs
@@ -1080,7 +4524,7 @@ You hopefully updated to a supported version of Python a while ago. If you haven
* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#5352](https://github.com/tiangolo/fastapi/pull/5352) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
-## 0.82.0
+## 0.82.0 (2022-09-04)
🚨 This is probably the last release (or one of the last releases) to support Python 3.6. 🔥
@@ -1127,7 +4571,7 @@ You hopefully updated to a supported version of Python a while ago. If you haven
* ♻ Internal small refactor, move `operation_id` parameter position in delete method for consistency with the code. PR [#4474](https://github.com/tiangolo/fastapi/pull/4474) by [@hiel](https://github.com/hiel).
* 🔧 Update sponsors, disable ImgWhale. PR [#5338](https://github.com/tiangolo/fastapi/pull/5338) by [@tiangolo](https://github.com/tiangolo).
-## 0.81.0
+## 0.81.0 (2022-08-26)
### Features
@@ -1180,7 +4624,7 @@ You hopefully updated to a supported version of Python a while ago. If you haven
* ⬆ Upgrade version pin accepted for Flake8, for internal code, to `flake8 >=3.8.3,<6.0.0`. PR [#4097](https://github.com/tiangolo/fastapi/pull/4097) by [@jamescurtin](https://github.com/jamescurtin).
* 🍱 Update Jina banner, fix typo. PR [#5301](https://github.com/tiangolo/fastapi/pull/5301) by [@tiangolo](https://github.com/tiangolo).
-## 0.80.0
+## 0.80.0 (2022-08-23)
### Breaking Changes - Fixes
@@ -1263,7 +4707,7 @@ This way the data will be correctly validated, you won't have an internal server
* 🌐 Add missing navigator for `encoder.md` in Korean translation. PR [#5238](https://github.com/tiangolo/fastapi/pull/5238) by [@joonas-yoon](https://github.com/joonas-yoon).
* (Empty PR merge by accident) [#4913](https://github.com/tiangolo/fastapi/pull/4913).
-## 0.79.1
+## 0.79.1 (2022-08-18)
### Fixes
@@ -1299,7 +4743,7 @@ This way the data will be correctly validated, you won't have an internal server
* 🔧 Update Jina sponsorship. PR [#5272](https://github.com/tiangolo/fastapi/pull/5272) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update sponsors, Striveworks badge. PR [#5179](https://github.com/tiangolo/fastapi/pull/5179) by [@tiangolo](https://github.com/tiangolo).
-## 0.79.0
+## 0.79.0 (2022-07-14)
### Fixes - Breaking Changes
@@ -1336,7 +4780,7 @@ This way the data will be correctly validated, you won't have an internal server
* 🔧 Update sponsors, remove Dropbase, add Doist. PR [#5096](https://github.com/tiangolo/fastapi/pull/5096) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update sponsors, remove Classiq, add ImgWhale. PR [#5079](https://github.com/tiangolo/fastapi/pull/5079) by [@tiangolo](https://github.com/tiangolo).
-## 0.78.0
+## 0.78.0 (2022-05-14)
### Features
@@ -1442,7 +4886,7 @@ def main(
* 🔧 Add pre-commit with first config and first formatting pass. PR [#4888](https://github.com/tiangolo/fastapi/pull/4888) by [@tiangolo](https://github.com/tiangolo).
* 👷 Disable CI installing Material for MkDocs in forks. PR [#4410](https://github.com/tiangolo/fastapi/pull/4410) by [@dolfinus](https://github.com/dolfinus).
-## 0.77.1
+## 0.77.1 (2022-05-10)
### Upgrades
@@ -1465,7 +4909,7 @@ def main(
* 🔧 Add notifications in issue for Uzbek translations. PR [#4884](https://github.com/tiangolo/fastapi/pull/4884) by [@tiangolo](https://github.com/tiangolo).
-## 0.77.0
+## 0.77.0 (2022-05-10)
### Upgrades
@@ -1498,7 +4942,7 @@ def main(
* 🌐 Add Portuguese translation of `tutorial/extra-data-types.md`. PR [#4077](https://github.com/tiangolo/fastapi/pull/4077) by [@luccasmmg](https://github.com/luccasmmg).
* 🌐 Update German translation for `docs/features.md`. PR [#3905](https://github.com/tiangolo/fastapi/pull/3905) by [@jomue](https://github.com/jomue).
-## 0.76.0
+## 0.76.0 (2022-05-05)
### Upgrades
@@ -1511,7 +4955,7 @@ def main(
* 🍱 Update sponsor, ExoFlare badge. PR [#4822](https://github.com/tiangolo/fastapi/pull/4822) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update sponsors, enable Dropbase again, update TalkPython link. PR [#4821](https://github.com/tiangolo/fastapi/pull/4821) by [@tiangolo](https://github.com/tiangolo).
-## 0.75.2
+## 0.75.2 (2022-04-17)
This release includes upgrades to third-party packages that handle security issues. Although there's a chance these issues don't affect you in particular, please upgrade as soon as possible.
@@ -1532,7 +4976,7 @@ This release includes upgrades to third-party packages that handle security issu
* 🔧 Update sponsors, add: ExoFlare, Ines Course; remove: Dropbase, Vim.so, Calmcode; update: Striveworks, TalkPython and TestDriven.io. PR [#4805](https://github.com/tiangolo/fastapi/pull/4805) by [@tiangolo](https://github.com/tiangolo).
* ⬆️ Upgrade Codecov GitHub Action. PR [#4801](https://github.com/tiangolo/fastapi/pull/4801) by [@tiangolo](https://github.com/tiangolo).
-## 0.75.1
+## 0.75.1 (2022-04-01)
### Translations
@@ -1551,19 +4995,19 @@ This release includes upgrades to third-party packages that handle security issu
* 🔧 Add Classiq sponsor. PR [#4671](https://github.com/tiangolo/fastapi/pull/4671) by [@tiangolo](https://github.com/tiangolo).
* 📝 Add Jina's QA Bot to the docs to help people that want to ask quick questions. PR [#4655](https://github.com/tiangolo/fastapi/pull/4655) by [@tiangolo](https://github.com/tiangolo) based on original PR [#4626](https://github.com/tiangolo/fastapi/pull/4626) by [@hanxiao](https://github.com/hanxiao).
-## 0.75.0
+## 0.75.0 (2022-03-04)
### Features
* ✨ Add support for custom `generate_unique_id_function` and docs for generating clients. New docs: [Advanced - Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/). PR [#4650](https://github.com/tiangolo/fastapi/pull/4650) by [@tiangolo](https://github.com/tiangolo).
-## 0.74.1
+## 0.74.1 (2022-02-21)
### Features
* ✨ Include route in scope to allow middleware and other tools to extract its information. PR [#4603](https://github.com/tiangolo/fastapi/pull/4603) by [@tiangolo](https://github.com/tiangolo).
-## 0.74.0
+## 0.74.0 (2022-02-17)
### Breaking Changes
@@ -1633,7 +5077,7 @@ async def set_up_request_state_dependency():
* 💚 Only build docs on push when on master to avoid duplicate runs from PRs. PR [#4564](https://github.com/tiangolo/fastapi/pull/4564) by [@tiangolo](https://github.com/tiangolo).
* 👥 Update FastAPI People. PR [#4502](https://github.com/tiangolo/fastapi/pull/4502) by [@github-actions[bot]](https://github.com/apps/github-actions).
-## 0.73.0
+## 0.73.0 (2022-01-23)
### Features
@@ -1656,7 +5100,7 @@ async def set_up_request_state_dependency():
* 🐛 Fix docs dependencies cache, to get the latest Material for MkDocs. PR [#4466](https://github.com/tiangolo/fastapi/pull/4466) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Add sponsor Dropbase. PR [#4465](https://github.com/tiangolo/fastapi/pull/4465) by [@tiangolo](https://github.com/tiangolo).
-## 0.72.0
+## 0.72.0 (2022-01-16)
### Features
@@ -1677,7 +5121,7 @@ async def set_up_request_state_dependency():
* 🔧 Enable MkDocs Material Insiders' `content.tabs.link`. PR [#4399](https://github.com/tiangolo/fastapi/pull/4399) by [@tiangolo](https://github.com/tiangolo).
-## 0.71.0
+## 0.71.0 (2022-01-07)
### Features
@@ -1692,7 +5136,7 @@ async def set_up_request_state_dependency():
* 🔧 Add FastAPI Trove Classifier for PyPI as now there's one 🤷😁. PR [#4386](https://github.com/tiangolo/fastapi/pull/4386) by [@tiangolo](https://github.com/tiangolo).
* ⬆ Upgrade MkDocs Material and configs. PR [#4385](https://github.com/tiangolo/fastapi/pull/4385) by [@tiangolo](https://github.com/tiangolo).
-## 0.70.1
+## 0.70.1 (2021-12-12)
There's nothing interesting in this particular FastAPI release. It is mainly to enable/unblock the release of the next version of Pydantic that comes packed with features and improvements. 🤩
@@ -1721,7 +5165,7 @@ There's nothing interesting in this particular FastAPI release. It is mainly to
* 👥 Update FastAPI People. PR [#4274](https://github.com/tiangolo/fastapi/pull/4274) by [@github-actions[bot]](https://github.com/apps/github-actions).
-## 0.70.0
+## 0.70.0 (2021-10-07)
This release just upgrades Starlette to the latest version, `0.16.0`, which includes several bug fixes and some small breaking changes.
@@ -1742,7 +5186,7 @@ Also upgrades the ranges of optional dependencies:
* `"jinja2 >=2.11.2,<4.0.0"`
* `"itsdangerous >=1.1.0,<3.0.0"`
-## 0.69.0
+## 0.69.0 (2021-10-07)
### Breaking Changes - Upgrade
@@ -1791,7 +5235,7 @@ This release also removes `graphene` as an optional dependency for GraphQL. If y
* 🔧 Lint only in Python 3.7 and above. PR [#4006](https://github.com/tiangolo/fastapi/pull/4006) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Add GitHub Action notify-translations config for Azerbaijani. PR [#3995](https://github.com/tiangolo/fastapi/pull/3995) by [@tiangolo](https://github.com/tiangolo).
-## 0.68.2
+## 0.68.2 (2021-10-05)
This release has **no breaking changes**. 🎉
@@ -1835,7 +5279,7 @@ Soon there will be a new FastAPI release upgrading Starlette to take advantage o
* 🎨 Tweak CSS styles for shell animations. PR [#3888](https://github.com/tiangolo/fastapi/pull/3888) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Add new Sponsor Calmcode.io. PR [#3777](https://github.com/tiangolo/fastapi/pull/3777) by [@tiangolo](https://github.com/tiangolo).
-## 0.68.1
+## 0.68.1 (2021-08-24)
* ✨ Add support for `read_with_orm_mode`, to support [SQLModel](https://sqlmodel.tiangolo.com/) relationship attributes. PR [#3757](https://github.com/tiangolo/fastapi/pull/3757) by [@tiangolo](https://github.com/tiangolo).
@@ -1859,7 +5303,7 @@ Soon there will be a new FastAPI release upgrading Starlette to take advantage o
* ⬆ Enable tests for Python 3.9. PR [#2298](https://github.com/tiangolo/fastapi/pull/2298) by [@Kludex](https://github.com/Kludex).
* 👥 Update FastAPI People. PR [#3642](https://github.com/tiangolo/fastapi/pull/3642) by [@github-actions[bot]](https://github.com/apps/github-actions).
-## 0.68.0
+## 0.68.0 (2021-07-29)
### Features
@@ -1886,9 +5330,9 @@ Soon there will be a new FastAPI release upgrading Starlette to take advantage o
* ✅ Add the `docs_src` directory to test coverage and update tests. Initial PR [#1904](https://github.com/tiangolo/fastapi/pull/1904) by [@Kludex](https://github.com/Kludex).
* 🔧 Add new GitHub templates with forms for new issues. PR [#3612](https://github.com/tiangolo/fastapi/pull/3612) by [@tiangolo](https://github.com/tiangolo).
-* 📝 Add official FastAPI Twitter to docs: [@fastapi](https://twitter.com/fastapi). PR [#3578](https://github.com/tiangolo/fastapi/pull/3578) by [@tiangolo](https://github.com/tiangolo).
+* 📝 Add official FastAPI Twitter to docs: [@fastapi](https://x.com/fastapi). PR [#3578](https://github.com/tiangolo/fastapi/pull/3578) by [@tiangolo](https://github.com/tiangolo).
-## 0.67.0
+## 0.67.0 (2021-07-21)
### Features
@@ -1916,7 +5360,7 @@ Soon there will be a new FastAPI release upgrading Starlette to take advantage o
* 👷 Update GitHub Action latest-changes, strike 2 ⚾. PR [#3575](https://github.com/tiangolo/fastapi/pull/3575) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Sort external links in docs to have the most recent at the top. PR [#3568](https://github.com/tiangolo/fastapi/pull/3568) by [@tiangolo](https://github.com/tiangolo).
-## 0.66.1
+## 0.66.1 (2021-07-19)
### Translations
@@ -1929,7 +5373,7 @@ Soon there will be a new FastAPI release upgrading Starlette to take advantage o
* 🔧 Configure strict pytest options and update/refactor tests. Upgrade pytest to `>=6.2.4,<7.0.0` and pytest-cov to `>=2.12.0,<3.0.0`. Initial PR [#2790](https://github.com/tiangolo/fastapi/pull/2790) by [@graingert](https://github.com/graingert).
* ⬆️ Upgrade python-jose dependency to `>=3.3.0,<4.0.0` for tests. PR [#3468](https://github.com/tiangolo/fastapi/pull/3468) by [@tiangolo](https://github.com/tiangolo).
-## 0.66.0
+## 0.66.0 (2021-07-04)
### Features
@@ -1947,7 +5391,7 @@ Soon there will be a new FastAPI release upgrading Starlette to take advantage o
* 🌐 Add Spanish translation for `advanced/additional-status-codes.md`. PR [#1252](https://github.com/tiangolo/fastapi/pull/1252) by [@jfunez](https://github.com/jfunez).
* 🌐 Add Spanish translation for `advanced/path-operation-advanced-configuration.md`. PR [#1251](https://github.com/tiangolo/fastapi/pull/1251) by [@jfunez](https://github.com/jfunez).
-## 0.65.3
+## 0.65.3 (2021-07-03)
### Fixes
@@ -1978,7 +5422,7 @@ Soon there will be a new FastAPI release upgrading Starlette to take advantage o
* 👥 Update FastAPI People. PR [#3319](https://github.com/tiangolo/fastapi/pull/3319) by [@github-actions[bot]](https://github.com/apps/github-actions).
* ⬆ Upgrade docs development dependency on `typer-cli` to >=0.0.12 to fix conflicts. PR [#3429](https://github.com/tiangolo/fastapi/pull/3429) by [@tiangolo](https://github.com/tiangolo).
-## 0.65.2
+## 0.65.2 (2021-06-09)
### Security fixes
@@ -1994,7 +5438,7 @@ But requests with content type `text/plain` are exempt from [CORS](https://devel
See [CVE-2021-32677](https://github.com/tiangolo/fastapi/security/advisories/GHSA-8h2j-cgx8-6xv7) for more details.
-Thanks to [Dima Boger](https://twitter.com/b0g3r) for the security report! 🙇🔒
+Thanks to [Dima Boger](https://x.com/b0g3r) for the security report! 🙇🔒
### Internal
@@ -2003,13 +5447,13 @@ Thanks to [Dima Boger](https://twitter.com/b0g3r) for the security report! 🙇
* 🔧 Add new banner sponsor badge for FastAPI courses bundle. PR [#3288](https://github.com/tiangolo/fastapi/pull/3288) by [@tiangolo](https://github.com/tiangolo).
* 👷 Upgrade Issue Manager GitHub Action. PR [#3236](https://github.com/tiangolo/fastapi/pull/3236) by [@tiangolo](https://github.com/tiangolo).
-## 0.65.1
+## 0.65.1 (2021-05-11)
### Security fixes
* 📌 Upgrade pydantic pin, to handle security vulnerability [CVE-2021-29510](https://github.com/pydantic/pydantic/security/advisories/GHSA-5jqp-qgf6-3pvh). PR [#3213](https://github.com/tiangolo/fastapi/pull/3213) by [@tiangolo](https://github.com/tiangolo).
-## 0.65.0
+## 0.65.0 (2021-05-10)
### Breaking Changes - Upgrade
@@ -2028,7 +5472,7 @@ Thanks to [Dima Boger](https://twitter.com/b0g3r) for the security report! 🙇
* 👥 Update FastAPI People. PR [#3189](https://github.com/tiangolo/fastapi/pull/3189) by [@github-actions[bot]](https://github.com/apps/github-actions).
* 🔊 Update FastAPI People to allow better debugging. PR [#3188](https://github.com/tiangolo/fastapi/pull/3188) by [@tiangolo](https://github.com/tiangolo).
-## 0.64.0
+## 0.64.0 (2021-05-07)
### Features
@@ -2108,7 +5552,7 @@ Thanks to [Dima Boger](https://twitter.com/b0g3r) for the security report! 🙇
* 🔧 Update InvestSuite sponsor data. PR [#2608](https://github.com/tiangolo/fastapi/pull/2608) by [@tiangolo](https://github.com/tiangolo).
* 👥 Update FastAPI People. PR [#2590](https://github.com/tiangolo/fastapi/pull/2590) by [@github-actions[bot]](https://github.com/apps/github-actions).
-## 0.63.0
+## 0.63.0 (2020-12-20)
### Features
@@ -2147,7 +5591,7 @@ Thanks to [Dima Boger](https://twitter.com/b0g3r) for the security report! 🙇
* ✨ Add new Gold Sponsor: InvestSuite 🎉. PR [#2508](https://github.com/tiangolo/fastapi/pull/2508) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Add issue template configs. PR [#2476](https://github.com/tiangolo/fastapi/pull/2476) by [@tiangolo](https://github.com/tiangolo).
-## 0.62.0
+## 0.62.0 (2020-11-29)
### Features
@@ -2233,10 +5677,10 @@ Note: all the previous parameters are still there, so it's still possible to dec
### Docs
* PR [#2434](https://github.com/tiangolo/fastapi/pull/2434) (above) includes new or updated docs:
- * Advanced User Guide - OpenAPI Callbacks.
- * Tutorial - Bigger Applications.
- * Tutorial - Dependencies - Dependencies in path operation decorators.
- * Tutorial - Dependencies - Global Dependencies.
+ * [Advanced User Guide - OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
+ * [Tutorial - Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/).
+ * [Tutorial - Dependencies - Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
+ * [Tutorial - Dependencies - Global Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/).
* 📝 Add FastAPI monitoring blog post to External Links. PR [#2324](https://github.com/tiangolo/fastapi/pull/2324) by [@louisguitton](https://github.com/louisguitton).
* ✏️ Fix typo in Deta tutorial. PR [#2320](https://github.com/tiangolo/fastapi/pull/2320) by [@tiangolo](https://github.com/tiangolo).
@@ -2263,7 +5707,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* ✨ Add silver sponsor WeTransfer. PR [#2338](https://github.com/tiangolo/fastapi/pull/2338) by [@tiangolo](https://github.com/tiangolo).
* ✨ Set up and enable Material for MkDocs Insiders for the docs. PR [#2325](https://github.com/tiangolo/fastapi/pull/2325) by [@tiangolo](https://github.com/tiangolo).
-## 0.61.2
+## 0.61.2 (2020-11-05)
### Fixes
@@ -2345,7 +5789,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* 👷 Add GitHub Action Latest Changes. PR [#2160](https://github.com/tiangolo/fastapi/pull/2160).
* 👷 Add GitHub Action Label Approved. PR [#2161](https://github.com/tiangolo/fastapi/pull/2161).
-## 0.61.1
+## 0.61.1 (2020-08-29)
### Fixes
@@ -2365,7 +5809,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Improve docs maintainability by updating `hl_lines` syntax to use ranges. PR [#1863](https://github.com/tiangolo/fastapi/pull/1863) by [@la-mar](https://github.com/la-mar).
-## 0.61.0
+## 0.61.0 (2020-08-09)
### Features
@@ -2398,7 +5842,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Add Flake8 linting. Original PR [#1774](https://github.com/tiangolo/fastapi/pull/1774) by [@MashhadiNima](https://github.com/MashhadiNima).
* Disable Gitter bot, as it's currently broken, and Gitter's response doesn't show the problem. PR [#1853](https://github.com/tiangolo/fastapi/pull/1853).
-## 0.60.2
+## 0.60.2 (2020-08-08)
* Fix typo in docs for query parameters. PR [#1832](https://github.com/tiangolo/fastapi/pull/1832) by [@ycd](https://github.com/ycd).
* Add docs about [Async Tests](https://fastapi.tiangolo.com/advanced/async-tests/). PR [#1619](https://github.com/tiangolo/fastapi/pull/1619) by [@empicano](https://github.com/empicano).
@@ -2427,7 +5871,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Remove docs preview comment from each commit. PR [#1826](https://github.com/tiangolo/fastapi/pull/1826).
* Update GitHub context extraction for Gitter notification bot. PR [#1766](https://github.com/tiangolo/fastapi/pull/1766).
-## 0.60.1
+## 0.60.1 (2020-07-22)
* Add debugging logs for GitHub actions to introspect GitHub hidden context. PR [#1764](https://github.com/tiangolo/fastapi/pull/1764).
* Use OS preference theme for online docs. PR [#1760](https://github.com/tiangolo/fastapi/pull/1760) by [@adriencaccia](https://github.com/adriencaccia).
@@ -2436,7 +5880,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Update GitHub Actions, use commit from PR for docs preview, not commit from pre-merge. PR [#1761](https://github.com/tiangolo/fastapi/pull/1761).
* Update GitHub Actions, refactor Gitter bot. PR [#1746](https://github.com/tiangolo/fastapi/pull/1746).
-## 0.60.0
+## 0.60.0 (2020-07-20)
* Add GitHub Action to watch for missing preview docs and trigger a preview deploy. PR [#1740](https://github.com/tiangolo/fastapi/pull/1740).
* Add custom GitHub Action to get artifact with docs preview. PR [#1739](https://github.com/tiangolo/fastapi/pull/1739).
@@ -2446,7 +5890,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Add GitHub Actions for CI, move from Travis. PR [#1735](https://github.com/tiangolo/fastapi/pull/1735).
* Add support for adding OpenAPI schema for GET requests with a body. PR [#1626](https://github.com/tiangolo/fastapi/pull/1626) by [@victorphoenix3](https://github.com/victorphoenix3).
-## 0.59.0
+## 0.59.0 (2020-07-10)
* Fix typo in docstring for OAuth2 utils. PR [#1621](https://github.com/tiangolo/fastapi/pull/1621) by [@tomarv2](https://github.com/tomarv2).
* Update JWT docs to use Python-jose instead of PyJWT. Initial PR [#1610](https://github.com/tiangolo/fastapi/pull/1610) by [@asheux](https://github.com/asheux).
@@ -2464,7 +5908,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Pin dependencies. PR [#1697](https://github.com/tiangolo/fastapi/pull/1697).
* Update isort to version 5.x.x. PR [#1670](https://github.com/tiangolo/fastapi/pull/1670) by [@asheux](https://github.com/asheux).
-## 0.58.1
+## 0.58.1 (2020-06-28)
* Add link in docs to Pydantic data types. PR [#1612](https://github.com/tiangolo/fastapi/pull/1612) by [@tayoogunbiyi](https://github.com/tayoogunbiyi).
* Fix link in warning logs for `openapi_prefix`. PR [#1611](https://github.com/tiangolo/fastapi/pull/1611) by [@bavaria95](https://github.com/bavaria95).
@@ -2479,7 +5923,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Add translation to Chinese for [Path Parameters and Numeric Validations - 路径参数和数值校验](https://fastapi.tiangolo.com/zh/tutorial/path-params-numeric-validations/). PR [#1506](https://github.com/tiangolo/fastapi/pull/1506) by [@waynerv](https://github.com/waynerv).
* Add GitHub action to auto-label approved PRs (mainly for translations). PR [#1638](https://github.com/tiangolo/fastapi/pull/1638).
-## 0.58.0
+## 0.58.0 (2020-06-15)
* Deep merge OpenAPI responses to preserve all the additional metadata. PR [#1577](https://github.com/tiangolo/fastapi/pull/1577).
* Mention in docs that only main app events are run (not sub-apps). PR [#1554](https://github.com/tiangolo/fastapi/pull/1554) by [@amacfie](https://github.com/amacfie).
@@ -2488,7 +5932,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Fix Model for JSON Schema keyword `not` as a JSON Schema instead of a list. PR [#1548](https://github.com/tiangolo/fastapi/pull/1548) by [@v-do](https://github.com/v-do).
* Add support for OpenAPI `servers`. PR [#1547](https://github.com/tiangolo/fastapi/pull/1547) by [@mikaello](https://github.com/mikaello).
-## 0.57.0
+## 0.57.0 (2020-06-13)
* Remove broken link from "External Links". PR [#1565](https://github.com/tiangolo/fastapi/pull/1565) by [@victorphoenix3](https://github.com/victorphoenix3).
* Update/fix docs for [WebSockets with dependencies](https://fastapi.tiangolo.com/advanced/websockets/#using-depends-and-others). Original PR [#1540](https://github.com/tiangolo/fastapi/pull/1540) by [@ChihSeanHsu](https://github.com/ChihSeanHsu).
@@ -2510,7 +5954,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Remove obsolete Chinese articles after adding official community translations. PR [#1510](https://github.com/tiangolo/fastapi/pull/1510) by [@waynerv](https://github.com/waynerv).
* Add `__repr__` for *path operation function* parameter helpers (like `Query`, `Depends`, etc) to simplify debugging. PR [#1560](https://github.com/tiangolo/fastapi/pull/1560) by [@rkbeatss](https://github.com/rkbeatss) and [@victorphoenix3](https://github.com/victorphoenix3).
-## 0.56.1
+## 0.56.1 (2020-06-12)
* Add link to advanced docs from tutorial. PR [#1512](https://github.com/tiangolo/fastapi/pull/1512) by [@kx-chen](https://github.com/kx-chen).
* Remove internal unnecessary f-strings. PR [#1526](https://github.com/tiangolo/fastapi/pull/1526) by [@kotamatsuoka](https://github.com/kotamatsuoka).
@@ -2530,7 +5974,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Remove `*,` from functions in docs where it's not needed. PR [#1239](https://github.com/tiangolo/fastapi/pull/1239) by [@pankaj-giri](https://github.com/pankaj-giri).
* Start translations for Italian. PR [#1557](https://github.com/tiangolo/fastapi/pull/1557) by [@csr](https://github.com/csr).
-## 0.56.0
+## 0.56.0 (2020-06-11)
* Add support for ASGI `root_path`:
* Use `root_path` internally for mounted applications, so that OpenAPI and the docs UI works automatically without extra configurations and parameters.
@@ -2545,26 +5989,26 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Add new links:
* **English articles**:
* [Real-time Notifications with Python and Postgres](https://wuilly.com/2019/10/real-time-notifications-with-python-and-postgres/) by [Guillermo Cruz](https://wuilly.com/).
- * [Microservice in Python using FastAPI](https://dev.to/paurakhsharma/microservice-in-python-using-fastapi-24cc) by [Paurakh Sharma Humagain](https://twitter.com/PaurakhSharma).
+ * [Microservice in Python using FastAPI](https://dev.to/paurakhsharma/microservice-in-python-using-fastapi-24cc) by [Paurakh Sharma Humagain](https://x.com/PaurakhSharma).
* [Build simple API service with Python FastAPI — Part 1](https://dev.to/cuongld2/build-simple-api-service-with-python-fastapi-part-1-581o) by [cuongld2](https://dev.to/cuongld2).
- * [FastAPI + Zeit.co = 🚀](https://paulsec.github.io/posts/fastapi_plus_zeit_serverless_fu/) by [Paul Sec](https://twitter.com/PaulWebSec).
- * [Build a web API from scratch with FastAPI - the workshop](https://dev.to/tiangolo/build-a-web-api-from-scratch-with-fastapi-the-workshop-2ehe) by [Sebastián Ramírez (tiangolo)](https://twitter.com/tiangolo).
+ * [FastAPI + Zeit.co = 🚀](https://paulsec.github.io/posts/fastapi_plus_zeit_serverless_fu/) by [Paul Sec](https://x.com/PaulWebSec).
+ * [Build a web API from scratch with FastAPI - the workshop](https://dev.to/tiangolo/build-a-web-api-from-scratch-with-fastapi-the-workshop-2ehe) by [Sebastián Ramírez (tiangolo)](https://x.com/tiangolo).
* [Build a Secure Twilio Webhook with Python and FastAPI](https://www.twilio.com/blog/build-secure-twilio-webhook-python-fastapi) by [Twilio](https://www.twilio.com).
- * [Using FastAPI with Django](https://www.stavros.io/posts/fastapi-with-django/) by [Stavros Korokithakis](https://twitter.com/Stavros).
+ * [Using FastAPI with Django](https://www.stavros.io/posts/fastapi-with-django/) by [Stavros Korokithakis](https://x.com/Stavros).
* [Introducing Dispatch](https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072) by [Netflix](https://netflixtechblog.com/).
* **Podcasts**:
* [Build The Next Generation Of Python Web Applications With FastAPI - Episode 259 - interview to Sebastían Ramírez (tiangolo)](https://www.pythonpodcast.com/fastapi-web-application-framework-episode-259/) by [Podcast.`__init__`](https://www.pythonpodcast.com/).
* **Talks**:
- * [PyConBY 2020: Serve ML models easily with FastAPI](https://www.youtube.com/watch?v=z9K5pwb0rt8) by [Sebastián Ramírez (tiangolo)](https://twitter.com/tiangolo).
- * [[VIRTUAL] Py.Amsterdam's flying Software Circus: Intro to FastAPI](https://www.youtube.com/watch?v=PnpTY1f4k2U) by [Sebastián Ramírez (tiangolo)](https://twitter.com/tiangolo).
+ * [PyConBY 2020: Serve ML models easily with FastAPI](https://www.youtube.com/watch?v=z9K5pwb0rt8) by [Sebastián Ramírez (tiangolo)](https://x.com/tiangolo).
+ * [[VIRTUAL] Py.Amsterdam's flying Software Circus: Intro to FastAPI](https://www.youtube.com/watch?v=PnpTY1f4k2U) by [Sebastián Ramírez (tiangolo)](https://x.com/tiangolo).
* PR [#1467](https://github.com/tiangolo/fastapi/pull/1467).
* Add translation to Chinese for [Python Types Intro - Python 类型提示简介](https://fastapi.tiangolo.com/zh/python-types/). PR [#1197](https://github.com/tiangolo/fastapi/pull/1197) by [@waynerv](https://github.com/waynerv).
-## 0.55.1
+## 0.55.1 (2020-05-23)
* Fix handling of enums with their own schema in path parameters. To support [pydantic/pydantic#1432](https://github.com/pydantic/pydantic/pull/1432) in FastAPI. PR [#1463](https://github.com/tiangolo/fastapi/pull/1463).
-## 0.55.0
+## 0.55.0 (2020-05-23)
* Allow enums to allow them to have their own schemas in OpenAPI. To support [pydantic/pydantic#1432](https://github.com/pydantic/pydantic/pull/1432) in FastAPI. PR [#1461](https://github.com/tiangolo/fastapi/pull/1461).
* Add links for funding through [GitHub sponsors](https://github.com/sponsors/tiangolo). PR [#1425](https://github.com/tiangolo/fastapi/pull/1425).
@@ -2580,7 +6024,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Update order of execution for `get_db` in SQLAlchemy tutorial. PR [#1293](https://github.com/tiangolo/fastapi/pull/1293) by [@bcb](https://github.com/bcb).
* Fix typos in Async docs. PR [#1423](https://github.com/tiangolo/fastapi/pull/1423).
-## 0.54.2
+## 0.54.2 (2020-05-16)
* Add translation to Spanish for [Concurrency and async / await - Concurrencia y async / await](https://fastapi.tiangolo.com/es/async/). PR [#1290](https://github.com/tiangolo/fastapi/pull/1290) by [@alvaropernas](https://github.com/alvaropernas).
* Remove obsolete vote link. PR [#1289](https://github.com/tiangolo/fastapi/pull/1289) by [@donhui](https://github.com/donhui).
@@ -2600,12 +6044,12 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Add Spanish translation for [Introducción a los Tipos de Python (Python Types Intro)](https://fastapi.tiangolo.com/es/python-types/). PR [#1237](https://github.com/tiangolo/fastapi/pull/1237) by [@mariacamilagl](https://github.com/mariacamilagl).
* Add Spanish translation for [Características (Features)](https://fastapi.tiangolo.com/es/features/). PR [#1220](https://github.com/tiangolo/fastapi/pull/1220) by [@mariacamilagl](https://github.com/mariacamilagl).
-## 0.54.1
+## 0.54.1 (2020-04-08)
* Update database test setup. PR [#1226](https://github.com/tiangolo/fastapi/pull/1226).
* Improve test debugging by showing response text in failing tests. PR [#1222](https://github.com/tiangolo/fastapi/pull/1222) by [@samuelcolvin](https://github.com/samuelcolvin).
-## 0.54.0
+## 0.54.0 (2020-04-05)
* Fix grammatical mistakes in async docs. PR [#1188](https://github.com/tiangolo/fastapi/pull/1188) by [@mickeypash](https://github.com/mickeypash).
* Add support for `response_model_exclude_defaults` and `response_model_exclude_none`:
@@ -2620,7 +6064,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Add first translation to Spanish [FastAPI](https://fastapi.tiangolo.com/es/). PR [#1201](https://github.com/tiangolo/fastapi/pull/1201) by [@mariacamilagl](https://github.com/mariacamilagl).
* Add docs about [Settings and Environment Variables](https://fastapi.tiangolo.com/advanced/settings/). Initial PR [1118](https://github.com/tiangolo/fastapi/pull/1118) by [@alexmitelman](https://github.com/alexmitelman).
-## 0.53.2
+## 0.53.2 (2020-03-30)
* Fix automatic embedding of body fields for dependencies and sub-dependencies. Original PR [#1079](https://github.com/tiangolo/fastapi/pull/1079) by [@Toad2186](https://github.com/Toad2186).
* Fix dependency overrides in WebSocket testing. PR [#1122](https://github.com/tiangolo/fastapi/pull/1122) by [@amitlissack](https://github.com/amitlissack).
@@ -2628,7 +6072,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Start translations for Chinese. PR [#1187](https://github.com/tiangolo/fastapi/pull/1187) by [@RunningIkkyu](https://github.com/RunningIkkyu).
* Add docs for [Schema Extra - Example](https://fastapi.tiangolo.com/tutorial/schema-extra-example/). PR [#1185](https://github.com/tiangolo/fastapi/pull/1185).
-## 0.53.1
+## 0.53.1 (2020-03-29)
* Fix included example after translations refactor. PR [#1182](https://github.com/tiangolo/fastapi/pull/1182).
* Add docs example for `example` in `Field`. Docs at [Body - Fields: JSON Schema extras](https://fastapi.tiangolo.com/tutorial/body-fields/#json-schema-extras). PR [#1106](https://github.com/tiangolo/fastapi/pull/1106) by [@JohnPaton](https://github.com/JohnPaton).
@@ -2637,7 +6081,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Fix typo in docs. PR [#1148](https://github.com/tiangolo/fastapi/pull/1148) by [@PLNech](https://github.com/PLNech).
* Update Windows development environment instructions. PR [#1179](https://github.com/tiangolo/fastapi/pull/1179).
-## 0.53.0
+## 0.53.0 (2020-03-27)
* Update test coverage badge. PR [#1175](https://github.com/tiangolo/fastapi/pull/1175).
* Add `orjson` to `pip install fastapi[all]`. PR [#1161](https://github.com/tiangolo/fastapi/pull/1161) by [@michael0liver](https://github.com/michael0liver).
@@ -2652,11 +6096,11 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Add support for docs translations. New docs: [Development - Contributing: Docs: Translations](https://fastapi.tiangolo.com/contributing/#translations). PR [#1168](https://github.com/tiangolo/fastapi/pull/1168).
* Update terminal styles in docs and add note about [**Typer**, the FastAPI of CLIs](https://typer.tiangolo.com/). PR [#1139](https://github.com/tiangolo/fastapi/pull/1139).
-## 0.52.0
+## 0.52.0 (2020-03-01)
* Add new high-performance JSON response class using `orjson`. New docs: [Custom Response - HTML, Stream, File, others: `ORJSONResponse`](https://fastapi.tiangolo.com/advanced/custom-response/#use-orjsonresponse). PR [#1065](https://github.com/tiangolo/fastapi/pull/1065).
-## 0.51.0
+## 0.51.0 (2020-03-01)
* Re-export utils from Starlette:
* This allows using things like `from fastapi.responses import JSONResponse` instead of `from starlette.responses import JSONResponse`.
@@ -2668,7 +6112,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* [Including WSGI - Flask, Django, others](https://fastapi.tiangolo.com/advanced/wsgi/).
* PR [#1064](https://github.com/tiangolo/fastapi/pull/1064).
-## 0.50.0
+## 0.50.0 (2020-02-29)
* Add link to Release Notes from docs about pinning versions for deployment. PR [#1058](https://github.com/tiangolo/fastapi/pull/1058).
* Upgrade code to use the latest version of Starlette, including:
@@ -2678,7 +6122,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* PR [#1057](https://github.com/tiangolo/fastapi/pull/1057).
* Add docs about pinning FastAPI versions for deployment: [Deployment: FastAPI versions](https://fastapi.tiangolo.com/deployment/#fastapi-versions). PR [#1056](https://github.com/tiangolo/fastapi/pull/1056).
-## 0.49.2
+## 0.49.2 (2020-02-29)
* Fix links in release notes. PR [#1052](https://github.com/tiangolo/fastapi/pull/1052) by [@sattosan](https://github.com/sattosan).
* Fix typo in release notes. PR [#1051](https://github.com/tiangolo/fastapi/pull/1051) by [@sattosan](https://github.com/sattosan).
@@ -2688,14 +6132,14 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Fix accepting valid types for response models, including Python types like `List[int]`. PR [#1017](https://github.com/tiangolo/fastapi/pull/1017) by [@patrickmckenna](https://github.com/patrickmckenna).
* Fix format in SQL tutorial. PR [#1015](https://github.com/tiangolo/fastapi/pull/1015) by [@vegarsti](https://github.com/vegarsti).
-## 0.49.1
+## 0.49.1 (2020-02-28)
* Fix path operation duplicated parameters when used in dependencies and the path operation function. PR [#994](https://github.com/tiangolo/fastapi/pull/994) by [@merowinger92](https://github.com/merowinger92).
* Update Netlify previews deployment GitHub action as the fix is already merged and there's a new release. PR [#1047](https://github.com/tiangolo/fastapi/pull/1047).
* Move mypy configurations to config file. PR [#987](https://github.com/tiangolo/fastapi/pull/987) by [@hukkinj1](https://github.com/hukkinj1).
* Temporary fix to Netlify previews not deployable from PRs from forks. PR [#1046](https://github.com/tiangolo/fastapi/pull/1046) by [@mariacamilagl](https://github.com/mariacamilagl).
-## 0.49.0
+## 0.49.0 (2020-02-16)
* Fix encoding of `pathlib` paths in `jsonable_encoder`. PR [#978](https://github.com/tiangolo/fastapi/pull/978) by [@patrickmckenna](https://github.com/patrickmckenna).
* Add articles to [External Links](https://fastapi.tiangolo.com/external-links/): [PythonのWeb frameworkのパフォーマンス比較 (Django, Flask, responder, FastAPI, japronto)](https://qiita.com/bee2/items/0ad260ab9835a2087dae) and [[FastAPI] Python製のASGI Web フレームワーク FastAPIに入門する](https://qiita.com/bee2/items/75d9c0d7ba20e7a4a0e9). PR [#974](https://github.com/tiangolo/fastapi/pull/974) by [@tokusumi](https://github.com/tokusumi).
@@ -2706,7 +6150,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Update CI to run docs deployment in GitHub actions. PR [#983](https://github.com/tiangolo/fastapi/pull/983).
* Allow `callable`s in *path operation functions*, like functions modified with `functools.partial`. PR [#977](https://github.com/tiangolo/fastapi/pull/977).
-## 0.48.0
+## 0.48.0 (2020-02-04)
* Run linters first in tests to error out faster. PR [#948](https://github.com/tiangolo/fastapi/pull/948).
* Log warning about `email-validator` only when used. PR [#946](https://github.com/tiangolo/fastapi/pull/946).
@@ -2723,12 +6167,12 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Fix link in middleware docs. PR [#893](https://github.com/tiangolo/fastapi/pull/893) by [@linchiwei123](https://github.com/linchiwei123).
* Rename default API title from "Fast API" to "FastAPI" for consistency. PR [#890](https://github.com/tiangolo/fastapi/pull/890).
-## 0.47.1
+## 0.47.1 (2020-01-18)
* Fix model filtering in `response_model`, cloning sub-models. PR [#889](https://github.com/tiangolo/fastapi/pull/889).
* Fix FastAPI serialization of Pydantic models using ORM mode blocking the event loop. PR [#888](https://github.com/tiangolo/fastapi/pull/888).
-## 0.47.0
+## 0.47.0 (2020-01-18)
* Refactor documentation to make a simpler and shorter [Tutorial - User Guide](https://fastapi.tiangolo.com/tutorial/) and an additional [Advanced User Guide](https://fastapi.tiangolo.com/advanced/) with all the additional docs. PR [#887](https://github.com/tiangolo/fastapi/pull/887).
* Tweak external links, Markdown format, typos. PR [#881](https://github.com/tiangolo/fastapi/pull/881).
@@ -2740,7 +6184,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Setup development environment with Python's Venv and Flit, instead of requiring the extra Pipenv duplicating dependencies. Updated docs: [Development - Contributing](https://fastapi.tiangolo.com/contributing/). PR [#877](https://github.com/tiangolo/fastapi/pull/877).
* Update docs for [HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/security/http-basic-auth/) to improve security against timing attacks. Initial PR [#807](https://github.com/tiangolo/fastapi/pull/807) by [@zwass](https://github.com/zwass).
-## 0.46.0
+## 0.46.0 (2020-01-08)
* Fix typos and tweak configs. PR [#837](https://github.com/tiangolo/fastapi/pull/837).
* Add link to Chinese article in [External Links](https://fastapi.tiangolo.com/external-links/). PR [810](https://github.com/tiangolo/fastapi/pull/810) by [@wxq0309](https://github.com/wxq0309).
@@ -2754,7 +6198,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Fix Twitter links in docs. PR [#813](https://github.com/tiangolo/fastapi/pull/813) by [@justindujardin](https://github.com/justindujardin).
* Add docs for correctly [using FastAPI with Peewee ORM](https://fastapi.tiangolo.com/advanced/sql-databases-peewee/). Including how to overwrite parts of Peewee to correctly handle async threads. PR [#789](https://github.com/tiangolo/fastapi/pull/789).
-## 0.45.0
+## 0.45.0 (2019-12-11)
* Add support for OpenAPI Callbacks:
* New docs: [OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
@@ -2766,7 +6210,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Remove gender bias in docs for handling errors. PR [#780](https://github.com/tiangolo/fastapi/pull/780). Original idea in PR [#761](https://github.com/tiangolo/fastapi/pull/761) by [@classywhetten](https://github.com/classywhetten).
* Rename docs and references to `body-schema` to `body-fields` to keep in line with Pydantic. PR [#746](https://github.com/tiangolo/fastapi/pull/746) by [@prostomarkeloff](https://github.com/prostomarkeloff).
-## 0.44.1
+## 0.44.1 (2019-12-04)
* Add GitHub social preview images to git. PR [#752](https://github.com/tiangolo/fastapi/pull/752).
* Update PyPI "trove classifiers". PR [#751](https://github.com/tiangolo/fastapi/pull/751).
@@ -2774,7 +6218,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Update "new issue" templates. PR [#749](https://github.com/tiangolo/fastapi/pull/749).
* Fix serialization of errors for exotic Pydantic types. PR [#748](https://github.com/tiangolo/fastapi/pull/748) by [@dmontagu](https://github.com/dmontagu).
-## 0.44.0
+## 0.44.0 (2019-11-27)
* Add GitHub action [Issue Manager](https://github.com/tiangolo/issue-manager). PR [#742](https://github.com/tiangolo/fastapi/pull/742).
* Fix typos in docs. PR [734](https://github.com/tiangolo/fastapi/pull/734) by [@bundabrg](https://github.com/bundabrg).
@@ -2787,7 +6231,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Fix typo in HTTP protocol in CORS example. PR [#647](https://github.com/tiangolo/fastapi/pull/647) by [@forestmonster](https://github.com/forestmonster).
* Add support for Pydantic versions `1.0.0` and above, with temporary (deprecated) backwards compatibility for Pydantic `0.32.2`. PR [#646](https://github.com/tiangolo/fastapi/pull/646) by [@dmontagu](https://github.com/dmontagu).
-## 0.43.0
+## 0.43.0 (2019-11-24)
* Update docs to reduce gender bias. PR [#645](https://github.com/tiangolo/fastapi/pull/645) by [@ticosax](https://github.com/ticosax).
* Add docs about [overriding the `operationId` for all the *path operations*](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#using-the-path-operation-function-name-as-the-operationid) based on their function name. PR [#642](https://github.com/tiangolo/fastapi/pull/642) by [@SKalt](https://github.com/SKalt).
@@ -2797,7 +6241,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Add docs for [self-serving docs' (Swagger UI) static assets](https://fastapi.tiangolo.com/advanced/extending-openapi/#self-hosting-javascript-and-css-for-docs), e.g. to use the docs offline, or without Internet. Initial PR [#557](https://github.com/tiangolo/fastapi/pull/557) by [@svalouch](https://github.com/svalouch).
* Fix `black` linting after upgrade. PR [#682](https://github.com/tiangolo/fastapi/pull/682) by [@frankie567](https://github.com/frankie567).
-## 0.42.0
+## 0.42.0 (2019-10-09)
* Add dependencies with `yield`, a.k.a. exit steps, context managers, cleanup, teardown, ...
* This allows adding extra code after a dependency is done. It can be used, for example, to close database connections.
@@ -2812,7 +6256,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* PR [#595](https://github.com/tiangolo/fastapi/pull/595).
* Fix `sitemap.xml` in website. PR [#598](https://github.com/tiangolo/fastapi/pull/598) by [@samuelcolvin](https://github.com/samuelcolvin).
-## 0.41.0
+## 0.41.0 (2019-10-07)
* Upgrade required Starlette to `0.12.9`, the new range is `>=0.12.9,<=0.12.9`.
* Add `State` to FastAPI apps at `app.state`.
@@ -2827,7 +6271,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* PR [#589](https://github.com/tiangolo/fastapi/pull/589) by [@dmontagu](https://github.com/dmontagu).
* Fix preserving custom route class in routers when including other sub-routers. PR [#538](https://github.com/tiangolo/fastapi/pull/538) by [@dmontagu](https://github.com/dmontagu).
-## 0.40.0
+## 0.40.0 (2019-10-04)
* Add notes to docs about installing `python-multipart` when using forms. PR [#574](https://github.com/tiangolo/fastapi/pull/574) by [@sliptonic](https://github.com/sliptonic).
* Generate OpenAPI schemas in alphabetical order. PR [#554](https://github.com/tiangolo/fastapi/pull/554) by [@dmontagu](https://github.com/dmontagu).
@@ -2840,7 +6284,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Fix incorrect documentation example in [first steps](https://fastapi.tiangolo.com/tutorial/first-steps/). PR [#511](https://github.com/tiangolo/fastapi/pull/511) by [@IgnatovFedor](https://github.com/IgnatovFedor).
* Add support for Swagger UI [initOauth](https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/oauth2.md) settings with the parameter `swagger_ui_init_oauth`. PR [#499](https://github.com/tiangolo/fastapi/pull/499) by [@zamiramir](https://github.com/zamiramir).
-## 0.39.0
+## 0.39.0 (2019-09-29)
* Allow path parameters to have default values (e.g. `None`) and discard them instead of raising an error.
* This allows declaring a parameter like `user_id: str = None` that can be taken from a query parameter, but the same *path operation* can be included in a router with a path `/users/{user_id}`, in which case will be taken from the path and will be required.
@@ -2848,17 +6292,17 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Add support for setting a `default_response_class` in the `FastAPI` instance or in `include_router`. Initial PR [#467](https://github.com/tiangolo/fastapi/pull/467) by [@toppk](https://github.com/toppk).
* Add support for type annotations using strings and `from __future__ import annotations`. PR [#451](https://github.com/tiangolo/fastapi/pull/451) by [@dmontagu](https://github.com/dmontagu).
-## 0.38.1
+## 0.38.1 (2019-09-01)
* Fix incorrect `Request` class import. PR [#493](https://github.com/tiangolo/fastapi/pull/493) by [@kamalgill](https://github.com/kamalgill).
-## 0.38.0
+## 0.38.0 (2019-08-31)
* Add recent articles to [External Links](https://fastapi.tiangolo.com/external-links/) and recent opinions. PR [#490](https://github.com/tiangolo/fastapi/pull/490).
* Upgrade support range for Starlette to include `0.12.8`. The new range is `>=0.11.1,<=0.12.8"`. PR [#477](https://github.com/tiangolo/fastapi/pull/477) by [@dmontagu](https://github.com/dmontagu).
* Upgrade support to Pydantic version 0.32.2 and update internal code to use it (breaking change). PR [#463](https://github.com/tiangolo/fastapi/pull/463) by [@dmontagu](https://github.com/dmontagu).
-## 0.37.0
+## 0.37.0 (2019-08-31)
* Add support for custom route classes for advanced use cases. PR [#468](https://github.com/tiangolo/fastapi/pull/468) by [@dmontagu](https://github.com/dmontagu).
* Allow disabling Google fonts in ReDoc. PR [#481](https://github.com/tiangolo/fastapi/pull/481) by [@b1-luettje](https://github.com/b1-luettje).
@@ -2867,14 +6311,14 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Add support and tests for Pydantic dataclasses in `response_model`. PR [#454](https://github.com/tiangolo/fastapi/pull/454) by [@dconathan](https://github.com/dconathan).
* Fix typo in OAuth2 JWT tutorial. PR [#447](https://github.com/tiangolo/fastapi/pull/447) by [@pablogamboa](https://github.com/pablogamboa).
* Use the `media_type` parameter in `Body()` params to set the media type in OpenAPI for `requestBody`. PR [#439](https://github.com/tiangolo/fastapi/pull/439) by [@divums](https://github.com/divums).
-* Add article [Deploying a scikit-learn model with ONNX and FastAPI](https://medium.com/@nico.axtmann95/deploying-a-scikit-learn-model-with-onnx-und-fastapi-1af398268915) by [https://www.linkedin.com/in/nico-axtmann](Nico Axtmann). PR [#438](https://github.com/tiangolo/fastapi/pull/438) by [@naxty](https://github.com/naxty).
+* Add article [Deploying a scikit-learn model with ONNX and FastAPI](https://medium.com/@nico.axtmann95/deploying-a-scikit-learn-model-with-onnx-und-fastapi-1af398268915) by [Nico Axtmann](https://www.linkedin.com/in/nico-axtmann). PR [#438](https://github.com/tiangolo/fastapi/pull/438) by [@naxty](https://github.com/naxty).
* Allow setting custom `422` (validation error) response/schema in OpenAPI.
* And use media type from response class instead of fixed `application/json` (the default).
* PR [#437](https://github.com/tiangolo/fastapi/pull/437) by [@divums](https://github.com/divums).
* Fix using `"default"` extra response with status codes at the same time. PR [#489](https://github.com/tiangolo/fastapi/pull/489).
* Allow additional responses to use status code ranges (like `5XX` and `4XX`) and `"default"`. PR [#435](https://github.com/tiangolo/fastapi/pull/435) by [@divums](https://github.com/divums).
-## 0.36.0
+## 0.36.0 (2019-08-26)
* Fix implementation for `skip_defaults` when returning a Pydantic model. PR [#422](https://github.com/tiangolo/fastapi/pull/422) by [@dmontagu](https://github.com/dmontagu).
* Fix OpenAPI generation when using the same dependency in multiple places for the same *path operation*. PR [#417](https://github.com/tiangolo/fastapi/pull/417) by [@dmontagu](https://github.com/dmontagu).
@@ -2885,23 +6329,23 @@ Note: all the previous parameters are still there, so it's still possible to dec
* PR [#415](https://github.com/tiangolo/fastapi/pull/415) by [@vitalik](https://github.com/vitalik).
* Fix mypy error after merging PR #415. PR [#462](https://github.com/tiangolo/fastapi/pull/462).
-## 0.35.0
+## 0.35.0 (2019-08-08)
* Fix typo in routing `assert`. PR [#419](https://github.com/tiangolo/fastapi/pull/419) by [@pablogamboa](https://github.com/pablogamboa).
* Fix typo in docs. PR [#411](https://github.com/tiangolo/fastapi/pull/411) by [@bronsen](https://github.com/bronsen).
* Fix parsing a body type declared with `Union`. PR [#400](https://github.com/tiangolo/fastapi/pull/400) by [@koxudaxi](https://github.com/koxudaxi).
-## 0.34.0
+## 0.34.0 (2019-08-06)
* Upgrade Starlette supported range to include the latest `0.12.7`. The new range is `0.11.1,<=0.12.7`. PR [#367](https://github.com/tiangolo/fastapi/pull/367) by [@dedsm](https://github.com/dedsm).
* Add test for OpenAPI schema with duplicate models from PR [#333](https://github.com/tiangolo/fastapi/pull/333) by [@dmontagu](https://github.com/dmontagu). PR [#385](https://github.com/tiangolo/fastapi/pull/385).
-## 0.33.0
+## 0.33.0 (2019-07-13)
* Upgrade Pydantic version to `0.30.0`. PR [#384](https://github.com/tiangolo/fastapi/pull/384) by [@jekirl](https://github.com/jekirl).
-## 0.32.0
+## 0.32.0 (2019-07-12)
* Fix typo in docs for features. PR [#380](https://github.com/tiangolo/fastapi/pull/380) by [@MartinoMensio](https://github.com/MartinoMensio).
@@ -2925,14 +6369,14 @@ Note: all the previous parameters are still there, so it's still possible to dec
* This also adds the possibility of using `.include_router()` with the same `APIRouter` *multiple* times, with different prefixes, e.g. `/api/v2` and `/api/latest`, and it will now work correctly.
* PR [#347](https://github.com/tiangolo/fastapi/pull/347).
-## 0.31.0
+## 0.31.0 (2019-06-28)
* Upgrade Pydantic supported version to `0.29.0`.
* New supported version range is `"pydantic >=0.28,<=0.29.0"`.
- * This adds support for Pydantic [Generic Models](https://pydantic-docs.helpmanual.io/#generic-models), kudos to [@dmontagu](https://github.com/dmontagu).
+ * This adds support for Pydantic [Generic Models](https://docs.pydantic.dev/latest/#generic-models), kudos to [@dmontagu](https://github.com/dmontagu).
* PR [#344](https://github.com/tiangolo/fastapi/pull/344).
-## 0.30.1
+## 0.30.1 (2019-06-28)
* Add section in docs about [External Links and Articles](https://fastapi.tiangolo.com/external-links/). PR [#341](https://github.com/tiangolo/fastapi/pull/341).
@@ -2946,7 +6390,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Add SQLite [online viewers to the docs](https://fastapi.tiangolo.com/tutorial/sql-databases/#interact-with-the-database-directly). PR [#330](https://github.com/tiangolo/fastapi/pull/330) by [@cyrilbois](https://github.com/cyrilbois).
-## 0.30.0
+## 0.30.0 (2019-06-20)
* Add support for Pydantic's ORM mode:
* Updated documentation about SQL with SQLAlchemy, using Pydantic models with ORM mode, SQLAlchemy models with relations, separation of files, simplification of code and other changes. New docs: [SQL (Relational) Databases](https://fastapi.tiangolo.com/tutorial/sql-databases/).
@@ -2969,7 +6413,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Upgrade Pydantic support to `0.28`. PR [#320](https://github.com/tiangolo/fastapi/pull/320) by [@jekirl](https://github.com/jekirl).
-## 0.29.1
+## 0.29.1 (2019-06-13)
* Fix handling an empty-body request with a required body param. PR [#311](https://github.com/tiangolo/fastapi/pull/311).
@@ -2977,7 +6421,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Fix docs discrepancy in docs for [Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). PR [#288](https://github.com/tiangolo/fastapi/pull/288) by [@awiddersheim](https://github.com/awiddersheim).
-## 0.29.0
+## 0.29.0 (2019-06-06)
* Add support for declaring a `Response` parameter:
* This allows declaring:
@@ -2988,7 +6432,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Update attribution to Hug, for inspiring the `response` parameter pattern.
* PR [#294](https://github.com/tiangolo/fastapi/pull/294).
-## 0.28.0
+## 0.28.0 (2019-06-05)
* Implement dependency cache per request.
* This avoids calling each dependency multiple times for the same request.
@@ -3003,17 +6447,17 @@ Note: all the previous parameters are still there, so it's still possible to dec
* New docs: [Testing Dependencies with Overrides](https://fastapi.tiangolo.com/advanced/testing-dependencies/).
* PR [#291](https://github.com/tiangolo/fastapi/pull/291).
-## 0.27.2
+## 0.27.2 (2019-06-03)
* Fix path and query parameters receiving `dict` as a valid type. It should be mapped to a body payload. PR [#287](https://github.com/tiangolo/fastapi/pull/287). Updated docs at: [Query parameter list / multiple values with defaults: Using `list`](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#using-list).
-## 0.27.1
+## 0.27.1 (2019-06-03)
* Fix `auto_error=False` handling in `HTTPBearer` security scheme. Do not `raise` when there's an incorrect `Authorization` header if `auto_error=False`. PR [#282](https://github.com/tiangolo/fastapi/pull/282).
* Fix type declaration of `HTTPException`. PR [#279](https://github.com/tiangolo/fastapi/pull/279).
-## 0.27.0
+## 0.27.0 (2019-05-30)
* Fix broken link in docs about OAuth 2.0 with scopes. PR [#275](https://github.com/tiangolo/fastapi/pull/275) by [@dmontagu](https://github.com/dmontagu).
@@ -3024,7 +6468,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Add support for type annotations using `Optional` as in `param: Optional[str] = None`. New documentation: [Optional type declarations](https://fastapi.tiangolo.com/tutorial/query-params/#optional-type-declarations).
* PR [#278](https://github.com/tiangolo/fastapi/pull/278).
-## 0.26.0
+## 0.26.0 (2019-05-29)
* Separate error handling for validation errors.
* This will allow developers to customize the exception handlers.
@@ -3033,7 +6477,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* New documentation about exceptions handlers:
* [Install custom exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers).
* [Override the default exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-the-default-exception-handlers).
- * [Re-use **FastAPI's** exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#re-use-fastapis-exception-handlers).
+ * [Reuse **FastAPI's** exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#reuse-fastapis-exception-handlers).
* PR [#273](https://github.com/tiangolo/fastapi/pull/273).
* Fix support for *paths* in *path parameters* without needing explicit `Path(...)`.
@@ -3045,7 +6489,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Fix type declaration of `response_model` to allow generic Python types as `List[Model]`. Mainly to fix `mypy` for users. PR [#266](https://github.com/tiangolo/fastapi/pull/266).
-## 0.25.0
+## 0.25.0 (2019-05-27)
* Add support for Pydantic's `include`, `exclude`, `by_alias`.
* Update documentation: [Response Model](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
@@ -3061,7 +6505,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* New [documentation section about using `response_model_skip_defaults`](https://fastapi.tiangolo.com/tutorial/response-model/#response-model-encoding-parameters).
* PR [#248](https://github.com/tiangolo/fastapi/pull/248) by [@wshayes](https://github.com/wshayes).
-## 0.24.0
+## 0.24.0 (2019-05-24)
* Add support for WebSockets with dependencies and parameters.
* Support included for:
@@ -3079,17 +6523,17 @@ Note: all the previous parameters are still there, so it's still possible to dec
* This includes JSON Schema support for IP address and network objects, bug fixes, and other features.
* PR [#247](https://github.com/tiangolo/fastapi/pull/247) by [@euri10](https://github.com/euri10).
-## 0.23.0
+## 0.23.0 (2019-05-21)
* Upgrade the compatible version of Starlette to `0.12.0`.
* This includes support for ASGI 3 (the latest version of the standard).
- * It's now possible to use [Starlette's `StreamingResponse`](https://www.starlette.io/responses/#streamingresponse) with iterators, like [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) objects (as those returned by `open()`).
+ * It's now possible to use [Starlette's `StreamingResponse`](https://www.starlette.dev/responses/#streamingresponse) with iterators, like [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) objects (as those returned by `open()`).
* It's now possible to use the low level utility `iterate_in_threadpool` from `starlette.concurrency` (for advanced scenarios).
* PR [#243](https://github.com/tiangolo/fastapi/pull/243).
* 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).
@@ -3097,7 +6541,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Make Swagger UI and ReDoc URLs parameterizable, allowing to host and serve local versions of them and have offline docs. PR [#112](https://github.com/tiangolo/fastapi/pull/112) by [@euri10](https://github.com/euri10).
-## 0.22.0
+## 0.22.0 (2019-05-16)
* Add support for `dependencies` parameter:
* A parameter in *path operation decorators*, for dependencies that should be executed but the return value is not important or not used in the *path operation function*.
@@ -3119,7 +6563,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Re-enable `black` formatting checks for Python 3.7. PR [#229](https://github.com/tiangolo/fastapi/pull/229) by [@zamiramir](https://github.com/zamiramir).
-## 0.21.0
+## 0.21.0 (2019-05-15)
* On body parsing errors, raise `from` previous exception, to allow better introspection in logging code. PR [#192](https://github.com/tiangolo/fastapi/pull/195) by [@ricardomomm](https://github.com/ricardomomm).
@@ -3129,13 +6573,13 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Fix typo in routing. PR [#221](https://github.com/tiangolo/fastapi/pull/221) by [@djlambert](https://github.com/djlambert).
-## 0.20.1
+## 0.20.1 (2019-05-11)
* Add typing information to package including file `py.typed`. PR [#209](https://github.com/tiangolo/fastapi/pull/209) by [@meadsteve](https://github.com/meadsteve).
* Add FastAPI bot for Gitter. To automatically announce new releases. PR [#189](https://github.com/tiangolo/fastapi/pull/189).
-## 0.20.0
+## 0.20.0 (2019-04-27)
* Upgrade OAuth2:
* Upgrade Password flow using Bearer tokens to use the correct HTTP status code 401 `UNAUTHORIZED`, with `WWW-Authenticate` headers.
@@ -3152,7 +6596,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Fix typos in docs. PR [#176](https://github.com/tiangolo/fastapi/pull/176) by [@chdsbd](https://github.com/chdsbd).
-## 0.19.0
+## 0.19.0 (2019-04-26)
* Rename *path operation decorator* parameter `content_type` to `response_class`. PR [#183](https://github.com/tiangolo/fastapi/pull/183).
@@ -3162,7 +6606,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Update how to use a [Custom Response Class](https://fastapi.tiangolo.com/advanced/custom-response/).
* PR [#184](https://github.com/tiangolo/fastapi/pull/184).
-## 0.18.0
+## 0.18.0 (2019-04-22)
* Add docs for [HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/custom-response/). PR [#177](https://github.com/tiangolo/fastapi/pull/177).
@@ -3172,7 +6616,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Add docs for [Middleware](https://fastapi.tiangolo.com/tutorial/middleware/). PR [#173](https://github.com/tiangolo/fastapi/pull/173).
-## 0.17.0
+## 0.17.0 (2019-04-20)
* Make Flit publish from CI. PR [#170](https://github.com/tiangolo/fastapi/pull/170).
@@ -3180,7 +6624,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* By default, encode by alias. This allows using Pydantic `alias` parameters working by default. PR [#168](https://github.com/tiangolo/fastapi/pull/168).
-## 0.16.0
+## 0.16.0 (2019-04-16)
* Upgrade *path operation* `docstring` parsing to support proper Markdown descriptions. New documentation at [Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#description-from-docstring). PR [#163](https://github.com/tiangolo/fastapi/pull/163).
@@ -3192,13 +6636,13 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Fix [Query Parameters](https://fastapi.tiangolo.com/tutorial/query-params/) URL examples in docs. PR [#157](https://github.com/tiangolo/fastapi/pull/157) by [@hayata-yamamoto](https://github.com/hayata-yamamoto).
-## 0.15.0
+## 0.15.0 (2019-04-14)
* Add support for multiple file uploads (as a single form field). New docs at: [Multiple file uploads](https://fastapi.tiangolo.com/tutorial/request-files/#multiple-file-uploads). PR [#158](https://github.com/tiangolo/fastapi/pull/158).
* Add docs for: [Additional Status Codes](https://fastapi.tiangolo.com/advanced/additional-status-codes/). PR [#156](https://github.com/tiangolo/fastapi/pull/156).
-## 0.14.0
+## 0.14.0 (2019-04-12)
* Improve automatically generated names of *path operations* in OpenAPI (in API docs). A function `read_items` instead of having a generated name "Read Items Get" will have "Read Items". PR [#155](https://github.com/tiangolo/fastapi/pull/155).
@@ -3210,7 +6654,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Include Falcon and Hug in: [Alternatives, Inspiration and Comparisons](https://fastapi.tiangolo.com/alternatives/).
-## 0.13.0
+## 0.13.0 (2019-04-09)
* Improve/upgrade OAuth2 scopes support with `SecurityScopes`:
* `SecurityScopes` can be declared as a parameter like `Request`, to get the scopes of all super-dependencies/dependants.
@@ -3220,7 +6664,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* New docs about: [OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/).
* PR [#141](https://github.com/tiangolo/fastapi/pull/141).
-## 0.12.1
+## 0.12.1 (2019-04-05)
* Fix bug: handling additional `responses` in `APIRouter.include_router()`. PR [#140](https://github.com/tiangolo/fastapi/pull/140).
@@ -3228,7 +6672,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Fix typos in section about nested models and OAuth2 with JWT. PR [#127](https://github.com/tiangolo/fastapi/pull/127) by [@mmcloud](https://github.com/mmcloud).
-## 0.12.0
+## 0.12.0 (2019-04-05)
* Add additional `responses` parameter to *path operation decorators* to extend responses in OpenAPI (and API docs).
* It also allows extending existing responses generated from `response_model`, declare other media types (like images), etc.
@@ -3237,7 +6681,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* PR [#97](https://github.com/tiangolo/fastapi/pull/97) originally initiated by [@barsi](https://github.com/barsi).
* Update `scripts/test-cov-html.sh` to allow passing extra parameters like `-vv`, for development.
-## 0.11.0
+## 0.11.0 (2019-04-03)
* Add `auto_error` parameter to security utility functions. Allowing them to be optional. Also allowing to have multiple alternative security schemes that are then checked in a single dependency instead of each one verifying and returning the error to the client automatically when not satisfied. PR [#134](https://github.com/tiangolo/fastapi/pull/134).
@@ -3245,7 +6689,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Fix duplicate dependency in `pyproject.toml`. PR [#128](https://github.com/tiangolo/fastapi/pull/128) by [@zxalif](https://github.com/zxalif).
-## 0.10.3
+## 0.10.3 (2019-03-30)
* Add Gitter chat, badge, links, etc. [https://gitter.im/tiangolo/fastapi](https://gitter.im/tiangolo/fastapi) . PR [#117](https://github.com/tiangolo/fastapi/pull/117).
@@ -3259,7 +6703,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Fix event docs (startup/shutdown) function name. PR [#105](https://github.com/tiangolo/fastapi/pull/105) by [@stratosgear](https://github.com/stratosgear).
-## 0.10.2
+## 0.10.2 (2019-03-29)
* Fix OpenAPI (JSON Schema) for declarations of Python `Union` (JSON Schema `additionalProperties`). PR [#121](https://github.com/tiangolo/fastapi/pull/121).
@@ -3267,11 +6711,11 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Document response models using unions and lists, updated at: [Extra Models](https://fastapi.tiangolo.com/tutorial/extra-models/). PR [#108](https://github.com/tiangolo/fastapi/pull/108).
-## 0.10.1
+## 0.10.1 (2019-03-25)
* Add docs and tests for [encode/databases](https://github.com/encode/databases). New docs at: [Async SQL (Relational) Databases](https://fastapi.tiangolo.com/advanced/async-sql-databases/). PR [#107](https://github.com/tiangolo/fastapi/pull/107).
-## 0.10.0
+## 0.10.0 (2019-03-24)
* Add support for Background Tasks in *path operation functions* and dependencies. New documentation about [Background Tasks is here](https://fastapi.tiangolo.com/tutorial/background-tasks/). PR [#103](https://github.com/tiangolo/fastapi/pull/103).
@@ -3279,11 +6723,11 @@ Note: all the previous parameters are still there, so it's still possible to dec
* New docs section about [Events: startup - shutdown](https://fastapi.tiangolo.com/advanced/events/). PR [#99](https://github.com/tiangolo/fastapi/pull/99).
-## 0.9.1
+## 0.9.1 (2019-03-22)
* Document receiving [Multiple values with the same query parameter](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#query-parameter-list-multiple-values) and [Duplicate headers](https://fastapi.tiangolo.com/tutorial/header-params/#duplicate-headers). PR [#95](https://github.com/tiangolo/fastapi/pull/95).
-## 0.9.0
+## 0.9.0 (2019-03-22)
* Upgrade compatible Pydantic version to `0.21.0`. PR [#90](https://github.com/tiangolo/fastapi/pull/90).
@@ -3293,7 +6737,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Fix link in "Deployment" to "Bigger Applications".
-## 0.8.0
+## 0.8.0 (2019-03-16)
* Make development scripts executable. PR [#76](https://github.com/tiangolo/fastapi/pull/76) by [@euri10](https://github.com/euri10).
@@ -3303,7 +6747,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Update `isort` imports and scripts to be compatible with newer versions. PR [#75](https://github.com/tiangolo/fastapi/pull/75).
-## 0.7.1
+## 0.7.1 (2019-03-04)
* Update [technical details about `async def` handling](https://fastapi.tiangolo.com/async/#path-operation-functions) with respect to previous frameworks. PR [#64](https://github.com/tiangolo/fastapi/pull/64) by [@haizaar](https://github.com/haizaar).
@@ -3311,7 +6755,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Trigger Docker images build on Travis CI automatically. PR [#65](https://github.com/tiangolo/fastapi/pull/65).
-## 0.7.0
+## 0.7.0 (2019-03-03)
* Add support for `UploadFile` in `File` parameter annotations.
* This includes a file-like interface.
@@ -3319,7 +6763,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
* And here's the updated documentation for using [`Form` parameters mixed with `File` parameters, supporting `bytes` and `UploadFile`](https://fastapi.tiangolo.com/tutorial/request-forms-and-files/) at the same time.
* PR [#63](https://github.com/tiangolo/fastapi/pull/63).
-## 0.6.4
+## 0.6.4 (2019-03-02)
* Add [technical details about `async def` handling to docs](https://fastapi.tiangolo.com/async/#very-technical-details). PR [#61](https://github.com/tiangolo/fastapi/pull/61).
@@ -3333,11 +6777,11 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Add docs for using [WebSockets with **FastAPI**](https://fastapi.tiangolo.com/advanced/websockets/). PR [#62](https://github.com/tiangolo/fastapi/pull/62).
-## 0.6.3
+## 0.6.3 (2019-02-23)
* Add Favicons to docs. PR [#53](https://github.com/tiangolo/fastapi/pull/53).
-## 0.6.2
+## 0.6.2 (2019-02-23)
* Introduce new project generator based on FastAPI and PostgreSQL: [https://github.com/tiangolo/full-stack-fastapi-postgresql](https://github.com/tiangolo/full-stack-fastapi-postgresql). PR [#52](https://github.com/tiangolo/fastapi/pull/52).
@@ -3345,17 +6789,17 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Improve middleware naming in tutorial for SQL with SQLAlchemy [https://fastapi.tiangolo.com/tutorial/sql-databases/](https://fastapi.tiangolo.com/tutorial/sql-databases/).
-## 0.6.1
+## 0.6.1 (2019-02-20)
* Add docs for GraphQL: [https://fastapi.tiangolo.com/advanced/graphql/](https://fastapi.tiangolo.com/advanced/graphql/). PR [#48](https://github.com/tiangolo/fastapi/pull/48).
-## 0.6.0
+## 0.6.0 (2019-02-19)
* Update SQL with SQLAlchemy tutorial at [https://fastapi.tiangolo.com/tutorial/sql-databases/](https://fastapi.tiangolo.com/tutorial/sql-databases/) using the new official `request.state`. PR [#45](https://github.com/tiangolo/fastapi/pull/45).
* Upgrade Starlette to version `0.11.1` and add required compatibility changes. PR [#44](https://github.com/tiangolo/fastapi/pull/44).
-## 0.5.1
+## 0.5.1 (2019-02-18)
* Add section about [helping and getting help with **FastAPI**](https://fastapi.tiangolo.com/help-fastapi/).
@@ -3363,9 +6807,9 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Update [section about error handling](https://fastapi.tiangolo.com/tutorial/handling-errors/) with more information and make relation with Starlette error handling utilities more explicit. PR [#41](https://github.com/tiangolo/fastapi/pull/41).
-* Add Development - Contributing section to the docs. PR [#42](https://github.com/tiangolo/fastapi/pull/42).
+* Add [Development - Contributing section to the docs](). PR [#42](https://github.com/tiangolo/fastapi/pull/42).
-## 0.5.0
+## 0.5.0 (2019-02-16)
* Add new `HTTPException` with support for custom headers. With new documentation for handling errors at: [https://fastapi.tiangolo.com/tutorial/handling-errors/](https://fastapi.tiangolo.com/tutorial/handling-errors/). PR [#35](https://github.com/tiangolo/fastapi/pull/35).
@@ -3375,26 +6819,26 @@ Note: all the previous parameters are still there, so it's still possible to dec
* Update example for the SQLAlchemy tutorial at [https://fastapi.tiangolo.com/tutorial/sql-databases/](https://fastapi.tiangolo.com/tutorial/sql-databases/) using middleware and database session attached to request.
-## 0.4.0
+## 0.4.0 (2019-02-16)
* Add `openapi_prefix`, support for reverse proxy and mounting sub-applications. See the docs at [https://fastapi.tiangolo.com/advanced/sub-applications-proxy/](https://fastapi.tiangolo.com/advanced/sub-applications-proxy/): [#26](https://github.com/tiangolo/fastapi/pull/26) by [@kabirkhan](https://github.com/kabirkhan).
* Update [docs/tutorial for SQLAlchemy](https://fastapi.tiangolo.com/tutorial/sql-databases/) including note about _DB Browser for SQLite_.
-## 0.3.0
+## 0.3.0 (2019-02-12)
* Fix/add SQLAlchemy support, including ORM, and update [docs for SQLAlchemy](https://fastapi.tiangolo.com/tutorial/sql-databases/): [#30](https://github.com/tiangolo/fastapi/pull/30).
-## 0.2.1
+## 0.2.1 (2019-02-12)
* Fix `jsonable_encoder` for Pydantic models with `Config` but without `json_encoders`: [#29](https://github.com/tiangolo/fastapi/pull/29).
-## 0.2.0
+## 0.2.0 (2019-02-08)
* Fix typos in Security section: [#24](https://github.com/tiangolo/fastapi/pull/24) by [@kkinder](https://github.com/kkinder).
* Add support for Pydantic custom JSON encoders: [#21](https://github.com/tiangolo/fastapi/pull/21) by [@euri10](https://github.com/euri10).
-## 0.1.19
+## 0.1.19 (2019-02-01)
* Upgrade Starlette version to the current latest `0.10.1`: [#17](https://github.com/tiangolo/fastapi/pull/17) by [@euri10](https://github.com/euri10).
diff --git a/docs/en/docs/resources/index.md b/docs/en/docs/resources/index.md
new file mode 100644
index 0000000000000..f7d48576ffa03
--- /dev/null
+++ b/docs/en/docs/resources/index.md
@@ -0,0 +1,3 @@
+# Resources { #resources }
+
+Additional resources, external links, and more. ✈️
diff --git a/docs/en/docs/translation-banner.md b/docs/en/docs/translation-banner.md
new file mode 100644
index 0000000000000..1422870744b72
--- /dev/null
+++ b/docs/en/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 Translation by AI and humans
+
+This translation was made by AI guided by humans. 🤝
+
+It could have mistakes of misunderstanding the original meaning, or looking unnatural, etc. 🤖
+
+You can improve this translation by [helping us guide the AI LLM better](https://fastapi.tiangolo.com/contributing/#translations).
+
+[English version](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/en/docs/tutorial/background-tasks.md b/docs/en/docs/tutorial/background-tasks.md
index 1782971922ab2..dfb082f34c3e2 100644
--- a/docs/en/docs/tutorial/background-tasks.md
+++ b/docs/en/docs/tutorial/background-tasks.md
@@ -1,4 +1,4 @@
-# Background Tasks
+# Background Tasks { #background-tasks }
You can define background tasks to be run *after* returning a response.
@@ -9,19 +9,17 @@ This includes, for example:
* Email notifications sent after performing an action:
* As connecting to an email server and sending an email tends to be "slow" (several seconds), you can return the response right away and send the email notification in the background.
* Processing data:
- * For example, let's say you receive a file that must go through a slow process, you can return a response of "Accepted" (HTTP 202) and process it in the background.
+ * For example, let's say you receive a file that must go through a slow process, you can return a response of "Accepted" (HTTP 202) and process the file in the background.
-## Using `BackgroundTasks`
+## Using `BackgroundTasks` { #using-backgroundtasks }
First, import `BackgroundTasks` and define a parameter in your *path operation function* with a type declaration of `BackgroundTasks`:
-```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
**FastAPI** will create the object of type `BackgroundTasks` for you and pass it as that parameter.
-## Create a task function
+## Create a task function { #create-a-task-function }
Create a function to be run as the background task.
@@ -33,17 +31,13 @@ In this case, the task function will write to a file (simulating sending an emai
And as the write operation doesn't use `async` and `await`, we define the function with normal `def`:
-```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
-## Add the background task
+## Add the background task { #add-the-background-task }
Inside of your *path operation function*, pass your task function to the *background tasks* object with the method `.add_task()`:
-```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
`.add_task()` receives as arguments:
@@ -51,47 +45,15 @@ Inside of your *path operation function*, pass your task function to the *backgr
* Any sequence of arguments that should be passed to the task function in order (`email`).
* Any keyword arguments that should be passed to the task function (`message="some notification"`).
-## Dependency Injection
+## Dependency Injection { #dependency-injection }
Using `BackgroundTasks` also works with the dependency injection system, you can declare a parameter of type `BackgroundTasks` at multiple levels: in a *path operation function*, in a dependency (dependable), in a sub-dependency, etc.
-**FastAPI** knows what to do in each case and how to re-use the same object, so that all the background tasks are merged together and are run in the background afterwards:
+**FastAPI** knows what to do in each case and how to reuse the same object, so that all the background tasks are merged together and are run in the background afterwards:
-=== "Python 3.10+"
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!}
- ```
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
-=== "Python 3.9+"
-
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="14 16 23 26"
- {!> ../../../docs_src/background_tasks/tutorial002_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
In this example, the messages will be written to the `log.txt` file *after* the response is sent.
@@ -99,9 +61,9 @@ If there was a query in the request, it will be written to the log in a backgrou
And then another background task generated at the *path operation function* will write a message using the `email` path parameter.
-## Technical Details
+## Technical Details { #technical-details }
-The class `BackgroundTasks` comes directly from `starlette.background`.
+The class `BackgroundTasks` comes directly from [`starlette.background`](https://www.starlette.dev/background/).
It is imported/included directly into FastAPI so that you can import it from `fastapi` and avoid accidentally importing the alternative `BackgroundTask` (without the `s` at the end) from `starlette.background`.
@@ -109,18 +71,16 @@ By only using `BackgroundTasks` (and not `BackgroundTask`), it's then possible t
It's still possible to use `BackgroundTask` alone in FastAPI, but you have to create the object in your code and return a Starlette `Response` including it.
-You can see more details in Starlette's official docs for Background Tasks.
+You can see more details in [Starlette's official docs for Background Tasks](https://www.starlette.dev/background/).
-## Caveat
+## Caveat { #caveat }
-If you need to perform heavy background computation and you don't necessarily need it to be run by the same process (for example, you don't need to share memory, variables, etc), you might benefit from using other bigger tools like Celery.
+If you need to perform heavy background computation and you don't necessarily need it to be run by the same process (for example, you don't need to share memory, variables, etc), you might benefit from using other bigger tools like [Celery](https://docs.celeryq.dev).
They tend to require more complex configurations, a message/job queue manager, like RabbitMQ or Redis, but they allow you to run background tasks in multiple processes, and especially, in multiple servers.
-To see an example, check the [Project Generators](../project-generation.md){.internal-link target=_blank}, they all include Celery already configured.
-
But if you need to access variables and objects from the same **FastAPI** app, or you need to perform small background tasks (like sending an email notification), you can simply just use `BackgroundTasks`.
-## Recap
+## Recap { #recap }
Import and use `BackgroundTasks` with parameters in *path operation functions* and dependencies to add background tasks.
diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md
index 26d26475f2f52..675ec1b437687 100644
--- a/docs/en/docs/tutorial/bigger-applications.md
+++ b/docs/en/docs/tutorial/bigger-applications.md
@@ -1,13 +1,16 @@
-# Bigger Applications - Multiple Files
+# Bigger Applications - Multiple Files { #bigger-applications-multiple-files }
-If you are building an application or a web API, it's rarely the case that you can put everything on a single file.
+If you are building an application or a web API, it's rarely the case that you can put everything in a single file.
**FastAPI** provides a convenience tool to structure your application while keeping all the flexibility.
-!!! info
- If you come from Flask, this would be the equivalent of Flask's Blueprints.
+/// info
-## An example file structure
+If you come from Flask, this would be the equivalent of Flask's Blueprints.
+
+///
+
+## An example file structure { #an-example-file-structure }
Let's say you have a file structure like this:
@@ -26,16 +29,19 @@ Let's say you have a file structure like this:
│ └── admin.py
```
-!!! tip
- There are several `__init__.py` files: one in each directory or subdirectory.
+/// tip
+
+There are several `__init__.py` files: one in each directory or subdirectory.
- This is what allows importing code from one file into another.
+This is what allows importing code from one file into another.
- For example, in `app/main.py` you could have a line like:
+For example, in `app/main.py` you could have a line like:
- ```
- from app.routers import items
- ```
+```
+from app.routers import items
+```
+
+///
* The `app` directory contains everything. And it has an empty file `app/__init__.py`, so it is a "Python package" (a collection of "Python modules"): `app`.
* It contains an `app/main.py` file. As it is inside a Python package (a directory with a file `__init__.py`), it is a "module" of that package: `app.main`.
@@ -46,11 +52,11 @@ Let's say you have a file structure like this:
* There's also a subdirectory `app/internal/` with another file `__init__.py`, so it's another "Python subpackage": `app.internal`.
* And the file `app/internal/admin.py` is another submodule: `app.internal.admin`.
-
-## Include the same router multiple times with different `prefix`
+## Include the same router multiple times with different `prefix` { #include-the-same-router-multiple-times-with-different-prefix }
You can also use `.include_router()` multiple times with the *same* router using different prefixes.
@@ -494,7 +524,7 @@ This could be useful, for example, to expose the same API under different prefix
This is an advanced usage that you might not really need, but it's there in case you do.
-## Include an `APIRouter` in another
+## Include an `APIRouter` in another { #include-an-apirouter-in-another }
The same way you can include an `APIRouter` in a `FastAPI` application, you can include an `APIRouter` in another `APIRouter` using:
diff --git a/docs/en/docs/tutorial/body-fields.md b/docs/en/docs/tutorial/body-fields.md
index 8966032ff1473..11d4068480a8b 100644
--- a/docs/en/docs/tutorial/body-fields.md
+++ b/docs/en/docs/tutorial/body-fields.md
@@ -1,115 +1,60 @@
-# Body - Fields
+# Body - Fields { #body-fields }
The same way you can declare additional validation and metadata in *path operation function* parameters with `Query`, `Path` and `Body`, you can declare validation and metadata inside of Pydantic models using Pydantic's `Field`.
-## Import `Field`
+## Import `Field` { #import-field }
First, you have to import it:
-=== "Python 3.10+"
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
-=== "Python 3.9+"
+/// warning
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+Notice that `Field` is imported directly from `pydantic`, not from `fastapi` as are all the rest (`Query`, `Path`, `Body`, etc).
-=== "Python 3.6+"
+///
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
-
-!!! warning
- Notice that `Field` is imported directly from `pydantic`, not from `fastapi` as are all the rest (`Query`, `Path`, `Body`, etc).
-
-## Declare model attributes
+## Declare model attributes { #declare-model-attributes }
You can then use `Field` with model attributes:
-=== "Python 3.10+"
-
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
-
-=== "Python 3.9+"
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="12-15"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+`Field` works the same way as `Query`, `Path` and `Body`, it has all the same parameters, etc.
-=== "Python 3.6+ non-Annotated"
+/// note | Technical Details
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Actually, `Query`, `Path` and others you'll see next create objects of subclasses of a common `Param` class, which is itself a subclass of Pydantic's `FieldInfo` class.
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+And Pydantic's `Field` returns an instance of `FieldInfo` as well.
-`Field` works the same way as `Query`, `Path` and `Body`, it has all the same parameters, etc.
+`Body` also returns objects of a subclass of `FieldInfo` directly. And there are others you will see later that are subclasses of the `Body` class.
-!!! note "Technical Details"
- Actually, `Query`, `Path` and others you'll see next create objects of subclasses of a common `Param` class, which is itself a subclass of Pydantic's `FieldInfo` class.
+Remember that when you import `Query`, `Path`, and others from `fastapi`, those are actually functions that return special classes.
- And Pydantic's `Field` returns an instance of `FieldInfo` as well.
+///
- `Body` also returns objects of a subclass of `FieldInfo` directly. And there are others you will see later that are subclasses of the `Body` class.
+/// tip
- Remember that when you import `Query`, `Path`, and others from `fastapi`, those are actually functions that return special classes.
+Notice how each model's attribute with a type, default value and `Field` has the same structure as a *path operation function's* parameter, with `Field` instead of `Path`, `Query` and `Body`.
-!!! tip
- Notice how each model's attribute with a type, default value and `Field` has the same structure as a *path operation function's* parameter, with `Field` instead of `Path`, `Query` and `Body`.
+///
-## Add extra information
+## Add extra information { #add-extra-information }
You can declare extra information in `Field`, `Query`, `Body`, etc. And it will be included in the generated JSON Schema.
You will learn more about adding extra information later in the docs, when learning to declare examples.
-!!! warning
- Extra keys passed to `Field` will also be present in the resulting OpenAPI schema for your application.
- As these keys may not necessarily be part of the OpenAPI specification, some OpenAPI tools, for example [the OpenAPI validator](https://validator.swagger.io/), may not work with your generated schema.
+/// warning
+
+Extra keys passed to `Field` will also be present in the resulting OpenAPI schema for your application.
+As these keys may not necessarily be part of the OpenAPI specification, some OpenAPI tools, for example [the OpenAPI validator](https://validator.swagger.io/), may not work with your generated schema.
+
+///
-## Recap
+## Recap { #recap }
You can use Pydantic's `Field` to declare extra validations and metadata for model attributes.
diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md
index b214092c9b175..d904fb8397a5f 100644
--- a/docs/en/docs/tutorial/body-multiple-params.md
+++ b/docs/en/docs/tutorial/body-multiple-params.md
@@ -1,53 +1,22 @@
-# Body - Multiple Parameters
+# Body - Multiple Parameters { #body-multiple-parameters }
Now that we have seen how to use `Path` and `Query`, let's see more advanced uses of request body declarations.
-## Mix `Path`, `Query` and body parameters
+## Mix `Path`, `Query` and body parameters { #mix-path-query-and-body-parameters }
First, of course, you can mix `Path`, `Query` and request body parameter declarations freely and **FastAPI** will know what to do.
And you can also declare body parameters as optional, by setting the default to `None`:
-=== "Python 3.10+"
+{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
- ```
+/// note
-=== "Python 3.9+"
+Notice that, in this case, the `item` that would be taken from the body is optional. As it has a `None` default value.
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
- ```
+///
-=== "Python 3.6+"
-
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
-
-!!! note
- Notice that, in this case, the `item` that would be taken from the body is optional. As it has a `None` default value.
-
-## Multiple body parameters
+## Multiple body parameters { #multiple-body-parameters }
In the previous example, the *path operations* would expect a JSON body with the attributes of an `Item`, like:
@@ -62,19 +31,10 @@ In the previous example, the *path operations* would expect a JSON body with the
But you can also declare multiple body parameters, e.g. `item` and `user`:
-=== "Python 3.10+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
- ```
-
-=== "Python 3.6+"
+{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
- ```
-In this case, **FastAPI** will notice that there are more than one body parameters in the function (two parameters that are Pydantic models).
+In this case, **FastAPI** will notice that there is more than one body parameter in the function (there are two parameters that are Pydantic models).
So, it will then use the parameter names as keys (field names) in the body, and expect a body like:
@@ -93,15 +53,17 @@ So, it will then use the parameter names as keys (field names) in the body, and
}
```
-!!! note
- Notice that even though the `item` was declared the same way as before, it is now expected to be inside of the body with a key `item`.
+/// note
+Notice that even though the `item` was declared the same way as before, it is now expected to be inside of the body with a key `item`.
-**FastAPI** will do the automatic conversion from the request, so that the parameter `item` receives it's specific content and the same for `user`.
+///
+
+**FastAPI** will do the automatic conversion from the request, so that the parameter `item` receives its specific content and the same for `user`.
It will perform the validation of the compound data, and will document it like that for the OpenAPI schema and automatic docs.
-## Singular values in body
+## Singular values in body { #singular-values-in-body }
The same way there is a `Query` and `Path` to define extra data for query and path parameters, **FastAPI** provides an equivalent `Body`.
@@ -111,41 +73,8 @@ If you declare it as is, because it is a singular value, **FastAPI** will assume
But you can instruct **FastAPI** to treat it as another body key using `Body`:
-=== "Python 3.10+"
-
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
+{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
In this case, **FastAPI** will expect a body like:
@@ -167,64 +96,28 @@ In this case, **FastAPI** will expect a body like:
Again, it will convert the data types, validate, document, etc.
-## Multiple body params and query
+## Multiple body params and query { #multiple-body-params-and-query }
Of course, you can also declare additional query parameters whenever you need, additional to any body parameters.
As, by default, singular values are interpreted as query parameters, you don't have to explicitly add a `Query`, you can just do:
-```Python
-q: Union[str, None] = None
-```
-
-Or in Python 3.10 and above:
-
```Python
q: str | None = None
```
For example:
-=== "Python 3.10+"
-
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="28"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
- ```Python hl_lines="25"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
-=== "Python 3.6+ non-Annotated"
+/// info
- !!! tip
- Prefer to use the `Annotated` version if possible.
+`Body` also has all the same extra validation and metadata parameters as `Query`, `Path` and others you will see later.
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+///
-!!! info
- `Body` also has all the same extra validation and metadata parameters as `Query`,`Path` and others you will see later.
-
-## Embed a single body parameter
+## Embed a single body parameter { #embed-a-single-body-parameter }
Let's say you only have a single `item` body parameter from a Pydantic model `Item`.
@@ -238,41 +131,8 @@ item: Item = Body(embed=True)
as in:
-=== "Python 3.10+"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
+{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
In this case **FastAPI** will expect a body like:
@@ -298,7 +158,7 @@ instead of:
}
```
-## Recap
+## Recap { #recap }
You can add multiple body parameters to your *path operation function*, even though a request can only have a single body.
diff --git a/docs/en/docs/tutorial/body-nested-models.md b/docs/en/docs/tutorial/body-nested-models.md
index ffa0c0d0ef74f..17c560f40e5fd 100644
--- a/docs/en/docs/tutorial/body-nested-models.md
+++ b/docs/en/docs/tutorial/body-nested-models.md
@@ -1,85 +1,37 @@
-# Body - Nested Models
+# Body - Nested Models { #body-nested-models }
With **FastAPI**, you can define, validate, document, and use arbitrarily deeply nested models (thanks to Pydantic).
-## List fields
+## List fields { #list-fields }
You can define an attribute to be a subtype. For example, a Python `list`:
-=== "Python 3.10+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial001.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}
This will make `tags` be a list, although it doesn't declare the type of the elements of the list.
-## List fields with type parameter
+## List fields with type parameter { #list-fields-with-type-parameter }
But Python has a specific way to declare lists with internal types, or "type parameters":
-### Import typing's `List`
-
-In Python 3.9 and above you can use the standard `list` to declare these type annotations as we'll see below. 💡
-
-But in Python versions before 3.9 (3.6 and above), you first need to import `List` from standard Python's `typing` module:
-
-```Python hl_lines="1"
-{!> ../../../docs_src/body_nested_models/tutorial002.py!}
-```
-
-### Declare a `list` with a type parameter
-
-To declare types that have type parameters (internal types), like `list`, `dict`, `tuple`:
+### Declare a `list` with a type parameter { #declare-a-list-with-a-type-parameter }
-* If you are in a Python version lower than 3.9, import their equivalent version from the `typing` module
-* Pass the internal type(s) as "type parameters" using square brackets: `[` and `]`
-
-In Python 3.9 it would be:
+To declare types that have type parameters (internal types), like `list`, `dict`, `tuple`,
+pass the internal type(s) as "type parameters" using square brackets: `[` and `]`
```Python
my_list: list[str]
```
-In versions of Python before 3.9, it would be:
-
-```Python
-from typing import List
-
-my_list: List[str]
-```
-
That's all standard Python syntax for type declarations.
Use that same standard syntax for model attributes with internal types.
So, in our example, we can make `tags` be specifically a "list of strings":
-=== "Python 3.10+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}
-=== "Python 3.6+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002.py!}
- ```
-
-## Set types
+## Set types { #set-types }
But then we think about it, and realize that tags shouldn't repeat, they would probably be unique strings.
@@ -87,23 +39,7 @@ And Python has a special data type for sets of unique items, the `set`.
Then we can declare `tags` as a set of strings:
-=== "Python 3.10+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="1 14"
- {!> ../../../docs_src/body_nested_models/tutorial003.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}
With this, even if you receive a request with duplicate data, it will be converted to a set of unique items.
@@ -111,7 +47,7 @@ And whenever you output that data, even if the source had duplicates, it will be
And it will be annotated / documented accordingly too.
-## Nested Models
+## Nested Models { #nested-models }
Each attribute of a Pydantic model has a type.
@@ -121,49 +57,17 @@ So, you can declare deeply nested JSON "objects" with specific attribute names,
All that, arbitrarily nested.
-### Define a submodel
+### Define a submodel { #define-a-submodel }
For example, we can define an `Image` model:
-=== "Python 3.10+"
-
- ```Python hl_lines="7-9"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}
-=== "Python 3.6+"
-
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
-
-### Use the submodel as a type
+### Use the submodel as a type { #use-the-submodel-as-a-type }
And then we can use it as the type of an attribute:
-=== "Python 3.10+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}
This would mean that **FastAPI** would expect a body similar to:
@@ -183,62 +87,30 @@ This would mean that **FastAPI** would expect a body similar to:
Again, doing just that declaration, with **FastAPI** you get:
-* Editor support (completion, etc), even for nested models
+* Editor support (completion, etc.), even for nested models
* Data conversion
* Data validation
* Automatic documentation
-## Special types and validation
+## Special types and validation { #special-types-and-validation }
-Apart from normal singular types like `str`, `int`, `float`, etc. You can use more complex singular types that inherit from `str`.
+Apart from normal singular types like `str`, `int`, `float`, etc. you can use more complex singular types that inherit from `str`.
-To see all the options you have, checkout the docs for Pydantic's exotic types. You will see some examples in the next chapter.
+To see all the options you have, checkout [Pydantic's Type Overview](https://docs.pydantic.dev/latest/concepts/types/). You will see some examples in the next chapter.
-For example, as in the `Image` model we have a `url` field, we can declare it to be instead of a `str`, a Pydantic's `HttpUrl`:
+For example, as in the `Image` model we have a `url` field, we can declare it to be an instance of Pydantic's `HttpUrl` instead of a `str`:
-=== "Python 3.10+"
-
- ```Python hl_lines="2 8"
- {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}
The string will be checked to be a valid URL, and documented in JSON Schema / OpenAPI as such.
-## Attributes with lists of submodels
-
-You can also use Pydantic models as subtypes of `list`, `set`, etc:
-
-=== "Python 3.10+"
+## Attributes with lists of submodels { #attributes-with-lists-of-submodels }
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
- ```
+You can also use Pydantic models as subtypes of `list`, `set`, etc.:
-=== "Python 3.9+"
+{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006.py!}
- ```
-
-This will expect (convert, validate, document, etc) a JSON body like:
+This will expect (convert, validate, document, etc.) a JSON body like:
```JSON hl_lines="11"
{
@@ -264,63 +136,37 @@ This will expect (convert, validate, document, etc) a JSON body like:
}
```
-!!! info
- Notice how the `images` key now has a list of image objects.
+/// info
-## Deeply nested models
+Notice how the `images` key now has a list of image objects.
-You can define arbitrarily deeply nested models:
+///
-=== "Python 3.10+"
+## Deeply nested models { #deeply-nested-models }
- ```Python hl_lines="7 12 18 21 25"
- {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
- ```
-
-=== "Python 3.9+"
+You can define arbitrarily deeply nested models:
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}
-=== "Python 3.6+"
+/// info
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007.py!}
- ```
+Notice how `Offer` has a list of `Item`s, which in turn have an optional list of `Image`s
-!!! info
- Notice how `Offer` has a list of `Item`s, which in turn have an optional list of `Image`s
+///
-## Bodies of pure lists
+## Bodies of pure lists { #bodies-of-pure-lists }
If the top level value of the JSON body you expect is a JSON `array` (a Python `list`), you can declare the type in the parameter of the function, the same as in Pydantic models:
-```Python
-images: List[Image]
-```
-
-or in Python 3.9 and above:
-
```Python
images: list[Image]
```
as in:
-=== "Python 3.9+"
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
-=== "Python 3.6+"
-
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_nested_models/tutorial008.py!}
- ```
-
-## Editor support everywhere
+## Editor support everywhere { #editor-support-everywhere }
And you get editor support everywhere.
@@ -332,44 +178,37 @@ You couldn't get this kind of editor support if you were working directly with `
But you don't have to worry about them either, incoming dicts are converted automatically and your output is converted automatically to JSON too.
-## Bodies of arbitrary `dict`s
+## Bodies of arbitrary `dict`s { #bodies-of-arbitrary-dicts }
-You can also declare a body as a `dict` with keys of some type and values of other type.
+You can also declare a body as a `dict` with keys of some type and values of some other type.
-Without having to know beforehand what are the valid field/attribute names (as would be the case with Pydantic models).
+This way, you don't have to know beforehand what the valid field/attribute names are (as would be the case with Pydantic models).
This would be useful if you want to receive keys that you don't already know.
---
-Other useful case is when you want to have keys of other type, e.g. `int`.
+Another useful case is when you want to have keys of another type (e.g., `int`).
That's what we are going to see here.
In this case, you would accept any `dict` as long as it has `int` keys with `float` values:
-=== "Python 3.9+"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
-=== "Python 3.6+"
+/// tip
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
- ```
+Keep in mind that JSON only supports `str` as keys.
-!!! tip
- Have in mind that JSON only supports `str` as keys.
+But Pydantic has automatic data conversion.
- But Pydantic has automatic data conversion.
+This means that, even though your API clients can only send strings as keys, as long as those strings contain pure integers, Pydantic will convert them and validate them.
- This means that, even though your API clients can only send strings as keys, as long as those strings contain pure integers, Pydantic will convert them and validate them.
+And the `dict` you receive as `weights` will actually have `int` keys and `float` values.
- And the `dict` you receive as `weights` will actually have `int` keys and `float` values.
+///
-## Recap
+## Recap { #recap }
With **FastAPI** you have the maximum flexibility provided by Pydantic models, while keeping your code simple, short and elegant.
diff --git a/docs/en/docs/tutorial/body-updates.md b/docs/en/docs/tutorial/body-updates.md
index a32948db1a104..e45f96c16fdcf 100644
--- a/docs/en/docs/tutorial/body-updates.md
+++ b/docs/en/docs/tutorial/body-updates.md
@@ -1,32 +1,16 @@
-# Body - Updates
+# Body - Updates { #body-updates }
-## Update replacing with `PUT`
+## Update replacing with `PUT` { #update-replacing-with-put }
-To update an item you can use the HTTP `PUT` operation.
+To update an item you can use the [HTTP `PUT`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) operation.
You can use the `jsonable_encoder` to convert the input data to data that can be stored as JSON (e.g. with a NoSQL database). For example, converting `datetime` to `str`.
-=== "Python 3.10+"
-
- ```Python hl_lines="28-33"
- {!> ../../../docs_src/body_updates/tutorial001_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="30-35"
- {!> ../../../docs_src/body_updates/tutorial001.py!}
- ```
+{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}
`PUT` is used to receive data that should replace the existing data.
-### Warning about replacing
+### Warning about replacing { #warning-about-replacing }
That means that if you want to update the item `bar` using `PUT` with a body containing:
@@ -42,74 +26,45 @@ because it doesn't include the already stored attribute `"tax": 20.2`, the input
And the data would be saved with that "new" `tax` of `10.5`.
-## Partial updates with `PATCH`
+## Partial updates with `PATCH` { #partial-updates-with-patch }
-You can also use the HTTP `PATCH` operation to *partially* update data.
+You can also use the [HTTP `PATCH`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) operation to *partially* update data.
This means that you can send only the data that you want to update, leaving the rest intact.
-!!! Note
- `PATCH` is less commonly used and known than `PUT`.
-
- And many teams use only `PUT`, even for partial updates.
-
- You are **free** to use them however you want, **FastAPI** doesn't impose any restrictions.
-
- But this guide shows you, more or less, how they are intended to be used.
-
-### Using Pydantic's `exclude_unset` parameter
+/// note
-If you want to receive partial updates, it's very useful to use the parameter `exclude_unset` in Pydantic's model's `.dict()`.
+`PATCH` is less commonly used and known than `PUT`.
-Like `item.dict(exclude_unset=True)`.
+And many teams use only `PUT`, even for partial updates.
-That would generate a `dict` with only the data that was set when creating the `item` model, excluding default values.
-
-Then you can use this to generate a `dict` with only the data that was set (sent in the request), omitting default values:
-
-=== "Python 3.10+"
-
- ```Python hl_lines="32"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+You are **free** to use them however you want, **FastAPI** doesn't impose any restrictions.
-=== "Python 3.9+"
+But this guide shows you, more or less, how they are intended to be used.
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+///
-=== "Python 3.6+"
+### Using Pydantic's `exclude_unset` parameter { #using-pydantics-exclude-unset-parameter }
- ```Python hl_lines="34"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+If you want to receive partial updates, it's very useful to use the parameter `exclude_unset` in Pydantic's model's `.model_dump()`.
-### Using Pydantic's `update` parameter
+Like `item.model_dump(exclude_unset=True)`.
-Now, you can create a copy of the existing model using `.copy()`, and pass the `update` parameter with a `dict` containing the data to update.
-
-Like `stored_item_model.copy(update=update_data)`:
+That would generate a `dict` with only the data that was set when creating the `item` model, excluding default values.
-=== "Python 3.10+"
+Then you can use this to generate a `dict` with only the data that was set (sent in the request), omitting default values:
- ```Python hl_lines="33"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}
-=== "Python 3.9+"
+### Using Pydantic's `update` parameter { #using-pydantics-update-parameter }
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+Now, you can create a copy of the existing model using `.model_copy()`, and pass the `update` parameter with a `dict` containing the data to update.
-=== "Python 3.6+"
+Like `stored_item_model.model_copy(update=update_data)`:
- ```Python hl_lines="35"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}
-### Partial updates recap
+### Partial updates recap { #partial-updates-recap }
In summary, to apply partial updates you would:
@@ -118,38 +73,28 @@ In summary, to apply partial updates you would:
* Put that data in a Pydantic model.
* Generate a `dict` without default values from the input model (using `exclude_unset`).
* This way you can update only the values actually set by the user, instead of overriding values already stored with default values in your model.
-* Create a copy of the stored model, updating it's attributes with the received partial updates (using the `update` parameter).
+* Create a copy of the stored model, updating its attributes with the received partial updates (using the `update` parameter).
* Convert the copied model to something that can be stored in your DB (for example, using the `jsonable_encoder`).
- * This is comparable to using the model's `.dict()` method again, but it makes sure (and converts) the values to data types that can be converted to JSON, for example, `datetime` to `str`.
+ * This is comparable to using the model's `.model_dump()` method again, but it makes sure (and converts) the values to data types that can be converted to JSON, for example, `datetime` to `str`.
* Save the data to your DB.
* Return the updated model.
-=== "Python 3.10+"
-
- ```Python hl_lines="28-35"
- {!> ../../../docs_src/body_updates/tutorial002_py310.py!}
- ```
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *}
-=== "Python 3.9+"
+/// tip
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002_py39.py!}
- ```
+You can actually use this same technique with an HTTP `PUT` operation.
-=== "Python 3.6+"
+But the example here uses `PATCH` because it was created for these use cases.
- ```Python hl_lines="30-37"
- {!> ../../../docs_src/body_updates/tutorial002.py!}
- ```
+///
-!!! tip
- You can actually use this same technique with an HTTP `PUT` operation.
+/// note
- But the example here uses `PATCH` because it was created for these use cases.
+Notice that the input model is still validated.
-!!! note
- Notice that the input model is still validated.
+So, if you want to receive partial updates that can omit all the attributes, you need to have a model with all the attributes marked as optional (with default values or `None`).
- So, if you want to receive partial updates that can omit all the attributes, you need to have a model with all the attributes marked as optional (with default values or `None`).
+To distinguish from the models with all optional values for **updates** and models with required values for **creation**, you can use the ideas described in [Extra Models](extra-models.md).
- To distinguish from the models with all optional values for **updates** and models with required values for **creation**, you can use the ideas described in [Extra Models](extra-models.md){.internal-link target=_blank}.
+///
diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md
index 172b91fdfa61e..ca72548a4d05c 100644
--- a/docs/en/docs/tutorial/body.md
+++ b/docs/en/docs/tutorial/body.md
@@ -1,53 +1,37 @@
-# Request Body
+# Request Body { #request-body }
When you need to send data from a client (let's say, a browser) to your API, you send it as a **request body**.
A **request** body is data sent by the client to your API. A **response** body is the data your API sends to the client.
-Your API almost always has to send a **response** body. But clients don't necessarily need to send **request** bodies all the time.
+Your API almost always has to send a **response** body. But clients don't necessarily need to send **request bodies** all the time, sometimes they only request a path, maybe with some query parameters, but don't send a body.
-To declare a **request** body, you use Pydantic models with all their power and benefits.
+To declare a **request** body, you use [Pydantic](https://docs.pydantic.dev/) models with all their power and benefits.
-!!! info
- To send data, you should use one of: `POST` (the more common), `PUT`, `DELETE` or `PATCH`.
+/// info
- Sending a body with a `GET` request has an undefined behavior in the specifications, nevertheless, it is supported by FastAPI, only for very complex/extreme use cases.
+To send data, you should use one of: `POST` (the more common), `PUT`, `DELETE` or `PATCH`.
- As it is discouraged, the interactive docs with Swagger UI won't show the documentation for the body when using `GET`, and proxies in the middle might not support it.
+Sending a body with a `GET` request has an undefined behavior in the specifications, nevertheless, it is supported by FastAPI, only for very complex/extreme use cases.
-## Import Pydantic's `BaseModel`
+As it is discouraged, the interactive docs with Swagger UI won't show the documentation for the body when using `GET`, and proxies in the middle might not support it.
-First, you need to import `BaseModel` from `pydantic`:
-
-=== "Python 3.10+"
+///
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+## Import Pydantic's `BaseModel` { #import-pydantics-basemodel }
-=== "Python 3.6+"
+First, you need to import `BaseModel` from `pydantic`:
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+{* ../../docs_src/body/tutorial001_py310.py hl[2] *}
-## Create your data model
+## Create your data model { #create-your-data-model }
Then you declare your data model as a class that inherits from `BaseModel`.
Use standard Python types for all the attributes:
-=== "Python 3.10+"
-
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+"
+{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
The same as when declaring query parameters, when a model attribute has a default value, it is not required. Otherwise, it is required. Use `None` to make it just optional.
@@ -71,25 +55,15 @@ For example, this model above declares a JSON "`object`" (or Python `dict`) like
}
```
-## Declare it as a parameter
+## Declare it as a parameter { #declare-it-as-a-parameter }
To add it to your *path operation*, declare it the same way you declared path and query parameters:
-=== "Python 3.10+"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+{* ../../docs_src/body/tutorial001_py310.py hl[16] *}
...and declare its type as the model you created, `Item`.
-## Results
+## Results { #results }
With just that Python type declaration, **FastAPI** will:
@@ -99,20 +73,20 @@ With just that Python type declaration, **FastAPI** will:
* If the data is invalid, it will return a nice and clear error, indicating exactly where and what was the incorrect data.
* Give you the received data in the parameter `item`.
* As you declared it in the function to be of type `Item`, you will also have all the editor support (completion, etc) for all of the attributes and their types.
-* Generate JSON Schema definitions for your model, you can also use them anywhere else you like if it makes sense for your project.
+* Generate [JSON Schema](https://json-schema.org) definitions for your model, you can also use them anywhere else you like if it makes sense for your project.
* Those schemas will be part of the generated OpenAPI schema, and used by the automatic documentation UIs.
-## Automatic docs
+## Automatic docs { #automatic-docs }
The JSON Schemas of your models will be part of your OpenAPI generated schema, and will be shown in the interactive API docs:
-And will be also used in the API docs inside each *path operation* that needs them:
+And will also be used in the API docs inside each *path operation* that needs them:
-## Editor support
+## Editor support { #editor-support }
In your editor, inside your function you will get type hints and completion everywhere (this wouldn't happen if you received a `dict` instead of a Pydantic model):
@@ -128,74 +102,48 @@ And it was thoroughly tested at the design phase, before any implementation, to
There were even some changes to Pydantic itself to support this.
-The previous screenshots were taken with Visual Studio Code.
+The previous screenshots were taken with [Visual Studio Code](https://code.visualstudio.com).
-But you would get the same editor support with PyCharm and most of the other Python editors:
+But you would get the same editor support with [PyCharm](https://www.jetbrains.com/pycharm/) and most of the other Python editors:
-!!! tip
- If you use PyCharm as your editor, you can use the Pydantic PyCharm Plugin.
+/// tip
- It improves editor support for Pydantic models, with:
+If you use [PyCharm](https://www.jetbrains.com/pycharm/) as your editor, you can use the [Pydantic PyCharm Plugin](https://github.com/koxudaxi/pydantic-pycharm-plugin/).
- * auto-completion
- * type checks
- * refactoring
- * searching
- * inspections
+It improves editor support for Pydantic models, with:
-## Use the model
-
-Inside of the function, you can access all the attributes of the model object directly:
+* auto-completion
+* type checks
+* refactoring
+* searching
+* inspections
-=== "Python 3.10+"
+///
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+## Use the model { #use-the-model }
-=== "Python 3.6+"
+Inside of the function, you can access all the attributes of the model object directly:
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+{* ../../docs_src/body/tutorial002_py310.py *}
-## Request body + path parameters
+## Request body + path parameters { #request-body-path-parameters }
You can declare path parameters and request body at the same time.
**FastAPI** will recognize that the function parameters that match path parameters should be **taken from the path**, and that function parameters that are declared to be Pydantic models should be **taken from the request body**.
-=== "Python 3.10+"
-
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
-
-=== "Python 3.6+"
+{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
-## Request body + path + query parameters
+## Request body + path + query parameters { #request-body-path-query-parameters }
You can also declare **body**, **path** and **query** parameters, all at the same time.
**FastAPI** will recognize each of them and take the data from the correct place.
-=== "Python 3.10+"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
+{* ../../docs_src/body/tutorial004_py310.py hl[16] *}
The function parameters will be recognized as follows:
@@ -203,11 +151,16 @@ The function parameters will be recognized as follows:
* If the parameter is of a **singular type** (like `int`, `float`, `str`, `bool`, etc) it will be interpreted as a **query** parameter.
* If the parameter is declared to be of the type of a **Pydantic model**, it will be interpreted as a request **body**.
-!!! note
- FastAPI will know that the value of `q` is not required because of the default value `= None`.
+/// note
+
+FastAPI will know that the value of `q` is not required because of the default value `= None`.
+
+The `str | None` is not used by FastAPI to determine that the value is not required, it will know it's not required because it has a default value of `= None`.
+
+But adding the type annotations will allow your editor to give you better support and detect errors.
- The `Union` in `Union[str, None]` is not used by FastAPI, but will allow your editor to give you better support and detect errors.
+///
-## Without Pydantic
+## Without Pydantic { #without-pydantic }
-If you don't want to use Pydantic models, you can also use **Body** parameters. See the docs for [Body - Multiple Parameters: Singular values in body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}.
+If you don't want to use Pydantic models, you can also use **Body** parameters. See the docs for [Body - Multiple Parameters: Singular values in body](body-multiple-params.md#singular-values-in-body).
diff --git a/docs/en/docs/tutorial/cookie-param-models.md b/docs/en/docs/tutorial/cookie-param-models.md
new file mode 100644
index 0000000000000..609838f766d11
--- /dev/null
+++ b/docs/en/docs/tutorial/cookie-param-models.md
@@ -0,0 +1,76 @@
+# Cookie Parameter Models { #cookie-parameter-models }
+
+If you have a group of **cookies** that are related, you can create a **Pydantic model** to declare them. 🍪
+
+This would allow you to **re-use the model** in **multiple places** and also to declare validations and metadata for all the parameters at once. 😎
+
+/// note
+
+This is supported since FastAPI version `0.115.0`. 🤓
+
+///
+
+/// tip
+
+This same technique applies to `Query`, `Cookie`, and `Header`. 😎
+
+///
+
+## Cookies with a Pydantic Model { #cookies-with-a-pydantic-model }
+
+Declare the **cookie** parameters that you need in a **Pydantic model**, and then declare the parameter as `Cookie`:
+
+{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}
+
+**FastAPI** will **extract** the data for **each field** from the **cookies** received in the request and give you the Pydantic model you defined.
+
+## Check the Docs { #check-the-docs }
+
+You can see the defined cookies in the docs UI at `/docs`:
+
+
+
-## Shortcut
+## Shortcut { #shortcut }
But you see that we are having some code repetition here, writing `CommonQueryParams` twice:
-=== "Python 3.6+ non-Annotated"
+//// tab | Python 3.10+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+/// tip
-=== "Python 3.6+"
+Prefer to use the `Annotated` version if possible.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+////
**FastAPI** provides a shortcut for these cases, in where the dependency is *specifically* a class that **FastAPI** will "call" to create an instance of the class itself.
@@ -401,81 +225,64 @@ For those specific cases, you can do the following:
Instead of writing:
-=== "Python 3.6+"
-
- ```Python
- commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
- ```
+//// tab | Python 3.10+
-=== "Python 3.6+ non-Annotated"
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python
- commons: CommonQueryParams = Depends(CommonQueryParams)
- ```
+//// tab | Python 3.10+ non-Annotated
-...you write:
+/// tip
-=== "Python 3.6+"
+Prefer to use the `Annotated` version if possible.
- ```Python
- commons: Annotated[CommonQueryParams, Depends()]
- ```
+///
-=== "Python 3.6 non-Annotated"
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
- !!! tip
- Prefer to use the `Annotated` version if possible.
+////
- ```Python
- commons: CommonQueryParams = Depends()
- ```
+...you write:
-You declare the dependency as the type of the parameter, and you use `Depends()` without any parameter, instead of having to write the full class *again* inside of `Depends(CommonQueryParams)`.
+//// tab | Python 3.10+
-The same example would then look like:
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
-=== "Python 3.10+"
+////
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!}
- ```
+//// tab | Python 3.10+ non-Annotated
-=== "Python 3.9+"
+/// tip
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!}
- ```
+Prefer to use the `Annotated` version if possible.
-=== "Python 3.6+"
+///
- ```Python hl_lines="20"
- {!> ../../../docs_src/dependencies/tutorial004_an.py!}
- ```
+```Python
+commons: CommonQueryParams = Depends()
+```
-=== "Python 3.10+ non-Annotated"
+////
- !!! tip
- Prefer to use the `Annotated` version if possible.
+You declare the dependency as the type of the parameter, and you use `Depends()` without any parameter, instead of having to write the full class *again* inside of `Depends(CommonQueryParams)`.
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
+The same example would then look like:
-=== "Python 3.6+ non-Annotated"
+{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *}
- !!! tip
- Prefer to use the `Annotated` version if possible.
+...and **FastAPI** will know what to do.
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
- ```
+/// tip
-...and **FastAPI** will know what to do.
+If that seems more confusing than helpful, disregard it, you don't *need* it.
-!!! tip
- If that seems more confusing than helpful, disregard it, you don't *need* it.
+It is just a shortcut. Because **FastAPI** cares about helping you minimize code repetition.
- It is just a shortcut. Because **FastAPI** cares about helping you minimize code repetition.
+///
diff --git a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
index ccef5aef4b27f..e663c40823a1b 100644
--- a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
+++ b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -1,4 +1,4 @@
-# Dependencies in path operation decorators
+# Dependencies in path operation decorators { #dependencies-in-path-operation-decorators }
In some cases you don't really need the return value of a dependency inside your *path operation function*.
@@ -8,132 +8,62 @@ But you still need it to be executed/solved.
For those cases, instead of declaring a *path operation function* parameter with `Depends`, you can add a `list` of `dependencies` to the *path operation decorator*.
-## Add `dependencies` to the *path operation decorator*
+## Add `dependencies` to the *path operation decorator* { #add-dependencies-to-the-path-operation-decorator }
The *path operation decorator* receives an optional argument `dependencies`.
It should be a `list` of `Depends()`:
-=== "Python 3.9+"
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
+These dependencies will be executed/solved the same way as normal dependencies. But their value (if they return any) won't be passed to your *path operation function*.
-=== "Python 3.6 non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Some editors check for unused function parameters, and show them as errors.
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+Using these `dependencies` in the *path operation decorator* you can make sure they are executed while avoiding editor/tooling errors.
-These dependencies will be executed/solved the same way as normal dependencies. But their value (if they return any) won't be passed to your *path operation function*.
+It might also help avoid confusion for new developers that see an unused parameter in your code and could think it's unnecessary.
-!!! tip
- Some editors check for unused function parameters, and show them as errors.
+///
- Using these `dependencies` in the *path operation decorator* you can make sure they are executed while avoiding editor/tooling errors.
+/// info
- It might also help avoid confusion for new developers that see an unused parameter in your code and could think it's unnecessary.
+In this example we use invented custom headers `X-Key` and `X-Token`.
-!!! info
- In this example we use invented custom headers `X-Key` and `X-Token`.
+But in real cases, when implementing security, you would get more benefits from using the integrated [Security utilities (the next chapter)](../security/index.md).
- But in real cases, when implementing security, you would get more benefits from using the integrated [Security utilities (the next chapter)](../security/index.md){.internal-link target=_blank}.
+///
-## Dependencies errors and return values
+## Dependencies errors and return values { #dependencies-errors-and-return-values }
You can use the same dependency *functions* you use normally.
-### Dependency requirements
+### Dependency requirements { #dependency-requirements }
They can declare request requirements (like headers) or other sub-dependencies:
-=== "Python 3.9+"
-
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
-
-=== "Python 3.6+"
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
- ```Python hl_lines="7 12"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
-
-=== "Python 3.6 non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="6 11"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
-
-### Raise exceptions
+### Raise exceptions { #raise-exceptions }
These dependencies can `raise` exceptions, the same as normal dependencies:
-=== "Python 3.9+"
-
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
-=== "Python 3.6+"
-
- ```Python hl_lines="9 14"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
-
-=== "Python 3.6 non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
-
-### Return values
+### Return values { #return-values }
And they can return values or not, the values won't be used.
-So, you can re-use a normal dependency (that returns a value) you already use somewhere else, and even though the value won't be used, the dependency will be executed:
-
-=== "Python 3.9+"
-
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/dependencies/tutorial006_an.py!}
- ```
-
-=== "Python 3.6 non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
+So, you can reuse a normal dependency (that returns a value) you already use somewhere else, and even though the value won't be used, the dependency will be executed:
- ```Python hl_lines="9 14"
- {!> ../../../docs_src/dependencies/tutorial006.py!}
- ```
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
-## Dependencies for a group of *path operations*
+## Dependencies for a group of *path operations* { #dependencies-for-a-group-of-path-operations }
-Later, when reading about how to structure bigger applications ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), possibly with multiple files, you will learn how to declare a single `dependencies` parameter for a group of *path operations*.
+Later, when reading about how to structure bigger applications ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md)), possibly with multiple files, you will learn how to declare a single `dependencies` parameter for a group of *path operations*.
-## Global Dependencies
+## Global Dependencies { #global-dependencies }
Next we will see how to add dependencies to the whole `FastAPI` application, so that they apply to each *path operation*.
diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
index 8a5422ac862e4..7b80a74e4466a 100644
--- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
+++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -1,64 +1,65 @@
-# Dependencies with yield
+# Dependencies with yield { #dependencies-with-yield }
-FastAPI supports dependencies that do some extra steps after finishing.
+FastAPI supports dependencies that do some extra steps after finishing.
-To do this, use `yield` instead of `return`, and write the extra steps after.
+To do this, use `yield` instead of `return`, and write the extra steps (code) after.
-!!! tip
- Make sure to use `yield` one single time.
+/// tip
-!!! note "Technical Details"
- Any function that is valid to use with:
+Make sure to use `yield` one single time per dependency.
- * `@contextlib.contextmanager` or
- * `@contextlib.asynccontextmanager`
+///
- would be valid to use as a **FastAPI** dependency.
+/// note | Technical Details
- In fact, FastAPI uses those two decorators internally.
+Any function that is valid to use with:
-## A database dependency with `yield`
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) or
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+would be valid to use as a **FastAPI** dependency.
+
+In fact, FastAPI uses those two decorators internally.
+
+///
+
+## A database dependency with `yield` { #a-database-dependency-with-yield }
For example, you could use this to create a database session and close it after finishing.
-Only the code prior to and including the `yield` statement is executed before sending a response:
+Only the code prior to and including the `yield` statement is executed before creating a response:
-```Python hl_lines="2-4"
-{!../../../docs_src/dependencies/tutorial007.py!}
-```
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
The yielded value is what is injected into *path operations* and other dependencies:
-```Python hl_lines="4"
-{!../../../docs_src/dependencies/tutorial007.py!}
-```
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
-The code following the `yield` statement is executed after the response has been delivered:
+The code following the `yield` statement is executed after the response:
-```Python hl_lines="5-6"
-{!../../../docs_src/dependencies/tutorial007.py!}
-```
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
-!!! tip
- You can use `async` or normal functions.
+/// tip
- **FastAPI** will do the right thing with each, the same as with normal dependencies.
+You can use `async` or regular functions.
-## A dependency with `yield` and `try`
+**FastAPI** will do the right thing with each, the same as with normal dependencies.
+
+///
+
+## A dependency with `yield` and `try` { #a-dependency-with-yield-and-try }
If you use a `try` block in a dependency with `yield`, you'll receive any exception that was thrown when using the dependency.
-For example, if some code at some point in the middle, in another dependency or in a *path operation*, made a database transaction "rollback" or create any other error, you will receive the exception in your dependency.
+For example, if some code at some point in the middle, in another dependency or in a *path operation*, made a database transaction "rollback" or created any other exception, you would receive the exception in your dependency.
So, you can look for that specific exception inside the dependency with `except SomeException`.
In the same way, you can use `finally` to make sure the exit steps are executed, no matter if there was an exception or not.
-```Python hl_lines="3 5"
-{!../../../docs_src/dependencies/tutorial007.py!}
-```
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
-## Sub-dependencies with `yield`
+## Sub-dependencies with `yield` { #sub-dependencies-with-yield }
You can have sub-dependencies and "trees" of sub-dependencies of any size and shape, and any or all of them can use `yield`.
@@ -66,89 +67,71 @@ You can have sub-dependencies and "trees" of sub-dependencies of any size and sh
For example, `dependency_c` can have a dependency on `dependency_b`, and `dependency_b` on `dependency_a`:
-=== "Python 3.9+"
-
- ```Python hl_lines="6 14 22"
- {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
- ```
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
-=== "Python 3.6+"
+And all of them can use `yield`.
- ```Python hl_lines="5 13 21"
- {!> ../../../docs_src/dependencies/tutorial008_an.py!}
- ```
+In this case `dependency_c`, to execute its exit code, needs the value from `dependency_b` (here named `dep_b`) to still be available.
-=== "Python 3.6+ non-Annotated"
+And, in turn, `dependency_b` needs the value from `dependency_a` (here named `dep_a`) to be available for its exit code.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
- ```Python hl_lines="4 12 20"
- {!> ../../../docs_src/dependencies/tutorial008.py!}
- ```
+The same way, you could have some dependencies with `yield` and some other dependencies with `return`, and have some of those depend on some of the others.
-And all of them can use `yield`.
+And you could have a single dependency that requires several other dependencies with `yield`, etc.
-In this case `dependency_c`, to execute its exit code, needs the value from `dependency_b` (here named `dep_b`) to still be available.
+You can have any combinations of dependencies that you want.
-And, in turn, `dependency_b` needs the value from `dependency_a` (here named `dep_a`) to be available for its exit code.
+**FastAPI** will make sure everything is run in the correct order.
-=== "Python 3.9+"
+/// note | Technical Details
- ```Python hl_lines="18-19 26-27"
- {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!}
- ```
+This works thanks to Python's [Context Managers](https://docs.python.org/3/library/contextlib.html).
-=== "Python 3.6+"
+**FastAPI** uses them internally to achieve this.
- ```Python hl_lines="17-18 25-26"
- {!> ../../../docs_src/dependencies/tutorial008_an.py!}
- ```
+///
-=== "Python 3.6+ non-Annotated"
+## Dependencies with `yield` and `HTTPException` { #dependencies-with-yield-and-httpexception }
- !!! tip
- Prefer to use the `Annotated` version if possible.
+You saw that you can use dependencies with `yield` and have `try` blocks that try to execute some code and then run some exit code after `finally`.
- ```Python hl_lines="16-17 24-25"
- {!> ../../../docs_src/dependencies/tutorial008.py!}
- ```
+You can also use `except` to catch the exception that was raised and do something with it.
-The same way, you could have dependencies with `yield` and `return` mixed.
+For example, you can raise a different exception, like `HTTPException`.
-And you could have a single dependency that requires several other dependencies with `yield`, etc.
+/// tip
-You can have any combinations of dependencies that you want.
+This is a somewhat advanced technique, and in most of the cases you won't really need it, as you can raise exceptions (including `HTTPException`) from inside of the rest of your application code, for example, in the *path operation function*.
-**FastAPI** will make sure everything is run in the correct order.
+But it's there for you if you need it. 🤓
-!!! note "Technical Details"
- This works thanks to Python's Context Managers.
+///
- **FastAPI** uses them internally to achieve this.
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
-## Dependencies with `yield` and `HTTPException`
+If you want to catch exceptions and create a custom response based on that, create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers).
-You saw that you can use dependencies with `yield` and have `try` blocks that catch exceptions.
+## Dependencies with `yield` and `except` { #dependencies-with-yield-and-except }
-It might be tempting to raise an `HTTPException` or similar in the exit code, after the `yield`. But **it won't work**.
+If you catch an exception using `except` in a dependency with `yield` and you don't raise it again (or raise a new exception), FastAPI won't be able to notice there was an exception, the same way that would happen with regular Python:
-The exit code in dependencies with `yield` is executed *after* the response is sent, so [Exception Handlers](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} will have already run. There's nothing catching exceptions thrown by your dependencies in the exit code (after the `yield`).
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
-So, if you raise an `HTTPException` after the `yield`, the default (or any custom) exception handler that catches `HTTPException`s and returns an HTTP 400 response won't be there to catch that exception anymore.
+In this case, the client will see an *HTTP 500 Internal Server Error* response as it should, given that we are not raising an `HTTPException` or similar, but the server will **not have any logs** or any other indication of what was the error. 😱
-This is what allows anything set in the dependency (e.g. a DB session) to, for example, be used by background tasks.
+### Always `raise` in Dependencies with `yield` and `except` { #always-raise-in-dependencies-with-yield-and-except }
-Background tasks are run *after* the response has been sent. So there's no way to raise an `HTTPException` because there's not even a way to change the response that is *already sent*.
+If you catch an exception in a dependency with `yield`, unless you are raising another `HTTPException` or similar, **you should re-raise the original exception**.
-But if a background task creates a DB error, at least you can rollback or cleanly close the session in the dependency with `yield`, and maybe log the error or report it to a remote tracking system.
+You can re-raise the same exception using `raise`:
-If you have some code that you know could raise an exception, do the most normal/"Pythonic" thing and add a `try` block in that section of the code.
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
-If you have custom exceptions that you would like to handle *before* returning the response and possibly modifying the response, maybe even raising an `HTTPException`, create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.
+Now the client will get the same *HTTP 500 Internal Server Error* response, but the server will have our custom `InternalError` in the logs. 😎
-!!! tip
- You can still raise exceptions including `HTTPException` *before* the `yield`. But not after.
+## Execution of dependencies with `yield` { #execution-of-dependencies-with-yield }
The sequence of execution is more or less like this diagram. Time flows from top to bottom. And each column is one of the parts interacting or executing code.
@@ -161,54 +144,103 @@ 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
+ Note over client,operation: Can raise exceptions, including HTTPException
client ->> dep: Start request
Note over dep: Run code up to yield
- opt raise
- dep -->> handler: Raise HTTPException
+ opt raise Exception
+ dep -->> handler: Raise Exception
handler -->> client: HTTP error response
- dep -->> dep: Raise other exception
end
dep ->> operation: Run dependency, e.g. DB session
opt raise
- operation -->> dep: Raise HTTPException
- dep -->> handler: Auto forward exception
+ operation -->> dep: Raise Exception (e.g. HTTPException)
+ opt handle
+ dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception
+ end
handler -->> client: HTTP error response
- operation -->> dep: Raise other exception
- dep -->> handler: Auto forward 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.
+ tasks -->> tasks: Handle exceptions in the background task code
end
```
-!!! info
- Only **one response** will be sent to the client. It might be one of the error responses or it will be the response from the *path operation*.
+/// info
+
+Only **one response** will be sent to the client. It might be one of the error responses or it will be the response from the *path operation*.
+
+After one of those responses is sent, no other response can be sent.
- After one of those responses is sent, no other response can be sent.
+///
-!!! tip
- This diagram shows `HTTPException`, but you could also raise any other exception for which you create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.
+/// tip
- If you raise any exception, it will be passed to the dependencies with yield, including `HTTPException`, and then **again** to the exception handlers. If there's no exception handler for that exception, it will then be handled by the default internal `ServerErrorMiddleware`, returning a 500 HTTP status code, to let the client know that there was an error in the server.
+If you raise any exception in the code from the *path operation function*, it will be passed to the dependencies with yield, including `HTTPException`. In most cases you will want to re-raise that same exception or a new one from the dependency with `yield` to make sure it's properly handled.
-## Context Managers
+///
-### What are "Context Managers"
+## Early exit and `scope` { #early-exit-and-scope }
+
+Normally the exit code of dependencies with `yield` is executed **after the response** is sent to the client.
+
+But if you know that you won't need to use the dependency after returning from the *path operation function*, you can use `Depends(scope="function")` to tell FastAPI that it should close the dependency after the *path operation function* returns, but **before** the **response is sent**.
+
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
+
+`Depends()` receives a `scope` parameter that can be:
+
+* `"function"`: start the dependency before the *path operation function* that handles the request, end the dependency after the *path operation function* ends, but **before** the response is sent back to the client. So, the dependency function will be executed **around** the *path operation **function***.
+* `"request"`: start the dependency before the *path operation function* that handles the request (similar to when using `"function"`), but end **after** the response is sent back to the client. So, the dependency function will be executed **around** the **request** and response cycle.
+
+If not specified and the dependency has `yield`, it will have a `scope` of `"request"` by default.
+
+### `scope` for sub-dependencies { #scope-for-sub-dependencies }
+
+When you declare a dependency with a `scope="request"` (the default), any sub-dependency needs to also have a `scope` of `"request"`.
+
+But a dependency with `scope` of `"function"` can have dependencies with `scope` of `"function"` and `scope` of `"request"`.
+
+This is because any dependency needs to be able to run its exit code before the sub-dependencies, as it might need to still use them during its exit code.
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant dep_req as Dep scope="request"
+participant dep_func as Dep scope="function"
+participant operation as Path Operation
+
+ client ->> dep_req: Start request
+ Note over dep_req: Run code up to yield
+ dep_req ->> dep_func: Pass dependency
+ Note over dep_func: Run code up to yield
+ dep_func ->> operation: Run path operation with dependency
+ operation ->> dep_func: Return from path operation
+ Note over dep_func: Run code after yield
+ Note over dep_func: ✅ Dependency closed
+ dep_func ->> client: Send response to client
+ Note over client: Response sent
+ Note over dep_req: Run code after yield
+ Note over dep_req: ✅ Dependency closed
+```
+
+## Dependencies with `yield`, `HTTPException`, `except` and Background Tasks { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+Dependencies with `yield` have evolved over time to cover different use cases and fix some issues.
+
+If you want to see what has changed in different versions of FastAPI, you can read more about it in the advanced guide, in [Advanced Dependencies - Dependencies with `yield`, `HTTPException`, `except` and Background Tasks](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks).
+## Context Managers { #context-managers }
+
+### What are "Context Managers" { #what-are-context-managers }
"Context Managers" are any of those Python objects that you can use in a `with` statement.
-For example, you can use `with` to read a file:
+For example, [you can use `with` to read a file](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files):
```Python
with open("./somefile.txt") as f:
@@ -216,38 +248,42 @@ with open("./somefile.txt") as f:
print(contents)
```
-Underneath, the `open("./somefile.txt")` creates an object that is a called a "Context Manager".
+Underneath, the `open("./somefile.txt")` creates an object that is called a "Context Manager".
When the `with` block finishes, it makes sure to close the file, even if there were exceptions.
-When you create a dependency with `yield`, **FastAPI** will internally convert it to a context manager, and combine it with some other related tools.
+When you create a dependency with `yield`, **FastAPI** will internally create a context manager for it, and combine it with some other related tools.
+
+### Using context managers in dependencies with `yield` { #using-context-managers-in-dependencies-with-yield }
+
+/// warning
-### Using context managers in dependencies with `yield`
+This is, more or less, an "advanced" idea.
-!!! warning
- This is, more or less, an "advanced" idea.
+If you are just starting with **FastAPI** you might want to skip it for now.
- If you are just starting with **FastAPI** you might want to skip it for now.
+///
-In Python, you can create Context Managers by creating a class with two methods: `__enter__()` and `__exit__()`.
+In Python, you can create Context Managers by [creating a class with two methods: `__enter__()` and `__exit__()`](https://docs.python.org/3/reference/datamodel.html#context-managers).
You can also use them inside of **FastAPI** dependencies with `yield` by using
`with` or `async with` statements inside of the dependency function:
-```Python hl_lines="1-9 13"
-{!../../../docs_src/dependencies/tutorial010.py!}
-```
+{* ../../docs_src/dependencies/tutorial010_py310.py hl[1:9,13] *}
+
+/// tip
+
+Another way to create a context manager is with:
-!!! tip
- Another way to create a context manager is with:
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) or
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
- * `@contextlib.contextmanager` or
- * `@contextlib.asynccontextmanager`
+using them to decorate a function with a single `yield`.
- using them to decorate a function with a single `yield`.
+That's what **FastAPI** uses internally for dependencies with `yield`.
- That's what **FastAPI** uses internally for dependencies with `yield`.
+But you don't have to use the decorators for FastAPI dependencies (and you shouldn't).
- But you don't have to use the decorators for FastAPI dependencies (and you shouldn't).
+FastAPI will do it for you internally.
- FastAPI will do it for you internally.
+///
diff --git a/docs/en/docs/tutorial/dependencies/global-dependencies.md b/docs/en/docs/tutorial/dependencies/global-dependencies.md
index 0989b31d46205..e02ac14db2e56 100644
--- a/docs/en/docs/tutorial/dependencies/global-dependencies.md
+++ b/docs/en/docs/tutorial/dependencies/global-dependencies.md
@@ -1,34 +1,16 @@
-# Global Dependencies
+# Global Dependencies { #global-dependencies }
For some types of applications you might want to add dependencies to the whole application.
-Similar to the way you can [add `dependencies` to the *path operation decorators*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, you can add them to the `FastAPI` application.
+Similar to the way you can [add `dependencies` to the *path operation decorators*](dependencies-in-path-operation-decorators.md), you can add them to the `FastAPI` application.
In that case, they will be applied to all the *path operations* in the application:
-=== "Python 3.9+"
+{* ../../docs_src/dependencies/tutorial012_an_py310.py hl[17] *}
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!}
- ```
-=== "Python 3.6+"
+And all the ideas in the section about [adding `dependencies` to the *path operation decorators*](dependencies-in-path-operation-decorators.md) still apply, but in this case, to all of the *path operations* in the app.
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial012_an.py!}
- ```
+## Dependencies for groups of *path operations* { #dependencies-for-groups-of-path-operations }
-=== "Python 3.6 non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="15"
- {!> ../../../docs_src/dependencies/tutorial012.py!}
- ```
-
-And all the ideas in the section about [adding `dependencies` to the *path operation decorators*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} still apply, but in this case, to all of the *path operations* in the app.
-
-## Dependencies for groups of *path operations*
-
-Later, when reading about how to structure bigger applications ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), possibly with multiple files, you will learn how to declare a single `dependencies` parameter for a group of *path operations*.
+Later, when reading about how to structure bigger applications ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md)), possibly with multiple files, you will learn how to declare a single `dependencies` parameter for a group of *path operations*.
diff --git a/docs/en/docs/tutorial/dependencies/index.md b/docs/en/docs/tutorial/dependencies/index.md
index f6f4bced08a76..396c23acbbd9f 100644
--- a/docs/en/docs/tutorial/dependencies/index.md
+++ b/docs/en/docs/tutorial/dependencies/index.md
@@ -1,10 +1,10 @@
-# Dependencies
+# Dependencies { #dependencies }
-**FastAPI** has a very powerful but intuitive **Dependency Injection** system.
+**FastAPI** has a very powerful but intuitive **Dependency Injection** system.
It is designed to be very simple to use, and to make it very easy for any developer to integrate other components with **FastAPI**.
-## What is "Dependency Injection"
+## What is "Dependency Injection" { #what-is-dependency-injection }
**"Dependency Injection"** means, in programming, that there is a way for your code (in this case, your *path operation functions*) to declare things that it requires to work and use: "dependencies".
@@ -19,53 +19,19 @@ This is very useful when you need to:
All these, while minimizing code repetition.
-## First Steps
+## First Steps { #first-steps }
Let's see a very simple example. It will be so simple that it is not very useful, for now.
But this way we can focus on how the **Dependency Injection** system works.
-### Create a dependency, or "dependable"
+### Create a dependency, or "dependable" { #create-a-dependency-or-dependable }
Let's first focus on the dependency.
It is just a function that can take all the same parameters that a *path operation function* can take:
-=== "Python 3.10+"
-
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="8-11"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}
That's it.
@@ -85,90 +51,25 @@ In this case, this dependency expects:
And then it just returns a `dict` containing those values.
-!!! info
- FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.
-
- If you have an older version, you would get errors when trying to use `Annotated`.
-
- Make sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`.
-
-### Import `Depends`
-
-=== "Python 3.10+"
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
+/// info
-=== "Python 3.10+ non-Annotated"
+FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+If you have an older version, you would get errors when trying to use `Annotated`.
- ```Python hl_lines="1"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+Make sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgrading-the-fastapi-versions) to at least 0.95.1 before using `Annotated`.
-=== "Python 3.6+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+### Import `Depends` { #import-depends }
- ```Python hl_lines="3"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}
-### Declare the dependency, in the "dependant"
+### Declare the dependency, in the "dependant" { #declare-the-dependency-in-the-dependant }
The same way you use `Body`, `Query`, etc. with your *path operation function* parameters, use `Depends` with a new parameter:
-=== "Python 3.10+"
-
- ```Python hl_lines="13 18"
- {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/dependencies/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="15 20"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}
Although you use `Depends` in the parameters of your function the same way you use `Body`, `Query`, etc, `Depends` works a bit differently.
@@ -180,8 +81,11 @@ You **don't call it** directly (don't add the parenthesis at the end), you just
And that function takes parameters in the same way that *path operation functions* do.
-!!! tip
- You'll see what other "things", apart from functions, can be used as dependencies in the next chapter.
+/// tip
+
+You'll see what other "things", apart from functions, can be used as dependencies in the next chapter.
+
+///
Whenever a new request arrives, **FastAPI** will take care of:
@@ -202,12 +106,15 @@ common_parameters --> read_users
This way you write shared code once and **FastAPI** takes care of calling it for your *path operations*.
-!!! check
- Notice that you don't have to create a special class and pass it somewhere to **FastAPI** to "register" it or anything similar.
+/// check
+
+Notice that you don't have to create a special class and pass it somewhere to **FastAPI** to "register" it or anything similar.
+
+You just pass it to `Depends` and **FastAPI** knows how to do the rest.
- You just pass it to `Depends` and **FastAPI** knows how to do the rest.
+///
-## Share `Annotated` dependencies
+## Share `Annotated` dependencies { #share-annotated-dependencies }
In the examples above, you see that there's a tiny bit of **code duplication**.
@@ -219,34 +126,21 @@ commons: Annotated[dict, Depends(common_parameters)]
But because we are using `Annotated`, we can store that `Annotated` value in a variable and use it in multiple places:
-=== "Python 3.10+"
+{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}
- ```Python hl_lines="12 16 21"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+This is just standard Python, it's called a "type alias", it's actually not specific to **FastAPI**.
- ```Python hl_lines="14 18 23"
- {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!}
- ```
+But because **FastAPI** is based on the Python standards, including `Annotated`, you can use this trick in your code. 😎
-=== "Python 3.6+"
-
- ```Python hl_lines="15 19 24"
- {!> ../../../docs_src/dependencies/tutorial001_02_an.py!}
- ```
-
-!!! tip
- This is just standard Python, it's called a "type alias", it's actually not specific to **FastAPI**.
-
- But because **FastAPI** is based on the Python standards, including `Annotated`, you can use this trick in your code. 😎
+///
The dependencies will keep working as expected, and the **best part** is that the **type information will be preserved**, which means that your editor will be able to keep providing you with **autocompletion**, **inline errors**, etc. The same for other tools like `mypy`.
This will be especially useful when you use it in a **large code base** where you use **the same dependencies** over and over again in **many *path operations***.
-## To `async` or not to `async`
+## To `async` or not to `async` { #to-async-or-not-to-async }
As dependencies will also be called by **FastAPI** (the same as your *path operation functions*), the same rules apply while defining your functions.
@@ -256,10 +150,13 @@ And you can declare dependencies with `async def` inside of normal `def` *path o
It doesn't matter. **FastAPI** will know what to do.
-!!! note
- If you don't know, check the [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} section about `async` and `await` in the docs.
+/// note
+
+If you don't know, check the [Async: *"In a hurry?"*](../../async.md#in-a-hurry) section about `async` and `await` in the docs.
+
+///
-## Integrated with OpenAPI
+## Integrated with OpenAPI { #integrated-with-openapi }
All the request declarations, validations and requirements of your dependencies (and sub-dependencies) will be integrated in the same OpenAPI schema.
@@ -267,7 +164,7 @@ So, the interactive docs will have all the information from these dependencies t
-## Simple usage
+## Simple usage { #simple-usage }
If you look at it, *path operation functions* are declared to be used whenever a *path* and *operation* matches, and then **FastAPI** takes care of calling the function with the correct parameters, extracting the data from the request.
@@ -285,15 +182,15 @@ Other common terms for this same idea of "dependency injection" are:
* injectables
* components
-## **FastAPI** plug-ins
+## **FastAPI** plug-ins { #fastapi-plug-ins }
-Integrations and "plug-in"s can be built using the **Dependency Injection** system. But in fact, there is actually **no need to create "plug-ins"**, as by using dependencies it's possible to declare an infinite number of integrations and interactions that become available to your *path operation functions*.
+Integrations and "plug-ins" can be built using the **Dependency Injection** system. But in fact, there is actually **no need to create "plug-ins"**, as by using dependencies it's possible to declare an infinite number of integrations and interactions that become available to your *path operation functions*.
-And dependencies can be created in a very simple and intuitive way that allow you to just import the Python packages you need, and integrate them with your API functions in a couple of lines of code, *literally*.
+And dependencies can be created in a very simple and intuitive way that allows you to just import the Python packages you need, and integrate them with your API functions in a couple of lines of code, *literally*.
You will see examples of this in the next chapters, about relational and NoSQL databases, security, etc.
-## **FastAPI** compatibility
+## **FastAPI** compatibility { #fastapi-compatibility }
The simplicity of the dependency injection system makes **FastAPI** compatible with:
@@ -306,7 +203,7 @@ The simplicity of the dependency injection system makes **FastAPI** compatible w
* response data injection systems
* etc.
-## Simple and Powerful
+## Simple and Powerful { #simple-and-powerful }
Although the hierarchical dependency injection system is very simple to define and use, it's still very powerful.
@@ -346,7 +243,7 @@ admin_user --> activate_user
paying_user --> pro_items
```
-## Integrated with **OpenAPI**
+## Integrated with **OpenAPI** { #integrated-with-openapi_1 }
All these dependencies, while declaring their requirements, also add parameters, validations, etc. to your *path operations*.
diff --git a/docs/en/docs/tutorial/dependencies/sub-dependencies.md b/docs/en/docs/tutorial/dependencies/sub-dependencies.md
index b50de1a46cce3..99588dd3c536a 100644
--- a/docs/en/docs/tutorial/dependencies/sub-dependencies.md
+++ b/docs/en/docs/tutorial/dependencies/sub-dependencies.md
@@ -1,4 +1,4 @@
-# Sub-dependencies
+# Sub-dependencies { #sub-dependencies }
You can create dependencies that have **sub-dependencies**.
@@ -6,89 +6,21 @@ They can be as **deep** as you need them to be.
**FastAPI** will take care of solving them.
-## First dependency "dependable"
+## First dependency "dependable" { #first-dependency-dependable }
You could create a first dependency ("dependable") like:
-=== "Python 3.10+"
-
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="9-10"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
-
-=== "Python 3.10 non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="6-7"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
-
-=== "Python 3.6 non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="8-9"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}
It declares an optional query parameter `q` as a `str`, and then it just returns it.
This is quite simple (not very useful), but will help us focus on how the sub-dependencies work.
-## Second dependency, "dependable" and "dependant"
+## Second dependency, "dependable" and "dependant" { #second-dependency-dependable-and-dependant }
Then you can create another dependency function (a "dependable") that at the same time declares a dependency of its own (so it is a "dependant" too):
-=== "Python 3.10+"
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
-
-=== "Python 3.10 non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
-
-=== "Python 3.6 non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}
Let's focus on the parameters declared:
@@ -97,50 +29,19 @@ Let's focus on the parameters declared:
* It also declares an optional `last_query` cookie, as a `str`.
* If the user didn't provide any query `q`, we use the last query used, which we saved to a cookie before.
-## Use the dependency
+## Use the dependency { #use-the-dependency }
Then we can use the dependency with:
-=== "Python 3.10+"
-
- ```Python hl_lines="23"
- {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="23"
- {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/dependencies/tutorial005_an.py!}
- ```
-
-=== "Python 3.10 non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial005_py310.py!}
- ```
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}
-=== "Python 3.6 non-Annotated"
+/// info
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Notice that we are only declaring one dependency in the *path operation function*, the `query_or_cookie_extractor`.
- ```Python hl_lines="22"
- {!> ../../../docs_src/dependencies/tutorial005.py!}
- ```
+But **FastAPI** will know that it has to solve `query_extractor` first, to pass the results of that to `query_or_cookie_extractor` while calling it.
-!!! info
- Notice that we are only declaring one dependency in the *path operation function*, the `query_or_cookie_extractor`.
-
- But **FastAPI** will know that it has to solve `query_extractor` first, to pass the results of that to `query_or_cookie_extractor` while calling it.
+///
```mermaid
graph TB
@@ -153,32 +54,39 @@ read_query["/items/"]
query_extractor --> query_or_cookie_extractor --> read_query
```
-## Using the same dependency multiple times
+## Using the same dependency multiple times { #using-the-same-dependency-multiple-times }
If one of your dependencies is declared multiple times for the same *path operation*, for example, multiple dependencies have a common sub-dependency, **FastAPI** will know to call that sub-dependency only once per request.
-And it will save the returned value in a "cache" and pass it to all the "dependants" that need it in that specific request, instead of calling the dependency multiple times for the same request.
+And it will save the returned value in a "cache" and pass it to all the "dependants" that need it in that specific request, instead of calling the dependency multiple times for the same request.
In an advanced scenario where you know you need the dependency to be called at every step (possibly multiple times) in the same request instead of using the "cached" value, you can set the parameter `use_cache=False` when using `Depends`:
-=== "Python 3.6+"
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
- ```Python hl_lines="1"
- async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
- return {"fresh_value": fresh_value}
- ```
+////
-=== "Python 3.6+ non-Annotated"
+//// tab | Python 3.10+ non-Annotated
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="1"
- async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
- return {"fresh_value": fresh_value}
- ```
+Prefer to use the `Annotated` version if possible.
-## Recap
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+## Recap { #recap }
Apart from all the fancy words used here, the **Dependency Injection** system is quite simple.
@@ -186,9 +94,12 @@ Just functions that look the same as the *path operation functions*.
But still, it is very powerful, and allows you to declare arbitrarily deeply nested dependency "graphs" (trees).
-!!! tip
- All this might not seem as useful with these simple examples.
+/// tip
+
+All this might not seem as useful with these simple examples.
+
+But you will see how useful it is in the chapters about **security**.
- But you will see how useful it is in the chapters about **security**.
+And you will also see the amounts of code it will save you.
- And you will also see the amounts of code it will save you.
+///
diff --git a/docs/en/docs/tutorial/encoder.md b/docs/en/docs/tutorial/encoder.md
index 735aa2209ffed..c8f8bca8c9d89 100644
--- a/docs/en/docs/tutorial/encoder.md
+++ b/docs/en/docs/tutorial/encoder.md
@@ -1,4 +1,4 @@
-# JSON Compatible Encoder
+# JSON Compatible Encoder { #json-compatible-encoder }
There are some cases where you might need to convert a data type (like a Pydantic model) to something compatible with JSON (like a `dict`, `list`, etc).
@@ -6,13 +6,13 @@ For example, if you need to store it in a database.
For that, **FastAPI** provides a `jsonable_encoder()` function.
-## Using the `jsonable_encoder`
+## Using the `jsonable_encoder` { #using-the-jsonable-encoder }
Let's imagine that you have a database `fake_db` that only receives JSON compatible data.
For example, it doesn't receive `datetime` objects, as those are not compatible with JSON.
-So, a `datetime` object would have to be converted to a `str` containing the data in ISO format.
+So, a `datetime` object would have to be converted to a `str` containing the data in [ISO format](https://en.wikipedia.org/wiki/ISO_8601).
The same way, this database wouldn't receive a Pydantic model (an object with attributes), only a `dict`.
@@ -20,23 +20,16 @@ You can use `jsonable_encoder` for that.
It receives an object, like a Pydantic model, and returns a JSON compatible version:
-=== "Python 3.10+"
-
- ```Python hl_lines="4 21"
- {!> ../../../docs_src/encoder/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="5 22"
- {!> ../../../docs_src/encoder/tutorial001.py!}
- ```
+{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *}
In this example, it would convert the Pydantic model to a `dict`, and the `datetime` to a `str`.
-The result of calling it is something that can be encoded with the Python standard `json.dumps()`.
+The result of calling it is something that can be encoded with the Python standard [`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps).
It doesn't return a large `str` containing the data in JSON format (as a string). It returns a Python standard data structure (e.g. a `dict`) with values and sub-values that are all compatible with JSON.
-!!! note
- `jsonable_encoder` is actually used by **FastAPI** internally to convert data. But it is useful in many other scenarios.
+/// note
+
+`jsonable_encoder` is actually used by **FastAPI** internally to convert data. But it is useful in many other scenarios.
+
+///
diff --git a/docs/en/docs/tutorial/extra-data-types.md b/docs/en/docs/tutorial/extra-data-types.md
index b34ccd26f4c1c..611aa9b9eeb40 100644
--- a/docs/en/docs/tutorial/extra-data-types.md
+++ b/docs/en/docs/tutorial/extra-data-types.md
@@ -1,4 +1,4 @@
-# Extra Data Types
+# Extra Data Types { #extra-data-types }
Up to now, you have been using common data types, like:
@@ -17,7 +17,7 @@ And you will still have the same features as seen up to now:
* Data validation.
* Automatic annotation and documentation.
-## Other data types
+## Other data types { #other-data-types }
Here are some of the additional data types you can use:
@@ -36,7 +36,7 @@ Here are some of the additional data types you can use:
* `datetime.timedelta`:
* A Python `datetime.timedelta`.
* In requests and responses will be represented as a `float` of total seconds.
- * Pydantic also allows representing it as a "ISO 8601 time diff encoding", see the docs for more info.
+ * Pydantic also allows representing it as a "ISO 8601 time diff encoding", [see the docs for more info](https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers).
* `frozenset`:
* In requests and responses, treated the same as a `set`:
* In requests, a list will be read, eliminating duplicates and converting it to a `set`.
@@ -49,82 +49,14 @@ Here are some of the additional data types you can use:
* `Decimal`:
* Standard Python `Decimal`.
* In requests and responses, handled the same as a `float`.
-* You can check all the valid pydantic data types here: Pydantic data types.
+* You can check all the valid Pydantic data types here: [Pydantic data types](https://docs.pydantic.dev/latest/usage/types/types/).
-## Example
+## Example { #example }
Here's an example *path operation* with parameters using some of the above types.
-=== "Python 3.10+"
-
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="1 3 13-17"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="1 2 11-15"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="1 2 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *}
Note that the parameters inside the function have their natural data type, and you can, for example, perform normal date manipulations, like:
-=== "Python 3.10+"
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="19-20"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *}
diff --git a/docs/en/docs/tutorial/extra-models.md b/docs/en/docs/tutorial/extra-models.md
index e91e879e41672..e231aea90af73 100644
--- a/docs/en/docs/tutorial/extra-models.md
+++ b/docs/en/docs/tutorial/extra-models.md
@@ -1,4 +1,4 @@
-# Extra Models
+# Extra Models { #extra-models }
Continuing with the previous example, it will be common to have more than one related model.
@@ -8,34 +8,27 @@ This is especially the case for user models, because:
* The **output model** should not have a password.
* The **database model** would probably need to have a hashed password.
-!!! danger
- Never store user's plaintext passwords. Always store a "secure hash" that you can then verify.
+/// danger
- If you don't know, you will learn what a "password hash" is in the [security chapters](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}.
+Never store user's plaintext passwords. Always store a "secure hash" that you can then verify.
-## Multiple models
+If you don't know, you will learn what a "password hash" is in the [security chapters](security/simple-oauth2.md#password-hashing).
-Here's a general idea of how the models could look like with their password fields and the places where they are used:
-
-=== "Python 3.10+"
+///
- ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
- {!> ../../../docs_src/extra_models/tutorial001_py310.py!}
- ```
+## Multiple models { #multiple-models }
-=== "Python 3.6+"
+Here's a general idea of how the models could look like with their password fields and the places where they are used:
- ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
- {!> ../../../docs_src/extra_models/tutorial001.py!}
- ```
+{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}
-### About `**user_in.dict()`
+### About `**user_in.model_dump()` { #about-user-in-model-dump }
-#### Pydantic's `.dict()`
+#### Pydantic's `.model_dump()` { #pydantics-model-dump }
`user_in` is a Pydantic model of class `UserIn`.
-Pydantic models have a `.dict()` method that returns a `dict` with the model's data.
+Pydantic models have a `.model_dump()` method that returns a `dict` with the model's data.
So, if we create a Pydantic object `user_in` like:
@@ -46,7 +39,7 @@ user_in = UserIn(username="john", password="secret", email="john.doe@example.com
and then we call:
```Python
-user_dict = user_in.dict()
+user_dict = user_in.model_dump()
```
we now have a `dict` with the data in the variable `user_dict` (it's a `dict` instead of a Pydantic model object).
@@ -68,9 +61,9 @@ we would get a Python `dict` with:
}
```
-#### Unwrapping a `dict`
+#### Unpacking a `dict` { #unpacking-a-dict }
-If we take a `dict` like `user_dict` and pass it to a function (or class) with `**user_dict`, Python will "unwrap" it. It will pass the keys and values of the `user_dict` directly as key-value arguments.
+If we take a `dict` like `user_dict` and pass it to a function (or class) with `**user_dict`, Python will "unpack" it. It will pass the keys and values of the `user_dict` directly as key-value arguments.
So, continuing with the `user_dict` from above, writing:
@@ -78,7 +71,7 @@ So, continuing with the `user_dict` from above, writing:
UserInDB(**user_dict)
```
-Would result in something equivalent to:
+would result in something equivalent to:
```Python
UserInDB(
@@ -100,31 +93,31 @@ UserInDB(
)
```
-#### A Pydantic model from the contents of another
+#### A Pydantic model from the contents of another { #a-pydantic-model-from-the-contents-of-another }
-As in the example above we got `user_dict` from `user_in.dict()`, this code:
+As in the example above we got `user_dict` from `user_in.model_dump()`, this code:
```Python
-user_dict = user_in.dict()
+user_dict = user_in.model_dump()
UserInDB(**user_dict)
```
would be equivalent to:
```Python
-UserInDB(**user_in.dict())
+UserInDB(**user_in.model_dump())
```
-...because `user_in.dict()` is a `dict`, and then we make Python "unwrap" it by passing it to `UserInDB` prepended with `**`.
+...because `user_in.model_dump()` is a `dict`, and then we make Python "unpack" it by passing it to `UserInDB` prefixed with `**`.
So, we get a Pydantic model from the data in another Pydantic model.
-#### Unwrapping a `dict` and extra keywords
+#### Unpacking a `dict` and extra keywords { #unpacking-a-dict-and-extra-keywords }
And then adding the extra keyword argument `hashed_password=hashed_password`, like in:
```Python
-UserInDB(**user_in.dict(), hashed_password=hashed_password)
+UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
```
...ends up being like:
@@ -139,10 +132,13 @@ UserInDB(
)
```
-!!! warning
- The supporting additional functions are just to demo a possible flow of the data, but they of course are not providing any real security.
+/// warning
+
+The supporting additional functions `fake_password_hasher` and `fake_save_user` are just to demo a possible flow of the data, but they of course are not providing any real security.
-## Reduce duplication
+///
+
+## Reduce duplication { #reduce-duplication }
Reducing code duplication is one of the core ideas in **FastAPI**.
@@ -158,42 +154,25 @@ All the data conversion, validation, documentation, etc. will still work as norm
That way, we can declare just the differences between the models (with plaintext `password`, with `hashed_password` and without password):
-=== "Python 3.10+"
-
- ```Python hl_lines="7 13-14 17-18 21-22"
- {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="9 15-16 19-20 23-24"
- {!> ../../../docs_src/extra_models/tutorial002.py!}
- ```
+{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}
-## `Union` or `anyOf`
+## `Union` or `anyOf` { #union-or-anyof }
-You can declare a response to be the `Union` of two types, that means, that the response would be any of the two.
+You can declare a response to be the `Union` of two or more types, that means, that the response would be any of them.
It will be defined in OpenAPI with `anyOf`.
-To do that, use the standard Python type hint `typing.Union`:
+To do that, use the standard Python type hint [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union):
-!!! note
- When defining a `Union`, include the most specific type first, followed by the less specific type. In the example below, the more specific `PlaneItem` comes before `CarItem` in `Union[PlaneItem, CarItem]`.
+/// note
-=== "Python 3.10+"
+When defining a [`Union`](https://docs.pydantic.dev/latest/concepts/types/#unions), include the most specific type first, followed by the less specific type. In the example below, the more specific `PlaneItem` comes before `CarItem` in `Union[PlaneItem, CarItem]`.
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003_py310.py!}
- ```
+///
-=== "Python 3.6+"
+{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003.py!}
- ```
-
-### `Union` in Python 3.10
+### `Union` in Python 3.10 { #union-in-python-3-10 }
In this example we pass `Union[PlaneItem, CarItem]` as the value of the argument `response_model`.
@@ -205,47 +184,27 @@ If it was in a type annotation we could have used the vertical bar, as:
some_variable: PlaneItem | CarItem
```
-But if we put that in `response_model=PlaneItem | CarItem` we would get an error, because Python would try to perform an **invalid operation** between `PlaneItem` and `CarItem` instead of interpreting that as a type annotation.
+But if we put that in the assignment `response_model=PlaneItem | CarItem` we would get an error, because Python would try to perform an **invalid operation** between `PlaneItem` and `CarItem` instead of interpreting that as a type annotation.
-## List of models
+## List of models { #list-of-models }
The same way, you can declare responses of lists of objects.
-For that, use the standard Python `typing.List` (or just `list` in Python 3.9 and above):
-
-=== "Python 3.9+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/extra_models/tutorial004_py39.py!}
- ```
-
-=== "Python 3.6+"
+For that, use the standard Python `list`:
- ```Python hl_lines="1 20"
- {!> ../../../docs_src/extra_models/tutorial004.py!}
- ```
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
-## Response with arbitrary `dict`
+## Response with arbitrary `dict` { #response-with-arbitrary-dict }
You can also declare a response using a plain arbitrary `dict`, declaring just the type of the keys and values, without using a Pydantic model.
This is useful if you don't know the valid field/attribute names (that would be needed for a Pydantic model) beforehand.
-In this case, you can use `typing.Dict` (or just `dict` in Python 3.9 and above):
-
-=== "Python 3.9+"
-
- ```Python hl_lines="6"
- {!> ../../../docs_src/extra_models/tutorial005_py39.py!}
- ```
-
-=== "Python 3.6+"
+In this case, you can use `dict`:
- ```Python hl_lines="1 8"
- {!> ../../../docs_src/extra_models/tutorial005.py!}
- ```
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
-## Recap
+## Recap { #recap }
Use multiple Pydantic models and inherit freely for each case.
diff --git a/docs/en/docs/tutorial/first-steps.md b/docs/en/docs/tutorial/first-steps.md
index cfa159329405c..3355079900b38 100644
--- a/docs/en/docs/tutorial/first-steps.md
+++ b/docs/en/docs/tutorial/first-steps.md
@@ -1,10 +1,8 @@
-# First Steps
+# First Steps { #first-steps }
The simplest FastAPI file could look like this:
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
Copy that to a file `main.py`.
@@ -13,23 +11,42 @@ Run the live server:
get operation
+* using a get operation
+
+/// info | `@decorator` Info
-!!! info "`@decorator` Info"
- That `@something` syntax in Python is called a "decorator".
+That `@something` syntax in Python is called a "decorator".
- You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).
+You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).
- A "decorator" takes the function below and does something with it.
+A "decorator" takes the function below and does something with it.
- In our case, this decorator tells **FastAPI** that the function below corresponds to the **path** `/` with an **operation** `get`.
+In our case, this decorator tells **FastAPI** that the function below corresponds to the **path** `/` with an **operation** `get`.
- It is the "**path operation decorator**".
+It is the "**path operation decorator**".
+
+///
You can also use the other operations:
@@ -274,16 +349,19 @@ And the more exotic ones:
* `@app.patch()`
* `@app.trace()`
-!!! tip
- You are free to use each operation (HTTP method) as you wish.
+/// tip
+
+You are free to use each operation (HTTP method) as you wish.
+
+**FastAPI** doesn't enforce any specific meaning.
- **FastAPI** doesn't enforce any specific meaning.
+The information here is presented as a guideline, not a requirement.
- The information here is presented as a guideline, not a requirement.
+For example, when using GraphQL you normally perform all the actions using only `POST` operations.
- For example, when using GraphQL you normally perform all the actions using only `POST` operations.
+///
-### Step 4: define the **path operation function**
+### Step 4: define the **path operation function** { #step-4-define-the-path-operation-function }
This is our "**path operation function**":
@@ -291,9 +369,7 @@ This is our "**path operation function**":
* **operation**: is `get`.
* **function**: is the function below the "decorator" (below `@app.get("/")`).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
This is a Python function.
@@ -305,18 +381,17 @@ In this case, it is an `async` function.
You could also define it as a normal function instead of `async def`:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
-!!! note
- If you don't know the difference, check the [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+/// note
-### Step 5: return the content
+If you don't know the difference, check the [Async: *"In a hurry?"*](../async.md#in-a-hurry).
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+///
+
+### Step 5: return the content { #step-5-return-the-content }
+
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
You can return a `dict`, `list`, singular values as `str`, `int`, etc.
@@ -324,10 +399,31 @@ You can also return Pydantic models (you'll see more about that later).
There are many other objects and models that will be automatically converted to JSON (including ORMs, etc). Try using your favorite ones, it's highly probable that they are already supported.
-## Recap
+### Step 6: Deploy it { #step-6-deploy-it }
+
+Deploy your app to **[FastAPI Cloud](https://fastapicloud.com)** with one command: `fastapi deploy`. 🎉
+
+#### About FastAPI Cloud { #about-fastapi-cloud }
+
+**[FastAPI Cloud](https://fastapicloud.com)** is built by the same author and team behind **FastAPI**.
+
+It streamlines the process of **building**, **deploying**, and **accessing** an API with minimal effort.
+
+It brings the same **developer experience** of building apps with FastAPI to **deploying** them to the cloud. 🎉
+
+FastAPI Cloud is the primary sponsor and funding provider for the *FastAPI and friends* open source projects. ✨
+
+#### Deploy to other cloud providers { #deploy-to-other-cloud-providers }
+
+FastAPI is open source and based on standards. You can deploy FastAPI apps to any cloud provider you choose.
+
+Follow your cloud provider's guides to deploy FastAPI apps with them. 🤓
+
+## Recap { #recap }
* Import `FastAPI`.
* Create an `app` instance.
-* Write a **path operation decorator** (like `@app.get("/")`).
-* Write a **path operation function** (like `def root(): ...` above).
-* Run the development server (like `uvicorn main:app --reload`).
+* Write a **path operation decorator** using decorators like `@app.get("/")`.
+* Define a **path operation function**; for example, `def root(): ...`.
+* Run the development server using the command `fastapi dev`.
+* Optionally deploy your app with `fastapi deploy`.
diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md
index a03029e811356..78a5f1f20ae9b 100644
--- a/docs/en/docs/tutorial/handling-errors.md
+++ b/docs/en/docs/tutorial/handling-errors.md
@@ -1,4 +1,4 @@
-# Handling Errors
+# Handling Errors { #handling-errors }
There are many situations in which you need to notify an error to a client that is using your API.
@@ -19,17 +19,15 @@ The status codes in the 400 range mean that there was an error from the client.
Remember all those **"404 Not Found"** errors (and jokes)?
-## Use `HTTPException`
+## Use `HTTPException` { #use-httpexception }
To return HTTP responses with errors to the client you use `HTTPException`.
-### Import `HTTPException`
+### Import `HTTPException` { #import-httpexception }
-```Python hl_lines="1"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-```
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
-### Raise an `HTTPException` in your code
+### Raise an `HTTPException` in your code { #raise-an-httpexception-in-your-code }
`HTTPException` is a normal Python exception with additional data relevant for APIs.
@@ -37,15 +35,13 @@ Because it's a Python exception, you don't `return` it, you `raise` it.
This also means that if you are inside a utility function that you are calling inside of your *path operation function*, and you raise the `HTTPException` from inside of that utility function, it won't run the rest of the code in the *path operation function*, it will terminate that request right away and send the HTTP error from the `HTTPException` to the client.
-The benefit of raising an exception over `return`ing a value will be more evident in the section about Dependencies and Security.
+The benefit of raising an exception over returning a value will be more evident in the section about Dependencies and Security.
In this example, when the client requests an item by an ID that doesn't exist, raise an exception with a status code of `404`:
-```Python hl_lines="11"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-```
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
-### The resulting response
+### The resulting response { #the-resulting-response }
If the client requests `http://example.com/items/foo` (an `item_id` `"foo"`), that client will receive an HTTP status code of 200, and a JSON response of:
@@ -63,14 +59,17 @@ But if the client requests `http://example.com/items/bar` (a non-existent `item_
}
```
-!!! tip
- When raising an `HTTPException`, you can pass any value that can be converted to JSON as the parameter `detail`, not only `str`.
+/// tip
+
+When raising an `HTTPException`, you can pass any value that can be converted to JSON as the parameter `detail`, not only `str`.
- You could pass a `dict`, a `list`, etc.
+You could pass a `dict`, a `list`, etc.
- They are handled automatically by **FastAPI** and converted to JSON.
+They are handled automatically by **FastAPI** and converted to JSON.
-## Add custom headers
+///
+
+## Add custom headers { #add-custom-headers }
There are some situations in where it's useful to be able to add custom headers to the HTTP error. For example, for some types of security.
@@ -78,13 +77,11 @@ You probably won't need to use it directly in your code.
But in case you needed it for an advanced scenario, you can add custom headers:
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial002.py!}
-```
+{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
-## Install custom exception handlers
+## Install custom exception handlers { #install-custom-exception-handlers }
-You can add custom exception handlers with the same exception utilities from Starlette.
+You can add custom exception handlers with [the same exception utilities from Starlette](https://www.starlette.dev/exceptions/).
Let's say you have a custom exception `UnicornException` that you (or a library you use) might `raise`.
@@ -92,9 +89,7 @@ And you want to handle this exception globally with FastAPI.
You could add a custom exception handler with `@app.exception_handler()`:
-```Python hl_lines="5-7 13-18 24"
-{!../../../docs_src/handling_errors/tutorial003.py!}
-```
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
Here, if you request `/unicorns/yolo`, the *path operation* will `raise` a `UnicornException`.
@@ -106,12 +101,15 @@ So, you will receive a clean error, with an HTTP status code of `418` and a JSON
{"message": "Oops! yolo did something. There goes a rainbow..."}
```
-!!! note "Technical Details"
- You could also use `from starlette.requests import Request` and `from starlette.responses import JSONResponse`.
+/// note | Technical Details
+
+You could also use `from starlette.requests import Request` and `from starlette.responses import JSONResponse`.
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request`.
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request`.
-## Override the default exception handlers
+///
+
+## Override the default exception handlers { #override-the-default-exception-handlers }
**FastAPI** has some default exception handlers.
@@ -119,7 +117,7 @@ These handlers are in charge of returning the default JSON responses when you `r
You can override these exception handlers with your own.
-### Override request validation exceptions
+### Override request validation exceptions { #override-request-validation-exceptions }
When a request contains invalid data, **FastAPI** internally raises a `RequestValidationError`.
@@ -129,9 +127,7 @@ To override it, import the `RequestValidationError` and use it with `@app.except
The exception handler will receive a `Request` and the exception.
-```Python hl_lines="2 14-16"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-```
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
Now, if you go to `/items/foo`, instead of getting the default JSON error with:
@@ -153,50 +149,41 @@ Now, if you go to `/items/foo`, instead of getting the default JSON error with:
you will get a text version, with:
```
-1 validation error
-path -> item_id
- value is not a valid integer (type=type_error.integer)
+Validation errors:
+Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer
```
-#### `RequestValidationError` vs `ValidationError`
+### Override the `HTTPException` error handler { #override-the-httpexception-error-handler }
-!!! warning
- These are technical details that you might skip if it's not important for you now.
+The same way, you can override the `HTTPException` handler.
-`RequestValidationError` is a sub-class of Pydantic's `ValidationError`.
+For example, you could want to return a plain text response instead of JSON for these errors:
-**FastAPI** uses it so that, if you use a Pydantic model in `response_model`, and your data has an error, you will see the error in your log.
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
-But the client/user will not see it. Instead, the client will receive an "Internal Server Error" with a HTTP status code `500`.
+/// note | Technical Details
-It should be this way because if you have a Pydantic `ValidationError` in your *response* or anywhere in your code (not in the client's *request*), it's actually a bug in your code.
+You could also use `from starlette.responses import PlainTextResponse`.
-And while you fix it, your clients/users shouldn't have access to internal information about the error, as that could expose a security vulnerability.
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
-### Override the `HTTPException` error handler
+///
-The same way, you can override the `HTTPException` handler.
+/// warning
-For example, you could want to return a plain text response instead of JSON for these errors:
+Have in mind that the `RequestValidationError` contains the information of the file name and line where the validation error happens so that you can show it in your logs with the relevant information if you want to.
-```Python hl_lines="3-4 9-11 22"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-```
+But that means that if you just convert it to a string and return that information directly, you could be leaking a bit of information about your system, that's why here the code extracts and shows each error independently.
-!!! note "Technical Details"
- You could also use `from starlette.responses import PlainTextResponse`.
+///
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
-
-### Use the `RequestValidationError` body
+### Use the `RequestValidationError` body { #use-the-requestvalidationerror-body }
The `RequestValidationError` contains the `body` it received with invalid data.
You could use it while developing your app to log the body and debug it, return it to the user, etc.
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial005.py!}
-```
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
Now try sending an invalid item like:
@@ -228,15 +215,13 @@ You will receive a response telling you that the data is invalid containing the
}
```
-#### FastAPI's `HTTPException` vs Starlette's `HTTPException`
+#### FastAPI's `HTTPException` vs Starlette's `HTTPException` { #fastapis-httpexception-vs-starlettes-httpexception }
**FastAPI** has its own `HTTPException`.
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.
@@ -250,12 +235,10 @@ In this example, to be able to have both `HTTPException`s in the same code, Star
from starlette.exceptions import HTTPException as StarletteHTTPException
```
-### Re-use **FastAPI**'s exception handlers
+### Reuse **FastAPI**'s exception handlers { #reuse-fastapis-exception-handlers }
-If you want to use the exception along with the same default exception handlers from **FastAPI**, You can import and re-use the default exception handlers from `fastapi.exception_handlers`:
+If you want to use the exception along with the same default exception handlers from **FastAPI**, you can import and reuse the default exception handlers from `fastapi.exception_handlers`:
-```Python hl_lines="2-5 15 21"
-{!../../../docs_src/handling_errors/tutorial006.py!}
-```
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
-In this example you are just `print`ing the error with a very expressive message, but you get the idea. You can use the exception and then just re-use the default exception handlers.
+In this example you are just printing the error with a very expressive message, but you get the idea. You can use the exception and then just reuse the default exception handlers.
diff --git a/docs/en/docs/tutorial/header-param-models.md b/docs/en/docs/tutorial/header-param-models.md
new file mode 100644
index 0000000000000..011d5d7fc25ca
--- /dev/null
+++ b/docs/en/docs/tutorial/header-param-models.md
@@ -0,0 +1,72 @@
+# Header Parameter Models { #header-parameter-models }
+
+If you have a group of related **header parameters**, you can create a **Pydantic model** to declare them.
+
+This would allow you to **re-use the model** in **multiple places** and also to declare validations and metadata for all the parameters at once. 😎
+
+/// note
+
+This is supported since FastAPI version `0.115.0`. 🤓
+
+///
+
+## Header Parameters with a Pydantic Model { #header-parameters-with-a-pydantic-model }
+
+Declare the **header parameters** that you need in a **Pydantic model**, and then declare the parameter as `Header`:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI** will **extract** the data for **each field** from the **headers** in the request and give you the Pydantic model you defined.
+
+## Check the Docs { #check-the-docs }
+
+You can see the required headers in the docs UI at `/docs`:
+
+
+contact fields| Parameter | Type | Description |
|---|---|---|
name | str | The identifying name of the contact person/organization. |
url | str | The URL pointing to the contact information. MUST be in the format of a URL. |
email | str | The email address of the contact person/organization. MUST be in the format of an email address. |
license_info fields| Parameter | Type | Description |
|---|---|---|
name | str | REQUIRED (if a license_info is set). The license name used for the API. |
identifier | str | An SPDX license expression for the API. The identifier field is mutually exclusive of the url field. Available since OpenAPI 3.1.0, FastAPI 0.99.0. |
url | str | A URL to the license used for the API. MUST be in the format of a URL. |
license_info fields| Parameter | Type | Description |
|---|---|---|
name | str | REQUIRED (if a license_info is set). The license name used for the API. |
identifier | str | An [SPDX](https://spdx.org/licenses/) license expression for the API. The identifier field is mutually exclusive of the url field. Available since OpenAPI 3.1.0, FastAPI 0.99.0. |
url | str | A URL to the license used for the API. MUST be in the format of a URL. |
-## License identifier
+## License identifier { #license-identifier }
Since OpenAPI 3.1.0 and FastAPI 0.99.0, you can also set the `license_info` with an `identifier` instead of a `url`.
For example:
-```Python hl_lines="31"
-{!../../../docs_src/metadata/tutorial001_1.py!}
-```
+{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}
-## Metadata for tags
+## Metadata for tags { #metadata-for-tags }
You can also add additional metadata for the different tags used to group your path operations with the parameter `openapi_tags`.
@@ -53,45 +52,47 @@ Each dictionary can contain:
* `description`: a `str` with a short description for the external docs.
* `url` (**required**): a `str` with the URL for the external documentation.
-### Create metadata for tags
+### Create metadata for tags { #create-metadata-for-tags }
Let's try that in an example with tags for `users` and `items`.
Create metadata for your tags and pass it to the `openapi_tags` parameter:
-```Python hl_lines="3-16 18"
-{!../../../docs_src/metadata/tutorial004.py!}
-```
+{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}
Notice that you can use Markdown inside of the descriptions, for example "login" will be shown in bold (**login**) and "fancy" will be shown in italics (_fancy_).
-!!! tip
- You don't have to add metadata for all the tags that you use.
+/// tip
+
+You don't have to add metadata for all the tags that you use.
-### Use your tags
+///
+
+### Use your tags { #use-your-tags }
Use the `tags` parameter with your *path operations* (and `APIRouter`s) to assign them to different tags:
-```Python hl_lines="21 26"
-{!../../../docs_src/metadata/tutorial004.py!}
-```
+{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}
+
+/// info
+
+Read more about tags in [Path Operation Configuration](path-operation-configuration.md#tags).
-!!! info
- Read more about tags in [Path Operation Configuration](../path-operation-configuration/#tags){.internal-link target=_blank}.
+///
-### Check the docs
+### Check the docs { #check-the-docs }
Now, if you check the docs, they will show all the additional metadata:
-### Order of tags
+### Order of tags { #order-of-tags }
The order of each tag metadata dictionary also defines the order shown in the docs UI.
For example, even though `users` would go after `items` in alphabetical order, it is shown before them, because we added their metadata as the first dictionary in the list.
-## OpenAPI URL
+## OpenAPI URL { #openapi-url }
By default, the OpenAPI schema is served at `/openapi.json`.
@@ -99,13 +100,11 @@ But you can configure it with the parameter `openapi_url`.
For example, to set it to be served at `/api/v1/openapi.json`:
-```Python hl_lines="3"
-{!../../../docs_src/metadata/tutorial002.py!}
-```
+{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}
If you want to disable the OpenAPI schema completely you can set `openapi_url=None`, that will also disable the documentation user interfaces that use it.
-## Docs URLs
+## Docs URLs { #docs-urls }
You can configure the two documentation user interfaces included:
@@ -118,6 +117,4 @@ You can configure the two documentation user interfaces included:
For example, to set Swagger UI to be served at `/documentation` and disable ReDoc:
-```Python hl_lines="3"
-{!../../../docs_src/metadata/tutorial003.py!}
-```
+{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}
diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md
index 3c6868fe4de73..5da549cb7e8ea 100644
--- a/docs/en/docs/tutorial/middleware.md
+++ b/docs/en/docs/tutorial/middleware.md
@@ -1,4 +1,4 @@
-# Middleware
+# Middleware { #middleware }
You can add middleware to **FastAPI** applications.
@@ -11,12 +11,15 @@ A "middleware" is a function that works with every **request** before it is proc
* It can do something to that **response** or run any needed code.
* Then it returns the **response**.
-!!! note "Technical Details"
- If you have dependencies with `yield`, the exit code will run *after* the middleware.
+/// note | Technical Details
- If there were any background tasks (documented later), they will run *after* all the middleware.
+If you have dependencies with `yield`, the exit code will run *after* the middleware.
-## Create a middleware
+If there were any background tasks (covered in the [Background Tasks](background-tasks.md) section, you will see it later), they will run *after* all the middleware.
+
+///
+
+## Create a middleware { #create-a-middleware }
To create a middleware you use the decorator `@app.middleware("http")` on top of a function.
@@ -26,23 +29,27 @@ The middleware function receives:
* A function `call_next` that will receive the `request` as a parameter.
* This function will pass the `request` to the corresponding *path operation*.
* Then it returns the `response` generated by the corresponding *path operation*.
-* You can then modify further the `response` before returning it.
+* You can then further modify the `response` before returning it.
-```Python hl_lines="8-9 11 14"
-{!../../../docs_src/middleware/tutorial001.py!}
-```
+{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}
+
+/// tip
+
+Keep in mind that custom proprietary headers can be added [using the `X-` prefix](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers).
-!!! tip
- Have in mind that custom proprietary headers can be added using the 'X-' prefix.
+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)) using the parameter `expose_headers` documented in [Starlette's CORS docs](https://www.starlette.dev/middleware/#corsmiddleware).
- 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 Starlette's CORS docs.
+///
-!!! note "Technical Details"
- You could also use `from starlette.requests import Request`.
+/// note | Technical Details
- **FastAPI** provides it as a convenience for you, the developer. But it comes directly from Starlette.
+You could also use `from starlette.requests import Request`.
-### Before and after the `response`
+**FastAPI** provides it as a convenience for you, the developer. But it comes directly from Starlette.
+
+///
+
+### Before and after the `response` { #before-and-after-the-response }
You can add code to be run with the `request`, before any *path operation* receives it.
@@ -50,12 +57,39 @@ And also after the `response` is generated, before returning it.
For example, you could add a custom header `X-Process-Time` containing the time in seconds that it took to process the request and generate a response:
-```Python hl_lines="10 12-13"
-{!../../../docs_src/middleware/tutorial001.py!}
+{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}
+
+/// tip
+
+Here we use [`time.perf_counter()`](https://docs.python.org/3/library/time.html#time.perf_counter) instead of `time.time()` because it can be more precise for these use cases. 🤓
+
+///
+
+## Multiple middleware execution order { #multiple-middleware-execution-order }
+
+When you add multiple middlewares using either `@app.middleware()` decorator or `app.add_middleware()` method, each new middleware wraps the application, forming a stack. The last middleware added is the *outermost*, and the first is the *innermost*.
+
+On the request path, the *outermost* middleware runs first.
+
+On the response path, it runs last.
+
+For example:
+
+```Python
+app.add_middleware(MiddlewareA)
+app.add_middleware(MiddlewareB)
```
-## Other middlewares
+This results in the following execution order:
+
+* **Request**: MiddlewareB → MiddlewareA → route
+
+* **Response**: route → MiddlewareA → MiddlewareB
+
+This stacking behavior ensures that middlewares are executed in a predictable and controllable order.
+
+## Other middlewares { #other-middlewares }
-You can later read more about other middlewares in the [Advanced User Guide: Advanced Middleware](../advanced/middleware.md){.internal-link target=_blank}.
+You can later read more about other middlewares in the [Advanced User Guide: Advanced Middleware](../advanced/middleware.md).
You will read about how to handle CORS with a middleware in the next section.
diff --git a/docs/en/docs/tutorial/path-operation-configuration.md b/docs/en/docs/tutorial/path-operation-configuration.md
index 7d4d4bccaf64c..e350f7683fb9a 100644
--- a/docs/en/docs/tutorial/path-operation-configuration.md
+++ b/docs/en/docs/tutorial/path-operation-configuration.md
@@ -1,11 +1,14 @@
-# Path Operation Configuration
+# Path Operation Configuration { #path-operation-configuration }
There are several parameters that you can pass to your *path operation decorator* to configure it.
-!!! warning
- Notice that these parameters are passed directly to the *path operation decorator*, not to your *path operation function*.
+/// warning
-## Response Status Code
+Notice that these parameters are passed directly to the *path operation decorator*, not to your *path operation function*.
+
+///
+
+## Response Status Code { #response-status-code }
You can define the (HTTP) `status_code` to be used in the response of your *path operation*.
@@ -13,58 +16,29 @@ You can pass directly the `int` code, like `404`.
But if you don't remember what each number code is for, you can use the shortcut constants in `status`:
-=== "Python 3.10+"
-
- ```Python hl_lines="1 15"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *}
That status code will be used in the response and will be added to the OpenAPI schema.
-!!! note "Technical Details"
- You could also use `from starlette import status`.
-
- **FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette.
-
-## Tags
+/// note | Technical Details
-You can add tags to your *path operation*, pass the parameter `tags` with a `list` of `str` (commonly just one `str`):
-
-=== "Python 3.10+"
+You could also use `from starlette import status`.
- ```Python hl_lines="15 20 25"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
- ```
+**FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette.
-=== "Python 3.9+"
+///
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
- ```
+## Tags { #tags }
-=== "Python 3.6+"
+You can add tags to your *path operation*, pass the parameter `tags` with a `list` of `str` (commonly just one `str`):
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *}
They will be added to the OpenAPI schema and used by the automatic documentation interfaces:
-### Tags with Enums
+### Tags with Enums { #tags-with-enums }
If you have a big application, you might end up accumulating **several tags**, and you would want to make sure you always use the **same tag** for related *path operations*.
@@ -72,99 +46,53 @@ In these cases, it could make sense to store the tags in an `Enum`.
**FastAPI** supports that the same way as with plain strings:
-```Python hl_lines="1 8-10 13 18"
-{!../../../docs_src/path_operation_configuration/tutorial002b.py!}
-```
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
-## Summary and description
+## Summary and description { #summary-and-description }
You can add a `summary` and `description`:
-=== "Python 3.10+"
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *}
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
- ```
+## Description from docstring { #description-from-docstring }
-=== "Python 3.9+"
+As descriptions tend to be long and cover multiple lines, you can declare the *path operation* description in the function docstring and **FastAPI** will read it from there.
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
- ```
+You can write [Markdown](https://en.wikipedia.org/wiki/Markdown) in the docstring, it will be interpreted and displayed correctly (taking into account docstring indentation).
-=== "Python 3.6+"
-
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
- ```
-
-## Description from docstring
-
-As descriptions tend to be long and cover multiple lines, you can declare the *path operation* description in the function docstring and **FastAPI** will read it from there.
-
-You can write Markdown in the docstring, it will be interpreted and displayed correctly (taking into account docstring indentation).
-
-=== "Python 3.10+"
-
- ```Python hl_lines="17-25"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}
It will be used in the interactive docs:
-## Response description
+## Response description { #response-description }
You can specify the response description with the parameter `response_description`:
-=== "Python 3.10+"
-
- ```Python hl_lines="19"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
-=== "Python 3.9+"
+/// info
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
- ```
+Notice that `response_description` refers specifically to the response, the `description` refers to the *path operation* in general.
-=== "Python 3.6+"
+///
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
- ```
+/// check
-!!! info
- Notice that `response_description` refers specifically to the response, the `description` refers to the *path operation* in general.
+OpenAPI specifies that each *path operation* requires a response description.
-!!! check
- OpenAPI specifies that each *path operation* requires a response description.
+So, if you don't provide one, **FastAPI** will automatically generate one of "Successful response".
- So, if you don't provide one, **FastAPI** will automatically generate one of "Successful response".
+///
-## Deprecate a *path operation*
+## Deprecate a *path operation* { #deprecate-a-path-operation }
-If you need to mark a *path operation* as deprecated, but without removing it, pass the parameter `deprecated`:
+If you need to mark a *path operation* as deprecated, but without removing it, pass the parameter `deprecated`:
-```Python hl_lines="16"
-{!../../../docs_src/path_operation_configuration/tutorial006.py!}
-```
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
It will be clearly marked as deprecated in the interactive docs:
@@ -174,6 +102,6 @@ Check how deprecated and non-deprecated *path operations* look like:
-## Recap
+## Recap { #recap }
You can configure and add metadata for your *path operations* easily by passing parameters to the *path operation decorators*.
diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md
index 9255875d605b8..2ba40e92fe16d 100644
--- a/docs/en/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/en/docs/tutorial/path-params-numeric-validations.md
@@ -1,107 +1,44 @@
-# Path Parameters and Numeric Validations
+# Path Parameters and Numeric Validations { #path-parameters-and-numeric-validations }
In the same way that you can declare more validations and metadata for query parameters with `Query`, you can declare the same type of validations and metadata for path parameters with `Path`.
-## Import Path
+## Import `Path` { #import-path }
First, import `Path` from `fastapi`, and import `Annotated`:
-=== "Python 3.10+"
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+/// info
-=== "Python 3.9+"
+FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+If you have an older version, you would get errors when trying to use `Annotated`.
-=== "Python 3.6+"
+Make sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions) to at least 0.95.1 before using `Annotated`.
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+///
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
-
-!!! info
- FastAPI added support for `Annotated` (and started recommending it) in version 0.95.0.
-
- If you have an older version, you would get errors when trying to use `Annotated`.
-
- Make sure you [Upgrade the FastAPI version](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} to at least 0.95.1 before using `Annotated`.
-
-## Declare metadata
+## Declare metadata { #declare-metadata }
You can declare all the same parameters as for `Query`.
For example, to declare a `title` metadata value for the path parameter `item_id` you can type:
-=== "Python 3.10+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *}
-=== "Python 3.6+"
+/// note
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+A path parameter is always required as it has to be part of the path. Even if you declared it with `None` or set a default value, it would not affect anything, it would still be always required.
-=== "Python 3.10+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+## Order the parameters as you need { #order-the-parameters-as-you-need }
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+/// tip
-=== "Python 3.6+ non-Annotated"
+This is probably not as important or necessary if you use `Annotated`.
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
-
-!!! note
- A path parameter is always required as it has to be part of the path.
-
- So, you should declare it with `...` to mark it as required.
-
- Nevertheless, even if you declared it with `None` or set a default value, it would not affect anything, it would still be always required.
-
-## Order the parameters as you need
-
-!!! tip
- This is probably not as important or necessary if you use `Annotated`.
+///
Let's say that you want to declare the query parameter `q` as a required `str`.
@@ -117,33 +54,19 @@ It doesn't matter for **FastAPI**. It will detect the parameters by their names,
So, you can declare your function as:
-=== "Python 3.6 non-Annotated"
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
- !!! tip
- Prefer to use the `Annotated` version if possible.
+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 hl_lines="7"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.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()`.
+## Order the parameters as you need, tricks { #order-the-parameters-as-you-need-tricks }
-=== "Python 3.9+"
+/// tip
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
- ```
+This is probably not as important or necessary if you use `Annotated`.
-=== "Python 3.6+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
- ```
-
-## Order the parameters as you need, tricks
-
-!!! tip
- This is probably not as important or necessary if you use `Annotated`.
+///
Here's a **small trick** that can be handy, but you won't need it often.
@@ -160,82 +83,32 @@ Pass `*`, as the first parameter of the function.
Python won't do anything with that `*`, but it will know that all the following parameters should be called as keyword arguments (key-value pairs), also known as kwargs. Even if they don't have a default value.
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
-```
-
-### 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 `*`.
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
-=== "Python 3.9+"
+### Better with `Annotated` { #better-with-annotated }
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
- ```
+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.6+"
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
- ```
-
-## Number validations: greater than or equal
+## Number validations: greater than or equal { #number-validations-greater-than-or-equal }
With `Query` and `Path` (and others you'll see later) you can declare number constraints.
Here, with `ge=1`, `item_id` will need to be an integer number "`g`reater than or `e`qual" to `1`.
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
- ```
-
-## Number validations: greater than and less than or equal
+## Number validations: greater than and less than or equal { #number-validations-greater-than-and-less-than-or-equal }
The same applies for:
* `gt`: `g`reater `t`han
* `le`: `l`ess than or `e`qual
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
- ```
-
-## Number validations: floats, greater than and less than
+## Number validations: floats, greater than and less than { #number-validations-floats-greater-than-and-less-than }
Number validations also work for `float` values.
@@ -245,30 +118,11 @@ So, `0.5` would be a valid value. But `0.0` or `0` would not.
And the same for lt.
-=== "Python 3.9+"
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
- ```
+## Recap { #recap }
-## Recap
-
-With `Query`, `Path` (and others you haven't seen yet) you can declare metadata and string validations in the same ways as with [Query Parameters and String Validations](query-params-str-validations.md){.internal-link target=_blank}.
+With `Query`, `Path` (and others you haven't seen yet) you can declare metadata and string validations in the same ways as with [Query Parameters and String Validations](query-params-str-validations.md).
And you can also declare numeric validations:
@@ -277,18 +131,24 @@ And you can also declare numeric validations:
* `lt`: `l`ess `t`han
* `le`: `l`ess than or `e`qual
-!!! info
- `Query`, `Path`, and other classes you will see later are subclasses of a common `Param` class.
+/// info
+
+`Query`, `Path`, and other classes you will see later are subclasses of a common `Param` class.
+
+All of them share the same parameters for additional validation and metadata you have seen.
+
+///
+
+/// note | Technical Details
- All of them share the same parameters for additional validation and metadata you have seen.
+When you import `Query`, `Path` and others from `fastapi`, they are actually functions.
-!!! note "Technical Details"
- When you import `Query`, `Path` and others from `fastapi`, they are actually functions.
+That when called, return instances of classes of the same name.
- That when called, return instances of classes of the same name.
+So, you import `Query`, which is a function. And when you call it, it returns an instance of a class also named `Query`.
- So, you import `Query`, which is a function. And when you call it, it returns an instance of a class also named `Query`.
+These functions are there (instead of just using the classes directly) so that your editor doesn't mark errors about their types.
- These functions are there (instead of just using the classes directly) so that your editor doesn't mark errors about their types.
+That way you can use your normal editor and coding tools without having to add custom configurations to disregard those errors.
- That way you can use your normal editor and coding tools without having to add custom configurations to disregard those errors.
+///
diff --git a/docs/en/docs/tutorial/path-params.md b/docs/en/docs/tutorial/path-params.md
index 6594a7a8b5f95..6614dfdcb718a 100644
--- a/docs/en/docs/tutorial/path-params.md
+++ b/docs/en/docs/tutorial/path-params.md
@@ -1,105 +1,114 @@
-# Path Parameters
+# Path Parameters { #path-parameters }
You can declare path "parameters" or "variables" with the same syntax used by Python format strings:
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
The value of the path parameter `item_id` will be passed to your function as the argument `item_id`.
-So, if you run this example and go to http://127.0.0.1:8000/items/foo, you will see a response of:
+So, if you run this example and go to [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo), you will see a response of:
```JSON
{"item_id":"foo"}
```
-## Path parameters with types
+## Path parameters with types { #path-parameters-with-types }
You can declare the type of a path parameter in the function, using standard Python type annotations:
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
+{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}
In this case, `item_id` is declared to be an `int`.
-!!! check
- This will give you editor support inside of your function, with error checks, completion, etc.
+/// check
+
+This will give you editor support inside of your function, with error checks, completion, etc.
-## Data conversion
+///
-If you run this example and open your browser at http://127.0.0.1:8000/items/3, you will see a response of:
+## Data conversion { #data-conversion }
+
+If you run this example and open your browser at [http://127.0.0.1:8000/items/3](http://127.0.0.1:8000/items/3), you will see a response of:
```JSON
{"item_id":3}
```
-!!! check
- Notice that the value your function received (and returned) is `3`, as a Python `int`, not a string `"3"`.
+/// check
+
+Notice that the value your function received (and returned) is `3`, as a Python `int`, not a string `"3"`.
+
+So, with that type declaration, **FastAPI** gives you automatic request "parsing".
- So, with that type declaration, **FastAPI** gives you automatic request "parsing".
+///
-## Data validation
+## Data validation { #data-validation }
-But if you go to the browser at http://127.0.0.1:8000/items/foo, you will see a nice HTTP error of:
+But if you go to the browser at [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo), you will see a nice HTTP error of:
```JSON
{
- "detail": [
- {
- "loc": [
- "path",
- "item_id"
- ],
- "msg": "value is not a valid integer",
- "type": "type_error.integer"
- }
- ]
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo"
+ }
+ ]
}
```
because the path parameter `item_id` had a value of `"foo"`, which is not an `int`.
-The same error would appear if you provided a `float` instead of an `int`, as in: http://127.0.0.1:8000/items/4.2
+The same error would appear if you provided a `float` instead of an `int`, as in: [http://127.0.0.1:8000/items/4.2](http://127.0.0.1:8000/items/4.2)
-!!! check
- So, with the same Python type declaration, **FastAPI** gives you data validation.
+/// check
- Notice that the error also clearly states exactly the point where the validation didn't pass.
+So, with the same Python type declaration, **FastAPI** gives you data validation.
- This is incredibly helpful while developing and debugging code that interacts with your API.
+Notice that the error also clearly states exactly the point where the validation didn't pass.
-## Documentation
+This is incredibly helpful while developing and debugging code that interacts with your API.
-And when you open your browser at http://127.0.0.1:8000/docs, you will see an automatic, interactive, API documentation like:
+///
+
+## Documentation { #documentation }
+
+And when you open your browser at [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs), you will see an automatic, interactive, API documentation like:
-!!! check
- Again, just with that same Python type declaration, **FastAPI** gives you automatic, interactive documentation (integrating Swagger UI).
+/// check
+
+Again, just with that same Python type declaration, **FastAPI** gives you automatic, interactive documentation (integrating Swagger UI).
- Notice that the path parameter is declared to be an integer.
+Notice that the path parameter is declared to be an integer.
-## Standards-based benefits, alternative documentation
+///
-And because the generated schema is from the OpenAPI standard, there are many compatible tools.
+## Standards-based benefits, alternative documentation { #standards-based-benefits-alternative-documentation }
-Because of this, **FastAPI** itself provides an alternative API documentation (using ReDoc), which you can access at http://127.0.0.1:8000/redoc:
+And because the generated schema is from the [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md) standard, there are many compatible tools.
+
+Because of this, **FastAPI** itself provides an alternative API documentation (using ReDoc), which you can access at [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc):
The same way, there are many compatible tools. Including code generation tools for many languages.
-## Pydantic
+## Pydantic { #pydantic }
-All the data validation is performed under the hood by Pydantic, so you get all the benefits from it. And you know you are in good hands.
+All the data validation is performed under the hood by [Pydantic](https://docs.pydantic.dev/), so you get all the benefits from it. And you know you are in good hands.
You can use the same type declarations with `str`, `float`, `bool` and many other complex data types.
Several of these are explored in the next chapters of the tutorial.
-## Order matters
+## Order matters { #order-matters }
When creating *path operations*, you can find situations where you have a fixed path.
@@ -109,25 +118,21 @@ And then you can also have a path `/users/{user_id}` to get data about a specifi
Because *path operations* are evaluated in order, you need to make sure that the path for `/users/me` is declared before the one for `/users/{user_id}`:
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
-```
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
Otherwise, the path for `/users/{user_id}` would match also for `/users/me`, "thinking" that it's receiving a parameter `user_id` with a value of `"me"`.
Similarly, you cannot redefine a path operation:
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003b.py!}
-```
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
The first one will always be used since the path matches first.
-## Predefined values
+## Predefined values { #predefined-values }
If you have a *path operation* that receives a *path parameter*, but you want the possible valid *path parameter* values to be predefined, you can use a standard Python `Enum`.
-### Create an `Enum` class
+### Create an `Enum` class { #create-an-enum-class }
Import `Enum` and create a sub-class that inherits from `str` and from `Enum`.
@@ -135,62 +140,55 @@ By inheriting from `str` the API docs will be able to know that the values must
Then create class attributes with fixed values, which will be the available valid values:
-```Python hl_lines="1 6-9"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
+
+/// tip
-!!! info
- Enumerations (or enums) are available in Python since version 3.4.
+If you are wondering, "AlexNet", "ResNet", and "LeNet" are just names of Machine Learning models.
-!!! tip
- If you are wondering, "AlexNet", "ResNet", and "LeNet" are just names of Machine Learning models.
+///
-### Declare a *path parameter*
+### Declare a *path parameter* { #declare-a-path-parameter }
Then create a *path parameter* with a type annotation using the enum class you created (`ModelName`):
-```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
-### Check the docs
+### Check the docs { #check-the-docs }
Because the available values for the *path parameter* are predefined, the interactive docs can show them nicely:
-### Working with Python *enumerations*
+### Working with Python *enumerations* { #working-with-python-enumerations }
The value of the *path parameter* will be an *enumeration member*.
-#### Compare *enumeration members*
+#### Compare *enumeration members* { #compare-enumeration-members }
You can compare it with the *enumeration member* in your created enum `ModelName`:
-```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}
-#### Get the *enumeration value*
+#### Get the *enumeration value* { #get-the-enumeration-value }
You can get the actual value (a `str` in this case) using `model_name.value`, or in general, `your_enum_member.value`:
-```Python hl_lines="20"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}
+
+/// tip
-!!! tip
- You could also access the value `"lenet"` with `ModelName.lenet.value`.
+You could also access the value `"lenet"` with `ModelName.lenet.value`.
-#### Return *enumeration members*
+///
+
+#### Return *enumeration members* { #return-enumeration-members }
You can return *enum members* from your *path operation*, even nested in a JSON body (e.g. a `dict`).
They will be converted to their corresponding values (strings in this case) before returning them to the client:
-```Python hl_lines="18 21 23"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}
In your client you will get a JSON response like:
@@ -201,7 +199,7 @@ In your client you will get a JSON response like:
}
```
-## Path parameters containing paths
+## Path parameters containing paths { #path-parameters-containing-paths }
Let's say you have a *path operation* with a path `/files/{file_path}`.
@@ -209,7 +207,7 @@ But you need `file_path` itself to contain a *path*, like `home/johndoe/myfile.t
So, the URL for that file would be something like: `/files/home/johndoe/myfile.txt`.
-### OpenAPI support
+### OpenAPI support { #openapi-support }
OpenAPI doesn't support a way to declare a *path parameter* to contain a *path* inside, as that could lead to scenarios that are difficult to test and define.
@@ -217,7 +215,7 @@ Nevertheless, you can still do it in **FastAPI**, using one of the internal tool
And the docs would still work, although not adding any documentation telling that the parameter should contain a path.
-### Path convertor
+### Path convertor { #path-convertor }
Using an option directly from Starlette you can declare a *path parameter* containing a *path* using a URL like:
@@ -229,21 +227,22 @@ In this case, the name of the parameter is `file_path`, and the last part, `:pat
So, you can use it with:
-```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
-```
+{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}
+
+/// tip
+
+You might need the parameter to contain `/home/johndoe/myfile.txt`, with a leading slash (`/`).
-!!! tip
- You could need the parameter to contain `/home/johndoe/myfile.txt`, with a leading slash (`/`).
+In that case, the URL would be: `/files//home/johndoe/myfile.txt`, with a double slash (`//`) between `files` and `home`.
- In that case, the URL would be: `/files//home/johndoe/myfile.txt`, with a double slash (`//`) between `files` and `home`.
+///
-## Recap
+## Recap { #recap }
With **FastAPI**, by using short, intuitive and standard Python type declarations, you get:
* Editor support: error checks, autocompletion, etc.
-* Data "parsing"
+* Data "parsing"
* Data validation
* API annotation and automatic documentation
diff --git a/docs/en/docs/tutorial/query-param-models.md b/docs/en/docs/tutorial/query-param-models.md
new file mode 100644
index 0000000000000..b70cdc3354d8d
--- /dev/null
+++ b/docs/en/docs/tutorial/query-param-models.md
@@ -0,0 +1,68 @@
+# Query Parameter Models { #query-parameter-models }
+
+If you have a group of **query parameters** that are related, you can create a **Pydantic model** to declare them.
+
+This would allow you to **re-use the model** in **multiple places** and also to declare validations and metadata for all the parameters at once. 😎
+
+/// note
+
+This is supported since FastAPI version `0.115.0`. 🤓
+
+///
+
+## Query Parameters with a Pydantic Model { #query-parameters-with-a-pydantic-model }
+
+Declare the **query parameters** that you need in a **Pydantic model**, and then declare the parameter as `Query`:
+
+{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}
+
+**FastAPI** will **extract** the data for **each field** from the **query parameters** in the request and give you the Pydantic model you defined.
+
+## Check the Docs { #check-the-docs }
+
+You can see the query parameters in the docs UI at `/docs`:
+
+
+
-
-### Query parameter list / multiple values with defaults
+/// tip
-And you can also define a default `list` of values if none are provided:
+To declare a query parameter with a type of `list`, like in the example above, you need to explicitly use `Query`, otherwise it would be interpreted as a request body.
-=== "Python 3.9+"
+///
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!}
- ```
-
-=== "Python 3.9+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
+The interactive API docs will update accordingly, to allow multiple values:
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
- ```
+
-=== "Python 3.6+ non-Annotated"
+### Query parameter list / multiple values with defaults { #query-parameter-list-multiple-values-with-defaults }
- !!! tip
- Prefer to use the `Annotated` version if possible.
+You can also define a default `list` of values if none are provided:
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
If you go to:
@@ -658,124 +288,43 @@ the default of `q` will be: `["foo", "bar"]` and your response will be:
}
```
-#### Using `list`
+#### Using just `list` { #using-just-list }
-You can also use `list` directly instead of `List[str]` (or `list[str]` in Python 3.9+):
+You can also use `list` directly instead of `list[str]`:
-=== "Python 3.9+"
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!}
- ```
+/// note
-=== "Python 3.6+"
+Keep in mind that in this case, FastAPI won't check the contents of the list.
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!}
- ```
+For example, `list[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't.
-=== "Python 3.6+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial013.py!}
- ```
-
-!!! note
- Have 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.
-
-## Declare more metadata
+## Declare more metadata { #declare-more-metadata }
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.
-
- 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.
+/// note
-You can add a `title`:
+Keep in mind that different tools might have different levels of OpenAPI support.
-=== "Python 3.10+"
+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.
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!}
- ```
+///
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
+You can add a `title`:
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *}
And a `description`:
-=== "Python 3.10+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!}
- ```
-
-=== "Python 3.9+"
+{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *}
- ```Python hl_lines="14"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="15"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
- ```
-
-## Alias parameters
+## Alias parameters { #alias-parameters }
Imagine that you want the parameter to be `item-query`.
@@ -793,131 +342,91 @@ But you still need it to be exactly `item-query`...
Then you can declare an `alias`, and that alias is what will be used to find the parameter value:
-=== "Python 3.10+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!}
- ```
-
-=== "Python 3.9+"
+{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *}
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
- ```
+## Deprecating parameters { #deprecating-parameters }
-=== "Python 3.6+"
+Now let's say you don't like this parameter anymore.
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!}
- ```
+You have to leave it there a while because there are clients using it, but you want the docs to clearly show it as deprecated.
-=== "Python 3.10+ non-Annotated"
+Then pass the parameter `deprecated=True` to `Query`:
- !!! tip
- Prefer to use the `Annotated` version if possible.
+{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *}
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
- ```
+The docs will show it like this:
-=== "Python 3.6+ non-Annotated"
+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+## Exclude parameters from OpenAPI { #exclude-parameters-from-openapi }
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
- ```
+To exclude a query parameter from the generated OpenAPI schema (and thus, from the automatic documentation systems), set the parameter `include_in_schema` of `Query` to `False`:
-## Deprecating parameters
+{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *}
-Now let's say you don't like this parameter anymore.
+## Custom Validation { #custom-validation }
-You have to leave it there a while because there are clients using it, but you want the docs to clearly show it as deprecated.
+There could be cases where you need to do some **custom validation** that can't be done with the parameters shown above.
-Then pass the parameter `deprecated=True` to `Query`:
+In those cases, you can use a **custom validator function** that is applied after the normal validation (e.g. after validating that the value is a `str`).
-=== "Python 3.10+"
+You can achieve that using [Pydantic's `AfterValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-after-validator) inside of `Annotated`.
- ```Python hl_lines="19"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+Pydantic also has [`BeforeValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-before-validator) and others. 🤓
- ```Python hl_lines="19"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
- ```
+///
-=== "Python 3.6+"
+For example, this custom validator checks that the item ID starts with `isbn-` for an ISBN book number or with `imdb-` for an IMDB movie URL ID:
- ```Python hl_lines="20"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
-=== "Python 3.10+ non-Annotated"
+/// info
- !!! tip
- Prefer to use the `Annotated` version if possible.
+This is available with Pydantic version 2 or above. 😎
- ```Python hl_lines="17"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
- ```
+///
-=== "Python 3.6+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+If you need to do any type of validation that requires communicating with any **external component**, like a database or another API, you should instead use **FastAPI Dependencies**, you will learn about them later.
- ```Python hl_lines="18"
- {!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
- ```
+These custom validators are for things that can be checked with **only** the **same data** provided in the request.
-The docs will show it like this:
+///
-
+### Understand that Code { #understand-that-code }
-## Exclude from OpenAPI
+The important point is just using **`AfterValidator` with a function inside `Annotated`**. Feel free to skip this part. 🤸
-To exclude a query parameter from the generated OpenAPI schema (and thus, from the automatic documentation systems), set the parameter `include_in_schema` of `Query` to `False`:
+---
-=== "Python 3.10+"
+But if you're curious about this specific code example and you're still entertained, here are some extra details.
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!}
- ```
+#### String with `value.startswith()` { #string-with-value-startswith }
-=== "Python 3.9+"
+Did you notice? a string using `value.startswith()` can take a tuple, and it will check each value in the tuple:
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *}
-=== "Python 3.6+"
+#### A Random Item { #a-random-item }
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!}
- ```
+With `data.items()` we get an iterable object with tuples containing the key and value for each dictionary item.
-=== "Python 3.10+ non-Annotated"
+We convert this iterable object into a proper `list` with `list(data.items())`.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Then with `random.choice()` we can get a **random value** from the list, so, we get a tuple with `(id, name)`. It will be something like `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")`.
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
- ```
+Then we **assign those two values** of the tuple to the variables `id` and `name`.
-=== "Python 3.6+ non-Annotated"
+So, if the user didn't provide an item ID, they will still receive a random suggestion.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+...we do all this in a **single simple line**. 🤯 Don't you love Python? 🐍
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *}
-## Recap
+## Recap { #recap }
You can declare additional validations and metadata for your parameters.
@@ -934,6 +443,8 @@ Validations specific for strings:
* `max_length`
* `pattern`
+Custom validations using `AfterValidator`.
+
In these examples you saw how to declare validations for `str` values.
-See the next chapters to see how to declare validations for other types, like numbers.
+See the next chapters to learn how to declare validations for other types, like numbers.
diff --git a/docs/en/docs/tutorial/query-params.md b/docs/en/docs/tutorial/query-params.md
index 0b74b10f81c8c..efe2c6d7a0fbf 100644
--- a/docs/en/docs/tutorial/query-params.md
+++ b/docs/en/docs/tutorial/query-params.md
@@ -1,10 +1,8 @@
-# Query Parameters
+# Query Parameters { #query-parameters }
When you declare other function parameters that are not part of the path parameters, they are automatically interpreted as "query" parameters.
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial001.py!}
-```
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
The query is the set of key-value pairs that go after the `?` in a URL, separated by `&` characters.
@@ -26,11 +24,11 @@ But when you declare them with Python types (in the example above, as `int`), th
All the same process that applied for path parameters also applies for query parameters:
* Editor support (obviously)
-* Data "parsing"
+* Data "parsing"
* Data validation
* Automatic documentation
-## Defaults
+## Defaults { #defaults }
As query parameters are not a fixed part of a path, they can be optional and can have default values.
@@ -59,42 +57,25 @@ The parameter values in your function will be:
* `skip=20`: because you set it in the URL
* `limit=10`: because that was the default value
-## Optional parameters
+## Optional parameters { #optional-parameters }
The same way, you can declare optional query parameters, by setting their default to `None`:
-=== "Python 3.10+"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
- ```
+{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *}
In this case, the function parameter `q` will be optional, and will be `None` by default.
-!!! check
- Also notice that **FastAPI** is smart enough to notice that the path parameter `item_id` is a path parameter and `q` is not, so, it's a query parameter.
+/// check
-## Query parameter type conversion
+Also notice that **FastAPI** is smart enough to notice that the path parameter `item_id` is a path parameter and `q` is not, so, it's a query parameter.
-You can also declare `bool` types, and they will be converted:
-
-=== "Python 3.10+"
+///
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
- ```
+## Query parameter type conversion { #query-parameter-type-conversion }
-=== "Python 3.6+"
+You can also declare `bool` types, and they will be converted:
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *}
In this case, if you go to:
@@ -129,7 +110,7 @@ http://127.0.0.1:8000/items/foo?short=yes
or any other case variation (uppercase, first letter in uppercase, etc), your function will see the parameter `short` with a `bool` value of `True`. Otherwise as `False`.
-## Multiple path and query parameters
+## Multiple path and query parameters { #multiple-path-and-query-parameters }
You can declare multiple path parameters and query parameters at the same time, **FastAPI** knows which is which.
@@ -137,19 +118,9 @@ And you don't have to declare them in any specific order.
They will be detected by name:
-=== "Python 3.10+"
-
- ```Python hl_lines="6 8"
- {!> ../../../docs_src/query_params/tutorial004_py310.py!}
- ```
+{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *}
-=== "Python 3.6+"
-
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
-
-## Required query parameters
+## Required query parameters { #required-query-parameters }
When you declare a default value for non-path parameters (for now, we have only seen query parameters), then it is not required.
@@ -157,9 +128,7 @@ If you don't want to add a specific value but just make it optional, set the def
But when you want to make a query parameter required, you can just not declare any default value:
-```Python hl_lines="6-7"
-{!../../../docs_src/query_params/tutorial005.py!}
-```
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
Here the query parameter `needy` is a required query parameter of type `str`.
@@ -173,16 +142,17 @@ http://127.0.0.1:8000/items/foo-item
```JSON
{
- "detail": [
- {
- "loc": [
- "query",
- "needy"
- ],
- "msg": "field required",
- "type": "value_error.missing"
- }
- ]
+ "detail": [
+ {
+ "type": "missing",
+ "loc": [
+ "query",
+ "needy"
+ ],
+ "msg": "Field required",
+ "input": null
+ }
+ ]
}
```
@@ -203,17 +173,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
And of course, you can define some parameters as required, some as having a default value, and some entirely optional:
-=== "Python 3.10+"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params/tutorial006_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params/tutorial006.py!}
- ```
+{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *}
In this case, there are 3 query parameters:
@@ -221,5 +181,8 @@ In this case, there are 3 query parameters:
* `skip`, an `int` with a default value of `0`.
* `limit`, an optional `int`.
-!!! tip
- You could also use `Enum`s the same way as with [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}.
+/// tip
+
+You could also use `Enum`s the same way as with [Path Parameters](path-params.md#predefined-values).
+
+///
diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md
index 1fe1e7a33db99..ae3d6a119d63f 100644
--- a/docs/en/docs/tutorial/request-files.md
+++ b/docs/en/docs/tutorial/request-files.md
@@ -1,104 +1,60 @@
-# Request Files
+# Request Files { #request-files }
You can define files to be uploaded by the client using `File`.
-!!! info
- To receive uploaded files, first install `python-multipart`.
+/// info
- E.g. `pip install python-multipart`.
+To receive uploaded files, first install [`python-multipart`](https://github.com/Kludex/python-multipart).
- This is because uploaded files are sent as "form data".
+Make sure you create a [virtual environment](../virtual-environments.md), activate it, and then install it, for example:
-## Import `File`
-
-Import `File` and `UploadFile` from `fastapi`:
-
-=== "Python 3.9+"
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+```console
+$ pip install python-multipart
+```
-=== "Python 3.6+"
+This is because uploaded files are sent as "form data".
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+///
-=== "Python 3.6+ non-Annotated"
+## Import `File` { #import-file }
- !!! tip
- Prefer to use the `Annotated` version if possible.
+Import `File` and `UploadFile` from `fastapi`:
- ```Python hl_lines="1"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
-## Define `File` Parameters
+## Define `File` Parameters { #define-file-parameters }
Create file parameters the same way you would for `Body` or `Form`:
-=== "Python 3.9+"
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
- ```Python hl_lines="9"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
+/// info
-=== "Python 3.6+"
+`File` is a class that inherits directly from `Form`.
- ```Python hl_lines="8"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
+But remember that when you import `Query`, `Path`, `File` and others from `fastapi`, those are actually functions that return special classes.
-=== "Python 3.6+ non-Annotated"
+///
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="7"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+To declare File bodies, you need to use `File`, because otherwise the parameters would be interpreted as query parameters or body (JSON) parameters.
-!!! info
- `File` is a class that inherits directly from `Form`.
-
- But remember that when you import `Query`, `Path`, `File` and others from `fastapi`, those are actually functions that return special classes.
-
-!!! tip
- To declare File bodies, you need to use `File`, because otherwise the parameters would be interpreted as query parameters or body (JSON) parameters.
+///
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`.
-## File Parameters with `UploadFile`
+## File Parameters with `UploadFile` { #file-parameters-with-uploadfile }
Define a file parameter with a type of `UploadFile`:
-=== "Python 3.9+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/request_files/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/request_files/tutorial001_an.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/request_files/tutorial001.py!}
- ```
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
Using `UploadFile` has several advantages over `bytes`:
@@ -107,16 +63,16 @@ Using `UploadFile` has several advantages over `bytes`:
* A file stored in memory up to a maximum size limit, and after passing this limit it will be stored in disk.
* This means that it will work well for large files like images, videos, large binaries, etc. without consuming all the memory.
* You can get metadata from the uploaded file.
-* It has a file-like `async` interface.
-* It exposes an actual Python `SpooledTemporaryFile` object that you can pass directly to other libraries that expect a file-like object.
+* It has a [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) `async` interface.
+* It exposes an actual Python [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) object that you can pass directly to other libraries that expect a file-like object.
-### `UploadFile`
+### `UploadFile` { #uploadfile }
`UploadFile` has the following attributes:
* `filename`: A `str` with the original file name that was uploaded (e.g. `myimage.jpg`).
* `content_type`: A `str` with the content type (MIME type / media type) (e.g. `image/jpeg`).
-* `file`: A `SpooledTemporaryFile` (a file-like object). This is the actual Python file that you can pass directly to other functions or libraries that expect a "file-like" object.
+* `file`: A [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) (a [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) object). This is the actual Python file object that you can pass directly to other functions or libraries that expect a "file-like" object.
`UploadFile` has the following `async` methods. They all call the corresponding file methods underneath (using the internal `SpooledTemporaryFile`).
@@ -141,96 +97,55 @@ If you are inside of a normal `def` *path operation function*, you can access th
contents = myfile.file.read()
```
-!!! note "`async` Technical Details"
- When you use the `async` methods, **FastAPI** runs the file methods in a threadpool and awaits for them.
-
-!!! note "Starlette Technical Details"
- **FastAPI**'s `UploadFile` inherits directly from **Starlette**'s `UploadFile`, but adds some necessary parts to make it compatible with **Pydantic** and the other parts of FastAPI.
-
-## What is "Form Data"
-
-The way HTML forms (``) sends the data to the server normally uses a "special" encoding for that data, it's different from JSON.
+/// note | `async` Technical Details
-**FastAPI** will make sure to read that data from the right place instead of JSON.
+When you use the `async` methods, **FastAPI** runs the file methods in a threadpool and awaits for them.
-!!! note "Technical Details"
- Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded` when it doesn't include files.
+///
- But when the form includes files, it is encoded as `multipart/form-data`. If you use `File`, **FastAPI** will know it has to get the files from the correct part of the body.
+/// note | Starlette Technical Details
- If you want to read more about these encodings and form fields, head to the MDN web docs for POST.
+**FastAPI**'s `UploadFile` inherits directly from **Starlette**'s `UploadFile`, but adds some necessary parts to make it compatible with **Pydantic** and the other parts of FastAPI.
-!!! warning
- You can declare multiple `File` and `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `multipart/form-data` instead of `application/json`.
+///
- This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
+## What is "Form Data" { #what-is-form-data }
-## Optional File Upload
+The way HTML forms (``) sends the data to the server normally uses a "special" encoding for that data, it's different from JSON.
-You can make a file optional by using standard type annotations and setting a default value of `None`:
+**FastAPI** will make sure to read that data from the right place instead of JSON.
-=== "Python 3.10+"
+/// note | Technical Details
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!}
- ```
+Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded` when it doesn't include files.
-=== "Python 3.9+"
+But when the form includes files, it is encoded as `multipart/form-data`. If you use `File`, **FastAPI** will know it has to get the files from the correct part of the body.
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!}
- ```
+If you want to read more about these encodings and form fields, head to the [MDN web docs for `POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST).
-=== "Python 3.6+"
+///
- ```Python hl_lines="10 18"
- {!> ../../../docs_src/request_files/tutorial001_02_an.py!}
- ```
+/// warning
-=== "Python 3.10+ non-Annotated"
+You can declare multiple `File` and `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `multipart/form-data` instead of `application/json`.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
- ```Python hl_lines="7 15"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+///
-=== "Python 3.6+ non-Annotated"
+## Optional File Upload { #optional-file-upload }
- !!! tip
- Prefer to use the `Annotated` version if possible.
+You can make a file optional by using standard type annotations and setting a default value of `None`:
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
-## `UploadFile` with Additional Metadata
+## `UploadFile` with Additional Metadata { #uploadfile-with-additional-metadata }
You can also use `File()` with `UploadFile`, for example, to set additional metadata:
-=== "Python 3.9+"
-
- ```Python hl_lines="9 15"
- {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!}
- ```
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
-=== "Python 3.6+"
-
- ```Python hl_lines="8 14"
- {!> ../../../docs_src/request_files/tutorial001_03_an.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="7 13"
- {!> ../../../docs_src/request_files/tutorial001_03.py!}
- ```
-
-## Multiple File Uploads
+## Multiple File Uploads { #multiple-file-uploads }
It's possible to upload several files at the same time.
@@ -238,77 +153,24 @@ They would be associated to the same "form field" sent using "form data".
To use that, declare a list of `bytes` or `UploadFile`:
-=== "Python 3.9+"
-
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="11 16"
- {!> ../../../docs_src/request_files/tutorial002_an.py!}
- ```
-
-=== "Python 3.9+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
You will receive, as declared, a `list` of `bytes` or `UploadFile`s.
-!!! note "Technical Details"
- You could also use `from starlette.responses import HTMLResponse`.
-
- **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
-
-### Multiple File Uploads with Additional Metadata
-
-And the same way as before, you can use `File()` to set additional parameters, even for `UploadFile`:
+/// note | Technical Details
-=== "Python 3.9+"
+You could also use `from starlette.responses import HTMLResponse`.
- ```Python hl_lines="11 18-20"
- {!> ../../../docs_src/request_files/tutorial003_an_py39.py!}
- ```
+**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
-=== "Python 3.6+"
+///
- ```Python hl_lines="12 19-21"
- {!> ../../../docs_src/request_files/tutorial003_an.py!}
- ```
+### Multiple File Uploads with Additional Metadata { #multiple-file-uploads-with-additional-metadata }
-=== "Python 3.9+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="9 16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
+And the same way as before, you can use `File()` to set additional parameters, even for `UploadFile`:
- ```Python hl_lines="11 18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
-## Recap
+## Recap { #recap }
Use `File`, `bytes`, and `UploadFile` to declare files to be uploaded in the request, sent as form data.
diff --git a/docs/en/docs/tutorial/request-form-models.md b/docs/en/docs/tutorial/request-form-models.md
new file mode 100644
index 0000000000000..2e0f463294555
--- /dev/null
+++ b/docs/en/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Form Models { #form-models }
+
+You can use **Pydantic models** to declare **form fields** in FastAPI.
+
+/// info
+
+To use forms, first install [`python-multipart`](https://github.com/Kludex/python-multipart).
+
+Make sure you create a [virtual environment](../virtual-environments.md), activate it, and then install it, for example:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note
+
+This is supported since FastAPI version `0.113.0`. 🤓
+
+///
+
+## Pydantic Models for Forms { #pydantic-models-for-forms }
+
+You just need to declare a **Pydantic model** with the fields you want to receive as **form fields**, and then declare the parameter as `Form`:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
+
+**FastAPI** will **extract** the data for **each field** from the **form data** in the request and give you the Pydantic model you defined.
+
+## Check the Docs { #check-the-docs }
+
+You can verify it in the docs UI at `/docs`:
+
+
+POST.
+You can declare multiple `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `application/x-www-form-urlencoded` instead of `application/json`.
-!!! warning
- You can declare multiple `Form` parameters in a *path operation*, but you can't also declare `Body` fields that you expect to receive as JSON, as the request will have the body encoded using `application/x-www-form-urlencoded` instead of `application/json`.
+This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
- This is not a limitation of **FastAPI**, it's part of the HTTP protocol.
+///
-## Recap
+## Recap { #recap }
Use `Form` to declare form data input parameters.
diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md
index 2181cfb5ae7bb..d628167ddb153 100644
--- a/docs/en/docs/tutorial/response-model.md
+++ b/docs/en/docs/tutorial/response-model.md
@@ -1,26 +1,10 @@
-# Response Model - Return Type
+# Response Model - Return Type { #response-model-return-type }
You can declare the type used for the response by annotating the *path operation function* **return type**.
You can use **type annotations** the same way you would for input data in function **parameters**, you can use Pydantic models, lists, dictionaries, scalar values like integers, booleans, etc.
-=== "Python 3.10+"
-
- ```Python hl_lines="16 21"
- {!> ../../../docs_src/response_model/tutorial001_01_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="18 23"
- {!> ../../../docs_src/response_model/tutorial001_01.py!}
- ```
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
FastAPI will use this return type to:
@@ -29,13 +13,14 @@ FastAPI will use this return type to:
* Add a **JSON Schema** for the response, in the OpenAPI *path operation*.
* This will be used by the **automatic docs**.
* It will also be used by automatic client code generation tools.
+* **Serialize** the returned data to JSON using Pydantic, which is written in **Rust**, so it will be **much faster**.
But most importantly:
* It will **limit and filter** the output data to what is defined in the return type.
* This is particularly important for **security**, we'll see more of that below.
-## `response_model` Parameter
+## `response_model` Parameter { #response-model-parameter }
There are some cases where you need or want to return some data that is not exactly what the type declares.
@@ -53,37 +38,27 @@ You can use the `response_model` parameter in any of the *path operations*:
* `@app.delete()`
* etc.
-=== "Python 3.10+"
-
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py310.py!}
- ```
-
-=== "Python 3.9+"
+{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *}
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+/// note
-=== "Python 3.6+"
+Notice that `response_model` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body.
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001.py!}
- ```
-
-!!! note
- Notice that `response_model` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body.
+///
`response_model` receives the same type you would declare for a Pydantic model field, so, it can be a Pydantic model, but it can also be, e.g. a `list` of Pydantic models, like `List[Item]`.
FastAPI will use this `response_model` to do all the data documentation, validation, etc. and also to **convert and filter the output data** to its type declaration.
-!!! tip
- If you have strict type checks in your editor, mypy, etc, you can declare the function return type as `Any`.
+/// tip
+
+If you have strict type checks in your editor, mypy, etc, you can declare the function return type as `Any`.
+
+That way you tell the editor that you are intentionally returning anything. But FastAPI will still do the data documentation, validation, filtering, etc. with the `response_model`.
- That way you tell the editor that you are intentionally returning anything. But FastAPI will still do the data documentation, validation, filtering, etc. with the `response_model`.
+///
-### `response_model` Priority
+### `response_model` Priority { #response-model-priority }
If you declare both a return type and a `response_model`, the `response_model` will take priority and be used by FastAPI.
@@ -91,41 +66,33 @@ This way you can add correct type annotations to your functions even when you ar
You can also use `response_model=None` to disable creating a response model for that *path operation*, you might need to do it if you are adding type annotations for things that are not valid Pydantic fields, you will see an example of that in one of the sections below.
-## Return the same input data
+## Return the same input data { #return-the-same-input-data }
Here we are declaring a `UserIn` model, it will contain a plaintext password:
-=== "Python 3.10+"
+{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *}
- ```Python hl_lines="7 9"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+/// info
-=== "Python 3.6+"
+To use `EmailStr`, first install [`email-validator`](https://github.com/JoshData/python-email-validator).
- ```Python hl_lines="9 11"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+Make sure you create a [virtual environment](../virtual-environments.md), activate it, and then install it, for example:
-!!! info
- To use `EmailStr`, first install `email_validator`.
-
- E.g. `pip install email-validator`
- or `pip install pydantic[email]`.
+```console
+$ pip install email-validator
+```
-And we are using this model to declare our input and the same model to declare our output:
+or with:
-=== "Python 3.10+"
+```console
+$ pip install "pydantic[email]"
+```
- ```Python hl_lines="16"
- {!> ../../../docs_src/response_model/tutorial002_py310.py!}
- ```
+///
-=== "Python 3.6+"
+And we are using this model to declare our input and the same model to declare our output:
- ```Python hl_lines="18"
- {!> ../../../docs_src/response_model/tutorial002.py!}
- ```
+{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *}
Now, whenever a browser is creating a user with a password, the API will return the same password in the response.
@@ -133,56 +100,29 @@ In this case, it might not be a problem, because it's the same user sending the
But if we use the same model for another *path operation*, we could be sending our user's passwords to every client.
-!!! danger
- Never store the plain password of a user or send it in a response like this, unless you know all the caveats and you know what you are doing.
+/// danger
-## Add an output model
-
-We can instead create an input model with the plaintext password and an output model without it:
+Never store the plain password of a user or send it in a response like this, unless you know all the caveats and you know what you are doing.
-=== "Python 3.10+"
+///
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+## Add an output model { #add-an-output-model }
-=== "Python 3.6+"
+We can instead create an input model with the plaintext password and an output model without it:
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *}
Here, even though our *path operation function* is returning the same input user that contains the password:
-=== "Python 3.10+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *}
...we declared the `response_model` to be our model `UserOut`, that doesn't include the password:
-=== "Python 3.10+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *}
So, **FastAPI** will take care of filtering out all the data that is not declared in the output model (using Pydantic).
-### `response_model` or Return Type
+### `response_model` or Return Type { #response-model-or-return-type }
In this case, because the two models are different, if we annotated the function return type as `UserOut`, the editor and tools would complain that we are returning an invalid type, as those are different classes.
@@ -190,11 +130,11 @@ That's why in this example we have to declare it in the `response_model` paramet
...but continue reading below to see how to overcome that.
-## Return Type and Data Filtering
+## Return Type and Data Filtering { #return-type-and-data-filtering }
-Let's continue from the previous example. We wanted to **annotate the function with one type** but return something that includes **more data**.
+Let's continue from the previous example. We wanted to **annotate the function with one type**, but we wanted to be able to return from the function something that actually includes **more data**.
-We want FastAPI to keep **filtering** the data using the response model.
+We want FastAPI to keep **filtering** the data using the response model. So that even though the function returns more data, the response will only include the fields declared in the response model.
In the previous example, because the classes were different, we had to use the `response_model` parameter. But that also means that we don't get the support from the editor and tools checking the function return type.
@@ -202,23 +142,13 @@ But in most of the cases where we need to do something like this, we want the mo
And in those cases, we can use classes and inheritance to take advantage of function **type annotations** to get better support in the editor and tools, and still get the FastAPI **data filtering**.
-=== "Python 3.10+"
-
- ```Python hl_lines="7-10 13-14 18"
- {!> ../../../docs_src/response_model/tutorial003_01_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="9-13 15-16 20"
- {!> ../../../docs_src/response_model/tutorial003_01.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *}
With this, we get tooling support, from editors and mypy as this code is correct in terms of types, but we also get the data filtering from FastAPI.
How does this work? Let's check that out. 🤓
-### Type Annotations and Tooling
+### Type Annotations and Tooling { #type-annotations-and-tooling }
First let's see how editors, mypy and other tools would see this.
@@ -228,7 +158,7 @@ We annotate the function return type as `BaseUser`, but we are actually returnin
The editor, mypy, and other tools won't complain about this because, in typing terms, `UserIn` is a subclass of `BaseUser`, which means it's a *valid* type when what is expected is anything that is a `BaseUser`.
-### FastAPI Data Filtering
+### FastAPI Data Filtering { #fastapi-data-filtering }
Now, for FastAPI, it will see the return type and make sure that what you return includes **only** the fields that are declared in the type.
@@ -236,7 +166,7 @@ FastAPI does several things internally with Pydantic to make sure that those sam
This way, you can get the best of both worlds: type annotations with **tooling support** and **data filtering**.
-## See it in the docs
+## See it in the docs { #see-it-in-the-docs }
When you see the automatic docs, you can check that the input model and output model will both have their own JSON Schema:
@@ -246,53 +176,39 @@ And both models will be used for the interactive API documentation:
-## Other Return Type Annotations
+## Other Return Type Annotations { #other-return-type-annotations }
There might be cases where you return something that is not a valid Pydantic field and you annotate it in the function, only to get the support provided by tooling (the editor, mypy, etc).
-### Return a Response Directly
+### Return a Response Directly { #return-a-response-directly }
-The most common case would be [returning a Response directly as explained later in the advanced docs](../advanced/response-directly.md){.internal-link target=_blank}.
+The most common case would be [returning a Response directly as explained later in the advanced docs](../advanced/response-directly.md).
-```Python hl_lines="8 10-11"
-{!> ../../../docs_src/response_model/tutorial003_02.py!}
-```
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
-This simple case is handled automatically by FastAPI because the return type annotation is the class (or a subclass) of `Response`.
+This simple case is handled automatically by FastAPI because the return type annotation is the class (or a subclass of) `Response`.
And tools will also be happy because both `RedirectResponse` and `JSONResponse` are subclasses of `Response`, so the type annotation is correct.
-### Annotate a Response Subclass
+### Annotate a Response Subclass { #annotate-a-response-subclass }
You can also use a subclass of `Response` in the type annotation:
-```Python hl_lines="8-9"
-{!> ../../../docs_src/response_model/tutorial003_03.py!}
-```
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
This will also work because `RedirectResponse` is a subclass of `Response`, and FastAPI will automatically handle this simple case.
-### Invalid Return Type Annotations
+### Invalid Return Type Annotations { #invalid-return-type-annotations }
But when you return some other arbitrary object that is not a valid Pydantic type (e.g. a database object) and you annotate it like that in the function, FastAPI will try to create a Pydantic response model from that type annotation, and will fail.
-The same would happen if you had something like a union between different types where one or more of them are not valid Pydantic types, for example this would fail 💥:
-
-=== "Python 3.10+"
+The same would happen if you had something like a union between different types where one or more of them are not valid Pydantic types, for example this would fail 💥:
- ```Python hl_lines="8"
- {!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/response_model/tutorial003_04.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
...this fails because the type annotation is not a Pydantic type and is not just a single `Response` class or subclass, it's a union (any of the two) between a `Response` and a `dict`.
-### Disable Response Model
+### Disable Response Model { #disable-response-model }
Continuing from the example above, you might not want to have the default data validation, documentation, filtering, etc. that is performed by FastAPI.
@@ -300,71 +216,29 @@ But you might want to still keep the return type annotation in the function to g
In this case, you can disable the response model generation by setting `response_model=None`:
-=== "Python 3.10+"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/response_model/tutorial003_05.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}
This will make FastAPI skip the response model generation and that way you can have any return type annotations you need without it affecting your FastAPI application. 🤓
-## Response Model encoding parameters
+## Response Model encoding parameters { #response-model-encoding-parameters }
Your response model could have default values, like:
-=== "Python 3.10+"
-
- ```Python hl_lines="9 11-12"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}
* `description: Union[str, None] = None` (or `str | None = None` in Python 3.10) has a default of `None`.
* `tax: float = 10.5` has a default of `10.5`.
-* `tags: List[str] = []` as a default of an empty list: `[]`.
+* `tags: List[str] = []` has a default of an empty list: `[]`.
but you might want to omit them from the result if they were not actually stored.
For example, if you have models with many optional attributes in a NoSQL database, but you don't want to send very long JSON responses full of default values.
-### Use the `response_model_exclude_unset` parameter
+### Use the `response_model_exclude_unset` parameter { #use-the-response-model-exclude-unset-parameter }
You can set the *path operation decorator* parameter `response_model_exclude_unset=True`:
-=== "Python 3.10+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}
and those default values won't be included in the response, only the values actually set.
@@ -377,18 +251,18 @@ So, if you send a request to that *path operation* for the item with ID `foo`, t
}
```
-!!! info
- FastAPI uses Pydantic model's `.dict()` with its `exclude_unset` parameter to achieve this.
+/// info
+
+You can also use:
-!!! info
- You can also use:
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+as described in [the Pydantic docs](https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict) for `exclude_defaults` and `exclude_none`.
- as described in the Pydantic docs for `exclude_defaults` and `exclude_none`.
+///
-#### Data with values for fields with defaults
+#### Data with values for fields with defaults { #data-with-values-for-fields-with-defaults }
But if your data has values for the model's fields with default values, like the item with ID `bar`:
@@ -403,7 +277,7 @@ But if your data has values for the model's fields with default values, like the
they will be included in the response.
-#### Data with the same values as the defaults
+#### Data with the same values as the defaults { #data-with-the-same-values-as-the-defaults }
If the data has the same values as the default ones, like the item with ID `baz`:
@@ -421,12 +295,15 @@ FastAPI is smart enough (actually, Pydantic is smart enough) to realize that, ev
So, they will be included in the JSON response.
-!!! tip
- Notice that the default values can be anything, not only `None`.
+/// tip
- They can be a list (`[]`), a `float` of `10.5`, etc.
+Notice that the default values can be anything, not only `None`.
-### `response_model_include` and `response_model_exclude`
+They can be a list (`[]`), a `float` of `10.5`, etc.
+
+///
+
+### `response_model_include` and `response_model_exclude` { #response-model-include-and-response-model-exclude }
You can also use the *path operation decorator* parameters `response_model_include` and `response_model_exclude`.
@@ -434,47 +311,33 @@ They take a `set` of `str` with the name of the attributes to include (omitting
This can be used as a quick shortcut if you have only one Pydantic model and want to remove some data from the output.
-!!! tip
- But it is still recommended to use the ideas above, using multiple classes, instead of these parameters.
-
- This is because the JSON Schema generated in your app's OpenAPI (and the docs) will still be the one for the complete model, even if you use `response_model_include` or `response_model_exclude` to omit some attributes.
+/// tip
- This also applies to `response_model_by_alias` that works similarly.
+But it is still recommended to use the ideas above, using multiple classes, instead of these parameters.
-=== "Python 3.10+"
+This is because the JSON Schema generated in your app's OpenAPI (and the docs) will still be the one for the complete model, even if you use `response_model_include` or `response_model_exclude` to omit some attributes.
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial005_py310.py!}
- ```
+This also applies to `response_model_by_alias` that works similarly.
-=== "Python 3.6+"
+///
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial005.py!}
- ```
+{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}
-!!! tip
- The syntax `{"name", "description"}` creates a `set` with those two values.
+/// tip
- It is equivalent to `set(["name", "description"])`.
+The syntax `{"name", "description"}` creates a `set` with those two values.
-#### Using `list`s instead of `set`s
+It is equivalent to `set(["name", "description"])`.
-If you forget to use a `set` and use a `list` or `tuple` instead, FastAPI will still convert it to a `set` and it will work correctly:
-
-=== "Python 3.10+"
+///
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial006_py310.py!}
- ```
+#### Using `list`s instead of `set`s { #using-lists-instead-of-sets }
-=== "Python 3.6+"
+If you forget to use a `set` and use a `list` or `tuple` instead, FastAPI will still convert it to a `set` and it will work correctly:
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial006.py!}
- ```
+{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}
-## Recap
+## Recap { #recap }
Use the *path operation decorator's* parameter `response_model` to define response models and especially to ensure private data is filtered out.
diff --git a/docs/en/docs/tutorial/response-status-code.md b/docs/en/docs/tutorial/response-status-code.md
index 646378aa105ac..dcadaa36d816e 100644
--- a/docs/en/docs/tutorial/response-status-code.md
+++ b/docs/en/docs/tutorial/response-status-code.md
@@ -1,4 +1,4 @@
-# Response Status Code
+# Response Status Code { #response-status-code }
The same way you can specify a response model, you can also declare the HTTP status code used for the response with the parameter `status_code` in any of the *path operations*:
@@ -8,17 +8,21 @@ The same way you can specify a response model, you can also declare the HTTP sta
* `@app.delete()`
* etc.
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
-!!! note
- Notice that `status_code` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body.
+/// note
+
+Notice that `status_code` is a parameter of the "decorator" method (`get`, `post`, etc). Not of your *path operation function*, like all the parameters and body.
+
+///
The `status_code` parameter receives a number with the HTTP status code.
-!!! info
- `status_code` can alternatively also receive an `IntEnum`, such as Python's `http.HTTPStatus`.
+/// info
+
+`status_code` can alternatively also receive an `IntEnum`, such as Python's [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus).
+
+///
It will:
@@ -27,15 +31,21 @@ It will:
-!!! note
- Some response codes (see the next section) indicate that the response does not have a body.
+/// note
+
+Some response codes (see the next section) indicate that the response does not have a body.
+
+FastAPI knows this, and will produce OpenAPI docs that state there is no response body.
- FastAPI knows this, and will produce OpenAPI docs that state there is no response body.
+///
-## About HTTP status codes
+## About HTTP status codes { #about-http-status-codes }
-!!! note
- If you already know what HTTP status codes are, skip to the next section.
+/// note
+
+If you already know what HTTP status codes are, skip to the next section.
+
+///
In HTTP, you send a numeric status code of 3 digits as part of the response.
@@ -43,27 +53,28 @@ These status codes have a name associated to recognize them, but the important p
In short:
-* `100` and above are for "Information". You rarely use them directly. Responses with these status codes cannot have a body.
-* **`200`** and above are for "Successful" responses. These are the ones you would use the most.
+* `100 - 199` are for "Information". You rarely use them directly. Responses with these status codes cannot have a body.
+* **`200 - 299`** are for "Successful" responses. These are the ones you would use the most.
* `200` is the default status code, which means everything was "OK".
* Another example would be `201`, "Created". It is commonly used after creating a new record in the database.
* A special case is `204`, "No Content". This response is used when there is no content to return to the client, and so the response must not have a body.
-* **`300`** and above are for "Redirection". Responses with these status codes may or may not have a body, except for `304`, "Not Modified", which must not have one.
-* **`400`** and above are for "Client error" responses. These are the second type you would probably use the most.
+* **`300 - 399`** are for "Redirection". Responses with these status codes may or may not have a body, except for `304`, "Not Modified", which must not have one.
+* **`400 - 499`** are for "Client error" responses. These are the second type you would probably use the most.
* An example is `404`, for a "Not Found" response.
* For generic errors from the client, you can just use `400`.
-* `500` and above are for server errors. You almost never use them directly. When something goes wrong at some part in your application code, or server, it will automatically return one of these status codes.
+* `500 - 599` are for server errors. You almost never use them directly. When something goes wrong at some part in your application code, or server, it will automatically return one of these status codes.
+
+/// tip
-!!! tip
- To know more about each status code and which code is for what, check the MDN documentation about HTTP status codes.
+To know more about each status code and which code is for what, check the [MDN documentation about HTTP status codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status).
-## Shortcut to remember the names
+///
+
+## Shortcut to remember the names { #shortcut-to-remember-the-names }
Let's see the previous example again:
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
`201` is the status code for "Created".
@@ -71,19 +82,20 @@ But you don't have to memorize what each of these codes mean.
You can use the convenience variables from `fastapi.status`.
-```Python hl_lines="1 6"
-{!../../../docs_src/response_status_code/tutorial002.py!}
-```
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
They are just a convenience, they hold the same number, but that way you can use the editor's autocomplete to find them:
-!!! note "Technical Details"
- You could also use `from starlette import status`.
+/// note | Technical Details
+
+You could also use `from starlette import status`.
+
+**FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette.
- **FastAPI** provides the same `starlette.status` as `fastapi.status` just as a convenience for you, the developer. But it comes directly from Starlette.
+///
-## Changing the default
+## Changing the default { #changing-the-default }
-Later, in the [Advanced User Guide](../advanced/response-change-status-code.md){.internal-link target=_blank}, you will see how to return a different status code than the default you are declaring here.
+Later, in the [Advanced User Guide](../advanced/response-change-status-code.md), you will see how to return a different status code than the default you are declaring here.
diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md
index 9eeb3f1f29351..2b5fe11c0bdbd 100644
--- a/docs/en/docs/tutorial/schema-extra-example.md
+++ b/docs/en/docs/tutorial/schema-extra-example.md
@@ -1,80 +1,46 @@
-# Declare Request Example Data
+# Declare Request Example Data { #declare-request-example-data }
You can declare examples of the data your app can receive.
Here are several ways to do it.
-## Extra JSON Schema data in Pydantic models
+## Extra JSON Schema data in Pydantic models { #extra-json-schema-data-in-pydantic-models }
You can declare `examples` for a Pydantic model that will be added to the generated JSON Schema.
-=== "Python 3.10+ Pydantic v2"
-
- ```Python hl_lines="13-24"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
- ```
-
-=== "Python 3.10+ Pydantic v1"
-
- ```Python hl_lines="13-23"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!}
- ```
-
-=== "Python 3.6+ Pydantic v2"
-
- ```Python hl_lines="15-26"
- {!> ../../../docs_src/schema_extra_example/tutorial001.py!}
- ```
-
-=== "Python 3.6+ Pydantic v1"
-
- ```Python hl_lines="15-25"
- {!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!}
- ```
+{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}
That extra info will be added as-is to the output **JSON Schema** for that model, and it will be used in the API docs.
-=== "Pydantic v2"
+You can use the attribute `model_config` that takes a `dict` as described in [Pydantic's docs: Configuration](https://docs.pydantic.dev/latest/api/config/).
- In Pydantic version 2, you would use the attribute `model_config`, that takes a `dict` as described in Pydantic's docs: Model Config.
+You can set `"json_schema_extra"` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`.
- You can set `"json_schema_extra"` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`.
+/// tip
-=== "Pydantic v1"
+You could use the same technique to extend the JSON Schema and add your own custom extra info.
- In Pydantic version 1, you would use an internal class `Config` and `schema_extra`, as described in Pydantic's docs: Schema customization.
+For example you could use it to add metadata for a frontend user interface, etc.
- You can set `schema_extra` with a `dict` containing any additional data you would like to show up in the generated JSON Schema, including `examples`.
+///
-!!! tip
- You could use the same technique to extend the JSON Schema and add your own custom extra info.
+/// info
- For example you could use it to add metadata for a frontend user interface, etc.
+OpenAPI 3.1.0 (used since FastAPI 0.99.0) added support for `examples`, which is part of the **JSON Schema** standard.
-!!! info
- OpenAPI 3.1.0 (used since FastAPI 0.99.0) added support for `examples`, which is part of the **JSON Schema** standard.
+Before that, it only supported the keyword `example` with a single example. That is still supported by OpenAPI 3.1.0, but is deprecated and is not part of the JSON Schema standard. So you are encouraged to migrate `example` to `examples`. 🤓
- Before that, it only supported the keyword `example` with a single example. That is still supported by OpenAPI 3.1.0, but is deprecated and is not part of the JSON Schema standard. So you are encouraged to migrate `example` to `examples`. 🤓
+You can read more at the end of this page.
- You can read more at the end of this page.
+///
-## `Field` additional arguments
+## `Field` additional arguments { #field-additional-arguments }
When using `Field()` with Pydantic models, you can also declare additional `examples`:
-=== "Python 3.10+"
-
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
- ```
-
-=== "Python 3.6+"
+{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
-
-## `examples` in JSON Schema - OpenAPI
+## `examples` in JSON Schema - OpenAPI { #examples-in-json-schema-openapi }
When using any of:
@@ -88,97 +54,29 @@ When using any of:
you can also declare a group of `examples` with additional information that will be added to their **JSON Schemas** inside of **OpenAPI**.
-### `Body` with `examples`
+### `Body` with `examples` { #body-with-examples }
Here we pass `examples` containing one example of the data expected in `Body()`:
-=== "Python 3.10+"
-
- ```Python hl_lines="22-29"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
- ```
-
-=== "Python 3.9+"
+{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *}
- ```Python hl_lines="22-29"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="23-30"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="18-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="20-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
- ```
-
-### Example in the docs UI
+### Example in the docs UI { #example-in-the-docs-ui }
With any of the methods above it would look like this in the `/docs`:
-### `Body` with multiple `examples`
+### `Body` with multiple `examples` { #body-with-multiple-examples }
You can of course also pass multiple `examples`:
-=== "Python 3.10+"
-
- ```Python hl_lines="23-38"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="23-38"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="24-39"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="19-34"
- {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="21-36"
- {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
- ```
+{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *}
When you do this, the examples will be part of the internal **JSON Schema** for that body data.
-Nevertheless, at the time of writing this, Swagger UI, the tool in charge of showing the docs UI, doesn't support showing multiple examples for the data in **JSON Schema**. But read below for a workaround.
+Nevertheless, at the time of writing this, Swagger UI, the tool in charge of showing the docs UI, doesn't support showing multiple examples for the data in **JSON Schema**. But read below for a workaround.
-### OpenAPI-specific `examples`
+### OpenAPI-specific `examples` { #openapi-specific-examples }
Since before **JSON Schema** supported `examples` OpenAPI had support for a different field also called `examples`.
@@ -190,7 +88,7 @@ The shape of this OpenAPI-specific field `examples` is a `dict` with **multiple
This doesn't go inside of each JSON Schema contained in OpenAPI, this goes outside, in the *path operation* directly.
-### Using the `openapi_examples` Parameter
+### Using the `openapi_examples` Parameter { #using-the-openapi-examples-parameter }
You can declare the OpenAPI-specific `examples` in FastAPI with the parameter `openapi_examples` for:
@@ -213,84 +111,59 @@ Each specific example `dict` in the `examples` can contain:
You can use it like this:
-=== "Python 3.10+"
-
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.6+"
+{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *}
- ```Python hl_lines="24-50"
- {!> ../../../docs_src/schema_extra_example/tutorial005_an.py!}
- ```
+### OpenAPI Examples in the Docs UI { #openapi-examples-in-the-docs-ui }
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="19-45"
- {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!}
- ```
+With `openapi_examples` added to `Body()` the `/docs` would look like:
-=== "Python 3.6+ non-Annotated"
+
- !!! tip
- Prefer to use the `Annotated` version if possible.
+## Technical Details { #technical-details }
- ```Python hl_lines="21-47"
- {!> ../../../docs_src/schema_extra_example/tutorial005.py!}
- ```
+/// tip
-### OpenAPI Examples in the Docs UI
+If you are already using **FastAPI** version **0.99.0 or above**, you can probably **skip** these details.
-With `openapi_examples` added to `Body()` the `/docs` would look like:
+They are more relevant for older versions, before OpenAPI 3.1.0 was available.
-
+You can consider this a brief OpenAPI and JSON Schema **history lesson**. 🤓
-## Technical Details
+///
-!!! tip
- If you are already using **FastAPI** version **0.99.0 or above**, you can probably **skip** these details.
+/// warning
- They are more relevant for older versions, before OpenAPI 3.1.0 was available.
+These are very technical details about the standards **JSON Schema** and **OpenAPI**.
- You can consider this a brief OpenAPI and JSON Schema **history lesson**. 🤓
+If the ideas above already work for you, that might be enough, and you probably don't need these details, feel free to skip them.
-!!! warning
- These are very technical details about the standards **JSON Schema** and **OpenAPI**.
-
- If the ideas above already work for you, that might be enough, and you probably don't need these details, feel free to skip them.
+///
Before OpenAPI 3.1.0, OpenAPI used an older and modified version of **JSON Schema**.
-JSON Schema didn't have `examples`, so OpenAPI added it's own `example` field to its own modified version.
+JSON Schema didn't have `examples`, so OpenAPI added its own `example` field to its own modified version.
OpenAPI also added `example` and `examples` fields to other parts of the specification:
-* `Parameter Object` (in the specification) that was used by FastAPI's:
+* [`Parameter Object` (in the specification)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object) that was used by FastAPI's:
* `Path()`
* `Query()`
* `Header()`
* `Cookie()`
-* `Request Body Object`, in the field `content`, on the `Media Type Object` (in the specification) that was used by FastAPI's:
+* [`Request Body Object`, in the field `content`, on the `Media Type Object` (in the specification)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object) that was used by FastAPI's:
* `Body()`
* `File()`
* `Form()`
-!!! info
- This old OpenAPI-specific `examples` parameter is now `openapi_examples` since FastAPI `0.103.0`.
+/// info
+
+This old OpenAPI-specific `examples` parameter is now `openapi_examples` since FastAPI `0.103.0`.
+
+///
-### JSON Schema's `examples` field
+### JSON Schema's `examples` field { #json-schemas-examples-field }
-But then JSON Schema added an `examples` field to a new version of the specification.
+But then JSON Schema added an [`examples`](https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.9.5) field to a new version of the specification.
And then the new OpenAPI 3.1.0 was based on the latest version (JSON Schema 2020-12) that included this new field `examples`.
@@ -298,14 +171,17 @@ And now this new `examples` field takes precedence over the old single (and cust
This new `examples` field in JSON Schema is **just a `list`** of examples, not a dict with extra metadata as in the other places in OpenAPI (described above).
-!!! info
- Even after OpenAPI 3.1.0 was released with this new simpler integration with JSON Schema, for a while, Swagger UI, the tool that provides the automatic docs, didn't support OpenAPI 3.1.0 (it does since version 5.0.0 🎉).
+/// info
+
+Even after OpenAPI 3.1.0 was released with this new simpler integration with JSON Schema, for a while, Swagger UI, the tool that provides the automatic docs, didn't support OpenAPI 3.1.0 (it does since version 5.0.0 🎉).
+
+Because of that, versions of FastAPI previous to 0.99.0 still used versions of OpenAPI lower than 3.1.0.
- Because of that, versions of FastAPI previous to 0.99.0 still used versions of OpenAPI lower than 3.1.0.
+///
-### Pydantic and FastAPI `examples`
+### Pydantic and FastAPI `examples` { #pydantic-and-fastapi-examples }
-When you add `examples` inside of a Pydantic model, using `schema_extra` or `Field(examples=["something"])` that example is added to the **JSON Schema** for that Pydantic model.
+When you add `examples` inside a Pydantic model, using `schema_extra` or `Field(examples=["something"])` that example is added to the **JSON Schema** for that Pydantic model.
And that **JSON Schema** of the Pydantic model is included in the **OpenAPI** of your API, and then it's used in the docs UI.
@@ -313,13 +189,13 @@ In versions of FastAPI before 0.99.0 (0.99.0 and above use the newer OpenAPI 3.1
But now that FastAPI 0.99.0 and above uses OpenAPI 3.1.0, that uses JSON Schema 2020-12, and Swagger UI 5.0.0 and above, everything is more consistent and the examples are included in JSON Schema.
-### Swagger UI and OpenAPI-specific `examples`
+### Swagger UI and OpenAPI-specific `examples` { #swagger-ui-and-openapi-specific-examples }
Now, as Swagger UI didn't support multiple JSON Schema examples (as of 2023-08-26), users didn't have a way to show multiple examples in the docs.
To solve that, FastAPI `0.103.0` **added support** for declaring the same old **OpenAPI-specific** `examples` field with the new parameter `openapi_examples`. 🤓
-### Summary
+### Summary { #summary }
I used to say I didn't like history that much... and look at me now giving "tech history" lessons. 😅
diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md
index 5765cf2d62611..cf19f7dbdc9e4 100644
--- a/docs/en/docs/tutorial/security/first-steps.md
+++ b/docs/en/docs/tutorial/security/first-steps.md
@@ -1,4 +1,4 @@
-# Security - First Steps
+# Security - First Steps { #security-first-steps }
Let's imagine that you have your **backend** API in some domain.
@@ -12,76 +12,71 @@ But let's save you the time of reading the full long specification just to find
Let's use the tools provided by **FastAPI** to handle security.
-## How it looks
+## How it looks { #how-it-looks }
Let's first just use the code and see how it works, and then we'll come back to understand what's happening.
-## Create `main.py`
+## Create `main.py` { #create-main-py }
Copy the example in a file `main.py`:
-=== "Python 3.9+"
+{* ../../docs_src/security/tutorial001_an_py310.py *}
- ```Python
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+## Run it { #run-it }
-=== "Python 3.6+"
+/// info
- ```Python
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+The [`python-multipart`](https://github.com/Kludex/python-multipart) package is automatically installed with **FastAPI** when you run the `pip install "fastapi[standard]"` command.
-=== "Python 3.6+ non-Annotated"
+However, if you use the `pip install fastapi` command, the `python-multipart` package is not included by default.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+To install it manually, make sure you create a [virtual environment](../../virtual-environments.md), activate it, and then install it with:
- ```Python
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
-
-
-## Run it
-
-!!! info
- First install `python-multipart`.
+```console
+$ pip install python-multipart
+```
- E.g. `pip install python-multipart`.
+This is because **OAuth2** uses "form data" for sending the `username` and `password`.
- This is because **OAuth2** uses "form data" for sending the `username` and `password`.
+///
Run the example with:
-!!! check "Authorize button!"
- You already have a shiny new "Authorize" button.
+/// check | Authorize button!
+
+You already have a shiny new "Authorize" button.
- And your *path operation* has a little lock in the top-right corner that you can click.
+And your *path operation* has a little lock in the top-right corner that you can click.
+
+///
And if you click it, you have a little authorization form to type a `username` and `password` (and other optional fields):
-!!! note
- It doesn't matter what you type in the form, it won't work yet. But we'll get there.
+/// note
+
+It doesn't matter what you type in the form, it won't work yet. But we'll get there.
+
+///
This is of course not the frontend for the final users, but it's a great automatic tool to document interactively all your API.
@@ -91,7 +86,7 @@ It can be used by third party applications and systems.
And it can also be used by yourself, to debug, check and test the same application.
-## The `password` flow
+## The `password` flow { #the-password-flow }
Now let's go back a bit and understand what is all that.
@@ -117,59 +112,49 @@ So, let's review it from that simplified point of view:
* So, to authenticate with our API, it sends a header `Authorization` with a value of `Bearer ` plus the token.
* If the token contains `foobar`, the content of the `Authorization` header would be: `Bearer foobar`.
-## **FastAPI**'s `OAuth2PasswordBearer`
+## **FastAPI**'s `OAuth2PasswordBearer` { #fastapis-oauth2passwordbearer }
**FastAPI** provides several tools, at different levels of abstraction, to implement these security features.
In this example we are going to use **OAuth2**, with the **Password** flow, using a **Bearer** token. We do that using the `OAuth2PasswordBearer` class.
-!!! info
- A "bearer" token is not the only option.
+/// info
- But it's the best one for our use case.
+A "bearer" token is not the only option.
- And it might be the best for most use cases, unless you are an OAuth2 expert and know exactly why there's another option that suits better your needs.
-
- In that case, **FastAPI** also provides you with the tools to build it.
-
-When we create an instance of the `OAuth2PasswordBearer` class we pass in the `tokenUrl` parameter. This parameter contains the URL that the client (the frontend running in the user's browser) will use to send the `username` and `password` in order to get a token.
+But it's the best one for our use case.
-=== "Python 3.9+"
+And it might be the best for most use cases, unless you are an OAuth2 expert and know exactly why there's another option that better suits your needs.
- ```Python hl_lines="8"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+In that case, **FastAPI** also provides you with the tools to build it.
-=== "Python 3.6+"
+///
- ```Python hl_lines="7"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+When we create an instance of the `OAuth2PasswordBearer` class we pass in the `tokenUrl` parameter. This parameter contains the URL that the client (the frontend running in the user's browser) will use to send the `username` and `password` in order to get a token.
-=== "Python 3.6+ non-Annotated"
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="6"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+Here `tokenUrl="token"` refers to a relative URL `token` that we haven't created yet. As it's a relative URL, it's equivalent to `./token`.
-!!! tip
- Here `tokenUrl="token"` refers to a relative URL `token` that we haven't created yet. As it's a relative URL, it's equivalent to `./token`.
+Because we are using a relative URL, if your API was located at `https://example.com/`, then it would refer to `https://example.com/token`. But if your API was located at `https://example.com/api/v1/`, then it would refer to `https://example.com/api/v1/token`.
- Because we are using a relative URL, if your API was located at `https://example.com/`, then it would refer to `https://example.com/token`. But if your API was located at `https://example.com/api/v1/`, then it would refer to `https://example.com/api/v1/token`.
+Using a relative URL is important to make sure your application keeps working even in an advanced use case like [Behind a Proxy](../../advanced/behind-a-proxy.md).
- Using a relative URL is important to make sure your application keeps working even in an advanced use case like [Behind a Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+///
This parameter doesn't create that endpoint / *path operation*, but declares that the URL `/token` will be the one that the client should use to get the token. That information is used in OpenAPI, and then in the interactive API documentation systems.
We will soon also create the actual path operation.
-!!! info
- If you are a very strict "Pythonista" you might dislike the style of the parameter name `tokenUrl` instead of `token_url`.
+/// info
+
+If you are a very strict "Pythonista" you might dislike the style of the parameter name `tokenUrl` instead of `token_url`.
+
+That's because it is using the same name as in the OpenAPI spec. So that if you need to investigate more about any of these security schemes you can just copy and paste it to find more information about it.
- That's because it is using the same name as in the OpenAPI spec. So that if you need to investigate more about any of these security schemes you can just copy and paste it to find more information about it.
+///
The `oauth2_scheme` variable is an instance of `OAuth2PasswordBearer`, but it is also a "callable".
@@ -181,41 +166,25 @@ oauth2_scheme(some, parameters)
So, it can be used with `Depends`.
-### Use it
+### Use it { #use-it }
Now you can pass that `oauth2_scheme` in a dependency with `Depends`.
-=== "Python 3.9+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
This dependency will provide a `str` that is assigned to the parameter `token` of the *path operation function*.
**FastAPI** will know that it can use this dependency to define a "security scheme" in the OpenAPI schema (and the automatic API docs).
-!!! info "Technical Details"
- **FastAPI** will know that it can use the class `OAuth2PasswordBearer` (declared in a dependency) to define the security scheme in OpenAPI because it inherits from `fastapi.security.oauth2.OAuth2`, which in turn inherits from `fastapi.security.base.SecurityBase`.
+/// info | Technical Details
+
+**FastAPI** will know that it can use the class `OAuth2PasswordBearer` (declared in a dependency) to define the security scheme in OpenAPI because it inherits from `fastapi.security.oauth2.OAuth2`, which in turn inherits from `fastapi.security.base.SecurityBase`.
+
+All the security utilities that integrate with OpenAPI (and the automatic API docs) inherit from `SecurityBase`, that's how **FastAPI** can know how to integrate them in OpenAPI.
- All the security utilities that integrate with OpenAPI (and the automatic API docs) inherit from `SecurityBase`, that's how **FastAPI** can know how to integrate them in OpenAPI.
+///
-## What it does
+## What it does { #what-it-does }
It will go and look in the request for that `Authorization` header, check if the value is `Bearer ` plus some token, and will return the token as a `str`.
@@ -229,6 +198,6 @@ You can try it already in the interactive docs:
We are not verifying the validity of the token yet, but that's a start already.
-## Recap
+## Recap { #recap }
So, in just 3 or 4 extra lines, you already have some primitive form of security.
diff --git a/docs/en/docs/tutorial/security/get-current-user.md b/docs/en/docs/tutorial/security/get-current-user.md
index 1a8c5d9a8d8fd..2eb80341f9759 100644
--- a/docs/en/docs/tutorial/security/get-current-user.md
+++ b/docs/en/docs/tutorial/security/get-current-user.md
@@ -1,75 +1,22 @@
-# Get Current User
+# Get Current User { #get-current-user }
In the previous chapter the security system (which is based on the dependency injection system) was giving the *path operation function* a `token` as a `str`:
-=== "Python 3.9+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="11"
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
But that is still not that useful.
Let's make it give us the current user.
-## Create a user model
+## Create a user model { #create-a-user-model }
First, let's create a Pydantic user model.
The same way we use Pydantic to declare bodies, we can use it anywhere else:
-=== "Python 3.10+"
-
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="5 13-17"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="3 10-14"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
+{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *}
- ```Python hl_lines="5 12-16"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
-
-## Create a `get_current_user` dependency
+## Create a `get_current_user` dependency { #create-a-get-current-user-dependency }
Let's create a dependency `get_current_user`.
@@ -79,137 +26,41 @@ Remember that dependencies can have sub-dependencies?
The same as we were doing before in the *path operation* directly, our new dependency `get_current_user` will receive a `token` as a `str` from the sub-dependency `oauth2_scheme`:
-=== "Python 3.10+"
-
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="26"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
+{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *}
- ```Python hl_lines="23"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="25"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
-
-## Get the user
+## Get the user { #get-the-user }
`get_current_user` will use a (fake) utility function we created, that takes a token as a `str` and returns our Pydantic `User` model:
-=== "Python 3.10+"
-
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
+{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *}
-=== "Python 3.6+"
-
- ```Python hl_lines="20-23 27-28"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="17-20 24-25"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="19-22 26-27"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
-
-## Inject the current user
+## Inject the current user { #inject-the-current-user }
So now we can use the same `Depends` with our `get_current_user` in the *path operation*:
-=== "Python 3.10+"
-
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="32"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
+{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *}
- ```Python hl_lines="29"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
+Notice that we declare the type of `current_user` as the Pydantic model `User`.
-=== "Python 3.6+ non-Annotated"
+This will help us inside of the function with all the completion and type checks.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// tip
- ```Python hl_lines="31"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+You might remember that request bodies are also declared with Pydantic models.
-Notice that we declare the type of `current_user` as the Pydantic model `User`.
+Here **FastAPI** won't get confused because you are using `Depends`.
-This will help us inside of the function with all the completion and type checks.
+///
-!!! tip
- You might remember that request bodies are also declared with Pydantic models.
+/// check
- Here **FastAPI** won't get confused because you are using `Depends`.
+The way this dependency system is designed allows us to have different dependencies (different "dependables") that all return a `User` model.
-!!! check
- The way this dependency system is designed allows us to have different dependencies (different "dependables") that all return a `User` model.
+We are not restricted to having only one dependency that can return that type of data.
- We are not restricted to having only one dependency that can return that type of data.
+///
-## Other models
+## Other models { #other-models }
You can now get the current user directly in the *path operation functions* and deal with the security mechanisms at the **Dependency Injection** level, using `Depends`.
@@ -225,9 +76,9 @@ You actually don't have users that log in to your application but robots, bots,
Just use any kind of model, any kind of class, any kind of database that you need for your application. **FastAPI** has you covered with the dependency injection system.
-## Code size
+## Code size { #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.
@@ -237,47 +88,13 @@ And you can make it as complex as you want. And still, have it written only once
But you can have thousands of endpoints (*path operations*) using the same security system.
-And all of them (or any portion of them that you want) can take the advantage of re-using these dependencies or any other dependencies you create.
+And all of them (or any portion of them that you want) can take advantage of re-using these dependencies or any other dependencies you create.
And all these thousands of *path operations* can be as small as 3 lines:
-=== "Python 3.10+"
-
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="31-33"
- {!> ../../../docs_src/security/tutorial002_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="28-30"
- {!> ../../../docs_src/security/tutorial002_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="30-32"
- {!> ../../../docs_src/security/tutorial002.py!}
- ```
+{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *}
-## Recap
+## Recap { #recap }
You can now get the current user directly in your *path operation function*.
diff --git a/docs/en/docs/tutorial/security/index.md b/docs/en/docs/tutorial/security/index.md
index 659a94dc30179..6f460d627fd30 100644
--- a/docs/en/docs/tutorial/security/index.md
+++ b/docs/en/docs/tutorial/security/index.md
@@ -1,4 +1,4 @@
-# Security
+# Security { #security }
There are many ways to handle security, authentication and authorization.
@@ -10,11 +10,11 @@ In many frameworks and systems just handling security and authentication takes a
But first, let's check some small concepts.
-## In a hurry?
+## In a hurry? { #in-a-hurry }
If you don't care about any of these terms and you just need to add security with authentication based on username and password *right now*, skip to the next chapters.
-## OAuth2
+## OAuth2 { #oauth2 }
OAuth2 is a specification that defines several ways to handle authentication and authorization.
@@ -22,9 +22,9 @@ It is quite an extensive specification and covers several complex use cases.
It includes ways to authenticate using a "third party".
-That's what all the systems with "login with Facebook, Google, Twitter, GitHub" use underneath.
+That's what all the systems with "login with Facebook, Google, X (Twitter), GitHub" use underneath.
-### OAuth 1
+### OAuth 1 { #oauth-1 }
There was an OAuth 1, which is very different from OAuth2, and more complex, as it included direct specifications on how to encrypt the communication.
@@ -32,11 +32,13 @@ It is not very popular or used nowadays.
OAuth2 doesn't specify how to encrypt the communication, it expects you to have your application served with HTTPS.
-!!! tip
- In the section about **deployment** you will see how to set up HTTPS for free, using Traefik and Let's Encrypt.
+/// tip
+In the section about **deployment** you will see how to set up HTTPS for free, using Traefik and Let's Encrypt.
-## OpenID Connect
+///
+
+## OpenID Connect { #openid-connect }
OpenID Connect is another specification, based on **OAuth2**.
@@ -46,7 +48,7 @@ For example, Google login uses OpenID Connect (which underneath uses OAuth2).
But Facebook login doesn't support OpenID Connect. It has its own flavor of OAuth2.
-### OpenID (not "OpenID Connect")
+### OpenID (not "OpenID Connect") { #openid-not-openid-connect }
There was also an "OpenID" specification. That tried to solve the same thing as **OpenID Connect**, but was not based on OAuth2.
@@ -54,7 +56,7 @@ So, it was a complete additional system.
It is not very popular or used nowadays.
-## OpenAPI
+## OpenAPI { #openapi }
OpenAPI (previously known as Swagger) is the open specification for building APIs (now part of the Linux Foundation).
@@ -77,7 +79,7 @@ OpenAPI defines the following security schemes:
* HTTP Basic authentication.
* HTTP Digest, etc.
* `oauth2`: all the OAuth2 ways to handle security (called "flows").
- * Several of these flows are appropriate for building an OAuth 2.0 authentication provider (like Google, Facebook, Twitter, GitHub, etc):
+ * Several of these flows are appropriate for building an OAuth 2.0 authentication provider (like Google, Facebook, X (Twitter), GitHub, etc):
* `implicit`
* `clientCredentials`
* `authorizationCode`
@@ -87,12 +89,15 @@ OpenAPI defines the following security schemes:
* This automatic discovery is what is defined in the OpenID Connect specification.
-!!! tip
- Integrating other authentication/authorization providers like Google, Facebook, Twitter, GitHub, etc. is also possible and relatively easy.
+/// tip
+
+Integrating other authentication/authorization providers like Google, Facebook, X (Twitter), GitHub, etc. is also possible and relatively easy.
+
+The most complex problem is building an authentication/authorization provider like those, but **FastAPI** gives you the tools to do it easily, while doing the heavy lifting for you.
- The most complex problem is building an authentication/authorization provider like those, but **FastAPI** gives you the tools to do it easily, while doing the heavy lifting for you.
+///
-## **FastAPI** utilities
+## **FastAPI** utilities { #fastapi-utilities }
FastAPI provides several tools for each of these security schemes in the `fastapi.security` module that simplify using these security mechanisms.
diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md
index deb722b966e26..fabdd06a6bb7a 100644
--- a/docs/en/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/en/docs/tutorial/security/oauth2-jwt.md
@@ -1,4 +1,4 @@
-# OAuth2 with Password (and hashing), Bearer with JWT tokens
+# OAuth2 with Password (and hashing), Bearer with JWT tokens { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
Now that we have all the security flow, let's make the application actually secure, using JWT tokens and secure password hashing.
@@ -6,7 +6,7 @@ This code is something you can actually use in your application, save the passwo
We are going to start from where we left in the previous chapter and increment it.
-## About JWT
+## About JWT { #about-jwt }
JWT means "JSON Web Tokens".
@@ -24,32 +24,33 @@ That way, you can create a token with an expiration of, let's say, 1 week. And t
After a week, the token will be expired and the user will not be authorized and will have to sign in again to get a new token. And if the user (or a third party) tried to modify the token to change the expiration, you would be able to discover it, because the signatures would not match.
-If you want to play with JWT tokens and see how they work, check https://jwt.io.
+If you want to play with JWT tokens and see how they work, check [https://jwt.io](https://jwt.io/).
-## Install `python-jose`
+## Install `PyJWT` { #install-pyjwt }
-We need to install `python-jose` to generate and verify the JWT tokens in Python:
+We need to install `PyJWT` to generate and verify the JWT tokens in Python.
+
+Make sure you create a [virtual environment](../../virtual-environments.md), activate it, and then install `pyjwt`:
@@ -357,10 +238,13 @@ If you open the developer tools, you could see how the data sent only includes t
-!!! note
- Notice the header `Authorization`, with a value that starts with `Bearer `.
+/// note
+
+Notice the header `Authorization`, with a value that starts with `Bearer `.
+
+///
-## Advanced usage with `scopes`
+## Advanced usage with `scopes` { #advanced-usage-with-scopes }
OAuth2 has the notion of "scopes".
@@ -370,7 +254,7 @@ Then you can give this token to a user directly or a third party, to interact wi
You can learn how to use them and how they are integrated into **FastAPI** later in the **Advanced User Guide**.
-## Recap
+## Recap { #recap }
With what you have seen up to now, you can set up a secure **FastAPI** application using standards like OAuth2 and JWT.
@@ -384,10 +268,10 @@ Many packages that simplify it a lot have to make many compromises with the data
It gives you all the flexibility to choose the ones that fit your project the best.
-And you can use directly many well maintained and widely used packages like `passlib` and `python-jose`, because **FastAPI** doesn't require any complex mechanisms to integrate external packages.
+And you can use directly many well maintained and widely used packages like `pwdlib` and `PyJWT`, because **FastAPI** doesn't require any complex mechanisms to integrate external packages.
But it provides you the tools to simplify the process as much as possible without compromising flexibility, robustness, or security.
And you can use and implement secure, standard protocols, like OAuth2 in a relatively simple way.
-You can learn more in the **Advanced User Guide** about how to use OAuth2 "scopes", for a more fine-grained permission system, following these same standards. OAuth2 with scopes is the mechanism used by many big authentication providers, like Facebook, Google, GitHub, Microsoft, Twitter, etc. to authorize third party applications to interact with their APIs on behalf of their users.
+You can learn more in the **Advanced User Guide** about how to use OAuth2 "scopes", for a more fine-grained permission system, following these same standards. OAuth2 with scopes is the mechanism used by many big authentication providers, like Facebook, Google, GitHub, Microsoft, X (Twitter), etc. to authorize third party applications to interact with their APIs on behalf of their users.
diff --git a/docs/en/docs/tutorial/security/simple-oauth2.md b/docs/en/docs/tutorial/security/simple-oauth2.md
index abcf6b667c573..a98112d765333 100644
--- a/docs/en/docs/tutorial/security/simple-oauth2.md
+++ b/docs/en/docs/tutorial/security/simple-oauth2.md
@@ -1,8 +1,8 @@
-# Simple OAuth2 with Password and Bearer
+# Simple OAuth2 with Password and Bearer { #simple-oauth2-with-password-and-bearer }
Now let's build from the previous chapter and add the missing parts to have a complete security flow.
-## Get the `username` and `password`
+## Get the `username` and `password` { #get-the-username-and-password }
We are going to use **FastAPI** security utilities to get the `username` and `password`.
@@ -18,7 +18,7 @@ But for the login *path operation*, we need to use these names to be compatible
The spec also states that the `username` and `password` must be sent as form data (so, no JSON here).
-### `scope`
+### `scope` { #scope }
The spec also says that the client can send another form field "`scope`".
@@ -32,58 +32,27 @@ They are normally used to declare specific security permissions, for example:
* `instagram_basic` is used by Facebook / Instagram.
* `https://www.googleapis.com/auth/drive` is used by Google.
-!!! info
- In OAuth2 a "scope" is just a string that declares a specific permission required.
+/// info
- It doesn't matter if it has other characters like `:` or if it is a URL.
+In OAuth2 a "scope" is just a string that declares a specific permission required.
- Those details are implementation specific.
+It doesn't matter if it has other characters like `:` or if it is a URL.
- For OAuth2 they are just strings.
+Those details are implementation specific.
-## Code to get the `username` and `password`
+For OAuth2 they are just strings.
-Now let's use the utilities provided by **FastAPI** to handle this.
-
-### `OAuth2PasswordRequestForm`
-
-First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depends` in the *path operation* for `/token`:
-
-=== "Python 3.10+"
-
- ```Python hl_lines="4 78"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
-
-=== "Python 3.9+"
+///
- ```Python hl_lines="4 78"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+## Code to get the `username` and `password` { #code-to-get-the-username-and-password }
-=== "Python 3.6+"
-
- ```Python hl_lines="4 79"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="2 74"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+Now let's use the utilities provided by **FastAPI** to handle this.
-=== "Python 3.6+ non-Annotated"
+### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform }
- !!! tip
- Prefer to use the `Annotated` version if possible.
+First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depends` in the *path operation* for `/token`:
- ```Python hl_lines="4 76"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}
`OAuth2PasswordRequestForm` is a class dependency that declares a form body with:
@@ -92,73 +61,48 @@ First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depe
* An optional `scope` field as a big string, composed of strings separated by spaces.
* An optional `grant_type`.
-!!! tip
- The OAuth2 spec actually *requires* a field `grant_type` with a fixed value of `password`, but `OAuth2PasswordRequestForm` doesn't enforce it.
-
- If you need to enforce it, use `OAuth2PasswordRequestFormStrict` instead of `OAuth2PasswordRequestForm`.
+/// tip
-* An optional `client_id` (we don't need it for our example).
-* An optional `client_secret` (we don't need it for our example).
-
-!!! info
- The `OAuth2PasswordRequestForm` is not a special class for **FastAPI** as is `OAuth2PasswordBearer`.
-
- `OAuth2PasswordBearer` makes **FastAPI** know that it is a security scheme. So it is added that way to OpenAPI.
+The OAuth2 spec actually *requires* a field `grant_type` with a fixed value of `password`, but `OAuth2PasswordRequestForm` doesn't enforce it.
- But `OAuth2PasswordRequestForm` is just a class dependency that you could have written yourself, or you could have declared `Form` parameters directly.
+If you need to enforce it, use `OAuth2PasswordRequestFormStrict` instead of `OAuth2PasswordRequestForm`.
- But as it's a common use case, it is provided by **FastAPI** directly, just to make it easier.
+///
-### Use the form data
-
-!!! tip
- The instance of the dependency class `OAuth2PasswordRequestForm` won't have an attribute `scope` with the long string separated by spaces, instead, it will have a `scopes` attribute with the actual list of strings for each scope sent.
-
- We are not using `scopes` in this example, but the functionality is there if you need it.
+* An optional `client_id` (we don't need it for our example).
+* An optional `client_secret` (we don't need it for our example).
-Now, get the user data from the (fake) database, using the `username` from the form field.
+/// info
-If there is no such user, we return an error saying "incorrect username or password".
+The `OAuth2PasswordRequestForm` is not a special class for **FastAPI** as is `OAuth2PasswordBearer`.
-For the error, we use the exception `HTTPException`:
+`OAuth2PasswordBearer` makes **FastAPI** know that it is a security scheme. So it is added that way to OpenAPI.
-=== "Python 3.10+"
+But `OAuth2PasswordRequestForm` is just a class dependency that you could have written yourself, or you could have declared `Form` parameters directly.
- ```Python hl_lines="3 79-81"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+But as it's a common use case, it is provided by **FastAPI** directly, just to make it easier.
-=== "Python 3.9+"
+///
- ```Python hl_lines="3 79-81"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+### Use the form data { #use-the-form-data }
-=== "Python 3.6+"
+/// tip
- ```Python hl_lines="3 80-82"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+The instance of the dependency class `OAuth2PasswordRequestForm` won't have an attribute `scope` with the long string separated by spaces, instead, it will have a `scopes` attribute with the actual list of strings for each scope sent.
-=== "Python 3.10+ non-Annotated"
+We are not using `scopes` in this example, but the functionality is there if you need it.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
- ```Python hl_lines="1 75-77"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+Now, get the user data from the (fake) database, using the `username` from the form field.
-=== "Python 3.6+ non-Annotated"
+If there is no such user, we return an error saying "Incorrect username or password".
- !!! tip
- Prefer to use the `Annotated` version if possible.
+For the error, we use the exception `HTTPException`:
- ```Python hl_lines="3 77-79"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}
-### Check the password
+### Check the password { #check-the-password }
At this point we have the user data from our database, but we haven't checked the password.
@@ -168,7 +112,7 @@ You should never save plaintext passwords, so, we'll use the (fake) password has
If the passwords don't match, we return the same error.
-#### Password hashing
+#### Password hashing { #password-hashing }
"Hashing" means: converting some content (a password in this case) into a sequence of bytes (just a string) that looks like gibberish.
@@ -176,49 +120,15 @@ Whenever you pass exactly the same content (exactly the same password) you get e
But you cannot convert from the gibberish back to the password.
-##### Why use password hashing
+##### Why use password hashing { #why-use-password-hashing }
If your database is stolen, the thief won't have your users' plaintext passwords, only the hashes.
So, the thief won't be able to try to use those same passwords in another system (as many users use the same password everywhere, this would be dangerous).
-=== "Python 3.10+"
-
- ```Python hl_lines="82-85"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
-
-=== "Python 3.9+"
+{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}
- ```Python hl_lines="82-85"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="83-86"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="78-81"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="80-83"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
-
-#### About `**user_dict`
+#### About `**user_dict` { #about-user-dict }
`UserInDB(**user_dict)` means:
@@ -234,10 +144,13 @@ UserInDB(
)
```
-!!! info
- For a more complete explanation of `**user_dict` check back in [the documentation for **Extra Models**](../extra-models.md#about-user_indict){.internal-link target=_blank}.
+/// info
+
+For a more complete explanation of `**user_dict` check back in [the documentation for **Extra Models**](../extra-models.md#about-user-in-dict).
+
+///
-## Return the token
+## Return the token { #return-the-token }
The response of the `token` endpoint must be a JSON object.
@@ -247,57 +160,29 @@ And it should have an `access_token`, with a string containing our access token.
For this simple example, we are going to just be completely insecure and return the same `username` as the token.
-!!! tip
- In the next chapter, you will see a real secure implementation, with password hashing and JWT tokens.
-
- But for now, let's focus on the specific details we need.
-
-=== "Python 3.10+"
-
- ```Python hl_lines="87"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
+/// tip
-=== "Python 3.9+"
+In the next chapter, you will see a real secure implementation, with password hashing and JWT tokens.
- ```Python hl_lines="87"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
+But for now, let's focus on the specific details we need.
-=== "Python 3.6+"
+///
- ```Python hl_lines="88"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
+{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}
-=== "Python 3.10+ non-Annotated"
+/// tip
- !!! tip
- Prefer to use the `Annotated` version if possible.
+By the spec, you should return a JSON with an `access_token` and a `token_type`, the same as in this example.
- ```Python hl_lines="83"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
+This is something that you have to do yourself in your code, and make sure you use those JSON keys.
-=== "Python 3.6+ non-Annotated"
+It's almost the only thing that you have to remember to do correctly yourself, to be compliant with the specifications.
- !!! tip
- Prefer to use the `Annotated` version if possible.
+For the rest, **FastAPI** handles it for you.
- ```Python hl_lines="85"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+///
-!!! tip
- By the spec, you should return a JSON with an `access_token` and a `token_type`, the same as in this example.
-
- This is something that you have to do yourself in your code, and make sure you use those JSON keys.
-
- It's almost the only thing that you have to remember to do correctly yourself, to be compliant with the specifications.
-
- For the rest, **FastAPI** handles it for you.
-
-## Update the dependencies
+## Update the dependencies { #update-the-dependencies }
Now we are going to update our dependencies.
@@ -309,62 +194,31 @@ Both of these dependencies will just return an HTTP error if the user doesn't ex
So, in our endpoint, we will only get a user if the user exists, was correctly authenticated, and is active:
-=== "Python 3.10+"
-
- ```Python hl_lines="58-66 69-74 94"
- {!> ../../../docs_src/security/tutorial003_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="58-66 69-74 94"
- {!> ../../../docs_src/security/tutorial003_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="59-67 70-75 95"
- {!> ../../../docs_src/security/tutorial003_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="56-64 67-70 88"
- {!> ../../../docs_src/security/tutorial003_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
+{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}
- !!! tip
- Prefer to use the `Annotated` version if possible.
+/// info
- ```Python hl_lines="58-66 69-72 90"
- {!> ../../../docs_src/security/tutorial003.py!}
- ```
+The additional header `WWW-Authenticate` with value `Bearer` we are returning here is also part of the spec.
-!!! info
- The additional header `WWW-Authenticate` with value `Bearer` we are returning here is also part of the spec.
+Any HTTP (error) status code 401 "UNAUTHORIZED" is supposed to also return a `WWW-Authenticate` header.
- Any HTTP (error) status code 401 "UNAUTHORIZED" is supposed to also return a `WWW-Authenticate` header.
+In the case of bearer tokens (our case), the value of that header should be `Bearer`.
- In the case of bearer tokens (our case), the value of that header should be `Bearer`.
+You can actually skip that extra header and it would still work.
- You can actually skip that extra header and it would still work.
+But it's provided here to be compliant with the specifications.
- But it's provided here to be compliant with the specifications.
+Also, there might be tools that expect and use it (now or in the future) and that might be useful for you or your users, now or in the future.
- Also, there might be tools that expect and use it (now or in the future) and that might be useful for you or your users, now or in the future.
+That's the benefit of standards...
- That's the benefit of standards...
+///
-## See it in action
+## See it in action { #see-it-in-action }
-Open the interactive docs: http://127.0.0.1:8000/docs.
+Open the interactive docs: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).
-### Authenticate
+### Authenticate { #authenticate }
Click the "Authorize" button.
@@ -380,7 +234,7 @@ After authenticating in the system, you will see it like:
-### Get your own user data
+### Get your own user data { #get-your-own-user-data }
Now use the operation `GET` with the path `/users/me`.
@@ -406,7 +260,7 @@ If you click the lock icon and logout, and then try the same operation again, yo
}
```
-### Inactive user
+### Inactive user { #inactive-user }
Now try with an inactive user, authenticate with:
@@ -416,7 +270,7 @@ Password: `secret2`
And try to use the operation `GET` with the path `/users/me`.
-You will get an "inactive user" error, like:
+You will get an "Inactive user" error, like:
```JSON
{
@@ -424,7 +278,7 @@ You will get an "inactive user" error, like:
}
```
-## Recap
+## Recap { #recap }
You now have the tools to implement a complete security system based on `username` and `password` for your API.
diff --git a/docs/en/docs/tutorial/server-sent-events.md b/docs/en/docs/tutorial/server-sent-events.md
new file mode 100644
index 0000000000000..d264f8536f097
--- /dev/null
+++ b/docs/en/docs/tutorial/server-sent-events.md
@@ -0,0 +1,120 @@
+# Server-Sent Events (SSE) { #server-sent-events-sse }
+
+You can stream data to the client using **Server-Sent Events** (SSE).
+
+This is similar to [Stream JSON Lines](stream-json-lines.md), but uses the `text/event-stream` format, which is supported natively by browsers with the [`EventSource` API](https://developer.mozilla.org/en-US/docs/Web/API/EventSource).
+
+/// info
+
+Added in FastAPI 0.135.0.
+
+///
+
+## What are Server-Sent Events? { #what-are-server-sent-events }
+
+SSE is a standard for streaming data from the server to the client over HTTP.
+
+Each event is a small text block with "fields" like `data`, `event`, `id`, and `retry`, separated by blank lines.
+
+It looks like this:
+
+```
+data: {"name": "Portal Gun", "price": 999.99}
+
+data: {"name": "Plumbus", "price": 32.99}
+
+```
+
+SSE is commonly used for AI chat streaming, live notifications, logs and observability, and other cases where the server pushes updates to the client.
+
+/// tip
+
+If you want to stream binary data, for example video or audio, check the advanced guide: [Stream Data](../advanced/stream-data.md).
+
+///
+
+## Stream SSE with FastAPI { #stream-sse-with-fastapi }
+
+To stream SSE with FastAPI, use `yield` in your *path operation function* and set `response_class=EventSourceResponse`.
+
+Import `EventSourceResponse` from `fastapi.sse`:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[4,22] *}
+
+Each yielded item is encoded as JSON and sent in the `data:` field of an SSE event.
+
+If you declare the return type as `AsyncIterable[Item]`, FastAPI will use it to **validate**, **document**, and **serialize** the data using Pydantic.
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[10:12,23] *}
+
+/// tip
+
+As Pydantic will serialize it in the **Rust** side, you will get much higher **performance** than if you don't declare a return type.
+
+///
+
+### Non-async *path operation functions* { #non-async-path-operation-functions }
+
+You can also use regular `def` functions (without `async`), and use `yield` the same way.
+
+FastAPI will make sure it's run correctly so that it doesn't block the event loop.
+
+As in this case the function is not async, the right return type would be `Iterable[Item]`:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[28:31] hl[29] *}
+
+### No Return Type { #no-return-type }
+
+You can also omit the return type. FastAPI will use the [`jsonable_encoder`](./encoder.md) to convert the data and send it.
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[34:37] hl[35] *}
+
+## `ServerSentEvent` { #serversentevent }
+
+If you need to set SSE fields like `event`, `id`, `retry`, or `comment`, you can yield `ServerSentEvent` objects instead of plain data.
+
+Import `ServerSentEvent` from `fastapi.sse`:
+
+{* ../../docs_src/server_sent_events/tutorial002_py310.py hl[4,26] *}
+
+The `data` field is always encoded as JSON. You can pass any value that can be serialized as JSON, including Pydantic models.
+
+## Raw Data { #raw-data }
+
+If you need to send data **without** JSON encoding, use `raw_data` instead of `data`.
+
+This is useful for sending pre-formatted text, log lines, or special "sentinel" values like `[DONE]`.
+
+{* ../../docs_src/server_sent_events/tutorial003_py310.py hl[17] *}
+
+/// note
+
+`data` and `raw_data` are mutually exclusive. You can only set one of them on each `ServerSentEvent`.
+
+///
+
+## Resuming with `Last-Event-ID` { #resuming-with-last-event-id }
+
+When a browser reconnects after a connection drop, it sends the last received `id` in the `Last-Event-ID` header.
+
+You can read it as a header parameter and use it to resume the stream from where the client left off:
+
+{* ../../docs_src/server_sent_events/tutorial004_py310.py hl[25,27,31] *}
+
+## SSE with POST { #sse-with-post }
+
+SSE works with **any HTTP method**, not just `GET`.
+
+This is useful for protocols like [MCP](https://modelcontextprotocol.io) that stream SSE over `POST`:
+
+{* ../../docs_src/server_sent_events/tutorial005_py310.py hl[14] *}
+
+## Technical Details { #technical-details }
+
+FastAPI implements some SSE best practices out of the box.
+
+* Send a **"keep alive" `ping` comment** every 15 seconds when there hasn't been any message, to prevent some proxies from closing the connection, as suggested in the [HTML specification: Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes).
+* Set the `Cache-Control: no-cache` header to **prevent caching** of the stream.
+* Set a special header `X-Accel-Buffering: no` to **prevent buffering** in some proxies like Nginx.
+
+You don't have to do anything about it, it works out of the box. 🤓
diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md
index 6e0e5dc06eaa1..b8cbac295bc74 100644
--- a/docs/en/docs/tutorial/sql-databases.md
+++ b/docs/en/docs/tutorial/sql-databases.md
@@ -1,19 +1,18 @@
-# SQL (Relational) Databases
+# SQL (Relational) Databases { #sql-relational-databases }
-!!! info
- These docs are about to be updated. 🎉
+**FastAPI** doesn't require you to use a SQL (relational) database. But you can use **any database** that you want.
- The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0.
+Here we'll see an example using [SQLModel](https://sqlmodel.tiangolo.com/).
- The new docs will include Pydantic v2 and will use SQLModel (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well.
+**SQLModel** is built on top of [SQLAlchemy](https://www.sqlalchemy.org/) and Pydantic. It was made by the same author of **FastAPI** to be the perfect match for FastAPI applications that need to use **SQL databases**.
-**FastAPI** doesn't require you to use a SQL (relational) database.
+/// tip
-But you can use any relational database that you want.
+You could use any other SQL or NoSQL database library you want (in some cases called "ORMs"), FastAPI doesn't force you to use anything. 😎
-Here we'll see an example using SQLAlchemy.
+///
-You can easily adapt it to any database supported by SQLAlchemy, like:
+As SQLModel is based on SQLAlchemy, you can easily use **any database supported** by SQLAlchemy (which makes them also supported by SQLModel), like:
* PostgreSQL
* MySQL
@@ -25,769 +24,334 @@ In this example, we'll use **SQLite**, because it uses a single file and Python
Later, for your production application, you might want to use a database server like **PostgreSQL**.
-!!! tip
- There is an official project generator with **FastAPI** and **PostgreSQL**, all based on **Docker**, including a frontend and more tools: https://github.com/tiangolo/full-stack-fastapi-postgresql
+/// tip
-!!! note
- Notice that most of the code is the standard `SQLAlchemy` code you would use with any framework.
+There is an official project generator with **FastAPI** and **PostgreSQL** including a frontend and more tools: [https://github.com/fastapi/full-stack-fastapi-template](https://github.com/fastapi/full-stack-fastapi-template)
- The **FastAPI** specific code is as small as always.
+///
-## ORMs
+This is a very simple and short tutorial, if you want to learn about databases in general, about SQL, or more advanced features, go to the [SQLModel docs](https://sqlmodel.tiangolo.com/).
-**FastAPI** works with any database and any style of library to talk to the database.
+## Install `SQLModel` { #install-sqlmodel }
-A common pattern is to use an "ORM": an "object-relational mapping" library.
-
-An ORM has tools to convert ("*map*") between *objects* in code and database tables ("*relations*").
-
-With an ORM, you normally create a class that represents a table in a SQL database, each attribute of the class represents a column, with a name and a type.
-
-For example a class `Pet` could represent a SQL table `pets`.
-
-And each *instance* object of that class represents a row in the database.
-
-For example an object `orion_cat` (an instance of `Pet`) could have an attribute `orion_cat.type`, for the column `type`. And the value of that attribute could be, e.g. `"cat"`.
-
-These ORMs also have tools to make the connections or relations between tables or entities.
-
-This way, you could also have an attribute `orion_cat.owner` and the owner would contain the data for this pet's owner, taken from the table *owners*.
-
-So, `orion_cat.owner.name` could be the name (from the `name` column in the `owners` table) of this pet's owner.
-
-It could have a value like `"Arquilian"`.
-
-And the ORM will do all the work to get the information from the corresponding table *owners* when you try to access it from your pet object.
-
-Common ORMs are for example: Django-ORM (part of the Django framework), SQLAlchemy ORM (part of SQLAlchemy, independent of framework) and Peewee (independent of framework), among others.
-
-Here we will see how to work with **SQLAlchemy ORM**.
-
-In a similar way you could use any other ORM.
-
-!!! tip
- There's an equivalent article using Peewee here in the docs.
-
-## File structure
-
-For these examples, let's say you have a directory named `my_super_project` that contains a sub-directory called `sql_app` with a structure like this:
-
-```
-.
-└── sql_app
- ├── __init__.py
- ├── crud.py
- ├── database.py
- ├── main.py
- ├── models.py
- └── schemas.py
-```
-
-The file `__init__.py` is just an empty file, but it tells Python that `sql_app` with all its modules (Python files) is a package.
-
-Now let's see what each file/module does.
-
-## Install `SQLAlchemy`
-
-First you need to install `SQLAlchemy`:
+First, make sure you create your [virtual environment](../virtual-environments.md), activate it, and then install `sqlmodel`:
+
-
-## Interact with the database directly
-
-If you want to explore the SQLite database (file) directly, independently of FastAPI, to debug its contents, add tables, columns, records, modify data, etc. you can use DB Browser for SQLite.
-
-It will look like this:
+If you go to the `/docs` API UI, you will see that it is now updated, and it won't expect to receive the `id` from the client when creating a hero, etc.
+
+
+
+
+
+
+
+
+
+
+
lt
+* XWT
+* PSGI
+
+### El abbr da una frase completa y una explicación { #the-abbr-gives-a-full-phrase-and-an-explanation }
+
+* MDN
+* I/O.
+
+////
+
+//// tab | Info
+
+Los atributos "title" de los elementos "abbr" se traducen siguiendo instrucciones específicas.
+
+Las traducciones pueden añadir sus propios elementos "abbr" que el LLM no debe eliminar. P. ej., para explicar palabras en inglés.
+
+Consulta la sección `### HTML abbr elements` en el prompt general en `scripts/translate.py`.
+
+////
+
+## Elementos HTML "dfn" { #html-dfn-elements }
+
+* clúster
+* Deep Learning
+
+## Encabezados { #headings }
+
+//// tab | Prueba
+
+### Desarrolla una webapp - un tutorial { #develop-a-webapp-a-tutorial }
+
+Hola.
+
+### Anotaciones de tipos y -anotaciones { #type-hints-and-annotations }
+
+Hola de nuevo.
+
+### Superclases y subclases { #super-and-subclasses }
+
+Hola de nuevo.
+
+////
+
+//// tab | Info
+
+La única regla estricta para los encabezados es que el LLM deje la parte del hash dentro de llaves sin cambios, lo que asegura que los enlaces no se rompan.
+
+Consulta la sección `### Headings` en el prompt general en `scripts/translate.py`.
+
+Para instrucciones específicas del idioma, mira p. ej. la sección `### Headings` en `docs/de/llm-prompt.md`.
+
+////
+
+## Términos usados en la documentación { #terms-used-in-the-docs }
+
+//// tab | Prueba
+
+* tú
+* tu
+
+* p. ej.
+* etc.
+
+* `foo` como un `int`
+* `bar` como un `str`
+* `baz` como una `list`
+
+* el Tutorial - Guía de usuario
+* la Guía de usuario avanzada
+* la documentación de SQLModel
+* la documentación de la API
+* la documentación automática
+
+* Ciencia de datos
+* Deep Learning
+* Machine Learning
+* Inyección de dependencias
+* autenticación HTTP Basic
+* HTTP Digest
+* formato ISO
+* el estándar JSON Schema
+* el JSON Schema
+* la definición del esquema
+* Flujo de contraseña
+* Móvil
+
+* obsoleto
+* diseñado
+* inválido
+* sobre la marcha
+* estándar
+* por defecto
+* sensible a mayúsculas/minúsculas
+* insensible a mayúsculas/minúsculas
+
+* servir la aplicación
+* servir la página
+
+* la app
+* la aplicación
+
+* la request
+* la response
+* la response de error
+
+* la path operation
+* el decorador de path operation
+* la path operation function
+
+* el body
+* el request body
+* el response body
+* el body JSON
+* el body del formulario
+* el body de archivo
+* el cuerpo de la función
+
+* el parámetro
+* el parámetro del body
+* el parámetro del path
+* el parámetro de query
+* el parámetro de cookie
+* el parámetro de header
+* el parámetro del formulario
+* el parámetro de la función
+
+* el evento
+* el evento de inicio
+* el inicio del servidor
+* el evento de apagado
+* el evento de lifespan
+
+* el manejador
+* el manejador de eventos
+* el manejador de excepciones
+* manejar
+
+* el modelo
+* el modelo de Pydantic
+* el modelo de datos
+* el modelo de base de datos
+* el modelo de formulario
+* el objeto del modelo
+
+* la clase
+* la clase base
+* la clase padre
+* la subclase
+* la clase hija
+* la clase hermana
+* el método de clase
+
+* el header
+* los headers
+* el header de autorización
+* el header `Authorization`
+* el header forwarded
+
+* el sistema de inyección de dependencias
+* la dependencia
+* el dependable
+* el dependiente
+
+* limitado por I/O
+* limitado por CPU
+* concurrencia
+* paralelismo
+* multiprocesamiento
+
+* la env var
+* la variable de entorno
+* el `PATH`
+* la variable `PATH`
+
+* la autenticación
+* el proveedor de autenticación
+* la autorización
+* el formulario de autorización
+* el proveedor de autorización
+* el usuario se autentica
+* el sistema autentica al usuario
+
+* la CLI
+* la interfaz de línea de comandos
+
+* el servidor
+* el cliente
+
+* el proveedor en la nube
+* el servicio en la nube
+
+* el desarrollo
+* las etapas de desarrollo
+
+* el dict
+* el diccionario
+* la enumeración
+* el enum
+* el miembro del enum
+
+* el codificador
+* el decodificador
+* codificar
+* decodificar
+
+* la excepción
+* lanzar
+
+* la expresión
+* el statement
+
+* el frontend
+* el backend
+
+* la discusión de GitHub
+* el issue de GitHub
+
+* el rendimiento
+* la optimización de rendimiento
+
+* el tipo de retorno
+* el valor de retorno
+
+* la seguridad
+* el esquema de seguridad
+
+* la tarea
+* la tarea en segundo plano
+* la función de tarea
+
+* la plantilla
+* el motor de plantillas
+
+* la anotación de tipos
+* la anotación de tipos
+
+* el worker del servidor
+* el worker de Uvicorn
+* el Gunicorn Worker
+* el worker process
+* la worker class
+* la carga de trabajo
+
+* el despliegue
+* desplegar
+
+* el SDK
+* el kit de desarrollo de software
+
+* el `APIRouter`
+* el `requirements.txt`
+* el Bearer Token
+* el cambio incompatible
+* el bug
+* el botón
+* el invocable
+* el código
+* el commit
+* el context manager
+* la corrutina
+* la sesión de base de datos
+* el disco
+* el dominio
+* el motor
+* el X falso
+* el método HTTP GET
+* el ítem
+* el paquete
+* el lifespan
+* el lock
+* el middleware
+* la aplicación móvil
+* el módulo
+* el montaje
+* la red
+* el origen
+* el override
+* el payload
+* el procesador
+* la propiedad
+* el proxy
+* el pull request
+* la query
+* la RAM
+* la máquina remota
+* el código de estado
+* el string
+* la etiqueta
+* el framework web
+* el comodín
+* devolver
+* validar
+
+////
+
+//// tab | Info
+
+Esta es una lista no completa y no normativa de términos (mayormente) técnicos vistos en la documentación. Puede ayudar a la persona que diseña el prompt a identificar para qué términos el LLM necesita una mano. Por ejemplo cuando sigue revirtiendo una buena traducción a una traducción subóptima. O cuando tiene problemas conjugando/declinando un término en tu idioma.
+
+Mira p. ej. la sección `### List of English terms and their preferred German translations` en `docs/de/llm-prompt.md`.
+
+////
diff --git a/docs/es/docs/about/index.md b/docs/es/docs/about/index.md
new file mode 100644
index 0000000000000..fa152c62dbfe7
--- /dev/null
+++ b/docs/es/docs/about/index.md
@@ -0,0 +1,3 @@
+# Acerca de { #about }
+
+Acerca de FastAPI, su diseño, inspiración y más. 🤓
diff --git a/docs/es/docs/advanced/additional-responses.md b/docs/es/docs/advanced/additional-responses.md
new file mode 100644
index 0000000000000..83053d3a9ebcd
--- /dev/null
+++ b/docs/es/docs/advanced/additional-responses.md
@@ -0,0 +1,247 @@
+# Responses Adicionales en OpenAPI { #additional-responses-in-openapi }
+
+/// warning | Advertencia
+
+Este es un tema bastante avanzado.
+
+Si estás comenzando con **FastAPI**, puede que no lo necesites.
+
+///
+
+Puedes declarar responses adicionales, con códigos de estado adicionales, media types, descripciones, etc.
+
+Esos responses adicionales se incluirán en el esquema de OpenAPI, por lo que también aparecerán en la documentación de la API.
+
+Pero para esos responses adicionales tienes que asegurarte de devolver un `Response` como `JSONResponse` directamente, con tu código de estado y contenido.
+
+## Response Adicional con `model` { #additional-response-with-model }
+
+Puedes pasar a tus *decoradores de path operation* un parámetro `responses`.
+
+Recibe un `dict`: las claves son los códigos de estado para cada response (como `200`), y los valores son otros `dict`s con la información para cada uno de ellos.
+
+Cada uno de esos `dict`s de response puede tener una clave `model`, conteniendo un modelo de Pydantic, así como `response_model`.
+
+**FastAPI** tomará ese modelo, generará su JSON Schema y lo incluirá en el lugar correcto en OpenAPI.
+
+Por ejemplo, para declarar otro response con un código de estado `404` y un modelo Pydantic `Message`, puedes escribir:
+
+{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}
+
+/// note | Nota
+
+Ten en cuenta que debes devolver el `JSONResponse` directamente.
+
+///
+
+/// info | Información
+
+La clave `model` no es parte de OpenAPI.
+
+**FastAPI** tomará el modelo de Pydantic de allí, generará el JSON Schema y lo colocará en el lugar correcto.
+
+El lugar correcto es:
+
+* En la clave `content`, que tiene como valor otro objeto JSON (`dict`) que contiene:
+ * Una clave con el media type, por ejemplo, `application/json`, que contiene como valor otro objeto JSON, que contiene:
+ * Una clave `schema`, que tiene como valor el JSON Schema del modelo, aquí es el lugar correcto.
+ * **FastAPI** agrega una referencia aquí a los JSON Schemas globales en otro lugar de tu OpenAPI en lugar de incluirlo directamente. De este modo, otras aplicaciones y clientes pueden usar esos JSON Schemas directamente, proporcionar mejores herramientas de generación de código, etc.
+
+///
+
+Los responses generadas en el OpenAPI para esta *path operation* serán:
+
+```JSON hl_lines="3-12"
+{
+ "responses": {
+ "404": {
+ "description": "Additional Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Message"
+ }
+ }
+ }
+ },
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+Los esquemas se referencian a otro lugar dentro del esquema de OpenAPI:
+
+```JSON hl_lines="4-16"
+{
+ "components": {
+ "schemas": {
+ "Message": {
+ "title": "Message",
+ "required": [
+ "message"
+ ],
+ "type": "object",
+ "properties": {
+ "message": {
+ "title": "Message",
+ "type": "string"
+ }
+ }
+ },
+ "Item": {
+ "title": "Item",
+ "required": [
+ "id",
+ "value"
+ ],
+ "type": "object",
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
+ },
+ "value": {
+ "title": "Value",
+ "type": "string"
+ }
+ }
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": [
+ "loc",
+ "msg",
+ "type"
+ ],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string"
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string"
+ }
+ }
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+## Media types adicionales para el response principal { #additional-media-types-for-the-main-response }
+
+Puedes usar este mismo parámetro `responses` para agregar diferentes media type para el mismo response principal.
+
+Por ejemplo, puedes agregar un media type adicional de `image/png`, declarando que tu *path operation* puede devolver un objeto JSON (con media type `application/json`) o una imagen PNG:
+
+{* ../../docs_src/additional_responses/tutorial002_py310.py hl[17:22,26] *}
+
+/// note | Nota
+
+Nota que debes devolver la imagen usando un `FileResponse` directamente.
+
+///
+
+/// info | Información
+
+A menos que especifiques un media type diferente explícitamente en tu parámetro `responses`, FastAPI asumirá que el response tiene el mismo media type que la clase de response principal (por defecto `application/json`).
+
+Pero si has especificado una clase de response personalizada con `None` como su media type, FastAPI usará `application/json` para cualquier response adicional que tenga un modelo asociado.
+
+///
+
+## Combinando información { #combining-information }
+
+También puedes combinar información de response de múltiples lugares, incluyendo los parámetros `response_model`, `status_code`, y `responses`.
+
+Puedes declarar un `response_model`, usando el código de estado por defecto `200` (o uno personalizado si lo necesitas), y luego declarar información adicional para ese mismo response en `responses`, directamente en el esquema de OpenAPI.
+
+**FastAPI** mantendrá la información adicional de `responses` y la combinará con el JSON Schema de tu modelo.
+
+Por ejemplo, puedes declarar un response con un código de estado `404` que usa un modelo Pydantic y tiene una `description` personalizada.
+
+Y un response con un código de estado `200` que usa tu `response_model`, pero incluye un `example` personalizado:
+
+{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}
+
+Todo se combinará e incluirá en tu OpenAPI, y se mostrará en la documentación de la API:
+
+
+
+## Combina responses predefinidos y personalizados { #combine-predefined-responses-and-custom-ones }
+
+Es posible que desees tener algunos responses predefinidos que se apliquen a muchas *path operations*, pero que quieras combinarlos con responses personalizados necesarios por cada *path operation*.
+
+Para esos casos, puedes usar la técnica de Python de "desempaquetar" un `dict` con `**dict_to_unpack`:
+
+```Python
+old_dict = {
+ "old key": "old value",
+ "second old key": "second old value",
+}
+new_dict = {**old_dict, "new key": "new value"}
+```
+
+Aquí, `new_dict` contendrá todos los pares clave-valor de `old_dict` más el nuevo par clave-valor:
+
+```Python
+{
+ "old key": "old value",
+ "second old key": "second old value",
+ "new key": "new value",
+}
+```
+
+Puedes usar esa técnica para reutilizar algunos responses predefinidos en tus *path operations* y combinarlos con otros personalizados adicionales.
+
+Por ejemplo:
+
+{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}
+
+## Más información sobre responses OpenAPI { #more-information-about-openapi-responses }
+
+Para ver exactamente qué puedes incluir en los responses, puedes revisar estas secciones en la especificación OpenAPI:
+
+* [Objeto de Responses de OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responses-object), incluye el `Response Object`.
+* [Objeto de Response de OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#response-object), puedes incluir cualquier cosa de esto directamente en cada response dentro de tu parámetro `responses`. Incluyendo `description`, `headers`, `content` (dentro de este es que declaras diferentes media types y JSON Schemas), y `links`.
diff --git a/docs/es/docs/advanced/additional-status-codes.md b/docs/es/docs/advanced/additional-status-codes.md
index 1f28ea85b738a..5c0ab6980fca0 100644
--- a/docs/es/docs/advanced/additional-status-codes.md
+++ b/docs/es/docs/advanced/additional-status-codes.md
@@ -1,37 +1,41 @@
-# Códigos de estado adicionales
+# Códigos de Estado Adicionales { #additional-status-codes }
-Por defecto, **FastAPI** devolverá las respuestas utilizando una `JSONResponse`, poniendo el contenido que devuelves en tu *operación de path* dentro de esa `JSONResponse`.
+Por defecto, **FastAPI** devolverá los responses usando un `JSONResponse`, colocando el contenido que devuelves desde tu *path operation* dentro de ese `JSONResponse`.
-Utilizará el código de estado por defecto, o el que hayas asignado en tu *operación de path*.
+Usará el código de estado por defecto o el que configures en tu *path operation*.
-## Códigos de estado adicionales
+## Códigos de estado adicionales { #additional-status-codes_1 }
-Si quieres devolver códigos de estado adicionales además del principal, puedes hacerlo devolviendo directamente una `Response`, como una `JSONResponse`, y asignar directamente el código de estado adicional.
+Si quieres devolver códigos de estado adicionales aparte del principal, puedes hacerlo devolviendo un `Response` directamente, como un `JSONResponse`, y configurando el código de estado adicional directamente.
-Por ejemplo, digamos que quieres tener una *operación de path* que permita actualizar ítems y devolver códigos de estado HTTP 200 "OK" cuando sea exitosa.
+Por ejemplo, supongamos que quieres tener una *path operation* que permita actualizar elementos, y devuelva códigos de estado HTTP de 200 "OK" cuando sea exitoso.
-Pero también quieres que acepte nuevos ítems. Cuando los ítems no existan anteriormente, serán creados y devolverá un código de estado HTTP 201 "Created".
+Pero también quieres que acepte nuevos elementos. Y cuando los elementos no existían antes, los crea y devuelve un código de estado HTTP de 201 "Created".
-Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu contenido, asignando el `status_code` que quieras:
+Para lograr eso, importa `JSONResponse`, y devuelve tu contenido allí directamente, configurando el `status_code` que deseas:
-```Python hl_lines="4 25"
-{!../../../docs_src/additional_status_codes/tutorial001.py!}
-```
+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
-!!! warning "Advertencia"
- Cuando devuelves directamente una `Response`, como en los ejemplos anteriores, será devuelta directamente.
+/// warning | Advertencia
- No será serializado con el modelo, etc.
+Cuando devuelves un `Response` directamente, como en el ejemplo anterior, se devuelve directamente.
- Asegurate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`).
+No se serializará con un modelo, etc.
-!!! note "Detalles Técnicos"
- También podrías utilizar `from starlette.responses import JSONResponse`.
+Asegúrate de que tenga los datos que deseas que tenga y que los valores sean JSON válidos (si estás usando `JSONResponse`).
- **FastAPI** provee las mismas `starlette.responses` que `fastapi.responses` simplemente como una convención para ti, el desarrollador. Pero la mayoría de las respuestas disponibles vienen directamente de Starlette. Lo mismo con `status`.
+///
-## OpenAPI y documentación de API
+/// note | Detalles Técnicos
-Si quieres devolver códigos de estado y respuestas adicionales directamente, estas no estarán incluidas en el schema de OpenAPI (documentación de API), porque FastAPI no tiene una manera de conocer de antemano lo que vas a devolver.
+También podrías usar `from starlette.responses import JSONResponse`.
-Pero puedes documentar eso en tu código usando [Respuestas Adicionales](additional-responses.md){.internal-link target=_blank}.
+**FastAPI** proporciona los mismos `starlette.responses` que `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles provienen directamente de Starlette. Lo mismo con `status`.
+
+///
+
+## OpenAPI y documentación de API { #openapi-and-api-docs }
+
+Si devuelves códigos de estado adicionales y responses directamente, no se incluirán en el esquema de OpenAPI (la documentación de la API), porque FastAPI no tiene una forma de saber de antemano qué vas a devolver.
+
+Pero puedes documentarlo en tu código, usando: [Responses Adicionales](additional-responses.md).
diff --git a/docs/es/docs/advanced/advanced-dependencies.md b/docs/es/docs/advanced/advanced-dependencies.md
new file mode 100644
index 0000000000000..cee93692d751a
--- /dev/null
+++ b/docs/es/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,163 @@
+# Dependencias Avanzadas { #advanced-dependencies }
+
+## Dependencias con parámetros { #parameterized-dependencies }
+
+Todas las dependencias que hemos visto son una función o clase fija.
+
+Pero podría haber casos en los que quieras poder establecer parámetros en la dependencia, sin tener que declarar muchas funciones o clases diferentes.
+
+Imaginemos que queremos tener una dependencia que revise si el parámetro de query `q` contiene algún contenido fijo.
+
+Pero queremos poder parametrizar ese contenido fijo.
+
+## Una *instance* "callable" { #a-callable-instance }
+
+En Python hay una forma de hacer que una instance de una clase sea un "callable".
+
+No la clase en sí (que ya es un callable), sino una instance de esa clase.
+
+Para hacer eso, declaramos un método `__call__`:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}
+
+En este caso, este `__call__` es lo que **FastAPI** usará para comprobar parámetros adicionales y sub-dependencias, y es lo que llamará para pasar un valor al parámetro en tu *path operation function* más adelante.
+
+## Parametrizar la instance { #parameterize-the-instance }
+
+Y ahora, podemos usar `__init__` para declarar los parámetros de la instance que podemos usar para "parametrizar" la dependencia:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}
+
+En este caso, **FastAPI** nunca tocará ni se preocupará por `__init__`, lo usaremos directamente en nuestro código.
+
+## Crear una instance { #create-an-instance }
+
+Podríamos crear una instance de esta clase con:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}
+
+Y de esa manera podemos "parametrizar" nuestra dependencia, que ahora tiene `"bar"` dentro de ella, como el atributo `checker.fixed_content`.
+
+## Usar la instance como una dependencia { #use-the-instance-as-a-dependency }
+
+Luego, podríamos usar este `checker` en un `Depends(checker)`, en lugar de `Depends(FixedContentQueryChecker)`, porque la dependencia es la instance, `checker`, no la clase en sí.
+
+Y al resolver la dependencia, **FastAPI** llamará a este `checker` así:
+
+```Python
+checker(q="somequery")
+```
+
+...y pasará lo que eso retorne como el valor de la dependencia en nuestra *path operation function* como el parámetro `fixed_content_included`:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}
+
+/// tip | Consejo
+
+Todo esto podría parecer complicado. Y puede que no esté muy claro cómo es útil aún.
+
+Estos ejemplos son intencionalmente simples, pero muestran cómo funciona todo.
+
+En los capítulos sobre seguridad, hay funciones utilitarias que se implementan de esta misma manera.
+
+Si entendiste todo esto, ya sabes cómo funcionan por debajo esas herramientas de utilidad para seguridad.
+
+///
+
+## Dependencias con `yield`, `HTTPException`, `except` y Tareas en segundo plano { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+/// warning | Advertencia
+
+Muy probablemente no necesites estos detalles técnicos.
+
+Estos detalles son útiles principalmente si tenías una aplicación de FastAPI anterior a la 0.121.0 y estás enfrentando problemas con dependencias con `yield`.
+
+///
+
+Las dependencias con `yield` han evolucionado con el tiempo para cubrir diferentes casos de uso y arreglar algunos problemas; aquí tienes un resumen de lo que ha cambiado.
+
+### Dependencias con `yield` y `scope` { #dependencies-with-yield-and-scope }
+
+En la versión 0.121.0, FastAPI agregó soporte para `Depends(scope="function")` para dependencias con `yield`.
+
+Usando `Depends(scope="function")`, el código de salida después de `yield` se ejecuta justo después de que la *path operation function* termina, antes de que la response se envíe de vuelta al cliente.
+
+Y al usar `Depends(scope="request")` (el valor por defecto), el código de salida después de `yield` se ejecuta después de que la response es enviada.
+
+Puedes leer más al respecto en la documentación de [Dependencias con `yield` - Salida temprana y `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope).
+
+### Dependencias con `yield` y `StreamingResponse`, detalles técnicos { #dependencies-with-yield-and-streamingresponse-technical-details }
+
+Antes de FastAPI 0.118.0, si usabas una dependencia con `yield`, ejecutaba el código de salida después de que la *path operation function* retornaba pero justo antes de enviar la response.
+
+La intención era evitar retener recursos por más tiempo del necesario, esperando a que la response viajara por la red.
+
+Este cambio también significaba que si retornabas un `StreamingResponse`, el código de salida de la dependencia con `yield` ya se habría ejecutado.
+
+Por ejemplo, si tenías una sesión de base de datos en una dependencia con `yield`, el `StreamingResponse` no podría usar esa sesión mientras hace streaming de datos porque la sesión ya se habría cerrado en el código de salida después de `yield`.
+
+Este comportamiento se revirtió en la 0.118.0, para hacer que el código de salida después de `yield` se ejecute después de que la response sea enviada.
+
+/// info | Información
+
+Como verás abajo, esto es muy similar al comportamiento anterior a la versión 0.106.0, pero con varias mejoras y arreglos de bugs para casos límite.
+
+///
+
+#### Casos de uso con salida temprana del código { #use-cases-with-early-exit-code }
+
+Hay algunos casos de uso con condiciones específicas que podrían beneficiarse del comportamiento antiguo de ejecutar el código de salida de dependencias con `yield` antes de enviar la response.
+
+Por ejemplo, imagina que tienes código que usa una sesión de base de datos en una dependencia con `yield` solo para verificar un usuario, pero la sesión de base de datos no se vuelve a usar en la *path operation function*, solo en la dependencia, y la response tarda mucho en enviarse, como un `StreamingResponse` que envía datos lentamente, pero que por alguna razón no usa la base de datos.
+
+En este caso, la sesión de base de datos se mantendría hasta que la response termine de enviarse, pero si no la usas, entonces no sería necesario mantenerla.
+
+Así es como se vería:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
+
+El código de salida, el cierre automático de la `Session` en:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
+
+...se ejecutaría después de que la response termine de enviar los datos lentos:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
+
+Pero como `generate_stream()` no usa la sesión de base de datos, no es realmente necesario mantener la sesión abierta mientras se envía la response.
+
+Si tienes este caso de uso específico usando SQLModel (o SQLAlchemy), podrías cerrar explícitamente la sesión después de que ya no la necesites:
+
+{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}
+
+De esa manera la sesión liberaría la conexión a la base de datos, para que otras requests puedan usarla.
+
+Si tienes un caso de uso diferente que necesite salir temprano desde una dependencia con `yield`, por favor crea una [Pregunta de Discusión en GitHub](https://github.com/fastapi/fastapi/discussions/new?category=questions) con tu caso de uso específico y por qué te beneficiaría tener cierre temprano para dependencias con `yield`.
+
+Si hay casos de uso convincentes para el cierre temprano en dependencias con `yield`, consideraría agregar una nueva forma de optar por el cierre temprano.
+
+### Dependencias con `yield` y `except`, detalles técnicos { #dependencies-with-yield-and-except-technical-details }
+
+Antes de FastAPI 0.110.0, si usabas una dependencia con `yield`, y luego capturabas una excepción con `except` en esa dependencia, y no volvías a elevar la excepción, la excepción se elevaría/remitiría automáticamente a cualquier manejador de excepciones o al manejador de error interno del servidor.
+
+Esto cambió en la versión 0.110.0 para arreglar consumo de memoria no manejado por excepciones reenviadas sin un manejador (errores internos del servidor), y para hacerlo consistente con el comportamiento del código Python normal.
+
+### Tareas en segundo plano y dependencias con `yield`, detalles técnicos { #background-tasks-and-dependencies-with-yield-technical-details }
+
+Antes de FastAPI 0.106.0, elevar excepciones después de `yield` no era posible, el código de salida en dependencias con `yield` se ejecutaba después de que la response era enviada, por lo que [Manejadores de Excepciones](../tutorial/handling-errors.md#install-custom-exception-handlers) ya habrían corrido.
+
+Esto se diseñó así principalmente para permitir usar los mismos objetos devueltos con `yield` por las dependencias dentro de tareas en segundo plano, porque el código de salida se ejecutaría después de que las tareas en segundo plano terminaran.
+
+Esto cambió en FastAPI 0.106.0 con la intención de no retener recursos mientras se espera a que la response viaje por la red.
+
+/// tip | Consejo
+
+Adicionalmente, una tarea en segundo plano normalmente es un conjunto independiente de lógica que debería manejarse por separado, con sus propios recursos (por ejemplo, su propia conexión a la base de datos).
+
+Así, probablemente tendrás un código más limpio.
+
+///
+
+Si solías depender de este comportamiento, ahora deberías crear los recursos para las tareas en segundo plano dentro de la propia tarea en segundo plano, y usar internamente solo datos que no dependan de los recursos de dependencias con `yield`.
+
+Por ejemplo, en lugar de usar la misma sesión de base de datos, crearías una nueva sesión de base de datos dentro de la tarea en segundo plano, y obtendrías los objetos de la base de datos usando esta nueva sesión. Y entonces, en lugar de pasar el objeto de la base de datos como parámetro a la función de la tarea en segundo plano, pasarías el ID de ese objeto y luego obtendrías el objeto de nuevo dentro de la función de la tarea en segundo plano.
diff --git a/docs/es/docs/advanced/advanced-python-types.md b/docs/es/docs/advanced/advanced-python-types.md
new file mode 100644
index 0000000000000..a18c5d6cc8430
--- /dev/null
+++ b/docs/es/docs/advanced/advanced-python-types.md
@@ -0,0 +1,61 @@
+# Tipos avanzados de Python { #advanced-python-types }
+
+Aquí tienes algunas ideas adicionales que podrían ser útiles al trabajar con tipos de Python.
+
+## Usar `Union` u `Optional` { #using-union-or-optional }
+
+Si por alguna razón tu código no puede usar `|`, por ejemplo si no está en una anotación de tipos sino en algo como `response_model=`, en lugar de usar la barra vertical (`|`) puedes usar `Union` de `typing`.
+
+Por ejemplo, podrías declarar que algo podría ser un `str` o `None`:
+
+```python
+from typing import Union
+
+
+def say_hi(name: Union[str, None]):
+ print(f"Hi {name}!")
+```
+
+`typing` también tiene un atajo para declarar que algo podría ser `None`, con `Optional`.
+
+Aquí va un Consejo desde mi punto de vista muy subjetivo:
+
+* 🚨 Evita usar `Optional[SomeType]`
+* En su lugar ✨ **usa `Union[SomeType, None]`** ✨.
+
+Ambas son equivalentes y por debajo son lo mismo, pero recomendaría `Union` en lugar de `Optional` porque la palabra "**optional**" parecería implicar que el valor es opcional, y en realidad significa "puede ser `None`", incluso si no es opcional y sigue siendo requerido.
+
+Creo que `Union[SomeType, None]` es más explícito respecto a lo que significa.
+
+Se trata solo de palabras y nombres. Pero esas palabras pueden afectar cómo tú y tu equipo piensan sobre el código.
+
+Como ejemplo, tomemos esta función:
+
+```python
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+ print(f"Hey {name}!")
+```
+
+El parámetro `name` está definido como `Optional[str]`, pero **no es opcional**, no puedes llamar a la función sin el parámetro:
+
+```Python
+say_hi() # ¡Oh, no, esto lanza un error! 😱
+```
+
+El parámetro `name` **sigue siendo requerido** (no es *opcional*) porque no tiene un valor por defecto. Aun así, `name` acepta `None` como valor:
+
+```Python
+say_hi(name=None) # Esto funciona, None es válido 🎉
+```
+
+La buena noticia es que, en la mayoría de los casos, podrás simplemente usar `|` para definir uniones de tipos:
+
+```python
+def say_hi(name: str | None):
+ print(f"Hey {name}!")
+```
+
+Así que, normalmente no tienes que preocuparte por nombres como `Optional` y `Union`. 😎
diff --git a/docs/es/docs/advanced/async-tests.md b/docs/es/docs/advanced/async-tests.md
new file mode 100644
index 0000000000000..4ccd664e63c02
--- /dev/null
+++ b/docs/es/docs/advanced/async-tests.md
@@ -0,0 +1,99 @@
+# Tests Asíncronos { #async-tests }
+
+Ya has visto cómo probar tus aplicaciones de **FastAPI** usando el `TestClient` proporcionado. Hasta ahora, solo has visto cómo escribir tests sincrónicos, sin usar funciones `async`.
+
+Poder usar funciones asíncronas en tus tests puede ser útil, por ejemplo, cuando consultas tu base de datos de forma asíncrona. Imagina que quieres probar el envío de requests a tu aplicación FastAPI y luego verificar que tu backend escribió exitosamente los datos correctos en la base de datos, mientras usas un paquete de base de datos asíncrono.
+
+Veamos cómo podemos hacer que esto funcione.
+
+## pytest.mark.anyio { #pytest-mark-anyio }
+
+Si queremos llamar funciones asíncronas en nuestros tests, nuestras funciones de test tienen que ser asíncronas. AnyIO proporciona un plugin útil para esto, que nos permite especificar que algunas funciones de test deben ser llamadas de manera asíncrona.
+
+## HTTPX { #httpx }
+
+Incluso si tu aplicación de **FastAPI** usa funciones `def` normales en lugar de `async def`, sigue siendo una aplicación `async` por debajo.
+
+El `TestClient` hace algo de magia interna para llamar a la aplicación FastAPI asíncrona en tus funciones de test `def` normales, usando pytest estándar. Pero esa magia ya no funciona cuando lo usamos dentro de funciones asíncronas. Al ejecutar nuestros tests de manera asíncrona, ya no podemos usar el `TestClient` dentro de nuestras funciones de test.
+
+El `TestClient` está basado en [HTTPX](https://www.python-httpx.org), y afortunadamente, podemos usarlo directamente para probar la API.
+
+## Ejemplo { #example }
+
+Para un ejemplo simple, consideremos una estructura de archivos similar a la descrita en [Aplicaciones Más Grandes](../tutorial/bigger-applications.md) y [Testing](../tutorial/testing.md):
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+El archivo `main.py` tendría:
+
+{* ../../docs_src/async_tests/app_a_py310/main.py *}
+
+El archivo `test_main.py` tendría los tests para `main.py`, podría verse así ahora:
+
+{* ../../docs_src/async_tests/app_a_py310/test_main.py *}
+
+## Ejecútalo { #run-it }
+
+Puedes ejecutar tus tests como de costumbre vía:
+
+
+
+Pero si accedemos a la UI de los docs en la URL "oficial" usando el proxy con puerto `9999`, en `/api/v1/docs`, ¡funciona correctamente! 🎉
+
+Puedes verificarlo en [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs):
+
+
+
+Justo como queríamos. ✔️
+
+Esto es porque FastAPI usa este `root_path` para crear el `server` por defecto en OpenAPI con la URL proporcionada por `root_path`.
+
+## Servidores adicionales { #additional-servers }
+
+/// warning | Advertencia
+
+Este es un caso de uso más avanzado. Siéntete libre de omitirlo.
+
+///
+
+Por defecto, **FastAPI** creará un `server` en el esquema de OpenAPI con la URL para el `root_path`.
+
+Pero también puedes proporcionar otros `servers` alternativos, por ejemplo, si deseas que *la misma* UI de los docs interactúe con un entorno de pruebas y de producción.
+
+Si pasas una lista personalizada de `servers` y hay un `root_path` (porque tu API existe detrás de un proxy), **FastAPI** insertará un "server" con este `root_path` al comienzo de la lista.
+
+Por ejemplo:
+
+{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}
+
+Generará un esquema de OpenAPI como:
+
+```JSON hl_lines="5-7"
+{
+ "openapi": "3.1.0",
+ // Más cosas aquí
+ "servers": [
+ {
+ "url": "/api/v1"
+ },
+ {
+ "url": "https://stag.example.com",
+ "description": "Staging environment"
+ },
+ {
+ "url": "https://prod.example.com",
+ "description": "Production environment"
+ }
+ ],
+ "paths": {
+ // Más cosas aquí
+ }
+}
+```
+
+/// tip | Consejo
+
+Observa el server auto-generado con un valor `url` de `/api/v1`, tomado del `root_path`.
+
+///
+
+En la UI de los docs en [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs) se vería como:
+
+
+
+/// tip | Consejo
+
+La UI de los docs interactuará con el server que selecciones.
+
+///
+
+/// note | Detalles Técnicos
+
+La propiedad `servers` en la especificación de OpenAPI es opcional.
+
+Si no especificas el parámetro `servers` y `root_path` es igual a `/`, la propiedad `servers` en el esquema de OpenAPI generado se omitirá por completo por defecto, lo cual es equivalente a un único server con un valor `url` de `/`.
+
+///
+
+### Desactivar el server automático de `root_path` { #disable-automatic-server-from-root-path }
+
+Si no quieres que **FastAPI** incluya un server automático usando el `root_path`, puedes usar el parámetro `root_path_in_servers=False`:
+
+{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}
+
+y entonces no lo incluirá en el esquema de OpenAPI.
+
+## Montando una sub-aplicación { #mounting-a-sub-application }
+
+Si necesitas montar una sub-aplicación (como se describe en [Aplicaciones secundarias - Monturas](sub-applications.md)) mientras usas un proxy con `root_path`, puedes hacerlo normalmente, como esperarías.
+
+FastAPI usará internamente el `root_path` de manera inteligente, así que simplemente funcionará. ✨
diff --git a/docs/es/docs/advanced/custom-response.md b/docs/es/docs/advanced/custom-response.md
new file mode 100644
index 0000000000000..e1db101479dfe
--- /dev/null
+++ b/docs/es/docs/advanced/custom-response.md
@@ -0,0 +1,273 @@
+# Response Personalizado - HTML, Stream, Archivo, otros { #custom-response-html-stream-file-others }
+
+Por defecto, **FastAPI** devolverá responses JSON.
+
+Puedes sobrescribirlo devolviendo un `Response` directamente como se ve en [Devolver una Response directamente](response-directly.md).
+
+Pero si devuelves un `Response` directamente (o cualquier subclase, como `JSONResponse`), los datos no se convertirán automáticamente (incluso si declaras un `response_model`), y la documentación no se generará automáticamente (por ejemplo, incluyendo el "media type" específico, en el HTTP header `Content-Type` como parte del OpenAPI generado).
+
+Pero también puedes declarar el `Response` que quieres usar (por ejemplo, cualquier subclase de `Response`), en el *path operation decorator* usando el parámetro `response_class`.
+
+Los contenidos que devuelvas desde tu *path operation function* se colocarán dentro de esa `Response`.
+
+/// note | Nota
+
+Si usas una clase de response sin media type, FastAPI esperará que tu response no tenga contenido, por lo que no documentará el formato del response en su OpenAPI generado.
+
+///
+
+## Responses JSON { #json-responses }
+
+Por defecto FastAPI devuelve responses JSON.
+
+Si declaras un [Response Model](../tutorial/response-model.md) FastAPI lo usará para serializar los datos a JSON, usando Pydantic.
+
+Si no declaras un response model, FastAPI usará el `jsonable_encoder` explicado en [Codificador Compatible con JSON](../tutorial/encoder.md) y lo pondrá en un `JSONResponse`.
+
+Si declaras un `response_class` con un media type JSON (`application/json`), como es el caso con `JSONResponse`, los datos que devuelvas se convertirán automáticamente (y serán filtrados) con cualquier `response_model` de Pydantic que hayas declarado en el *path operation decorator*. Pero los datos no se serializarán a bytes JSON con Pydantic, en su lugar se convertirán con el `jsonable_encoder` y luego se pasarán a la clase `JSONResponse`, que los serializará a bytes usando la librería JSON estándar de Python.
+
+### Rendimiento JSON { #json-performance }
+
+En resumen, si quieres el máximo rendimiento, usa un [Response Model](../tutorial/response-model.md) y no declares un `response_class` en el *path operation decorator*.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py ln[15:17] hl[16] *}
+
+## Response HTML { #html-response }
+
+Para devolver un response con HTML directamente desde **FastAPI**, usa `HTMLResponse`.
+
+* Importa `HTMLResponse`.
+* Pasa `HTMLResponse` como parámetro `response_class` de tu *path operation decorator*.
+
+{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}
+
+/// info | Información
+
+El parámetro `response_class` también se utilizará para definir el "media type" del response.
+
+En este caso, el HTTP header `Content-Type` se establecerá en `text/html`.
+
+Y se documentará así en OpenAPI.
+
+///
+
+### Devuelve una `Response` { #return-a-response }
+
+Como se ve en [Devolver una Response directamente](response-directly.md), también puedes sobrescribir el response directamente en tu *path operation*, devolviéndolo.
+
+El mismo ejemplo de arriba, devolviendo una `HTMLResponse`, podría verse así:
+
+{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}
+
+/// warning | Advertencia
+
+Una `Response` devuelta directamente por tu *path operation function* no se documentará en OpenAPI (por ejemplo, el `Content-Type` no se documentará) y no será visible en la documentación interactiva automática.
+
+///
+
+/// info | Información
+
+Por supuesto, el `Content-Type` header real, el código de estado, etc., provendrán del objeto `Response` que devolviste.
+
+///
+
+### Documenta en OpenAPI y sobrescribe `Response` { #document-in-openapi-and-override-response }
+
+Si quieres sobrescribir el response desde dentro de la función pero al mismo tiempo documentar el "media type" en OpenAPI, puedes usar el parámetro `response_class` Y devolver un objeto `Response`.
+
+El `response_class` solo se usará para documentar el OpenAPI *path operation*, pero tu `Response` se usará tal cual.
+
+#### Devuelve un `HTMLResponse` directamente { #return-an-htmlresponse-directly }
+
+Por ejemplo, podría ser algo así:
+
+{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}
+
+En este ejemplo, la función `generate_html_response()` ya genera y devuelve una `Response` en lugar de devolver el HTML en un `str`.
+
+Al devolver el resultado de llamar a `generate_html_response()`, ya estás devolviendo una `Response` que sobrescribirá el comportamiento por defecto de **FastAPI**.
+
+Pero como pasaste `HTMLResponse` en el `response_class` también, **FastAPI** sabrá cómo documentarlo en OpenAPI y la documentación interactiva como HTML con `text/html`:
+
+
+
+## Responses disponibles { #available-responses }
+
+Aquí hay algunos de los responses disponibles.
+
+Ten en cuenta que puedes usar `Response` para devolver cualquier otra cosa, o incluso crear una sub-clase personalizada.
+
+/// note | Nota Técnica
+
+También podrías usar `from starlette.responses import HTMLResponse`.
+
+**FastAPI** proporciona los mismos `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette.
+
+///
+
+### `Response` { #response }
+
+La clase principal `Response`, todos los otros responses heredan de ella.
+
+Puedes devolverla directamente.
+
+Acepta los siguientes parámetros:
+
+* `content` - Un `str` o `bytes`.
+* `status_code` - Un código de estado HTTP `int`.
+* `headers` - Un `dict` de strings.
+* `media_type` - Un `str` que da el media type. Por ejemplo, `"text/html"`.
+
+FastAPI (de hecho Starlette) incluirá automáticamente un header Content-Length. También incluirá un header Content-Type, basado en el `media_type` y añadiendo un conjunto de caracteres para tipos de texto.
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+### `HTMLResponse` { #htmlresponse }
+
+Toma algún texto o bytes y devuelve un response HTML, como leíste arriba.
+
+### `PlainTextResponse` { #plaintextresponse }
+
+Toma algún texto o bytes y devuelve un response de texto plano.
+
+{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}
+
+### `JSONResponse` { #jsonresponse }
+
+Toma algunos datos y devuelve un response codificado como `application/json`.
+
+Este es el response usado por defecto en **FastAPI**, como leíste arriba.
+
+/// note | Nota Técnica
+
+Pero si declaras un response model o un tipo de retorno, eso se usará directamente para serializar los datos a JSON, y se devolverá directamente un response con el media type correcto para JSON, sin usar la clase `JSONResponse`.
+
+Esta es la forma ideal de obtener el mejor rendimiento.
+
+///
+
+### `RedirectResponse` { #redirectresponse }
+
+Devuelve una redirección HTTP. Usa un código de estado 307 (Redirección Temporal) por defecto.
+
+Puedes devolver un `RedirectResponse` directamente:
+
+{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}
+
+---
+
+O puedes usarlo en el parámetro `response_class`:
+
+
+{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}
+
+Si haces eso, entonces puedes devolver la URL directamente desde tu *path operation* function.
+
+En este caso, el `status_code` utilizado será el por defecto para `RedirectResponse`, que es `307`.
+
+---
+
+También puedes usar el parámetro `status_code` combinado con el parámetro `response_class`:
+
+{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}
+
+### `StreamingResponse` { #streamingresponse }
+
+Toma un generador `async` o un generador/iterador normal (una función con `yield`) y transmite el cuerpo del response.
+
+{* ../../docs_src/custom_response/tutorial007_py310.py hl[3,16] *}
+
+/// note | Nota Técnica
+
+Una tarea `async` solo puede cancelarse cuando llega a un `await`. Si no hay `await`, el generador (función con `yield`) no se puede cancelar correctamente y puede seguir ejecutándose incluso después de solicitar la cancelación.
+
+Como este pequeño ejemplo no necesita ninguna sentencia `await`, añadimos un `await anyio.sleep(0)` para darle al loop de eventos la oportunidad de manejar la cancelación.
+
+Esto sería aún más importante con streams grandes o infinitos.
+
+///
+
+/// tip | Consejo
+
+En lugar de devolver un `StreamingResponse` directamente, probablemente deberías seguir el estilo en [Stream Data](./stream-data.md), es mucho más conveniente y maneja la cancelación por detrás de escena por ti.
+
+Si estás transmitiendo JSON Lines, sigue el tutorial [Stream JSON Lines](../tutorial/stream-json-lines.md).
+
+///
+
+### `FileResponse` { #fileresponse }
+
+Transmite un archivo asincrónicamente como response.
+
+Toma un conjunto diferente de argumentos para crear un instance que los otros tipos de response:
+
+* `path` - La path del archivo para el archivo a transmitir.
+* `headers` - Cualquier header personalizado para incluir, como un diccionario.
+* `media_type` - Un string que da el media type. Si no se establece, se usará el nombre de archivo o la path para inferir un media type.
+* `filename` - Si se establece, se incluirá en el response `Content-Disposition`.
+
+Los responses de archivos incluirán los headers apropiados `Content-Length`, `Last-Modified` y `ETag`.
+
+{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}
+
+También puedes usar el parámetro `response_class`:
+
+{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}
+
+En este caso, puedes devolver la path del archivo directamente desde tu *path operation* function.
+
+## Clase de response personalizada { #custom-response-class }
+
+Puedes crear tu propia clase de response personalizada, heredando de `Response` y usándola.
+
+Por ejemplo, digamos que quieres usar [`orjson`](https://github.com/ijl/orjson) con algunas configuraciones.
+
+Digamos que quieres que devuelva JSON con sangría y formato, por lo que quieres usar la opción de orjson `orjson.OPT_INDENT_2`.
+
+Podrías crear un `CustomORJSONResponse`. Lo principal que tienes que hacer es crear un método `Response.render(content)` que devuelva el contenido como `bytes`:
+
+{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}
+
+Ahora en lugar de devolver:
+
+```json
+{"message": "Hello World"}
+```
+
+...este response devolverá:
+
+```json
+{
+ "message": "Hello World"
+}
+```
+
+Por supuesto, probablemente encontrarás formas mucho mejores de aprovechar esto que formatear JSON. 😉
+
+### `orjson` o Response Model { #orjson-or-response-model }
+
+Si lo que buscas es rendimiento, probablemente te convenga más usar un [Response Model](../tutorial/response-model.md) que un response con `orjson`.
+
+Con un response model, FastAPI usará Pydantic para serializar los datos a JSON, sin pasos intermedios, como convertirlos con `jsonable_encoder`, que ocurriría en cualquier otro caso.
+
+Y por debajo, Pydantic usa los mismos mecanismos en Rust que `orjson` para serializar a JSON, así que ya obtendrás el mejor rendimiento con un response model.
+
+## Clase de response por defecto { #default-response-class }
+
+Al crear una instance de la clase **FastAPI** o un `APIRouter`, puedes especificar qué clase de response usar por defecto.
+
+El parámetro que define esto es `default_response_class`.
+
+En el ejemplo a continuación, **FastAPI** usará `HTMLResponse` por defecto, en todas las *path operations*, en lugar de JSON.
+
+{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}
+
+/// tip | Consejo
+
+Todavía puedes sobrescribir `response_class` en *path operations* como antes.
+
+///
+
+## Documentación adicional { #additional-documentation }
+
+También puedes declarar el media type y muchos otros detalles en OpenAPI usando `responses`: [Responses Adicionales en OpenAPI](additional-responses.md).
diff --git a/docs/es/docs/advanced/dataclasses.md b/docs/es/docs/advanced/dataclasses.md
new file mode 100644
index 0000000000000..3ce5c754f5e9a
--- /dev/null
+++ b/docs/es/docs/advanced/dataclasses.md
@@ -0,0 +1,95 @@
+# Usando Dataclasses { #using-dataclasses }
+
+FastAPI está construido sobre **Pydantic**, y te he estado mostrando cómo usar modelos de Pydantic para declarar requests y responses.
+
+Pero FastAPI también soporta el uso de [`dataclasses`](https://docs.python.org/3/library/dataclasses.html) de la misma manera:
+
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
+
+Esto sigue siendo soportado gracias a **Pydantic**, ya que tiene [soporte interno para `dataclasses`](https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel).
+
+Así que, incluso con el código anterior que no usa Pydantic explícitamente, FastAPI está usando Pydantic para convertir esos dataclasses estándar en su propia versión de dataclasses de Pydantic.
+
+Y por supuesto, soporta lo mismo:
+
+* validación de datos
+* serialización de datos
+* documentación de datos, etc.
+
+Esto funciona de la misma manera que con los modelos de Pydantic. Y en realidad se logra de la misma manera internamente, utilizando Pydantic.
+
+/// info | Información
+
+Ten en cuenta que los dataclasses no pueden hacer todo lo que los modelos de Pydantic pueden hacer.
+
+Así que, podrías necesitar seguir usando modelos de Pydantic.
+
+Pero si tienes un montón de dataclasses por ahí, este es un buen truco para usarlos para potenciar una API web usando FastAPI. 🤓
+
+///
+
+## Dataclasses en `response_model` { #dataclasses-in-response-model }
+
+También puedes usar `dataclasses` en el parámetro `response_model`:
+
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
+
+El dataclass será automáticamente convertido a un dataclass de Pydantic.
+
+De esta manera, su esquema aparecerá en la interfaz de usuario de la documentación de la API:
+
+
+
+## Dataclasses en Estructuras de Datos Anidadas { #dataclasses-in-nested-data-structures }
+
+También puedes combinar `dataclasses` con otras anotaciones de tipos para crear estructuras de datos anidadas.
+
+En algunos casos, todavía podrías tener que usar la versión de `dataclasses` de Pydantic. Por ejemplo, si tienes errores con la documentación de la API generada automáticamente.
+
+En ese caso, simplemente puedes intercambiar los `dataclasses` estándar con `pydantic.dataclasses`, que es un reemplazo directo:
+
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+
+1. Todavía importamos `field` de los `dataclasses` estándar.
+
+2. `pydantic.dataclasses` es un reemplazo directo para `dataclasses`.
+
+3. El dataclass `Author` incluye una lista de dataclasses `Item`.
+
+4. El dataclass `Author` se usa como el parámetro `response_model`.
+
+5. Puedes usar otras anotaciones de tipos estándar con dataclasses como el request body.
+
+ En este caso, es una lista de dataclasses `Item`.
+
+6. Aquí estamos regresando un diccionario que contiene `items`, que es una lista de dataclasses.
+
+ FastAPI todavía es capaz de serializar los datos a JSON.
+
+7. Aquí el `response_model` está usando una anotación de tipo de una lista de dataclasses `Author`.
+
+ Nuevamente, puedes combinar `dataclasses` con anotaciones de tipos estándar.
+
+8. Nota que esta *path operation function* usa `def` regular en lugar de `async def`.
+
+ Como siempre, en FastAPI puedes combinar `def` y `async def` según sea necesario.
+
+ Si necesitas un repaso sobre cuándo usar cuál, revisa la sección _"¿Con prisa?"_ en la documentación sobre [`async` y `await`](../async.md#in-a-hurry).
+
+9. Esta *path operation function* no está devolviendo dataclasses (aunque podría), sino una lista de diccionarios con datos internos.
+
+ FastAPI usará el parámetro `response_model` (que incluye dataclasses) para convertir el response.
+
+Puedes combinar `dataclasses` con otras anotaciones de tipos en muchas combinaciones diferentes para formar estructuras de datos complejas.
+
+Revisa las anotaciones en el código arriba para ver más detalles específicos.
+
+## Aprende Más { #learn-more }
+
+También puedes combinar `dataclasses` con otros modelos de Pydantic, heredar de ellos, incluirlos en tus propios modelos, etc.
+
+Para saber más, revisa la [documentación de Pydantic sobre dataclasses](https://docs.pydantic.dev/latest/concepts/dataclasses/).
+
+## Versión { #version }
+
+Esto está disponible desde la versión `0.67.0` de FastAPI. 🔖
diff --git a/docs/es/docs/advanced/events.md b/docs/es/docs/advanced/events.md
new file mode 100644
index 0000000000000..264ee27ede593
--- /dev/null
+++ b/docs/es/docs/advanced/events.md
@@ -0,0 +1,165 @@
+# Eventos de Lifespan { #lifespan-events }
+
+Puedes definir lógica (código) que debería ser ejecutada antes de que la aplicación **inicie**. Esto significa que este código será ejecutado **una vez**, **antes** de que la aplicación **comience a recibir requests**.
+
+De la misma manera, puedes definir lógica (código) que debería ser ejecutada cuando la aplicación esté **cerrándose**. En este caso, este código será ejecutado **una vez**, **después** de haber manejado posiblemente **muchos requests**.
+
+Debido a que este código se ejecuta antes de que la aplicación **comience** a tomar requests, y justo después de que **termine** de manejarlos, cubre todo el **lifespan** de la aplicación (la palabra "lifespan" será importante en un momento 😉).
+
+Esto puede ser muy útil para configurar **recursos** que necesitas usar para toda la app, y que son **compartidos** entre requests, y/o que necesitas **limpiar** después. Por ejemplo, un pool de conexiones a una base de datos, o cargando un modelo de machine learning compartido.
+
+## Caso de Uso { #use-case }
+
+Empecemos con un ejemplo de **caso de uso** y luego veamos cómo resolverlo con esto.
+
+Imaginemos que tienes algunos **modelos de machine learning** que quieres usar para manejar requests. 🤖
+
+Los mismos modelos son compartidos entre requests, por lo que no es un modelo por request, o uno por usuario o algo similar.
+
+Imaginemos que cargar el modelo puede **tomar bastante tiempo**, porque tiene que leer muchos **datos del disco**. Entonces no quieres hacerlo para cada request.
+
+Podrías cargarlo en el nivel superior del módulo/archivo, pero eso también significaría que **cargaría el modelo** incluso si solo estás ejecutando una simple prueba automatizada, entonces esa prueba sería **lenta** porque tendría que esperar a que el modelo se cargue antes de poder ejecutar una parte independiente del código.
+
+Eso es lo que resolveremos, vamos a cargar el modelo antes de que los requests sean manejados, pero solo justo antes de que la aplicación comience a recibir requests, no mientras el código se está cargando.
+
+## Lifespan { #lifespan }
+
+Puedes definir esta lógica de *startup* y *shutdown* usando el parámetro `lifespan` de la app de `FastAPI`, y un "context manager" (te mostraré lo que es en un momento).
+
+Comencemos con un ejemplo y luego veámoslo en detalle.
+
+Creamos una función asíncrona `lifespan()` con `yield` así:
+
+{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}
+
+Aquí estamos simulando la operación costosa de *startup* de cargar el modelo poniendo la función del (falso) modelo en el diccionario con modelos de machine learning antes del `yield`. Este código será ejecutado **antes** de que la aplicación **comience a tomar requests**, durante el *startup*.
+
+Y luego, justo después del `yield`, quitaremos el modelo de memoria. Este código será ejecutado **después** de que la aplicación **termine de manejar requests**, justo antes del *shutdown*. Esto podría, por ejemplo, liberar recursos como la memoria o una GPU.
+
+/// tip | Consejo
+
+El `shutdown` ocurriría cuando estás **deteniendo** la aplicación.
+
+Quizás necesites iniciar una nueva versión, o simplemente te cansaste de ejecutarla. 🤷
+
+///
+
+### Función de Lifespan { #lifespan-function }
+
+Lo primero que hay que notar es que estamos definiendo una función asíncrona con `yield`. Esto es muy similar a las Dependencias con `yield`.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}
+
+La primera parte de la función, antes del `yield`, será ejecutada **antes** de que la aplicación comience.
+
+Y la parte después del `yield` será ejecutada **después** de que la aplicación haya terminado.
+
+### Async Context Manager { #async-context-manager }
+
+Si revisas, la función está decorada con un `@asynccontextmanager`.
+
+Eso convierte a la función en algo llamado un "**async context manager**".
+
+{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}
+
+Un **context manager** en Python es algo que puedes usar en un statement `with`, por ejemplo, `open()` puede ser usado como un context manager:
+
+```Python
+with open("file.txt") as file:
+ file.read()
+```
+
+En versiones recientes de Python, también hay un **async context manager**. Lo usarías con `async with`:
+
+```Python
+async with lifespan(app):
+ await do_stuff()
+```
+
+Cuando creas un context manager o un async context manager como arriba, lo que hace es que, antes de entrar al bloque `with`, ejecutará el código antes del `yield`, y al salir del bloque `with`, ejecutará el código después del `yield`.
+
+En nuestro ejemplo de código arriba, no lo usamos directamente, pero se lo pasamos a FastAPI para que lo use.
+
+El parámetro `lifespan` de la app de `FastAPI` toma un **async context manager**, por lo que podemos pasar nuestro nuevo `lifespan` async context manager a él.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[22] *}
+
+## Eventos Alternativos (obsoleto) { #alternative-events-deprecated }
+
+/// warning | Advertencia
+
+La forma recomendada de manejar el *startup* y el *shutdown* es usando el parámetro `lifespan` de la app de `FastAPI` como se describió arriba. Si proporcionas un parámetro `lifespan`, los manejadores de eventos `startup` y `shutdown` ya no serán llamados. Es solo `lifespan` o solo los eventos, no ambos.
+
+Probablemente puedas saltarte esta parte.
+
+///
+
+Hay una forma alternativa de definir esta lógica para ser ejecutada durante el *startup* y durante el *shutdown*.
+
+Puedes definir manejadores de eventos (funciones) que necesitan ser ejecutadas antes de que la aplicación se inicie, o cuando la aplicación se está cerrando.
+
+Estas funciones pueden ser declaradas con `async def` o `def` normal.
+
+### Evento `startup` { #startup-event }
+
+Para añadir una función que debería ejecutarse antes de que la aplicación inicie, declárala con el evento `"startup"`:
+
+{* ../../docs_src/events/tutorial001_py310.py hl[8] *}
+
+En este caso, la función manejadora del evento `startup` inicializará los ítems de la "base de datos" (solo un `dict`) con algunos valores.
+
+Puedes añadir más de un manejador de eventos.
+
+Y tu aplicación no comenzará a recibir requests hasta que todos los manejadores de eventos `startup` hayan completado.
+
+### Evento `shutdown` { #shutdown-event }
+
+Para añadir una función que debería ejecutarse cuando la aplicación se esté cerrando, declárala con el evento `"shutdown"`:
+
+{* ../../docs_src/events/tutorial002_py310.py hl[6] *}
+
+Aquí, la función manejadora del evento `shutdown` escribirá una línea de texto `"Application shutdown"` a un archivo `log.txt`.
+
+/// info | Información
+
+En la función `open()`, el `mode="a"` significa "añadir", por lo tanto, la línea será añadida después de lo que sea que esté en ese archivo, sin sobrescribir el contenido anterior.
+
+///
+
+/// tip | Consejo
+
+Nota que en este caso estamos usando una función estándar de Python `open()` que interactúa con un archivo.
+
+Entonces, involucra I/O (entrada/salida), que requiere "esperar" para que las cosas se escriban en el disco.
+
+Pero `open()` no usa `async` y `await`.
+
+Por eso, declaramos la función manejadora del evento con `def` estándar en vez de `async def`.
+
+///
+
+### `startup` y `shutdown` juntos { #startup-and-shutdown-together }
+
+Hay una gran posibilidad de que la lógica para tu *startup* y *shutdown* esté conectada, podrías querer iniciar algo y luego finalizarlo, adquirir un recurso y luego liberarlo, etc.
+
+Hacer eso en funciones separadas que no comparten lógica o variables juntas es más difícil ya que necesitarías almacenar valores en variables globales o trucos similares.
+
+Debido a eso, ahora se recomienda en su lugar usar el `lifespan` como se explicó arriba.
+
+## Detalles Técnicos { #technical-details }
+
+Solo un detalle técnico para los nerds curiosos. 🤓
+
+Por debajo, en la especificación técnica ASGI, esto es parte del [Protocolo de Lifespan](https://asgi.readthedocs.io/en/latest/specs/lifespan.html), y define eventos llamados `startup` y `shutdown`.
+
+/// info | Información
+
+Puedes leer más sobre los manejadores `lifespan` de Starlette en [la documentación de `Lifespan` de Starlette](https://www.starlette.dev/lifespan/).
+
+Incluyendo cómo manejar el estado de lifespan que puede ser usado en otras áreas de tu código.
+
+///
+
+## Sub Aplicaciones { #sub-applications }
+
+🚨 Ten en cuenta que estos eventos de lifespan (startup y shutdown) solo serán ejecutados para la aplicación principal, no para [Sub Aplicaciones - Mounts](sub-applications.md).
diff --git a/docs/es/docs/advanced/generate-clients.md b/docs/es/docs/advanced/generate-clients.md
new file mode 100644
index 0000000000000..e43cb7f052da9
--- /dev/null
+++ b/docs/es/docs/advanced/generate-clients.md
@@ -0,0 +1,208 @@
+# Generando SDKs { #generating-sdks }
+
+Como **FastAPI** está basado en la especificación **OpenAPI**, sus APIs se pueden describir en un formato estándar que muchas herramientas entienden.
+
+Esto facilita generar **documentación** actualizada, paquetes de cliente (**SDKs**) en múltiples lenguajes y **escribir pruebas** o **flujos de automatización** que se mantengan sincronizados con tu código.
+
+En esta guía, aprenderás a generar un **SDK de TypeScript** para tu backend con FastAPI.
+
+## Generadores de SDKs de código abierto { #open-source-sdk-generators }
+
+Una opción versátil es el [OpenAPI Generator](https://openapi-generator.tech/), que soporta **muchos lenguajes de programación** y puede generar SDKs a partir de tu especificación OpenAPI.
+
+Para **clientes de TypeScript**, [Hey API](https://heyapi.dev/) es una solución diseñada específicamente, que ofrece una experiencia optimizada para el ecosistema de TypeScript.
+
+Puedes descubrir más generadores de SDK en [OpenAPI.Tools](https://openapi.tools/#sdk).
+
+/// tip | Consejo
+
+FastAPI genera automáticamente especificaciones **OpenAPI 3.1**, así que cualquier herramienta que uses debe soportar esta versión.
+
+///
+
+## Generadores de SDKs de sponsors de FastAPI { #sdk-generators-from-fastapi-sponsors }
+
+Esta sección destaca soluciones **respaldadas por empresas** y **venture-backed** de compañías que sponsorean FastAPI. Estos productos ofrecen **funcionalidades adicionales** e **integraciones** además de SDKs generados de alta calidad.
+
+Al ✨ [**sponsorear FastAPI**](../help-fastapi.md#sponsor-the-author) ✨, estas compañías ayudan a asegurar que el framework y su **ecosistema** se mantengan saludables y **sustentables**.
+
+Su sponsorship también demuestra un fuerte compromiso con la **comunidad** de FastAPI (tú), mostrando que no solo les importa ofrecer un **gran servicio**, sino también apoyar un **framework robusto y próspero**, FastAPI. 🙇
+
+Por ejemplo, podrías querer probar:
+
+* [Speakeasy](https://speakeasy.com/editor?utm_source=fastapi+repo&utm_medium=github+sponsorship)
+* [Stainless](https://www.stainless.com/?utm_source=fastapi&utm_medium=referral)
+* [liblab](https://developers.liblab.com/tutorials/sdk-for-fastapi?utm_source=fastapi)
+
+Algunas de estas soluciones también pueden ser open source u ofrecer niveles gratuitos, así que puedes probarlas sin un compromiso financiero. Hay otros generadores de SDK comerciales disponibles y se pueden encontrar en línea. 🤓
+
+## Crea un SDK de TypeScript { #create-a-typescript-sdk }
+
+Empecemos con una aplicación simple de FastAPI:
+
+{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}
+
+Nota que las *path operations* definen los modelos que usan para el payload del request y el payload del response, usando los modelos `Item` y `ResponseMessage`.
+
+### Documentación de la API { #api-docs }
+
+Si vas a `/docs`, verás que tiene los **esquemas** para los datos a enviar en requests y recibir en responses:
+
+
+
+Puedes ver esos esquemas porque fueron declarados con los modelos en la app.
+
+Esa información está disponible en el **OpenAPI schema** de la app, y luego se muestra en la documentación de la API.
+
+Y esa misma información de los modelos que está incluida en OpenAPI es lo que puede usarse para **generar el código del cliente**.
+
+### Hey API { #hey-api }
+
+Una vez que tenemos una app de FastAPI con los modelos, podemos usar Hey API para generar un cliente de TypeScript. La forma más rápida de hacerlo es con npx.
+
+```sh
+npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
+```
+
+Esto generará un SDK de TypeScript en `./src/client`.
+
+Puedes aprender cómo [instalar `@hey-api/openapi-ts`](https://heyapi.dev/openapi-ts/get-started) y leer sobre el [output generado](https://heyapi.dev/openapi-ts/output) en su sitio web.
+
+### Usar el SDK { #using-the-sdk }
+
+Ahora puedes importar y usar el código del cliente. Podría verse así, nota que tienes autocompletado para los métodos:
+
+
+
+También obtendrás autocompletado para el payload a enviar:
+
+
+
+/// tip | Consejo
+
+Nota el autocompletado para `name` y `price`, que fue definido en la aplicación de FastAPI, en el modelo `Item`.
+
+///
+
+Tendrás errores en línea para los datos que envíes:
+
+
+
+El objeto de response también tendrá autocompletado:
+
+
+
+## App de FastAPI con tags { #fastapi-app-with-tags }
+
+En muchos casos tu app de FastAPI será más grande, y probablemente usarás tags para separar diferentes grupos de *path operations*.
+
+Por ejemplo, podrías tener una sección para **items** y otra sección para **users**, y podrían estar separadas por tags:
+
+{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}
+
+### Genera un Cliente TypeScript con tags { #generate-a-typescript-client-with-tags }
+
+Si generas un cliente para una app de FastAPI usando tags, normalmente también separará el código del cliente basándose en los tags.
+
+De esta manera podrás tener las cosas ordenadas y agrupadas correctamente para el código del cliente:
+
+
+
+En este caso tienes:
+
+* `ItemsService`
+* `UsersService`
+
+### Nombres de los métodos del cliente { #client-method-names }
+
+Ahora mismo los nombres de los métodos generados como `createItemItemsPost` no se ven muy limpios:
+
+```TypeScript
+ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
+```
+
+...eso es porque el generador del cliente usa el **operation ID** interno de OpenAPI para cada *path operation*.
+
+OpenAPI requiere que cada operation ID sea único a través de todas las *path operations*, por lo que FastAPI usa el **nombre de la función**, el **path**, y el **método/operación HTTP** para generar ese operation ID, porque de esa manera puede asegurarse de que los operation IDs sean únicos.
+
+Pero te mostraré cómo mejorar eso a continuación. 🤓
+
+## Operation IDs personalizados y mejores nombres de métodos { #custom-operation-ids-and-better-method-names }
+
+Puedes **modificar** la forma en que estos operation IDs son **generados** para hacerlos más simples y tener **nombres de métodos más simples** en los clientes.
+
+En este caso tendrás que asegurarte de que cada operation ID sea **único** de alguna otra manera.
+
+Por ejemplo, podrías asegurarte de que cada *path operation* tenga un tag, y luego generar el operation ID basado en el **tag** y el **name** de la *path operation* (el nombre de la función).
+
+### Función personalizada para generar ID único { #custom-generate-unique-id-function }
+
+FastAPI usa un **ID único** para cada *path operation*, se usa para el **operation ID** y también para los nombres de cualquier modelo personalizado necesario, para requests o responses.
+
+Puedes personalizar esa función. Toma un `APIRoute` y retorna un string.
+
+Por ejemplo, aquí está usando el primer tag (probablemente tendrás solo un tag) y el nombre de la *path operation* (el nombre de la función).
+
+Puedes entonces pasar esa función personalizada a **FastAPI** como el parámetro `generate_unique_id_function`:
+
+{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}
+
+### Genera un Cliente TypeScript con operation IDs personalizados { #generate-a-typescript-client-with-custom-operation-ids }
+
+Ahora, si generas el cliente de nuevo, verás que tiene los nombres de métodos mejorados:
+
+
+
+Como ves, los nombres de métodos ahora tienen el tag y luego el nombre de la función, ahora no incluyen información del path de la URL y la operación HTTP.
+
+### Preprocesa la especificación OpenAPI para el generador de clientes { #preprocess-the-openapi-specification-for-the-client-generator }
+
+El código generado aún tiene algo de **información duplicada**.
+
+Ya sabemos que este método está relacionado con los **items** porque esa palabra está en el `ItemsService` (tomado del tag), pero aún tenemos el nombre del tag prefijado en el nombre del método también. 😕
+
+Probablemente aún querremos mantenerlo para OpenAPI en general, ya que eso asegurará que los operation IDs sean **únicos**.
+
+Pero para el cliente generado podríamos **modificar** los operation IDs de OpenAPI justo antes de generar los clientes, solo para hacer esos nombres de métodos más bonitos y **limpios**.
+
+Podríamos descargar el JSON de OpenAPI a un archivo `openapi.json` y luego podríamos **remover ese tag prefijado** con un script como este:
+
+{* ../../docs_src/generate_clients/tutorial004_py310.py *}
+
+//// tab | Node.js
+
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
+```
+
+////
+
+Con eso, los operation IDs serían renombrados de cosas como `items-get_items` a solo `get_items`, de esa manera el generador del cliente puede generar nombres de métodos más simples.
+
+### Genera un Cliente TypeScript con el OpenAPI preprocesado { #generate-a-typescript-client-with-the-preprocessed-openapi }
+
+Como el resultado final ahora está en un archivo `openapi.json`, necesitas actualizar la ubicación de la entrada:
+
+```sh
+npx @hey-api/openapi-ts -i ./openapi.json -o src/client
+```
+
+Después de generar el nuevo cliente, ahora tendrías nombres de métodos **limpios**, con todo el **autocompletado**, **errores en línea**, etc:
+
+
+
+## Beneficios { #benefits }
+
+Cuando uses los clientes generados automáticamente obtendrás **autocompletado** para:
+
+* Métodos.
+* Payloads de request en el body, parámetros de query, etc.
+* Payloads de response.
+
+También tendrás **errores en línea** para todo.
+
+Y cada vez que actualices el código del backend, y **regeneres** el frontend, tendrás las nuevas *path operations* disponibles como métodos, las antiguas eliminadas, y cualquier otro cambio se reflejará en el código generado. 🤓
+
+Esto también significa que si algo cambió será **reflejado** automáticamente en el código del cliente. Y si haces **build** del cliente, dará error si tienes algún **desajuste** en los datos utilizados.
+
+Así que, **detectarás muchos errores** muy temprano en el ciclo de desarrollo en lugar de tener que esperar a que los errores se muestren a tus usuarios finales en producción para luego intentar depurar dónde está el problema. ✨
diff --git a/docs/es/docs/advanced/index.md b/docs/es/docs/advanced/index.md
index ba1d20b0d1758..a18a7fd64d14a 100644
--- a/docs/es/docs/advanced/index.md
+++ b/docs/es/docs/advanced/index.md
@@ -1,18 +1,21 @@
-# Guía de Usuario Avanzada
+# Guía avanzada del usuario { #advanced-user-guide }
-## Características Adicionales
+## Funcionalidades adicionales { #additional-features }
-El [Tutorial - Guía de Usuario](../tutorial/){.internal-link target=_blank} principal debe ser suficiente para darte un paseo por todas las características principales de **FastAPI**
+El [Tutorial - Guía del usuario](../tutorial/index.md) principal debería ser suficiente para darte un recorrido por todas las funcionalidades principales de **FastAPI**.
-En las secciones siguientes verás otras opciones, configuraciones, y características adicionales.
+En las siguientes secciones verás otras opciones, configuraciones y funcionalidades adicionales.
-!!! tip
- Las próximas secciones **no son necesariamente "avanzadas"**.
+/// tip | Consejo
- Y es posible que para tu caso, la solución se encuentre en una de estas.
+Las siguientes secciones **no son necesariamente "avanzadas"**.
-## Lee primero el Tutorial
+Y es posible que para tu caso de uso, la solución esté en una de ellas.
-Puedes continuar usando la mayoría de las características de **FastAPI** con el conocimiento del [Tutorial - Guía de Usuario](../tutorial/){.internal-link target=_blank} principal.
+///
-En las siguientes secciones se asume que lo has leído y conoces esas ideas principales.
+## Lee primero el Tutorial { #read-the-tutorial-first }
+
+Aún podrías usar la mayoría de las funcionalidades en **FastAPI** con el conocimiento del [Tutorial - Guía del usuario](../tutorial/index.md) principal.
+
+Y las siguientes secciones asumen que ya lo leíste y que conoces esas ideas principales.
diff --git a/docs/es/docs/advanced/json-base64-bytes.md b/docs/es/docs/advanced/json-base64-bytes.md
new file mode 100644
index 0000000000000..12936722c717f
--- /dev/null
+++ b/docs/es/docs/advanced/json-base64-bytes.md
@@ -0,0 +1,63 @@
+# JSON con Bytes como Base64 { #json-with-bytes-as-base64 }
+
+Si tu app necesita recibir y enviar datos JSON, pero necesitas incluir datos binarios en él, puedes codificarlos como base64.
+
+## Base64 vs Archivos { #base64-vs-files }
+
+Considera primero si puedes usar [Archivos en request](../tutorial/request-files.md) para subir datos binarios y [Response personalizada - FileResponse](./custom-response.md#fileresponse--fileresponse-) para enviar datos binarios, en lugar de codificarlos en JSON.
+
+JSON solo puede contener strings codificados en UTF-8, así que no puede contener bytes crudos.
+
+Base64 puede codificar datos binarios en strings, pero para hacerlo necesita usar más caracteres que los datos binarios originales, así que normalmente sería menos eficiente que los archivos normales.
+
+Usa base64 solo si definitivamente necesitas incluir datos binarios en JSON y no puedes usar archivos para eso.
+
+## Pydantic `bytes` { #pydantic-bytes }
+
+Puedes declarar un modelo de Pydantic con campos `bytes`, y luego usar `val_json_bytes` en la configuración del modelo para indicarle que use base64 para validar datos JSON de entrada; como parte de esa validación decodificará el string base64 en bytes.
+
+{* ../../docs_src/json_base64_bytes/tutorial001_py310.py ln[1:9,29:35] hl[9] *}
+
+Si revisas `/docs`, verás que el campo `data` espera bytes codificados en base64:
+
+
+
diff --git a/docs/es/docs/advanced/openapi-webhooks.md b/docs/es/docs/advanced/openapi-webhooks.md
new file mode 100644
index 0000000000000..163293f834013
--- /dev/null
+++ b/docs/es/docs/advanced/openapi-webhooks.md
@@ -0,0 +1,55 @@
+# Webhooks de OpenAPI { #openapi-webhooks }
+
+Hay casos donde quieres decirle a los **usuarios** de tu API que tu aplicación podría llamar a *su* aplicación (enviando una request) con algunos datos, normalmente para **notificar** de algún tipo de **evento**.
+
+Esto significa que en lugar del proceso normal de tus usuarios enviando requests a tu API, es **tu API** (o tu aplicación) la que podría **enviar requests a su sistema** (a su API, su aplicación).
+
+Esto normalmente se llama un **webhook**.
+
+## Pasos de los webhooks { #webhooks-steps }
+
+El proceso normalmente es que **tú defines** en tu código cuál es el mensaje que enviarás, el **body de la request**.
+
+También defines de alguna manera en qué **momentos** tu aplicación enviará esas requests o eventos.
+
+Y **tus usuarios** definen de alguna manera (por ejemplo en un panel web en algún lugar) el **URL** donde tu aplicación debería enviar esas requests.
+
+Toda la **lógica** sobre cómo registrar los URLs para webhooks y el código para realmente enviar esas requests depende de ti. Lo escribes como quieras en **tu propio código**.
+
+## Documentando webhooks con **FastAPI** y OpenAPI { #documenting-webhooks-with-fastapi-and-openapi }
+
+Con **FastAPI**, usando OpenAPI, puedes definir los nombres de estos webhooks, los tipos de operaciones HTTP que tu aplicación puede enviar (por ejemplo, `POST`, `PUT`, etc.) y los **bodies** de las requests que tu aplicación enviaría.
+
+Esto puede hacer mucho más fácil para tus usuarios **implementar sus APIs** para recibir tus requests de **webhook**, incluso podrían ser capaces de autogenerar algo de su propio código de API.
+
+/// info | Información
+
+Los webhooks están disponibles en OpenAPI 3.1.0 y superiores, soportados por FastAPI `0.99.0` y superiores.
+
+///
+
+## Una aplicación con webhooks { #an-app-with-webhooks }
+
+Cuando creas una aplicación de **FastAPI**, hay un atributo `webhooks` que puedes usar para definir *webhooks*, de la misma manera que definirías *path operations*, por ejemplo con `@app.webhooks.post()`.
+
+{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}
+
+Los webhooks que defines terminarán en el esquema de **OpenAPI** y en la interfaz automática de **documentación**.
+
+/// info | Información
+
+El objeto `app.webhooks` es en realidad solo un `APIRouter`, el mismo tipo que usarías al estructurar tu aplicación con múltiples archivos.
+
+///
+
+Nota que con los webhooks en realidad no estás declarando un *path* (como `/items/`), el texto que pasas allí es solo un **identificador** del webhook (el nombre del evento), por ejemplo en `@app.webhooks.post("new-subscription")`, el nombre del webhook es `new-subscription`.
+
+Esto es porque se espera que **tus usuarios** definan el actual **URL path** donde quieren recibir la request del webhook de alguna otra manera (por ejemplo, un panel web).
+
+### Revisa la documentación { #check-the-docs }
+
+Ahora puedes iniciar tu app e ir a [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).
+
+Verás que tu documentación tiene las *path operations* normales y ahora también algunos **webhooks**:
+
+
diff --git a/docs/es/docs/advanced/path-operation-advanced-configuration.md b/docs/es/docs/advanced/path-operation-advanced-configuration.md
index e4edcc52bb4e3..a21975bc7c73f 100644
--- a/docs/es/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/es/docs/advanced/path-operation-advanced-configuration.md
@@ -1,52 +1,172 @@
-# Configuración avanzada de las operaciones de path
+# Configuración Avanzada de Path Operation { #path-operation-advanced-configuration }
-## OpenAPI operationId
+## operationId de OpenAPI { #openapi-operationid }
-!!! warning "Advertencia"
- Si no eres una persona "experta" en OpenAPI, probablemente no necesitas leer esto.
+/// warning | Advertencia
-Puedes asignar el `operationId` de OpenAPI para ser usado en tu *operación de path* con el parámetro `operation_id`.
+Si no eres un "experto" en OpenAPI, probablemente no necesites esto.
-En este caso tendrías que asegurarte de que sea único para cada operación.
+///
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
-```
+Puedes establecer el `operationId` de OpenAPI para ser usado en tu *path operation* con el parámetro `operation_id`.
-### Usando el nombre de la *función de la operación de path* en el operationId
+Tendrías que asegurarte de que sea único para cada operación.
-Si quieres usar tus nombres de funciones de API como `operationId`s, puedes iterar sobre todos ellos y sobrescribir `operation_id` de cada *operación de path* usando su `APIRoute.name`.
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
-Deberías hacerlo después de adicionar todas tus *operaciones de path*.
+### Usar el nombre de la *path operation function* como el operationId { #using-the-path-operation-function-name-as-the-operationid }
-```Python hl_lines="2 12 13 14 15 16 17 18 19 20 21 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
-```
+Si quieres usar los nombres de las funciones de tus APIs como `operationId`s, puedes iterar sobre todas ellas y sobrescribir el `operation_id` de cada *path operation* usando su `APIRoute.name`.
-!!! tip "Consejo"
- Si llamas manualmente a `app.openapi()`, debes actualizar el `operationId`s antes de hacerlo.
+Deberías hacerlo después de agregar todas tus *path operations*.
-!!! warning "Advertencia"
- Si haces esto, debes asegurarte de que cada una de tus *funciones de las operaciones de path* tenga un nombre único.
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *}
- Incluso si están en diferentes módulos (archivos Python).
+/// tip | Consejo
-## Excluir de OpenAPI
+Si llamas manualmente a `app.openapi()`, deberías actualizar los `operationId`s antes de eso.
-Para excluir una *operación de path* del esquema OpenAPI generado (y por tanto del la documentación generada automáticamente), usa el parámetro `include_in_schema` y asigna el valor como `False`;
+///
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
-```
+/// warning | Advertencia
+
+Si haces esto, tienes que asegurarte de que cada una de tus *path operation functions* tenga un nombre único.
+
+Incluso si están en diferentes módulos (archivos de Python).
+
+///
+
+## Excluir de OpenAPI { #exclude-from-openapi }
+
+Para excluir una *path operation* del esquema OpenAPI generado (y por lo tanto, de los sistemas de documentación automática), utiliza el parámetro `include_in_schema` y configúralo en `False`:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}
+
+## Descripción avanzada desde el docstring { #advanced-description-from-docstring }
+
+Puedes limitar las líneas usadas del docstring de una *path operation function* para OpenAPI.
+
+Añadir un `\f` (un carácter "form feed" escapado) hace que **FastAPI** trunque la salida usada para OpenAPI en este punto.
+
+No aparecerá en la documentación, pero otras herramientas (como Sphinx) podrán usar el resto.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}
+
+## Responses Adicionales { #additional-responses }
+
+Probablemente has visto cómo declarar el `response_model` y el `status_code` para una *path operation*.
+
+Eso define los metadatos sobre el response principal de una *path operation*.
+
+También puedes declarar responses adicionales con sus modelos, códigos de estado, etc.
+
+Hay un capítulo entero en la documentación sobre ello, puedes leerlo en [Responses Adicionales en OpenAPI](additional-responses.md).
+
+## OpenAPI Extra { #openapi-extra }
+
+Cuando declaras una *path operation* en tu aplicación, **FastAPI** genera automáticamente los metadatos relevantes sobre esa *path operation* para incluirlos en el esquema de OpenAPI.
+
+/// note | Detalles técnicos
+
+En la especificación de OpenAPI se llama el [Objeto de Operación](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object).
+
+///
+
+Tiene toda la información sobre la *path operation* y se usa para generar la documentación automática.
+
+Incluye los `tags`, `parameters`, `requestBody`, `responses`, etc.
+
+Este esquema de OpenAPI específico de *path operation* normalmente se genera automáticamente por **FastAPI**, pero también puedes extenderlo.
+
+/// tip | Consejo
-## Descripción avanzada desde el docstring
+Este es un punto de extensión de bajo nivel.
-Puedes limitar las líneas usadas desde el docstring de una *operación de path* para OpenAPI.
+Si solo necesitas declarar responses adicionales, una forma más conveniente de hacerlo es con [Responses Adicionales en OpenAPI](additional-responses.md).
-Agregar un `\f` (un carácter de "form feed" escapado) hace que **FastAPI** trunque el output utilizada para OpenAPI en ese punto.
+///
-No será mostrado en la documentación, pero otras herramientas (como Sphinx) serán capaces de usar el resto.
+Puedes extender el esquema de OpenAPI para una *path operation* usando el parámetro `openapi_extra`.
-```Python hl_lines="19 20 21 22 23 24 25 26 27 28 29"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
+### Extensiones de OpenAPI { #openapi-extensions }
+
+Este `openapi_extra` puede ser útil, por ejemplo, para declarar [Extensiones de OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py310.py hl[6] *}
+
+Si abres la documentación automática de la API, tu extensión aparecerá en la parte inferior de la *path operation* específica.
+
+
+
+Y si ves el OpenAPI resultante (en `/openapi.json` en tu API), verás tu extensión como parte de la *path operation* específica también:
+
+```JSON hl_lines="22"
+{
+ "openapi": "3.1.0",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0"
+ },
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ }
+ },
+ "x-aperture-labs-portal": "blue"
+ }
+ }
+ }
+}
```
+
+### Esquema de *path operation* personalizada de OpenAPI { #custom-openapi-path-operation-schema }
+
+El diccionario en `openapi_extra` se combinará profundamente con el esquema de OpenAPI generado automáticamente para la *path operation*.
+
+Por lo tanto, podrías añadir datos adicionales al esquema generado automáticamente.
+
+Por ejemplo, podrías decidir leer y validar el request con tu propio código, sin usar las funcionalidades automáticas de FastAPI con Pydantic, pero aún podrías querer definir el request en el esquema de OpenAPI.
+
+Podrías hacer eso con `openapi_extra`:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py310.py hl[19:36, 39:40] *}
+
+En este ejemplo, no declaramos ningún modelo Pydantic. De hecho, el request body ni siquiera es parseado como JSON, se lee directamente como `bytes`, y la función `magic_data_reader()` sería la encargada de hacer parse de él de alguna manera.
+
+Sin embargo, podemos declarar el esquema esperado para el request body.
+
+### Tipo de contenido personalizado de OpenAPI { #custom-openapi-content-type }
+
+Usando este mismo truco, podrías usar un modelo Pydantic para definir el JSON Schema que luego se incluye en la sección personalizada del esquema OpenAPI para la *path operation*.
+
+Y podrías hacer esto incluso si el tipo de datos en el request no es JSON.
+
+Por ejemplo, en esta aplicación no usamos la funcionalidad integrada de FastAPI para extraer el JSON Schema de los modelos Pydantic ni la validación automática para JSON. De hecho, estamos declarando el tipo de contenido del request como YAML, no JSON:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[15:20, 22] *}
+
+Sin embargo, aunque no estamos usando la funcionalidad integrada por defecto, aún estamos usando un modelo Pydantic para generar manualmente el JSON Schema para los datos que queremos recibir en YAML.
+
+Luego usamos el request directamente, y extraemos el cuerpo como `bytes`. Esto significa que FastAPI ni siquiera intentará hacer parse de la carga útil del request como JSON.
+
+Y luego en nuestro código, hacemos parse de ese contenido YAML directamente, y nuevamente estamos usando el mismo modelo Pydantic para validar el contenido YAML:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *}
+
+/// tip | Consejo
+
+Aquí reutilizamos el mismo modelo Pydantic.
+
+Pero de la misma manera, podríamos haberlo validado de alguna otra forma.
+
+///
diff --git a/docs/es/docs/advanced/response-change-status-code.md b/docs/es/docs/advanced/response-change-status-code.md
new file mode 100644
index 0000000000000..859f484de6c64
--- /dev/null
+++ b/docs/es/docs/advanced/response-change-status-code.md
@@ -0,0 +1,31 @@
+# Response - Cambiar Código de Estado { #response-change-status-code }
+
+Probablemente leíste antes que puedes establecer un [Código de Estado de Response](../tutorial/response-status-code.md) por defecto.
+
+Pero en algunos casos necesitas devolver un código de estado diferente al predeterminado.
+
+## Caso de uso { #use-case }
+
+Por ejemplo, imagina que quieres devolver un código de estado HTTP de "OK" `200` por defecto.
+
+Pero si los datos no existieran, quieres crearlos y devolver un código de estado HTTP de "CREATED" `201`.
+
+Pero todavía quieres poder filtrar y convertir los datos que devuelves con un `response_model`.
+
+Para esos casos, puedes usar un parámetro `Response`.
+
+## Usa un parámetro `Response` { #use-a-response-parameter }
+
+Puedes declarar un parámetro de tipo `Response` en tu *path operation function* (como puedes hacer para cookies y headers).
+
+Y luego puedes establecer el `status_code` en ese objeto de response *temporal*.
+
+{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}
+
+Y luego puedes devolver cualquier objeto que necesites, como lo harías normalmente (un `dict`, un modelo de base de datos, etc).
+
+Y si declaraste un `response_model`, todavía se utilizará para filtrar y convertir el objeto que devolviste.
+
+**FastAPI** usará ese response *temporal* para extraer el código de estado (también cookies y headers), y los pondrá en el response final que contiene el valor que devolviste, filtrado por cualquier `response_model`.
+
+También puedes declarar el parámetro `Response` en dependencias y establecer el código de estado en ellas. Pero ten en cuenta que el último establecido prevalecerá.
diff --git a/docs/es/docs/advanced/response-cookies.md b/docs/es/docs/advanced/response-cookies.md
new file mode 100644
index 0000000000000..e40a19129891a
--- /dev/null
+++ b/docs/es/docs/advanced/response-cookies.md
@@ -0,0 +1,51 @@
+# Cookies de Response { #response-cookies }
+
+## Usar un parámetro `Response` { #use-a-response-parameter }
+
+Puedes declarar un parámetro de tipo `Response` en tu *path operation function*.
+
+Y luego puedes establecer cookies en ese objeto de response *temporal*.
+
+{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}
+
+Y entonces puedes devolver cualquier objeto que necesites, como normalmente lo harías (un `dict`, un modelo de base de datos, etc).
+
+Y si declaraste un `response_model`, todavía se utilizará para filtrar y convertir el objeto que devolviste.
+
+**FastAPI** utilizará ese response *temporal* para extraer las cookies (también los headers y el código de estado), y las pondrá en el response final que contiene el valor que devolviste, filtrado por cualquier `response_model`.
+
+También puedes declarar el parámetro `Response` en las dependencias, y establecer cookies (y headers) en ellas.
+
+## Devolver una `Response` directamente { #return-a-response-directly }
+
+También puedes crear cookies al devolver una `Response` directamente en tu código.
+
+Para hacer eso, puedes crear un response como se describe en [Devolver un Response Directamente](response-directly.md).
+
+Luego establece Cookies en ella, y luego devuélvela:
+
+{* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *}
+
+/// tip | Consejo
+
+Ten en cuenta que si devuelves un response directamente en lugar de usar el parámetro `Response`, FastAPI lo devolverá directamente.
+
+Así que tendrás que asegurarte de que tus datos son del tipo correcto. Por ejemplo, que sea compatible con JSON, si estás devolviendo un `JSONResponse`.
+
+Y también que no estés enviando ningún dato que debería haber sido filtrado por un `response_model`.
+
+///
+
+### Más información { #more-info }
+
+/// note | Detalles Técnicos
+
+También podrías usar `from starlette.responses import Response` o `from starlette.responses import JSONResponse`.
+
+**FastAPI** proporciona los mismos `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette.
+
+Y como el `Response` se puede usar frecuentemente para establecer headers y cookies, **FastAPI** también lo proporciona en `fastapi.Response`.
+
+///
+
+Para ver todos los parámetros y opciones disponibles, revisa la [documentación en Starlette](https://www.starlette.dev/responses/#set-cookie).
diff --git a/docs/es/docs/advanced/response-directly.md b/docs/es/docs/advanced/response-directly.md
index 54dadf5763a9b..b2d5d18b88896 100644
--- a/docs/es/docs/advanced/response-directly.md
+++ b/docs/es/docs/advanced/response-directly.md
@@ -1,63 +1,83 @@
-# Devolver una respuesta directamente
+# Devolver una Response Directamente { #return-a-response-directly }
-Cuando creas una *operación de path* normalmente puedes devolver cualquier dato: un `dict`, una `list`, un modelo Pydantic, un modelo de base de datos, etc.
+Cuando creas una *path operation* en **FastAPI**, normalmente puedes devolver cualquier dato desde ella: un `dict`, una `list`, un modelo de Pydantic, un modelo de base de datos, etc.
-Por defecto, **FastAPI** convertiría automáticamente ese valor devuelto a JSON usando el `jsonable_encoder` explicado en [Codificador Compatible JSON](../tutorial/encoder.md){.internal-link target=_blank}.
+Si declaras un [Response Model](../tutorial/response-model.md) FastAPI lo usará para serializar los datos a JSON, usando Pydantic.
-Luego, tras bastidores, pondría esos datos compatibles con JSON (por ejemplo, un `dict`) dentro de una `JSONResponse` que se usaría para enviar la respuesta al cliente.
+Si no declaras un response model, FastAPI usará el `jsonable_encoder` explicado en [JSON Compatible Encoder](../tutorial/encoder.md) y lo pondrá en un `JSONResponse`.
-Pero puedes devolver una `JSONResponse` directamente de tu *operación de path*.
+También podrías crear un `JSONResponse` directamente y devolverlo.
-Esto puede ser útil, por ejemplo, para devolver cookies o headers personalizados.
+/// tip | Consejo
-## Devolver una `Response`
+Normalmente tendrás mucho mejor rendimiento usando un [Response Model](../tutorial/response-model.md) que devolviendo un `JSONResponse` directamente, ya que de esa forma serializa los datos usando Pydantic, en Rust.
-De hecho, puedes devolver cualquier `Response` o cualquier subclase de la misma.
+///
-!!! tip "Consejo"
- `JSONResponse` en sí misma es una subclase de `Response`.
+## Devolver una `Response` { #return-a-response }
+
+De hecho, puedes devolver cualquier `Response` o cualquier subclase de ella.
+
+/// info | Información
+
+`JSONResponse` en sí misma es una subclase de `Response`.
+
+///
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.
+No hará ninguna conversión de datos con los modelos de Pydantic, no convertirá los contenidos a ningún tipo, etc.
+
+Esto te da mucha flexibilidad. Puedes devolver cualquier tipo de datos, sobrescribir cualquier declaración o validación de datos, etc.
+
+También te da mucha responsabilidad. Tienes que asegurarte de que los datos que devuelves sean correctos, en el formato correcto, que se puedan serializar, etc.
+
+## Usar el `jsonable_encoder` en una `Response` { #using-the-jsonable-encoder-in-a-response }
+
+Como **FastAPI** no realiza cambios en una `Response` que devuelves, tienes que asegurarte de que sus contenidos estén listos para ello.
+
+Por ejemplo, no puedes poner un modelo de Pydantic en un `JSONResponse` sin primero convertirlo a un `dict` con todos los tipos de datos (como `datetime`, `UUID`, etc.) convertidos a tipos compatibles con JSON.
+
+Para esos casos, puedes usar el `jsonable_encoder` para convertir tus datos antes de pasarlos a un response:
+
+{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}
+
+/// note | Detalles técnicos
+
+También podrías usar `from starlette.responses import JSONResponse`.
-Esto te da mucha flexibilidad. Puedes devolver cualquier tipo de dato, sobrescribir cualquer declaración de datos o validación, etc.
+**FastAPI** proporciona los mismos `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette.
-## Usando el `jsonable_encoder` en una `Response`
+///
-Como **FastAPI** no realiza ningún cambio en la `Response` que devuelves, debes asegurarte de que el contenido está listo.
+## Devolver una `Response` personalizada { #returning-a-custom-response }
-Por ejemplo, no puedes poner un modelo Pydantic en una `JSONResponse` sin primero convertirlo a un `dict` con todos los tipos de datos (como `datetime`, `UUID`, etc) convertidos a tipos compatibles con JSON.
+El ejemplo anterior muestra todas las partes que necesitas, pero aún no es muy útil, ya que podrías haber devuelto el `item` directamente, y **FastAPI** lo colocaría en un `JSONResponse` por ti, convirtiéndolo a un `dict`, etc. Todo eso por defecto.
-Para esos casos, puedes usar el `jsonable_encoder` para convertir tus datos antes de pasarlos a la respuesta:
+Ahora, veamos cómo podrías usar eso para devolver un response personalizado.
-```Python hl_lines="4 6 20 21"
-{!../../../docs_src/response_directly/tutorial001.py!}
-```
+Digamos que quieres devolver un response en [XML](https://en.wikipedia.org/wiki/XML).
-!!! note "Detalles Técnicos"
- También puedes usar `from starlette.responses import JSONResponse`.
+Podrías poner tu contenido XML en un string, poner eso en un `Response`, y devolverlo:
- **FastAPI** provee `starlette.responses` como `fastapi.responses`, simplemente como una conveniencia para ti, el desarrollador. Pero la mayoría de las respuestas disponibles vienen directamente de Starlette.
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
-## Devolviendo una `Response` personalizada
+## Cómo funciona un Response Model { #how-a-response-model-works }
-El ejemplo anterior muestra las partes que necesitas, pero no es muy útil todavía, dado que podrías simplemente devolver el `item` directamente, y **FastAPI** lo pondría en una `JSONResponse` por ti, convirtiéndolo en un `dict`, etc. Todo esto por defecto.
+Cuando declaras un [Response Model - Return Type](../tutorial/response-model.md) en una *path operation*, **FastAPI** lo usará para serializar los datos a JSON, usando Pydantic.
-Ahora, veamos cómo puedes usarlo para devolver una respuesta personalizada.
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
-Digamos que quieres devolver una respuesta XML.
+Como eso sucederá del lado de Rust, el rendimiento será mucho mejor que si se hiciera con Python normal y la clase `JSONResponse`.
-Podrías poner tu contenido XML en un string, ponerlo en una `Response` y devolverlo:
+Al usar un `response_model` o tipo de retorno, FastAPI no usará el `jsonable_encoder` para convertir los datos (lo cual sería más lento) ni la clase `JSONResponse`.
-```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
-```
+En su lugar, toma los bytes JSON generados con Pydantic usando el response model (o tipo de retorno) y devuelve una `Response` con el media type correcto para JSON directamente (`application/json`).
-## Notas
+## Notas { #notes }
-Cuando devuelves una `Response` directamente, los datos no son validados, convertidos (serializados), ni documentados automáticamente.
+Cuando devuelves una `Response` directamente, sus datos no son validados, convertidos (serializados), ni documentados automáticamente.
-Pero todavía es posible documentarlo como es descrito en [Respuestas adicionales en OpenAPI](additional-responses.md){.internal-link target=_blank}.
+Pero aún puedes documentarlo como se describe en [Additional Responses in OpenAPI](additional-responses.md).
-Puedes ver en secciones posteriores como usar/declarar esas `Response`s personalizadas aún teniendo conversión automática de datos, documentación, etc.
+Puedes ver en secciones posteriores cómo usar/declarar estas `Response`s personalizadas mientras todavía tienes conversión automática de datos, documentación, etc.
diff --git a/docs/es/docs/advanced/response-headers.md b/docs/es/docs/advanced/response-headers.md
new file mode 100644
index 0000000000000..06107eb2d1e15
--- /dev/null
+++ b/docs/es/docs/advanced/response-headers.md
@@ -0,0 +1,41 @@
+# Headers de Response { #response-headers }
+
+## Usa un parámetro `Response` { #use-a-response-parameter }
+
+Puedes declarar un parámetro de tipo `Response` en tu *path operation function* (como puedes hacer para cookies).
+
+Y luego puedes establecer headers en ese objeto de response *temporal*.
+
+{* ../../docs_src/response_headers/tutorial002_py310.py hl[1, 7:8] *}
+
+Y luego puedes devolver cualquier objeto que necesites, como harías normalmente (un `dict`, un modelo de base de datos, etc).
+
+Y si declaraste un `response_model`, aún se usará para filtrar y convertir el objeto que devolviste.
+
+**FastAPI** usará ese response *temporal* para extraer los headers (también cookies y el código de estado), y los pondrá en el response final que contiene el valor que devolviste, filtrado por cualquier `response_model`.
+
+También puedes declarar el parámetro `Response` en dependencias y establecer headers (y cookies) en ellas.
+
+## Retorna una `Response` directamente { #return-a-response-directly }
+
+También puedes agregar headers cuando devuelves un `Response` directamente.
+
+Crea un response como se describe en [Retorna un Response Directamente](response-directly.md) y pasa los headers como un parámetro adicional:
+
+{* ../../docs_src/response_headers/tutorial001_py310.py hl[10:12] *}
+
+/// note | Detalles Técnicos
+
+También podrías usar `from starlette.responses import Response` o `from starlette.responses import JSONResponse`.
+
+**FastAPI** proporciona las mismas `starlette.responses` como `fastapi.responses` solo por conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles provienen directamente de Starlette.
+
+Y como el `Response` se puede usar frecuentemente para establecer headers y cookies, **FastAPI** también lo proporciona en `fastapi.Response`.
+
+///
+
+## Headers Personalizados { #custom-headers }
+
+Ten en cuenta que los headers propietarios personalizados se pueden agregar [usando el prefijo `X-`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers).
+
+Pero si tienes headers personalizados que quieres que un cliente en un navegador pueda ver, necesitas agregarlos a tus configuraciones de CORS (leer más en [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md)), usando el parámetro `expose_headers` documentado en [la documentación CORS de Starlette](https://www.starlette.dev/middleware/#corsmiddleware).
diff --git a/docs/es/docs/advanced/security/http-basic-auth.md b/docs/es/docs/advanced/security/http-basic-auth.md
new file mode 100644
index 0000000000000..c9c1562b5a31a
--- /dev/null
+++ b/docs/es/docs/advanced/security/http-basic-auth.md
@@ -0,0 +1,107 @@
+# HTTP Basic Auth { #http-basic-auth }
+
+Para los casos más simples, puedes usar HTTP Basic Auth.
+
+En HTTP Basic Auth, la aplicación espera un header que contiene un nombre de usuario y una contraseña.
+
+Si no lo recibe, devuelve un error HTTP 401 "Unauthorized".
+
+Y devuelve un header `WWW-Authenticate` con un valor de `Basic`, y un parámetro `realm` opcional.
+
+Eso le dice al navegador que muestre el prompt integrado para un nombre de usuario y contraseña.
+
+Luego, cuando escribes ese nombre de usuario y contraseña, el navegador los envía automáticamente en el header.
+
+## Simple HTTP Basic Auth { #simple-http-basic-auth }
+
+* Importa `HTTPBasic` y `HTTPBasicCredentials`.
+* Crea un "esquema de `security`" usando `HTTPBasic`.
+* Usa ese `security` con una dependencia en tu *path operation*.
+* Devuelve un objeto de tipo `HTTPBasicCredentials`:
+ * Contiene el `username` y `password` enviados.
+
+{* ../../docs_src/security/tutorial006_an_py310.py hl[4,8,12] *}
+
+Cuando intentas abrir la URL por primera vez (o haces clic en el botón "Execute" en la documentación) el navegador te pedirá tu nombre de usuario y contraseña:
+
+
+
+## Revisa el nombre de usuario { #check-the-username }
+
+Aquí hay un ejemplo más completo.
+
+Usa una dependencia para comprobar si el nombre de usuario y la contraseña son correctos.
+
+Para esto, usa el módulo estándar de Python [`secrets`](https://docs.python.org/3/library/secrets.html) para verificar el nombre de usuario y la contraseña.
+
+`secrets.compare_digest()` necesita tomar `bytes` o un `str` que solo contenga caracteres ASCII (los carácteres en inglés), esto significa que no funcionaría con caracteres como `á`, como en `Sebastián`.
+
+Para manejar eso, primero convertimos el `username` y `password` a `bytes` codificándolos con UTF-8.
+
+Luego podemos usar `secrets.compare_digest()` para asegurar que `credentials.username` es `"stanleyjobson"`, y que `credentials.password` es `"swordfish"`.
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[1,12:24] *}
+
+Esto sería similar a:
+
+```Python
+if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
+ # Devuelve algún error
+ ...
+```
+
+Pero al usar `secrets.compare_digest()` será seguro contra un tipo de ataques llamados "timing attacks".
+
+### Timing attacks { #timing-attacks }
+
+¿Pero qué es un "timing attack"?
+
+Imaginemos que algunos atacantes están tratando de adivinar el nombre de usuario y la contraseña.
+
+Y envían un request con un nombre de usuario `johndoe` y una contraseña `love123`.
+
+Entonces el código de Python en tu aplicación equivaldría a algo como:
+
+```Python
+if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Pero justo en el momento en que Python compara la primera `j` en `johndoe` con la primera `s` en `stanleyjobson`, devolverá `False`, porque ya sabe que esas dos strings no son iguales, pensando que "no hay necesidad de gastar más computación comparando el resto de las letras". Y tu aplicación dirá "Nombre de usuario o contraseña incorrectos".
+
+Pero luego los atacantes prueban con el nombre de usuario `stanleyjobsox` y contraseña `love123`.
+
+Y el código de tu aplicación hace algo así como:
+
+```Python
+if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Python tendrá que comparar todo `stanleyjobso` en ambos `stanleyjobsox` y `stanleyjobson` antes de darse cuenta de que ambas strings no son las mismas. Así que tomará algunos microsegundos extra para responder "Nombre de usuario o contraseña incorrectos".
+
+#### El tiempo de respuesta ayuda a los atacantes { #the-time-to-answer-helps-the-attackers }
+
+En ese punto, al notar que el servidor tardó algunos microsegundos más en enviar el response "Nombre de usuario o contraseña incorrectos", los atacantes sabrán que acertaron en _algo_, algunas de las letras iniciales eran correctas.
+
+Y luego pueden intentar de nuevo sabiendo que probablemente es algo más similar a `stanleyjobsox` que a `johndoe`.
+
+#### Un ataque "profesional" { #a-professional-attack }
+
+Por supuesto, los atacantes no intentarían todo esto a mano, escribirían un programa para hacerlo, posiblemente con miles o millones de pruebas por segundo. Y obtendrían solo una letra correcta adicional a la vez.
+
+Pero haciendo eso, en algunos minutos u horas, los atacantes habrían adivinado el nombre de usuario y la contraseña correctos, con la "ayuda" de nuestra aplicación, solo usando el tiempo tomado para responder.
+
+#### Arréglalo con `secrets.compare_digest()` { #fix-it-with-secrets-compare-digest }
+
+Pero en nuestro código estamos usando realmente `secrets.compare_digest()`.
+
+En resumen, tomará el mismo tiempo comparar `stanleyjobsox` con `stanleyjobson` que comparar `johndoe` con `stanleyjobson`. Y lo mismo para la contraseña.
+
+De esa manera, usando `secrets.compare_digest()` en el código de tu aplicación, será seguro contra todo este rango de ataques de seguridad.
+
+### Devuelve el error { #return-the-error }
+
+Después de detectar que las credenciales son incorrectas, regresa un `HTTPException` con un código de estado 401 (el mismo que se devuelve cuando no se proporcionan credenciales) y agrega el header `WWW-Authenticate` para que el navegador muestre el prompt de inicio de sesión nuevamente:
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[26:30] *}
diff --git a/docs/es/docs/advanced/security/index.md b/docs/es/docs/advanced/security/index.md
new file mode 100644
index 0000000000000..3aa4d2dcf8cce
--- /dev/null
+++ b/docs/es/docs/advanced/security/index.md
@@ -0,0 +1,19 @@
+# Seguridad Avanzada { #advanced-security }
+
+## Funcionalidades Adicionales { #additional-features }
+
+Hay algunas funcionalidades extra para manejar la seguridad aparte de las cubiertas en el [Tutorial - Guía del Usuario: Seguridad](../../tutorial/security/index.md).
+
+/// tip | Consejo
+
+Las siguientes secciones no son necesariamente "avanzadas".
+
+Y es posible que para tu caso de uso, la solución esté en una de ellas.
+
+///
+
+## Lee primero el Tutorial { #read-the-tutorial-first }
+
+Las siguientes secciones asumen que ya leíste el [Tutorial - Guía del Usuario: Seguridad](../../tutorial/security/index.md) principal.
+
+Todas están basadas en los mismos conceptos, pero permiten algunas funcionalidades adicionales.
diff --git a/docs/es/docs/advanced/security/oauth2-scopes.md b/docs/es/docs/advanced/security/oauth2-scopes.md
new file mode 100644
index 0000000000000..6ee3dd5ac977f
--- /dev/null
+++ b/docs/es/docs/advanced/security/oauth2-scopes.md
@@ -0,0 +1,274 @@
+# Scopes de OAuth2 { #oauth2-scopes }
+
+Puedes usar scopes de OAuth2 directamente con **FastAPI**, están integrados para funcionar de manera fluida.
+
+Esto te permitiría tener un sistema de permisos más detallado, siguiendo el estándar de OAuth2, integrado en tu aplicación OpenAPI (y la documentación de la API).
+
+OAuth2 con scopes es el mecanismo usado por muchos grandes proveedores de autenticación, como Facebook, Google, GitHub, Microsoft, X (Twitter), etc. Lo usan para proporcionar permisos específicos a usuarios y aplicaciones.
+
+Cada vez que te "logueas con" Facebook, Google, GitHub, Microsoft, X (Twitter), esa aplicación está usando OAuth2 con scopes.
+
+En esta sección verás cómo manejar autenticación y autorización con el mismo OAuth2 con scopes en tu aplicación de **FastAPI**.
+
+/// warning | Advertencia
+
+Esta es una sección más o menos avanzada. Si estás comenzando, puedes saltarla.
+
+No necesariamente necesitas scopes de OAuth2, y puedes manejar autenticación y autorización como quieras.
+
+Pero OAuth2 con scopes se puede integrar muy bien en tu API (con OpenAPI) y en la documentación de tu API.
+
+No obstante, tú aún impones esos scopes, o cualquier otro requisito de seguridad/autorización, como necesites, en tu código.
+
+En muchos casos, OAuth2 con scopes puede ser un exceso.
+
+Pero si sabes que lo necesitas, o tienes curiosidad, sigue leyendo.
+
+///
+
+## Scopes de OAuth2 y OpenAPI { #oauth2-scopes-and-openapi }
+
+La especificación de OAuth2 define "scopes" como una lista de strings separados por espacios.
+
+El contenido de cada uno de estos strings puede tener cualquier formato, pero no debe contener espacios.
+
+Estos scopes representan "permisos".
+
+En OpenAPI (por ejemplo, en la documentación de la API), puedes definir "esquemas de seguridad".
+
+Cuando uno de estos esquemas de seguridad usa OAuth2, también puedes declarar y usar scopes.
+
+Cada "scope" es solo un string (sin espacios).
+
+Normalmente se utilizan para declarar permisos de seguridad específicos, por ejemplo:
+
+* `users:read` o `users:write` son ejemplos comunes.
+* `instagram_basic` es usado por Facebook / Instagram.
+* `https://www.googleapis.com/auth/drive` es usado por Google.
+
+/// info | Información
+
+En OAuth2 un "scope" es solo un string que declara un permiso específico requerido.
+
+No importa si tiene otros caracteres como `:` o si es una URL.
+
+Esos detalles son específicos de la implementación.
+
+Para OAuth2 son solo strings.
+
+///
+
+## Vista global { #global-view }
+
+Primero, echemos un vistazo rápido a las partes que cambian desde los ejemplos en el **Tutorial - User Guide** principal para [OAuth2 con Password (y hashing), Bearer con tokens JWT](../../tutorial/security/oauth2-jwt.md). Ahora usando scopes de OAuth2:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}
+
+Ahora revisemos esos cambios paso a paso.
+
+## Esquema de seguridad OAuth2 { #oauth2-security-scheme }
+
+El primer cambio es que ahora estamos declarando el esquema de seguridad OAuth2 con dos scopes disponibles, `me` y `items`.
+
+El parámetro `scopes` recibe un `dict` con cada scope como clave y la descripción como valor:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *}
+
+Como ahora estamos declarando esos scopes, aparecerán en la documentación de la API cuando inicies sesión/autorices.
+
+Y podrás seleccionar cuáles scopes quieres dar de acceso: `me` y `items`.
+
+Este es el mismo mecanismo utilizado cuando das permisos al iniciar sesión con Facebook, Google, GitHub, etc:
+
+
+
+## Token JWT con scopes { #jwt-token-with-scopes }
+
+Ahora, modifica la *path operation* del token para devolver los scopes solicitados.
+
+Todavía estamos usando el mismo `OAuth2PasswordRequestForm`. Incluye una propiedad `scopes` con una `list` de `str`, con cada scope que recibió en el request.
+
+Y devolvemos los scopes como parte del token JWT.
+
+/// danger | Peligro
+
+Para simplificar, aquí solo estamos añadiendo los scopes recibidos directamente al token.
+
+Pero en tu aplicación, por seguridad, deberías asegurarte de añadir solo los scopes que el usuario realmente puede tener, o los que has predefinido.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}
+
+## Declarar scopes en *path operations* y dependencias { #declare-scopes-in-path-operations-and-dependencies }
+
+Ahora declaramos que la *path operation* para `/users/me/items/` requiere el scope `items`.
+
+Para esto, importamos y usamos `Security` de `fastapi`.
+
+Puedes usar `Security` para declarar dependencias (igual que `Depends`), pero `Security` también recibe un parámetro `scopes` con una lista de scopes (strings).
+
+En este caso, pasamos una función de dependencia `get_current_active_user` a `Security` (de la misma manera que haríamos con `Depends`).
+
+Pero también pasamos una `list` de scopes, en este caso con solo un scope: `items` (podría tener más).
+
+Y la función de dependencia `get_current_active_user` también puede declarar sub-dependencias, no solo con `Depends` sino también con `Security`. Declarando su propia función de sub-dependencia (`get_current_user`), y más requisitos de scope.
+
+En este caso, requiere el scope `me` (podría requerir más de un scope).
+
+/// note | Nota
+
+No necesariamente necesitas añadir diferentes scopes en diferentes lugares.
+
+Lo estamos haciendo aquí para demostrar cómo **FastAPI** maneja scopes declarados en diferentes niveles.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}
+
+/// info | Información Técnica
+
+`Security` es en realidad una subclase de `Depends`, y tiene solo un parámetro extra que veremos más adelante.
+
+Pero al usar `Security` en lugar de `Depends`, **FastAPI** sabrá que puede declarar scopes de seguridad, usarlos internamente y documentar la API con OpenAPI.
+
+Pero cuando importas `Query`, `Path`, `Depends`, `Security` y otros de `fastapi`, en realidad son funciones que devuelven clases especiales.
+
+///
+
+## Usar `SecurityScopes` { #use-securityscopes }
+
+Ahora actualiza la dependencia `get_current_user`.
+
+Esta es la que usan las dependencias anteriores.
+
+Aquí es donde estamos usando el mismo esquema de OAuth2 que creamos antes, declarándolo como una dependencia: `oauth2_scheme`.
+
+Porque esta función de dependencia no tiene ningún requisito de scope en sí, podemos usar `Depends` con `oauth2_scheme`, no tenemos que usar `Security` cuando no necesitamos especificar scopes de seguridad.
+
+También declaramos un parámetro especial de tipo `SecurityScopes`, importado de `fastapi.security`.
+
+Esta clase `SecurityScopes` es similar a `Request` (`Request` se usó para obtener el objeto request directamente).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}
+
+## Usar los `scopes` { #use-the-scopes }
+
+El parámetro `security_scopes` será del tipo `SecurityScopes`.
+
+Tendrá una propiedad `scopes` con una lista que contiene todos los scopes requeridos por sí mismo y por todas las dependencias que lo usan como sub-dependencia. Eso significa, todos los "dependientes"... esto podría sonar confuso, se explica de nuevo más abajo.
+
+El objeto `security_scopes` (de la clase `SecurityScopes`) también proporciona un atributo `scope_str` con un único string, que contiene esos scopes separados por espacios (lo vamos a usar).
+
+Creamos una `HTTPException` que podemos reutilizar (`raise`) más tarde en varios puntos.
+
+En esta excepción, incluimos los scopes requeridos (si los hay) como un string separado por espacios (usando `scope_str`). Ponemos ese string que contiene los scopes en el header `WWW-Authenticate` (esto es parte de la especificación).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}
+
+## Verificar el `username` y la forma de los datos { #verify-the-username-and-data-shape }
+
+Verificamos que obtenemos un `username`, y extraemos los scopes.
+
+Y luego validamos esos datos con el modelo de Pydantic (capturando la excepción `ValidationError`), y si obtenemos un error leyendo el token JWT o validando los datos con Pydantic, lanzamos la `HTTPException` que creamos antes.
+
+Para eso, actualizamos el modelo de Pydantic `TokenData` con una nueva propiedad `scopes`.
+
+Al validar los datos con Pydantic podemos asegurarnos de que tenemos, por ejemplo, exactamente una `list` de `str` con los scopes y un `str` con el `username`.
+
+En lugar de, por ejemplo, un `dict`, o algo más, ya que podría romper la aplicación en algún punto posterior, haciéndolo un riesgo de seguridad.
+
+También verificamos que tenemos un usuario con ese username, y si no, lanzamos esa misma excepción que creamos antes.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}
+
+## Verificar los `scopes` { #verify-the-scopes }
+
+Ahora verificamos que todos los scopes requeridos, por esta dependencia y todos los dependientes (incluyendo *path operations*), estén incluidos en los scopes proporcionados en el token recibido, de lo contrario, lanzamos una `HTTPException`.
+
+Para esto, usamos `security_scopes.scopes`, que contiene una `list` con todos estos scopes como `str`.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}
+
+## Árbol de dependencias y scopes { #dependency-tree-and-scopes }
+
+Revisemos de nuevo este árbol de dependencias y los scopes.
+
+Como la dependencia `get_current_active_user` tiene como sub-dependencia a `get_current_user`, el scope `"me"` declarado en `get_current_active_user` se incluirá en la lista de scopes requeridos en el `security_scopes.scopes` pasado a `get_current_user`.
+
+La *path operation* en sí también declara un scope, `"items"`, por lo que esto también estará en la lista de `security_scopes.scopes` pasado a `get_current_user`.
+
+Así es como se ve la jerarquía de dependencias y scopes:
+
+* La *path operation* `read_own_items` tiene:
+ * Scopes requeridos `["items"]` con la dependencia:
+ * `get_current_active_user`:
+ * La función de dependencia `get_current_active_user` tiene:
+ * Scopes requeridos `["me"]` con la dependencia:
+ * `get_current_user`:
+ * La función de dependencia `get_current_user` tiene:
+ * No requiere scopes por sí misma.
+ * Una dependencia usando `oauth2_scheme`.
+ * Un parámetro `security_scopes` de tipo `SecurityScopes`:
+ * Este parámetro `security_scopes` tiene una propiedad `scopes` con una `list` que contiene todos estos scopes declarados arriba, por lo que:
+ * `security_scopes.scopes` contendrá `["me", "items"]` para la *path operation* `read_own_items`.
+ * `security_scopes.scopes` contendrá `["me"]` para la *path operation* `read_users_me`, porque está declarado en la dependencia `get_current_active_user`.
+ * `security_scopes.scopes` contendrá `[]` (nada) para la *path operation* `read_system_status`, porque no declaró ningún `Security` con `scopes`, y su dependencia, `get_current_user`, tampoco declara ningún `scopes`.
+
+/// tip | Consejo
+
+Lo importante y "mágico" aquí es que `get_current_user` tendrá una lista diferente de `scopes` para verificar para cada *path operation*.
+
+Todo depende de los `scopes` declarados en cada *path operation* y cada dependencia en el árbol de dependencias para esa *path operation* específica.
+
+///
+
+## Más detalles sobre `SecurityScopes` { #more-details-about-securityscopes }
+
+Puedes usar `SecurityScopes` en cualquier punto, y en múltiples lugares, no tiene que ser en la dependencia "raíz".
+
+Siempre tendrá los scopes de seguridad declarados en las dependencias `Security` actuales y todos los dependientes para **esa específica** *path operation* y **ese específico** árbol de dependencias.
+
+Debido a que `SecurityScopes` tendrá todos los scopes declarados por dependientes, puedes usarlo para verificar que un token tiene los scopes requeridos en una función de dependencia central, y luego declarar diferentes requisitos de scope en diferentes *path operations*.
+
+Serán verificados independientemente para cada *path operation*.
+
+## Revisa { #check-it }
+
+Si abres la documentación de la API, puedes autenticarte y especificar qué scopes deseas autorizar.
+
+
+
+Si no seleccionas ningún scope, estarás "autenticado", pero cuando intentes acceder a `/users/me/` o `/users/me/items/` obtendrás un error diciendo que no tienes suficientes permisos. Aún podrás acceder a `/status/`.
+
+Y si seleccionas el scope `me` pero no el scope `items`, podrás acceder a `/users/me/` pero no a `/users/me/items/`.
+
+Eso es lo que pasaría a una aplicación de terceros que intentara acceder a una de estas *path operations* con un token proporcionado por un usuario, dependiendo de cuántos permisos el usuario otorgó a la aplicación.
+
+## Acerca de las integraciones de terceros { #about-third-party-integrations }
+
+En este ejemplo estamos usando el flujo de OAuth2 "password".
+
+Esto es apropiado cuando estamos iniciando sesión en nuestra propia aplicación, probablemente con nuestro propio frontend.
+
+Porque podemos confiar en ella para recibir el `username` y `password`, ya que la controlamos.
+
+Pero si estás construyendo una aplicación OAuth2 a la que otros se conectarían (es decir, si estás construyendo un proveedor de autenticación equivalente a Facebook, Google, GitHub, etc.) deberías usar uno de los otros flujos.
+
+El más común es el flujo implícito.
+
+El más seguro es el flujo de código, pero es más complejo de implementar ya que requiere más pasos. Como es más complejo, muchos proveedores terminan sugiriendo el flujo implícito.
+
+/// note | Nota
+
+Es común que cada proveedor de autenticación nombre sus flujos de una manera diferente, para hacerlos parte de su marca.
+
+Pero al final, están implementando el mismo estándar OAuth2.
+
+///
+
+**FastAPI** incluye utilidades para todos estos flujos de autenticación OAuth2 en `fastapi.security.oauth2`.
+
+## `Security` en `dependencies` del decorador { #security-in-decorator-dependencies }
+
+De la misma manera que puedes definir una `list` de `Depends` en el parámetro `dependencies` del decorador (como se explica en [Dependencias en decoradores de path operation](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md)), también podrías usar `Security` con `scopes` allí.
diff --git a/docs/es/docs/advanced/settings.md b/docs/es/docs/advanced/settings.md
new file mode 100644
index 0000000000000..2411ddc452041
--- /dev/null
+++ b/docs/es/docs/advanced/settings.md
@@ -0,0 +1,302 @@
+# Configuraciones y Variables de Entorno { #settings-and-environment-variables }
+
+En muchos casos, tu aplicación podría necesitar algunas configuraciones o ajustes externos, por ejemplo, claves secretas, credenciales de base de datos, credenciales para servicios de correo electrónico, etc.
+
+La mayoría de estas configuraciones son variables (pueden cambiar), como las URLs de bases de datos. Y muchas podrían ser sensibles, como los secretos.
+
+Por esta razón, es común proporcionarlas en variables de entorno que son leídas por la aplicación.
+
+/// tip | Consejo
+
+Para entender las variables de entorno, puedes leer [Variables de Entorno](../environment-variables.md).
+
+///
+
+## Tipos y validación { #types-and-validation }
+
+Estas variables de entorno solo pueden manejar strings de texto, ya que son externas a Python y tienen que ser compatibles con otros programas y el resto del sistema (e incluso con diferentes sistemas operativos, como Linux, Windows, macOS).
+
+Eso significa que cualquier valor leído en Python desde una variable de entorno será un `str`, y cualquier conversión a un tipo diferente o cualquier validación tiene que hacerse en código.
+
+## Pydantic `Settings` { #pydantic-settings }
+
+Afortunadamente, Pydantic proporciona una gran utilidad para manejar estas configuraciones provenientes de variables de entorno con [Pydantic: Settings management](https://docs.pydantic.dev/latest/concepts/pydantic_settings/).
+
+### Instalar `pydantic-settings` { #install-pydantic-settings }
+
+Primero, asegúrate de crear tu [entorno virtual](../virtual-environments.md), actívalo y luego instala el paquete `pydantic-settings`:
+
+
+
+Y luego, abre la documentación para la sub-aplicación, en [http://127.0.0.1:8000/subapi/docs](http://127.0.0.1:8000/subapi/docs).
+
+Verás la documentación automática de la API para la sub-aplicación, incluyendo solo sus propias _path operations_, todas bajo el prefijo correcto del sub-path `/subapi`:
+
+
+
+Si intentas interactuar con cualquiera de las dos interfaces de usuario, funcionarán correctamente, porque el navegador podrá comunicarse con cada aplicación o sub-aplicación específica.
+
+### Detalles Técnicos: `root_path` { #technical-details-root-path }
+
+Cuando montas una sub-aplicación como se describe arriba, FastAPI se encargará de comunicar el path de montaje para la sub-aplicación usando un mecanismo de la especificación ASGI llamado `root_path`.
+
+De esa manera, la sub-aplicación sabrá usar ese prefijo de path para la interfaz de documentación.
+
+Y la sub-aplicación también podría tener sus propias sub-aplicaciones montadas y todo funcionaría correctamente, porque FastAPI maneja todos estos `root_path`s automáticamente.
+
+Aprenderás más sobre el `root_path` y cómo usarlo explícitamente en la sección sobre [Detrás de un Proxy](behind-a-proxy.md).
diff --git a/docs/es/docs/advanced/templates.md b/docs/es/docs/advanced/templates.md
new file mode 100644
index 0000000000000..ce28c3062cf29
--- /dev/null
+++ b/docs/es/docs/advanced/templates.md
@@ -0,0 +1,126 @@
+# Plantillas { #templates }
+
+Puedes usar cualquier motor de plantillas que desees con **FastAPI**.
+
+Una elección común es Jinja2, el mismo que usa Flask y otras herramientas.
+
+Hay utilidades para configurarlo fácilmente que puedes usar directamente en tu aplicación de **FastAPI** (proporcionadas por Starlette).
+
+## Instala dependencias { #install-dependencies }
+
+Asegúrate de crear un [entorno virtual](../virtual-environments.md), activarlo e instalar `jinja2`:
+
+
+
+Puedes escribir mensajes en el cuadro de entrada y enviarlos:
+
+
+
+Y tu aplicación **FastAPI** con WebSockets responderá de vuelta:
+
+
+
+Puedes enviar (y recibir) muchos mensajes:
+
+
+
+Y todos usarán la misma conexión WebSocket.
+
+## Usando `Depends` y otros { #using-depends-and-others }
+
+En endpoints de WebSocket puedes importar desde `fastapi` y usar:
+
+* `Depends`
+* `Security`
+* `Cookie`
+* `Header`
+* `Path`
+* `Query`
+
+Funcionan de la misma manera que para otros endpoints de FastAPI/*path operations*:
+
+{* ../../docs_src/websockets_/tutorial002_an_py310.py hl[68:69,82] *}
+
+/// info | Información
+
+Como esto es un WebSocket no tiene mucho sentido lanzar un `HTTPException`, en su lugar lanzamos un `WebSocketException`.
+
+Puedes usar un código de cierre de los [códigos válidos definidos en la especificación](https://tools.ietf.org/html/rfc6455#section-7.4.1).
+
+///
+
+### Prueba los WebSockets con dependencias { #try-the-websockets-with-dependencies }
+
+Ejecuta tu aplicación:
+
+
+
+## Manejar desconexiones y múltiples clientes { #handling-disconnections-and-multiple-clients }
+
+Cuando una conexión de WebSocket se cierra, el `await websocket.receive_text()` lanzará una excepción `WebSocketDisconnect`, que puedes capturar y manejar como en este ejemplo.
+
+{* ../../docs_src/websockets_/tutorial003_py310.py hl[79:81] *}
+
+Para probarlo:
+
+* Abre la aplicación con varias pestañas del navegador.
+* Escribe mensajes desde ellas.
+* Luego cierra una de las pestañas.
+
+Eso lanzará la excepción `WebSocketDisconnect`, y todos los otros clientes recibirán un mensaje como:
+
+```
+Client #1596980209979 left the chat
+```
+
+/// tip | Consejo
+
+La aplicación anterior es un ejemplo mínimo y simple para demostrar cómo manejar y transmitir mensajes a varias conexiones WebSocket.
+
+Pero ten en cuenta que, como todo se maneja en memoria, en una sola lista, solo funcionará mientras el proceso esté en ejecución, y solo funcionará con un solo proceso.
+
+Si necesitas algo fácil de integrar con FastAPI pero que sea más robusto, soportado por Redis, PostgreSQL u otros, revisa [encode/broadcaster](https://github.com/encode/broadcaster).
+
+///
+
+## Más información { #more-info }
+
+Para aprender más sobre las opciones, revisa la documentación de Starlette para:
+
+* [La clase `WebSocket`](https://www.starlette.dev/websockets/).
+* [Manejo de WebSocket basado en clases](https://www.starlette.dev/endpoints/#websocketendpoint).
diff --git a/docs/es/docs/advanced/wsgi.md b/docs/es/docs/advanced/wsgi.md
new file mode 100644
index 0000000000000..0d0c42fd540a7
--- /dev/null
+++ b/docs/es/docs/advanced/wsgi.md
@@ -0,0 +1,51 @@
+# Incluyendo WSGI - Flask, Django, otros { #including-wsgi-flask-django-others }
+
+Puedes montar aplicaciones WSGI como viste con [Sub Aplicaciones - Mounts](sub-applications.md), [Detrás de un Proxy](behind-a-proxy.md).
+
+Para eso, puedes usar el `WSGIMiddleware` y usarlo para envolver tu aplicación WSGI, por ejemplo, Flask, Django, etc.
+
+## Usando `WSGIMiddleware` { #using-wsgimiddleware }
+
+/// info | Información
+
+Esto requiere instalar `a2wsgi`, por ejemplo con `pip install a2wsgi`.
+
+///
+
+Necesitas importar `WSGIMiddleware` de `a2wsgi`.
+
+Luego envuelve la aplicación WSGI (p. ej., Flask) con el middleware.
+
+Y luego móntala bajo un path.
+
+{* ../../docs_src/wsgi/tutorial001_py310.py hl[1,3,23] *}
+
+/// note | Nota
+
+Anteriormente, se recomendaba usar `WSGIMiddleware` de `fastapi.middleware.wsgi`, pero ahora está deprecado.
+
+Se aconseja usar el paquete `a2wsgi` en su lugar. El uso sigue siendo el mismo.
+
+Solo asegúrate de tener instalado el paquete `a2wsgi` e importar `WSGIMiddleware` correctamente desde `a2wsgi`.
+
+///
+
+## Revisa { #check-it }
+
+Ahora, cada request bajo el path `/v1/` será manejado por la aplicación Flask.
+
+Y el resto será manejado por **FastAPI**.
+
+Si lo ejecutas y vas a [http://localhost:8000/v1/](http://localhost:8000/v1/) verás el response de Flask:
+
+```txt
+Hello, World from Flask!
+```
+
+Y si vas a [http://localhost:8000/v2](http://localhost:8000/v2) verás el response de FastAPI:
+
+```JSON
+{
+ "message": "Hello World"
+}
+```
diff --git a/docs/es/docs/alternatives.md b/docs/es/docs/alternatives.md
new file mode 100644
index 0000000000000..4250f0a02bc9c
--- /dev/null
+++ b/docs/es/docs/alternatives.md
@@ -0,0 +1,485 @@
+# Alternativas, Inspiración y Comparaciones { #alternatives-inspiration-and-comparisons }
+
+Lo que inspiró a **FastAPI**, cómo se compara con las alternativas y lo que aprendió de ellas.
+
+## Introducción { #intro }
+
+**FastAPI** no existiría si no fuera por el trabajo previo de otros.
+
+Se han creado muchas herramientas antes que han ayudado a inspirar su creación.
+
+He estado evitando la creación de un nuevo framework durante varios años. Primero intenté resolver todas las funcionalidades cubiertas por **FastAPI** usando muchos frameworks diferentes, plug-ins y herramientas.
+
+Pero en algún punto, no hubo otra opción que crear algo que proporcionara todas estas funcionalidades, tomando las mejores ideas de herramientas previas y combinándolas de la mejor manera posible, usando funcionalidades del lenguaje que ni siquiera estaban disponibles antes (anotaciones de tipos de Python 3.6+).
+
+## Herramientas previas { #previous-tools }
+
+### [Django](https://www.djangoproject.com/) { #django }
+
+Es el framework más popular de Python y es ampliamente confiable. Se utiliza para construir sistemas como Instagram.
+
+Está relativamente acoplado con bases de datos relacionales (como MySQL o PostgreSQL), por lo que tener una base de datos NoSQL (como Couchbase, MongoDB, Cassandra, etc) como motor de almacenamiento principal no es muy fácil.
+
+Fue creado para generar el HTML en el backend, no para crear APIs utilizadas por un frontend moderno (como React, Vue.js y Angular) o por otros sistemas (como dispositivos del IoT) comunicándose con él.
+
+### [Django REST Framework](https://www.django-rest-framework.org/) { #django-rest-framework }
+
+El framework Django REST fue creado para ser un kit de herramientas flexible para construir APIs Web utilizando Django, mejorando sus capacidades API.
+
+Es utilizado por muchas empresas, incluidas Mozilla, Red Hat y Eventbrite.
+
+Fue uno de los primeros ejemplos de **documentación automática de APIs**, y esto fue específicamente una de las primeras ideas que inspiraron "la búsqueda de" **FastAPI**.
+
+/// note | Nota
+
+Django REST Framework fue creado por Tom Christie. El mismo creador de Starlette y Uvicorn, en los cuales **FastAPI** está basado.
+
+///
+
+/// check | Inspiró a **FastAPI** a
+
+Tener una interfaz de usuario web de documentación automática de APIs.
+
+///
+
+### [Flask](https://flask.palletsprojects.com) { #flask }
+
+Flask es un "microframework", no incluye integraciones de bases de datos ni muchas de las cosas que vienen por defecto en Django.
+
+Esta simplicidad y flexibilidad permiten hacer cosas como usar bases de datos NoSQL como el sistema de almacenamiento de datos principal.
+
+Como es muy simple, es relativamente intuitivo de aprender, aunque la documentación se vuelve algo técnica en algunos puntos.
+
+También se utiliza comúnmente para otras aplicaciones que no necesariamente necesitan una base de datos, gestión de usuarios, o cualquiera de las muchas funcionalidades que vienen preconstruidas en Django. Aunque muchas de estas funcionalidades se pueden añadir con plug-ins.
+
+Esta separación de partes, y ser un "microframework" que podría extenderse para cubrir exactamente lo que se necesita, fue una funcionalidad clave que quise mantener.
+
+Dada la simplicidad de Flask, parecía una buena opción para construir APIs. Lo siguiente a encontrar era un "Django REST Framework" para Flask.
+
+/// check | Inspiró a **FastAPI** a
+
+Ser un micro-framework. Haciendo fácil mezclar y combinar las herramientas y partes necesarias.
+
+Tener un sistema de routing simple y fácil de usar.
+
+///
+
+### [Requests](https://requests.readthedocs.io) { #requests }
+
+**FastAPI** no es en realidad una alternativa a **Requests**. Su ámbito es muy diferente.
+
+De hecho, sería común usar Requests *dentro* de una aplicación FastAPI.
+
+Aun así, FastAPI se inspiró bastante en Requests.
+
+**Requests** es un paquete para *interactuar* con APIs (como cliente), mientras que **FastAPI** es un paquete para *construir* APIs (como servidor).
+
+Están, más o menos, en extremos opuestos, complementándose entre sí.
+
+Requests tiene un diseño muy simple e intuitivo, es muy fácil de usar, con valores por defecto sensatos. Pero al mismo tiempo, es muy poderoso y personalizable.
+
+Por eso, como se dice en el sitio web oficial:
+
+> Requests es uno de los paquetes Python más descargados de todos los tiempos
+
+La forma en que lo usas es muy sencilla. Por ejemplo, para hacer un `GET` request, escribirías:
+
+```Python
+response = requests.get("http://example.com/some/url")
+```
+
+La operación de path equivalente en FastAPI podría verse como:
+
+```Python hl_lines="1"
+@app.get("/some/url")
+def read_url():
+ return {"message": "Hello World"}
+```
+
+Mira las similitudes entre `requests.get(...)` y `@app.get(...)`.
+
+/// check | Inspiró a **FastAPI** a
+
+* Tener un API simple e intuitivo.
+* Usar nombres de métodos HTTP (operaciones) directamente, de una manera sencilla e intuitiva.
+* Tener valores por defecto sensatos, pero personalizaciones poderosas.
+
+///
+
+### [Swagger](https://swagger.io/) / [OpenAPI](https://github.com/OAI/OpenAPI-Specification/) { #swagger-openapi }
+
+La principal funcionalidad que quería de Django REST Framework era la documentación automática de la API.
+
+Luego descubrí que había un estándar para documentar APIs, usando JSON (o YAML, una extensión de JSON) llamado Swagger.
+
+Y ya existía una interfaz de usuario web para las APIs Swagger. Por lo tanto, ser capaz de generar documentación Swagger para una API permitiría usar esta interfaz de usuario web automáticamente.
+
+En algún punto, Swagger fue entregado a la Linux Foundation, para ser renombrado OpenAPI.
+
+Es por eso que cuando se habla de la versión 2.0 es común decir "Swagger", y para la versión 3+ "OpenAPI".
+
+/// check | Inspiró a **FastAPI** a
+
+Adoptar y usar un estándar abierto para especificaciones de API, en lugar de usar un esquema personalizado.
+
+Y a integrar herramientas de interfaz de usuario basadas en estándares:
+
+* [Swagger UI](https://github.com/swagger-api/swagger-ui)
+* [ReDoc](https://github.com/Rebilly/ReDoc)
+
+Estas dos fueron elegidas por ser bastante populares y estables, pero haciendo una búsqueda rápida, podrías encontrar docenas de interfaces de usuario alternativas para OpenAPI (que puedes usar con **FastAPI**).
+
+///
+
+### Frameworks REST para Flask { #flask-rest-frameworks }
+
+Existen varios frameworks REST para Flask, pero después de invertir tiempo y trabajo investigándolos, encontré que muchos son descontinuados o abandonados, con varios problemas existentes que los hacían inadecuados.
+
+### [Marshmallow](https://marshmallow.readthedocs.io/en/stable/) { #marshmallow }
+
+Una de las principales funcionalidades necesitadas por los sistemas API es la "serialización" de datos, que consiste en tomar datos del código (Python) y convertirlos en algo que pueda ser enviado a través de la red. Por ejemplo, convertir un objeto que contiene datos de una base de datos en un objeto JSON. Convertir objetos `datetime` en strings, etc.
+
+Otra gran funcionalidad necesaria por las APIs es la validación de datos, asegurarse de que los datos sean válidos, dados ciertos parámetros. Por ejemplo, que algún campo sea un `int`, y no algún string aleatorio. Esto es especialmente útil para los datos entrantes.
+
+Sin un sistema de validación de datos, tendrías que hacer todas las comprobaciones a mano, en código.
+
+Estas funcionalidades son para lo que fue creado Marshmallow. Es un gran paquete, y lo he usado mucho antes.
+
+Pero fue creado antes de que existieran las anotaciones de tipos en Python. Así que, para definir cada esquema necesitas usar utilidades y clases específicas proporcionadas por Marshmallow.
+
+/// check | Inspiró a **FastAPI** a
+
+Usar código para definir "esquemas" que proporcionen tipos de datos y validación automáticamente.
+
+///
+
+### [Webargs](https://webargs.readthedocs.io/en/latest/) { #webargs }
+
+Otra gran funcionalidad requerida por las APIs es el parsing de datos de las requests entrantes.
+
+Webargs es una herramienta que fue creada para proporcionar esa funcionalidad sobre varios frameworks, incluido Flask.
+
+Usa Marshmallow por debajo para hacer la validación de datos. Y fue creada por los mismos desarrolladores.
+
+Es una gran herramienta y la he usado mucho también, antes de tener **FastAPI**.
+
+/// info | Información
+
+Webargs fue creada por los mismos desarrolladores de Marshmallow.
+
+///
+
+/// check | Inspiró a **FastAPI** a
+
+Tener validación automática de datos entrantes en una request.
+
+///
+
+### [APISpec](https://apispec.readthedocs.io/en/stable/) { #apispec }
+
+Marshmallow y Webargs proporcionan validación, parsing y serialización como plug-ins.
+
+Pero la documentación todavía falta. Entonces APISpec fue creado.
+
+Es un plug-in para muchos frameworks (y hay un plug-in para Starlette también).
+
+La manera en que funciona es que escribes la definición del esquema usando el formato YAML dentro del docstring de cada función que maneja una ruta.
+
+Y genera esquemas OpenAPI.
+
+Así es como funciona en Flask, Starlette, Responder, etc.
+
+Pero luego, tenemos otra vez el problema de tener una micro-sintaxis, dentro de un string de Python (un gran YAML).
+
+El editor no puede ayudar mucho con eso. Y si modificamos parámetros o esquemas de Marshmallow y olvidamos también modificar ese docstring YAML, el esquema generado estaría obsoleto.
+
+/// info | Información
+
+APISpec fue creado por los mismos desarrolladores de Marshmallow.
+
+///
+
+/// check | Inspiró a **FastAPI** a
+
+Soportar el estándar abierto para APIs, OpenAPI.
+
+///
+
+### [Flask-apispec](https://flask-apispec.readthedocs.io/en/latest/) { #flask-apispec }
+
+Es un plug-in de Flask, que conecta juntos Webargs, Marshmallow y APISpec.
+
+Usa la información de Webargs y Marshmallow para generar automáticamente esquemas OpenAPI, usando APISpec.
+
+Es una gran herramienta, muy subestimada. Debería ser mucho más popular que muchos plug-ins de Flask por ahí. Puede que se deba a que su documentación es demasiado concisa y abstracta.
+
+Esto resolvió tener que escribir YAML (otra sintaxis) dentro de docstrings de Python.
+
+Esta combinación de Flask, Flask-apispec con Marshmallow y Webargs fue mi stack de backend favorito hasta construir **FastAPI**.
+
+Usarlo llevó a la creación de varios generadores de full-stack para Flask. Estos son los principales stacks que yo (y varios equipos externos) hemos estado usando hasta ahora:
+
+* [https://github.com/tiangolo/full-stack](https://github.com/tiangolo/full-stack)
+* [https://github.com/tiangolo/full-stack-flask-couchbase](https://github.com/tiangolo/full-stack-flask-couchbase)
+* [https://github.com/tiangolo/full-stack-flask-couchdb](https://github.com/tiangolo/full-stack-flask-couchdb)
+
+Y estos mismos generadores de full-stack fueron la base de los [Generadores de Proyectos **FastAPI**](project-generation.md).
+
+/// info | Información
+
+Flask-apispec fue creado por los mismos desarrolladores de Marshmallow.
+
+///
+
+/// check | Inspiró a **FastAPI** a
+
+Generar el esquema OpenAPI automáticamente, desde el mismo código que define la serialización y validación.
+
+///
+
+### [NestJS](https://nestjs.com/) (y [Angular](https://angular.io/)) { #nestjs-and-angular }
+
+Esto ni siquiera es Python, NestJS es un framework de JavaScript (TypeScript) NodeJS inspirado por Angular.
+
+Logra algo algo similar a lo que se puede hacer con Flask-apispec.
+
+Tiene un sistema de inyección de dependencias integrado, inspirado por Angular 2. Requiere pre-registrar los "inyectables" (como todos los otros sistemas de inyección de dependencias que conozco), por lo que añade a la verbosidad y repetición de código.
+
+Como los parámetros se describen con tipos de TypeScript (similar a las anotaciones de tipos en Python), el soporte editorial es bastante bueno.
+
+Pero como los datos de TypeScript no se preservan después de la compilación a JavaScript, no puede depender de los tipos para definir validación, serialización y documentación al mismo tiempo. Debido a esto y algunas decisiones de diseño, para obtener validación, serialización y generación automática del esquema, es necesario agregar decoradores en muchos lugares. Por lo tanto, se vuelve bastante verboso.
+
+No puede manejar muy bien modelos anidados. Entonces, si el cuerpo JSON en la request es un objeto JSON que tiene campos internos que a su vez son objetos JSON anidados, no puede ser documentado y validado apropiadamente.
+
+/// check | Inspiró a **FastAPI** a
+
+Usar tipos de Python para tener un gran soporte del editor.
+
+Tener un poderoso sistema de inyección de dependencias. Encontrar una forma de minimizar la repetición de código.
+
+///
+
+### [Sanic](https://sanic.readthedocs.io/en/latest/) { #sanic }
+
+Fue uno de los primeros frameworks de Python extremadamente rápidos basados en `asyncio`. Fue hecho para ser muy similar a Flask.
+
+/// note | Detalles Técnicos
+
+Usó [`uvloop`](https://github.com/MagicStack/uvloop) en lugar del loop `asyncio` por defecto de Python. Eso fue lo que lo hizo tan rápido.
+
+Claramente inspiró a Uvicorn y Starlette, que actualmente son más rápidos que Sanic en benchmarks abiertos.
+
+///
+
+/// check | Inspiró a **FastAPI** a
+
+Encontrar una manera de tener un rendimiento impresionante.
+
+Por eso **FastAPI** se basa en Starlette, ya que es el framework más rápido disponible (probado por benchmarks de terceros).
+
+///
+
+### [Falcon](https://falconframework.org/) { #falcon }
+
+Falcon es otro framework de Python de alto rendimiento, está diseñado para ser minimalista y funcionar como la base de otros frameworks como Hug.
+
+Está diseñado para tener funciones que reciben dos parámetros, un "request" y un "response". Luego "lees" partes del request y "escribes" partes en el response. Debido a este diseño, no es posible declarar parámetros de request y cuerpos con las anotaciones de tipos estándar de Python como parámetros de función.
+
+Por lo tanto, la validación de datos, la serialización y la documentación, tienen que hacerse en código, no automáticamente. O tienen que implementarse como un framework sobre Falcon, como Hug. Esta misma distinción ocurre en otros frameworks que se inspiran en el diseño de Falcon, de tener un objeto request y un objeto response como parámetros.
+
+/// check | Inspiró a **FastAPI** a
+
+Buscar maneras de obtener un gran rendimiento.
+
+Junto con Hug (ya que Hug se basa en Falcon), inspiraron a **FastAPI** a declarar un parámetro `response` en las funciones.
+
+Aunque en FastAPI es opcional, y se utiliza principalmente para configurar headers, cookies y códigos de estado alternativos.
+
+///
+
+### [Molten](https://moltenframework.com/) { #molten }
+
+Descubrí Molten en las primeras etapas de construcción de **FastAPI**. Y tiene ideas bastante similares:
+
+* Basado en las anotaciones de tipos de Python.
+* Validación y documentación a partir de estos tipos.
+* Sistema de Inyección de Dependencias.
+
+No utiliza un paquete de validación de datos, serialización y documentación de terceros como Pydantic, tiene el suyo propio. Por lo tanto, estas definiciones de tipos de datos no serían reutilizables tan fácilmente.
+
+Requiere configuraciones un poquito más verbosas. Y dado que se basa en WSGI (en lugar de ASGI), no está diseñado para aprovechar el alto rendimiento proporcionado por herramientas como Uvicorn, Starlette y Sanic.
+
+El sistema de inyección de dependencias requiere pre-registrar las dependencias y las dependencias se resuelven en base a los tipos declarados. Por lo tanto, no es posible declarar más de un "componente" que proporcione cierto tipo.
+
+Las rutas se declaran en un solo lugar, usando funciones declaradas en otros lugares (en lugar de usar decoradores que pueden colocarse justo encima de la función que maneja el endpoint). Esto se acerca más a cómo lo hace Django que a cómo lo hace Flask (y Starlette). Separa en el código cosas que están relativamente acopladas.
+
+/// check | Inspiró a **FastAPI** a
+
+Definir validaciones extra para tipos de datos usando el valor "default" de los atributos del modelo. Esto mejora el soporte del editor y no estaba disponible en Pydantic antes.
+
+Esto en realidad inspiró la actualización de partes de Pydantic, para soportar el mismo estilo de declaración de validación (toda esta funcionalidad ya está disponible en Pydantic).
+
+///
+
+### [Hug](https://github.com/hugapi/hug) { #hug }
+
+Hug fue uno de los primeros frameworks en implementar la declaración de tipos de parámetros API usando las anotaciones de tipos de Python. Esta fue una gran idea que inspiró a otras herramientas a hacer lo mismo.
+
+Usaba tipos personalizados en sus declaraciones en lugar de tipos estándar de Python, pero aún así fue un gran avance.
+
+También fue uno de los primeros frameworks en generar un esquema personalizado declarando toda la API en JSON.
+
+No se basaba en un estándar como OpenAPI y JSON Schema. Por lo que no sería sencillo integrarlo con otras herramientas, como Swagger UI. Pero, nuevamente, fue una idea muy innovadora.
+
+Tiene una funcionalidad interesante e inusual: usando el mismo framework, es posible crear APIs y también CLIs.
+
+Dado que se basa en el estándar previo para frameworks web Python sincrónicos (WSGI), no puede manejar Websockets y otras cosas, aunque aún así tiene un alto rendimiento también.
+
+/// info | Información
+
+Hug fue creado por Timothy Crosley, el mismo creador de [`isort`](https://github.com/timothycrosley/isort), una gran herramienta para ordenar automáticamente imports en archivos Python.
+
+///
+
+/// check | Ideas que inspiraron a **FastAPI**
+
+Hug inspiró partes de APIStar, y fue una de las herramientas que encontré más prometedoras, junto a APIStar.
+
+Hug ayudó a inspirar a **FastAPI** a usar anotaciones de tipos de Python para declarar parámetros, y a generar un esquema definiendo la API automáticamente.
+
+Hug inspiró a **FastAPI** a declarar un parámetro `response` en funciones para configurar headers y cookies.
+
+///
+
+### [APIStar](https://github.com/encode/apistar) (<= 0.5) { #apistar-0-5 }
+
+Justo antes de decidir construir **FastAPI** encontré **APIStar** server. Tenía casi todo lo que estaba buscando y tenía un gran diseño.
+
+Era una de las primeras implementaciones de un framework utilizando las anotaciones de tipos de Python para declarar parámetros y requests que jamás vi (antes de NestJS y Molten). Lo encontré más o menos al mismo tiempo que Hug. Pero APIStar usaba el estándar OpenAPI.
+
+Tenía validación de datos automática, serialización de datos y generación del esquema OpenAPI basada en las mismas anotaciones de tipos en varios lugares.
+
+Las definiciones de esquema de cuerpo no usaban las mismas anotaciones de tipos de Python como Pydantic, era un poco más similar a Marshmallow, por lo que el soporte del editor no sería tan bueno, pero aún así, APIStar era la mejor opción disponible.
+
+Tenía los mejores benchmarks de rendimiento en ese momento (solo superado por Starlette).
+
+Al principio, no tenía una interfaz de usuario web de documentación de API automática, pero sabía que podía agregar Swagger UI a él.
+
+Tenía un sistema de inyección de dependencias. Requería pre-registrar componentes, como otras herramientas discutidas anteriormente. Pero aún así, era una gran funcionalidad.
+
+Nunca pude usarlo en un proyecto completo, ya que no tenía integración de seguridad, por lo que no podía reemplazar todas las funcionalidades que tenía con los generadores de full-stack basados en Flask-apispec. Tenía en mi lista de tareas pendientes de proyectos crear un pull request agregando esa funcionalidad.
+
+Pero luego, el enfoque del proyecto cambió.
+
+Ya no era un framework web API, ya que el creador necesitaba enfocarse en Starlette.
+
+Ahora APIStar es un conjunto de herramientas para validar especificaciones OpenAPI, no un framework web.
+
+/// info | Información
+
+APIStar fue creado por Tom Christie. El mismo que creó:
+
+* Django REST Framework
+* Starlette (en la cual **FastAPI** está basado)
+* Uvicorn (usado por Starlette y **FastAPI**)
+
+///
+
+/// check | Inspiró a **FastAPI** a
+
+Existir.
+
+La idea de declarar múltiples cosas (validación de datos, serialización y documentación) con los mismos tipos de Python, que al mismo tiempo proporcionaban un gran soporte del editor, era algo que consideré una idea brillante.
+
+Y después de buscar durante mucho tiempo un framework similar y probar muchas alternativas diferentes, APIStar fue la mejor opción disponible.
+
+Luego APIStar dejó de existir como servidor y Starlette fue creado, y fue una nueva y mejor base para tal sistema. Esa fue la inspiración final para construir **FastAPI**.
+
+Considero a **FastAPI** un "sucesor espiritual" de APIStar, mientras mejora y aumenta las funcionalidades, el sistema de tipos y otras partes, basándose en los aprendizajes de todas estas herramientas previas.
+
+///
+
+## Usado por **FastAPI** { #used-by-fastapi }
+
+### [Pydantic](https://docs.pydantic.dev/) { #pydantic }
+
+Pydantic es un paquete para definir validación de datos, serialización y documentación (usando JSON Schema) basándose en las anotaciones de tipos de Python.
+
+Eso lo hace extremadamente intuitivo.
+
+Es comparable a Marshmallow. Aunque es más rápido que Marshmallow en benchmarks. Y como está basado en las mismas anotaciones de tipos de Python, el soporte del editor es estupendo.
+
+/// check | **FastAPI** lo usa para
+
+Manejar toda la validación de datos, serialización de datos y documentación automática de modelos (basada en JSON Schema).
+
+**FastAPI** luego toma esos datos JSON Schema y los coloca en OpenAPI, aparte de todas las otras cosas que hace.
+
+///
+
+### [Starlette](https://www.starlette.dev/) { #starlette }
+
+Starlette es un framework/toolkit ASGI liviano, ideal para construir servicios asyncio de alto rendimiento.
+
+Es muy simple e intuitivo. Está diseñado para ser fácilmente extensible y tener componentes modulares.
+
+Tiene:
+
+* Un rendimiento seriamente impresionante.
+* Soporte para WebSocket.
+* Tareas en segundo plano dentro del proceso.
+* Eventos de inicio y apagado.
+* Cliente de pruebas basado en HTTPX.
+* CORS, GZip, Archivos estáticos, Responses en streaming.
+* Soporte para sesiones y cookies.
+* Cobertura de tests del 100%.
+* code base 100% tipada.
+* Pocas dependencias obligatorias.
+
+Starlette es actualmente el framework de Python más rápido probado. Solo superado por Uvicorn, que no es un framework, sino un servidor.
+
+Starlette proporciona toda la funcionalidad básica de un microframework web.
+
+Pero no proporciona validación de datos automática, serialización o documentación.
+
+Esa es una de las principales cosas que **FastAPI** agrega, todo basado en las anotaciones de tipos de Python (usando Pydantic). Eso, además del sistema de inyección de dependencias, utilidades de seguridad, generación de esquemas OpenAPI, etc.
+
+/// note | Detalles Técnicos
+
+ASGI es un nuevo "estándar" que está siendo desarrollado por miembros del equipo central de Django. Todavía no es un "estándar de Python" (un PEP), aunque están en proceso de hacerlo.
+
+No obstante, ya está siendo usado como un "estándar" por varias herramientas. Esto mejora enormemente la interoperabilidad, ya que podrías cambiar Uvicorn por cualquier otro servidor ASGI (como Daphne o Hypercorn), o podrías añadir herramientas compatibles con ASGI, como `python-socketio`.
+
+///
+
+/// check | **FastAPI** lo usa para
+
+Manejar todas las partes web centrales. Añadiendo funcionalidades encima.
+
+La clase `FastAPI` en sí misma hereda directamente de la clase `Starlette`.
+
+Por lo tanto, cualquier cosa que puedas hacer con Starlette, puedes hacerlo directamente con **FastAPI**, ya que es básicamente Starlette potenciado.
+
+///
+
+### [Uvicorn](https://www.uvicorn.dev/) { #uvicorn }
+
+Uvicorn es un servidor ASGI extremadamente rápido, construido sobre uvloop y httptools.
+
+No es un framework web, sino un servidor. Por ejemplo, no proporciona herramientas para el enrutamiento por paths. Eso es algo que un framework como Starlette (o **FastAPI**) proporcionaría encima.
+
+Es el servidor recomendado para Starlette y **FastAPI**.
+
+/// check | **FastAPI** lo recomienda como
+
+El servidor web principal para ejecutar aplicaciones **FastAPI**.
+
+También puedes usar la opción de línea de comandos `--workers` para tener un servidor multiproceso asíncrono.
+
+Revisa más detalles en la sección [Despliegue](deployment/index.md).
+
+///
+
+## Benchmarks y velocidad { #benchmarks-and-speed }
+
+Para entender, comparar, y ver la diferencia entre Uvicorn, Starlette y FastAPI, revisa la sección sobre [Benchmarks](benchmarks.md).
diff --git a/docs/es/docs/async.md b/docs/es/docs/async.md
index 83dd532ee941e..a8ed00df128fa 100644
--- a/docs/es/docs/async.md
+++ b/docs/es/docs/async.md
@@ -1,18 +1,18 @@
-# Concurrencia y async / await
+# Concurrencia y async / await { #concurrency-and-async-await }
-Detalles sobre la sintaxis `async def` para *path operation functions* y un poco de información sobre código asíncrono, concurrencia y paralelismo.
+Detalles sobre la sintaxis `async def` para *path operation functions* y algunos antecedentes sobre el código asíncrono, la concurrencia y el paralelismo.
-## ¿Tienes prisa?
+## ¿Con prisa? { #in-a-hurry }
-TL;DR:
+TL;DR:
-Si estás utilizando libraries de terceros que te dicen que las llames con `await`, del tipo:
+Si estás usando paquetes de terceros que te dicen que los llames con `await`, como:
```Python
results = await some_library()
```
-Entonces declara tus *path operation functions* con `async def` de la siguiente manera:
+Entonces, declara tus *path operation functions* con `async def` así:
```Python hl_lines="2"
@app.get('/')
@@ -21,12 +21,15 @@ async def read_results():
return results
```
-!!! note "Nota"
- Solo puedes usar `await` dentro de funciones creadas con `async def`.
+/// note | Nota
+
+Solo puedes usar `await` dentro de funciones creadas con `async def`.
+
+///
---
-Si estás utilizando libraries de terceros que se comunican con algo (una base de datos, una API, el sistema de archivos, etc.) y no tienes soporte para `await` (este es el caso para la mayoría de las libraries de bases de datos), declara tus *path operation functions* de forma habitual, con solo `def`, de la siguiente manera:
+Si estás usando un paquete de terceros que se comunica con algo (una base de datos, una API, el sistema de archivos, etc.) y no tiene soporte para usar `await` (este es actualmente el caso para la mayoría de los paquetes de base de datos), entonces declara tus *path operation functions* como normalmente, usando simplemente `def`, así:
```Python hl_lines="2"
@app.get('/')
@@ -37,7 +40,7 @@ def results():
---
-Si tu aplicación (de alguna manera) no tiene que comunicarse con nada más y en consecuencia esperar a que responda, usa `async def`.
+Si tu aplicación (de alguna manera) no tiene que comunicarse con nada más y esperar a que responda, usa `async def`, incluso si no necesitas usar `await` dentro.
---
@@ -45,215 +48,218 @@ Si simplemente no lo sabes, usa `def` normal.
---
-**Nota**: puedes mezclar `def` y `async def` en tus *path operation functions* tanto como lo necesites y definir cada una utilizando la mejor opción para ti. FastAPI hará lo correcto con ellos.
+**Nota**: Puedes mezclar `def` y `async def` en tus *path operation functions* tanto como necesites y definir cada una utilizando la mejor opción para ti. FastAPI hará lo correcto con ellas.
De todos modos, en cualquiera de los casos anteriores, FastAPI seguirá funcionando de forma asíncrona y será extremadamente rápido.
-Pero siguiendo los pasos anteriores, FastAPI podrá hacer algunas optimizaciones de rendimiento.
+Pero al seguir los pasos anteriores, podrá hacer algunas optimizaciones de rendimiento.
-## Detalles Técnicos
+## Detalles Técnicos { #technical-details }
-Las versiones modernas de Python tienen soporte para **"código asíncrono"** usando algo llamado **"coroutines"**, usando la sintaxis **`async` y `await`**.
+Las versiones modernas de Python tienen soporte para **"código asíncrono"** utilizando algo llamado **"coroutines"**, con la sintaxis **`async` y `await`**.
-Veamos esa frase por partes en las secciones siguientes:
+Veamos esa frase por partes en las secciones a continuación:
* **Código Asíncrono**
* **`async` y `await`**
* **Coroutines**
-## Código Asíncrono
+## Código Asíncrono { #asynchronous-code }
-El código asíncrono sólo significa que el lenguaje 💬 tiene una manera de decirle al sistema / programa 🤖 que, en algún momento del código, 🤖 tendrá que esperar a que *algo más* termine en otro sitio. Digamos que ese *algo más* se llama, por ejemplo, "archivo lento" 📝.
+El código asíncrono simplemente significa que el lenguaje 💬 tiene una forma de decirle a la computadora / programa 🤖 que en algún momento del código, tendrá que esperar que *otra cosa* termine en otro lugar. Digamos que esa *otra cosa* se llama "archivo-lento" 📝.
-Durante ese tiempo, el sistema puede hacer otras cosas, mientras "archivo lento" 📝 termina.
+Entonces, durante ese tiempo, la computadora puede ir y hacer algún otro trabajo, mientras "archivo-lento" 📝 termina.
-Entonces el sistema / programa 🤖 volverá cada vez que pueda, sea porque está esperando otra vez, porque 🤖 ha terminado todo el trabajo que tenía en ese momento. Y 🤖 verá si alguna de las tareas por las que estaba esperando ha terminado, haciendo lo que tenía que hacer.
+Luego la computadora / programa 🤖 volverá cada vez que tenga una oportunidad porque está esperando nuevamente, o siempre que 🤖 haya terminado todo el trabajo que tenía en ese punto. Y 🤖 comprobará si alguna de las tareas que estaba esperando ya se han completado, haciendo lo que tenía que hacer.
-Luego, 🤖 cogerá la primera tarea finalizada (digamos, nuestro "archivo lento" 📝) y continuará con lo que tenía que hacer con esa tarea.
+Después, 🤖 toma la primera tarea que termine (digamos, nuestro "archivo-lento" 📝) y continúa con lo que tenía que hacer con ella.
-Esa "espera de otra cosa" normalmente se refiere a operaciones I/O que son relativamente "lentas" (en relación a la velocidad del procesador y memoria RAM), como por ejemplo esperar por:
+Ese "esperar otra cosa" normalmente se refiere a las operaciones de I/O que son relativamente "lentas" (comparadas con la velocidad del procesador y la memoria RAM), como esperar:
-* los datos de cliente que se envían a través de la red
-* los datos enviados por tu programa para ser recibidos por el cliente a través de la red
-* el contenido de un archivo en disco para ser leído por el sistema y entregado al programa
-* los contenidos que tu programa da al sistema para ser escritos en disco
-* una operación relacionada con una API remota
-* una operación de base de datos
-* el retorno de resultados de una consulta de base de datos
+* que los datos del cliente se envíen a través de la red
+* que los datos enviados por tu programa sean recibidos por el cliente a través de la red
+* que el contenido de un archivo en el disco sea leído por el sistema y entregado a tu programa
+* que el contenido que tu programa entregó al sistema sea escrito en el disco
+* una operación de API remota
+* que una operación de base de datos termine
+* que una query de base de datos devuelva los resultados
* etc.
-Como el tiempo de ejecución se consume principalmente al esperar a operaciones de I/O, las llaman operaciones "I/O bound".
+Como el tiempo de ejecución se consume principalmente esperando operaciones de I/O, las llaman operaciones "I/O bound".
-Se llama "asíncrono" porque el sistema / programa no tiene que estar "sincronizado" con la tarea lenta, esperando el momento exacto en que finaliza la tarea, sin hacer nada, para poder recoger el resultado de la tarea y continuar el trabajo.
+Se llama "asíncrono" porque la computadora / programa no tiene que estar "sincronizado" con la tarea lenta, esperando el momento exacto en que la tarea termine, sin hacer nada, para poder tomar el resultado de la tarea y continuar el trabajo.
-En lugar de eso, al ser un sistema "asíncrono", una vez finalizada, la tarea puede esperar un poco en la cola (algunos microsegundos) para que la computadora / programa termine lo que estaba haciendo, y luego vuelva para recoger los resultados y seguir trabajando con ellos.
+En lugar de eso, al ser un sistema "asíncrono", una vez terminado, la tarea puede esperar un poco en la cola (algunos microsegundos) para que la computadora / programa termine lo que salió a hacer, y luego regrese para tomar los resultados y continuar trabajando con ellos.
-Por "síncrono" (contrario a "asíncrono") también se usa habitualmente el término "secuencial", porque el sistema / programa sigue todos los pasos secuencialmente antes de cambiar a una tarea diferente, incluso si esos pasos implican esperas.
+Para el "sincrónico" (contrario al "asíncrono") comúnmente también usan el término "secuencial", porque la computadora / programa sigue todos los pasos en secuencia antes de cambiar a una tarea diferente, incluso si esos pasos implican esperar.
-### Concurrencia y Hamburguesas
+### Concurrencia y Hamburguesas { #concurrency-and-burgers }
-El concepto de código **asíncrono** descrito anteriormente a veces también se llama **"concurrencia"**. Es diferente del **"paralelismo"**.
+Esta idea de código **asíncrono** descrita anteriormente a veces también se llama **"concurrencia"**. Es diferente del **"paralelismo"**.
-**Concurrencia** y **paralelismo** ambos se relacionan con "cosas diferentes que suceden más o menos al mismo tiempo".
+**Concurrencia** y **paralelismo** ambos se relacionan con "diferentes cosas sucediendo más o menos al mismo tiempo".
Pero los detalles entre *concurrencia* y *paralelismo* son bastante diferentes.
-Para entender las diferencias, imagina la siguiente historia sobre hamburguesas:
+Para ver la diferencia, imagina la siguiente historia sobre hamburguesas:
-### Hamburguesas Concurrentes
+### Hamburguesas Concurrentes { #concurrent-burgers }
-Vas con la persona que te gusta 😍 a pedir comida rápida 🍔, haces cola mientras el cajero 💁 recoge los pedidos de las personas de delante tuyo.
+Vas con tu crush a conseguir comida rápida, te pones en fila mientras el cajero toma los pedidos de las personas frente a ti. 😍
-
+
-Llega tu turno, haces tu pedido de 2 hamburguesas impresionantes para esa persona 😍 y para ti.
+Luego es tu turno, haces tu pedido de 2 hamburguesas muy sofisticadas para tu crush y para ti. 🍔🍔
-
+
-El cajero 💁 le dice algo al chico de la cocina 👨🍳 para que sepa que tiene que preparar tus hamburguesas 🍔 (a pesar de que actualmente está preparando las de los clientes anteriores).
+El cajero dice algo al cocinero en la cocina para que sepan que tienen que preparar tus hamburguesas (aunque actualmente están preparando las de los clientes anteriores).
-
+
-Pagas 💸.
-El cajero 💁 te da el número de tu turno.
+Pagas. 💸
+
+El cajero te da el número de tu turno.
+
+
-
+Mientras esperas, vas con tu crush y eliges una mesa, te sientas y hablas con tu crush por un largo rato (ya que tus hamburguesas son muy sofisticadas y toman un tiempo en prepararse).
-Mientras esperas, vas con esa persona 😍 y eliges una mesa, se sientan y hablan durante un rato largo (ya que las hamburguesas son muy impresionantes y necesitan un rato para prepararse ✨🍔✨).
+Mientras estás sentado en la mesa con tu crush, mientras esperas las hamburguesas, puedes pasar ese tiempo admirando lo increíble, lindo e inteligente que es tu crush ✨😍✨.
-Mientras te sientas en la mesa con esa persona 😍, esperando las hamburguesas 🍔, puedes disfrutar ese tiempo admirando lo increíble, inteligente, y bien que se ve ✨😍✨.
+
-
+Mientras esperas y hablas con tu crush, de vez en cuando revisas el número mostrado en el mostrador para ver si ya es tu turno.
-Mientras esperas y hablas con esa persona 😍, de vez en cuando, verificas el número del mostrador para ver si ya es tu turno.
+Luego, en algún momento, finalmente es tu turno. Vas al mostrador, obtienes tus hamburguesas y vuelves a la mesa.
-Al final, en algún momento, llega tu turno. Vas al mostrador, coges tus hamburguesas 🍔 y vuelves a la mesa.
+
-
+Tú y tu crush comen las hamburguesas y pasan un buen rato. ✨
-Tú y esa persona 😍 se comen las hamburguesas 🍔 y la pasan genial ✨.
+
-
+/// info | Información
-!!! info
- Las ilustraciones fueron creados por Ketrina Thompson. 🎨
+Hermosas ilustraciones de [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨
+
+///
---
-Imagina que eres el sistema / programa 🤖 en esa historia.
+Imagina que eres la computadora / programa 🤖 en esa historia.
-Mientras estás en la cola, estás quieto 😴, esperando tu turno, sin hacer nada muy "productivo". Pero la línea va rápida porque el cajero 💁 solo recibe los pedidos (no los prepara), así que está bien.
+Mientras estás en la fila, estás inactivo 😴, esperando tu turno, sin hacer nada muy "productivo". Pero la fila es rápida porque el cajero solo está tomando los pedidos (no preparándolos), así que está bien.
-Luego, cuando llega tu turno, haces un trabajo "productivo" real 🤓, procesas el menú, decides lo que quieres, lo que quiere esa persona 😍, pagas 💸, verificas que das el billete o tarjeta correctos, verificas que te cobren correctamente, que el pedido tiene los artículos correctos, etc.
+Luego, cuando es tu turno, haces un trabajo realmente "productivo", procesas el menú, decides lo que quieres, obtienes la elección de tu crush, pagas, verificas que das el billete o tarjeta correctos, verificas que te cobren correctamente, verificas que el pedido tenga los artículos correctos, etc.
-Pero entonces, aunque aún no tienes tus hamburguesas 🍔, el trabajo hecho con el cajero 💁 está "en pausa" ⏸, porque debes esperar 🕙 a que tus hamburguesas estén listas.
+Pero luego, aunque todavía no tienes tus hamburguesas, tu trabajo con el cajero está "en pausa" ⏸, porque tienes que esperar 🕙 a que tus hamburguesas estén listas.
-Pero como te alejas del mostrador y te sientas en la mesa con un número para tu turno, puedes cambiar tu atención 🔀 a esa persona 😍 y "trabajar" ⏯ 🤓 en eso. Entonces nuevamente estás haciendo algo muy "productivo" 🤓, como coquetear con esa persona 😍.
+Pero como te alejas del mostrador y te sientas en la mesa con un número para tu turno, puedes cambiar 🔀 tu atención a tu crush, y "trabajar" ⏯ 🤓 en eso. Luego, nuevamente estás haciendo algo muy "productivo" como es coquetear con tu crush 😍.
-Después, el 💁 cajero dice "he terminado de hacer las hamburguesas" 🍔 poniendo tu número en la pantalla del mostrador, pero no saltas al momento que el número que se muestra es el tuyo. Sabes que nadie robará tus hamburguesas 🍔 porque tienes el número de tu turno y ellos tienen el suyo.
+Luego el cajero 💁 dice "he terminado de hacer las hamburguesas" al poner tu número en el mostrador, pero no saltas como loco inmediatamente cuando el número mostrado cambia a tu número de turno. Sabes que nadie robará tus hamburguesas porque tienes el número de tu turno, y ellos tienen el suyo.
-Así que esperas a que esa persona 😍 termine la historia (terminas el trabajo actual ⏯ / tarea actual que se está procesando 🤓), sonríes gentilmente y le dices que vas por las hamburguesas ⏸.
+Así que esperas a que tu crush termine la historia (termine el trabajo ⏯ / tarea actual que se está procesando 🤓), sonríes amablemente y dices que vas por las hamburguesas ⏸.
-Luego vas al mostrador 🔀, a la tarea inicial que ya está terminada ⏯, recoges las hamburguesas 🍔, les dices gracias y las llevas a la mesa. Eso termina esa fase / tarea de interacción con el mostrador ⏹. Eso a su vez, crea una nueva tarea, "comer hamburguesas" 🔀 ⏯, pero la anterior de "conseguir hamburguesas" está terminada ⏹.
+Luego vas al mostrador 🔀, a la tarea inicial que ahora está terminada ⏯, recoges las hamburguesas, das las gracias y las llevas a la mesa. Eso termina ese paso / tarea de interacción con el mostrador ⏹. Eso a su vez, crea una nueva tarea, de "comer hamburguesas" 🔀 ⏯, pero la anterior de "obtener hamburguesas" ha terminado ⏹.
-### Hamburguesas Paralelas
+### Hamburguesas Paralelas { #parallel-burgers }
-Ahora imagina que estas no son "Hamburguesas Concurrentes" sino "Hamburguesas Paralelas".
+Ahora imaginemos que estas no son "Hamburguesas Concurrentes", sino "Hamburguesas Paralelas".
-Vas con la persona que te gusta 😍 por comida rápida paralela 🍔.
+Vas con tu crush a obtener comida rápida paralela.
-Haces la cola mientras varios cajeros (digamos 8) que a la vez son cocineros 👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳 toman los pedidos de las personas que están delante de ti.
+Te pones en fila mientras varios (digamos 8) cajeros que al mismo tiempo son cocineros toman los pedidos de las personas frente a ti.
-Todos los que están antes de ti están esperando 🕙 que sus hamburguesas 🍔 estén listas antes de dejar el mostrador porque cada uno de los 8 cajeros prepara la hamburguesa de inmediato antes de recibir el siguiente pedido.
+Todos antes que tú están esperando a que sus hamburguesas estén listas antes de dejar el mostrador porque cada uno de los 8 cajeros va y prepara la hamburguesa de inmediato antes de obtener el siguiente pedido.
-
+
-Entonces finalmente es tu turno, haces tu pedido de 2 hamburguesas 🍔 impresionantes para esa persona 😍 y para ti.
+Luego, finalmente es tu turno, haces tu pedido de 2 hamburguesas muy sofisticadas para tu crush y para ti.
Pagas 💸.
-
+
+
+El cajero va a la cocina.
-El cajero va a la cocina 👨🍳.
+Esperas, de pie frente al mostrador 🕙, para que nadie más tome tus hamburguesas antes que tú, ya que no hay números para los turnos.
-Esperas, de pie frente al mostrador 🕙, para que nadie más recoja tus hamburguesas 🍔, ya que no hay números para los turnos.
+
-
+Como tú y tu crush están ocupados no dejando que nadie se interponga y tome tus hamburguesas cuando lleguen, no puedes prestar atención a tu crush. 😞
-Como tu y esa persona 😍 están ocupados en impedir que alguien se ponga delante y recoja tus hamburguesas apenas llegan 🕙, tampoco puedes prestarle atención a esa persona 😞.
+Este es un trabajo "sincrónico", estás "sincronizado" con el cajero/cocinero 👨🍳. Tienes que esperar 🕙 y estar allí en el momento exacto en que el cajero/cocinero 👨🍳 termine las hamburguesas y te las entregue, o de lo contrario, alguien más podría tomarlas.
-Este es un trabajo "síncrono", estás "sincronizado" con el cajero / cocinero 👨🍳. Tienes que esperar y estar allí en el momento exacto en que el cajero / cocinero 👨🍳 termina las hamburguesas 🍔 y te las da, o de lo contrario, alguien más podría cogerlas.
+
-
+Luego tu cajero/cocinero 👨🍳 finalmente regresa con tus hamburguesas, después de mucho tiempo esperando 🕙 allí frente al mostrador.
-Luego, el cajero / cocinero 👨🍳 finalmente regresa con tus hamburguesas 🍔, después de mucho tiempo esperando 🕙 frente al mostrador.
+
-
+Tomas tus hamburguesas y vas a la mesa con tu crush.
-Cojes tus hamburguesas 🍔 y vas a la mesa con esa persona 😍.
+Simplemente las comes, y has terminado. ⏹
-Sólo las comes y listo 🍔 ⏹.
+
-
+No hubo mucho hablar o coquetear ya que la mayor parte del tiempo se dedicó a esperar 🕙 frente al mostrador. 😞
-No has hablado ni coqueteado mucho, ya que has pasado la mayor parte del tiempo esperando 🕙 frente al mostrador 😞.
+/// info | Información
-!!! info
- Las ilustraciones fueron creados por Ketrina Thompson. 🎨
+Hermosas ilustraciones de [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨
+
+///
---
-En este escenario de las hamburguesas paralelas, tú eres un sistema / programa 🤖 con dos procesadores (tú y la persona que te gusta 😍), ambos esperando 🕙 y dedicando su atención ⏯ a estar "esperando en el mostrador" 🕙 durante mucho tiempo.
+En este escenario de las hamburguesas paralelas, eres una computadora / programa 🤖 con dos procesadores (tú y tu crush), ambos esperando 🕙 y dedicando su atención ⏯ a estar "esperando en el mostrador" 🕙 por mucho tiempo.
-La tienda de comida rápida tiene 8 procesadores (cajeros / cocineros) 👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳. Mientras que la tienda de hamburguesas concurrentes podría haber tenido solo 2 (un cajero y un cocinero) 💁 👨🍳.
+La tienda de comida rápida tiene 8 procesadores (cajeros/cocineros). Mientras que la tienda de hamburguesas concurrentes podría haber tenido solo 2 (un cajero y un cocinero).
-Pero aún así, la experiencia final no es la mejor 😞.
+Pero aún así, la experiencia final no es la mejor. 😞
---
-Esta sería la historia paralela equivalente de las hamburguesas 🍔.
+Esta sería la historia equivalente de las hamburguesas paralelas. 🍔
-Para un ejemplo más "real" de ésto, imagina un banco.
+Para un ejemplo más "de la vida real" de esto, imagina un banco.
-Hasta hace poco, la mayoría de los bancos tenían varios cajeros 👨💼👨💼👨💼👨💼 y una gran línea 🕙🕙🕙🕙🕙🕙🕙🕙.
+Hasta hace poco, la mayoría de los bancos tenían múltiples cajeros 👨💼👨💼👨💼👨💼 y una gran fila 🕙🕙🕙🕙🕙🕙🕙🕙.
Todos los cajeros haciendo todo el trabajo con un cliente tras otro 👨💼⏯.
-Y tienes que esperar 🕙 en la fila durante mucho tiempo o perderás tu turno.
-
-Probablemente no querrás llevar contigo a la persona que te gusta 😍 a hacer encargos al banco 🏦.
+Y tienes que esperar 🕙 en la fila por mucho tiempo o pierdes tu turno.
-### Conclusión de las Hamburguesa
+Probablemente no querrías llevar a tu crush 😍 contigo a hacer trámites en el banco 🏦.
-En este escenario de "hamburguesas de comida rápida con tu pareja", debido a que hay mucha espera 🕙, tiene mucho más sentido tener un sistema con concurrencia ⏸🔀⏯.
+### Conclusión de las Hamburguesas { #burger-conclusion }
-Este es el caso de la mayoría de las aplicaciones web.
+En este escenario de "hamburguesas de comida rápida con tu crush", como hay mucha espera 🕙, tiene mucho más sentido tener un sistema concurrente ⏸🔀⏯.
-Muchos, muchos usuarios, pero el servidor está esperando 🕙 el envío de las peticiones ya que su conexión no es buena.
+Este es el caso para la mayoría de las aplicaciones web.
-Y luego esperando 🕙 nuevamente a que las respuestas retornen.
+Muchos, muchos usuarios, pero tu servidor está esperando 🕙 su conexión no tan buena para enviar sus requests.
-Esta "espera" 🕙 se mide en microsegundos, pero aun así, sumando todo, al final es mucha espera.
+Y luego esperar 🕙 nuevamente a que los responses retornen.
-Es por eso que tiene mucho sentido usar código asíncrono ⏸🔀⏯ para las API web.
+Esta "espera" 🕙 se mide en microsegundos, pero aún así, sumándolo todo, es mucha espera al final.
-La mayoría de los framework populares de Python existentes (incluidos Flask y Django) se crearon antes de que existieran las nuevas funciones asíncronas en Python. Por lo tanto, las formas en que pueden implementarse admiten la ejecución paralela y una forma más antigua de ejecución asíncrona que no es tan potente como la actual.
+Por eso tiene mucho sentido usar código asíncrono ⏸🔀⏯ para las APIs web.
-A pesar de que la especificación principal para Python web asíncrono (ASGI) se desarrolló en Django, para agregar soporte para WebSockets.
-
-Ese tipo de asincronía es lo que hizo popular a NodeJS (aunque NodeJS no es paralelo) y esa es la fortaleza de Go como lenguaje de programación.
+Este tipo de asincronía es lo que hizo popular a NodeJS (aunque NodeJS no es paralelo) y esa es la fortaleza de Go como lenguaje de programación.
Y ese es el mismo nivel de rendimiento que obtienes con **FastAPI**.
-Y como puede tener paralelismo y asincronía al mismo tiempo, obtienes un mayor rendimiento que la mayoría de los frameworks de NodeJS probados y a la par con Go, que es un lenguaje compilado más cercano a C (todo gracias Starlette).
+Y como puedes tener paralelismo y asincronía al mismo tiempo, obtienes un mayor rendimiento que la mayoría de los frameworks de NodeJS probados y a la par con Go, que es un lenguaje compilado más cercano a C [(todo gracias a Starlette)](https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=query&l=zijmkf-1).
-### ¿Es la concurrencia mejor que el paralelismo?
+### ¿Es la concurrencia mejor que el paralelismo? { #is-concurrency-better-than-parallelism }
¡No! Esa no es la moraleja de la historia.
-La concurrencia es diferente al paralelismo. Y es mejor en escenarios **específicos** que implican mucha espera. Debido a eso, generalmente es mucho mejor que el paralelismo para el desarrollo de aplicaciones web. Pero no para todo.
+La concurrencia es diferente del paralelismo. Y es mejor en escenarios **específicos** que implican mucha espera. Debido a eso, generalmente es mucho mejor que el paralelismo para el desarrollo de aplicaciones web. Pero no para todo.
-Entonces, para explicar eso, imagina la siguiente historia corta:
+Así que, para equilibrar eso, imagina la siguiente historia corta:
> Tienes que limpiar una casa grande y sucia.
@@ -261,80 +267,80 @@ Entonces, para explicar eso, imagina la siguiente historia corta:
---
-No hay esperas 🕙, solo hay mucho trabajo por hacer, en varios lugares de la casa.
+No hay esperas 🕙 en ninguna parte, solo mucho trabajo por hacer, en múltiples lugares de la casa.
-Podrías tener turnos como en el ejemplo de las hamburguesas, primero la sala de estar, luego la cocina, pero como no estás esperando nada, solo limpiando y limpiando, los turnos no afectarían nada.
+Podrías tener turnos como en el ejemplo de las hamburguesas, primero la sala de estar, luego la cocina, pero como no estás esperando 🕙 nada, solo limpiando y limpiando, los turnos no afectarían nada.
Tomaría la misma cantidad de tiempo terminar con o sin turnos (concurrencia) y habrías hecho la misma cantidad de trabajo.
-Pero en este caso, si pudieras traer a los 8 ex cajeros / cocineros / ahora limpiadores 👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳, y cada uno de ellos (y tú) podría tomar una zona de la casa para limpiarla, podría hacer todo el trabajo en **paralelo**, con la ayuda adicional y terminar mucho antes.
+Pero en este caso, si pudieras traer a los 8 ex-cajeros/cocineros/ahora-limpiadores, y cada uno de ellos (más tú) pudiera tomar una zona de la casa para limpiarla, podrías hacer todo el trabajo en **paralelo**, con la ayuda extra, y terminar mucho antes.
-En este escenario, cada uno de los limpiadores (incluido tú) sería un procesador, haciendo su parte del trabajo.
+En este escenario, cada uno de los limpiadores (incluyéndote) sería un procesador, haciendo su parte del trabajo.
-Y como la mayor parte del tiempo de ejecución lo coge el trabajo real (en lugar de esperar), y el trabajo en un sistema lo realiza una CPU , a estos problemas se les llama "CPU bound".
+Y como la mayor parte del tiempo de ejecución se dedica al trabajo real (en lugar de esperar), y el trabajo en una computadora lo realiza una CPU, llaman a estos problemas "CPU bound".
---
-Ejemplos típicos de operaciones dependientes de CPU son cosas que requieren un procesamiento matemático complejo.
+Ejemplos comunes de operaciones limitadas por la CPU son cosas que requieren procesamiento matemático complejo.
Por ejemplo:
-* **Audio** o **procesamiento de imágenes**.
-* **Visión por computadora**: una imagen está compuesta de millones de píxeles, cada píxel tiene 3 valores / colores, procesamiento que normalmente requiere calcular algo en esos píxeles, todo al mismo tiempo.
-* **Machine Learning**: normalmente requiere muchas multiplicaciones de "matrices" y "vectores". Imagina en una enorme hoja de cálculo con números y tener que multiplicarlos todos al mismo tiempo.
-* **Deep Learning**: este es un subcampo de Machine Learning, por lo tanto, aplica lo mismo. Es solo que no hay una sola hoja de cálculo de números para multiplicar, sino un gran conjunto de ellas, y en muchos casos, usa un procesador especial para construir y / o usar esos modelos.
+* **Procesamiento de audio** o **imágenes**.
+* **Visión por computadora**: una imagen está compuesta de millones de píxeles, cada píxel tiene 3 valores / colores, procesar eso normalmente requiere calcular algo en esos píxeles, todos al mismo tiempo.
+* **Machine Learning**: normalmente requiere muchas multiplicaciones de "matrices" y "vectores". Piensa en una enorme hoja de cálculo con números y multiplicando todos juntos al mismo tiempo.
+* **Deep Learning**: este es un subcampo de Machine Learning, por lo tanto, se aplica lo mismo. Es solo que no hay una sola hoja de cálculo de números para multiplicar, sino un enorme conjunto de ellas, y en muchos casos, usas un procesador especial para construir y / o usar esos modelos.
-### Concurrencia + Paralelismo: Web + Machine Learning
+### Concurrencia + Paralelismo: Web + Machine Learning { #concurrency-parallelism-web-machine-learning }
-Con **FastAPI** puedes aprovechar la concurrencia que es muy común para el desarrollo web (atractivo principal de NodeJS).
+Con **FastAPI** puedes aprovechar la concurrencia que es muy común para el desarrollo web (la misma atracción principal de NodeJS).
-Pero también puedes aprovechar los beneficios del paralelismo y el multiprocesamiento (tener múltiples procesos ejecutándose en paralelo) para cargas de trabajo **CPU bound** como las de los sistemas de Machine Learning.
+Pero también puedes explotar los beneficios del paralelismo y la multiprocesamiento (tener múltiples procesos ejecutándose en paralelo) para cargas de trabajo **CPU bound** como las de los sistemas de Machine Learning.
-Eso, más el simple hecho de que Python es el lenguaje principal para **Data Science**, Machine Learning y especialmente Deep Learning, hacen de FastAPI una muy buena combinación para las API y aplicaciones web de Data Science / Machine Learning (entre muchas otras).
+Eso, más el simple hecho de que Python es el lenguaje principal para **Data Science**, Machine Learning y especialmente Deep Learning, hacen de FastAPI una muy buena opción para APIs web de Data Science / Machine Learning y aplicaciones (entre muchas otras).
-Para ver cómo lograr este paralelismo en producción, consulta la sección sobre [Despliegue](deployment/index.md){.internal-link target=_blank}.
+Para ver cómo lograr este paralelismo en producción, consulta la sección sobre [Despliegue](deployment/index.md).
-## `async` y `await`
+## `async` y `await` { #async-and-await }
-Las versiones modernas de Python tienen una forma muy intuitiva de definir código asíncrono. Esto hace que se vea como un código "secuencial" normal y que haga la "espera" por ti en los momentos correctos.
+Las versiones modernas de Python tienen una forma muy intuitiva de definir código asíncrono. Esto hace que se vea igual que el código "secuencial" normal y hace el "wait" por ti en los momentos adecuados.
-Cuando hay una operación que requerirá esperar antes de dar los resultados y tiene soporte para estas nuevas características de Python, puedes programarlo como:
+Cuando hay una operación que requerirá esperar antes de dar los resultados y tiene soporte para estas nuevas funcionalidades de Python, puedes programarlo así:
```Python
burgers = await get_burgers(2)
```
-La clave aquí es `await`. Eso le dice a Python que tiene que esperar ⏸ a que `get_burgers (2)` termine de hacer lo suyo 🕙 antes de almacenar los resultados en `hamburguesas`. Con eso, Python sabrá que puede ir y hacer otra cosa 🔀 ⏯ mientras tanto (como recibir otra solicitud).
+La clave aquí es el `await`. Dice a Python que tiene que esperar ⏸ a que `get_burgers(2)` termine de hacer su cosa 🕙 antes de almacenar los resultados en `burgers`. Con eso, Python sabrá que puede ir y hacer algo más 🔀 ⏯ mientras tanto (como recibir otro request).
-Para que `await` funcione, tiene que estar dentro de una función que admita esta asincronía. Para hacer eso, simplemente lo declaras con `async def`:
+Para que `await` funcione, tiene que estar dentro de una función que soporte esta asincronía. Para hacer eso, solo declara la función con `async def`:
```Python hl_lines="1"
async def get_burgers(number: int):
- # Do some asynchronous stuff to create the burgers
+ # Hacer algunas cosas asíncronas para crear las hamburguesas
return burgers
```
-...en vez de `def`:
+...en lugar de `def`:
```Python hl_lines="2"
-# This is not asynchronous
+# Esto no es asíncrono
def get_sequential_burgers(number: int):
- # Do some sequential stuff to create the burgers
+ # Hacer algunas cosas secuenciales para crear las hamburguesas
return burgers
```
-Con `async def`, Python sabe que, dentro de esa función, debe tener en cuenta las expresiones `wait` y que puede "pausar" ⏸ la ejecución de esa función e ir a hacer otra cosa 🔀 antes de regresar.
+Con `async def`, Python sabe que, dentro de esa función, tiene que estar atento a las expresiones `await`, y que puede "pausar" ⏸ la ejecución de esa función e ir a hacer algo más 🔀 antes de regresar.
-Cuando desees llamar a una función `async def`, debes "esperarla". Entonces, esto no funcionará:
+Cuando deseas llamar a una función `async def`, tienes que "await" dicha función. Así que, esto no funcionará:
```Python
-# Esto no funcionará, porque get_burgers se definió con: async def
-hamburguesas = get_burgers (2)
+# Esto no funcionará, porque get_burgers fue definido con: async def
+burgers = get_burgers(2)
```
---
-Por lo tanto, si estás utilizando una library que te dice que puedes llamarla con `await`, debes crear las *path operation functions* que la usan con `async def`, como en:
+Así que, si estás usando un paquete que te dice que puedes llamarlo con `await`, necesitas crear las *path operation functions* que lo usen con `async def`, como en:
```Python hl_lines="2-3"
@app.get('/burgers')
@@ -343,83 +349,96 @@ async def read_burgers():
return burgers
```
-### Más detalles técnicos
+### Más detalles técnicos { #more-technical-details }
+
+Podrías haber notado que `await` solo se puede usar dentro de funciones definidas con `async def`.
+
+Pero al mismo tiempo, las funciones definidas con `async def` deben ser "awaited". Por lo tanto, las funciones con `async def` solo se pueden llamar dentro de funciones definidas con `async def` también.
+
+Entonces, sobre el huevo y la gallina, ¿cómo llamas a la primera función `async`?
-Es posible que hayas notado que `await` solo se puede usar dentro de las funciones definidas con `async def`.
+Si estás trabajando con **FastAPI** no tienes que preocuparte por eso, porque esa "primera" función será tu *path operation function*, y FastAPI sabrá cómo hacer lo correcto.
-Pero al mismo tiempo, las funciones definidas con `async def` deben ser "esperadas". Por lo tanto, las funciones con `async def` solo se pueden invocar dentro de las funciones definidas con `async def` también.
+Pero si deseas usar `async` / `await` sin FastAPI, también puedes hacerlo.
-Entonces, relacionado con la paradoja del huevo y la gallina, ¿cómo se llama a la primera función `async`?
+### Escribe tu propio código async { #write-your-own-async-code }
-Si estás trabajando con **FastAPI** no tienes que preocuparte por eso, porque esa "primera" función será tu *path operation function*, y FastAPI sabrá cómo hacer lo pertinente.
+Starlette (y **FastAPI**) están basados en [AnyIO](https://anyio.readthedocs.io/en/stable/), lo que lo hace compatible tanto con el [asyncio](https://docs.python.org/3/library/asyncio-task.html) del paquete estándar de Python como con [Trio](https://trio.readthedocs.io/en/stable/).
-En el caso de que desees usar `async` / `await` sin FastAPI, revisa la documentación oficial de Python.
+En particular, puedes usar directamente [AnyIO](https://anyio.readthedocs.io/en/stable/) para tus casos de uso avanzados de concurrencia que requieran patrones más avanzados en tu propio código.
-### Otras formas de código asíncrono
+E incluso si no estuvieras usando FastAPI, también podrías escribir tus propias aplicaciones asíncronas con [AnyIO](https://anyio.readthedocs.io/en/stable/) para ser altamente compatibles y obtener sus beneficios (p.ej. *concurrencia estructurada*).
+
+Creé otro paquete sobre AnyIO, como una capa delgada, para mejorar un poco las anotaciones de tipos y obtener mejor **autocompletado**, **errores en línea**, etc. También tiene una introducción amigable y tutorial para ayudarte a **entender** y escribir **tu propio código async**: [Asyncer](https://asyncer.tiangolo.com/). Sería particularmente útil si necesitas **combinar código async con regular** (bloqueante/sincrónico).
+
+### Otras formas de código asíncrono { #other-forms-of-asynchronous-code }
Este estilo de usar `async` y `await` es relativamente nuevo en el lenguaje.
Pero hace que trabajar con código asíncrono sea mucho más fácil.
-Esta misma sintaxis (o casi idéntica) también se incluyó recientemente en las versiones modernas de JavaScript (en Browser y NodeJS).
+Esta misma sintaxis (o casi idéntica) también se incluyó recientemente en las versiones modernas de JavaScript (en el Navegador y NodeJS).
-Pero antes de eso, manejar código asíncrono era bastante más complejo y difícil.
+Pero antes de eso, manejar el código asíncrono era mucho más complejo y difícil.
-En versiones anteriores de Python, podrías haber utilizado threads o Gevent. Pero el código es mucho más complejo de entender, depurar y desarrollar.
+En versiones previas de Python, podrías haber usado hilos o [Gevent](https://www.gevent.org/). Pero el código es mucho más complejo de entender, depurar y razonar.
-En versiones anteriores de NodeJS / Browser JavaScript, habrías utilizado "callbacks". Lo que conduce a callback hell.
+En versiones previas de NodeJS / JavaScript en el Navegador, habrías usado "callbacks". Lo que lleva al "callback hell".
-## Coroutines
+## Coroutines { #coroutines }
-**Coroutine** es un término sofisticado para referirse a la cosa devuelta por una función `async def`. Python sabe que es algo así como una función que puede iniciar y que terminará en algún momento, pero que también podría pausarse ⏸ internamente, siempre que haya un `await` dentro de ella.
+**Coroutines** es simplemente el término muy elegante para la cosa que devuelve una función `async def`. Python sabe que es algo parecido a una función, que puede comenzar y que terminará en algún momento, pero que podría pausar ⏸ internamente también, siempre que haya un `await` dentro de él.
-Pero toda esta funcionalidad de usar código asincrónico con `async` y `await` se resume muchas veces como usar "coroutines". Es comparable a la característica principal de Go, las "Goroutines".
+Pero toda esta funcionalidad de usar código asíncrono con `async` y `await` a menudo se resume como utilizar "coroutines". Es comparable a la funcionalidad clave principal de Go, las "Goroutines".
-## Conclusión
+## Conclusión { #conclusion }
Veamos la misma frase de arriba:
-> Las versiones modernas de Python tienen soporte para **"código asíncrono"** usando algo llamado **"coroutines"**, con la sintaxis **`async` y `await`**.
+> Las versiones modernas de Python tienen soporte para **"código asíncrono"** utilizando algo llamado **"coroutines"**, con la sintaxis **`async` y `await`**.
-Eso ya debería tener más sentido ahora. ✨
+Eso debería tener más sentido ahora. ✨
Todo eso es lo que impulsa FastAPI (a través de Starlette) y lo que hace que tenga un rendimiento tan impresionante.
-## Detalles muy técnicos
+## Detalles Muy Técnicos { #very-technical-details }
+
+/// warning | Advertencia
+
+Probablemente puedas saltarte esto.
-!!! warning "Advertencia"
- Probablemente puedas saltarte esto.
+Estos son detalles muy técnicos de cómo **FastAPI** funciona en su interior.
- Estos son detalles muy técnicos de cómo **FastAPI** funciona a muy bajo nivel.
+Si tienes bastante conocimiento técnico (coroutines, hilos, bloqueo, etc.) y tienes curiosidad sobre cómo FastAPI maneja `async def` vs `def` normal, adelante.
- Si tienes bastante conocimiento técnico (coroutines, threads, bloqueos, etc.) y tienes curiosidad acerca de cómo FastAPI gestiona `async def` vs `def` normal, continúa.
+///
-### Path operation functions
+### Funciones de *path operation* { #path-operation-functions }
-Cuando declaras una *path operation function* con `def` normal en lugar de `async def`, se ejecuta en un threadpool externo que luego es "awaited", en lugar de ser llamado directamente (ya que bloquearía el servidor).
+Cuando declaras una *path operation function* con `def` normal en lugar de `async def`, se ejecuta en un threadpool externo que luego es esperado, en lugar de ser llamado directamente (ya que bloquearía el servidor).
-Si vienes de otro framework asíncrono que no funciona de la manera descrita anteriormente y estás acostumbrado a definir *path operation functions* del tipo sólo cálculo con `def` simple para una pequeña ganancia de rendimiento (aproximadamente 100 nanosegundos), ten en cuenta que en **FastAPI** el efecto sería bastante opuesto. En estos casos, es mejor usar `async def` a menos que tus *path operation functions* usen un código que realice el bloqueo I/O.
+Si vienes de otro framework async que no funciona de la manera descrita anteriormente y estás acostumbrado a definir funciones de *path operation* solo de cómputo trivial con `def` normal para una pequeña ganancia de rendimiento (alrededor de 100 nanosegundos), ten en cuenta que en **FastAPI** el efecto sería bastante opuesto. En estos casos, es mejor usar `async def` a menos que tus *path operation functions* usen código que realice I/O de bloqueo.
-Aún así, en ambas situaciones, es probable que **FastAPI** sea [aún más rápido](/#rendimiento){.Internal-link target=_blank} que (o al menos comparable) a tu framework anterior.
+Aun así, en ambas situaciones, es probable que **FastAPI** [siga siendo más rápida](index.md#performance) que (o al menos comparable a) tu framework anterior.
-### Dependencias
+### Dependencias { #dependencies }
-Lo mismo se aplica para las dependencias. Si una dependencia es una función estándar `def` en lugar de `async def`, se ejecuta en el threadpool externo.
+Lo mismo aplica para las [dependencias](tutorial/dependencies/index.md). Si una dependencia es una función estándar `def` en lugar de `async def`, se ejecuta en el threadpool externo.
-### Subdependencias
+### Sub-dependencias { #sub-dependencies }
-Puedes tener múltiples dependencias y subdependencias que se requieren unas a otras (como parámetros de las definiciones de cada función), algunas de ellas pueden crearse con `async def` y otras con `def` normal. Igual todo seguiría funcionando correctamente, y las creadas con `def` normal se llamarían en un thread externo (del threadpool) en lugar de ser "awaited".
+Puedes tener múltiples dependencias y [sub-dependencias](tutorial/dependencies/sub-dependencies.md) requiriéndose mutuamente (como parámetros de las definiciones de funciones), algunas de ellas podrían ser creadas con `async def` y algunas con `def` normal. Aun funcionará, y las que fueron creadas con `def` normal serían llamadas en un hilo externo (del threadpool) en lugar de ser "awaited".
-### Otras funciones de utilidades
+### Otras funciones de utilidad { #other-utility-functions }
-Cualquier otra función de utilidad que llames directamente se puede crear con `def` o `async def` normales y FastAPI no afectará la manera en que la llames.
+Cualquier otra función de utilidad que llames directamente puede ser creada con `def` normal o `async def` y FastAPI no afectará la forma en que la llames.
-Esto contrasta con las funciones que FastAPI llama por ti: las *path operation functions* y dependencias.
+Esto contrasta con las funciones que FastAPI llama por ti: *path operation functions* y dependencias.
-Si tu función de utilidad es creada con `def` normal, se llamará directamente (tal cual la escribes en tu código), no en un threadpool, si la función se crea con `async def`, entonces debes usar `await` con esa función cuando la llamas en tu código.
+Si tu función de utilidad es una función normal con `def`, será llamada directamente (como la escribas en tu código), no en un threadpool; si la función es creada con `async def` entonces deberías "await" por esa función cuando la llames en tu código.
---
-Nuevamente, estos son detalles muy técnicos que probablemente sólo son útiles si los viniste a buscar expresamente.
+Nuevamente, estos son detalles muy técnicos que probablemente serían útiles si los buscaste.
-De lo contrario, la guía de la sección anterior debería ser suficiente: ¿Tienes prisa?.
+De lo contrario, deberías estar bien con las pautas de la sección anterior: ¿Con prisa?.
diff --git a/docs/es/docs/benchmarks.md b/docs/es/docs/benchmarks.md
new file mode 100644
index 0000000000000..040dc58129717
--- /dev/null
+++ b/docs/es/docs/benchmarks.md
@@ -0,0 +1,34 @@
+# Benchmarks { #benchmarks }
+
+Los benchmarks independientes de TechEmpower muestran aplicaciones de **FastAPI** ejecutándose bajo Uvicorn como [uno de los frameworks de Python más rápidos disponibles](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7), solo por debajo de Starlette y Uvicorn en sí mismos (utilizados internamente por FastAPI).
+
+Pero al revisar benchmarks y comparaciones, debes tener en cuenta lo siguiente.
+
+## Benchmarks y velocidad { #benchmarks-and-speed }
+
+Cuando ves los benchmarks, es común ver varias herramientas de diferentes tipos comparadas como equivalentes.
+
+Específicamente, ver Uvicorn, Starlette y FastAPI comparados juntos (entre muchas otras herramientas).
+
+Cuanto más simple sea el problema resuelto por la herramienta, mejor rendimiento tendrá. Y la mayoría de los benchmarks no prueban las funcionalidades adicionales proporcionadas por la herramienta.
+
+La jerarquía es como:
+
+* **Uvicorn**: un servidor ASGI
+ * **Starlette**: (usa Uvicorn) un microframework web
+ * **FastAPI**: (usa Starlette) un microframework para APIs con varias funcionalidades adicionales para construir APIs, con validación de datos, etc.
+
+* **Uvicorn**:
+ * Tendrá el mejor rendimiento, ya que no tiene mucho código extra aparte del propio servidor.
+ * No escribirías una aplicación directamente en Uvicorn. Eso significaría que tu código tendría que incluir, más o menos, al menos, todo el código proporcionado por Starlette (o **FastAPI**). Y si hicieras eso, tu aplicación final tendría la misma carga que si hubieras usado un framework, minimizando el código de tu aplicación y los bugs.
+ * Si estás comparando Uvicorn, compáralo con Daphne, Hypercorn, uWSGI, etc. Servidores de aplicaciones.
+* **Starlette**:
+ * Tendrá el siguiente mejor rendimiento, después de Uvicorn. De hecho, Starlette usa Uvicorn para ejecutarse. Así que probablemente solo pueda ser "más lento" que Uvicorn por tener que ejecutar más código.
+ * Pero te proporciona las herramientas para construir aplicaciones web sencillas, con enrutamiento basado en paths, etc.
+ * Si estás comparando Starlette, compáralo con Sanic, Flask, Django, etc. Frameworks web (o microframeworks).
+* **FastAPI**:
+ * De la misma forma en que Starlette usa Uvicorn y no puede ser más rápido que él, **FastAPI** usa Starlette, por lo que no puede ser más rápido que él.
+ * FastAPI ofrece más funcionalidades además de las de Starlette. Funcionalidades que casi siempre necesitas al construir APIs, como la validación y serialización de datos. Y al utilizarlo, obtienes documentación automática gratis (la documentación automática ni siquiera añade carga a las aplicaciones en ejecución, se genera al inicio).
+ * Si no usabas FastAPI y utilizabas Starlette directamente (u otra herramienta, como Sanic, Flask, Responder, etc.) tendrías que implementar toda la validación y serialización de datos por ti mismo. Entonces, tu aplicación final aún tendría la misma carga que si hubiera sido construida usando FastAPI. Y en muchos casos, esta validación y serialización de datos es la mayor cantidad de código escrito en las aplicaciones.
+ * Entonces, al usar FastAPI estás ahorrando tiempo de desarrollo, bugs, líneas de código, y probablemente obtendrías el mismo rendimiento (o mejor) que si no lo usaras (ya que tendrías que implementarlo todo en tu código).
+ * Si estás comparando FastAPI, compáralo con un framework de aplicación web (o conjunto de herramientas) que proporcione validación de datos, serialización y documentación, como Flask-apispec, NestJS, Molten, etc. Frameworks con validación de datos, serialización y documentación automáticas integradas.
diff --git a/docs/es/docs/deployment/cloud.md b/docs/es/docs/deployment/cloud.md
new file mode 100644
index 0000000000000..266d3cfd23d68
--- /dev/null
+++ b/docs/es/docs/deployment/cloud.md
@@ -0,0 +1,24 @@
+# Despliega FastAPI en Proveedores de Nube { #deploy-fastapi-on-cloud-providers }
+
+Puedes usar prácticamente **cualquier proveedor de nube** para desplegar tu aplicación FastAPI.
+
+En la mayoría de los casos, los principales proveedores de nube tienen guías para desplegar FastAPI con ellos.
+
+## FastAPI Cloud { #fastapi-cloud }
+
+**[FastAPI Cloud](https://fastapicloud.com)** está construido por el mismo autor y equipo detrás de **FastAPI**.
+
+Simplifica el proceso de **construir**, **desplegar** y **acceder** a una API con un esfuerzo mínimo.
+
+Trae la misma **experiencia de desarrollador** de construir aplicaciones con FastAPI a **desplegarlas** en la nube. 🎉
+
+FastAPI Cloud es el sponsor principal y proveedor de financiamiento de los proyectos open source *FastAPI and friends*. ✨
+
+## Proveedores de Nube - Sponsors { #cloud-providers-sponsors }
+
+Otros proveedores de nube ✨ [**son sponsors de FastAPI**](../help-fastapi.md#sponsor-the-author) ✨ también. 🙇
+
+También podrías considerarlos para seguir sus guías y probar sus servicios:
+
+* [Render](https://docs.render.com/deploy-fastapi?utm_source=deploydoc&utm_medium=referral&utm_campaign=fastapi)
+* [Railway](https://docs.railway.com/guides/fastapi?utm_medium=integration&utm_source=docs&utm_campaign=fastapi)
diff --git a/docs/es/docs/deployment/concepts.md b/docs/es/docs/deployment/concepts.md
new file mode 100644
index 0000000000000..9b3ac0a340d59
--- /dev/null
+++ b/docs/es/docs/deployment/concepts.md
@@ -0,0 +1,321 @@
+# Conceptos de Implementación { #deployments-concepts }
+
+Cuando implementas una aplicación **FastAPI**, o en realidad, cualquier tipo de API web, hay varios conceptos que probablemente te importen, y al entenderlos, puedes encontrar la **forma más adecuada** de **implementar tu aplicación**.
+
+Algunos de los conceptos importantes son:
+
+* Seguridad - HTTPS
+* Ejecución al iniciar
+* Reinicios
+* Replicación (la cantidad de procesos en ejecución)
+* Memoria
+* Pasos previos antes de iniciar
+
+Veremos cómo afectan estas **implementaciones**.
+
+Al final, el objetivo principal es poder **servir a tus clientes de API** de una manera que sea **segura**, para **evitar interrupciones**, y usar los **recursos de cómputo** (por ejemplo, servidores remotos/máquinas virtuales) de la manera más eficiente posible. 🚀
+
+Te contaré un poquito más sobre estos **conceptos** aquí, y eso, con suerte, te dará la **intuición** que necesitarías para decidir cómo implementar tu API en diferentes entornos, posiblemente incluso en aquellos **futuros** que aún no existen.
+
+Al considerar estos conceptos, podrás **evaluar y diseñar** la mejor manera de implementar **tus propias APIs**.
+
+En los próximos capítulos, te daré más **recetas concretas** para implementar aplicaciones de FastAPI.
+
+Pero por ahora, revisemos estas importantes **ideas conceptuales**. Estos conceptos también se aplican a cualquier otro tipo de API web. 💡
+
+## Seguridad - HTTPS { #security-https }
+
+En el [capítulo anterior sobre HTTPS](https.md) aprendimos sobre cómo HTTPS proporciona cifrado para tu API.
+
+También vimos que HTTPS es normalmente proporcionado por un componente **externo** a tu servidor de aplicaciones, un **Proxy de Terminación TLS**.
+
+Y debe haber algo encargado de **renovar los certificados HTTPS**, podría ser el mismo componente o algo diferente.
+
+### Herramientas de Ejemplo para HTTPS { #example-tools-for-https }
+
+Algunas de las herramientas que podrías usar como Proxy de Terminación TLS son:
+
+* Traefik
+ * Maneja automáticamente las renovaciones de certificados ✨
+* Caddy
+ * Maneja automáticamente las renovaciones de certificados ✨
+* Nginx
+ * Con un componente externo como Certbot para las renovaciones de certificados
+* HAProxy
+ * Con un componente externo como Certbot para las renovaciones de certificados
+* Kubernetes con un Controlador de Ingress como Nginx
+ * Con un componente externo como cert-manager para las renovaciones de certificados
+* Manejado internamente por un proveedor de nube como parte de sus servicios (lee abajo 👇)
+
+Otra opción es que podrías usar un **servicio de nube** que haga más del trabajo, incluyendo configurar HTTPS. Podría tener algunas restricciones o cobrarte más, etc. Pero en ese caso, no tendrías que configurar un Proxy de Terminación TLS tú mismo.
+
+Te mostraré algunos ejemplos concretos en los próximos capítulos.
+
+---
+
+Luego, los siguientes conceptos a considerar son todos acerca del programa que ejecuta tu API real (por ejemplo, Uvicorn).
+
+## Programa y Proceso { #program-and-process }
+
+Hablaremos mucho sobre el "**proceso**" en ejecución, así que es útil tener claridad sobre lo que significa y cuál es la diferencia con la palabra "**programa**".
+
+### Qué es un Programa { #what-is-a-program }
+
+La palabra **programa** se usa comúnmente para describir muchas cosas:
+
+* El **código** que escribes, los **archivos Python**.
+* El **archivo** que puede ser **ejecutado** por el sistema operativo, por ejemplo: `python`, `python.exe` o `uvicorn`.
+* Un programa específico mientras está siendo **ejecutado** en el sistema operativo, usando la CPU y almacenando cosas en la memoria. Esto también se llama **proceso**.
+
+### Qué es un Proceso { #what-is-a-process }
+
+La palabra **proceso** se usa normalmente de una manera más específica, refiriéndose solo a lo que está ejecutándose en el sistema operativo (como en el último punto anterior):
+
+* Un programa específico mientras está siendo **ejecutado** en el sistema operativo.
+ * Esto no se refiere al archivo, ni al código, se refiere **específicamente** a lo que está siendo **ejecutado** y gestionado por el sistema operativo.
+* Cualquier programa, cualquier código, **solo puede hacer cosas** cuando está siendo **ejecutado**. Así que, cuando hay un **proceso en ejecución**.
+* El proceso puede ser **terminado** (o "matado") por ti, o por el sistema operativo. En ese punto, deja de ejecutarse/ser ejecutado, y ya no puede **hacer cosas**.
+* Cada aplicación que tienes en ejecución en tu computadora tiene algún proceso detrás, cada programa en ejecución, cada ventana, etc. Y normalmente hay muchos procesos ejecutándose **al mismo tiempo** mientras una computadora está encendida.
+* Puede haber **múltiples procesos** del **mismo programa** ejecutándose al mismo tiempo.
+
+Si revisas el "administrador de tareas" o "monitor del sistema" (o herramientas similares) en tu sistema operativo, podrás ver muchos de esos procesos en ejecución.
+
+Y, por ejemplo, probablemente verás que hay múltiples procesos ejecutando el mismo programa del navegador (Firefox, Chrome, Edge, etc.). Normalmente ejecutan un proceso por pestaña, además de algunos otros procesos extra.
+
+
+
+---
+
+Ahora que conocemos la diferencia entre los términos **proceso** y **programa**, sigamos hablando sobre implementaciones.
+
+## Ejecución al Iniciar { #running-on-startup }
+
+En la mayoría de los casos, cuando creas una API web, quieres que esté **siempre en ejecución**, ininterrumpida, para que tus clientes puedan acceder a ella en cualquier momento. Esto, por supuesto, a menos que tengas una razón específica para que se ejecute solo en ciertas situaciones, pero la mayoría de las veces quieres que esté constantemente en ejecución y **disponible**.
+
+### En un Servidor Remoto { #in-a-remote-server }
+
+Cuando configuras un servidor remoto (un servidor en la nube, una máquina virtual, etc.) lo más sencillo que puedes hacer es usar `fastapi run` (que utiliza Uvicorn) o algo similar, manualmente, de la misma manera que lo haces al desarrollar localmente.
+
+Y funcionará y será útil **durante el desarrollo**.
+
+Pero si pierdes la conexión con el servidor, el **proceso en ejecución** probablemente morirá.
+
+Y si el servidor se reinicia (por ejemplo, después de actualizaciones o migraciones del proveedor de la nube) probablemente **no lo notarás**. Y debido a eso, ni siquiera sabrás que tienes que reiniciar el proceso manualmente. Así, tu API simplemente quedará muerta. 😱
+
+### Ejecutar Automáticamente al Iniciar { #run-automatically-on-startup }
+
+En general, probablemente querrás que el programa del servidor (por ejemplo, Uvicorn) se inicie automáticamente al arrancar el servidor, y sin necesidad de ninguna **intervención humana**, para tener siempre un proceso en ejecución con tu API (por ejemplo, Uvicorn ejecutando tu aplicación FastAPI).
+
+### Programa Separado { #separate-program }
+
+Para lograr esto, normalmente tendrás un **programa separado** que se asegurará de que tu aplicación se ejecute al iniciarse. Y en muchos casos, también se asegurará de que otros componentes o aplicaciones se ejecuten, por ejemplo, una base de datos.
+
+### Herramientas de Ejemplo para Ejecutar al Iniciar { #example-tools-to-run-at-startup }
+
+Algunos ejemplos de las herramientas que pueden hacer este trabajo son:
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Docker en Modo Swarm
+* Systemd
+* Supervisor
+* Manejado internamente por un proveedor de nube como parte de sus servicios
+* Otros...
+
+Te daré más ejemplos concretos en los próximos capítulos.
+
+## Reinicios { #restarts }
+
+De manera similar a asegurarte de que tu aplicación se ejecute al iniciar, probablemente también quieras asegurarte de que se **reinicie** después de fallos.
+
+### Cometemos Errores { #we-make-mistakes }
+
+Nosotros, como humanos, cometemos **errores**, todo el tiempo. El software casi *siempre* tiene **bugs** ocultos en diferentes lugares. 🐛
+
+Y nosotros, como desarrolladores, seguimos mejorando el código a medida que encontramos esos bugs y a medida que implementamos nuevas funcionalidades (posiblemente agregando nuevos bugs también 😅).
+
+### Errores Pequeños Manejados Automáticamente { #small-errors-automatically-handled }
+
+Al construir APIs web con FastAPI, si hay un error en nuestro código, FastAPI normalmente lo contiene al request único que desencadenó el error. 🛡
+
+El cliente obtendrá un **500 Internal Server Error** para ese request, pero la aplicación continuará funcionando para los siguientes requests en lugar de simplemente colapsar por completo.
+
+### Errores Mayores - Colapsos { #bigger-errors-crashes }
+
+Sin embargo, puede haber casos en los que escribamos algún código que **colapse toda la aplicación** haciendo que Uvicorn y Python colapsen. 💥
+
+Y aún así, probablemente no querrías que la aplicación quede muerta porque hubo un error en un lugar, probablemente querrás que **siga ejecutándose** al menos para las *path operations* que no estén rotas.
+
+### Reiniciar Después del Colapso { #restart-after-crash }
+
+Pero en esos casos con errores realmente malos que colapsan el **proceso en ejecución**, querrías un componente externo encargado de **reiniciar** el proceso, al menos un par de veces...
+
+/// tip | Consejo
+
+...Aunque si la aplicación completa **colapsa inmediatamente**, probablemente no tenga sentido seguir reiniciándola eternamente. Pero en esos casos, probablemente lo notarás durante el desarrollo, o al menos justo después de la implementación.
+
+Así que enfoquémonos en los casos principales, donde podría colapsar por completo en algunos casos particulares **en el futuro**, y aún así tenga sentido reiniciarla.
+
+///
+
+Probablemente querrías que la cosa encargada de reiniciar tu aplicación sea un **componente externo**, porque para ese punto, la misma aplicación con Uvicorn y Python ya colapsó, así que no hay nada en el mismo código de la misma aplicación que pueda hacer algo al respecto.
+
+### Herramientas de Ejemplo para Reiniciar Automáticamente { #example-tools-to-restart-automatically }
+
+En la mayoría de los casos, la misma herramienta que se utiliza para **ejecutar el programa al iniciar** también se utiliza para manejar reinicios automáticos.
+
+Por ejemplo, esto podría ser manejado por:
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Docker en Modo Swarm
+* Systemd
+* Supervisor
+* Manejado internamente por un proveedor de nube como parte de sus servicios
+* Otros...
+
+## Replicación - Procesos y Memoria { #replication-processes-and-memory }
+
+Con una aplicación FastAPI, usando un programa servidor como el comando `fastapi` que ejecuta Uvicorn, ejecutarlo una vez en **un proceso** puede servir a múltiples clientes concurrentemente.
+
+Pero en muchos casos, querrás ejecutar varios worker processes al mismo tiempo.
+
+### Múltiples Procesos - Workers { #multiple-processes-workers }
+
+Si tienes más clientes de los que un solo proceso puede manejar (por ejemplo, si la máquina virtual no es muy grande) y tienes **múltiples núcleos** en la CPU del servidor, entonces podrías tener **múltiples procesos** ejecutando la misma aplicación al mismo tiempo, y distribuir todas las requests entre ellos.
+
+Cuando ejecutas **múltiples procesos** del mismo programa de API, comúnmente se les llama **workers**.
+
+### Worker Processes y Puertos { #worker-processes-and-ports }
+
+Recuerda de la documentación [Sobre HTTPS](https.md) que solo un proceso puede estar escuchando en una combinación de puerto y dirección IP en un servidor.
+
+Esto sigue siendo cierto.
+
+Así que, para poder tener **múltiples procesos** al mismo tiempo, tiene que haber un **solo proceso escuchando en un puerto** que luego transmita la comunicación a cada worker process de alguna forma.
+
+### Memoria por Proceso { #memory-per-process }
+
+Ahora, cuando el programa carga cosas en memoria, por ejemplo, un modelo de Machine Learning en una variable, o el contenido de un archivo grande en una variable, todo eso **consume un poco de la memoria (RAM)** del servidor.
+
+Y múltiples procesos normalmente **no comparten ninguna memoria**. Esto significa que cada proceso en ejecución tiene sus propias cosas, variables y memoria. Y si estás consumiendo una gran cantidad de memoria en tu código, **cada proceso** consumirá una cantidad equivalente de memoria.
+
+### Memoria del Servidor { #server-memory }
+
+Por ejemplo, si tu código carga un modelo de Machine Learning con **1 GB de tamaño**, cuando ejecutas un proceso con tu API, consumirá al menos 1 GB de RAM. Y si inicias **4 procesos** (4 workers), cada uno consumirá 1 GB de RAM. Así que, en total, tu API consumirá **4 GB de RAM**.
+
+Y si tu servidor remoto o máquina virtual solo tiene 3 GB de RAM, intentar cargar más de 4 GB de RAM causará problemas. 🚨
+
+### Múltiples Procesos - Un Ejemplo { #multiple-processes-an-example }
+
+En este ejemplo, hay un **Proceso Administrador** que inicia y controla dos **Worker Processes**.
+
+Este Proceso Administrador probablemente sería el que escuche en el **puerto** en la IP. Y transmitirá toda la comunicación a los worker processes.
+
+Esos worker processes serían los que ejecutan tu aplicación, realizarían los cálculos principales para recibir un **request** y devolver un **response**, y cargarían cualquier cosa que pongas en variables en RAM.
+
++ +**FastAPI** no existiría si no fuera por el trabajo previo de otros. + +Ha habido muchas herramientas creadas antes que han ayudado a inspirar su creación. + +He estado evitando la creación de un nuevo framework durante varios años. Primero traté de resolver todas las funcionalidades cubiertas por **FastAPI** usando varios frameworks, plug-ins y herramientas diferentes. + +Pero en algún momento, no había otra opción que crear algo que proporcionara todas estas funcionalidades, tomando las mejores ideas de herramientas anteriores y combinándolas de la mejor manera posible, usando funcionalidades del lenguaje que ni siquiera estaban disponibles antes (anotaciones de tipos de Python 3.6+). + ++ +## Investigación { #investigation } + +Al usar todas las alternativas anteriores, tuve la oportunidad de aprender de todas ellas, tomar ideas y combinarlas de la mejor manera que pude encontrar para mí y los equipos de desarrolladores con los que he trabajado. + +Por ejemplo, estaba claro que idealmente debería estar basado en las anotaciones de tipos estándar de Python. + +También, el mejor enfoque era usar estándares ya existentes. + +Entonces, antes de siquiera empezar a programar **FastAPI**, pasé varios meses estudiando las especificaciones de OpenAPI, JSON Schema, OAuth2, etc. Entendiendo su relación, superposición y diferencias. + +## Diseño { #design } + +Luego pasé algún tiempo diseñando la "API" de desarrollador que quería tener como usuario (como desarrollador usando FastAPI). + +Probé varias ideas en los editores de Python más populares: PyCharm, VS Code, editores basados en Jedi. + +Según la última [Encuesta de Desarrolladores de Python](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools), estos editores cubren alrededor del 80% de los usuarios. + +Esto significa que **FastAPI** fue específicamente probado con los editores usados por el 80% de los desarrolladores de Python. Y como la mayoría de los otros editores tienden a funcionar de manera similar, todos sus beneficios deberían funcionar prácticamente para todos los editores. + +De esa manera, pude encontrar las mejores maneras de reducir la duplicación de código tanto como fuera posible, para tener autocompletado en todas partes, chequeos de tipos y errores, etc. + +Todo de una manera que proporcionara la mejor experiencia de desarrollo para todos los desarrolladores. + +## Requisitos { #requirements } + +Después de probar varias alternativas, decidí que iba a usar [**Pydantic**](https://docs.pydantic.dev/) por sus ventajas. + +Luego contribuí a este, para hacerlo totalmente compatible con JSON Schema, para soportar diferentes maneras de definir declaraciones de restricciones, y para mejorar el soporte de los editores (chequeo de tipos, autocompletado) basado en las pruebas en varios editores. + +Durante el desarrollo, también contribuí a [**Starlette**](https://www.starlette.dev/), el otro requisito clave. + +## Desarrollo { #development } + +Para cuando comencé a crear el propio **FastAPI**, la mayoría de las piezas ya estaban en su lugar, el diseño estaba definido, los requisitos y herramientas estaban listos, y el conocimiento sobre los estándares y especificaciones estaba claro y fresco. + +## Futuro { #future } + +A este punto, ya está claro que **FastAPI** con sus ideas está siendo útil para muchas personas. + +Está siendo elegido sobre alternativas anteriores por adaptarse mejor a muchos casos de uso. + +Muchos desarrolladores y equipos ya dependen de **FastAPI** para sus proyectos (incluyéndome a mí y a mi equipo). + +Pero aún así, hay muchas mejoras y funcionalidades por venir. + +**FastAPI** tiene un gran futuro por delante. + +Y [tu ayuda](help-fastapi.md) es muy apreciada. diff --git a/docs/es/docs/how-to/authentication-error-status-code.md b/docs/es/docs/how-to/authentication-error-status-code.md new file mode 100644 index 0000000000000..600c30d2635f4 --- /dev/null +++ b/docs/es/docs/how-to/authentication-error-status-code.md @@ -0,0 +1,17 @@ +# Usar los códigos de estado antiguos 403 para errores de autenticación { #use-old-403-authentication-error-status-codes } + +Antes de FastAPI versión `0.122.0`, cuando las utilidades de seguridad integradas devolvían un error al cliente después de una autenticación fallida, usaban el código de estado HTTP `403 Forbidden`. + +A partir de FastAPI versión `0.122.0`, usan el código de estado HTTP `401 Unauthorized`, más apropiado, y devuelven un `WWW-Authenticate` header adecuado en la response, siguiendo las especificaciones HTTP, [RFC 7235](https://datatracker.ietf.org/doc/html/rfc7235#section-3.1), [RFC 9110](https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized). + +Pero si por alguna razón tus clientes dependen del comportamiento anterior, puedes volver a él sobrescribiendo el método `make_not_authenticated_error` en tus clases de seguridad. + +Por ejemplo, puedes crear una subclase de `HTTPBearer` que devuelva un error `403 Forbidden` en lugar del `401 Unauthorized` por defecto: + +{* ../../docs_src/authentication_error_status_code/tutorial001_an_py310.py hl[9:13] *} + +/// tip | Consejo + +Ten en cuenta que la función devuelve la instance de la excepción, no la lanza. El lanzamiento se hace en el resto del código interno. + +/// diff --git a/docs/es/docs/how-to/conditional-openapi.md b/docs/es/docs/how-to/conditional-openapi.md new file mode 100644 index 0000000000000..cdf569805069b --- /dev/null +++ b/docs/es/docs/how-to/conditional-openapi.md @@ -0,0 +1,56 @@ +# OpenAPI condicional { #conditional-openapi } + +Si lo necesitaras, podrías usar configuraciones y variables de entorno para configurar OpenAPI condicionalmente según el entorno, e incluso desactivarlo por completo. + +## Sobre seguridad, APIs y documentación { #about-security-apis-and-docs } + +Ocultar las interfaces de usuario de la documentación en producción *no debería* ser la forma de proteger tu API. + +Eso no añade ninguna seguridad extra a tu API, las *path operations* seguirán estando disponibles donde están. + +Si hay una falla de seguridad en tu código, seguirá existiendo. + +Ocultar la documentación solo hace que sea más difícil entender cómo interactuar con tu API y podría dificultar más depurarla en producción. Podría considerarse simplemente una forma de [Seguridad mediante oscuridad](https://en.wikipedia.org/wiki/Security_through_obscurity). + +Si quieres asegurar tu API, hay varias cosas mejores que puedes hacer, por ejemplo: + +* Asegúrate de tener modelos Pydantic bien definidos para tus request bodies y responses. +* Configura los permisos y roles necesarios usando dependencias. +* Nunca guardes contraseñas en texto plano, solo hashes de contraseñas. +* Implementa y utiliza herramientas criptográficas bien conocidas, como pwdlib y JWT tokens, etc. +* Añade controles de permisos más detallados con Scopes de OAuth2 donde sea necesario. +* ...etc. + +No obstante, podrías tener un caso de uso muy específico donde realmente necesites desactivar la documentación de la API para algún entorno (por ejemplo, para producción) o dependiendo de configuraciones de variables de entorno. + +## OpenAPI condicional desde configuraciones y variables de entorno { #conditional-openapi-from-settings-and-env-vars } + +Puedes usar fácilmente las mismas configuraciones de Pydantic para configurar tu OpenAPI generado y las interfaces de usuario de la documentación. + +Por ejemplo: + +{* ../../docs_src/conditional_openapi/tutorial001_py310.py hl[6,11] *} + +Aquí declaramos la configuración `openapi_url` con el mismo valor por defecto de `"/openapi.json"`. + +Y luego la usamos al crear la app de `FastAPI`. + +Entonces podrías desactivar OpenAPI (incluyendo las UI de documentación) configurando la variable de entorno `OPENAPI_URL` a una string vacía, así: + +
+
+Pero puedes desactivarlo estableciendo `syntaxHighlight` en `False`:
+
+{* ../../docs_src/configure_swagger_ui/tutorial001_py310.py hl[3] *}
+
+...y entonces Swagger UI ya no mostrará el resaltado de sintaxis:
+
+
+
+## Cambiar el tema { #change-the-theme }
+
+De la misma manera, podrías configurar el tema del resaltado de sintaxis con la clave `"syntaxHighlight.theme"` (ten en cuenta que tiene un punto en el medio):
+
+{* ../../docs_src/configure_swagger_ui/tutorial002_py310.py hl[3] *}
+
+Esa configuración cambiaría el tema de color del resaltado de sintaxis:
+
+
+
+## Cambiar los parámetros por defecto de Swagger UI { #change-default-swagger-ui-parameters }
+
+FastAPI incluye algunos parámetros de configuración por defecto apropiados para la mayoría de los casos de uso.
+
+Incluye estas configuraciones por defecto:
+
+{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}
+
+Puedes sobrescribir cualquiera de ellos estableciendo un valor diferente en el argumento `swagger_ui_parameters`.
+
+Por ejemplo, para desactivar `deepLinking` podrías pasar estas configuraciones a `swagger_ui_parameters`:
+
+{* ../../docs_src/configure_swagger_ui/tutorial003_py310.py hl[3] *}
+
+## Otros parámetros de Swagger UI { #other-swagger-ui-parameters }
+
+Para ver todas las demás configuraciones posibles que puedes usar, lee la [documentación oficial de los parámetros de Swagger UI](https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/).
+
+## Configuraciones solo de JavaScript { #javascript-only-settings }
+
+Swagger UI también permite otras configuraciones que son objetos **solo de JavaScript** (por ejemplo, funciones de JavaScript).
+
+FastAPI también incluye estas configuraciones `presets` solo de JavaScript:
+
+```JavaScript
+presets: [
+ SwaggerUIBundle.presets.apis,
+ SwaggerUIBundle.SwaggerUIStandalonePreset
+]
+```
+
+Estos son objetos de **JavaScript**, no strings, por lo que no puedes pasarlos directamente desde código de Python.
+
+Si necesitas usar configuraciones solo de JavaScript como esas, puedes usar uno de los métodos anteriores. Sobrescribe toda la *path operation* de Swagger UI y escribe manualmente cualquier JavaScript que necesites.
diff --git a/docs/es/docs/how-to/custom-docs-ui-assets.md b/docs/es/docs/how-to/custom-docs-ui-assets.md
new file mode 100644
index 0000000000000..e9a34c5e4d13e
--- /dev/null
+++ b/docs/es/docs/how-to/custom-docs-ui-assets.md
@@ -0,0 +1,185 @@
+# Recursos Estáticos Personalizados para la Docs UI (self hosting) { #custom-docs-ui-static-assets-self-hosting }
+
+La documentación de la API utiliza **Swagger UI** y **ReDoc**, y cada uno de estos necesita algunos archivos JavaScript y CSS.
+
+Por defecto, esos archivos se sirven desde un CDN.
+
+Pero es posible personalizarlo, puedes establecer un CDN específico, o servir los archivos tú mismo.
+
+## CDN Personalizado para JavaScript y CSS { #custom-cdn-for-javascript-and-css }
+
+Digamos que quieres usar un CDN diferente, por ejemplo, quieres usar `https://unpkg.com/`.
+
+Esto podría ser útil si, por ejemplo, vives en un país que restringe algunas URLs.
+
+### Desactiva la documentación automática { #disable-the-automatic-docs }
+
+El primer paso es desactivar la documentación automática, ya que por defecto, esos usan el CDN por defecto.
+
+Para desactivarlos, establece sus URLs en `None` cuando crees tu aplicación de `FastAPI`:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[8] *}
+
+### Incluye la documentación personalizada { #include-the-custom-docs }
+
+Ahora puedes crear las *path operations* para la documentación personalizada.
+
+Puedes reutilizar las funciones internas de FastAPI para crear las páginas HTML para la documentación, y pasarles los argumentos necesarios:
+
+* `openapi_url`: la URL donde la página HTML para la documentación puede obtener el OpenAPI esquema de tu API. Puedes usar aquí el atributo `app.openapi_url`.
+* `title`: el título de tu API.
+* `oauth2_redirect_url`: puedes usar `app.swagger_ui_oauth2_redirect_url` aquí para usar el valor por defecto.
+* `swagger_js_url`: la URL donde el HTML para tu documentación de Swagger UI puede obtener el archivo **JavaScript**. Esta es la URL personalizada del CDN.
+* `swagger_css_url`: la URL donde el HTML para tu documentación de Swagger UI puede obtener el archivo **CSS**. Esta es la URL personalizada del CDN.
+
+Y de manera similar para ReDoc...
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[2:6,11:19,22:24,27:33] *}
+
+/// tip | Consejo
+
+La *path operation* para `swagger_ui_redirect` es una herramienta cuando utilizas OAuth2.
+
+Si integras tu API con un proveedor OAuth2, podrás autenticarte y regresar a la documentación de la API con las credenciales adquiridas. E interactuar con ella usando la autenticación real de OAuth2.
+
+Swagger UI lo manejará detrás de escena para ti, pero necesita este auxiliar de "redirección".
+
+///
+
+### Crea una *path operation* para probarlo { #create-a-path-operation-to-test-it }
+
+Ahora, para poder probar que todo funciona, crea una *path operation*:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[36:38] *}
+
+### Pruébalo { #test-it }
+
+Ahora, deberías poder ir a tu documentación en [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs), y recargar la página, cargará esos recursos desde el nuevo CDN.
+
+## self hosting de JavaScript y CSS para la documentación { #self-hosting-javascript-and-css-for-docs }
+
+El self hosting de JavaScript y CSS podría ser útil si, por ejemplo, necesitas que tu aplicación siga funcionando incluso offline, sin acceso a Internet, o en una red local.
+
+Aquí verás cómo servir esos archivos tú mismo, en la misma aplicación de FastAPI, y configurar la documentación para usarla.
+
+### Estructura de archivos del proyecto { #project-file-structure }
+
+Supongamos que la estructura de archivos de tu proyecto se ve así:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+```
+
+Ahora crea un directorio para almacenar esos archivos estáticos.
+
+Tu nueva estructura de archivos podría verse así:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static/
+```
+
+### Descarga los archivos { #download-the-files }
+
+Descarga los archivos estáticos necesarios para la documentación y ponlos en ese directorio `static/`.
+
+Probablemente puedas hacer clic derecho en cada enlace y seleccionar una opción similar a `Guardar enlace como...`.
+
+**Swagger UI** utiliza los archivos:
+
+* [`swagger-ui-bundle.js`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js)
+* [`swagger-ui.css`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css)
+
+Y **ReDoc** utiliza el archivo:
+
+* [`redoc.standalone.js`](https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js)
+
+Después de eso, tu estructura de archivos podría verse así:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static
+ ├── redoc.standalone.js
+ ├── swagger-ui-bundle.js
+ └── swagger-ui.css
+```
+
+### Sirve los archivos estáticos { #serve-the-static-files }
+
+* Importa `StaticFiles`.
+* "Monta" una instance de `StaticFiles()` en un path específico.
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[7,11] *}
+
+### Prueba los archivos estáticos { #test-the-static-files }
+
+Inicia tu aplicación y ve a [http://127.0.0.1:8000/static/redoc.standalone.js](http://127.0.0.1:8000/static/redoc.standalone.js).
+
+Deberías ver un archivo JavaScript muy largo de **ReDoc**.
+
+Podría comenzar con algo como:
+
+```JavaScript
+/*! For license information please see redoc.standalone.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")):
+...
+```
+
+Eso confirma que puedes servir archivos estáticos desde tu aplicación, y que colocaste los archivos estáticos para la documentación en el lugar correcto.
+
+Ahora podemos configurar la aplicación para usar esos archivos estáticos para la documentación.
+
+### Desactiva la documentación automática para archivos estáticos { #disable-the-automatic-docs-for-static-files }
+
+Igual que cuando usas un CDN personalizado, el primer paso es desactivar la documentación automática, ya que esos usan el CDN por defecto.
+
+Para desactivarlos, establece sus URLs en `None` cuando crees tu aplicación de `FastAPI`:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[9] *}
+
+### Incluye la documentación personalizada para archivos estáticos { #include-the-custom-docs-for-static-files }
+
+Y de la misma manera que con un CDN personalizado, ahora puedes crear las *path operations* para la documentación personalizada.
+
+Nuevamente, puedes reutilizar las funciones internas de FastAPI para crear las páginas HTML para la documentación, y pasarles los argumentos necesarios:
+
+* `openapi_url`: la URL donde la página HTML para la documentación puede obtener el OpenAPI esquema de tu API. Puedes usar aquí el atributo `app.openapi_url`.
+* `title`: el título de tu API.
+* `oauth2_redirect_url`: puedes usar `app.swagger_ui_oauth2_redirect_url` aquí para usar el valor por defecto.
+* `swagger_js_url`: la URL donde el HTML para tu documentación de Swagger UI puede obtener el archivo **JavaScript**. **Este es el que tu propia aplicación está sirviendo ahora**.
+* `swagger_css_url`: la URL donde el HTML para tu documentación de Swagger UI puede obtener el archivo **CSS**. **Este es el que tu propia aplicación está sirviendo ahora**.
+
+Y de manera similar para ReDoc...
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[2:6,14:22,25:27,30:36] *}
+
+/// tip | Consejo
+
+La *path operation* para `swagger_ui_redirect` es una herramienta cuando utilizas OAuth2.
+
+Si integras tu API con un proveedor OAuth2, podrás autenticarte y regresar a la documentación de la API con las credenciales adquiridas. Y interactuar con ella usando la autenticación real de OAuth2.
+
+Swagger UI lo manejará detrás de escena para ti, pero necesita este auxiliar de "redirección".
+
+///
+
+### Crea una *path operation* para probar archivos estáticos { #create-a-path-operation-to-test-static-files }
+
+Ahora, para poder probar que todo funciona, crea una *path operation*:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[39:41] *}
+
+### Prueba la UI de Archivos Estáticos { #test-static-files-ui }
+
+Ahora, deberías poder desconectar tu WiFi, ir a tu documentación en [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs), y recargar la página.
+
+E incluso sin Internet, podrás ver la documentación de tu API e interactuar con ella.
diff --git a/docs/es/docs/how-to/custom-request-and-route.md b/docs/es/docs/how-to/custom-request-and-route.md
new file mode 100644
index 0000000000000..56013a5c7b156
--- /dev/null
+++ b/docs/es/docs/how-to/custom-request-and-route.md
@@ -0,0 +1,109 @@
+# Clase personalizada de Request y APIRoute { #custom-request-and-apiroute-class }
+
+En algunos casos, puede que quieras sobrescribir la lógica utilizada por las clases `Request` y `APIRoute`.
+
+En particular, esta puede ser una buena alternativa a la lógica en un middleware.
+
+Por ejemplo, si quieres leer o manipular el request body antes de que sea procesado por tu aplicación.
+
+/// danger | Advertencia
+
+Esta es una funcionalidad "avanzada".
+
+Si apenas estás comenzando con **FastAPI**, quizás quieras saltar esta sección.
+
+///
+
+## Casos de uso { #use-cases }
+
+Algunos casos de uso incluyen:
+
+* Convertir cuerpos de requests no-JSON a JSON (por ejemplo, [`msgpack`](https://msgpack.org/index.html)).
+* Descomprimir cuerpos de requests comprimidos con gzip.
+* Registrar automáticamente todos los request bodies.
+
+## Manejo de codificaciones personalizadas de request body { #handling-custom-request-body-encodings }
+
+Veamos cómo hacer uso de una subclase personalizada de `Request` para descomprimir requests gzip.
+
+Y una subclase de `APIRoute` para usar esa clase de request personalizada.
+
+### Crear una clase personalizada `GzipRequest` { #create-a-custom-gziprequest-class }
+
+/// tip | Consejo
+
+Este es un ejemplo sencillo para demostrar cómo funciona. Si necesitas soporte para Gzip, puedes usar el [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware) proporcionado.
+
+///
+
+Primero, creamos una clase `GzipRequest`, que sobrescribirá el método `Request.body()` para descomprimir el request body si hay un header apropiado.
+
+Si no hay `gzip` en el header, no intentará descomprimir el request body.
+
+De esa manera, la misma clase de ruta puede manejar requests comprimidos con gzip o no comprimidos.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[9:16] *}
+
+### Crear una clase personalizada `GzipRoute` { #create-a-custom-gziproute-class }
+
+A continuación, creamos una subclase personalizada de `fastapi.routing.APIRoute` que hará uso de `GzipRequest`.
+
+Esta vez, sobrescribirá el método `APIRoute.get_route_handler()`.
+
+Este método devuelve una función. Y esa función es la que recibirá un request y devolverá un response.
+
+Aquí lo usamos para crear un `GzipRequest` a partir del request original.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[19:27] *}
+
+/// note | Detalles técnicos
+
+Un `Request` tiene un atributo `request.scope`, que es simplemente un `dict` de Python que contiene los metadatos relacionados con el request.
+
+Un `Request` también tiene un `request.receive`, que es una función para "recibir" el request body.
+
+El `dict` `scope` y la función `receive` son ambos parte de la especificación ASGI.
+
+Y esas dos cosas, `scope` y `receive`, son lo que se necesita para crear una nueva *Request instance*.
+
+Para aprender más sobre el `Request`, revisa [la documentación de Starlette sobre Requests](https://www.starlette.dev/requests/).
+
+///
+
+La única cosa que la función devuelta por `GzipRequest.get_route_handler` hace diferente es convertir el `Request` en un `GzipRequest`.
+
+Haciendo esto, nuestro `GzipRequest` se encargará de descomprimir los datos (si es necesario) antes de pasarlos a nuestras *path operations*.
+
+Después de eso, toda la lógica de procesamiento es la misma.
+
+Pero debido a nuestros cambios en `GzipRequest.body`, el request body se descomprimirá automáticamente cuando sea cargado por **FastAPI** si es necesario.
+
+## Accediendo al request body en un manejador de excepciones { #accessing-the-request-body-in-an-exception-handler }
+
+/// tip | Consejo
+
+Para resolver este mismo problema, probablemente sea mucho más fácil usar el `body` en un manejador personalizado para `RequestValidationError` ([Manejo de Errores](../tutorial/handling-errors.md#use-the-requestvalidationerror-body)).
+
+Pero este ejemplo sigue siendo válido y muestra cómo interactuar con los componentes internos.
+
+///
+
+También podemos usar este mismo enfoque para acceder al request body en un manejador de excepciones.
+
+Todo lo que necesitamos hacer es manejar el request dentro de un bloque `try`/`except`:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[14,16] *}
+
+Si ocurre una excepción, la `Request instance` aún estará en el alcance, así que podemos leer y hacer uso del request body cuando manejamos el error:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[17:19] *}
+
+## Clase personalizada `APIRoute` en un router { #custom-apiroute-class-in-a-router }
+
+También puedes establecer el parámetro `route_class` de un `APIRouter`:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[26] *}
+
+En este ejemplo, las *path operations* bajo el `router` usarán la clase personalizada `TimedRoute`, y tendrán un header `X-Response-Time` extra en el response con el tiempo que tomó generar el response:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[13:20] *}
diff --git a/docs/es/docs/how-to/extending-openapi.md b/docs/es/docs/how-to/extending-openapi.md
new file mode 100644
index 0000000000000..d00455afd7920
--- /dev/null
+++ b/docs/es/docs/how-to/extending-openapi.md
@@ -0,0 +1,80 @@
+# Extender OpenAPI { #extending-openapi }
+
+Hay algunos casos en los que podrías necesitar modificar el esquema de OpenAPI generado.
+
+En esta sección verás cómo hacerlo.
+
+## El proceso normal { #the-normal-process }
+
+El proceso normal (por defecto) es el siguiente.
+
+Una aplicación (instance) de `FastAPI` tiene un método `.openapi()` que se espera que devuelva el esquema de OpenAPI.
+
+Como parte de la creación del objeto de la aplicación, se registra una *path operation* para `/openapi.json` (o para lo que sea que configures tu `openapi_url`).
+
+Simplemente devuelve un response JSON con el resultado del método `.openapi()` de la aplicación.
+
+Por defecto, lo que hace el método `.openapi()` es revisar la propiedad `.openapi_schema` para ver si tiene contenido y devolverlo.
+
+Si no lo tiene, lo genera usando la función de utilidad en `fastapi.openapi.utils.get_openapi`.
+
+Y esa función `get_openapi()` recibe como parámetros:
+
+* `title`: El título de OpenAPI, mostrado en la documentación.
+* `version`: La versión de tu API, por ejemplo `2.5.0`.
+* `openapi_version`: La versión de la especificación OpenAPI utilizada. Por defecto, la más reciente: `3.1.0`.
+* `summary`: Un breve resumen de la API.
+* `description`: La descripción de tu API, esta puede incluir markdown y se mostrará en la documentación.
+* `routes`: Una list de rutas, estas son cada una de las *path operations* registradas. Se toman de `app.routes`.
+
+/// info | Información
+
+El parámetro `summary` está disponible en OpenAPI 3.1.0 y versiones superiores, soportado por FastAPI 0.99.0 y superiores.
+
+///
+
+## Sobrescribir los valores por defecto { #overriding-the-defaults }
+
+Usando la información anterior, puedes usar la misma función de utilidad para generar el esquema de OpenAPI y sobrescribir cada parte que necesites.
+
+Por ejemplo, vamos a añadir [la extensión OpenAPI de ReDoc para incluir un logo personalizado](https://github.com/Rebilly/ReDoc/blob/master/docs/redoc-vendor-extensions.md#x-logo).
+
+### **FastAPI** normal { #normal-fastapi }
+
+Primero, escribe toda tu aplicación **FastAPI** como normalmente:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[1,4,7:9] *}
+
+### Generar el esquema de OpenAPI { #generate-the-openapi-schema }
+
+Luego, usa la misma función de utilidad para generar el esquema de OpenAPI, dentro de una función `custom_openapi()`:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[2,15:21] *}
+
+### Modificar el esquema de OpenAPI { #modify-the-openapi-schema }
+
+Ahora puedes añadir la extensión de ReDoc, agregando un `x-logo` personalizado al "objeto" `info` en el esquema de OpenAPI:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[22:24] *}
+
+### Cachear el esquema de OpenAPI { #cache-the-openapi-schema }
+
+Puedes usar la propiedad `.openapi_schema` como un "cache", para almacenar tu esquema generado.
+
+De esa forma, tu aplicación no tendrá que generar el esquema cada vez que un usuario abra la documentación de tu API.
+
+Se generará solo una vez, y luego se usará el mismo esquema cacheado para las siguientes requests.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[13:14,25:26] *}
+
+### Sobrescribir el método { #override-the-method }
+
+Ahora puedes reemplazar el método `.openapi()` por tu nueva función.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[29] *}
+
+### Revisa { #check-it }
+
+Una vez que vayas a [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) verás que estás usando tu logo personalizado (en este ejemplo, el logo de **FastAPI**):
+
+
diff --git a/docs/es/docs/how-to/general.md b/docs/es/docs/how-to/general.md
new file mode 100644
index 0000000000000..03fe8441e4ff3
--- /dev/null
+++ b/docs/es/docs/how-to/general.md
@@ -0,0 +1,43 @@
+# General - Cómo Hacer - Recetas { #general-how-to-recipes }
+
+Aquí tienes varias indicaciones hacia otros lugares en la documentación, para preguntas generales o frecuentes.
+
+## Filtrar Datos - Seguridad { #filter-data-security }
+
+Para asegurarte de que no devuelves más datos de los que deberías, lee la documentación para [Tutorial - Modelo de Response - Tipo de Retorno](../tutorial/response-model.md).
+
+## Optimizar el Rendimiento del Response - Modelo de Response - Tipo de Retorno { #optimize-response-performance-response-model-return-type }
+
+Para optimizar el rendimiento al devolver datos JSON, usa un tipo de retorno o un modelo de Response; de esa manera Pydantic se encargará de la serialización a JSON del lado de Rust, sin pasar por Python. Lee más en la documentación para [Tutorial - Modelo de Response - Tipo de Retorno](../tutorial/response-model.md).
+
+## Etiquetas de Documentación - OpenAPI { #documentation-tags-openapi }
+
+Para agregar etiquetas a tus *path operations*, y agruparlas en la interfaz de usuario de la documentación, lee la documentación para [Tutorial - Configuraciones de Path Operation - Etiquetas](../tutorial/path-operation-configuration.md#tags).
+
+## Resumen y Descripción de Documentación - OpenAPI { #documentation-summary-and-description-openapi }
+
+Para agregar un resumen y descripción a tus *path operations*, y mostrarlos en la interfaz de usuario de la documentación, lee la documentación para [Tutorial - Configuraciones de Path Operation - Resumen y Descripción](../tutorial/path-operation-configuration.md#summary-and-description).
+
+## Documentación de Descripción de Response - OpenAPI { #documentation-response-description-openapi }
+
+Para definir la descripción del response, mostrada en la interfaz de usuario de la documentación, lee la documentación para [Tutorial - Configuraciones de Path Operation - Descripción del Response](../tutorial/path-operation-configuration.md#response-description).
+
+## Documentar la Deprecación de una *Path Operation* - OpenAPI { #documentation-deprecate-a-path-operation-openapi }
+
+Para deprecar una *path operation*, y mostrarla en la interfaz de usuario de la documentación, lee la documentación para [Tutorial - Configuraciones de Path Operation - Deprecación](../tutorial/path-operation-configuration.md#deprecate-a-path-operation).
+
+## Convertir cualquier Dato a Compatible con JSON { #convert-any-data-to-json-compatible }
+
+Para convertir cualquier dato a compatible con JSON, lee la documentación para [Tutorial - Codificador Compatible con JSON](../tutorial/encoder.md).
+
+## Metadatos OpenAPI - Documentación { #openapi-metadata-docs }
+
+Para agregar metadatos a tu esquema de OpenAPI, incluyendo una licencia, versión, contacto, etc, lee la documentación para [Tutorial - Metadatos y URLs de Documentación](../tutorial/metadata.md).
+
+## URL Personalizada de OpenAPI { #openapi-custom-url }
+
+Para personalizar la URL de OpenAPI (o eliminarla), lee la documentación para [Tutorial - Metadatos y URLs de Documentación](../tutorial/metadata.md#openapi-url).
+
+## URLs de Documentación de OpenAPI { #openapi-docs-urls }
+
+Para actualizar las URLs usadas para las interfaces de usuario de documentación generadas automáticamente, lee la documentación para [Tutorial - Metadatos y URLs de Documentación](../tutorial/metadata.md#docs-urls).
diff --git a/docs/es/docs/how-to/graphql.md b/docs/es/docs/how-to/graphql.md
new file mode 100644
index 0000000000000..11c0cc23c5a26
--- /dev/null
+++ b/docs/es/docs/how-to/graphql.md
@@ -0,0 +1,60 @@
+# GraphQL { #graphql }
+
+Como **FastAPI** se basa en el estándar **ASGI**, es muy fácil integrar cualquier paquete de **GraphQL** que también sea compatible con ASGI.
+
+Puedes combinar las *path operations* normales de FastAPI con GraphQL en la misma aplicación.
+
+/// tip | Consejo
+
+**GraphQL** resuelve algunos casos de uso muy específicos.
+
+Tiene **ventajas** y **desventajas** en comparación con las **APIs web** comunes.
+
+Asegúrate de evaluar si los **beneficios** para tu caso de uso compensan los **inconvenientes**. 🤓
+
+///
+
+## Paquetes de GraphQL { #graphql-libraries }
+
+Aquí algunos de los paquetes de **GraphQL** que tienen soporte **ASGI**. Podrías usarlos con **FastAPI**:
+
+* [Strawberry](https://strawberry.rocks/) 🍓
+ * Con [documentación para FastAPI](https://strawberry.rocks/docs/integrations/fastapi)
+* [Ariadne](https://ariadnegraphql.org/)
+ * Con [documentación para FastAPI](https://ariadnegraphql.org/docs/fastapi-integration)
+* [Tartiflette](https://tartiflette.io/)
+ * Con [Tartiflette ASGI](https://tartiflette.github.io/tartiflette-asgi/) para proporcionar integración con ASGI
+* [Graphene](https://graphene-python.org/)
+ * Con [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3)
+
+## GraphQL con Strawberry { #graphql-with-strawberry }
+
+Si necesitas o quieres trabajar con **GraphQL**, [**Strawberry**](https://strawberry.rocks/) es el paquete **recomendado** ya que tiene un diseño muy similar al diseño de **FastAPI**, todo basado en **anotaciones de tipos**.
+
+Dependiendo de tu caso de uso, podrías preferir usar un paquete diferente, pero si me preguntas, probablemente te sugeriría probar **Strawberry**.
+
+Aquí tienes una pequeña vista previa de cómo podrías integrar Strawberry con FastAPI:
+
+{* ../../docs_src/graphql_/tutorial001_py310.py hl[3,22,25] *}
+
+Puedes aprender más sobre Strawberry en la [documentación de Strawberry](https://strawberry.rocks/).
+
+Y también la documentación sobre [Strawberry con FastAPI](https://strawberry.rocks/docs/integrations/fastapi).
+
+## `GraphQLApp` viejo de Starlette { #older-graphqlapp-from-starlette }
+
+Las versiones anteriores de Starlette incluían una clase `GraphQLApp` para integrar con [Graphene](https://graphene-python.org/).
+
+Fue deprecada de Starlette, pero si tienes código que lo usaba, puedes fácilmente **migrar** a [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3), que cubre el mismo caso de uso y tiene una **interfaz casi idéntica**.
+
+/// tip | Consejo
+
+Si necesitas GraphQL, aún te recomendaría revisar [Strawberry](https://strawberry.rocks/), ya que se basa en anotaciones de tipos en lugar de clases y tipos personalizados.
+
+///
+
+## Aprende Más { #learn-more }
+
+Puedes aprender más sobre **GraphQL** en la [documentación oficial de GraphQL](https://graphql.org/).
+
+También puedes leer más sobre cada uno de esos paquetes descritos arriba en sus enlaces.
diff --git a/docs/es/docs/how-to/index.md b/docs/es/docs/how-to/index.md
new file mode 100644
index 0000000000000..464028ff24b16
--- /dev/null
+++ b/docs/es/docs/how-to/index.md
@@ -0,0 +1,13 @@
+# Cómo hacer - Recetas { #how-to-recipes }
+
+Aquí verás diferentes recetas o guías de "cómo hacer" para **varios temas**.
+
+La mayoría de estas ideas serían más o menos **independientes**, y en la mayoría de los casos solo deberías estudiarlas si aplican directamente a **tu proyecto**.
+
+Si algo parece interesante y útil para tu proyecto, adelante y revísalo, pero de lo contrario, probablemente puedas simplemente omitirlas.
+
+/// tip | Consejo
+
+Si quieres **aprender FastAPI** de una manera estructurada (recomendado), ve y lee el [Tutorial - Guía de Usuario](../tutorial/index.md) capítulo por capítulo en su lugar.
+
+///
diff --git a/docs/es/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/es/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
new file mode 100644
index 0000000000000..22d51674d06c4
--- /dev/null
+++ b/docs/es/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -0,0 +1,135 @@
+# Migra de Pydantic v1 a Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 }
+
+Si tienes una app de FastAPI antigua, podrías estar usando Pydantic versión 1.
+
+FastAPI versión 0.100.0 tenía compatibilidad con Pydantic v1 o v2. Usaba la que tuvieras instalada.
+
+FastAPI versión 0.119.0 introdujo compatibilidad parcial con Pydantic v1 desde dentro de Pydantic v2 (como `pydantic.v1`), para facilitar la migración a v2.
+
+FastAPI 0.126.0 eliminó la compatibilidad con Pydantic v1, aunque siguió soportando `pydantic.v1` por un poquito más de tiempo.
+
+/// warning | Advertencia
+
+El equipo de Pydantic dejó de dar soporte a Pydantic v1 para las versiones más recientes de Python, comenzando con **Python 3.14**.
+
+Esto incluye `pydantic.v1`, que ya no está soportado en Python 3.14 y superiores.
+
+Si quieres usar las funcionalidades más recientes de Python, tendrás que asegurarte de usar Pydantic v2.
+
+///
+
+Si tienes una app de FastAPI antigua con Pydantic v1, aquí te muestro cómo migrarla a Pydantic v2, y las **funcionalidades en FastAPI 0.119.0** para ayudarte con una migración gradual.
+
+## Guía oficial { #official-guide }
+
+Pydantic tiene una [Guía de migración](https://docs.pydantic.dev/latest/migration/) oficial de v1 a v2.
+
+También incluye qué cambió, cómo las validaciones ahora son más correctas y estrictas, posibles consideraciones, etc.
+
+Puedes leerla para entender mejor qué cambió.
+
+## Tests { #tests }
+
+Asegúrate de tener [tests](../tutorial/testing.md) para tu app y de ejecutarlos en integración continua (CI).
+
+Así podrás hacer la actualización y asegurarte de que todo sigue funcionando como esperas.
+
+## `bump-pydantic` { #bump-pydantic }
+
+En muchos casos, cuando usas modelos de Pydantic normales sin personalizaciones, podrás automatizar gran parte del proceso de migración de Pydantic v1 a Pydantic v2.
+
+Puedes usar [`bump-pydantic`](https://github.com/pydantic/bump-pydantic) del mismo equipo de Pydantic.
+
+Esta herramienta te ayudará a cambiar automáticamente la mayor parte del código que necesita cambiarse.
+
+Después de esto, puedes ejecutar los tests y revisa si todo funciona. Si es así, ya terminaste. 😎
+
+## Pydantic v1 en v2 { #pydantic-v1-in-v2 }
+
+Pydantic v2 incluye todo lo de Pydantic v1 como un submódulo `pydantic.v1`. Pero esto ya no está soportado en versiones por encima de Python 3.13.
+
+Esto significa que puedes instalar la versión más reciente de Pydantic v2 e importar y usar los componentes viejos de Pydantic v1 desde este submódulo, como si tuvieras instalado el Pydantic v1 antiguo.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}
+
+### Compatibilidad de FastAPI con Pydantic v1 en v2 { #fastapi-support-for-pydantic-v1-in-v2 }
+
+Desde FastAPI 0.119.0, también hay compatibilidad parcial para Pydantic v1 desde dentro de Pydantic v2, para facilitar la migración a v2.
+
+Así que podrías actualizar Pydantic a la última versión 2 y cambiar los imports para usar el submódulo `pydantic.v1`, y en muchos casos simplemente funcionaría.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py hl[2,5,15] *}
+
+/// warning | Advertencia
+
+Ten en cuenta que, como el equipo de Pydantic ya no da soporte a Pydantic v1 en versiones recientes de Python, empezando por Python 3.14, usar `pydantic.v1` tampoco está soportado en Python 3.14 y superiores.
+
+///
+
+### Pydantic v1 y v2 en la misma app { #pydantic-v1-and-v2-on-the-same-app }
+
+**No está soportado** por Pydantic tener un modelo de Pydantic v2 con sus propios campos definidos como modelos de Pydantic v1 o viceversa.
+
+```mermaid
+graph TB
+ subgraph "❌ Not Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+...pero puedes tener modelos separados usando Pydantic v1 y v2 en la misma app.
+
+```mermaid
+graph TB
+ subgraph "✅ Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+En algunos casos, incluso es posible tener modelos de Pydantic v1 y v2 en la misma **path operation** de tu app de FastAPI:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}
+
+En el ejemplo anterior, el modelo de entrada es un modelo de Pydantic v1 y el modelo de salida (definido en `response_model=ItemV2`) es un modelo de Pydantic v2.
+
+### Parámetros de Pydantic v1 { #pydantic-v1-parameters }
+
+Si necesitas usar algunas de las herramientas específicas de FastAPI para parámetros como `Body`, `Query`, `Form`, etc. con modelos de Pydantic v1, puedes importarlas de `fastapi.temp_pydantic_v1_params` mientras terminas la migración a Pydantic v2:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py hl[4,18] *}
+
+### Migra por pasos { #migrate-in-steps }
+
+/// tip | Consejo
+
+Primero prueba con `bump-pydantic`, si tus tests pasan y eso funciona, entonces terminaste con un solo comando. ✨
+
+///
+
+Si `bump-pydantic` no funciona para tu caso de uso, puedes usar la compatibilidad de modelos Pydantic v1 y v2 en la misma app para hacer la migración a Pydantic v2 de forma gradual.
+
+Podrías primero actualizar Pydantic para usar la última versión 2, y cambiar los imports para usar `pydantic.v1` para todos tus modelos.
+
+Luego puedes empezar a migrar tus modelos de Pydantic v1 a v2 por grupos, en pasos graduales. 🚶
diff --git a/docs/es/docs/how-to/separate-openapi-schemas.md b/docs/es/docs/how-to/separate-openapi-schemas.md
new file mode 100644
index 0000000000000..db9b46ddbed22
--- /dev/null
+++ b/docs/es/docs/how-to/separate-openapi-schemas.md
@@ -0,0 +1,102 @@
+# Separación de Esquemas OpenAPI para Entrada y Salida o No { #separate-openapi-schemas-for-input-and-output-or-not }
+
+Desde que se lanzó **Pydantic v2**, el OpenAPI generado es un poco más exacto y **correcto** que antes. 😎
+
+De hecho, en algunos casos, incluso tendrá **dos JSON Schemas** en OpenAPI para el mismo modelo Pydantic, para entrada y salida, dependiendo de si tienen **valores por defecto**.
+
+Veamos cómo funciona eso y cómo cambiarlo si necesitas hacerlo.
+
+## Modelos Pydantic para Entrada y Salida { #pydantic-models-for-input-and-output }
+
+Digamos que tienes un modelo Pydantic con valores por defecto, como este:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *}
+
+### Modelo para Entrada { #model-for-input }
+
+Si usas este modelo como entrada, como aquí:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *}
+
+...entonces el campo `description` **no será requerido**. Porque tiene un valor por defecto de `None`.
+
+### Modelo de Entrada en la Documentación { #input-model-in-docs }
+
+Puedes confirmar eso en la documentación, el campo `description` no tiene un **asterisco rojo**, no está marcado como requerido:
+
+
+
+
+
+
+- FastAPI framework, alto desempeño, fácil de aprender, rápido de programar, listo para producción + FastAPI framework, alto rendimiento, fácil de aprender, rápido de programar, listo para producción
--- -**Documentación**: https://fastapi.tiangolo.com +**Documentación**: [https://fastapi.tiangolo.com](https://fastapi.tiangolo.com/es) -**Código Fuente**: https://github.com/tiangolo/fastapi +**Código Fuente**: [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi) --- -FastAPI es un web framework moderno y rápido (de alto rendimiento) para construir APIs con Python 3.6+ basado en las anotaciones de tipos estándar de Python. -Sus características principales son: +FastAPI es un framework web moderno, rápido (de alto rendimiento), para construir APIs con Python basado en las anotaciones de tipos estándar de Python. -* **Rapidez**: Alto rendimiento, a la par con **NodeJS** y **Go** (gracias a Starlette y Pydantic). [Uno de los frameworks de Python más rápidos](#rendimiento). +Las funcionalidades clave son: -* **Rápido de programar**: Incrementa la velocidad de desarrollo entre 200% y 300%. * -* **Menos errores**: Reduce los errores humanos (de programador) aproximadamente un 40%. * -* **Intuitivo**: Gran soporte en los editores con auto completado en todas partes. Gasta menos tiempo debugging. -* **Fácil**: Está diseñado para ser fácil de usar y aprender. Gastando menos tiempo leyendo documentación. -* **Corto**: Minimiza la duplicación de código. Múltiples funcionalidades con cada declaración de parámetros. Menos errores. -* **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: OpenAPI (conocido previamente como Swagger) y JSON Schema. +* **Rápido**: Muy alto rendimiento, a la par con **NodeJS** y **Go** (gracias a Starlette y Pydantic). [Uno de los frameworks Python más rápidos disponibles](#performance). +* **Rápido de programar**: Aumenta la velocidad para desarrollar funcionalidades en aproximadamente un 200% a 300%. * +* **Menos bugs**: Reduce en aproximadamente un 40% los errores inducidos por humanos (desarrolladores). * +* **Intuitivo**: Gran soporte para editores. Autocompletado en todas partes. Menos tiempo depurando. +* **Fácil**: Diseñado para ser fácil de usar y aprender. Menos tiempo leyendo documentación. +* **Corto**: Minimiza la duplicación de código. Múltiples funcionalidades desde cada declaración de parámetro. Menos bugs. +* **Robusto**: Obtén código listo para producción. Con documentación interactiva automática. +* **Basado en estándares**: Basado (y completamente compatible) con los estándares abiertos para APIs: [OpenAPI](https://github.com/OAI/OpenAPI-Specification) (anteriormente conocido como Swagger) y [JSON Schema](https://json-schema.org/). -* Esta estimación está basada en pruebas con un equipo de desarrollo interno contruyendo aplicaciones listas para producción. +* estimación basada en pruebas con un equipo de desarrollo interno, construyendo aplicaciones de producción. -## Sponsors +## Sponsors { #sponsors } -{% if sponsors %} +### Sponsor Keystone { #keystone-sponsor } + +{% for sponsor in sponsors.keystone -%} +
-FastAPI está sobre los hombros de gigantes:
+## **Typer**, el FastAPI de las CLIs { #typer-the-fastapi-of-clis }
-* Starlette para las partes web.
-* Pydantic para las partes de datos.
+uvicorn main:app --reload...fastapi dev...email_validator - para validación de emails.
+* [`email-validator`](https://github.com/JoshData/python-email-validator) - para validación de correos electrónicos.
+
+Usadas por Starlette:
+
+* [`httpx`](https://www.python-httpx.org) - Requerido si deseas usar el `TestClient`.
+* [`jinja2`](https://jinja.palletsprojects.com) - Requerido si deseas usar la configuración de plantilla por defecto.
+* [`python-multipart`](https://github.com/Kludex/python-multipart) - Requerido si deseas soportar form "parsing", con `request.form()`.
+
+Usadas por FastAPI:
+
+* [`uvicorn`](https://www.uvicorn.dev) - para el servidor que carga y sirve tu aplicación. Esto incluye `uvicorn[standard]`, que incluye algunas dependencias (por ejemplo, `uvloop`) necesarias para servir con alto rendimiento.
+* `fastapi-cli[standard]` - para proporcionar el comando `fastapi`.
+ * Esto incluye `fastapi-cloud-cli`, que te permite desplegar tu aplicación de FastAPI en [FastAPI Cloud](https://fastapicloud.com).
+
+### Sin Dependencias `standard` { #without-standard-dependencies }
+
+Si no deseas incluir las dependencias opcionales `standard`, puedes instalar con `pip install fastapi` en lugar de `pip install "fastapi[standard]"`.
+
+### Sin `fastapi-cloud-cli` { #without-fastapi-cloud-cli }
+
+Si quieres instalar FastAPI con las dependencias standard pero sin `fastapi-cloud-cli`, puedes instalar con `pip install "fastapi[standard-no-fastapi-cloud-cli]"`.
+
+### Dependencias Opcionales Adicionales { #additional-optional-dependencies }
-Usados por Starlette:
+Existen algunas dependencias adicionales que podrías querer instalar.
-* httpx - Requerido si quieres usar el `TestClient`.
-* jinja2 - Requerido si quieres usar la configuración por defecto de templates.
-* python-multipart - Requerido si quieres dar soporte a "parsing" de formularios, con `request.form()`.
-* itsdangerous - Requerido para dar soporte a `SessionMiddleware`.
-* pyyaml - Requerido para dar soporte al `SchemaGenerator` de Starlette (probablemente no lo necesites con FastAPI).
-* graphene - Requerido para dar soporte a `GraphQLApp`.
-* ujson - Requerido si quieres usar `UJSONResponse`.
+Dependencias opcionales adicionales de Pydantic:
-Usado por FastAPI / Starlette:
+* [`pydantic-settings`](https://docs.pydantic.dev/latest/usage/pydantic_settings/) - para la gestión de configuraciones.
+* [`pydantic-extra-types`](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/) - para tipos extra para ser usados con Pydantic.
-* uvicorn - para el servidor que carga y sirve tu aplicación.
-* orjson - Requerido si quieres usar `ORJSONResponse`.
+Dependencias opcionales adicionales de FastAPI:
-Puedes instalarlos con `pip install fastapi[all]`.
+* [`orjson`](https://github.com/ijl/orjson) - Requerido si deseas usar `ORJSONResponse`.
+* [`ujson`](https://github.com/esnme/ultrajson) - Requerido si deseas usar `UJSONResponse`.
-## Licencia
+## Licencia { #license }
-Este proyecto está licenciado bajo los términos de la licencia del MIT.
+Este proyecto tiene licencia bajo los términos de la licencia MIT.
diff --git a/docs/es/docs/learn/index.md b/docs/es/docs/learn/index.md
new file mode 100644
index 0000000000000..4333bfcf6e3ce
--- /dev/null
+++ b/docs/es/docs/learn/index.md
@@ -0,0 +1,5 @@
+# Aprende { #learn }
+
+Aquí están las secciones introductorias y los tutoriales para aprender **FastAPI**.
+
+Podrías considerar esto un **libro**, un **curso**, la forma **oficial** y recomendada de aprender FastAPI. 😎
diff --git a/docs/es/docs/project-generation.md b/docs/es/docs/project-generation.md
new file mode 100644
index 0000000000000..11a560eba6936
--- /dev/null
+++ b/docs/es/docs/project-generation.md
@@ -0,0 +1,28 @@
+# Plantilla Full Stack FastAPI { #full-stack-fastapi-template }
+
+Las plantillas, aunque normalmente vienen con una configuración específica, están diseñadas para ser flexibles y personalizables. Esto te permite modificarlas y adaptarlas a los requisitos de tu proyecto, haciéndolas un excelente punto de partida. 🏁
+
+Puedes usar esta plantilla para comenzar, ya que incluye gran parte de la configuración inicial, seguridad, base de datos y algunos endpoints de API ya hechos para ti.
+
+Repositorio de GitHub: [Plantilla Full Stack FastAPI](https://github.com/tiangolo/full-stack-fastapi-template)
+
+## Plantilla Full Stack FastAPI - Stack de tecnología y funcionalidades { #full-stack-fastapi-template-technology-stack-and-features }
+
+- ⚡ [**FastAPI**](https://fastapi.tiangolo.com/es) para la API del backend en Python.
+ - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) para las interacciones con bases de datos SQL en Python (ORM).
+ - 🔍 [Pydantic](https://docs.pydantic.dev), utilizado por FastAPI, para la validación de datos y gestión de configuraciones.
+ - 💾 [PostgreSQL](https://www.postgresql.org) como base de datos SQL.
+- 🚀 [React](https://react.dev) para el frontend.
+ - 💃 Usando TypeScript, hooks, Vite, y otras partes de una stack moderna de frontend.
+ - 🎨 [Tailwind CSS](https://tailwindcss.com) y [shadcn/ui](https://ui.shadcn.com) para los componentes del frontend.
+ - 🤖 Un cliente de frontend generado automáticamente.
+ - 🧪 [Playwright](https://playwright.dev) para escribir pruebas End-to-End.
+ - 🦇 Soporte para modo oscuro.
+- 🐋 [Docker Compose](https://www.docker.com) para desarrollo y producción.
+- 🔒 Hashing seguro de contraseñas por defecto.
+- 🔑 Autenticación con tokens JWT.
+- 📫 Recuperación de contraseñas basada en email.
+- ✅ Pruebas con [Pytest](https://pytest.org).
+- 📞 [Traefik](https://traefik.io) como proxy inverso / load balancer.
+- 🚢 Instrucciones de despliegue usando Docker Compose, incluyendo cómo configurar un proxy Traefik frontend para manejar certificados HTTPS automáticos.
+- 🏭 CI (integración continua) y CD (despliegue continuo) basados en GitHub Actions.
diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md
index e9fd61629372e..5d60ea22c49e2 100644
--- a/docs/es/docs/python-types.md
+++ b/docs/es/docs/python-types.md
@@ -1,29 +1,30 @@
-# Introducción a los Tipos de Python
+# Introducción a Tipos en Python { #python-types-intro }
-**Python 3.6+** tiene soporte para "type hints" opcionales.
+Python tiene soporte para "anotaciones de tipos" opcionales (también llamadas "type hints").
-Estos **type hints** son una nueva sintáxis, desde Python 3.6+, que permite declarar el tipo de una variable.
+Estas **"anotaciones de tipos"** o type hints son una sintaxis especial que permite declarar el tipo de una variable.
-Usando las declaraciones de tipos para tus variables, los editores y otras herramientas pueden proveerte un soporte mejor.
+Al declarar tipos para tus variables, los editores y herramientas te pueden proporcionar un mejor soporte.
-Este es solo un **tutorial corto** sobre los Python type hints. Solo cubre lo mínimo necesario para usarlos con **FastAPI**... realmente es muy poco lo que necesitas.
+Este es solo un **tutorial rápido / recordatorio** sobre las anotaciones de tipos en Python. Cubre solo lo mínimo necesario para usarlas con **FastAPI**... que en realidad es muy poco.
-Todo **FastAPI** está basado en estos type hints, lo que le da muchas ventajas y beneficios.
+**FastAPI** se basa completamente en estas anotaciones de tipos, dándole muchas ventajas y beneficios.
-Pero, así nunca uses **FastAPI** te beneficiarás de aprender un poco sobre los type hints.
+Pero incluso si nunca usas **FastAPI**, te beneficiaría aprender un poco sobre ellas.
-!!! note "Nota"
- Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al siguiente capítulo.
+/// note | Nota
-## Motivación
+Si eres un experto en Python, y ya sabes todo sobre las anotaciones de tipos, salta al siguiente capítulo.
+
+///
+
+## Motivación { #motivation }
Comencemos con un ejemplo simple:
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001_py310.py *}
-Llamar este programa nos muestra el siguiente output:
+Llamar a este programa genera:
```
John Doe
@@ -31,39 +32,37 @@ John Doe
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 concatena con un espacio en la mitad.
+* Toma un `first_name` y `last_name`.
+* Convierte la primera letra de cada uno a mayúsculas con `title()`.
+* Concatena ambos con un espacio en el medio.
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}
-### Edítalo
+### Edítalo { #edit-it }
Es un programa muy simple.
-Ahora, imagina que lo estás escribiendo desde ceros.
+Pero ahora imagina que lo escribieras desde cero.
-En algún punto habrías comenzado con la definición de la función, tenías los parámetros listos...
+En algún momento habrías empezado la definición de la función, tenías los parámetros listos...
-Pero, luego tienes que llamar "ese método que convierte la primera letra en una mayúscula".
+Pero luego tienes que llamar "ese método que convierte la primera letra a mayúscula".
-Era `upper`? O era `uppercase`? `first_uppercase`? `capitalize`?
+¿Era `upper`? ¿Era `uppercase`? `first_uppercase`? `capitalize`?
-Luego lo intentas con el viejo amigo de los programadores, el autocompletado del editor.
+Entonces, pruebas con el amigo del viejo programador, el autocompletado 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+Espacio` para activar el autocompletado.
-Tristemente, no obtienes nada útil:
+Pero, tristemente, no obtienes nada útil:
-
+
-### Añade tipos
+### Añadir tipos { #add-types }
-Vamos a modificar una única línea de la versión previa.
+Modifiquemos una sola línea de la versión anterior.
-Vamos a cambiar exactamente este fragmento, los parámetros de la función, de:
+Cambiaremos exactamente este fragmento, los parámetros de la función, de:
```Python
first_name, last_name
@@ -77,210 +76,273 @@ a:
Eso es todo.
-Esos son los "type hints":
+Esas son las "anotaciones de tipos":
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
-No es lo mismo a declarar valores por defecto, como sería con:
+Eso no es lo mismo que declarar valores por defecto como sería con:
```Python
first_name="john", last_name="doe"
```
-Es algo diferente.
+Es una cosa diferente.
-Estamos usando los dos puntos (`:`), no un símbolo de igual (`=`).
+Estamos usando dos puntos (`:`), no igualdades (`=`).
-Añadir los type hints normalmente no cambia lo que sucedería si ellos no estuviesen presentes.
+Y agregar anotaciones de tipos normalmente no cambia lo que sucede de lo que ocurriría sin ellas.
-Pero ahora imagina que nuevamente estás creando la función, pero con los type hints.
+Pero ahora, imagina que nuevamente estás en medio de la creación de esa función, pero con anotaciones de tipos.
-En el mismo punto intentas iniciar el autocompletado con `Ctrl+Space` y ves:
+En el mismo punto, intentas activar el autocompletado con `Ctrl+Espacio` y ves:
-
+
-Con esto puedes moverte hacia abajo viendo las opciones hasta que encuentras una que te suene:
+Con eso, puedes desplazarte, viendo las opciones, hasta que encuentres la que "te suene":
-
+
-## Más motivación
+## Más motivación { #more-motivation }
-Mira esta función que ya tiene type hints:
+Revisa esta función, ya tiene anotaciones de tipos:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
-Como el editor conoce el tipo de las variables no solo obtienes autocompletado, si no que también obtienes chequeo de errores:
+Porque el editor conoce los tipos de las variables, no solo obtienes autocompletado, también obtienes chequeo de errores:
-
+
-Ahora que sabes que tienes que arreglarlo convierte `age` a un string con `str(age)`:
+Ahora sabes que debes corregirlo, convertir `age` a un string con `str(age)`:
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
-## Declarando tipos
+## Declaración de tipos { #declaring-types }
-Acabas de ver el lugar principal para declarar los type hints. Como parámetros de las funciones.
+Acabas de ver el lugar principal para declarar anotaciones de tipos. Como parámetros de función.
-Este es también el lugar principal en que los usarías con **FastAPI**.
+Este también es el lugar principal donde los utilizarías con **FastAPI**.
-### Tipos simples
+### Tipos simples { #simple-types }
-Puedes declarar todos los tipos estándar de Python, no solamente `str`.
+Puedes declarar todos los tipos estándar de Python, no solo `str`.
-Por ejemplo, puedes usar:
+Puedes usar, por ejemplo:
* `int`
* `float`
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
+
+### Módulo `typing` { #typing-module }
+
+Para algunos casos adicionales, podrías necesitar importar algunas cosas del módulo `typing` de la standard library, por ejemplo cuando quieres declarar que algo tiene "cualquier tipo", puedes usar `Any` de `typing`:
+
+```python
+from typing import Any
+
+
+def some_function(data: Any):
+ print(data)
```
-### Tipos con sub-tipos
+### Tipos genéricos { #generic-types }
-Existen algunas estructuras de datos que pueden contener otros valores, como `dict`, `list`, `set` y `tuple`. Los valores internos pueden tener su propio tipo también.
+Algunos tipos pueden tomar "parámetros de tipo" entre corchetes, para definir sus tipos internos, por ejemplo una "lista de strings" se declararía `list[str]`.
-Para declarar esos tipos y sub-tipos puedes usar el módulo estándar de Python `typing`.
+Estos tipos que pueden tomar parámetros de tipo se llaman **Tipos Genéricos** o **Genéricos**.
-Él existe específicamente para dar soporte a este tipo de type hints.
+Puedes usar los mismos tipos integrados como genéricos (con corchetes y tipos dentro):
-#### Listas
+* `list`
+* `tuple`
+* `set`
+* `dict`
-Por ejemplo, vamos a definir una variable para que sea una `list` compuesta de `str`.
+#### Lista { #list }
-De `typing`, importa `List` (con una `L` mayúscula):
+Por ejemplo, vamos a definir una variable para ser una `list` de `str`.
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+Declara la variable, con la misma sintaxis de dos puntos (`:`).
-Declara la variable con la misma sintáxis de los dos puntos (`:`).
+Como tipo, pon `list`.
-Pon `List` como el tipo.
+Como la lista es un tipo que contiene algunos tipos internos, los pones entre corchetes:
-Como la lista es un tipo que permite tener un "sub-tipo" pones el sub-tipo en corchetes `[]`:
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
-```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+/// info | Información
+
+Esos tipos internos en los corchetes se denominan "parámetros de tipo".
-Esto significa: la variable `items` es una `list` y cada uno de los ítems en esta lista es un `str`.
+En este caso, `str` es el parámetro de tipo pasado a `list`.
-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:
+Eso significa: "la variable `items` es una `list`, y cada uno de los ítems en esta lista es un `str`".
-
+Al hacer eso, tu editor puede proporcionar soporte incluso mientras procesa elementos de la lista:
-Observa que la variable `item` es unos de los elementos en la lista `items`.
+
-El editor aún sabe que es un `str` y provee soporte para ello.
+Sin tipos, eso es casi imposible de lograr.
-#### Tuples y Sets
+Nota que la variable `item` es uno de los elementos en la lista `items`.
+
+Y aún así, el editor sabe que es un `str` y proporciona soporte para eso.
+
+#### Tuple y Set { #tuple-and-set }
Harías lo mismo para declarar `tuple`s y `set`s:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
-```
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
Esto significa:
* La variable `items_t` es un `tuple` con 3 ítems, un `int`, otro `int`, y un `str`.
-* La variable `items_s` es un `set` y cada uno de sus ítems es de tipo `bytes`.
+* La variable `items_s` es un `set`, y cada uno de sus ítems es del tipo `bytes`.
-#### Diccionarios (Dicts)
+#### Dict { #dict }
-Para definir un `dict` le pasas 2 sub-tipos separados por comas.
+Para definir un `dict`, pasas 2 parámetros de tipo, separados por comas.
-El primer sub-tipo es para los keys del `dict`.
+El primer parámetro de tipo es para las claves del `dict`.
-El segundo sub-tipo es para los valores del `dict`:
+El segundo parámetro de tipo es para los valores del `dict`:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
-```
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
Esto significa:
* La variable `prices` es un `dict`:
- * Los keys de este `dict` son de tipo `str` (Digamos que son el nombre de cada ítem).
- * Los valores de este `dict` son de tipo `float` (Digamos que son el precio de cada ítem).
+ * Las claves de este `dict` son del tipo `str` (digamos, el nombre de cada ítem).
+ * Los valores de este `dict` son del tipo `float` (digamos, el precio de cada ítem).
-### Clases como tipos
+#### Union { #union }
-También puedes declarar una clase como el tipo de una variable.
+Puedes declarar que una variable puede ser cualquiera de **varios tipos**, por ejemplo, un `int` o un `str`.
+
+Para definirlo usas la barra vertical (`|`) para separar ambos tipos.
-Digamos que tienes una clase `Person`con un nombre:
+Esto se llama una "unión", porque la variable puede ser cualquiera en la unión de esos dos conjuntos de tipos.
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial009.py!}
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
```
-Entonces puedes declarar una variable que sea de tipo `Person`:
+Esto significa que `item` podría ser un `int` o un `str`.
+
+#### Posiblemente `None` { #possibly-none }
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial009.py!}
+Puedes declarar que un valor podría tener un tipo, como `str`, pero que también podría ser `None`.
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
```
-Una vez más tendrás todo el soporte del editor:
+////
-
+Usar `str | None` en lugar de solo `str` te permitirá al editor ayudarte a detectar errores donde podrías estar asumiendo que un valor siempre es un `str`, cuando en realidad también podría ser `None`.
-## Modelos de Pydantic
+### Clases como tipos { #classes-as-types }
-Pydantic es una library de Python para llevar a cabo validación de datos.
+También puedes declarar una clase como el tipo de una variable.
-Tú declaras la "forma" de los datos mediante clases con atributos.
+Digamos que tienes una clase `Person`, con un nombre:
-Cada atributo tiene un tipo.
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
-Luego creas un instance de esa clase con algunos valores y Pydantic validará los valores, los convertirá al tipo apropiado (si ese es el caso) y te dará un objeto con todos los datos.
+Luego puedes declarar una variable para que sea de tipo `Person`:
-Y obtienes todo el soporte del editor con el objeto resultante.
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
-Tomado de la documentación oficial de Pydantic:
+Y luego, nuevamente, obtienes todo el soporte del editor:
-```Python
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+
+
+Nota que esto significa "`one_person` es una **instance** de la clase `Person`".
+
+No significa "`one_person` es la **clase** llamada `Person`".
+
+## Modelos Pydantic { #pydantic-models }
+
+[Pydantic](https://docs.pydantic.dev/) es un paquete de Python para realizar la validación de datos.
+
+Declaras la "forma" de los datos como clases con atributos.
+
+Y cada atributo tiene un tipo.
+
+Entonces creas un instance de esa clase con algunos valores y validará los valores, los convertirá al tipo adecuado (si es el caso) y te dará un objeto con todos los datos.
+
+Y obtienes todo el soporte del editor con ese objeto resultante.
+
+Un ejemplo de la documentación oficial de Pydantic:
+
+{* ../../docs_src/python_types/tutorial011_py310.py *}
+
+/// info | Información
+
+Para saber más sobre [Pydantic, revisa su documentación](https://docs.pydantic.dev/).
-!!! info "Información"
- Para aprender más sobre Pydantic mira su documentación.
+///
-**FastAPI** está todo basado en Pydantic.
+**FastAPI** está completamente basado en Pydantic.
-Vas a ver mucho más de esto en práctica en el [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}.
+Verás mucho más de todo esto en práctica en el [Tutorial - Guía del Usuario](tutorial/index.md).
-## Type hints en **FastAPI**
+## Anotaciones de tipos con metadata { #type-hints-with-metadata-annotations }
-**FastAPI** aprovecha estos type hints para hacer varias cosas.
+Python también tiene una funcionalidad que permite poner **metadata adicional** en estas anotaciones de tipos usando `Annotated`.
-Con **FastAPI** declaras los parámetros con type hints y obtienes:
+Puedes importar `Annotated` desde `typing`.
-* **Soporte en el editor**.
-* **Type checks**.
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
+
+Python en sí no hace nada con este `Annotated`. Y para los editores y otras herramientas, el tipo sigue siendo `str`.
+
+Pero puedes usar este espacio en `Annotated` para proporcionar a **FastAPI** metadata adicional sobre cómo quieres que se comporte tu aplicación.
+
+Lo importante a recordar es que **el primer *parámetro de tipo*** que pasas a `Annotated` es el **tipo real**. El resto es solo metadata para otras herramientas.
+
+Por ahora, solo necesitas saber que `Annotated` existe, y que es Python estándar. 😎
+
+Luego verás lo **poderoso** que puede ser.
+
+/// tip | Consejo
+
+El hecho de que esto sea **Python estándar** significa que seguirás obteniendo la **mejor experiencia de desarrollador posible** en tu editor, con las herramientas que usas para analizar y refactorizar tu código, etc. ✨
+
+Y también que tu código será muy compatible con muchas otras herramientas y paquetes de Python. 🚀
+
+///
+
+## Anotaciones de tipos en **FastAPI** { #type-hints-in-fastapi }
+
+**FastAPI** aprovecha estas anotaciones de tipos para hacer varias cosas.
+
+Con **FastAPI** declaras parámetros con anotaciones de tipos y obtienes:
+
+* **Soporte del editor**.
+* **Chequeo de tipos**.
...y **FastAPI** usa las mismas declaraciones para:
-* **Definir requerimientos**: desde request path parameters, query parameters, headers, bodies, dependencies, etc.
-* **Convertir datos**: desde el request al tipo requerido.
-* **Validar datos**: viniendo de cada request:
+* **Definir requerimientos**: de parámetros de path de la request, parámetros de query, headers, bodies, dependencias, etc.
+* **Convertir datos**: de la request al tipo requerido.
+* **Validar datos**: provenientes de cada request:
* Generando **errores automáticos** devueltos al cliente cuando los datos son inválidos.
* **Documentar** la API usando OpenAPI:
- * que en su caso es usada por las interfaces de usuario de la documentación automática e interactiva.
+ * Que luego es usada por las interfaces de documentación interactiva automática.
+
+Todo esto puede sonar abstracto. No te preocupes. Verás todo esto en acción en el [Tutorial - Guía del Usuario](tutorial/index.md).
+
+Lo importante es que al usar tipos estándar de Python, en un solo lugar (en lugar de agregar más clases, decoradores, etc.), **FastAPI** hará gran parte del trabajo por ti.
-Puede que todo esto suene abstracto. Pero no te preocupes que todo lo verás en acción en el [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}.
+/// info | Información
-Lo importante es que usando los tipos de Python estándar en un único lugar (en vez de añadir más clases, decorator, etc.) **FastAPI** hará mucho del trabajo por ti.
+Si ya revisaste todo el tutorial y volviste para ver más sobre tipos, un buen recurso es [la "cheat sheet" de `mypy`](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html).
-!!! info "Información"
- Si ya pasaste por todo el tutorial y volviste a la sección de los tipos, una buena referencia es la "cheat sheet" de `mypy`.
+///
diff --git a/docs/es/docs/resources/index.md b/docs/es/docs/resources/index.md
new file mode 100644
index 0000000000000..3240095611675
--- /dev/null
+++ b/docs/es/docs/resources/index.md
@@ -0,0 +1,3 @@
+# Recursos { #resources }
+
+Recursos adicionales, enlaces externos y más. ✈️
diff --git a/docs/es/docs/translation-banner.md b/docs/es/docs/translation-banner.md
new file mode 100644
index 0000000000000..e38f20cbbd789
--- /dev/null
+++ b/docs/es/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 Traducción por IA y humanos
+
+Esta traducción fue hecha por IA guiada por humanos. 🤝
+
+Podría tener errores al interpretar el significado original, o sonar poco natural, etc. 🤖
+
+Puedes mejorar esta traducción [ayudándonos a guiar mejor al LLM de IA](https://fastapi.tiangolo.com/es/contributing/#translations).
+
+[Versión en inglés](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/es/docs/tutorial/background-tasks.md b/docs/es/docs/tutorial/background-tasks.md
new file mode 100644
index 0000000000000..6ae265b919a6e
--- /dev/null
+++ b/docs/es/docs/tutorial/background-tasks.md
@@ -0,0 +1,84 @@
+# Tareas en Segundo Plano { #background-tasks }
+
+Puedes definir tareas en segundo plano para que se ejecuten *después* de devolver un response.
+
+Esto es útil para operaciones que necesitan ocurrir después de un request, pero para las que el cliente realmente no necesita esperar a que la operación termine antes de recibir el response.
+
+Esto incluye, por ejemplo:
+
+* Notificaciones por email enviadas después de realizar una acción:
+ * Como conectarse a un servidor de email y enviar un email tiende a ser "lento" (varios segundos), puedes devolver el response de inmediato y enviar la notificación por email en segundo plano.
+* Procesamiento de datos:
+ * Por ejemplo, supongamos que recibes un archivo que debe pasar por un proceso lento, puedes devolver un response de "Accepted" (HTTP 202) y procesar el archivo en segundo plano.
+
+## Usando `BackgroundTasks` { #using-backgroundtasks }
+
+Primero, importa `BackgroundTasks` y define un parámetro en tu *path operation function* con una declaración de tipo de `BackgroundTasks`:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
+
+**FastAPI** creará el objeto de tipo `BackgroundTasks` por ti y lo pasará como ese parámetro.
+
+## Crear una función de tarea { #create-a-task-function }
+
+Crea una función para que se ejecute como la tarea en segundo plano.
+
+Es solo una función estándar que puede recibir parámetros.
+
+Puede ser una función `async def` o una función normal `def`, **FastAPI** sabrá cómo manejarla correctamente.
+
+En este caso, la función de tarea escribirá en un archivo (simulando el envío de un email).
+
+Y como la operación de escritura no usa `async` y `await`, definimos la función con un `def` normal:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
+
+## Agregar la tarea en segundo plano { #add-the-background-task }
+
+Dentro de tu *path operation function*, pasa tu función de tarea al objeto de *background tasks* con el método `.add_task()`:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
+
+`.add_task()` recibe como argumentos:
+
+* Una función de tarea para ejecutar en segundo plano (`write_notification`).
+* Cualquier secuencia de argumentos que deba pasarse a la función de tarea en orden (`email`).
+* Cualquier argumento de palabras clave que deba pasarse a la función de tarea (`message="some notification"`).
+
+## Inyección de Dependencias { #dependency-injection }
+
+Usar `BackgroundTasks` también funciona con el sistema de inyección de dependencias, puedes declarar un parámetro de tipo `BackgroundTasks` en varios niveles: en una *path operation function*, en una dependencia (dependable), en una sub-dependencia, etc.
+
+**FastAPI** sabe qué hacer en cada caso y cómo reutilizar el mismo objeto, de modo que todas las tareas en segundo plano se combinan y ejecutan en segundo plano después:
+
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
+
+En este ejemplo, los mensajes se escribirán en el archivo `log.txt` *después* de que se envíe el response.
+
+Si hay un query en el request, se escribirá en el log en una tarea en segundo plano.
+
+Y luego otra tarea en segundo plano generada en la *path operation function* escribirá un mensaje usando el parámetro de path `email`.
+
+## Detalles Técnicos { #technical-details }
+
+La clase `BackgroundTasks` proviene directamente de [`starlette.background`](https://www.starlette.dev/background/).
+
+Se importa/incluye directamente en FastAPI para que puedas importarla desde `fastapi` y evitar importar accidentalmente la alternativa `BackgroundTask` (sin la `s` al final) de `starlette.background`.
+
+Al usar solo `BackgroundTasks` (y no `BackgroundTask`), es posible usarla como un parámetro de *path operation function* y dejar que **FastAPI** maneje el resto por ti, tal como cuando usas el objeto `Request` directamente.
+
+Todavía es posible usar `BackgroundTask` solo en FastAPI, pero debes crear el objeto en tu código y devolver una `Response` de Starlette incluyéndolo.
+
+Puedes ver más detalles en [la documentación oficial de Starlette sobre Background Tasks](https://www.starlette.dev/background/).
+
+## Advertencia { #caveat }
+
+Si necesitas realizar una computación intensa en segundo plano y no necesariamente necesitas que se ejecute por el mismo proceso (por ejemplo, no necesitas compartir memoria, variables, etc.), podrías beneficiarte del uso de otras herramientas más grandes como [Celery](https://docs.celeryq.dev).
+
+Tienden a requerir configuraciones más complejas, un gestor de cola de mensajes/trabajos, como RabbitMQ o Redis, pero te permiten ejecutar tareas en segundo plano en múltiples procesos, y especialmente, en múltiples servidores.
+
+Pero si necesitas acceder a variables y objetos de la misma app de **FastAPI**, o necesitas realizar pequeñas tareas en segundo plano (como enviar una notificación por email), simplemente puedes usar `BackgroundTasks`.
+
+## Resumen { #recap }
+
+Importa y usa `BackgroundTasks` con parámetros en *path operation functions* y dependencias para agregar tareas en segundo plano.
diff --git a/docs/es/docs/tutorial/bigger-applications.md b/docs/es/docs/tutorial/bigger-applications.md
new file mode 100644
index 0000000000000..27a034f47d001
--- /dev/null
+++ b/docs/es/docs/tutorial/bigger-applications.md
@@ -0,0 +1,535 @@
+# Aplicaciones más grandes - Múltiples archivos { #bigger-applications-multiple-files }
+
+Si estás construyendo una aplicación o una API web, rara vez podrás poner todo en un solo archivo.
+
+**FastAPI** proporciona una herramienta conveniente para estructurar tu aplicación manteniendo toda la flexibilidad.
+
+/// info | Información
+
+Si vienes de Flask, esto sería el equivalente a los Blueprints de Flask.
+
+///
+
+## Un ejemplo de estructura de archivos { #an-example-file-structure }
+
+Digamos que tienes una estructura de archivos como esta:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ ├── dependencies.py
+│ └── routers
+│ │ ├── __init__.py
+│ │ ├── items.py
+│ │ └── users.py
+│ └── internal
+│ ├── __init__.py
+│ └── admin.py
+```
+
+/// tip | Consejo
+
+Hay varios archivos `__init__.py`: uno en cada directorio o subdirectorio.
+
+Esto es lo que permite importar código de un archivo a otro.
+
+Por ejemplo, en `app/main.py` podrías tener una línea como:
+
+```
+from app.routers import items
+```
+
+///
+
+* El directorio `app` contiene todo. Y tiene un archivo vacío `app/__init__.py`, por lo que es un "paquete de Python" (una colección de "módulos de Python"): `app`.
+* Contiene un archivo `app/main.py`. Como está dentro de un paquete de Python (un directorio con un archivo `__init__.py`), es un "módulo" de ese paquete: `app.main`.
+* También hay un archivo `app/dependencies.py`, al igual que `app/main.py`, es un "módulo": `app.dependencies`.
+* Hay un subdirectorio `app/routers/` con otro archivo `__init__.py`, por lo que es un "subpaquete de Python": `app.routers`.
+* El archivo `app/routers/items.py` está dentro de un paquete, `app/routers/`, por lo que es un submódulo: `app.routers.items`.
+* Lo mismo con `app/routers/users.py`, es otro submódulo: `app.routers.users`.
+* También hay un subdirectorio `app/internal/` con otro archivo `__init__.py`, por lo que es otro "subpaquete de Python": `app.internal`.
+* Y el archivo `app/internal/admin.py` es otro submódulo: `app.internal.admin`.
+
+
+
+## Incluir el mismo router múltiples veces con diferentes `prefix` { #include-the-same-router-multiple-times-with-different-prefix }
+
+También puedes usar `.include_router()` múltiples veces con el *mismo* router usando diferentes prefijos.
+
+Esto podría ser útil, por ejemplo, para exponer la misma API bajo diferentes prefijos, por ejemplo, `/api/v1` y `/api/latest`.
+
+Este es un uso avanzado que quizás no necesites realmente, pero está allí en caso de que lo necesites.
+
+## Incluir un `APIRouter` en otro { #include-an-apirouter-in-another }
+
+De la misma manera que puedes incluir un `APIRouter` en una aplicación `FastAPI`, puedes incluir un `APIRouter` en otro `APIRouter` usando:
+
+```Python
+router.include_router(other_router)
+```
+
+Asegúrate de hacerlo antes de incluir `router` en la app de `FastAPI`, para que las *path operations* de `other_router` también se incluyan.
diff --git a/docs/es/docs/tutorial/body-fields.md b/docs/es/docs/tutorial/body-fields.md
new file mode 100644
index 0000000000000..8902ce4e94cd6
--- /dev/null
+++ b/docs/es/docs/tutorial/body-fields.md
@@ -0,0 +1,60 @@
+# Body - Campos { #body-fields }
+
+De la misma manera que puedes declarar validaciones adicionales y metadatos en los parámetros de las *path operation function* con `Query`, `Path` y `Body`, puedes declarar validaciones y metadatos dentro de los modelos de Pydantic usando `Field` de Pydantic.
+
+## Importar `Field` { #import-field }
+
+Primero, tienes que importarlo:
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}
+
+/// warning | Advertencia
+
+Fíjate que `Field` se importa directamente desde `pydantic`, no desde `fastapi` como el resto (`Query`, `Path`, `Body`, etc).
+
+///
+
+## Declarar atributos del modelo { #declare-model-attributes }
+
+Después puedes utilizar `Field` con los atributos del modelo:
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}
+
+`Field` funciona de la misma manera que `Query`, `Path` y `Body`, tiene todos los mismos parámetros, etc.
+
+/// note | Detalles técnicos
+
+En realidad, `Query`, `Path` y otros que verás a continuación crean objetos de subclases de una clase común `Param`, que es a su vez una subclase de la clase `FieldInfo` de Pydantic.
+
+Y `Field` de Pydantic también regresa una instance de `FieldInfo`.
+
+`Body` también devuelve objetos de una subclase de `FieldInfo` directamente. Y hay otros que verás más adelante que son subclases de la clase `Body`.
+
+Recuerda que cuando importas `Query`, `Path`, y otros desde `fastapi`, en realidad son funciones que devuelven clases especiales.
+
+///
+
+/// tip | Consejo
+
+Observa cómo cada atributo del modelo con un tipo, un valor por defecto y `Field` tiene la misma estructura que un parámetro de una *path operation function*, con `Field` en lugar de `Path`, `Query` y `Body`.
+
+///
+
+## Agregar información extra { #add-extra-information }
+
+Puedes declarar información extra en `Field`, `Query`, `Body`, etc. Y será incluida en el JSON Schema generado.
+
+Aprenderás más sobre cómo agregar información extra más adelante en la documentación, cuando aprendamos a declarar ejemplos.
+
+/// warning | Advertencia
+
+Las claves extra pasadas a `Field` también estarán presentes en el esquema de OpenAPI resultante para tu aplicación.
+Como estas claves no necesariamente tienen que ser parte de la especificación de OpenAPI, algunas herramientas de OpenAPI, por ejemplo [el validador de OpenAPI](https://validator.swagger.io/), podrían no funcionar con tu esquema generado.
+
+///
+
+## Resumen { #recap }
+
+Puedes utilizar `Field` de Pydantic para declarar validaciones adicionales y metadatos para los atributos del modelo.
+
+También puedes usar los argumentos de palabra clave extra para pasar metadatos adicionales del JSON Schema.
diff --git a/docs/es/docs/tutorial/body-multiple-params.md b/docs/es/docs/tutorial/body-multiple-params.md
new file mode 100644
index 0000000000000..c78dd288120d7
--- /dev/null
+++ b/docs/es/docs/tutorial/body-multiple-params.md
@@ -0,0 +1,165 @@
+# Cuerpo - Múltiples Parámetros { #body-multiple-parameters }
+
+Ahora que hemos visto cómo usar `Path` y `Query`, veamos usos más avanzados de las declaraciones del request body.
+
+## Mezclar `Path`, `Query` y parámetros del cuerpo { #mix-path-query-and-body-parameters }
+
+Primero, por supuesto, puedes mezclar las declaraciones de parámetros de `Path`, `Query` y del request body libremente y **FastAPI** sabrá qué hacer.
+
+Y también puedes declarar parámetros del cuerpo como opcionales, estableciendo el valor por defecto a `None`:
+
+{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
+
+/// note | Nota
+
+Ten en cuenta que, en este caso, el `item` que se tomaría del cuerpo es opcional. Ya que tiene un valor por defecto de `None`.
+
+///
+
+## Múltiples parámetros del cuerpo { #multiple-body-parameters }
+
+En el ejemplo anterior, las *path operations* esperarían un cuerpo JSON con los atributos de un `Item`, como:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+
+Pero también puedes declarar múltiples parámetros del cuerpo, por ejemplo `item` y `user`:
+
+{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}
+
+En este caso, **FastAPI** notará que hay más de un parámetro del cuerpo en la función (hay dos parámetros que son modelos de Pydantic).
+
+Entonces, usará los nombres de los parámetros como claves (nombres de campo) en el cuerpo, y esperará un cuerpo como:
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ }
+}
+```
+
+/// note | Nota
+
+Ten en cuenta que aunque el `item` se declaró de la misma manera que antes, ahora se espera que esté dentro del cuerpo con una clave `item`.
+
+///
+
+**FastAPI** hará la conversión automática del request, de modo que el parámetro `item` reciba su contenido específico y lo mismo para `user`.
+
+Realizará la validación de los datos compuestos, y los documentará así para el esquema de OpenAPI y la documentación automática.
+
+## Valores singulares en el cuerpo { #singular-values-in-body }
+
+De la misma manera que hay un `Query` y `Path` para definir datos extra para parámetros de query y path, **FastAPI** proporciona un equivalente `Body`.
+
+Por ejemplo, ampliando el modelo anterior, podrías decidir que deseas tener otra clave `importance` en el mismo cuerpo, además de `item` y `user`.
+
+Si lo declaras tal cual, debido a que es un valor singular, **FastAPI** asumirá que es un parámetro de query.
+
+Pero puedes instruir a **FastAPI** para que lo trate como otra clave del cuerpo usando `Body`:
+
+{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
+
+En este caso, **FastAPI** esperará un cuerpo como:
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ },
+ "importance": 5
+}
+```
+
+Nuevamente, convertirá los tipos de datos, validará, documentará, etc.
+
+## Múltiples parámetros de cuerpo y query { #multiple-body-params-and-query }
+
+Por supuesto, también puedes declarar parámetros adicionales de query siempre que lo necesites, además de cualquier parámetro del cuerpo.
+
+Como, por defecto, los valores singulares se interpretan como parámetros de query, no tienes que añadir explícitamente un `Query`, solo puedes hacer:
+
+```Python
+q: str | None = None
+```
+
+Por ejemplo:
+
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
+
+/// info | Información
+
+`Body` también tiene todos los mismos parámetros de validación y metadatos extras que `Query`, `Path` y otros que verás luego.
+
+///
+
+## Embeber un solo parámetro de cuerpo { #embed-a-single-body-parameter }
+
+Supongamos que solo tienes un único parámetro de cuerpo `item` de un modelo Pydantic `Item`.
+
+Por defecto, **FastAPI** esperará su cuerpo directamente.
+
+Pero si deseas que espere un JSON con una clave `item` y dentro de ella los contenidos del modelo, como lo hace cuando declaras parámetros de cuerpo extra, puedes usar el parámetro especial `Body` `embed`:
+
+```Python
+item: Item = Body(embed=True)
+```
+
+como en:
+
+{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}
+
+En este caso, **FastAPI** esperará un cuerpo como:
+
+```JSON hl_lines="2"
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ }
+}
+```
+
+en lugar de:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+
+## Resumen { #recap }
+
+Puedes añadir múltiples parámetros de cuerpo a tu *path operation function*, aunque un request solo puede tener un único cuerpo.
+
+Pero **FastAPI** lo manejará, te dará los datos correctos en tu función, y validará y documentará el esquema correcto en la *path operation*.
+
+También puedes declarar valores singulares para ser recibidos como parte del cuerpo.
+
+Y puedes instruir a **FastAPI** para embeber el cuerpo en una clave incluso cuando solo hay un único parámetro declarado.
diff --git a/docs/es/docs/tutorial/body-nested-models.md b/docs/es/docs/tutorial/body-nested-models.md
new file mode 100644
index 0000000000000..742f78d420eeb
--- /dev/null
+++ b/docs/es/docs/tutorial/body-nested-models.md
@@ -0,0 +1,221 @@
+# Cuerpo - Modelos Anidados { #body-nested-models }
+
+Con **FastAPI**, puedes definir, validar, documentar y usar modelos profundamente anidados de manera arbitraria (gracias a Pydantic).
+
+## Campos de lista { #list-fields }
+
+Puedes definir un atributo como un subtipo. Por ejemplo, una `list` en Python:
+
+{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}
+
+Esto hará que `tags` sea una lista, aunque no declare el tipo de los elementos de la lista.
+
+## Campos de lista con parámetro de tipo { #list-fields-with-type-parameter }
+
+Pero Python tiene una forma específica de declarar listas con tipos internos, o "parámetros de tipo":
+
+### Declarar una `list` con un parámetro de tipo { #declare-a-list-with-a-type-parameter }
+
+Para declarar tipos que tienen parámetros de tipo (tipos internos), como `list`, `dict`, `tuple`,
+pasa el/los tipo(s) interno(s) como "parámetros de tipo" usando corchetes: `[` y `]`
+
+```Python
+my_list: list[str]
+```
+
+Eso es toda la sintaxis estándar de Python para declaraciones de tipo.
+
+Usa esa misma sintaxis estándar para atributos de modelos con tipos internos.
+
+Así, en nuestro ejemplo, podemos hacer que `tags` sea específicamente una "lista de strings":
+
+{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}
+
+## Tipos de conjunto { #set-types }
+
+Pero luego pensamos en ello, y nos damos cuenta de que los tags no deberían repetirse, probablemente serían strings únicos.
+
+Y Python tiene un tipo de datos especial para conjuntos de elementos únicos, el `set`.
+
+Entonces podemos declarar `tags` como un conjunto de strings:
+
+{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}
+
+Con esto, incluso si recibes un request con datos duplicados, se convertirá en un conjunto de elementos únicos.
+
+Y siempre que emitas esos datos, incluso si la fuente tenía duplicados, se emitirá como un conjunto de elementos únicos.
+
+Y también se anotará/documentará en consecuencia.
+
+## Modelos Anidados { #nested-models }
+
+Cada atributo de un modelo Pydantic tiene un tipo.
+
+Pero ese tipo puede ser en sí mismo otro modelo Pydantic.
+
+Así que, puedes declarar "objetos" JSON anidados profundamente con nombres de atributos específicos, tipos y validaciones.
+
+Todo eso, de manera arbitraria.
+
+### Definir un submodelo { #define-a-submodel }
+
+Por ejemplo, podemos definir un modelo `Image`:
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}
+
+### Usar el submodelo como tipo { #use-the-submodel-as-a-type }
+
+Y luego podemos usarlo como el tipo de un atributo:
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}
+
+Esto significaría que **FastAPI** esperaría un cuerpo similar a:
+
+```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"
+ }
+}
+```
+
+Nuevamente, haciendo solo esa declaración, con **FastAPI** obtienes:
+
+* Soporte de editor (autocompletado, etc.), incluso para modelos anidados
+* Conversión de datos
+* Validación de datos
+* Documentación automática
+
+## Tipos especiales y validación { #special-types-and-validation }
+
+Además de tipos singulares normales como `str`, `int`, `float`, etc., puedes usar tipos singulares más complejos que heredan de `str`.
+
+Para ver todas las opciones que tienes, Revisa [Resumen de tipos de Pydantic](https://docs.pydantic.dev/latest/concepts/types/). Verás algunos ejemplos en el siguiente capítulo.
+
+Por ejemplo, como en el modelo `Image` tenemos un campo `url`, podemos declararlo como una instance de `HttpUrl` de Pydantic en lugar de un `str`:
+
+{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}
+
+El string será verificado para ser una URL válida, y documentado en JSON Schema / OpenAPI como tal.
+
+## Atributos con listas de submodelos { #attributes-with-lists-of-submodels }
+
+También puedes usar modelos Pydantic como subtipos de `list`, `set`, etc.:
+
+{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}
+
+Esto esperará (convertirá, validará, documentará, etc.) un cuerpo JSON como:
+
+```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 | Información
+
+Nota cómo la clave `images` ahora tiene una lista de objetos de imagen.
+
+///
+
+## Modelos anidados profundamente { #deeply-nested-models }
+
+Puedes definir modelos anidados tan profundamente como desees:
+
+{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}
+
+/// info | Información
+
+Observa cómo `Offer` tiene una lista de `Item`s, que a su vez tienen una lista opcional de `Image`s
+
+///
+
+## Cuerpos de listas puras { #bodies-of-pure-lists }
+
+Si el valor superior del cuerpo JSON que esperas es un `array` JSON (una `list` en Python), puedes declarar el tipo en el parámetro de la función, al igual que en los modelos Pydantic:
+
+```Python
+images: list[Image]
+```
+
+como en:
+
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
+
+## Soporte de editor en todas partes { #editor-support-everywhere }
+
+Y obtienes soporte de editor en todas partes.
+
+Incluso para elementos dentro de listas:
+
+
+
+No podrías obtener este tipo de soporte de editor si estuvieras trabajando directamente con `dict` en lugar de modelos Pydantic.
+
+Pero tampoco tienes que preocuparte por ellos, los `dicts` entrantes se convierten automáticamente y tu salida se convierte automáticamente a JSON también.
+
+## Cuerpos de `dict`s arbitrarios { #bodies-of-arbitrary-dicts }
+
+También puedes declarar un cuerpo como un `dict` con claves de algún tipo y valores de algún otro tipo.
+
+De esta manera, no tienes que saber de antemano cuáles son los nombres válidos de campo/atributo (como sería el caso con modelos Pydantic).
+
+Esto sería útil si deseas recibir claves que aún no conoces.
+
+---
+
+Otro caso útil es cuando deseas tener claves de otro tipo (por ejemplo, `int`).
+
+Eso es lo que vamos a ver aquí.
+
+En este caso, aceptarías cualquier `dict` siempre que tenga claves `int` con valores `float`:
+
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
+
+/// tip | Consejo
+
+Ten en cuenta que JSON solo admite `str` como claves.
+
+Pero Pydantic tiene conversión automática de datos.
+
+Esto significa que, aunque tus clientes de API solo pueden enviar strings como claves, mientras esos strings contengan enteros puros, Pydantic los convertirá y validará.
+
+Y el `dict` que recibas como `weights` tendrá realmente claves `int` y valores `float`.
+
+///
+
+## Resumen { #recap }
+
+Con **FastAPI** tienes la máxima flexibilidad proporcionada por los modelos Pydantic, manteniendo tu código simple, corto y elegante.
+
+Pero con todos los beneficios:
+
+* Soporte de editor (¡autocompletado en todas partes!)
+* Conversión de datos (también conocido como parsing/serialización)
+* Validación de datos
+* Documentación del esquema
+* Documentación automática
diff --git a/docs/es/docs/tutorial/body-updates.md b/docs/es/docs/tutorial/body-updates.md
new file mode 100644
index 0000000000000..1b309ebbf4059
--- /dev/null
+++ b/docs/es/docs/tutorial/body-updates.md
@@ -0,0 +1,100 @@
+# Body - Actualizaciones { #body-updates }
+
+## Actualización reemplazando con `PUT` { #update-replacing-with-put }
+
+Para actualizar un ítem puedes utilizar la operación de [HTTP `PUT`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT).
+
+Puedes usar el `jsonable_encoder` para convertir los datos de entrada en datos que se puedan almacenar como JSON (por ejemplo, con una base de datos NoSQL). Por ejemplo, convirtiendo `datetime` a `str`.
+
+{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}
+
+`PUT` se usa para recibir datos que deben reemplazar los datos existentes.
+
+### Advertencia sobre el reemplazo { #warning-about-replacing }
+
+Esto significa que si quieres actualizar el ítem `bar` usando `PUT` con un body que contenga:
+
+```Python
+{
+ "name": "Barz",
+ "price": 3,
+ "description": None,
+}
+```
+
+debido a que no incluye el atributo ya almacenado `"tax": 20.2`, el modelo de entrada tomaría el valor por defecto de `"tax": 10.5`.
+
+Y los datos se guardarían con ese "nuevo" `tax` de `10.5`.
+
+## Actualizaciones parciales con `PATCH` { #partial-updates-with-patch }
+
+También puedes usar la operación de [HTTP `PATCH`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) para actualizar *parcialmente* datos.
+
+Esto significa que puedes enviar solo los datos que deseas actualizar, dejando el resto intacto.
+
+/// note | Nota
+
+`PATCH` es menos usado y conocido que `PUT`.
+
+Y muchos equipos utilizan solo `PUT`, incluso para actualizaciones parciales.
+
+Eres **libre** de usarlos como desees, **FastAPI** no impone ninguna restricción.
+
+Pero esta guía te muestra, más o menos, cómo se pretende que se usen.
+
+///
+
+### Uso del parámetro `exclude_unset` de Pydantic { #using-pydantics-exclude-unset-parameter }
+
+Si quieres recibir actualizaciones parciales, es muy útil usar el parámetro `exclude_unset` en el `.model_dump()` del modelo de Pydantic.
+
+Como `item.model_dump(exclude_unset=True)`.
+
+Eso generaría un `dict` solo con los datos que se establecieron al crear el modelo `item`, excluyendo los valores por defecto.
+
+Luego puedes usar esto para generar un `dict` solo con los datos que se establecieron (enviados en el request), omitiendo los valores por defecto:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}
+
+### Uso del parámetro `update` de Pydantic { #using-pydantics-update-parameter }
+
+Ahora, puedes crear una copia del modelo existente usando `.model_copy()`, y pasar el parámetro `update` con un `dict` que contenga los datos a actualizar.
+
+Como `stored_item_model.model_copy(update=update_data)`:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}
+
+### Resumen de actualizaciones parciales { #partial-updates-recap }
+
+En resumen, para aplicar actualizaciones parciales deberías:
+
+* (Opcionalmente) usar `PATCH` en lugar de `PUT`.
+* Recuperar los datos almacenados.
+* Poner esos datos en un modelo de Pydantic.
+* Generar un `dict` sin valores por defecto del modelo de entrada (usando `exclude_unset`).
+ * De esta manera puedes actualizar solo los valores realmente establecidos por el usuario, en lugar de sobrescribir valores ya almacenados con valores por defecto en tu modelo.
+* Crear una copia del modelo almacenado, actualizando sus atributos con las actualizaciones parciales recibidas (usando el parámetro `update`).
+* Convertir el modelo copiado en algo que pueda almacenarse en tu DB (por ejemplo, usando el `jsonable_encoder`).
+ * Esto es comparable a usar el método `.model_dump()` del modelo de nuevo, pero asegura (y convierte) los valores a tipos de datos que pueden convertirse a JSON, por ejemplo, `datetime` a `str`.
+* Guardar los datos en tu DB.
+* Devolver el modelo actualizado.
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *}
+
+/// tip | Consejo
+
+Puedes realmente usar esta misma técnica con una operación HTTP `PUT`.
+
+Pero el ejemplo aquí usa `PATCH` porque fue creado para estos casos de uso.
+
+///
+
+/// note | Nota
+
+Observa que el modelo de entrada sigue siendo validado.
+
+Entonces, si deseas recibir actualizaciones parciales que puedan omitir todos los atributos, necesitas tener un modelo con todos los atributos marcados como opcionales (con valores por defecto o `None`).
+
+Para distinguir entre los modelos con todos los valores opcionales para **actualizaciones** y modelos con valores requeridos para **creación**, puedes utilizar las ideas descritas en [Modelos Extra](extra-models.md).
+
+///
diff --git a/docs/es/docs/tutorial/body.md b/docs/es/docs/tutorial/body.md
new file mode 100644
index 0000000000000..7c3b8e9d9157b
--- /dev/null
+++ b/docs/es/docs/tutorial/body.md
@@ -0,0 +1,166 @@
+# Request Body { #request-body }
+
+Cuando necesitas enviar datos desde un cliente (digamos, un navegador) a tu API, los envías como un **request body**.
+
+Un **request** body es un dato enviado por el cliente a tu API. Un **response** body es el dato que tu API envía al cliente.
+
+Tu API casi siempre tiene que enviar un **response** body. Pero los clientes no necesariamente necesitan enviar **request bodies** todo el tiempo, a veces solo solicitan un path, quizás con algunos parámetros de query, pero no envían un body.
+
+Para declarar un **request** body, usas modelos de [Pydantic](https://docs.pydantic.dev/) con todo su poder y beneficios.
+
+/// info | Información
+
+Para enviar datos, deberías usar uno de estos métodos: `POST` (el más común), `PUT`, `DELETE` o `PATCH`.
+
+Enviar un body con un request `GET` tiene un comportamiento indefinido en las especificaciones, no obstante, es soportado por FastAPI, solo para casos de uso muy complejos/extremos.
+
+Como no se recomienda, la documentación interactiva con Swagger UI no mostrará la documentación para el body cuando se usa `GET`, y los proxies intermedios podrían no soportarlo.
+
+///
+
+## Importar `BaseModel` de Pydantic { #import-pydantics-basemodel }
+
+Primero, necesitas importar `BaseModel` de `pydantic`:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[2] *}
+
+## Crea tu modelo de datos { #create-your-data-model }
+
+Luego, declaras tu modelo de datos como una clase que hereda de `BaseModel`.
+
+Usa tipos estándar de Python para todos los atributos:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}
+
+
+Al igual que al declarar parámetros de query, cuando un atributo del modelo tiene un valor por defecto, no es obligatorio. De lo contrario, es obligatorio. Usa `None` para hacerlo solo opcional.
+
+Por ejemplo, el modelo anterior declara un “`object`” JSON (o `dict` en Python) como:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "An optional description",
+ "price": 45.2,
+ "tax": 3.5
+}
+```
+
+...dado que `description` y `tax` son opcionales (con un valor por defecto de `None`), este “`object`” JSON también sería válido:
+
+```JSON
+{
+ "name": "Foo",
+ "price": 45.2
+}
+```
+
+## Decláralo como un parámetro { #declare-it-as-a-parameter }
+
+Para añadirlo a tu *path operation*, decláralo de la misma manera que declaraste parámetros de path y query:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[16] *}
+
+...y declara su tipo como el modelo que creaste, `Item`.
+
+## Resultados { #results }
+
+Con solo esa declaración de tipo en Python, **FastAPI** hará lo siguiente:
+
+* Leer el body del request como JSON.
+* Convertir los tipos correspondientes (si es necesario).
+* Validar los datos.
+ * Si los datos son inválidos, devolverá un error claro e indicado, señalando exactamente dónde y qué fue lo incorrecto.
+* Proporcionar los datos recibidos en el parámetro `item`.
+ * Como lo declaraste en la función como de tipo `Item`, también tendrás todo el soporte del editor (autocompletado, etc.) para todos los atributos y sus tipos.
+* Generar definiciones de [JSON Schema](https://json-schema.org) para tu modelo, que también puedes usar en cualquier otro lugar si tiene sentido para tu proyecto.
+* Esos esquemas serán parte del esquema de OpenAPI generado y usados por las UIs de documentación automática.
+
+## Documentación automática { #automatic-docs }
+
+Los JSON Schemas de tus modelos serán parte del esquema OpenAPI generado y se mostrarán en la documentación API interactiva:
+
+
+
+Y también se utilizarán en la documentación API dentro de cada *path operation* que los necesite:
+
+
+
+## Soporte del editor { #editor-support }
+
+En tu editor, dentro de tu función, obtendrás anotaciones de tipos y autocompletado en todas partes (esto no sucedería si recibieras un `dict` en lugar de un modelo de Pydantic):
+
+
+
+También recibirás chequeos de errores para operaciones de tipo incorrecto:
+
+
+
+No es por casualidad, todo el framework fue construido alrededor de ese diseño.
+
+Y fue rigurosamente probado en la fase de diseño, antes de cualquier implementación, para garantizar que funcionaría con todos los editores.
+
+Incluso se hicieron algunos cambios en Pydantic para admitir esto.
+
+Las capturas de pantalla anteriores se tomaron con [Visual Studio Code](https://code.visualstudio.com).
+
+Pero obtendrías el mismo soporte en el editor con [PyCharm](https://www.jetbrains.com/pycharm/) y la mayoría de los otros editores de Python:
+
+
+
+/// tip | Consejo
+
+Si usas [PyCharm](https://www.jetbrains.com/pycharm/) como tu editor, puedes usar el [Pydantic PyCharm Plugin](https://github.com/koxudaxi/pydantic-pycharm-plugin/).
+
+Mejora el soporte del editor para modelos de Pydantic, con:
+
+* autocompletado
+* chequeo de tipos
+* refactorización
+* búsqueda
+* inspecciones
+
+///
+
+## Usa el modelo { #use-the-model }
+
+Dentro de la función, puedes acceder a todos los atributos del objeto modelo directamente:
+
+{* ../../docs_src/body/tutorial002_py310.py *}
+
+## Request body + parámetros de path { #request-body-path-parameters }
+
+Puedes declarar parámetros de path y request body al mismo tiempo.
+
+**FastAPI** reconocerá que los parámetros de función que coinciden con los parámetros de path deben ser **tomados del path**, y que los parámetros de función que se declaran como modelos de Pydantic deben ser **tomados del request body**.
+
+{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}
+
+
+## Request body + path + parámetros de query { #request-body-path-query-parameters }
+
+También puedes declarar parámetros de **body**, **path** y **query**, todos al mismo tiempo.
+
+**FastAPI** reconocerá cada uno de ellos y tomará los datos del lugar correcto.
+
+{* ../../docs_src/body/tutorial004_py310.py hl[16] *}
+
+Los parámetros de la función se reconocerán de la siguiente manera:
+
+* Si el parámetro también se declara en el **path**, se utilizará como un parámetro de path.
+* Si el parámetro es de un **tipo singular** (como `int`, `float`, `str`, `bool`, etc.), se interpretará como un parámetro de **query**.
+* Si el parámetro se declara como del tipo de un **modelo de Pydantic**, se interpretará como un **body** de request.
+
+/// note | Nota
+
+FastAPI sabrá que el valor de `q` no es requerido debido al valor por defecto `= None`.
+
+El `str | None` no es utilizado por FastAPI para determinar que el valor no es requerido, sabrá que no es requerido porque tiene un valor por defecto de `= None`.
+
+Pero agregar las anotaciones de tipos permitirá que tu editor te brinde un mejor soporte y detecte errores.
+
+///
+
+## Sin Pydantic { #without-pydantic }
+
+Si no quieres usar modelos de Pydantic, también puedes usar parámetros **Body**. Consulta la documentación para [Body - Múltiples parámetros: Valores singulares en el body](body-multiple-params.md#singular-values-in-body).
diff --git a/docs/es/docs/tutorial/cookie-param-models.md b/docs/es/docs/tutorial/cookie-param-models.md
new file mode 100644
index 0000000000000..4e6038a46bf16
--- /dev/null
+++ b/docs/es/docs/tutorial/cookie-param-models.md
@@ -0,0 +1,76 @@
+# Modelos de Cookies { #cookie-parameter-models }
+
+Si tienes un grupo de **cookies** que están relacionadas, puedes crear un **modelo de Pydantic** para declararlas. 🍪
+
+Esto te permitirá **reutilizar el modelo** en **múltiples lugares** y también declarar validaciones y metadatos para todos los parámetros a la vez. 😎
+
+/// note | Nota
+
+Esto es compatible desde la versión `0.115.0` de FastAPI. 🤓
+
+///
+
+/// tip | Consejo
+
+Esta misma técnica se aplica a `Query`, `Cookie`, y `Header`. 😎
+
+///
+
+## Cookies con un Modelo de Pydantic { #cookies-with-a-pydantic-model }
+
+Declara los parámetros de **cookie** que necesites en un **modelo de Pydantic**, y luego declara el parámetro como `Cookie`:
+
+{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}
+
+**FastAPI** **extraerá** los datos para **cada campo** de las **cookies** recibidas en el request y te entregará el modelo de Pydantic que definiste.
+
+## Revisa la Documentación { #check-the-docs }
+
+Puedes ver las cookies definidas en la UI de la documentación en `/docs`:
+
+
+
+
+---
+
+Si usas PyCharm, puedes:
+
+* Abrir el menú "Run".
+* Seleccionar la opción "Debug...".
+* Luego aparece un menú contextual.
+* Selecciona el archivo para depurar (en este caso, `main.py`).
+
+Luego, iniciará el servidor con tu código **FastAPI**, deteniéndose en tus puntos de interrupción, etc.
+
+Así es como podría verse:
+
+
diff --git a/docs/es/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/es/docs/tutorial/dependencies/classes-as-dependencies.md
new file mode 100644
index 0000000000000..7506bda470bf9
--- /dev/null
+++ b/docs/es/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -0,0 +1,288 @@
+# Clases como dependencias { #classes-as-dependencies }
+
+Antes de profundizar en el sistema de **Inyección de Dependencias**, vamos a mejorar el ejemplo anterior.
+
+## Un `dict` del ejemplo anterior { #a-dict-from-the-previous-example }
+
+En el ejemplo anterior, estábamos devolviendo un `dict` de nuestra dependencia ("dependable"):
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *}
+
+Pero luego obtenemos un `dict` en el parámetro `commons` de la *path operation function*.
+
+Y sabemos que los editores no pueden proporcionar mucho soporte (como autocompletado) para `dict`s, porque no pueden conocer sus claves y tipos de valor.
+
+Podemos hacerlo mejor...
+
+## Qué hace a una dependencia { #what-makes-a-dependency }
+
+Hasta ahora has visto dependencias declaradas como funciones.
+
+Pero esa no es la única forma de declarar dependencias (aunque probablemente sea la más común).
+
+El factor clave es que una dependencia debe ser un "callable".
+
+Un "**callable**" en Python es cualquier cosa que Python pueda "llamar" como una función.
+
+Entonces, si tienes un objeto `something` (que podría _no_ ser una función) y puedes "llamarlo" (ejecutarlo) como:
+
+```Python
+something()
+```
+
+o
+
+```Python
+something(some_argument, some_keyword_argument="foo")
+```
+
+entonces es un "callable".
+
+## Clases como dependencias { #classes-as-dependencies_1 }
+
+Puedes notar que para crear una instance de una clase en Python, utilizas esa misma sintaxis.
+
+Por ejemplo:
+
+```Python
+class Cat:
+ def __init__(self, name: str):
+ self.name = name
+
+
+fluffy = Cat(name="Mr Fluffy")
+```
+
+En este caso, `fluffy` es una instance de la clase `Cat`.
+
+Y para crear `fluffy`, estás "llamando" a `Cat`.
+
+Entonces, una clase en Python también es un **callable**.
+
+Entonces, en **FastAPI**, podrías usar una clase de Python como una dependencia.
+
+Lo que **FastAPI** realmente comprueba es que sea un "callable" (función, clase o cualquier otra cosa) y los parámetros definidos.
+
+Si pasas un "callable" como dependencia en **FastAPI**, analizará los parámetros de ese "callable", y los procesará de la misma manera que los parámetros de una *path operation function*. Incluyendo sub-dependencias.
+
+Eso también se aplica a los callables sin parámetros. Igual que sería para *path operation functions* sin parámetros.
+
+Entonces, podemos cambiar la dependencia "dependable" `common_parameters` de arriba a la clase `CommonQueryParams`:
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *}
+
+Presta atención al método `__init__` usado para crear la instance de la clase:
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *}
+
+...tiene los mismos parámetros que nuestros `common_parameters` anteriores:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *}
+
+Esos parámetros son los que **FastAPI** usará para "resolver" la dependencia.
+
+En ambos casos, tendrá:
+
+* Un parámetro de query `q` opcional que es un `str`.
+* Un parámetro de query `skip` que es un `int`, con un valor por defecto de `0`.
+* Un parámetro de query `limit` que es un `int`, con un valor por defecto de `100`.
+
+En ambos casos, los datos serán convertidos, validados, documentados en el esquema de OpenAPI, etc.
+
+## Úsalo { #use-it }
+
+Ahora puedes declarar tu dependencia usando esta clase.
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *}
+
+**FastAPI** llama a la clase `CommonQueryParams`. Esto crea una "instance" de esa clase y la instance será pasada como el parámetro `commons` a tu función.
+
+## Anotación de tipos vs `Depends` { #type-annotation-vs-depends }
+
+Nota cómo escribimos `CommonQueryParams` dos veces en el código anterior:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ sin `Annotated`
+
+/// tip | Consejo
+
+Prefiere usar la versión `Annotated` si es posible.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+El último `CommonQueryParams`, en:
+
+```Python
+... Depends(CommonQueryParams)
+```
+
+...es lo que **FastAPI** utilizará realmente para saber cuál es la dependencia.
+
+Es a partir de este que **FastAPI** extraerá los parámetros declarados y es lo que **FastAPI** realmente llamará.
+
+---
+
+En este caso, el primer `CommonQueryParams`, en:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, ...
+```
+
+////
+
+//// tab | Python 3.10+ sin `Annotated`
+
+/// tip | Consejo
+
+Prefiere usar la versión `Annotated` si es posible.
+
+///
+
+```Python
+commons: CommonQueryParams ...
+```
+
+////
+
+...no tiene ningún significado especial para **FastAPI**. **FastAPI** no lo usará para la conversión de datos, validación, etc. (ya que está usando `Depends(CommonQueryParams)` para eso).
+
+De hecho, podrías escribir simplemente:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[Any, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ sin `Annotated`
+
+/// tip | Consejo
+
+Prefiere usar la versión `Annotated` si es posible.
+
+///
+
+```Python
+commons = Depends(CommonQueryParams)
+```
+
+////
+
+...como en:
+
+{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *}
+
+Pero declarar el tipo es recomendable, ya que de esa manera tu editor sabrá lo que se pasará como el parámetro `commons`, y entonces podrá ayudarte con el autocompletado, chequeo de tipos, etc:
+
+
+
+## Atajo { #shortcut }
+
+Pero ves que estamos teniendo algo de repetición de código aquí, escribiendo `CommonQueryParams` dos veces:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ sin `Annotated`
+
+/// tip | Consejo
+
+Prefiere usar la versión `Annotated` si es posible.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+**FastAPI** proporciona un atajo para estos casos, en donde la dependencia es *específicamente* una clase que **FastAPI** "llamará" para crear una instance de la clase misma.
+
+Para esos casos específicos, puedes hacer lo siguiente:
+
+En lugar de escribir:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ sin `Annotated`
+
+/// tip | Consejo
+
+Prefiere usar la versión `Annotated` si es posible.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+...escribes:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
+
+////
+
+//// tab | Python 3.10+ sin `Annotated`
+
+/// tip | Consejo
+
+Prefiere usar la versión `Annotated` si es posible.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
+
+Declaras la dependencia como el tipo del parámetro, y usas `Depends()` sin ningún parámetro, en lugar de tener que escribir la clase completa *otra vez* dentro de `Depends(CommonQueryParams)`.
+
+El mismo ejemplo se vería entonces así:
+
+{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *}
+
+...y **FastAPI** sabrá qué hacer.
+
+/// tip | Consejo
+
+Si eso parece más confuso que útil, ignóralo, no lo *necesitas*.
+
+Es solo un atajo. Porque a **FastAPI** le importa ayudarte a minimizar la repetición de código.
+
+///
diff --git a/docs/es/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/es/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
new file mode 100644
index 0000000000000..72e4e973e954a
--- /dev/null
+++ b/docs/es/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -0,0 +1,69 @@
+# Dependencias en decoradores de *path operation* { #dependencies-in-path-operation-decorators }
+
+En algunos casos realmente no necesitas el valor de retorno de una dependencia dentro de tu *path operation function*.
+
+O la dependencia no devuelve un valor.
+
+Pero aún necesitas que sea ejecutada/resuelta.
+
+Para esos casos, en lugar de declarar un parámetro de *path operation function* con `Depends`, puedes añadir una `list` de `dependencies` al decorador de *path operation*.
+
+## Agregar `dependencies` al decorador de *path operation* { #add-dependencies-to-the-path-operation-decorator }
+
+El decorador de *path operation* recibe un argumento opcional `dependencies`.
+
+Debe ser una `list` de `Depends()`:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
+
+Estas dependencias serán ejecutadas/resueltas de la misma manera que las dependencias normales. Pero su valor (si devuelven alguno) no será pasado a tu *path operation function*.
+
+/// tip | Consejo
+
+Algunos editores revisan los parámetros de función no usados y los muestran como errores.
+
+Usando estas `dependencies` en el decorador de *path operation* puedes asegurarte de que se ejecutan mientras evitas errores en editores/herramientas.
+
+También puede ayudar a evitar confusiones para nuevos desarrolladores que vean un parámetro no usado en tu código y puedan pensar que es innecesario.
+
+///
+
+/// info | Información
+
+En este ejemplo usamos headers personalizados inventados `X-Key` y `X-Token`.
+
+Pero en casos reales, al implementar seguridad, obtendrías más beneficios usando las [Utilidades de Seguridad integradas (el próximo capítulo)](../security/index.md).
+
+///
+
+## Errores de dependencias y valores de retorno { #dependencies-errors-and-return-values }
+
+Puedes usar las mismas *funciones* de dependencia que usas normalmente.
+
+### Requisitos de dependencia { #dependency-requirements }
+
+Pueden declarar requisitos de request (como headers) u otras sub-dependencias:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
+
+### Lanzar excepciones { #raise-exceptions }
+
+Estas dependencias pueden `raise` excepciones, igual que las dependencias normales:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
+
+### Valores de retorno { #return-values }
+
+Y pueden devolver valores o no, los valores no serán usados.
+
+Así que, puedes reutilizar una dependencia normal (que devuelve un valor) que ya uses en otro lugar, y aunque el valor no se use, la dependencia será ejecutada:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
+
+## Dependencias para un grupo de *path operations* { #dependencies-for-a-group-of-path-operations }
+
+Más adelante, cuando leas sobre cómo estructurar aplicaciones más grandes ([Aplicaciones Más Grandes - Múltiples Archivos](../../tutorial/bigger-applications.md)), posiblemente con múltiples archivos, aprenderás cómo declarar un único parámetro `dependencies` para un grupo de *path operations*.
+
+## Dependencias Globales { #global-dependencies }
+
+A continuación veremos cómo añadir dependencias a toda la aplicación `FastAPI`, de modo que se apliquen a cada *path operation*.
diff --git a/docs/es/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/es/docs/tutorial/dependencies/dependencies-with-yield.md
new file mode 100644
index 0000000000000..084d72aa40c08
--- /dev/null
+++ b/docs/es/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -0,0 +1,289 @@
+# Dependencias con yield { #dependencies-with-yield }
+
+FastAPI admite dependencias que realizan algunos pasos adicionales después de finalizar.
+
+Para hacer esto, usa `yield` en lugar de `return`, y escribe los pasos adicionales (código) después.
+
+/// tip | Consejo
+
+Asegúrate de usar `yield` una sola vez por dependencia.
+
+///
+
+/// note | Detalles técnicos
+
+Cualquier función que sea válida para usar con:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) o
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+sería válida para usar como una dependencia en **FastAPI**.
+
+De hecho, FastAPI usa esos dos decoradores internamente.
+
+///
+
+## Una dependencia de base de datos con `yield` { #a-database-dependency-with-yield }
+
+Por ejemplo, podrías usar esto para crear una sesión de base de datos y cerrarla después de finalizar.
+
+Solo el código anterior e incluyendo el `yield` statement se ejecuta antes de crear un response:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
+
+El valor generado es lo que se inyecta en *path operations* y otras dependencias:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
+
+El código posterior al `yield` statement se ejecuta después del response:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
+
+/// tip | Consejo
+
+Puedes usar funciones `async` o regulares.
+
+**FastAPI** hará lo correcto con cada una, igual que con dependencias normales.
+
+///
+
+## Una dependencia con `yield` y `try` { #a-dependency-with-yield-and-try }
+
+Si usas un bloque `try` en una dependencia con `yield`, recibirás cualquier excepción que se haya lanzado al usar la dependencia.
+
+Por ejemplo, si algún código en algún punto intermedio, en otra dependencia o en una *path operation*, realiza un "rollback" en una transacción de base de datos o crea cualquier otro error, recibirás la excepción en tu dependencia.
+
+Por lo tanto, puedes buscar esa excepción específica dentro de la dependencia con `except SomeException`.
+
+Del mismo modo, puedes usar `finally` para asegurarte de que los pasos de salida se ejecuten, sin importar si hubo una excepción o no.
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
+
+## Sub-dependencias con `yield` { #sub-dependencies-with-yield }
+
+Puedes tener sub-dependencias y "árboles" de sub-dependencias de cualquier tamaño y forma, y cualquiera o todas ellas pueden usar `yield`.
+
+**FastAPI** se asegurará de que el "código de salida" en cada dependencia con `yield` se ejecute en el orden correcto.
+
+Por ejemplo, `dependency_c` puede tener una dependencia de `dependency_b`, y `dependency_b` de `dependency_a`:
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
+
+Y todas ellas pueden usar `yield`.
+
+En este caso, `dependency_c`, para ejecutar su código de salida, necesita que el valor de `dependency_b` (aquí llamado `dep_b`) todavía esté disponible.
+
+Y, a su vez, `dependency_b` necesita que el valor de `dependency_a` (aquí llamado `dep_a`) esté disponible para su código de salida.
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
+
+De la misma manera, podrías tener algunas dependencias con `yield` y otras dependencias con `return`, y hacer que algunas de esas dependan de algunas de las otras.
+
+Y podrías tener una sola dependencia que requiera varias otras dependencias con `yield`, etc.
+
+Puedes tener cualquier combinación de dependencias que quieras.
+
+**FastAPI** se asegurará de que todo se ejecute en el orden correcto.
+
+/// note | Detalles técnicos
+
+Esto funciona gracias a los [Context Managers](https://docs.python.org/3/library/contextlib.html) de Python.
+
+**FastAPI** los utiliza internamente para lograr esto.
+
+///
+
+## Dependencias con `yield` y `HTTPException` { #dependencies-with-yield-and-httpexception }
+
+Viste que puedes usar dependencias con `yield` y tener bloques `try` que intentan ejecutar algo de código y luego ejecutar código de salida después de `finally`.
+
+También puedes usar `except` para capturar la excepción que se lanzó y hacer algo con ella.
+
+Por ejemplo, puedes lanzar una excepción diferente, como `HTTPException`.
+
+/// tip | Consejo
+
+Esta es una técnica algo avanzada, y en la mayoría de los casos realmente no la necesitarás, ya que puedes lanzar excepciones (incluyendo `HTTPException`) desde dentro del resto del código de tu aplicación, por ejemplo, en la *path operation function*.
+
+Pero está ahí para ti si la necesitas. 🤓
+
+///
+
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
+
+Si quieres capturar excepciones y crear un response personalizado en base a eso, crea un [Manejador de Excepciones Personalizado](../handling-errors.md#install-custom-exception-handlers).
+
+## Dependencias con `yield` y `except` { #dependencies-with-yield-and-except }
+
+Si capturas una excepción usando `except` en una dependencia con `yield` y no la lanzas nuevamente (o lanzas una nueva excepción), FastAPI no podrá notar que hubo una excepción, al igual que sucedería con Python normal:
+
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
+
+En este caso, el cliente verá un response *HTTP 500 Internal Server Error* como debería, dado que no estamos lanzando una `HTTPException` o similar, pero el servidor **no tendrá ningún registro** ni ninguna otra indicación de cuál fue el error. 😱
+
+### Siempre `raise` en Dependencias con `yield` y `except` { #always-raise-in-dependencies-with-yield-and-except }
+
+Si capturas una excepción en una dependencia con `yield`, a menos que estés lanzando otra `HTTPException` o similar, **deberías volver a lanzar la excepción original**.
+
+Puedes volver a lanzar la misma excepción usando `raise`:
+
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
+
+Ahora el cliente obtendrá el mismo response *HTTP 500 Internal Server Error*, pero el servidor tendrá nuestro `InternalError` personalizado en los registros. 😎
+
+## Ejecución de dependencias con `yield` { #execution-of-dependencies-with-yield }
+
+La secuencia de ejecución es más o menos como este diagrama. El tiempo fluye de arriba a abajo. Y cada columna es una de las partes que interactúa o ejecuta código.
+
+```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,operation: Puede lanzar excepciones, incluyendo HTTPException
+ client ->> dep: Iniciar request
+ Note over dep: Ejecutar código hasta yield
+ opt raise Exception
+ dep -->> handler: Lanzar Exception
+ handler -->> client: Response HTTP de error
+ end
+ dep ->> operation: Ejecutar dependencia, por ejemplo, sesión de BD
+ opt raise
+ operation -->> dep: Lanzar Exception (por ejemplo, HTTPException)
+ opt handle
+ dep -->> dep: Puede capturar excepción, lanzar una nueva HTTPException, lanzar otra excepción
+ end
+ handler -->> client: Response HTTP de error
+ end
+
+ operation ->> client: Devolver response al cliente
+ Note over client,operation: El response ya fue enviado, no se puede cambiar
+ opt Tasks
+ operation -->> tasks: Enviar tareas en background
+ end
+ opt Lanzar otra excepción
+ tasks -->> tasks: Manejar excepciones en el código de la tarea en background
+ end
+```
+
+/// info | Información
+
+Solo **un response** será enviado al cliente. Podría ser uno de los responses de error o será el response de la *path operation*.
+
+Después de que se envíe uno de esos responses, no se podrá enviar ningún otro response.
+
+///
+
+/// tip | Consejo
+
+Si lanzas cualquier excepción en el código de la *path operation function*, se pasará a las dependencias con `yield`, incluyendo `HTTPException`. En la mayoría de los casos querrás volver a lanzar esa misma excepción o una nueva desde la dependencia con `yield` para asegurarte de que se maneje correctamente.
+
+///
+
+## Salida temprana y `scope` { #early-exit-and-scope }
+
+Normalmente, el código de salida de las dependencias con `yield` se ejecuta **después de que el response** se envía al cliente.
+
+Pero si sabes que no necesitarás usar la dependencia después de regresar de la *path operation function*, puedes usar `Depends(scope="function")` para decirle a FastAPI que debe cerrar la dependencia después de que la *path operation function* regrese, pero **antes** de que se envíe el **response**.
+
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
+
+`Depends()` recibe un parámetro `scope` que puede ser:
+
+* `"function"`: iniciar la dependencia antes de la *path operation function* que maneja el request, terminar la dependencia después de que termine la *path operation function*, pero **antes** de que el response se envíe de vuelta al cliente. Entonces, la función de dependencia se ejecutará **alrededor** de la *path operation **function***.
+* `"request"`: iniciar la dependencia antes de la *path operation function* que maneja el request (similar a cuando se usa `"function"`), pero terminar **después** de que el response se envíe de vuelta al cliente. Entonces, la función de dependencia se ejecutará **alrededor** del **request** y del ciclo del response.
+
+Si no se especifica y la dependencia tiene `yield`, tendrá un `scope` de `"request"` por defecto.
+
+### `scope` para sub-dependencias { #scope-for-sub-dependencies }
+
+Cuando declaras una dependencia con `scope="request"` (el valor por defecto), cualquier sub-dependencia también necesita tener un `scope` de `"request"`.
+
+Pero una dependencia con `scope` de `"function"` puede tener dependencias con `scope` de `"function"` y `scope` de `"request"`.
+
+Esto es porque cualquier dependencia necesita poder ejecutar su código de salida antes que las sub-dependencias, ya que podría necesitar seguir usándolas durante su código de salida.
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant dep_req as Dep scope="request"
+participant dep_func as Dep scope="function"
+participant operation as Path Operation
+
+ client ->> dep_req: Start request
+ Note over dep_req: Run code up to yield
+ dep_req ->> dep_func: Pass dependency
+ Note over dep_func: Run code up to yield
+ dep_func ->> operation: Run path operation with dependency
+ operation ->> dep_func: Return from path operation
+ Note over dep_func: Run code after yield
+ Note over dep_func: ✅ Dependency closed
+ dep_func ->> client: Send response to client
+ Note over client: Response sent
+ Note over dep_req: Run code after yield
+ Note over dep_req: ✅ Dependency closed
+```
+
+## Dependencias con `yield`, `HTTPException`, `except` y Tareas en Background { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+Las dependencias con `yield` han evolucionado con el tiempo para cubrir diferentes casos de uso y corregir algunos problemas.
+
+Si quieres ver qué ha cambiado en diferentes versiones de FastAPI, puedes leer más al respecto en la guía avanzada, en [Dependencias avanzadas - Dependencias con `yield`, `HTTPException`, `except` y Tareas en Background](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks).
+## Context Managers { #context-managers }
+
+### Qué son los "Context Managers" { #what-are-context-managers }
+
+Los "Context Managers" son aquellos objetos de Python que puedes usar en un `with` statement.
+
+Por ejemplo, [puedes usar `with` para leer un archivo](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files):
+
+```Python
+with open("./somefile.txt") as f:
+ contents = f.read()
+ print(contents)
+```
+
+Internamente, `open("./somefile.txt")` crea un objeto llamado "Context Manager".
+
+Cuando el bloque `with` termina, se asegura de cerrar el archivo, incluso si hubo excepciones.
+
+Cuando creas una dependencia con `yield`, **FastAPI** creará internamente un context manager para ella y lo combinará con algunas otras herramientas relacionadas.
+
+### Usando context managers en dependencias con `yield` { #using-context-managers-in-dependencies-with-yield }
+
+/// warning | Advertencia
+
+Esto es, más o menos, una idea "avanzada".
+
+Si apenas estás comenzando con **FastAPI**, podrías querer omitirlo por ahora.
+
+///
+
+En Python, puedes crear Context Managers [creando una clase con dos métodos: `__enter__()` y `__exit__()`](https://docs.python.org/3/reference/datamodel.html#context-managers).
+
+También puedes usarlos dentro de las dependencias de **FastAPI** con `yield` usando
+`with` o `async with` en la función de dependencia:
+
+{* ../../docs_src/dependencies/tutorial010_py310.py hl[1:9,13] *}
+
+/// tip | Consejo
+
+Otra manera de crear un context manager es con:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) o
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+usándolos para decorar una función con un solo `yield`.
+
+Eso es lo que **FastAPI** usa internamente para dependencias con `yield`.
+
+Pero no tienes que usar los decoradores para las dependencias de FastAPI (y no deberías).
+
+FastAPI lo hará por ti internamente.
+
+///
diff --git a/docs/es/docs/tutorial/dependencies/global-dependencies.md b/docs/es/docs/tutorial/dependencies/global-dependencies.md
new file mode 100644
index 0000000000000..661474f71648f
--- /dev/null
+++ b/docs/es/docs/tutorial/dependencies/global-dependencies.md
@@ -0,0 +1,15 @@
+# Dependencias Globales { #global-dependencies }
+
+Para algunos tipos de aplicaciones, podrías querer agregar dependencias a toda la aplicación.
+
+Similar a como puedes [agregar `dependencies` a los *path operation decorators*](dependencies-in-path-operation-decorators.md), puedes agregarlos a la aplicación de `FastAPI`.
+
+En ese caso, se aplicarán a todas las *path operations* en la aplicación:
+
+{* ../../docs_src/dependencies/tutorial012_an_py310.py hl[17] *}
+
+Y todas las ideas en la sección sobre [agregar `dependencies` a los *path operation decorators*](dependencies-in-path-operation-decorators.md) siguen aplicándose, pero en este caso, a todas las *path operations* en la app.
+
+## Dependencias para grupos de *path operations* { #dependencies-for-groups-of-path-operations }
+
+Más adelante, al leer sobre cómo estructurar aplicaciones más grandes ([Aplicaciones Más Grandes - Múltiples Archivos](../../tutorial/bigger-applications.md)), posiblemente con múltiples archivos, aprenderás cómo declarar un solo parámetro de `dependencies` para un grupo de *path operations*.
diff --git a/docs/es/docs/tutorial/dependencies/index.md b/docs/es/docs/tutorial/dependencies/index.md
new file mode 100644
index 0000000000000..ed5783f39d39b
--- /dev/null
+++ b/docs/es/docs/tutorial/dependencies/index.md
@@ -0,0 +1,250 @@
+# Dependencias { #dependencies }
+
+**FastAPI** tiene un sistema de **Inyección de Dependencias** muy poderoso pero intuitivo.
+
+Está diseñado para ser muy simple de usar, y para hacer que cualquier desarrollador integre otros componentes con **FastAPI** de forma muy sencilla.
+
+## Qué es la "Inyección de Dependencias" { #what-is-dependency-injection }
+
+**"Inyección de Dependencias"** significa, en programación, que hay una manera para que tu código (en este caso, tus *path operation functions*) declare las cosas que necesita para funcionar y utilizar: "dependencias".
+
+Y luego, ese sistema (en este caso **FastAPI**) se encargará de hacer lo que sea necesario para proporcionar a tu código esas dependencias necesarias ("inyectar" las dependencias).
+
+Esto es muy útil cuando necesitas:
+
+* Tener lógica compartida (la misma lógica de código una y otra vez).
+* Compartir conexiones a bases de datos.
+* Imponer seguridad, autenticación, requisitos de roles, etc.
+* Y muchas otras cosas...
+
+Todo esto, mientras minimizas la repetición de código.
+
+## Primeros Pasos { #first-steps }
+
+Veamos un ejemplo muy simple. Será tan simple que no es muy útil, por ahora.
+
+Pero de esta manera podemos enfocarnos en cómo funciona el sistema de **Inyección de Dependencias**.
+
+### Crear una dependencia, o "dependable" { #create-a-dependency-or-dependable }
+
+Primero enfoquémonos en la dependencia.
+
+Es solo una función que puede tomar todos los mismos parámetros que una *path operation function* puede tomar:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}
+
+Eso es todo.
+
+**2 líneas**.
+
+Y tiene la misma forma y estructura que todas tus *path operation functions*.
+
+Puedes pensar en ella como una *path operation function* sin el "decorador" (sin el `@app.get("/some-path")`).
+
+Y puede devolver lo que quieras.
+
+En este caso, esta dependencia espera:
+
+* Un parámetro de query opcional `q` que es un `str`.
+* Un parámetro de query opcional `skip` que es un `int`, y por defecto es `0`.
+* Un parámetro de query opcional `limit` que es un `int`, y por defecto es `100`.
+
+Y luego solo devuelve un `dict` que contiene esos valores.
+
+/// info | Información
+
+FastAPI agregó soporte para `Annotated` (y comenzó a recomendarlo) en la versión 0.95.0.
+
+Si tienes una versión anterior, obtendrás errores al intentar usar `Annotated`.
+
+Asegúrate de [Actualizar la versión de FastAPI](../../deployment/versions.md#upgrading-the-fastapi-versions) al menos a la 0.95.1 antes de usar `Annotated`.
+
+///
+
+### Importar `Depends` { #import-depends }
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}
+
+### Declarar la dependencia, en el "dependant" { #declare-the-dependency-in-the-dependant }
+
+De la misma forma en que usas `Body`, `Query`, etc. con los parámetros de tu *path operation function*, usa `Depends` con un nuevo parámetro:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}
+
+Aunque usas `Depends` en los parámetros de tu función de la misma manera que usas `Body`, `Query`, etc., `Depends` funciona un poco diferente.
+
+Le das a `Depends` un solo parámetro.
+
+Este parámetro debe ser algo como una función.
+
+**No la llames** directamente (no agregues los paréntesis al final), solo pásala como un parámetro a `Depends()`.
+
+Y esa función toma parámetros de la misma manera que las *path operation functions*.
+
+/// tip | Consejo
+
+Verás qué otras "cosas", además de funciones, pueden usarse como dependencias en el próximo capítulo.
+
+///
+
+Cada vez que llega un nuevo request, **FastAPI** se encargará de:
+
+* Llamar a tu función de dependencia ("dependable") con los parámetros correctos.
+* Obtener el resultado de tu función.
+* Asignar ese resultado al parámetro en tu *path operation function*.
+
+```mermaid
+graph TB
+
+common_parameters(["common_parameters"])
+read_items["/items/"]
+read_users["/users/"]
+
+common_parameters --> read_items
+common_parameters --> read_users
+```
+
+De esta manera escribes código compartido una vez y **FastAPI** se encarga de llamarlo para tus *path operations*.
+
+/// check | Revisa
+
+Nota que no tienes que crear una clase especial y pasarla en algún lugar a **FastAPI** para "registrarla" o algo similar.
+
+Solo la pasas a `Depends` y **FastAPI** sabe cómo hacer el resto.
+
+///
+
+## Compartir dependencias `Annotated` { #share-annotated-dependencies }
+
+En los ejemplos anteriores, ves que hay un poquito de **duplicación de código**.
+
+Cuando necesitas usar la dependencia `common_parameters()`, tienes que escribir todo el parámetro con la anotación de tipo y `Depends()`:
+
+```Python
+commons: Annotated[dict, Depends(common_parameters)]
+```
+
+Pero como estamos usando `Annotated`, podemos almacenar ese valor `Annotated` en una variable y usarlo en múltiples lugares:
+
+{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}
+
+/// tip | Consejo
+
+Esto es solo Python estándar, se llama un "alias de tipo", en realidad no es específico de **FastAPI**.
+
+Pero porque **FastAPI** está basado en los estándares de Python, incluido `Annotated`, puedes usar este truco en tu código. 😎
+
+///
+
+Las dependencias seguirán funcionando como se esperaba, y la **mejor parte** es que la **información de tipo se preservará**, lo que significa que tu editor podrá seguir proporcionándote **autocompletado**, **errores en línea**, etc. Lo mismo para otras herramientas como `mypy`.
+
+Esto será especialmente útil cuando lo uses en una **gran code base** donde uses **las mismas dependencias** una y otra vez en **muchas *path operations***.
+
+## Usar `async` o no usar `async` { #to-async-or-not-to-async }
+
+Como las dependencias también serán llamadas por **FastAPI** (lo mismo que tus *path operation functions*), las mismas reglas aplican al definir tus funciones.
+
+Puedes usar `async def` o `def` normal.
+
+Y puedes declarar dependencias con `async def` dentro de *path operation functions* normales `def`, o dependencias `def` dentro de *path operation functions* `async def`, etc.
+
+No importa. **FastAPI** sabrá qué hacer.
+
+/// note | Nota
+
+Si no lo sabes, revisa la sección [Async: *"¿Con prisa?"*](../../async.md#in-a-hurry) sobre `async` y `await` en la documentación.
+
+///
+
+## Integración con OpenAPI { #integrated-with-openapi }
+
+Todas las declaraciones de request, validaciones y requisitos de tus dependencias (y sub-dependencias) se integrarán en el mismo esquema de OpenAPI.
+
+Así, la documentación interactiva tendrá toda la información de estas dependencias también:
+
+
+
+## Uso simple { #simple-usage }
+
+Si lo ves, las *path operation functions* se declaran para ser usadas siempre que un *path* y una *operación* coincidan, y luego **FastAPI** se encarga de llamar la función con los parámetros correctos, extrayendo los datos del request.
+
+En realidad, todos (o la mayoría) de los frameworks web funcionan de esta misma manera.
+
+Nunca llamas directamente a esas funciones. Son llamadas por tu framework (en este caso, **FastAPI**).
+
+Con el sistema de Inyección de Dependencias, también puedes decirle a **FastAPI** que tu *path operation function* también "depende" de algo más que debe ejecutarse antes que tu *path operation function*, y **FastAPI** se encargará de ejecutarlo e "inyectar" los resultados.
+
+Otros términos comunes para esta misma idea de "inyección de dependencias" son:
+
+* recursos
+* proveedores
+* servicios
+* inyectables
+* componentes
+
+## Plug-ins de **FastAPI** { #fastapi-plug-ins }
+
+Las integraciones y "plug-ins" pueden construirse usando el sistema de **Inyección de Dependencias**. Pero, de hecho, en realidad **no hay necesidad de crear "plug-ins"**, ya que al usar dependencias es posible declarar una cantidad infinita de integraciones e interacciones que se vuelven disponibles para tus *path operation functions*.
+
+Y las dependencias se pueden crear de una manera muy simple e intuitiva que te permite simplemente importar los paquetes de Python que necesitas, e integrarlos con tus funciones de API en un par de líneas de código, *literalmente*.
+
+Verás ejemplos de esto en los próximos capítulos, sobre bases de datos relacionales y NoSQL, seguridad, etc.
+
+## Compatibilidad de **FastAPI** { #fastapi-compatibility }
+
+La simplicidad del sistema de inyección de dependencias hace que **FastAPI** sea compatible con:
+
+* todas las bases de datos relacionales
+* bases de datos NoSQL
+* paquetes externos
+* APIs externas
+* sistemas de autenticación y autorización
+* sistemas de monitoreo de uso de la API
+* sistemas de inyección de datos de response
+* etc.
+
+## Simple y Poderoso { #simple-and-powerful }
+
+Aunque el sistema de inyección de dependencias jerárquico es muy simple de definir y usar, sigue siendo muy poderoso.
+
+Puedes definir dependencias que a su vez pueden definir dependencias ellas mismas.
+
+Al final, se construye un árbol jerárquico de dependencias, y el sistema de **Inyección de Dependencias** se encarga de resolver todas estas dependencias por ti (y sus sub-dependencias) y proporcionar (inyectar) los resultados en cada paso.
+
+Por ejemplo, digamos que tienes 4 endpoints de API (*path operations*):
+
+* `/items/public/`
+* `/items/private/`
+* `/users/{user_id}/activate`
+* `/items/pro/`
+
+entonces podrías agregar diferentes requisitos de permiso para cada uno de ellos solo con dependencias y sub-dependencias:
+
+```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
+```
+
+## Integrado con **OpenAPI** { #integrated-with-openapi_1 }
+
+Todas estas dependencias, al declarar sus requisitos, también añaden parámetros, validaciones, etc. a tus *path operations*.
+
+**FastAPI** se encargará de agregar todo al esquema de OpenAPI, para que se muestre en los sistemas de documentación interactiva.
diff --git a/docs/es/docs/tutorial/dependencies/sub-dependencies.md b/docs/es/docs/tutorial/dependencies/sub-dependencies.md
new file mode 100644
index 0000000000000..95f3fe8174b2b
--- /dev/null
+++ b/docs/es/docs/tutorial/dependencies/sub-dependencies.md
@@ -0,0 +1,105 @@
+# Sub-dependencias { #sub-dependencies }
+
+Puedes crear dependencias que tengan **sub-dependencias**.
+
+Pueden ser tan **profundas** como necesites.
+
+**FastAPI** se encargará de resolverlas.
+
+## Primera dependencia "dependable" { #first-dependency-dependable }
+
+Podrías crear una primera dependencia ("dependable") así:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}
+
+Declara un parámetro de query opcional `q` como un `str`, y luego simplemente lo devuelve.
+
+Esto es bastante simple (no muy útil), pero nos ayudará a centrarnos en cómo funcionan las sub-dependencias.
+
+## Segunda dependencia, "dependable" y "dependant" { #second-dependency-dependable-and-dependant }
+
+Luego puedes crear otra función de dependencia (un "dependable") que al mismo tiempo declare una dependencia propia (por lo que también es un "dependant"):
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}
+
+Centrémonos en los parámetros declarados:
+
+* Aunque esta función es una dependencia ("dependable") en sí misma, también declara otra dependencia (depende de algo más).
+ * Depende del `query_extractor`, y asigna el valor que devuelve al parámetro `q`.
+* También declara una `last_query` cookie opcional, como un `str`.
+ * Si el usuario no proporcionó ningún query `q`, usamos el último query utilizado, que guardamos previamente en una cookie.
+
+## Usa la dependencia { #use-the-dependency }
+
+Entonces podemos usar la dependencia con:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}
+
+/// info | Información
+
+Fíjate que solo estamos declarando una dependencia en la *path operation function*, `query_or_cookie_extractor`.
+
+Pero **FastAPI** sabrá que tiene que resolver `query_extractor` primero, para pasar los resultados de eso a `query_or_cookie_extractor` al llamarlo.
+
+///
+
+```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
+```
+
+## Usando la misma dependencia múltiples veces { #using-the-same-dependency-multiple-times }
+
+Si una de tus dependencias se declara varias veces para la misma *path operation*, por ejemplo, múltiples dependencias tienen una sub-dependencia común, **FastAPI** sabrá llamar a esa sub-dependencia solo una vez por request.
+
+Y guardará el valor devuelto en un "caché" y lo pasará a todos los "dependants" que lo necesiten en ese request específico, en lugar de llamar a la dependencia varias veces para el mismo request.
+
+En un escenario avanzado donde sabes que necesitas que la dependencia se llame en cada paso (posiblemente varias veces) en el mismo request en lugar de usar el valor "en caché", puedes establecer el parámetro `use_cache=False` al usar `Depends`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+//// tab | Python 3.10+ sin Anotaciones
+
+/// tip | Consejo
+
+Prefiere usar la versión `Annotated` si es posible.
+
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+## Resumen { #recap }
+
+Aparte de todas las palabras rimbombantes usadas aquí, el sistema de **Inyección de Dependencias** es bastante simple.
+
+Solo son funciones que se ven igual que las *path operation functions*.
+
+Pero aun así, es muy potente y te permite declarar "grafos" de dependencia anidados arbitrariamente profundos (árboles).
+
+/// tip | Consejo
+
+Todo esto podría no parecer tan útil con estos ejemplos simples.
+
+Pero verás lo útil que es en los capítulos sobre **seguridad**.
+
+Y también verás la cantidad de código que te ahorrará.
+
+///
diff --git a/docs/es/docs/tutorial/encoder.md b/docs/es/docs/tutorial/encoder.md
new file mode 100644
index 0000000000000..2a83153a6c6c9
--- /dev/null
+++ b/docs/es/docs/tutorial/encoder.md
@@ -0,0 +1,35 @@
+# Codificador compatible con JSON { #json-compatible-encoder }
+
+Hay algunos casos en los que podrías necesitar convertir un tipo de dato (como un modelo de Pydantic) a algo compatible con JSON (como un `dict`, `list`, etc).
+
+Por ejemplo, si necesitas almacenarlo en una base de datos.
+
+Para eso, **FastAPI** proporciona una función `jsonable_encoder()`.
+
+## Usando el `jsonable_encoder` { #using-the-jsonable-encoder }
+
+Imaginemos que tienes una base de datos `fake_db` que solo recibe datos compatibles con JSON.
+
+Por ejemplo, no recibe objetos `datetime`, ya que no son compatibles con JSON.
+
+Entonces, un objeto `datetime` tendría que ser convertido a un `str` que contenga los datos en [formato ISO](https://en.wikipedia.org/wiki/ISO_8601).
+
+De la misma manera, esta base de datos no recibiría un modelo de Pydantic (un objeto con atributos), solo un `dict`.
+
+Puedes usar `jsonable_encoder` para eso.
+
+Recibe un objeto, como un modelo de Pydantic, y devuelve una versión compatible con JSON:
+
+{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *}
+
+En este ejemplo, convertiría el modelo de Pydantic a un `dict`, y el `datetime` a un `str`.
+
+El resultado de llamarlo es algo que puede ser codificado con la función estándar de Python [`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps).
+
+No devuelve un gran `str` que contenga los datos en formato JSON (como un string). Devuelve una estructura de datos estándar de Python (por ejemplo, un `dict`) con valores y sub-valores que son todos compatibles con JSON.
+
+/// note | Nota
+
+`jsonable_encoder` es utilizado internamente por **FastAPI** para convertir datos. Pero es útil en muchos otros escenarios.
+
+///
diff --git a/docs/es/docs/tutorial/extra-data-types.md b/docs/es/docs/tutorial/extra-data-types.md
new file mode 100644
index 0000000000000..b92d0fcd485f0
--- /dev/null
+++ b/docs/es/docs/tutorial/extra-data-types.md
@@ -0,0 +1,62 @@
+# Tipos de Datos Extra { #extra-data-types }
+
+Hasta ahora, has estado usando tipos de datos comunes, como:
+
+* `int`
+* `float`
+* `str`
+* `bool`
+
+Pero también puedes usar tipos de datos más complejos.
+
+Y seguirás teniendo las mismas funcionalidades como hasta ahora:
+
+* Gran soporte de editor.
+* Conversión de datos de requests entrantes.
+* Conversión de datos para datos de response.
+* Validación de datos.
+* Anotación y documentación automática.
+
+## Otros tipos de datos { #other-data-types }
+
+Aquí hay algunos de los tipos de datos adicionales que puedes usar:
+
+* `UUID`:
+ * Un "Identificador Universalmente Único" estándar, común como un ID en muchas bases de datos y sistemas.
+ * En requests y responses se representará como un `str`.
+* `datetime.datetime`:
+ * Un `datetime.datetime` de Python.
+ * En requests y responses se representará como un `str` en formato ISO 8601, como: `2008-09-15T15:53:00+05:00`.
+* `datetime.date`:
+ * `datetime.date` de Python.
+ * En requests y responses se representará como un `str` en formato ISO 8601, como: `2008-09-15`.
+* `datetime.time`:
+ * Un `datetime.time` de Python.
+ * En requests y responses se representará como un `str` en formato ISO 8601, como: `14:23:55.003`.
+* `datetime.timedelta`:
+ * Un `datetime.timedelta` de Python.
+ * En requests y responses se representará como un `float` de segundos totales.
+ * Pydantic también permite representarlo como una "codificación de diferencia horaria ISO 8601", [consulta la documentación para más información](https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers).
+* `frozenset`:
+ * En requests y responses, tratado igual que un `set`:
+ * En requests, se leerá una list, eliminando duplicados y convirtiéndola en un `set`.
+ * En responses, el `set` se convertirá en una `list`.
+ * El esquema generado especificará que los valores del `set` son únicos (usando `uniqueItems` de JSON Schema).
+* `bytes`:
+ * `bytes` estándar de Python.
+ * En requests y responses se tratará como `str`.
+ * El esquema generado especificará que es un `str` con `binary` como "format".
+* `Decimal`:
+ * `Decimal` estándar de Python.
+ * En requests y responses, manejado igual que un `float`.
+* Puedes revisar todos los tipos de datos válidos de Pydantic aquí: [Tipos de datos de Pydantic](https://docs.pydantic.dev/latest/usage/types/types/).
+
+## Ejemplo { #example }
+
+Aquí tienes un ejemplo de una *path operation* con parámetros usando algunos de los tipos anteriores.
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *}
+
+Nota que los parámetros dentro de la función tienen su tipo de dato natural, y puedes, por ejemplo, realizar manipulaciones de fechas normales, como:
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *}
diff --git a/docs/es/docs/tutorial/extra-models.md b/docs/es/docs/tutorial/extra-models.md
new file mode 100644
index 0000000000000..4a3b75b5bc1e4
--- /dev/null
+++ b/docs/es/docs/tutorial/extra-models.md
@@ -0,0 +1,211 @@
+# Modelos Extra { #extra-models }
+
+Continuando con el ejemplo anterior, será común tener más de un modelo relacionado.
+
+Esto es especialmente el caso para los modelos de usuario, porque:
+
+* El **modelo de entrada** necesita poder tener una contraseña.
+* El **modelo de salida** no debería tener una contraseña.
+* El **modelo de base de datos** probablemente necesitaría tener una contraseña hasheada.
+
+/// danger | Peligro
+
+Nunca almacenes contraseñas de usuarios en texto plano. Siempre almacena un "hash seguro" que puedas verificar luego.
+
+Si no lo sabes, aprenderás qué es un "hash de contraseña" en los [capítulos de seguridad](security/simple-oauth2.md#password-hashing).
+
+///
+
+## Múltiples modelos { #multiple-models }
+
+Aquí tienes una idea general de cómo podrían ser los modelos con sus campos de contraseña y los lugares donde se utilizan:
+
+{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}
+
+### Acerca de `**user_in.model_dump()` { #about-user-in-model-dump }
+
+#### `.model_dump()` de Pydantic { #pydantics-model-dump }
+
+`user_in` es un modelo Pydantic de la clase `UserIn`.
+
+Los modelos Pydantic tienen un método `.model_dump()` que devuelve un `dict` con los datos del modelo.
+
+Así que, si creamos un objeto Pydantic `user_in` como:
+
+```Python
+user_in = UserIn(username="john", password="secret", email="john.doe@example.com")
+```
+
+y luego llamamos a:
+
+```Python
+user_dict = user_in.model_dump()
+```
+
+ahora tenemos un `dict` con los datos en la variable `user_dict` (es un `dict` en lugar de un objeto modelo Pydantic).
+
+Y si llamamos a:
+
+```Python
+print(user_dict)
+```
+
+obtendríamos un `dict` de Python con:
+
+```Python
+{
+ 'username': 'john',
+ 'password': 'secret',
+ 'email': 'john.doe@example.com',
+ 'full_name': None,
+}
+```
+
+#### Desempaquetando un `dict` { #unpacking-a-dict }
+
+Si tomamos un `dict` como `user_dict` y lo pasamos a una función (o clase) con `**user_dict`, Python lo "desempaquetará". Pasará las claves y valores del `user_dict` directamente como argumentos clave-valor.
+
+Así que, continuando con el `user_dict` anterior, escribir:
+
+```Python
+UserInDB(**user_dict)
+```
+
+sería equivalente a algo como:
+
+```Python
+UserInDB(
+ username="john",
+ password="secret",
+ email="john.doe@example.com",
+ full_name=None,
+)
+```
+
+O más exactamente, usando `user_dict` directamente, con cualquier contenido que pueda tener en el futuro:
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ password = user_dict["password"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+)
+```
+
+#### Un modelo Pydantic a partir del contenido de otro { #a-pydantic-model-from-the-contents-of-another }
+
+Como en el ejemplo anterior obtuvimos `user_dict` de `user_in.model_dump()`, este código:
+
+```Python
+user_dict = user_in.model_dump()
+UserInDB(**user_dict)
+```
+
+sería equivalente a:
+
+```Python
+UserInDB(**user_in.model_dump())
+```
+
+...porque `user_in.model_dump()` es un `dict`, y luego hacemos que Python lo "desempaquete" al pasarlo a `UserInDB` con el prefijo `**`.
+
+Así, obtenemos un modelo Pydantic a partir de los datos en otro modelo Pydantic.
+
+#### Desempaquetando un `dict` y palabras clave adicionales { #unpacking-a-dict-and-extra-keywords }
+
+Y luego agregando el argumento de palabra clave adicional `hashed_password=hashed_password`, como en:
+
+```Python
+UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
+```
+
+...termina siendo como:
+
+```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 | Advertencia
+
+Las funciones adicionales de soporte `fake_password_hasher` y `fake_save_user` son solo para demostrar un posible flujo de datos, pero por supuesto no proporcionan ninguna seguridad real.
+
+///
+
+## Reducir duplicación { #reduce-duplication }
+
+Reducir la duplicación de código es una de las ideas centrales en **FastAPI**.
+
+Ya que la duplicación de código incrementa las posibilidades de bugs, problemas de seguridad, problemas de desincronización de código (cuando actualizas en un lugar pero no en los otros), etc.
+
+Y estos modelos están compartiendo muchos de los datos y duplicando nombres y tipos de atributos.
+
+Podríamos hacerlo mejor.
+
+Podemos declarar un modelo `UserBase` que sirva como base para nuestros otros modelos. Y luego podemos hacer subclases de ese modelo que heredan sus atributos (declaraciones de tipos, validación, etc).
+
+Toda la conversión de datos, validación, documentación, etc. seguirá funcionando normalmente.
+
+De esa manera, podemos declarar solo las diferencias entre los modelos (con `password` en texto plano, con `hashed_password` y sin contraseña):
+
+{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}
+
+## `Union` o `anyOf` { #union-or-anyof }
+
+Puedes declarar un response que sea la `Union` de dos o más tipos, eso significa que el response sería cualquiera de ellos.
+
+Se definirá en OpenAPI con `anyOf`.
+
+Para hacerlo, usa la anotación de tipos estándar de Python [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union):
+
+/// note | Nota
+
+Al definir una [`Union`](https://docs.pydantic.dev/latest/concepts/types/#unions), incluye el tipo más específico primero, seguido por el tipo menos específico. En el ejemplo a continuación, el más específico `PlaneItem` viene antes de `CarItem` en `Union[PlaneItem, CarItem]`.
+
+///
+
+{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}
+
+### `Union` en Python 3.10 { #union-in-python-3-10 }
+
+En este ejemplo pasamos `Union[PlaneItem, CarItem]` como el valor del argumento `response_model`.
+
+Porque lo estamos pasando como un **valor a un argumento** en lugar de ponerlo en una **anotación de tipos**, tenemos que usar `Union` incluso en Python 3.10.
+
+Si estuviera en una anotación de tipos podríamos haber usado la barra vertical, como:
+
+```Python
+some_variable: PlaneItem | CarItem
+```
+
+Pero si ponemos eso en la asignación `response_model=PlaneItem | CarItem` obtendríamos un error, porque Python intentaría realizar una **operación inválida** entre `PlaneItem` y `CarItem` en lugar de interpretar eso como una anotación de tipos.
+
+## Lista de modelos { #list-of-models }
+
+De la misma manera, puedes declarar responses de listas de objetos.
+
+Para eso, usa la `list` estándar de Python:
+
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
+
+## Response con `dict` arbitrario { #response-with-arbitrary-dict }
+
+También puedes declarar un response usando un `dict` arbitrario plano, declarando solo el tipo de las claves y valores, sin usar un modelo Pydantic.
+
+Esto es útil si no conoces los nombres de los campos/atributos válidos (que serían necesarios para un modelo Pydantic) de antemano.
+
+En este caso, puedes usar `dict`:
+
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
+
+## Recapitulación { #recap }
+
+Usa múltiples modelos Pydantic y hereda libremente para cada caso.
+
+No necesitas tener un solo modelo de datos por entidad si esa entidad debe poder tener diferentes "estados". Como el caso con la "entidad" usuario con un estado que incluye `password`, `password_hash` y sin contraseña.
diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md
index efa61f9944601..1fcfdc140237a 100644
--- a/docs/es/docs/tutorial/first-steps.md
+++ b/docs/es/docs/tutorial/first-steps.md
@@ -1,105 +1,122 @@
-# Primeros pasos
+# Primeros Pasos { #first-steps }
-Un archivo muy simple de FastAPI podría verse así:
+El archivo FastAPI más simple podría verse así:
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
-Copia eso a un archivo `main.py`.
+Copia eso en un archivo `main.py`.
-Corre el servidor en vivo:
+Ejecuta el servidor en vivo:
get
+* usando una get operación
+
+/// info | Información sobre `@decorator`
-!!! info "Información sobre `@decorator`"
- Esa sintaxis `@algo` se llama un "decorador" en Python.
+Esa sintaxis `@algo` en Python se llama un "decorador".
- Lo pones encima de una función. Es como un lindo sombrero decorado (creo que de ahí salió el concepto).
+Lo pones encima de una función. Como un bonito sombrero decorativo (supongo que de ahí viene el término).
- Un "decorador" toma la función que tiene debajo y hace algo con ella.
+Un "decorador" toma la función de abajo y hace algo con ella.
- En nuestro caso, este decorador le dice a **FastAPI** que la función que está debajo corresponde al **path** `/` con una **operación** `get`.
+En nuestro caso, este decorador le dice a **FastAPI** que la función de abajo corresponde al **path** `/` con una **operation** `get`.
- Es el "**decorador de operaciones de path**".
+Es el "**path operation decorator**".
+
+///
También puedes usar las otras operaciones:
@@ -267,67 +342,88 @@ También puedes usar las otras operaciones:
* `@app.put()`
* `@app.delete()`
-y las más exóticas:
+Y los más exóticos:
* `@app.options()`
* `@app.head()`
* `@app.patch()`
* `@app.trace()`
-!!! tip "Consejo"
- Tienes la libertad de usar cada operación (método de HTTP) como quieras.
+/// tip | Consejo
+
+Eres libre de usar cada operación (método HTTP) como quieras.
- **FastAPI** no impone ningún significado específico.
+**FastAPI** no fuerza ningún significado específico.
- La información que está presentada aquí es una guía, no un requerimiento.
+La información aquí se presenta como una guía, no un requisito.
- Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando únicamente operaciones `POST`.
+Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando solo operaciones `POST`.
-### Paso 4: define la **función de la operación de path**
+///
-Esta es nuestra "**función de la operación de path**":
+### Paso 4: define la **path operation function** { #step-4-define-the-path-operation-function }
+
+Esta es nuestra "**path operation function**":
* **path**: es `/`.
-* **operación**: es `get`.
-* **función**: es la función debajo del "decorador" (debajo de `@app.get("/")`).
+* **operation**: es `get`.
+* **function**: es la función debajo del "decorador" (debajo de `@app.get("/")`).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
-Esto es una función de Python.
+Esta es una función de Python.
-Esta función será llamada por **FastAPI** cada vez que reciba un request en la URL "`/`" usando una operación `GET`.
+Será llamada por **FastAPI** cuando reciba un request en la URL "`/`" usando una operación `GET`.
-En este caso es una función `async`.
+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 normal en lugar de `async def`:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
-!!! note "Nota"
- Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+/// note | Nota
-### Paso 5: devuelve el contenido
+Si no sabes la diferencia, Revisa la sección [Async: *"¿Tienes prisa?"*](../async.md#in-a-hurry).
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+///
+
+### Paso 5: retorna el contenido { #step-5-return-the-content }
+
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
+
+Puedes retornar un `dict`, `list`, valores singulares como `str`, `int`, etc.
+
+También puedes retornar modelos de Pydantic (verás más sobre eso más adelante).
+
+Hay muchos otros objetos y modelos que serán automáticamente convertidos a JSON (incluyendo ORMs, etc). Intenta usar tus favoritos, es altamente probable que ya sean compatibles.
+
+### Paso 6: Despliégalo { #step-6-deploy-it }
+
+Despliega tu app en **[FastAPI Cloud](https://fastapicloud.com)** con un solo comando: `fastapi deploy`. 🎉
+
+#### Sobre FastAPI Cloud { #about-fastapi-cloud }
+
+**[FastAPI Cloud](https://fastapicloud.com)** está construido por el mismo autor y equipo detrás de **FastAPI**.
+
+Agiliza el proceso de **construir**, **desplegar** y **acceder** a una API con el mínimo esfuerzo.
+
+Trae la misma **experiencia de desarrollador** de construir apps con FastAPI a **desplegarlas** en la nube. 🎉
+
+FastAPI Cloud es el sponsor principal y proveedor de financiación para los proyectos open source de *FastAPI and friends*. ✨
-Puedes devolver `dict`, `list`, valores singulares como un `str`, `int`, etc.
+#### Despliega en otros proveedores cloud { #deploy-to-other-cloud-providers }
-También puedes devolver modelos de Pydantic (ya verás más sobre esto más adelante).
+FastAPI es open source y basado en estándares. Puedes desplegar apps de FastAPI en cualquier proveedor cloud que elijas.
-Hay muchos objetos y modelos que pueden ser convertidos automáticamente a JSON (incluyendo ORMs, etc.). Intenta usar tus favoritos, es muy probable que ya tengan soporte.
+Sigue las guías de tu proveedor cloud para desplegar apps de FastAPI con ellos. 🤓
-## Repaso
+## Recapitulación { #recap }
* Importa `FastAPI`.
-* Crea un instance de `app`.
-* Escribe un **decorador de operación de path** (como `@app.get("/")`).
-* Escribe una **función de la operación de path** (como `def root(): ...` arriba).
-* Corre el servidor de desarrollo (como `uvicorn main:app --reload`).
+* Crea una instance `app`.
+* Escribe un **path operation decorator** usando decoradores como `@app.get("/")`.
+* Define una **path operation function**; por ejemplo, `def root(): ...`.
+* Ejecuta el servidor de desarrollo usando el comando `fastapi dev`.
+* Opcionalmente, despliega tu app con `fastapi deploy`.
diff --git a/docs/es/docs/tutorial/handling-errors.md b/docs/es/docs/tutorial/handling-errors.md
new file mode 100644
index 0000000000000..737c43e41bb57
--- /dev/null
+++ b/docs/es/docs/tutorial/handling-errors.md
@@ -0,0 +1,244 @@
+# Manejo de Errores { #handling-errors }
+
+Existen muchas situaciones en las que necesitas notificar un error a un cliente que está usando tu API.
+
+Este cliente podría ser un navegador con un frontend, un código de otra persona, un dispositivo IoT, etc.
+
+Podrías necesitar decirle al cliente que:
+
+* El cliente no tiene suficientes privilegios para esa operación.
+* El cliente no tiene acceso a ese recurso.
+* El ítem al que el cliente intentaba acceder no existe.
+* etc.
+
+En estos casos, normalmente devolverías un **código de estado HTTP** en el rango de **400** (de 400 a 499).
+
+Esto es similar a los códigos de estado HTTP 200 (de 200 a 299). Esos códigos de estado "200" significan que de alguna manera hubo un "éxito" en el request.
+
+Los códigos de estado en el rango de 400 significan que hubo un error por parte del cliente.
+
+¿Recuerdas todos esos errores de **"404 Not Found"** (y chistes)?
+
+## Usa `HTTPException` { #use-httpexception }
+
+Para devolver responses HTTP con errores al cliente, usa `HTTPException`.
+
+### Importa `HTTPException` { #import-httpexception }
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
+
+### Lanza un `HTTPException` en tu código { #raise-an-httpexception-in-your-code }
+
+`HTTPException` es una excepción de Python normal con datos adicionales relevantes para APIs.
+
+Debido a que es una excepción de Python, no la `return`, sino que la `raise`.
+
+Esto también significa que si estás dentro de una función de utilidad que estás llamando dentro de tu *path operation function*, y lanzas el `HTTPException` desde dentro de esa función de utilidad, no se ejecutará el resto del código en la *path operation function*, terminará ese request de inmediato y enviará el error HTTP del `HTTPException` al cliente.
+
+El beneficio de lanzar una excepción en lugar de `return`ar un valor será más evidente en la sección sobre Dependencias y Seguridad.
+
+En este ejemplo, cuando el cliente solicita un ítem por un ID que no existe, lanza una excepción con un código de estado de `404`:
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
+
+### El response resultante { #the-resulting-response }
+
+Si el cliente solicita `http://example.com/items/foo` (un `item_id` `"foo"`), ese cliente recibirá un código de estado HTTP de 200, y un response JSON de:
+
+```JSON
+{
+ "item": "The Foo Wrestlers"
+}
+```
+
+Pero si el cliente solicita `http://example.com/items/bar` (un `item_id` inexistente `"bar"`), ese cliente recibirá un código de estado HTTP de 404 (el error "no encontrado"), y un response JSON de:
+
+```JSON
+{
+ "detail": "Item not found"
+}
+```
+
+/// tip | Consejo
+
+Cuando lanzas un `HTTPException`, puedes pasar cualquier valor que pueda convertirse a JSON como el parámetro `detail`, no solo `str`.
+
+Podrías pasar un `dict`, un `list`, etc.
+
+Son manejados automáticamente por **FastAPI** y convertidos a JSON.
+
+///
+
+## Agrega headers personalizados { #add-custom-headers }
+
+Existen algunas situaciones en las que es útil poder agregar headers personalizados al error HTTP. Por ejemplo, para algunos tipos de seguridad.
+
+Probablemente no necesitarás usarlos directamente en tu código.
+
+Pero en caso de que los necesites para un escenario avanzado, puedes agregar headers personalizados:
+
+{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
+
+## Instalar manejadores de excepciones personalizados { #install-custom-exception-handlers }
+
+Puedes agregar manejadores de excepciones personalizados con [las mismas utilidades de excepciones de Starlette](https://www.starlette.dev/exceptions/).
+
+Supongamos que tienes una excepción personalizada `UnicornException` que tú (o un paquete que usas) podrías lanzar.
+
+Y quieres manejar esta excepción globalmente con FastAPI.
+
+Podrías agregar un manejador de excepciones personalizado con `@app.exception_handler()`:
+
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
+
+Aquí, si solicitas `/unicorns/yolo`, la *path operation* lanzará un `UnicornException`.
+
+Pero será manejado por el `unicorn_exception_handler`.
+
+Así que recibirás un error limpio, con un código de estado HTTP de `418` y un contenido JSON de:
+
+```JSON
+{"message": "Oops! yolo did something. There goes a rainbow..."}
+```
+
+/// note | Nota Técnica
+
+También podrías usar `from starlette.requests import Request` y `from starlette.responses import JSONResponse`.
+
+**FastAPI** ofrece las mismas `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette. Lo mismo con `Request`.
+
+///
+
+## Sobrescribir los manejadores de excepciones predeterminados { #override-the-default-exception-handlers }
+
+**FastAPI** tiene algunos manejadores de excepciones predeterminados.
+
+Estos manejadores se encargan de devolver los responses JSON predeterminadas cuando lanzas un `HTTPException` y cuando el request tiene datos inválidos.
+
+Puedes sobrescribir estos manejadores de excepciones con los tuyos propios.
+
+### Sobrescribir excepciones de validación de request { #override-request-validation-exceptions }
+
+Cuando un request contiene datos inválidos, **FastAPI** lanza internamente un `RequestValidationError`.
+
+Y también incluye un manejador de excepciones predeterminado para ello.
+
+Para sobrescribirlo, importa el `RequestValidationError` y úsalo con `@app.exception_handler(RequestValidationError)` para decorar el manejador de excepciones.
+
+El manejador de excepciones recibirá un `Request` y la excepción.
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
+
+Ahora, si vas a `/items/foo`, en lugar de obtener el error JSON por defecto con:
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ]
+}
+```
+
+obtendrás una versión en texto, con:
+
+```
+Validation errors:
+Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer
+```
+
+### Sobrescribir el manejador de errores de `HTTPException` { #override-the-httpexception-error-handler }
+
+De la misma manera, puedes sobrescribir el manejador de `HTTPException`.
+
+Por ejemplo, podrías querer devolver un response de texto plano en lugar de JSON para estos errores:
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
+
+/// note | Nota Técnica
+
+También podrías usar `from starlette.responses import PlainTextResponse`.
+
+**FastAPI** ofrece las mismas `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette.
+
+///
+
+/// warning | Advertencia
+
+Ten en cuenta que `RequestValidationError` contiene la información del nombre de archivo y la línea donde ocurre el error de validación, para que puedas mostrarla en tus logs con la información relevante si quieres.
+
+Pero eso significa que si simplemente lo conviertes a un string y devuelves esa información directamente, podrías estar filtrando un poquito de información sobre tu sistema, por eso aquí el código extrae y muestra cada error de forma independiente.
+
+///
+
+### Usar el body de `RequestValidationError` { #use-the-requestvalidationerror-body }
+
+El `RequestValidationError` contiene el `body` que recibió con datos inválidos.
+
+Podrías usarlo mientras desarrollas tu aplicación para registrar el body y depurarlo, devolverlo al usuario, etc.
+
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
+
+Ahora intenta enviar un ítem inválido como:
+
+```JSON
+{
+ "title": "towel",
+ "size": "XL"
+}
+```
+
+Recibirás un response que te dirá que los datos son inválidos conteniendo el body recibido:
+
+```JSON hl_lines="12-15"
+{
+ "detail": [
+ {
+ "loc": [
+ "body",
+ "size"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ],
+ "body": {
+ "title": "towel",
+ "size": "XL"
+ }
+}
+```
+
+#### `HTTPException` de FastAPI vs `HTTPException` de Starlette { #fastapis-httpexception-vs-starlettes-httpexception }
+
+**FastAPI** tiene su propio `HTTPException`.
+
+Y la clase de error `HTTPException` de **FastAPI** hereda de la clase de error `HTTPException` de Starlette.
+
+La única diferencia es que el `HTTPException` de **FastAPI** acepta cualquier dato JSON-able para el campo `detail`, mientras que el `HTTPException` de Starlette solo acepta strings para ello.
+
+Así que puedes seguir lanzando un `HTTPException` de **FastAPI** como de costumbre en tu código.
+
+Pero cuando registras un manejador de excepciones, deberías registrarlo para el `HTTPException` de Starlette.
+
+De esta manera, si alguna parte del código interno de Starlette, o una extensión o plug-in de Starlette, lanza un `HTTPException` de Starlette, tu manejador podrá capturarlo y manejarlo.
+
+En este ejemplo, para poder tener ambos `HTTPException` en el mismo código, las excepciones de Starlette son renombradas a `StarletteHTTPException`:
+
+```Python
+from starlette.exceptions import HTTPException as StarletteHTTPException
+```
+
+### Reutilizar los manejadores de excepciones de **FastAPI** { #reuse-fastapis-exception-handlers }
+
+Si quieres usar la excepción junto con los mismos manejadores de excepciones predeterminados de **FastAPI**, puedes importar y reutilizar los manejadores de excepciones predeterminados de `fastapi.exception_handlers`:
+
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
+
+En este ejemplo solo estás `print`eando el error con un mensaje muy expresivo, pero te haces una idea. Puedes usar la excepción y luego simplemente reutilizar los manejadores de excepciones predeterminados.
diff --git a/docs/es/docs/tutorial/header-param-models.md b/docs/es/docs/tutorial/header-param-models.md
new file mode 100644
index 0000000000000..546a8946d7d93
--- /dev/null
+++ b/docs/es/docs/tutorial/header-param-models.md
@@ -0,0 +1,72 @@
+# Modelos de Parámetros de Header { #header-parameter-models }
+
+Si tienes un grupo de **parámetros de header** relacionados, puedes crear un **modelo Pydantic** para declararlos.
+
+Esto te permitirá **reutilizar el modelo** en **múltiples lugares** y también declarar validaciones y metadatos para todos los parámetros al mismo tiempo. 😎
+
+/// note | Nota
+
+Esto es compatible desde la versión `0.115.0` de FastAPI. 🤓
+
+///
+
+## Parámetros de Header con un Modelo Pydantic { #header-parameters-with-a-pydantic-model }
+
+Declara los **parámetros de header** que necesitas en un **modelo Pydantic**, y luego declara el parámetro como `Header`:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI** **extraerá** los datos para **cada campo** de los **headers** en el request y te dará el modelo Pydantic que definiste.
+
+## Revisa la Documentación { #check-the-docs }
+
+Puedes ver los headers requeridos en la interfaz de documentación en `/docs`:
+
+
+contact fields| Parámetro | Tipo | Descripción |
|---|---|---|
name | str | El nombre identificativo de la persona/organización de contacto. |
url | str | La URL que apunta a la información de contacto. DEBE tener el formato de una URL. |
email | str | La dirección de correo electrónico de la persona/organización de contacto. DEBE tener el formato de una dirección de correo. |
license_info fields| Parámetro | Tipo | Descripción |
|---|---|---|
name | str | REQUERIDO (si se establece un license_info). El nombre de la licencia utilizada para la API. |
identifier | str | Una expresión de licencia [SPDX](https://spdx.org/licenses/) para la API. El campo identifier es mutuamente excluyente del campo url. Disponible desde OpenAPI 3.1.0, FastAPI 0.99.0. |
url | str | Una URL a la licencia utilizada para la API. DEBE tener el formato de una URL. |
+
+## Identificador de licencia { #license-identifier }
+
+Desde OpenAPI 3.1.0 y FastAPI 0.99.0, también puedes establecer la `license_info` con un `identifier` en lugar de una `url`.
+
+Por ejemplo:
+
+{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}
+
+## Metadata para etiquetas { #metadata-for-tags }
+
+También puedes agregar metadata adicional para las diferentes etiquetas usadas para agrupar tus path operations con el parámetro `openapi_tags`.
+
+Este toma una list que contiene un diccionario para cada etiqueta.
+
+Cada diccionario puede contener:
+
+* `name` (**requerido**): un `str` con el mismo nombre de etiqueta que usas en el parámetro `tags` en tus *path operations* y `APIRouter`s.
+* `description`: un `str` con una breve descripción de la etiqueta. Puede tener Markdown y se mostrará en la interfaz de documentación.
+* `externalDocs`: un `dict` que describe documentación externa con:
+ * `description`: un `str` con una breve descripción para la documentación externa.
+ * `url` (**requerido**): un `str` con la URL para la documentación externa.
+
+### Crear metadata para etiquetas { #create-metadata-for-tags }
+
+Probemos eso en un ejemplo con etiquetas para `users` y `items`.
+
+Crea metadata para tus etiquetas y pásala al parámetro `openapi_tags`:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}
+
+Nota que puedes utilizar Markdown dentro de las descripciones, por ejemplo "login" se mostrará en negrita (**login**) y "fancy" se mostrará en cursiva (_fancy_).
+
+/// tip | Consejo
+
+No tienes que agregar metadata para todas las etiquetas que uses.
+
+///
+
+### Usar tus etiquetas { #use-your-tags }
+
+Usa el parámetro `tags` con tus *path operations* (y `APIRouter`s) para asignarlas a diferentes etiquetas:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}
+
+/// info | Información
+
+Lee más sobre etiquetas en [Configuración de Path Operation](path-operation-configuration.md#tags).
+
+///
+
+### Revisa la documentación { #check-the-docs }
+
+Ahora, si revisas la documentación, mostrará toda la metadata adicional:
+
+
+
+### Orden de las etiquetas { #order-of-tags }
+
+El orden de cada diccionario de metadata de etiqueta también define el orden mostrado en la interfaz de documentación.
+
+Por ejemplo, aunque `users` iría después de `items` en orden alfabético, se muestra antes porque agregamos su metadata como el primer diccionario en la list.
+
+## URL de OpenAPI { #openapi-url }
+
+Por defecto, el esquema OpenAPI se sirve en `/openapi.json`.
+
+Pero puedes configurarlo con el parámetro `openapi_url`.
+
+Por ejemplo, para configurarlo para que se sirva en `/api/v1/openapi.json`:
+
+{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}
+
+Si quieres deshabilitar el esquema OpenAPI completamente, puedes establecer `openapi_url=None`, eso también deshabilitará las interfaces de usuario de documentación que lo usan.
+
+## URLs de Docs { #docs-urls }
+
+Puedes configurar las dos interfaces de usuario de documentación incluidas:
+
+* **Swagger UI**: servida en `/docs`.
+ * Puedes establecer su URL con el parámetro `docs_url`.
+ * Puedes deshabilitarla estableciendo `docs_url=None`.
+* **ReDoc**: servida en `/redoc`.
+ * Puedes establecer su URL con el parámetro `redoc_url`.
+ * Puedes deshabilitarla estableciendo `redoc_url=None`.
+
+Por ejemplo, para configurar Swagger UI para que se sirva en `/documentation` y deshabilitar ReDoc:
+
+{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}
diff --git a/docs/es/docs/tutorial/middleware.md b/docs/es/docs/tutorial/middleware.md
new file mode 100644
index 0000000000000..4729cadc00448
--- /dev/null
+++ b/docs/es/docs/tutorial/middleware.md
@@ -0,0 +1,95 @@
+# Middleware { #middleware }
+
+Puedes añadir middleware a las aplicaciones de **FastAPI**.
+
+Un "middleware" es una función que trabaja con cada **request** antes de que sea procesada por cualquier *path operation* específica. Y también con cada **response** antes de devolverla.
+
+* Toma cada **request** que llega a tu aplicación.
+* Puede entonces hacer algo a esa **request** o ejecutar cualquier código necesario.
+* Luego pasa la **request** para que sea procesada por el resto de la aplicación (por alguna *path operation*).
+* Después toma la **response** generada por la aplicación (por alguna *path operation*).
+* Puede hacer algo a esa **response** o ejecutar cualquier código necesario.
+* Luego devuelve la **response**.
+
+/// note | Detalles Técnicos
+
+Si tienes dependencias con `yield`, el código de salida se ejecutará *después* del middleware.
+
+Si hubiera tareas en segundo plano (cubiertas en la sección [Tareas en segundo plano](background-tasks.md), lo verás más adelante), se ejecutarán *después* de todo el middleware.
+
+///
+
+## Crear un middleware { #create-a-middleware }
+
+Para crear un middleware usas el decorador `@app.middleware("http")` encima de una función.
+
+La función middleware recibe:
+
+* La `request`.
+* Una función `call_next` que recibirá la `request` como parámetro.
+ * Esta función pasará la `request` a la correspondiente *path operation*.
+ * Luego devuelve la `response` generada por la correspondiente *path operation*.
+* Puedes entonces modificar aún más la `response` antes de devolverla.
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}
+
+/// tip | Consejo
+
+Ten en cuenta que los custom proprietary headers se pueden añadir [usando el prefijo `X-`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers).
+
+Pero si tienes custom headers que deseas que un cliente en un navegador pueda ver, necesitas añadirlos a tus configuraciones de CORS ([CORS (Cross-Origin Resource Sharing)](cors.md)) usando el parámetro `expose_headers` documentado en [la documentación de CORS de Starlette](https://www.starlette.dev/middleware/#corsmiddleware).
+
+///
+
+/// note | Detalles Técnicos
+
+También podrías usar `from starlette.requests import Request`.
+
+**FastAPI** lo proporciona como una conveniencia para ti, el desarrollador. Pero viene directamente de Starlette.
+
+///
+
+### Antes y después de la `response` { #before-and-after-the-response }
+
+Puedes añadir código que se ejecute con la `request`, antes de que cualquier *path operation* la reciba.
+
+Y también después de que se genere la `response`, antes de devolverla.
+
+Por ejemplo, podrías añadir un custom header `X-Process-Time` que contenga el tiempo en segundos que tomó procesar la request y generar una response:
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}
+
+/// tip | Consejo
+
+Aquí usamos [`time.perf_counter()`](https://docs.python.org/3/library/time.html#time.perf_counter) en lugar de `time.time()` porque puede ser más preciso para estos casos de uso. 🤓
+
+///
+
+## Orden de ejecución con múltiples middlewares { #multiple-middleware-execution-order }
+
+Cuando añades múltiples middlewares usando ya sea el decorador `@app.middleware()` o el método `app.add_middleware()`, cada nuevo middleware envuelve la aplicación, formando un stack. El último middleware añadido es el más externo, y el primero es el más interno.
+
+En el camino de la request, el middleware más externo se ejecuta primero.
+
+En el camino de la response, se ejecuta al final.
+
+Por ejemplo:
+
+```Python
+app.add_middleware(MiddlewareA)
+app.add_middleware(MiddlewareB)
+```
+
+Esto da como resultado el siguiente orden de ejecución:
+
+* **Request**: MiddlewareB → MiddlewareA → ruta
+
+* **Response**: ruta → MiddlewareA → MiddlewareB
+
+Este comportamiento de apilamiento asegura que los middlewares se ejecuten en un orden predecible y controlable.
+
+## Otros middlewares { #other-middlewares }
+
+Más adelante puedes leer sobre otros middlewares en la [Guía del Usuario Avanzado: Middleware Avanzado](../advanced/middleware.md).
+
+Leerás sobre cómo manejar CORS con un middleware en la siguiente sección.
diff --git a/docs/es/docs/tutorial/path-operation-configuration.md b/docs/es/docs/tutorial/path-operation-configuration.md
new file mode 100644
index 0000000000000..21fd503bb747e
--- /dev/null
+++ b/docs/es/docs/tutorial/path-operation-configuration.md
@@ -0,0 +1,107 @@
+# Configuración de Path Operation { #path-operation-configuration }
+
+Hay varios parámetros que puedes pasar a tu *path operation decorator* para configurarlo.
+
+/// warning | Advertencia
+
+Ten en cuenta que estos parámetros se pasan directamente al *path operation decorator*, no a tu *path operation function*.
+
+///
+
+## Código de Estado del Response { #response-status-code }
+
+Puedes definir el `status_code` (HTTP) que se utilizará en el response de tu *path operation*.
+
+Puedes pasar directamente el código `int`, como `404`.
+
+Pero si no recuerdas para qué es cada código numérico, puedes usar las constantes atajo en `status`:
+
+{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *}
+
+Ese código de estado se usará en el response y se añadirá al esquema de OpenAPI.
+
+/// note | Detalles Técnicos
+
+También podrías usar `from starlette import status`.
+
+**FastAPI** ofrece el mismo `starlette.status` como `fastapi.status` solo por conveniencia para ti, el desarrollador. Pero viene directamente de Starlette.
+
+///
+
+## Tags { #tags }
+
+Puedes añadir tags a tu *path operation*, pasando el parámetro `tags` con un `list` de `str` (comúnmente solo una `str`):
+
+{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *}
+
+Serán añadidas al esquema de OpenAPI y usadas por las interfaces de documentación automática:
+
+
+
+### Tags con Enums { #tags-with-enums }
+
+Si tienes una gran aplicación, podrías terminar acumulando **varias tags**, y querrías asegurarte de que siempre uses la **misma tag** para *path operations* relacionadas.
+
+En estos casos, podría tener sentido almacenar las tags en un `Enum`.
+
+**FastAPI** soporta eso de la misma manera que con strings normales:
+
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
+
+## Resumen y Descripción { #summary-and-description }
+
+Puedes añadir un `summary` y `description`:
+
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *}
+
+## Descripción desde docstring { #description-from-docstring }
+
+Como las descripciones tienden a ser largas y cubrir múltiples líneas, puedes declarar la descripción de la *path operation* en la docstring de la función y **FastAPI** la leerá desde allí.
+
+Puedes escribir [Markdown](https://en.wikipedia.org/wiki/Markdown) en el docstring, se interpretará y mostrará correctamente (teniendo en cuenta la indentación del docstring).
+
+{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}
+
+Será usado en la documentación interactiva:
+
+
+
+## Descripción del Response { #response-description }
+
+Puedes especificar la descripción del response con el parámetro `response_description`:
+
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
+
+/// info | Información
+
+Ten en cuenta que `response_description` se refiere específicamente al response, mientras que `description` se refiere a la *path operation* en general.
+
+///
+
+/// check | Revisa
+
+OpenAPI especifica que cada *path operation* requiere una descripción de response.
+
+Entonces, si no proporcionas una, **FastAPI** generará automáticamente una de "Response exitoso".
+
+///
+
+
+
+## Deprecar una *path operation* { #deprecate-a-path-operation }
+
+Si necesitas marcar una *path operation* como deprecated, pero sin eliminarla, pasa el parámetro `deprecated`:
+
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
+
+Se marcará claramente como deprecado en la documentación interactiva:
+
+
+
+Revisa cómo lucen las *path operations* deprecadas y no deprecadas:
+
+
+
+## Resumen { #recap }
+
+Puedes configurar y añadir metadatos a tus *path operations* fácilmente pasando parámetros a los *path operation decorators*.
diff --git a/docs/es/docs/tutorial/path-params-numeric-validations.md b/docs/es/docs/tutorial/path-params-numeric-validations.md
new file mode 100644
index 0000000000000..5e7b9a97828f1
--- /dev/null
+++ b/docs/es/docs/tutorial/path-params-numeric-validations.md
@@ -0,0 +1,154 @@
+# Parámetros de Path y Validaciones Numéricas { #path-parameters-and-numeric-validations }
+
+De la misma manera que puedes declarar más validaciones y metadatos para los parámetros de query con `Query`, puedes declarar el mismo tipo de validaciones y metadatos para los parámetros de path con `Path`.
+
+## Importar `Path` { #import-path }
+
+Primero, importa `Path` de `fastapi`, e importa `Annotated`:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
+
+/// info | Información
+
+FastAPI agregó soporte para `Annotated` (y comenzó a recomendar su uso) en la versión 0.95.0.
+
+Si tienes una versión anterior, obtendrás errores al intentar usar `Annotated`.
+
+Asegúrate de [Actualizar la versión de FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions) a al menos la 0.95.1 antes de usar `Annotated`.
+
+///
+
+## Declarar metadatos { #declare-metadata }
+
+Puedes declarar todos los mismos parámetros que para `Query`.
+
+Por ejemplo, para declarar un valor de metadato `title` para el parámetro de path `item_id` puedes escribir:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *}
+
+/// note | Nota
+
+Un parámetro de path siempre es requerido ya que tiene que formar parte del path. Incluso si lo declaras con `None` o le asignas un valor por defecto, no afectará en nada, siempre será requerido.
+
+///
+
+## Ordena los parámetros como necesites { #order-the-parameters-as-you-need }
+
+/// tip | Consejo
+
+Esto probablemente no es tan importante o necesario si usas `Annotated`.
+
+///
+
+Supongamos que quieres declarar el parámetro de query `q` como un `str` requerido.
+
+Y no necesitas declarar nada más para ese parámetro, así que realmente no necesitas usar `Query`.
+
+Pero aún necesitas usar `Path` para el parámetro de path `item_id`. Y no quieres usar `Annotated` por alguna razón.
+
+Python se quejará si pones un valor con "por defecto" antes de un valor que no tenga "por defecto".
+
+Pero puedes reordenarlos y poner el valor sin un valor por defecto (el parámetro de query `q`) primero.
+
+No importa para **FastAPI**. Detectará los parámetros por sus nombres, tipos y declaraciones por defecto (`Query`, `Path`, etc), no le importa el orden.
+
+Así que puedes declarar tu función como:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
+
+Pero ten en cuenta que si usas `Annotated`, no tendrás este problema, no importará ya que no estás usando los valores por defecto de los parámetros de la función para `Query()` o `Path()`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
+
+## Ordena los parámetros como necesites, trucos { #order-the-parameters-as-you-need-tricks }
+
+/// tip | Consejo
+
+Esto probablemente no es tan importante o necesario si usas `Annotated`.
+
+///
+
+Aquí hay un **pequeño truco** que puede ser útil, pero no lo necesitarás a menudo.
+
+Si quieres:
+
+* declarar el parámetro de query `q` sin un `Query` ni ningún valor por defecto
+* declarar el parámetro de path `item_id` usando `Path`
+* tenerlos en un orden diferente
+* no usar `Annotated`
+
+...Python tiene una sintaxis especial para eso.
+
+Pasa `*`, como el primer parámetro de la función.
+
+Python no hará nada con ese `*`, pero sabrá que todos los parámetros siguientes deben ser llamados como argumentos de palabras clave (parejas key-value), también conocidos como kwargs. Incluso si no tienen un valor por defecto.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
+
+### Mejor con `Annotated` { #better-with-annotated }
+
+Ten en cuenta que si usas `Annotated`, como no estás usando valores por defecto de los parámetros de la función, no tendrás este problema y probablemente no necesitarás usar `*`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
+
+## Validaciones numéricas: mayor o igual { #number-validations-greater-than-or-equal }
+
+Con `Query` y `Path` (y otros que verás más adelante) puedes declarar restricciones numéricas.
+
+Aquí, con `ge=1`, `item_id` necesitará ser un número entero "`g`reater than or `e`qual" a `1`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
+
+## Validaciones numéricas: mayor que y menor o igual { #number-validations-greater-than-and-less-than-or-equal }
+
+Lo mismo aplica para:
+
+* `gt`: `g`reater `t`han
+* `le`: `l`ess than or `e`qual
+
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
+
+## Validaciones numéricas: flotantes, mayor y menor { #number-validations-floats-greater-than-and-less-than }
+
+Las validaciones numéricas también funcionan para valores `float`.
+
+Aquí es donde se convierte en importante poder declarar gt y no solo ge. Ya que con esto puedes requerir, por ejemplo, que un valor sea mayor que `0`, incluso si es menor que `1`.
+
+Así, `0.5` sería un valor válido. Pero `0.0` o `0` no lo serían.
+
+Y lo mismo para lt.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
+
+## Resumen { #recap }
+
+Con `Query`, `Path` (y otros que aún no has visto) puedes declarar metadatos y validaciones de string de las mismas maneras que con [Parámetros de Query y Validaciones de String](query-params-str-validations.md).
+
+Y también puedes declarar validaciones numéricas:
+
+* `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 | Información
+
+`Query`, `Path` y otras clases que verás más adelante son subclases de una clase común `Param`.
+
+Todas ellas comparten los mismos parámetros para validación adicional y metadatos que has visto.
+
+///
+
+/// note | Detalles técnicos
+
+Cuando importas `Query`, `Path` y otros de `fastapi`, en realidad son funciones.
+
+Que cuando se llaman, retornan instances de clases con el mismo nombre.
+
+Así que importas `Query`, que es una función. Y cuando la llamas, retorna una instance de una clase también llamada `Query`.
+
+Estas funciones están allí (en lugar de usar simplemente las clases directamente) para que tu editor no marque errores sobre sus tipos.
+
+De esa forma puedes usar tu editor y herramientas de programación normales sin tener que agregar configuraciones personalizadas para omitir esos errores.
+
+///
diff --git a/docs/es/docs/tutorial/path-params.md b/docs/es/docs/tutorial/path-params.md
index 6432de1cdfe9b..f1aa4ef8b4391 100644
--- a/docs/es/docs/tutorial/path-params.md
+++ b/docs/es/docs/tutorial/path-params.md
@@ -1,190 +1,196 @@
-# Parámetros de path
+# Parámetros de Path { #path-parameters }
-Puedes declarar los "parámetros" o "variables" con la misma sintaxis que usan los format strings de Python:
+Puedes declarar "parámetros" o "variables" de path con la misma sintaxis que se usa en los format strings de Python:
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
-El valor del parámetro de path `item_id` será pasado a tu función como el argumento `item_id`.
+El valor del parámetro de path `item_id` se pasará a tu función como el argumento `item_id`.
-Entonces, si corres este ejemplo y vas a http://127.0.0.1:8000/items/foo, verás una respuesta de:
+Así que, si ejecutas este ejemplo y vas a [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo), verás un response de:
```JSON
{"item_id":"foo"}
```
-## Parámetros de path con tipos
+## Parámetros de path con tipos { #path-parameters-with-types }
-Puedes declarar el tipo de un parámetro de path en la función usando las anotaciones de tipos estándar de Python:
+Puedes declarar el tipo de un parámetro de path en la función, usando anotaciones de tipos estándar de Python:
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
+{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}
+
+En este caso, `item_id` se declara como un `int`.
+
+/// check | Revisa
-En este caso, `item_id` es declarado como un `int`.
+Esto te dará soporte del editor dentro de tu función, con chequeo de errores, autocompletado, etc.
-!!! check "Revisa"
- Esto te dará soporte en el editor dentro de tu función, con chequeos de errores, autocompletado, etc.
+///
-## Conversión de datos
+## Conversión de datos { #data-conversion }
-Si corres este ejemplo y abres tu navegador en http://127.0.0.1:8000/items/3 verás una respuesta de:
+Si ejecutas este ejemplo y abres tu navegador en [http://127.0.0.1:8000/items/3](http://127.0.0.1:8000/items/3), verás un response de:
```JSON
{"item_id":3}
```
-!!! check "Revisa"
- Observa que el valor que recibió (y devolvió) tu función es `3`, como un Python `int`, y no un string `"3"`.
+/// check | Revisa
- Entonces, con esa declaración de tipos **FastAPI** te da "parsing" automático del request.
+Nota que el valor que tu función recibió (y devolvió) es `3`, como un `int` de Python, no un string `"3"`.
-## Validación de datos
+Entonces, con esa declaración de tipo, **FastAPI** te ofrece "parsing" automático de request.
-Pero si abres tu navegador en http://127.0.0.1:8000/items/foo verás este lindo error de HTTP:
+///
+
+## Validación de datos { #data-validation }
+
+Pero si vas al navegador en [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo), verás un bonito error HTTP de:
```JSON
{
- "detail": [
- {
- "loc": [
- "path",
- "item_id"
- ],
- "msg": "value is not a valid integer",
- "type": "type_error.integer"
- }
- ]
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo"
+ }
+ ]
}
```
-debido a que el parámetro de path `item_id` tenía el valor `"foo"`, que no es un `int`.
+porque el parámetro de path `item_id` tenía un valor de `"foo"`, que no es un `int`.
+
+El mismo error aparecería si proporcionaras un `float` en lugar de un `int`, como en: [http://127.0.0.1:8000/items/4.2](http://127.0.0.1:8000/items/4.2)
-El mismo error aparecería si pasaras un `float` en vez de un `int` como en: http://127.0.0.1:8000/items/4.2
+/// check | Revisa
-!!! check "Revisa"
- Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos.
+Entonces, con la misma declaración de tipo de Python, **FastAPI** te ofrece validación de datos.
- Observa que el error también muestra claramente el punto exacto en el que no pasó la validación.
+Nota que el error también indica claramente el punto exacto donde la validación falló.
- Esto es increíblemente útil cuando estás desarrollando y debugging código que interactúa con tu API.
+Esto es increíblemente útil mientras desarrollas y depuras código que interactúa con tu API.
-## Documentación
+///
-Cuando abras tu navegador en http://127.0.0.1:8000/docs verás la documentación automática e interactiva del API como:
+## Documentación { #documentation }
+
+Y cuando abras tu navegador en [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs), verás una documentación de API automática e interactiva como:
-!!! check "Revisa"
- Nuevamente, con la misma declaración de tipo de Python, **FastAPI** te da documentación automática e interactiva (integrándose con Swagger UI)
+/// check | Revisa
+
+Nuevamente, solo con esa misma declaración de tipo de Python, **FastAPI** te ofrece documentación automática e interactiva (integrando Swagger UI).
+
+Nota que el parámetro de path está declarado como un entero.
- Observa que el parámetro de path está declarado como un integer.
+///
-## Beneficios basados en estándares, documentación alternativa
+## Beneficios basados en estándares, documentación alternativa { #standards-based-benefits-alternative-documentation }
-Debido a que el schema generado es del estándar OpenAPI hay muchas herramientas compatibles.
+Y porque el esquema generado es del estándar [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md), hay muchas herramientas compatibles.
-Es por esto que **FastAPI** mismo provee una documentación alternativa de la API (usando ReDoc), a la que puedes acceder en http://127.0.0.1:8000/redoc:
+Debido a esto, el propio **FastAPI** proporciona una documentación de API alternativa (usando ReDoc), a la cual puedes acceder en [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc):
-De la misma manera hay muchas herramientas compatibles. Incluyendo herramientas de generación de código para muchos lenguajes.
+De la misma manera, hay muchas herramientas compatibles. Incluyendo herramientas de generación de código para muchos lenguajes.
-## Pydantic
+## Pydantic { #pydantic }
-Toda la validación de datos es realizada tras bastidores por Pydantic, así que obtienes todos sus beneficios. Así sabes que estás en buenas manos.
+Toda la validación de datos se realiza internamente con [Pydantic](https://docs.pydantic.dev/), así que obtienes todos los beneficios de esta. Y sabes que estás en buenas manos.
-Puedes usar las mismas declaraciones de tipos con `str`, `float`, `bool` y otros tipos de datos más complejos.
+Puedes usar las mismas declaraciones de tipo con `str`, `float`, `bool` y muchos otros tipos de datos complejos.
-Exploraremos varios de estos tipos en los próximos capítulos del tutorial.
+Varios de estos se exploran en los siguientes capítulos del tutorial.
-## El orden importa
+## El orden importa { #order-matters }
-Cuando creas *operaciones de path* puedes encontrarte con situaciones en las que tengas un path fijo.
+Al crear *path operations*, puedes encontrarte en situaciones donde tienes un path fijo.
-Digamos algo como `/users/me` que sea para obtener datos del usuario actual.
+Como `/users/me`, imaginemos que es para obtener datos sobre el usuario actual.
-... y luego puedes tener el path `/users/{user_id}` para obtener los datos sobre un usuario específico asociados a un ID de usuario.
+Y luego también puedes tener un path `/users/{user_id}` para obtener datos sobre un usuario específico por algún ID de usuario.
-Porque las *operaciones de path* son evaluadas en orden, tienes que asegurarte de que el path para `/users/me` sea declarado antes que el path para `/users/{user_id}`:
+Debido a que las *path operations* se evalúan en orden, necesitas asegurarte de que el path para `/users/me` se declara antes que el de `/users/{user_id}`:
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
-```
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
-De otra manera el path para `/users/{user_id}` coincidiría también con `/users/me` "pensando" que está recibiendo el parámetro `user_id` con el valor `"me"`.
+De lo contrario, el path para `/users/{user_id}` también coincidiría para `/users/me`, "pensando" que está recibiendo un parámetro `user_id` con un valor de `"me"`.
-## Valores predefinidos
+De manera similar, no puedes redefinir una path operation:
-Si tienes una *operación de path* que recibe un *parámetro de path* pero quieres que los valores posibles del *parámetro de path* sean predefinidos puedes usar un `Enum` estándar de Python.
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
-### Crea una clase `Enum`
+La primera siempre será utilizada ya que el path coincide primero.
-Importa `Enum` y crea una sub-clase que herede desde `str` y desde `Enum`.
+## Valores predefinidos { #predefined-values }
-Al heredar desde `str` la documentación de la API podrá saber que los valores deben ser de tipo `string` y podrá mostrarlos correctamente.
+Si tienes una *path operation* que recibe un *path parameter*, pero quieres que los valores posibles válidos del *path parameter* estén predefinidos, puedes usar un `Enum` estándar de Python.
-Luego crea atributos de clase con valores fijos, que serán los valores disponibles válidos:
+### Crear una clase `Enum` { #create-an-enum-class }
-```Python hl_lines="1 6-9"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+Importa `Enum` y crea una subclase que herede de `str` y de `Enum`.
-!!! info "Información"
- Las Enumerations (o enums) están disponibles en Python desde la versión 3.4.
+Al heredar de `str`, la documentación de la API podrá saber que los valores deben ser de tipo `string` y podrá representarlos correctamente.
-!!! tip "Consejo"
- Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de modelos de Machine Learning.
+Luego crea atributos de clase con valores fijos, que serán los valores válidos disponibles:
-### Declara un *parámetro de path*
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
-Luego, crea un *parámetro de path* con anotaciones de tipos usando la clase enum que creaste (`ModelName`):
+/// tip | Consejo
-```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+Si te estás preguntando, "AlexNet", "ResNet" y "LeNet" son solo nombres de modelos de Machine Learning.
-### Revisa la documentación
+///
-Debido a que los valores disponibles para el *parámetro de path* están predefinidos, la documentación interactiva los puede mostrar bien:
+### Declarar un *path parameter* { #declare-a-path-parameter }
+
+Luego crea un *path parameter* con una anotación de tipo usando la clase enum que creaste (`ModelName`):
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
+
+### Revisa la documentación { #check-the-docs }
+
+Como los valores disponibles para el *path parameter* están predefinidos, la documentación interactiva puede mostrarlos de manera ordenada:
-### Trabajando con los *enumerations* de Python
+### Trabajando con *enumeraciones* de Python { #working-with-python-enumerations }
-El valor del *parámetro de path* será un *enumeration member*.
+El valor del *path parameter* será un *miembro* de enumeración.
-#### Compara *enumeration members*
+#### Comparar *miembros* de enumeraciones { #compare-enumeration-members }
-Puedes compararlo con el *enumeration member* en el enum (`ModelName`) que creaste:
+Puedes compararlo con el *miembro* de enumeración en tu enum creada `ModelName`:
-```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}
-#### Obtén el *enumeration value*
+#### Obtener el valor de *enumeración* { #get-the-enumeration-value }
-Puedes obtener el valor exacto (un `str` en este caso) usando `model_name.value`, o en general, `your_enum_member.value`:
+Puedes obtener el valor actual (un `str` en este caso) usando `model_name.value`, o en general, `your_enum_member.value`:
-```Python hl_lines="20"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}
-!!! tip "Consejo"
- También podrías obtener el valor `"lenet"` con `ModelName.lenet.value`.
+/// tip | Consejo
-#### Devuelve *enumeration members*
+También podrías acceder al valor `"lenet"` con `ModelName.lenet.value`.
-Puedes devolver *enum members* desde tu *operación de path* inclusive en un body de JSON anidado (por ejemplo, un `dict`).
+///
-Ellos serán convertidos a sus valores correspondientes (strings en este caso) antes de devolverlos al cliente:
+#### Devolver *miembros* de enumeración { #return-enumeration-members }
-```Python hl_lines="18 21 23"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+Puedes devolver *miembros de enum* desde tu *path operation*, incluso anidados en un cuerpo JSON (por ejemplo, un `dict`).
+
+Serán convertidos a sus valores correspondientes (cadenas en este caso) antes de devolverlos al cliente:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}
-En tu cliente obtendrás una respuesta en JSON como:
+En tu cliente recibirás un response JSON como:
```JSON
{
@@ -193,52 +199,53 @@ En tu cliente obtendrás una respuesta en JSON como:
}
```
-## Parámetros de path parameters que contienen paths
+## Parámetros de path conteniendo paths { #path-parameters-containing-paths }
-Digamos que tienes una *operación de path* con un path `/files/{file_path}`.
+Imaginemos que tienes una *path operation* con un path `/files/{file_path}`.
-Pero necesitas que el mismo `file_path` contenga un path como `home/johndoe/myfile.txt`.
+Pero necesitas que `file_path` en sí mismo contenga un *path*, como `home/johndoe/myfile.txt`.
Entonces, la URL para ese archivo sería algo como: `/files/home/johndoe/myfile.txt`.
-### Soporte de OpenAPI
+### Soporte de OpenAPI { #openapi-support }
-OpenAPI no soporta una manera de declarar un *parámetro de path* que contenga un path, dado que esto podría llevar a escenarios que son difíciles de probar y definir.
+OpenAPI no soporta una manera de declarar un *path parameter* para que contenga un *path* dentro, ya que eso podría llevar a escenarios que son difíciles de probar y definir.
-Sin embargo, lo puedes hacer en **FastAPI** usando una de las herramientas internas de Starlette.
+Sin embargo, todavía puedes hacerlo en **FastAPI**, usando una de las herramientas internas de Starlette.
-La documentación seguirá funcionando, aunque no añadirá ninguna información diciendo que el parámetro debería contener un path.
+Y la documentación seguiría funcionando, aunque no agregue ninguna documentación indicando que el parámetro debe contener un path.
-### Convertidor de path
+### Convertidor de Path { #path-convertor }
-Usando una opción directamente desde Starlette puedes declarar un *parámetro de path* que contenga un path usando una URL como:
+Usando una opción directamente de Starlette puedes declarar un *path parameter* conteniendo un *path* usando una URL como:
```
/files/{file_path:path}
```
-En este caso el nombre del parámetro es `file_path` y la última parte, `:path`, le dice que el parámetro debería coincidir con cualquier path.
+En este caso, el nombre del parámetro es `file_path`, y la última parte, `:path`, indica que el parámetro debería coincidir con cualquier *path*.
-Entonces lo puedes usar con:
+Así que, puedes usarlo con:
-```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
-```
+{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}
+
+/// tip | Consejo
+
+Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt`, con una barra inclinada (`/`) inicial.
-!!! tip "Consejo"
- Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt` con un slash inicial (`/`).
+En ese caso, la URL sería: `/files//home/johndoe/myfile.txt`, con una doble barra inclinada (`//`) entre `files` y `home`.
- En este caso la URL sería `/files//home/johndoe/myfile.txt` con un slash doble (`//`) entre `files` y `home`.
+///
-## Repaso
+## Resumen { #recap }
-Con **FastAPI**, usando declaraciones de tipo de Python intuitivas y estándares, obtienes:
+Con **FastAPI**, al usar declaraciones de tipo estándar de Python, cortas e intuitivas, obtienes:
-* Soporte en el editor: chequeos de errores, auto-completado, etc.
-* "Parsing" de datos
+* Soporte del editor: chequeo de errores, autocompletado, etc.
+* " parsing " de datos
* Validación de datos
-* Anotación de la API y documentación automática
+* Anotación de API y documentación automática
-Solo tienes que declararlos una vez.
+Y solo tienes que declararlos una vez.
-Esa es probablemente la principal ventaja visible de **FastAPI** sobre otros frameworks alternativos (aparte del rendimiento puro).
+Probablemente esa sea la principal ventaja visible de **FastAPI** en comparación con otros frameworks alternativos (aparte del rendimiento bruto).
diff --git a/docs/es/docs/tutorial/query-param-models.md b/docs/es/docs/tutorial/query-param-models.md
new file mode 100644
index 0000000000000..e335cfe61ea75
--- /dev/null
+++ b/docs/es/docs/tutorial/query-param-models.md
@@ -0,0 +1,68 @@
+# Modelos de Parámetros Query { #query-parameter-models }
+
+Si tienes un grupo de **parámetros query** que están relacionados, puedes crear un **modelo de Pydantic** para declararlos.
+
+Esto te permitiría **reutilizar el modelo** en **múltiples lugares** y también declarar validaciones y metadatos para todos los parámetros de una vez. 😎
+
+/// note | Nota
+
+Esto es compatible desde la versión `0.115.0` de FastAPI. 🤓
+
+///
+
+## Parámetros Query con un Modelo Pydantic { #query-parameters-with-a-pydantic-model }
+
+Declara los **parámetros query** que necesitas en un **modelo de Pydantic**, y luego declara el parámetro como `Query`:
+
+{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}
+
+**FastAPI** **extraerá** los datos para **cada campo** de los **parámetros query** en el request y te proporcionará el modelo de Pydantic que definiste.
+
+## Revisa la Documentación { #check-the-docs }
+
+Puedes ver los parámetros query en la UI de documentación en `/docs`:
+
+
+
+
+### Lista de parámetros de Query / múltiples valores con valores por defecto { #query-parameter-list-multiple-values-with-defaults }
+
+También puedes definir un valor por defecto `list` de valores si no se proporciona ninguno:
+
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
+
+Si vas a:
+
+```
+http://localhost:8000/items/
+```
+
+el valor por defecto de `q` será: `["foo", "bar"]` y tu response será:
+
+```JSON
+{
+ "q": [
+ "foo",
+ "bar"
+ ]
+}
+```
+
+#### Usando solo `list` { #using-just-list }
+
+También puedes usar `list` directamente en lugar de `list[str]`:
+
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
+
+/// note | Nota
+
+Ten en cuenta que en este caso, FastAPI no comprobará el contenido de la list.
+
+Por ejemplo, `list[int]` comprobaría (y documentaría) que el contenido de la list son enteros. Pero `list` sola no lo haría.
+
+///
+
+## Declarar más metadatos { #declare-more-metadata }
+
+Puedes agregar más información sobre el parámetro.
+
+Esa información se incluirá en el OpenAPI generado y será utilizada por las interfaces de usuario de documentación y herramientas externas.
+
+/// note | Nota
+
+Ten en cuenta que diferentes herramientas podrían tener diferentes niveles de soporte de OpenAPI.
+
+Algunas de ellas podrían no mostrar toda la información extra declarada todavía, aunque en la mayoría de los casos, la funcionalidad faltante ya está planificada para desarrollo.
+
+///
+
+Puedes agregar un `title`:
+
+{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *}
+
+Y una `description`:
+
+{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *}
+
+## Alias para parámetros { #alias-parameters }
+
+Imagina que quieres que el parámetro sea `item-query`.
+
+Como en:
+
+```
+http://127.0.0.1:8000/items/?item-query=foobaritems
+```
+
+Pero `item-query` no es un nombre de variable válido en Python.
+
+Lo más cercano sería `item_query`.
+
+Pero aún necesitas que sea exactamente `item-query`...
+
+Entonces puedes declarar un `alias`, y ese alias será usado para encontrar el valor del parámetro:
+
+{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *}
+
+## Declarar parámetros obsoletos { #deprecating-parameters }
+
+Ahora digamos que ya no te gusta este parámetro.
+
+Tienes que dejarlo allí por un tiempo porque hay clientes usándolo, pero quieres que la documentación lo muestre claramente como obsoleto.
+
+Luego pasa el parámetro `deprecated=True` a `Query`:
+
+{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *}
+
+La documentación lo mostrará así:
+
+
+
+## Excluir parámetros de OpenAPI { #exclude-parameters-from-openapi }
+
+Para excluir un parámetro de query del esquema de OpenAPI generado (y por lo tanto, de los sistemas de documentación automática), establece el parámetro `include_in_schema` de `Query` a `False`:
+
+{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *}
+
+## Validación personalizada { #custom-validation }
+
+Podría haber casos donde necesites hacer alguna validación personalizada que no puede hacerse con los parámetros mostrados arriba.
+
+En esos casos, puedes usar una función validadora personalizada que se aplique después de la validación normal (por ejemplo, después de validar que el valor es un `str`).
+
+Puedes lograr eso usando [`AfterValidator` de Pydantic](https://docs.pydantic.dev/latest/concepts/validators/#field-after-validator) dentro de `Annotated`.
+
+/// tip | Consejo
+
+Pydantic también tiene [`BeforeValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-before-validator) y otros. 🤓
+
+///
+
+Por ejemplo, este validador personalizado comprueba que el ID del ítem empiece con `isbn-` para un número de libro ISBN o con `imdb-` para un ID de URL de película de IMDB:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
+
+/// info | Información
+
+Esto está disponible con Pydantic versión 2 o superior. 😎
+
+///
+
+/// tip | Consejo
+
+Si necesitas hacer cualquier tipo de validación que requiera comunicarte con algún componente externo, como una base de datos u otra API, deberías usar Dependencias de FastAPI, las aprenderás más adelante.
+
+Estos validadores personalizados son para cosas que pueden comprobarse solo con los mismos datos provistos en el request.
+
+///
+
+### Entiende ese código { #understand-that-code }
+
+El punto importante es solo usar `AfterValidator` con una función dentro de `Annotated`. Si quieres, sáltate esta parte. 🤸
+
+---
+
+Pero si te da curiosidad este ejemplo de código específico y sigues entretenido, aquí tienes algunos detalles extra.
+
+#### String con `value.startswith()` { #string-with-value-startswith }
+
+¿Lo notaste? un string usando `value.startswith()` puede recibir una tupla, y comprobará cada valor en la tupla:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *}
+
+#### Un ítem aleatorio { #a-random-item }
+
+Con `data.items()` obtenemos un objeto iterable con tuplas que contienen la clave y el valor para cada elemento del diccionario.
+
+Convertimos este objeto iterable en una `list` propiamente dicha con `list(data.items())`.
+
+Luego con `random.choice()` podemos obtener un valor aleatorio de la lista, así que obtenemos una tupla con `(id, name)`. Será algo como `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")`.
+
+Luego asignamos esos dos valores de la tupla a las variables `id` y `name`.
+
+Así, si el usuario no proporcionó un ID de ítem, aún recibirá una sugerencia aleatoria.
+
+...hacemos todo esto en una sola línea simple. 🤯 ¿No te encanta Python? 🐍
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *}
+
+## Recapitulación { #recap }
+
+Puedes declarar validaciones y metadatos adicionales para tus parámetros.
+
+Validaciones genéricas y metadatos:
+
+* `alias`
+* `title`
+* `description`
+* `deprecated`
+
+Validaciones específicas para strings:
+
+* `min_length`
+* `max_length`
+* `pattern`
+
+Validaciones personalizadas usando `AfterValidator`.
+
+En estos ejemplos viste cómo declarar validaciones para valores de tipo `str`.
+
+Mira los siguientes capítulos para aprender cómo declarar validaciones para otros tipos, como números.
diff --git a/docs/es/docs/tutorial/query-params.md b/docs/es/docs/tutorial/query-params.md
index 482af8dc06f74..2dbb04ef45f87 100644
--- a/docs/es/docs/tutorial/query-params.md
+++ b/docs/es/docs/tutorial/query-params.md
@@ -1,12 +1,10 @@
-# Parámetros de query
+# Parámetros de Query { #query-parameters }
-Cuando declaras otros parámetros de la función que no hacen parte de los parámetros de path estos se interpretan automáticamente como parámetros de "query".
+Cuando declaras otros parámetros de función que no son parte de los parámetros de path, son automáticamente interpretados como parámetros de "query".
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial001.py!}
-```
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
-El query es el conjunto de pares de key-value que van después del `?` en la URL, separados por caracteres `&`.
+La query es el conjunto de pares clave-valor que van después del `?` en una URL, separados por caracteres `&`.
Por ejemplo, en la URL:
@@ -19,36 +17,36 @@ http://127.0.0.1:8000/items/?skip=0&limit=10
* `skip`: con un valor de `0`
* `limit`: con un valor de `10`
-Dado que son parte de la URL son strings "naturalmente".
+Como son parte de la URL, son "naturalmente" strings.
-Pero cuando los declaras con tipos de Python (en el ejemplo arriba, como `int`) son convertidos a ese tipo y son validados con él.
+Pero cuando los declaras con tipos de Python (en el ejemplo anterior, como `int`), son convertidos a ese tipo y validados respecto a él.
-Todo el proceso que aplicaba a los parámetros de path también aplica a los parámetros de query:
+Todo el mismo proceso que se aplica para los parámetros de path también se aplica para los parámetros de query:
* Soporte del editor (obviamente)
-* "Parsing" de datos
+* "parsing" de datos
* Validación de datos
* Documentación automática
-## Configuraciones por defecto
+## Valores por defecto { #defaults }
-Como los parámetros de query no están fijos en una parte del path pueden ser opcionales y pueden tener valores por defecto.
+Como los parámetros de query no son una parte fija de un path, pueden ser opcionales y pueden tener valores por defecto.
-El ejemplo arriba tiene `skip=0` y `limit=10` como los valores por defecto.
+En el ejemplo anterior, tienen valores por defecto de `skip=0` y `limit=10`.
-Entonces, si vas a la URL:
+Entonces, ir a la URL:
```
http://127.0.0.1:8000/items/
```
-Sería lo mismo que ir a:
+sería lo mismo que ir a:
```
http://127.0.0.1:8000/items/?skip=0&limit=10
```
-Pero, si por ejemplo vas a:
+Pero si vas a, por ejemplo:
```
http://127.0.0.1:8000/items/?skip=20
@@ -56,34 +54,28 @@ http://127.0.0.1:8000/items/?skip=20
Los valores de los parámetros en tu función serán:
-* `skip=20`: porque lo definiste en la URL
-* `limit=10`: porque era el valor por defecto
+* `skip=20`: porque lo configuraste en la URL
+* `limit=10`: porque ese era el valor por defecto
-## Parámetros opcionales
+## Parámetros opcionales { #optional-parameters }
-Del mismo modo puedes declarar parámetros de query opcionales definiendo el valor por defecto como `None`:
+De la misma manera, puedes declarar parámetros de query opcionales, estableciendo su valor por defecto en `None`:
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial002.py!}
-```
+{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *}
-En este caso el parámetro de la función `q` será opcional y será `None` por defecto.
+En este caso, el parámetro de función `q` será opcional y será `None` por defecto.
-!!! check "Revisa"
- También puedes notar que **FastAPI** es lo suficientemente inteligente para darse cuenta de que el parámetro de path `item_id` es un parámetro de path y que `q` no lo es, y por lo tanto es un parámetro de query.
+/// check | Revisa
-!!! note "Nota"
- FastAPI sabrá que `q` es opcional por el `= None`.
+Además, nota que **FastAPI** es lo suficientemente inteligente para notar que el parámetro de path `item_id` es un parámetro de path y `q` no lo es, por lo tanto, es un parámetro de query.
- El `Union` en `Union[str, None]` no es usado por FastAPI (FastAPI solo usará la parte `str`), pero el `Union[str, None]` le permitirá a tu editor ayudarte a encontrar errores en tu código.
+///
-## Conversión de tipos de parámetros de query
+## Conversión de tipos en parámetros de query { #query-parameter-type-conversion }
-También puedes declarar tipos `bool` y serán convertidos:
+También puedes declarar tipos `bool`, y serán convertidos:
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial003.py!}
-```
+{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *}
En este caso, si vas a:
@@ -115,58 +107,55 @@ o
http://127.0.0.1:8000/items/foo?short=yes
```
-o cualquier otra variación (mayúsculas, primera letra en mayúscula, etc.) tu función verá el parámetro `short` con un valor `bool` de `True`. Si no, lo verá como `False`.
+o cualquier otra variación (mayúsculas, primera letra en mayúscula, etc.), tu función verá el parámetro `short` con un valor `bool` de `True`. De lo contrario, será `False`.
-## Múltiples parámetros de path y query
+## Múltiples parámetros de path y de query { #multiple-path-and-query-parameters }
-Puedes declarar múltiples parámetros de path y parámetros de query al mismo tiempo. **FastAPI** sabe cuál es cuál.
+Puedes declarar múltiples parámetros de path y de query al mismo tiempo, **FastAPI** sabe cuál es cuál.
-No los tienes que declarar en un orden específico.
+Y no tienes que declararlos en un orden específico.
Serán detectados por nombre:
-```Python hl_lines="8 10"
-{!../../../docs_src/query_params/tutorial004.py!}
-```
+{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *}
-## Parámetros de query requeridos
+## Parámetros de query requeridos { #required-query-parameters }
-Cuando declaras un valor por defecto para los parámetros que no son de path (por ahora solo hemos visto parámetros de query), entonces no es requerido.
+Cuando declaras un valor por defecto para parámetros que no son de path (por ahora, solo hemos visto parámetros de query), entonces no es requerido.
-Si no quieres añadir un valor específico sino solo hacerlo opcional, pon el valor por defecto como `None`.
+Si no quieres agregar un valor específico pero solo hacer que sea opcional, establece el valor por defecto como `None`.
-Pero cuando quieres hacer que un parámetro de query sea requerido, puedes simplemente no declararle un valor por defecto:
+Pero cuando quieres hacer un parámetro de query requerido, simplemente no declares ningún valor por defecto:
-```Python hl_lines="6-7"
-{!../../../docs_src/query_params/tutorial005.py!}
-```
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
-Aquí el parámetro de query `needy` es un parámetro de query requerido, del tipo `str`.
+Aquí el parámetro de query `needy` es un parámetro de query requerido de tipo `str`.
-Si abres tu navegador en una URL como:
+Si abres en tu navegador una URL como:
```
http://127.0.0.1:8000/items/foo-item
```
-...sin añadir el parámetro `needy` requerido, verás un error como:
+...sin agregar el parámetro requerido `needy`, verás un error como:
```JSON
{
- "detail": [
- {
- "loc": [
- "query",
- "needy"
- ],
- "msg": "field required",
- "type": "value_error.missing"
- }
- ]
+ "detail": [
+ {
+ "type": "missing",
+ "loc": [
+ "query",
+ "needy"
+ ],
+ "msg": "Field required",
+ "input": null
+ }
+ ]
}
```
-Dado que `needy` es un parámetro requerido necesitarías declararlo en la URL:
+Como `needy` es un parámetro requerido, necesitarías establecerlo en la URL:
```
http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
@@ -181,17 +170,18 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
}
```
-Por supuesto que también puedes definir algunos parámetros como requeridos, con un valor por defecto y otros completamente opcionales:
+Y por supuesto, puedes definir algunos parámetros como requeridos, algunos con un valor por defecto, y algunos enteramente opcionales:
-```Python hl_lines="10"
-{!../../../docs_src/query_params/tutorial006.py!}
-```
+{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *}
-En este caso hay 3 parámetros de query:
+En este caso, hay 3 parámetros de query:
* `needy`, un `str` requerido.
* `skip`, un `int` con un valor por defecto de `0`.
* `limit`, un `int` opcional.
-!!! tip "Consejo"
- También podrías usar los `Enum`s de la misma manera que con los [Parámetros de path](path-params.md#predefined-values){.internal-link target=_blank}.
+/// tip | Consejo
+
+También podrías usar `Enum`s de la misma manera que con [Parámetros de Path](path-params.md#predefined-values).
+
+///
diff --git a/docs/es/docs/tutorial/request-files.md b/docs/es/docs/tutorial/request-files.md
new file mode 100644
index 0000000000000..8bfc7a772ee38
--- /dev/null
+++ b/docs/es/docs/tutorial/request-files.md
@@ -0,0 +1,176 @@
+# Archivos de Request { #request-files }
+
+Puedes definir archivos que serán subidos por el cliente utilizando `File`.
+
+/// info | Información
+
+Para recibir archivos subidos, primero instala [`python-multipart`](https://github.com/Kludex/python-multipart).
+
+Asegúrate de crear un [entorno virtual](../virtual-environments.md), activarlo y luego instalarlo, por ejemplo:
+
+```console
+$ pip install python-multipart
+```
+
+Esto es porque los archivos subidos se envían como "form data".
+
+///
+
+## Importar `File` { #import-file }
+
+Importa `File` y `UploadFile` desde `fastapi`:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
+
+## Definir Parámetros `File` { #define-file-parameters }
+
+Crea parámetros de archivo de la misma manera que lo harías para `Body` o `Form`:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
+
+/// info | Información
+
+`File` es una clase que hereda directamente de `Form`.
+
+Pero recuerda que cuando importas `Query`, `Path`, `File` y otros desde `fastapi`, esos son en realidad funciones que devuelven clases especiales.
+
+///
+
+/// tip | Consejo
+
+Para declarar cuerpos de File, necesitas usar `File`, porque de otra manera los parámetros serían interpretados como parámetros query o parámetros de cuerpo (JSON).
+
+///
+
+Los archivos se subirán como "form data".
+
+Si declaras el tipo de tu parámetro de *path operation function* como `bytes`, **FastAPI** leerá el archivo por ti y recibirás el contenido como `bytes`.
+
+Ten en cuenta que esto significa que todo el contenido se almacenará en memoria. Esto funcionará bien para archivos pequeños.
+
+Pero hay varios casos en los que podrías beneficiarte de usar `UploadFile`.
+
+## Parámetros de Archivo con `UploadFile` { #file-parameters-with-uploadfile }
+
+Define un parámetro de archivo con un tipo de `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
+
+Usar `UploadFile` tiene varias ventajas sobre `bytes`:
+
+* No tienes que usar `File()` en el valor por defecto del parámetro.
+* Usa un archivo "spooled":
+ * Un archivo almacenado en memoria hasta un límite de tamaño máximo, y después de superar este límite, se almacenará en el disco.
+* Esto significa que funcionará bien para archivos grandes como imágenes, videos, binarios grandes, etc. sin consumir toda la memoria.
+* Puedes obtener metadatos del archivo subido.
+* Tiene una interfaz `async` [parecida a un archivo](https://docs.python.org/3/glossary.html#term-file-like-object).
+* Expone un objeto Python real [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) que puedes pasar directamente a otros paquetes que esperan un objeto parecido a un archivo.
+
+### `UploadFile` { #uploadfile }
+
+`UploadFile` tiene los siguientes atributos:
+
+* `filename`: Un `str` con el nombre original del archivo que fue subido (por ejemplo, `myimage.jpg`).
+* `content_type`: Un `str` con el tipo de contenido (MIME type / media type) (por ejemplo, `image/jpeg`).
+* `file`: Un [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) (un objeto [parecido a un archivo](https://docs.python.org/3/glossary.html#term-file-like-object)). Este es el objeto de archivo Python real que puedes pasar directamente a otras funciones o paquetes que esperan un objeto "parecido a un archivo".
+
+`UploadFile` tiene los siguientes métodos `async`. Todos ellos llaman a los métodos correspondientes del archivo por debajo (usando el `SpooledTemporaryFile` interno).
+
+* `write(data)`: Escribe `data` (`str` o `bytes`) en el archivo.
+* `read(size)`: Lee `size` (`int`) bytes/caracteres del archivo.
+* `seek(offset)`: Va a la posición de bytes `offset` (`int`) en el archivo.
+ * Por ejemplo, `await myfile.seek(0)` iría al inicio del archivo.
+ * Esto es especialmente útil si ejecutas `await myfile.read()` una vez y luego necesitas leer el contenido nuevamente.
+* `close()`: Cierra el archivo.
+
+Como todos estos métodos son métodos `async`, necesitas "await" para ellos.
+
+Por ejemplo, dentro de una *path operation function* `async` puedes obtener los contenidos con:
+
+```Python
+contents = await myfile.read()
+```
+
+Si estás dentro de una *path operation function* normal `def`, puedes acceder al `UploadFile.file` directamente, por ejemplo:
+
+```Python
+contents = myfile.file.read()
+```
+
+/// note | Detalles Técnicos de `async`
+
+Cuando usas los métodos `async`, **FastAPI** ejecuta los métodos del archivo en un threadpool y los espera.
+
+///
+
+/// note | Detalles Técnicos de Starlette
+
+El `UploadFile` de **FastAPI** hereda directamente del `UploadFile` de **Starlette**, pero añade algunas partes necesarias para hacerlo compatible con **Pydantic** y las otras partes de FastAPI.
+
+///
+
+## Qué es "Form Data" { #what-is-form-data }
+
+La manera en que los formularios de HTML (``) envían los datos al servidor normalmente utiliza una codificación "especial" para esos datos, es diferente de JSON.
+
+**FastAPI** se asegurará de leer esos datos del lugar correcto en lugar de JSON.
+
+/// note | Detalles Técnicos
+
+Los datos de los forms normalmente se codifican usando el "media type" `application/x-www-form-urlencoded` cuando no incluyen archivos.
+
+Pero cuando el formulario incluye archivos, se codifica como `multipart/form-data`. Si usas `File`, **FastAPI** sabrá que tiene que obtener los archivos de la parte correcta del cuerpo.
+
+Si deseas leer más sobre estas codificaciones y campos de formularios, dirígete a la [MDN web docs para `POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST).
+
+///
+
+/// warning | Advertencia
+
+Puedes declarar múltiples parámetros `File` y `Form` en una *path operation*, pero no puedes declarar campos `Body` que esperas recibir como JSON, ya que el request tendrá el cuerpo codificado usando `multipart/form-data` en lugar de `application/json`.
+
+Esto no es una limitación de **FastAPI**, es parte del protocolo HTTP.
+
+///
+
+## Subida de Archivos Opcional { #optional-file-upload }
+
+Puedes hacer un archivo opcional utilizando anotaciones de tipos estándar y estableciendo un valor por defecto de `None`:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## `UploadFile` con Metadatos Adicionales { #uploadfile-with-additional-metadata }
+
+También puedes usar `File()` con `UploadFile`, por ejemplo, para establecer metadatos adicionales:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
+
+## Subidas de Múltiples Archivos { #multiple-file-uploads }
+
+Es posible subir varios archivos al mismo tiempo.
+
+Estarían asociados al mismo "campo de formulario" enviado usando "form data".
+
+Para usar eso, declara una `list` de `bytes` o `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
+
+Recibirás, como se declaró, una `list` de `bytes` o `UploadFile`s.
+
+/// note | Detalles Técnicos
+
+También podrías usar `from starlette.responses import HTMLResponse`.
+
+**FastAPI** proporciona las mismas `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette.
+
+///
+
+### Subidas de Múltiples Archivos con Metadatos Adicionales { #multiple-file-uploads-with-additional-metadata }
+
+Y de la misma manera que antes, puedes usar `File()` para establecer parámetros adicionales, incluso para `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
+
+## Recapitulación { #recap }
+
+Usa `File`, `bytes` y `UploadFile` para declarar archivos que se subirán en el request, enviados como form data.
diff --git a/docs/es/docs/tutorial/request-form-models.md b/docs/es/docs/tutorial/request-form-models.md
new file mode 100644
index 0000000000000..b20421bd01095
--- /dev/null
+++ b/docs/es/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Modelos de Formulario { #form-models }
+
+Puedes usar **modelos de Pydantic** para declarar **campos de formulario** en FastAPI.
+
+/// info | Información
+
+Para usar formularios, primero instala [`python-multipart`](https://github.com/Kludex/python-multipart).
+
+Asegúrate de crear un [entorno virtual](../virtual-environments.md), activarlo, y luego instalarlo, por ejemplo:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | Nota
+
+Esto es compatible desde la versión `0.113.0` de FastAPI. 🤓
+
+///
+
+## Modelos de Pydantic para Formularios { #pydantic-models-for-forms }
+
+Solo necesitas declarar un **modelo de Pydantic** con los campos que quieres recibir como **campos de formulario**, y luego declarar el parámetro como `Form`:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
+
+**FastAPI** **extraerá** los datos de **cada campo** de los **form data** en el request y te dará el modelo de Pydantic que definiste.
+
+## Revisa la Documentación { #check-the-docs }
+
+Puedes verificarlo en la interfaz de documentación en `/docs`:
+
+
+
+
+Y ambos modelos se utilizarán para la documentación interactiva de la API:
+
+
+
+## Otras Anotaciones de Tipos de Retorno { #other-return-type-annotations }
+
+Podría haber casos en los que devuelvas algo que no es un campo válido de Pydantic y lo anotes en la función, solo para obtener el soporte proporcionado por las herramientas (el editor, mypy, etc).
+
+### Devolver un Response Directamente { #return-a-response-directly }
+
+El caso más común sería [devolver un Response directamente como se explica más adelante en la documentación avanzada](../advanced/response-directly.md).
+
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
+
+Este caso simple es manejado automáticamente por FastAPI porque la anotación del tipo de retorno es la clase (o una subclase de) `Response`.
+
+Y las herramientas también estarán felices porque tanto `RedirectResponse` como `JSONResponse` son subclases de `Response`, por lo que la anotación del tipo es correcta.
+
+### Anotar una Subclase de Response { #annotate-a-response-subclass }
+
+También puedes usar una subclase de `Response` en la anotación del tipo:
+
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
+
+Esto también funcionará porque `RedirectResponse` es una subclase de `Response`, y FastAPI manejará automáticamente este caso simple.
+
+### Anotaciones de Tipos de Retorno Inválidas { #invalid-return-type-annotations }
+
+Pero cuando devuelves algún otro objeto arbitrario que no es un tipo válido de Pydantic (por ejemplo, un objeto de base de datos) y lo anotas así en la función, FastAPI intentará crear un modelo de response de Pydantic a partir de esa anotación de tipo, y fallará.
+
+Lo mismo sucedería si tuvieras algo como una unión entre diferentes tipos donde uno o más de ellos no son tipos válidos de Pydantic, por ejemplo esto fallaría 💥:
+
+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
+
+...esto falla porque la anotación de tipo no es un tipo de Pydantic y no es solo una sola clase `Response` o subclase, es una unión (cualquiera de los dos) entre una `Response` y un `dict`.
+
+### Desactivar el Modelo de Response { #disable-response-model }
+
+Continuando con el ejemplo anterior, puede que no quieras tener la validación de datos por defecto, documentación, filtrado, etc. que realiza FastAPI.
+
+Pero puedes querer mantener la anotación del tipo de retorno en la función para obtener el soporte de herramientas como editores y verificadores de tipos (por ejemplo, mypy).
+
+En este caso, puedes desactivar la generación del modelo de response configurando `response_model=None`:
+
+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}
+
+Esto hará que FastAPI omita la generación del modelo de response y de esa manera puedes tener cualquier anotación de tipo de retorno que necesites sin que afecte a tu aplicación FastAPI. 🤓
+
+## Parámetros de codificación del Modelo de Response { #response-model-encoding-parameters }
+
+Tu modelo de response podría tener valores por defecto, como:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}
+
+* `description: Union[str, None] = None` (o `str | None = None` en Python 3.10) tiene un valor por defecto de `None`.
+* `tax: float = 10.5` tiene un valor por defecto de `10.5`.
+* `tags: List[str] = []` tiene un valor por defecto de una list vacía: `[]`.
+
+pero podrías querer omitirlos del resultado si no fueron en realidad almacenados.
+
+Por ejemplo, si tienes modelos con muchos atributos opcionales en una base de datos NoSQL, pero no quieres enviar responses JSON muy largos llenos de valores por defecto.
+
+### Usa el parámetro `response_model_exclude_unset` { #use-the-response-model-exclude-unset-parameter }
+
+Puedes configurar el parámetro del decorador de path operation `response_model_exclude_unset=True`:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}
+
+y esos valores por defecto no serán incluidos en el response, solo los valores realmente establecidos.
+
+Entonces, si envías un request a esa *path operation* para el ítem con ID `foo`, el response (no incluyendo valores por defecto) será:
+
+```JSON
+{
+ "name": "Foo",
+ "price": 50.2
+}
+```
+
+/// info | Información
+
+También puedes usar:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+como se describe en [la documentación de Pydantic](https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict) para `exclude_defaults` y `exclude_none`.
+
+///
+
+#### Datos con valores para campos con valores por defecto { #data-with-values-for-fields-with-defaults }
+
+Pero si tus datos tienen valores para los campos del modelo con valores por defecto, como el artículo con ID `bar`:
+
+```Python hl_lines="3 5"
+{
+ "name": "Bar",
+ "description": "The bartenders",
+ "price": 62,
+ "tax": 20.2
+}
+```
+
+serán incluidos en el response.
+
+#### Datos con los mismos valores que los valores por defecto { #data-with-the-same-values-as-the-defaults }
+
+Si los datos tienen los mismos valores que los valores por defecto, como el artículo con ID `baz`:
+
+```Python hl_lines="3 5-6"
+{
+ "name": "Baz",
+ "description": None,
+ "price": 50.2,
+ "tax": 10.5,
+ "tags": []
+}
+```
+
+FastAPI es lo suficientemente inteligente (de hecho, Pydantic es lo suficientemente inteligente) para darse cuenta de que, a pesar de que `description`, `tax` y `tags` tienen los mismos valores que los valores por defecto, fueron establecidos explícitamente (en lugar de tomados de los valores por defecto).
+
+Por lo tanto, se incluirán en el response JSON.
+
+/// tip | Consejo
+
+Ten en cuenta que los valores por defecto pueden ser cualquier cosa, no solo `None`.
+
+Pueden ser una list (`[]`), un `float` de `10.5`, etc.
+
+///
+
+### `response_model_include` y `response_model_exclude` { #response-model-include-and-response-model-exclude }
+
+También puedes usar los parámetros del decorador de path operation `response_model_include` y `response_model_exclude`.
+
+Aceptan un `set` de `str` con el nombre de los atributos a incluir (omitiendo el resto) o excluir (incluyendo el resto).
+
+Esto se puede usar como un atajo rápido si solo tienes un modelo de Pydantic y quieres eliminar algunos datos de la salida.
+
+/// tip | Consejo
+
+Pero todavía se recomienda usar las ideas anteriores, usando múltiples clases, en lugar de estos parámetros.
+
+Esto se debe a que el JSON Schema generado en el OpenAPI de tu aplicación (y la documentación) aún será el del modelo completo, incluso si usas `response_model_include` o `response_model_exclude` para omitir algunos atributos.
+
+Esto también se aplica a `response_model_by_alias` que funciona de manera similar.
+
+///
+
+{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}
+
+/// tip | Consejo
+
+La sintaxis `{"name", "description"}` crea un `set` con esos dos valores.
+
+Es equivalente a `set(["name", "description"])`.
+
+///
+
+#### Usar `list`s en lugar de `set`s { #using-lists-instead-of-sets }
+
+Si olvidas usar un `set` y usas un `list` o `tuple` en su lugar, FastAPI todavía lo convertirá a un `set` y funcionará correctamente:
+
+{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}
+
+## Resumen { #recap }
+
+Usa el parámetro `response_model` del *decorador de path operation* para definir modelos de response y especialmente para asegurarte de que los datos privados sean filtrados.
+
+Usa `response_model_exclude_unset` para devolver solo los valores establecidos explícitamente.
diff --git a/docs/es/docs/tutorial/response-status-code.md b/docs/es/docs/tutorial/response-status-code.md
new file mode 100644
index 0000000000000..a070819bb1652
--- /dev/null
+++ b/docs/es/docs/tutorial/response-status-code.md
@@ -0,0 +1,101 @@
+# Código de Estado del Response { #response-status-code }
+
+De la misma manera que puedes especificar un modelo de response, también puedes declarar el código de estado HTTP usado para el response con el parámetro `status_code` en cualquiera de las *path operations*:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* etc.
+
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
+
+/// note | Nota
+
+Observa que `status_code` es un parámetro del método "decorador" (`get`, `post`, etc). No de tu *path operation function*, como todos los parámetros y body.
+
+///
+
+El parámetro `status_code` recibe un número con el código de estado HTTP.
+
+/// info | Información
+
+`status_code` también puede recibir un `IntEnum`, como por ejemplo el [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus) de Python.
+
+///
+
+Esto hará:
+
+* Devolver ese código de estado en el response.
+* Documentarlo como tal en el esquema de OpenAPI (y por lo tanto, en las interfaces de usuario):
+
+
+
+/// note | Nota
+
+Algunos códigos de response (ver la siguiente sección) indican que el response no tiene un body.
+
+FastAPI sabe esto, y producirá documentación OpenAPI que establece que no hay un response body.
+
+///
+
+## Acerca de los códigos de estado HTTP { #about-http-status-codes }
+
+/// note | Nota
+
+Si ya sabes qué son los códigos de estado HTTP, salta a la siguiente sección.
+
+///
+
+En HTTP, envías un código de estado numérico de 3 dígitos como parte del response.
+
+Estos códigos de estado tienen un nombre asociado para reconocerlos, pero la parte importante es el número.
+
+En breve:
+
+* `100 - 199` son para "Información". Rara vez los usas directamente. Los responses con estos códigos de estado no pueden tener un body.
+* **`200 - 299`** son para responses "Exitosos". Estos son los que usarías más.
+ * `200` es el código de estado por defecto, lo que significa que todo estaba "OK".
+ * Otro ejemplo sería `201`, "Created". Comúnmente se usa después de crear un nuevo registro en la base de datos.
+ * Un caso especial es `204`, "No Content". Este response se usa cuando no hay contenido para devolver al cliente, por lo tanto, el response no debe tener un body.
+* **`300 - 399`** son para "Redirección". Los responses con estos códigos de estado pueden o no tener un body, excepto `304`, "Not Modified", que no debe tener uno.
+* **`400 - 499`** son para responses de "Error del Cliente". Este es el segundo tipo que probablemente más usarías.
+ * Un ejemplo es `404`, para un response "Not Found".
+ * Para errores genéricos del cliente, puedes usar simplemente `400`.
+* `500 - 599` son para errores del servidor. Casi nunca los usas directamente. Cuando algo sale mal en alguna parte de tu código de aplicación, o del servidor, automáticamente devolverá uno de estos códigos de estado.
+
+/// tip | Consejo
+
+Para saber más sobre cada código de estado y qué código es para qué, revisa la [documentación de MDN sobre códigos de estado HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status).
+
+///
+
+## Atajo para recordar los nombres { #shortcut-to-remember-the-names }
+
+Veamos de nuevo el ejemplo anterior:
+
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
+
+`201` es el código de estado para "Created".
+
+Pero no tienes que memorizar lo que significa cada uno de estos códigos.
+
+Puedes usar las variables de conveniencia de `fastapi.status`.
+
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
+
+Son solo una conveniencia, mantienen el mismo número, pero de esa manera puedes usar el autocompletado del editor para encontrarlos:
+
+
+
+/// note | Detalles técnicos
+
+También podrías usar `from starlette import status`.
+
+**FastAPI** proporciona el mismo `starlette.status` como `fastapi.status` solo como una conveniencia para ti, el desarrollador. Pero proviene directamente de Starlette.
+
+///
+
+## Cambiando el valor por defecto { #changing-the-default }
+
+Más adelante, en la [Guía de Usuario Avanzada](../advanced/response-change-status-code.md), verás cómo devolver un código de estado diferente al valor por defecto que estás declarando aquí.
diff --git a/docs/es/docs/tutorial/schema-extra-example.md b/docs/es/docs/tutorial/schema-extra-example.md
new file mode 100644
index 0000000000000..73d0cdbe4657f
--- /dev/null
+++ b/docs/es/docs/tutorial/schema-extra-example.md
@@ -0,0 +1,202 @@
+# Declarar Datos de Ejemplo de Request { #declare-request-example-data }
+
+Puedes declarar ejemplos de los datos que tu aplicación puede recibir.
+
+Aquí tienes varias formas de hacerlo.
+
+## Datos extra de JSON Schema en modelos de Pydantic { #extra-json-schema-data-in-pydantic-models }
+
+Puedes declarar `examples` para un modelo de Pydantic que se añadirá al JSON Schema generado.
+
+{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}
+
+Esa información extra se añadirá tal cual al **JSON Schema** resultante para ese modelo, y se usará en la documentación de la API.
+
+Puedes usar el atributo `model_config` que toma un `dict` como se describe en [Documentación de Pydantic: Configuración](https://docs.pydantic.dev/latest/api/config/).
+
+Puedes establecer `"json_schema_extra"` con un `dict` que contenga cualquier dato adicional que te gustaría que aparezca en el JSON Schema generado, incluyendo `examples`.
+
+/// tip | Consejo
+
+Podrías usar la misma técnica para extender el JSON Schema y añadir tu propia información extra personalizada.
+
+Por ejemplo, podrías usarlo para añadir metadatos para una interfaz de usuario frontend, etc.
+
+///
+
+/// info | Información
+
+OpenAPI 3.1.0 (usado desde FastAPI 0.99.0) añadió soporte para `examples`, que es parte del estándar de **JSON Schema**.
+
+Antes de eso, solo soportaba la palabra clave `example` con un solo ejemplo. Eso aún es soportado por OpenAPI 3.1.0, pero está obsoleto y no es parte del estándar de JSON Schema. Así que se te anima a migrar `example` a `examples`. 🤓
+
+Puedes leer más al final de esta página.
+
+///
+
+## Argumentos adicionales en `Field` { #field-additional-arguments }
+
+Cuando usas `Field()` con modelos de Pydantic, también puedes declarar `examples` adicionales:
+
+{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}
+
+## `examples` en JSON Schema - OpenAPI { #examples-in-json-schema-openapi }
+
+Cuando usas cualquiera de:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+también puedes declarar un grupo de `examples` con información adicional que se añadirá a sus **JSON Schemas** dentro de **OpenAPI**.
+
+### `Body` con `examples` { #body-with-examples }
+
+Aquí pasamos `examples` que contiene un ejemplo de los datos esperados en `Body()`:
+
+{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *}
+
+### Ejemplo en la interfaz de documentación { #example-in-the-docs-ui }
+
+Con cualquiera de los métodos anteriores se vería así en los `/docs`:
+
+
+
+### `Body` con múltiples `examples` { #body-with-multiple-examples }
+
+Por supuesto, también puedes pasar múltiples `examples`:
+
+{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *}
+
+Cuando haces esto, los ejemplos serán parte del **JSON Schema** interno para esos datos del body.
+
+Sin embargo, al momento de escribir esto, Swagger UI, la herramienta encargada de mostrar la interfaz de documentación, no soporta mostrar múltiples ejemplos para los datos en **JSON Schema**. Pero lee más abajo para una solución alternativa.
+
+### `examples` específicos de OpenAPI { #openapi-specific-examples }
+
+Desde antes de que **JSON Schema** soportara `examples`, OpenAPI tenía soporte para un campo diferente también llamado `examples`.
+
+Estos `examples` específicos de **OpenAPI** van en otra sección en la especificación de OpenAPI. Van en los **detalles para cada *path operation***, no dentro de cada JSON Schema.
+
+Y Swagger UI ha soportado este campo particular de `examples` por un tiempo. Así que, puedes usarlo para **mostrar** diferentes **ejemplos en la interfaz de documentación**.
+
+La forma de este campo específico de OpenAPI `examples` es un `dict` con **múltiples ejemplos** (en lugar de una `list`), cada uno con información adicional que también se añadirá a **OpenAPI**.
+
+Esto no va dentro de cada JSON Schema contenido en OpenAPI, esto va afuera, directamente en la *path operation*.
+
+### Usando el Parámetro `openapi_examples` { #using-the-openapi-examples-parameter }
+
+Puedes declarar los `examples` específicos de OpenAPI en FastAPI con el parámetro `openapi_examples` para:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+Las claves del `dict` identifican cada ejemplo, y cada valor es otro `dict`.
+
+Cada `dict` específico del ejemplo en los `examples` puede contener:
+
+* `summary`: Descripción corta del ejemplo.
+* `description`: Una descripción larga que puede contener texto Markdown.
+* `value`: Este es el ejemplo real mostrado, e.g. un `dict`.
+* `externalValue`: alternativa a `value`, una URL que apunta al ejemplo. Aunque esto puede no ser soportado por tantas herramientas como `value`.
+
+Puedes usarlo así:
+
+{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *}
+
+### Ejemplos de OpenAPI en la Interfaz de Documentación { #openapi-examples-in-the-docs-ui }
+
+Con `openapi_examples` añadido a `Body()`, los `/docs` se verían así:
+
+
+
+## Detalles Técnicos { #technical-details }
+
+/// tip | Consejo
+
+Si ya estás usando la versión **0.99.0 o superior** de **FastAPI**, probablemente puedes **omitir** estos detalles.
+
+Son más relevantes para versiones más antiguas, antes de que OpenAPI 3.1.0 estuviera disponible.
+
+Puedes considerar esto una breve lección de **historia** de OpenAPI y JSON Schema. 🤓
+
+///
+
+/// warning | Advertencia
+
+Estos son detalles muy técnicos sobre los estándares **JSON Schema** y **OpenAPI**.
+
+Si las ideas anteriores ya funcionan para ti, eso podría ser suficiente, y probablemente no necesites estos detalles, siéntete libre de omitirlos.
+
+///
+
+Antes de OpenAPI 3.1.0, OpenAPI usaba una versión más antigua y modificada de **JSON Schema**.
+
+JSON Schema no tenía `examples`, así que OpenAPI añadió su propio campo `example` a su versión modificada.
+
+OpenAPI también añadió los campos `example` y `examples` a otras partes de la especificación:
+
+* [`Parameter Object` (en la especificación)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object) que era usado por FastAPI:
+ * `Path()`
+ * `Query()`
+ * `Header()`
+ * `Cookie()`
+* [`Request Body Object`, en el campo `content`, sobre el `Media Type Object` (en la especificación)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object) que era usado por FastAPI:
+ * `Body()`
+ * `File()`
+ * `Form()`
+
+/// info | Información
+
+Este viejo parámetro `examples` específico de OpenAPI ahora es `openapi_examples` desde FastAPI `0.103.0`.
+
+///
+
+### Campo `examples` de JSON Schema { #json-schemas-examples-field }
+
+Pero luego JSON Schema añadió un [campo `examples`](https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.9.5) a una nueva versión de la especificación.
+
+Y entonces el nuevo OpenAPI 3.1.0 se basó en la última versión (JSON Schema 2020-12) que incluía este nuevo campo `examples`.
+
+Y ahora este nuevo campo `examples` tiene precedencia sobre el viejo campo único (y personalizado) `example`, que ahora está obsoleto.
+
+Este nuevo campo `examples` en JSON Schema es **solo una `list`** de ejemplos, no un dict con metadatos adicionales como en los otros lugares en OpenAPI (descritos arriba).
+
+/// info | Información
+
+Incluso después de que OpenAPI 3.1.0 fue lanzado con esta nueva integración más sencilla con JSON Schema, por un tiempo, Swagger UI, la herramienta que proporciona la documentación automática, no soportaba OpenAPI 3.1.0 (lo hace desde la versión 5.0.0 🎉).
+
+Debido a eso, las versiones de FastAPI anteriores a 0.99.0 todavía usaban versiones de OpenAPI menores a 3.1.0.
+
+///
+
+### `examples` de Pydantic y FastAPI { #pydantic-and-fastapi-examples }
+
+Cuando añades `examples` dentro de un modelo de Pydantic, usando `schema_extra` o `Field(examples=["something"])`, ese ejemplo se añade al **JSON Schema** para ese modelo de Pydantic.
+
+Y ese **JSON Schema** del modelo de Pydantic se incluye en el **OpenAPI** de tu API, y luego se usa en la interfaz de documentación.
+
+En las versiones de FastAPI antes de 0.99.0 (0.99.0 y superiores usan el nuevo OpenAPI 3.1.0) cuando usabas `example` o `examples` con cualquiera de las otras utilidades (`Query()`, `Body()`, etc.) esos ejemplos no se añadían al JSON Schema que describe esos datos (ni siquiera a la propia versión de JSON Schema de OpenAPI), se añadían directamente a la declaración de la *path operation* en OpenAPI (fuera de las partes de OpenAPI que usan JSON Schema).
+
+Pero ahora que FastAPI 0.99.0 y superiores usa OpenAPI 3.1.0, que usa JSON Schema 2020-12, y Swagger UI 5.0.0 y superiores, todo es más consistente y los ejemplos se incluyen en JSON Schema.
+
+### Swagger UI y `examples` específicos de OpenAPI { #swagger-ui-and-openapi-specific-examples }
+
+Ahora, como Swagger UI no soportaba múltiples ejemplos de JSON Schema (a fecha de 2023-08-26), los usuarios no tenían una forma de mostrar múltiples ejemplos en la documentación.
+
+Para resolver eso, FastAPI `0.103.0` **añadió soporte** para declarar el mismo viejo campo **específico de OpenAPI** `examples` con el nuevo parámetro `openapi_examples`. 🤓
+
+### Resumen { #summary }
+
+Solía decir que no me gustaba mucho la historia... y mírame ahora dando lecciones de "historia tecnológica". 😅
+
+En resumen, **actualiza a FastAPI 0.99.0 o superior**, y las cosas son mucho **más simples, consistentes e intuitivas**, y no necesitas conocer todos estos detalles históricos. 😎
diff --git a/docs/es/docs/tutorial/security/first-steps.md b/docs/es/docs/tutorial/security/first-steps.md
new file mode 100644
index 0000000000000..8118906e5daa6
--- /dev/null
+++ b/docs/es/docs/tutorial/security/first-steps.md
@@ -0,0 +1,203 @@
+# Seguridad - Primeros pasos { #security-first-steps }
+
+Imaginemos que tienes tu API de **backend** en algún dominio.
+
+Y tienes un **frontend** en otro dominio o en un path diferente del mismo dominio (o en una aplicación móvil).
+
+Y quieres tener una forma para que el frontend se autentique con el backend, usando un **username** y **password**.
+
+Podemos usar **OAuth2** para construir eso con **FastAPI**.
+
+Pero vamos a ahorrarte el tiempo de leer la larga especificación completa solo para encontrar esos pequeños fragmentos de información que necesitas.
+
+Usemos las herramientas proporcionadas por **FastAPI** para manejar la seguridad.
+
+## Cómo se ve { #how-it-looks }
+
+Primero solo usemos el código y veamos cómo funciona, y luego volveremos para entender qué está sucediendo.
+
+## Crea `main.py` { #create-main-py }
+
+Copia el ejemplo en un archivo `main.py`:
+
+{* ../../docs_src/security/tutorial001_an_py310.py *}
+
+## Ejecútalo { #run-it }
+
+/// info | Información
+
+El paquete [`python-multipart`](https://github.com/Kludex/python-multipart) se instala automáticamente con **FastAPI** cuando ejecutas el comando `pip install "fastapi[standard]"`.
+
+Sin embargo, si usas el comando `pip install fastapi`, el paquete `python-multipart` no se incluye por defecto.
+
+Para instalarlo manualmente, asegúrate de crear un [entorno virtual](../../virtual-environments.md), activarlo, y luego instalarlo con:
+
+```console
+$ pip install python-multipart
+```
+
+Esto se debe a que **OAuth2** utiliza "form data" para enviar el `username` y `password`.
+
+///
+
+Ejecuta el ejemplo con:
+
+
+
+/// check | ¡Botón de autorización!
+
+Ya tienes un nuevo y brillante botón de "Authorize".
+
+Y tu *path operation* tiene un pequeño candado en la esquina superior derecha que puedes pulsar.
+
+///
+
+Y si lo haces, tendrás un pequeño formulario de autorización para escribir un `username` y `password` (y otros campos opcionales):
+
+
+
+/// note | Nota
+
+No importa lo que escribas en el formulario, aún no funcionará. Pero llegaremos allí.
+
+///
+
+Esto por supuesto no es el frontend para los usuarios finales, pero es una gran herramienta automática para documentar interactivamente toda tu API.
+
+Puede ser utilizada por el equipo de frontend (que también puedes ser tú mismo).
+
+Puede ser utilizada por aplicaciones y sistemas de terceros.
+
+Y también puede ser utilizada por ti mismo, para depurar, revisar y probar la misma aplicación.
+
+## El flujo `password` { #the-password-flow }
+
+Ahora retrocedamos un poco y entendamos qué es todo eso.
+
+El "flujo" `password` es una de las formas ("flujos") definidas en OAuth2, para manejar la seguridad y la autenticación.
+
+OAuth2 fue diseñado para que el backend o la API pudieran ser independientes del servidor que autentica al usuario.
+
+Pero en este caso, la misma aplicación de **FastAPI** manejará la API y la autenticación.
+
+Así que, revisémoslo desde ese punto de vista simplificado:
+
+* El usuario escribe el `username` y `password` en el frontend, y presiona `Enter`.
+* El frontend (ejecutándose en el navegador del usuario) envía ese `username` y `password` a una URL específica en nuestra API (declarada con `tokenUrl="token"`).
+* La API verifica ese `username` y `password`, y responde con un "token" (no hemos implementado nada de esto aún).
+ * Un "token" es solo un string con algún contenido que podemos usar luego para verificar a este usuario.
+ * Normalmente, un token se establece para que expire después de algún tiempo.
+ * Así que, el usuario tendrá que volver a iniciar sesión más adelante.
+ * Y si el token es robado, el riesgo es menor. No es como una llave permanente que funcionará para siempre (en la mayoría de los casos).
+* El frontend almacena temporalmente ese token en algún lugar.
+* El usuario hace clic en el frontend para ir a otra sección de la aplicación web frontend.
+* El frontend necesita obtener más datos de la API.
+ * Pero necesita autenticación para ese endpoint específico.
+ * Así que, para autenticarse con nuestra API, envía un `header` `Authorization` con un valor de `Bearer ` más el token.
+ * Si el token contiene `foobar`, el contenido del `header` `Authorization` sería: `Bearer foobar`.
+
+## `OAuth2PasswordBearer` de **FastAPI** { #fastapis-oauth2passwordbearer }
+
+**FastAPI** proporciona varias herramientas, en diferentes niveles de abstracción, para implementar estas funcionalidades de seguridad.
+
+En este ejemplo vamos a usar **OAuth2**, con el flujo **Password**, usando un token **Bearer**. Hacemos eso utilizando la clase `OAuth2PasswordBearer`.
+
+/// info | Información
+
+Un token "bearer" no es la única opción.
+
+Pero es la mejor para nuestro caso de uso.
+
+Y podría ser la mejor para la mayoría de los casos de uso, a menos que seas un experto en OAuth2 y sepas exactamente por qué hay otra opción que se adapta mejor a tus necesidades.
+
+En ese caso, **FastAPI** también te proporciona las herramientas para construirlo.
+
+///
+
+Cuando creamos una instance de la clase `OAuth2PasswordBearer` pasamos el parámetro `tokenUrl`. Este parámetro contiene la URL que el cliente (el frontend corriendo en el navegador del usuario) usará para enviar el `username` y `password` a fin de obtener un token.
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
+
+/// tip | Consejo
+
+Aquí `tokenUrl="token"` se refiere a una URL relativa `token` que aún no hemos creado. Como es una URL relativa, es equivalente a `./token`.
+
+Porque estamos usando una URL relativa, si tu API estuviera ubicada en `https://example.com/`, entonces se referiría a `https://example.com/token`. Pero si tu API estuviera ubicada en `https://example.com/api/v1/`, entonces se referiría a `https://example.com/api/v1/token`.
+
+Usar una URL relativa es importante para asegurarse de que tu aplicación siga funcionando incluso en un caso de uso avanzado como [Detrás de un Proxy](../../advanced/behind-a-proxy.md).
+
+///
+
+Este parámetro no crea ese endpoint / *path operation*, pero declara que la URL `/token` será la que el cliente deberá usar para obtener el token. Esa información se usa en OpenAPI, y luego en los sistemas de documentación interactiva del API.
+
+Pronto también crearemos la verdadera *path operation*.
+
+/// info | Información
+
+Si eres un "Pythonista" muy estricto, tal vez no te guste el estilo del nombre del parámetro `tokenUrl` en lugar de `token_url`.
+
+Eso es porque está usando el mismo nombre que en la especificación de OpenAPI. Para que si necesitas investigar más sobre cualquiera de estos esquemas de seguridad, puedas simplemente copiarlo y pegarlo para encontrar más información al respecto.
+
+///
+
+La variable `oauth2_scheme` es una instance de `OAuth2PasswordBearer`, pero también es un "callable".
+
+Podría ser llamada como:
+
+```Python
+oauth2_scheme(some, parameters)
+```
+
+Así que, puede usarse con `Depends`.
+
+### Úsalo { #use-it }
+
+Ahora puedes pasar ese `oauth2_scheme` en una dependencia con `Depends`.
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+Esta dependencia proporcionará un `str` que se asigna al parámetro `token` de la *path operation function*.
+
+**FastAPI** sabrá que puede usar esta dependencia para definir un "security scheme" en el esquema OpenAPI (y en los docs automáticos del API).
+
+/// info | Detalles técnicos
+
+**FastAPI** sabrá que puede usar la clase `OAuth2PasswordBearer` (declarada en una dependencia) para definir el esquema de seguridad en OpenAPI porque hereda de `fastapi.security.oauth2.OAuth2`, que a su vez hereda de `fastapi.security.base.SecurityBase`.
+
+Todas las utilidades de seguridad que se integran con OpenAPI (y los docs automáticos del API) heredan de `SecurityBase`, así es como **FastAPI** puede saber cómo integrarlas en OpenAPI.
+
+///
+
+## Lo que hace { #what-it-does }
+
+Irá y buscará en el request ese header `Authorization`, verificará si el valor es `Bearer ` más algún token, y devolverá el token como un `str`.
+
+Si no ve un header `Authorization`, o el valor no tiene un token `Bearer `, responderá directamente con un error de código de estado 401 (`UNAUTHORIZED`).
+
+Ni siquiera tienes que verificar si el token existe para devolver un error. Puedes estar seguro de que si tu función se ejecuta, tendrá un `str` en ese token.
+
+Puedes probarlo ya en los docs interactivos:
+
+
+
+Todavía no estamos verificando la validez del token, pero ya es un comienzo.
+
+## Resumen { #recap }
+
+Así que, en solo 3 o 4 líneas adicionales, ya tienes alguna forma primitiva de seguridad.
diff --git a/docs/es/docs/tutorial/security/get-current-user.md b/docs/es/docs/tutorial/security/get-current-user.md
new file mode 100644
index 0000000000000..67b6c58359b2f
--- /dev/null
+++ b/docs/es/docs/tutorial/security/get-current-user.md
@@ -0,0 +1,103 @@
+# Obtener Usuario Actual { #get-current-user }
+
+En el capítulo anterior, el sistema de seguridad (que se basa en el sistema de inyección de dependencias) le estaba dando a la *path operation function* un `token` como un `str`:
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+Pero eso aún no es tan útil. Vamos a hacer que nos dé el usuario actual.
+
+## Crear un modelo de usuario { #create-a-user-model }
+
+Primero, vamos a crear un modelo de usuario con Pydantic.
+
+De la misma manera que usamos Pydantic para declarar cuerpos, podemos usarlo en cualquier otra parte:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *}
+
+## Crear una dependencia `get_current_user` { #create-a-get-current-user-dependency }
+
+Vamos a crear una dependencia `get_current_user`.
+
+¿Recuerdas que las dependencias pueden tener sub-dependencias?
+
+`get_current_user` tendrá una dependencia con el mismo `oauth2_scheme` que creamos antes.
+
+De la misma manera que estábamos haciendo antes en la *path operation* directamente, nuestra nueva dependencia `get_current_user` recibirá un `token` como un `str` de la sub-dependencia `oauth2_scheme`:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *}
+
+## Obtener el usuario { #get-the-user }
+
+`get_current_user` usará una función de utilidad (falsa) que creamos, que toma un token como un `str` y devuelve nuestro modelo de Pydantic `User`:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *}
+
+## Inyectar al usuario actual { #inject-the-current-user }
+
+Entonces ahora podemos usar el mismo `Depends` con nuestro `get_current_user` en la *path operation*:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *}
+
+Ten en cuenta que declaramos el tipo de `current_user` como el modelo de Pydantic `User`.
+
+Esto nos ayudará dentro de la función con todo el autocompletado y chequeo de tipos.
+
+/// tip | Consejo
+
+Tal vez recuerdes que los request bodies también se declaran con modelos de Pydantic.
+
+Aquí **FastAPI** no se confundirá porque estás usando `Depends`.
+
+///
+
+/// check | Revisa
+
+El modo en que este sistema de dependencias está diseñado nos permite tener diferentes dependencias (diferentes "dependables") que todas devuelven un modelo `User`.
+
+No estamos restringidos a tener solo una dependencia que pueda devolver ese tipo de datos.
+
+///
+
+## Otros modelos { #other-models }
+
+Ahora puedes obtener el usuario actual directamente en las *path operation functions* y manejar los mecanismos de seguridad a nivel de **Dependency Injection**, usando `Depends`.
+
+Y puedes usar cualquier modelo o datos para los requisitos de seguridad (en este caso, un modelo de Pydantic `User`).
+
+Pero no estás limitado a usar algún modelo de datos, clase o tipo específico.
+
+¿Quieres tener un `id` y `email` y no tener un `username` en tu modelo? Claro. Puedes usar estas mismas herramientas.
+
+¿Quieres solo tener un `str`? ¿O solo un `dict`? ¿O un instance de clase modelo de base de datos directamente? Todo funciona de la misma manera.
+
+¿En realidad no tienes usuarios que inicien sesión en tu aplicación sino robots, bots u otros sistemas, que solo tienen un token de acceso? Una vez más, todo funciona igual.
+
+Usa cualquier tipo de modelo, cualquier tipo de clase, cualquier tipo de base de datos que necesites para tu aplicación. **FastAPI** te cubre con el sistema de inyección de dependencias.
+
+## Tamaño del código { #code-size }
+
+Este ejemplo podría parecer extenso. Ten en cuenta que estamos mezclando seguridad, modelos de datos, funciones de utilidad y *path operations* en el mismo archivo.
+
+Pero aquí está el punto clave.
+
+El tema de seguridad e inyección de dependencias se escribe una vez.
+
+Y puedes hacerlo tan complejo como desees. Y aún así, tenerlo escrito solo una vez, en un solo lugar. Con toda la flexibilidad.
+
+Pero puedes tener miles de endpoints (*path operations*) usando el mismo sistema de seguridad.
+
+Y todos ellos (o cualquier porción de ellos que quieras) pueden aprovechar la reutilización de estas dependencias o cualquier otra dependencia que crees.
+
+Y todas estas miles de *path operations* pueden ser tan pequeñas como 3 líneas:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *}
+
+## Resumen { #recap }
+
+Ahora puedes obtener el usuario actual directamente en tu *path operation function*.
+
+Ya estamos a mitad de camino.
+
+Solo necesitamos agregar una *path operation* para que el usuario/cliente envíe realmente el `username` y `password`.
+
+Eso es lo que viene a continuación.
diff --git a/docs/es/docs/tutorial/security/index.md b/docs/es/docs/tutorial/security/index.md
new file mode 100644
index 0000000000000..aecc6b4aac7f1
--- /dev/null
+++ b/docs/es/docs/tutorial/security/index.md
@@ -0,0 +1,105 @@
+# Seguridad { #security }
+
+Hay muchas formas de manejar la seguridad, autenticación y autorización.
+
+Y normalmente es un tema complejo y "difícil".
+
+En muchos frameworks y sistemas, solo manejar la seguridad y autenticación requiere una gran cantidad de esfuerzo y código (en muchos casos puede ser el 50% o más de todo el código escrito).
+
+**FastAPI** proporciona varias herramientas para ayudarte a manejar la **Seguridad** de manera fácil, rápida y estándar, sin tener que estudiar y aprender todas las especificaciones de seguridad.
+
+Pero primero, vamos a revisar algunos pequeños conceptos.
+
+## ¿Con prisa? { #in-a-hurry }
+
+Si no te importan ninguno de estos términos y solo necesitas agregar seguridad con autenticación basada en nombre de usuario y contraseña *ahora mismo*, salta a los siguientes capítulos.
+
+## OAuth2 { #oauth2 }
+
+OAuth2 es una especificación que define varias maneras de manejar la autenticación y autorización.
+
+Es una especificación bastante extensa y cubre varios casos de uso complejos.
+
+Incluye formas de autenticarse usando un "tercero".
+
+Eso es lo que todos los sistemas con "iniciar sesión con Facebook, Google, X (Twitter), GitHub" utilizan internamente.
+
+### OAuth 1 { #oauth-1 }
+
+Hubo un OAuth 1, que es muy diferente de OAuth2, y más complejo, ya que incluía especificaciones directas sobre cómo encriptar la comunicación.
+
+No es muy popular o usado hoy en día.
+
+OAuth2 no especifica cómo encriptar la comunicación, espera que tengas tu aplicación servida con HTTPS.
+
+/// tip | Consejo
+
+En la sección sobre **deployment** verás cómo configurar HTTPS de forma gratuita, usando Traefik y Let's Encrypt.
+
+///
+
+## OpenID Connect { #openid-connect }
+
+OpenID Connect es otra especificación, basada en **OAuth2**.
+
+Solo extiende OAuth2 especificando algunas cosas que son relativamente ambiguas en OAuth2, para intentar hacerla más interoperable.
+
+Por ejemplo, el login de Google usa OpenID Connect (que internamente usa OAuth2).
+
+Pero el login de Facebook no soporta OpenID Connect. Tiene su propia versión de OAuth2.
+
+### OpenID (no "OpenID Connect") { #openid-not-openid-connect }
+
+Hubo también una especificación "OpenID". Que intentaba resolver lo mismo que **OpenID Connect**, pero no estaba basada en OAuth2.
+
+Entonces, era un sistema completo adicional.
+
+No es muy popular o usado hoy en día.
+
+## OpenAPI { #openapi }
+
+OpenAPI (anteriormente conocido como Swagger) es la especificación abierta para construir APIs (ahora parte de la Linux Foundation).
+
+**FastAPI** se basa en **OpenAPI**.
+
+Eso es lo que hace posible tener múltiples interfaces de documentación interactiva automática, generación de código, etc.
+
+OpenAPI tiene una forma de definir múltiples "esquemas" de seguridad.
+
+Al usarlos, puedes aprovechar todas estas herramientas basadas en estándares, incluidos estos sistemas de documentación interactiva.
+
+OpenAPI define los siguientes esquemas de seguridad:
+
+* `apiKey`: una clave específica de la aplicación que puede provenir de:
+ * Un parámetro de query.
+ * Un header.
+ * Una cookie.
+* `http`: sistemas de autenticación HTTP estándar, incluyendo:
+ * `bearer`: un header `Authorization` con un valor de `Bearer ` más un token. Esto se hereda de OAuth2.
+ * Autenticación básica HTTP.
+ * Digest HTTP, etc.
+* `oauth2`: todas las formas de OAuth2 para manejar la seguridad (llamadas "flujos").
+ * Varios de estos flujos son apropiados para construir un proveedor de autenticación OAuth 2.0 (como Google, Facebook, X (Twitter), GitHub, etc.):
+ * `implicit`
+ * `clientCredentials`
+ * `authorizationCode`
+ * Pero hay un "flujo" específico que puede usarse perfectamente para manejar la autenticación directamente en la misma aplicación:
+ * `password`: algunos de los próximos capítulos cubrirán ejemplos de esto.
+* `openIdConnect`: tiene una forma de definir cómo descubrir automáticamente los datos de autenticación OAuth2.
+ * Este descubrimiento automático es lo que se define en la especificación de OpenID Connect.
+
+/// tip | Consejo
+
+Integrar otros proveedores de autenticación/autorización como Google, Facebook, X (Twitter), GitHub, etc. también es posible y relativamente fácil.
+
+El problema más complejo es construir un proveedor de autenticación/autorización como esos, pero **FastAPI** te da las herramientas para hacerlo fácilmente, mientras hace el trabajo pesado por ti.
+
+///
+
+## Utilidades de **FastAPI** { #fastapi-utilities }
+
+FastAPI proporciona varias herramientas para cada uno de estos esquemas de seguridad en el módulo `fastapi.security` que simplifican el uso de estos mecanismos de seguridad.
+
+En los siguientes capítulos verás cómo agregar seguridad a tu API usando esas herramientas proporcionadas por **FastAPI**.
+
+Y también verás cómo se integra automáticamente en el sistema de documentación interactiva.
diff --git a/docs/es/docs/tutorial/security/oauth2-jwt.md b/docs/es/docs/tutorial/security/oauth2-jwt.md
new file mode 100644
index 0000000000000..af1140d1bad52
--- /dev/null
+++ b/docs/es/docs/tutorial/security/oauth2-jwt.md
@@ -0,0 +1,277 @@
+# OAuth2 con Password (y hashing), Bearer con tokens JWT { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
+
+Ahora que tenemos todo el flujo de seguridad, hagamos que la aplicación sea realmente segura, usando tokens JWT y hashing de contraseñas seguras.
+
+Este código es algo que puedes usar realmente en tu aplicación, guardar los hashes de las contraseñas en tu base de datos, etc.
+
+Vamos a empezar desde donde lo dejamos en el capítulo anterior e incrementarlo.
+
+## Acerca de JWT { #about-jwt }
+
+JWT significa "JSON Web Tokens".
+
+Es un estándar para codificar un objeto JSON en un string largo y denso sin espacios. Se ve así:
+
+```
+eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
+```
+
+No está encriptado, por lo que cualquiera podría recuperar la información de los contenidos.
+
+Pero está firmado. Así que, cuando recibes un token que has emitido, puedes verificar que realmente lo emitiste.
+
+De esta manera, puedes crear un token con una expiración de, digamos, 1 semana. Y luego, cuando el usuario regresa al día siguiente con el token, sabes que el usuario todavía está registrado en tu sistema.
+
+Después de una semana, el token estará expirado y el usuario no estará autorizado y tendrá que iniciar sesión nuevamente para obtener un nuevo token. Y si el usuario (o un tercero) intenta modificar el token para cambiar la expiración, podrás descubrirlo, porque las firmas no coincidirían.
+
+Si quieres jugar con tokens JWT y ver cómo funcionan, revisa [https://jwt.io](https://jwt.io/).
+
+## Instalar `PyJWT` { #install-pyjwt }
+
+Necesitamos instalar `PyJWT` para generar y verificar los tokens JWT en Python.
+
+Asegúrate de crear un [entorno virtual](../../virtual-environments.md), activarlo y luego instalar `pyjwt`:
+
+
+
+Autoriza la aplicación de la misma manera que antes.
+
+Usando las credenciales:
+
+Usuario: `johndoe`
+Contraseña: `secret`
+
+/// check | Revisa
+
+Observa que en ninguna parte del código está la contraseña en texto claro "`secret`", solo tenemos la versión con hash.
+
+///
+
+
+
+Llama al endpoint `/users/me/`, obtendrás el response como:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false
+}
+```
+
+
+
+Si abres las herramientas de desarrollador, podrías ver cómo los datos enviados solo incluyen el token, la contraseña solo se envía en la primera request para autenticar al usuario y obtener ese token de acceso, pero no después:
+
+
+
+/// note | Nota
+
+Observa el header `Authorization`, con un valor que comienza con `Bearer `.
+
+///
+
+## Uso avanzado con `scopes` { #advanced-usage-with-scopes }
+
+OAuth2 tiene la noción de "scopes".
+
+Puedes usarlos para agregar un conjunto específico de permisos a un token JWT.
+
+Luego, puedes darle este token directamente a un usuario o a un tercero, para interactuar con tu API con un conjunto de restricciones.
+
+Puedes aprender cómo usarlos y cómo están integrados en **FastAPI** más adelante en la **Guía de Usuario Avanzada**.
+
+## Resumen { #recap }
+
+Con lo que has visto hasta ahora, puedes configurar una aplicación **FastAPI** segura usando estándares como OAuth2 y JWT.
+
+En casi cualquier framework el manejo de la seguridad se convierte en un tema bastante complejo rápidamente.
+
+Muchos paquetes que lo simplifican tienen que hacer muchos compromisos con el modelo de datos, la base de datos y las funcionalidades disponibles. Y algunos de estos paquetes que simplifican las cosas demasiado en realidad tienen fallos de seguridad en el fondo.
+
+---
+
+**FastAPI** no hace ningún compromiso con ninguna base de datos, modelo de datos o herramienta.
+
+Te da toda la flexibilidad para elegir aquellas que se ajusten mejor a tu proyecto.
+
+Y puedes usar directamente muchos paquetes bien mantenidos y ampliamente usados como `pwdlib` y `PyJWT`, porque **FastAPI** no requiere mecanismos complejos para integrar paquetes externos.
+
+Pero te proporciona las herramientas para simplificar el proceso tanto como sea posible sin comprometer la flexibilidad, la robustez o la seguridad.
+
+Y puedes usar e implementar protocolos seguros y estándar, como OAuth2 de una manera relativamente simple.
+
+Puedes aprender más en la **Guía de Usuario Avanzada** sobre cómo usar "scopes" de OAuth2, para un sistema de permisos más detallado, siguiendo estos mismos estándares. OAuth2 con scopes es el mecanismo utilizado por muchos grandes proveedores de autenticación, como Facebook, Google, GitHub, Microsoft, X (Twitter), etc. para autorizar aplicaciones de terceros para interactuar con sus APIs en nombre de sus usuarios.
diff --git a/docs/es/docs/tutorial/security/simple-oauth2.md b/docs/es/docs/tutorial/security/simple-oauth2.md
new file mode 100644
index 0000000000000..15c7146bd7ea5
--- /dev/null
+++ b/docs/es/docs/tutorial/security/simple-oauth2.md
@@ -0,0 +1,289 @@
+# Simple OAuth2 con Password y Bearer { #simple-oauth2-with-password-and-bearer }
+
+Ahora vamos a construir a partir del capítulo anterior y agregar las partes faltantes para tener un flujo de seguridad completo.
+
+## Obtener el `username` y `password` { #get-the-username-and-password }
+
+Vamos a usar las utilidades de seguridad de **FastAPI** para obtener el `username` y `password`.
+
+OAuth2 especifica que cuando se utiliza el "password flow" (que estamos usando), el cliente/usuario debe enviar campos `username` y `password` como form data.
+
+Y la especificación dice que los campos deben llamarse así. Por lo que `user-name` o `email` no funcionarían.
+
+Pero no te preocupes, puedes mostrarlo como quieras a tus usuarios finales en el frontend.
+
+Y tus modelos de base de datos pueden usar cualquier otro nombre que desees.
+
+Pero para la *path operation* de inicio de sesión, necesitamos usar estos nombres para ser compatibles con la especificación (y poder, por ejemplo, utilizar el sistema de documentación integrada de la API).
+
+La especificación también establece que el `username` y `password` deben enviarse como form data (por lo que no hay JSON aquí).
+
+### `scope` { #scope }
+
+La especificación también indica que el cliente puede enviar otro campo del formulario llamado "`scope`".
+
+El nombre del campo del formulario es `scope` (en singular), pero en realidad es un string largo con "scopes" separados por espacios.
+
+Cada "scope" es simplemente un string (sin espacios).
+
+Normalmente se utilizan para declarar permisos de seguridad específicos, por ejemplo:
+
+* `users:read` o `users:write` son ejemplos comunes.
+* `instagram_basic` es usado por Facebook / Instagram.
+* `https://www.googleapis.com/auth/drive` es usado por Google.
+
+/// info | Información
+
+En OAuth2 un "scope" es solo un string que declara un permiso específico requerido.
+
+No importa si tiene otros caracteres como `:` o si es una URL.
+
+Esos detalles son específicos de la implementación.
+
+Para OAuth2 son solo strings.
+
+///
+
+## Código para obtener el `username` y `password` { #code-to-get-the-username-and-password }
+
+Ahora vamos a usar las utilidades proporcionadas por **FastAPI** para manejar esto.
+
+### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform }
+
+Primero, importa `OAuth2PasswordRequestForm`, y úsalo como una dependencia con `Depends` en la *path operation* para `/token`:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}
+
+`OAuth2PasswordRequestForm` es una dependencia de clase que declara un body de formulario con:
+
+* El `username`.
+* El `password`.
+* Un campo opcional `scope` como un string grande, compuesto por strings separados por espacios.
+* Un `grant_type` opcional.
+
+/// tip | Consejo
+
+La especificación de OAuth2 en realidad *requiere* un campo `grant_type` con un valor fijo de `password`, pero `OAuth2PasswordRequestForm` no lo obliga.
+
+Si necesitas imponerlo, utiliza `OAuth2PasswordRequestFormStrict` en lugar de `OAuth2PasswordRequestForm`.
+
+///
+
+* Un `client_id` opcional (no lo necesitamos para nuestro ejemplo).
+* Un `client_secret` opcional (no lo necesitamos para nuestro ejemplo).
+
+/// info | Información
+
+`OAuth2PasswordRequestForm` no es una clase especial para **FastAPI** como lo es `OAuth2PasswordBearer`.
+
+`OAuth2PasswordBearer` hace que **FastAPI** sepa que es un esquema de seguridad. Así que se añade de esa manera a OpenAPI.
+
+Pero `OAuth2PasswordRequestForm` es solo una dependencia de clase que podrías haber escrito tú mismo, o podrías haber declarado parámetros de `Form` directamente.
+
+Pero como es un caso de uso común, se proporciona directamente por **FastAPI**, solo para facilitarlo.
+
+///
+
+### Usa el form data { #use-the-form-data }
+
+/// tip | Consejo
+
+La instance de la clase de dependencia `OAuth2PasswordRequestForm` no tendrá un atributo `scope` con el string largo separado por espacios, en su lugar, tendrá un atributo `scopes` con la lista real de strings para cada scope enviado.
+
+No estamos usando `scopes` en este ejemplo, pero la funcionalidad está ahí si la necesitas.
+
+///
+
+Ahora, obtén los datos del usuario desde la base de datos (falsa), usando el `username` del campo del form.
+
+Si no existe tal usuario, devolvemos un error diciendo "Incorrect username or password".
+
+Para el error, usamos la excepción `HTTPException`:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}
+
+### Revisa el password { #check-the-password }
+
+En este punto tenemos los datos del usuario de nuestra base de datos, pero no hemos revisado el password.
+
+Primero pongamos esos datos en el modelo `UserInDB` de Pydantic.
+
+Nunca deberías guardar passwords en texto plano, así que, usaremos el sistema de hash de passwords (falso).
+
+Si los passwords no coinciden, devolvemos el mismo error.
+
+#### Hashing de passwords { #password-hashing }
+
+"Hacer hash" significa: convertir algún contenido (un password en este caso) en una secuencia de bytes (solo un string) que parece un galimatías.
+
+Siempre que pases exactamente el mismo contenido (exactamente el mismo password) obtienes exactamente el mismo galimatías.
+
+Pero no puedes convertir del galimatías al password.
+
+##### Por qué usar hashing de passwords { #why-use-password-hashing }
+
+Si tu base de datos es robada, el ladrón no tendrá los passwords en texto plano de tus usuarios, solo los hashes.
+
+Entonces, el ladrón no podrá intentar usar esos mismos passwords en otro sistema (como muchos usuarios usan el mismo password en todas partes, esto sería peligroso).
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}
+
+#### Sobre `**user_dict` { #about-user-dict }
+
+`UserInDB(**user_dict)` significa:
+
+*Pasa las claves y valores de `user_dict` directamente como argumentos clave-valor, equivalente a:*
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ disabled = user_dict["disabled"],
+ hashed_password = user_dict["hashed_password"],
+)
+```
+
+/// info | Información
+
+Para una explicación más completa de `**user_dict` revisa en [la documentación para **Extra Models**](../extra-models.md#about-user-in-dict).
+
+///
+
+## Devolver el token { #return-the-token }
+
+El response del endpoint `token` debe ser un objeto JSON.
+
+Debe tener un `token_type`. En nuestro caso, como estamos usando tokens "Bearer", el tipo de token debe ser "`bearer`".
+
+Y debe tener un `access_token`, con un string que contenga nuestro token de acceso.
+
+Para este ejemplo simple, vamos a ser completamente inseguros y devolver el mismo `username` como el token.
+
+/// tip | Consejo
+
+En el próximo capítulo, verás una implementación segura real, con hashing de passwords y tokens JWT.
+
+Pero por ahora, enfoquémonos en los detalles específicos que necesitamos.
+
+///
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}
+
+/// tip | Consejo
+
+De acuerdo con la especificación, deberías devolver un JSON con un `access_token` y un `token_type`, igual que en este ejemplo.
+
+Esto es algo que tienes que hacer tú mismo en tu código, y asegurarte de usar esas claves JSON.
+
+Es casi lo único que tienes que recordar hacer correctamente tú mismo, para ser compatible con las especificaciones.
+
+Para el resto, **FastAPI** lo maneja por ti.
+
+///
+
+## Actualizar las dependencias { #update-the-dependencies }
+
+Ahora vamos a actualizar nuestras dependencias.
+
+Queremos obtener el `current_user` *solo* si este usuario está activo.
+
+Entonces, creamos una dependencia adicional `get_current_active_user` que a su vez utiliza `get_current_user` como dependencia.
+
+Ambas dependencias solo devolverán un error HTTP si el usuario no existe, o si está inactivo.
+
+Así que, en nuestro endpoint, solo obtendremos un usuario si el usuario existe, fue autenticado correctamente, y está activo:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}
+
+/// info | Información
+
+El header adicional `WWW-Authenticate` con el valor `Bearer` que estamos devolviendo aquí también es parte de la especificación.
+
+Cualquier código de estado HTTP (error) 401 "UNAUTHORIZED" se supone que también debe devolver un header `WWW-Authenticate`.
+
+En el caso de tokens bearer (nuestro caso), el valor de ese header debe ser `Bearer`.
+
+De hecho, puedes omitir ese header extra y aún funcionaría.
+
+Pero se proporciona aquí para cumplir con las especificaciones.
+
+Además, podría haber herramientas que lo esperen y lo usen (ahora o en el futuro) y eso podría ser útil para ti o tus usuarios, ahora o en el futuro.
+
+Ese es el beneficio de los estándares...
+
+///
+
+## Verlo en acción { #see-it-in-action }
+
+Abre la documentación interactiva: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).
+
+### Autenticar { #authenticate }
+
+Haz clic en el botón "Authorize".
+
+Usa las credenciales:
+
+Usuario: `johndoe`
+
+Contraseña: `secret`
+
+
+
+Después de autenticarte en el sistema, lo verás así:
+
+
+
+### Obtener tus propios datos de usuario { #get-your-own-user-data }
+
+Ahora usa la operación `GET` con la path `/users/me`.
+
+Obtendrás los datos de tu usuario, como:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false,
+ "hashed_password": "fakehashedsecret"
+}
+```
+
+
+
+Si haces clic en el icono de candado y cierras sesión, y luego intentas la misma operación nuevamente, obtendrás un error HTTP 401 de:
+
+```JSON
+{
+ "detail": "Not authenticated"
+}
+```
+
+### Usuario inactivo { #inactive-user }
+
+Ahora prueba con un usuario inactivo, autentícate con:
+
+Usuario: `alice`
+
+Contraseña: `secret2`
+
+Y trata de usar la operación `GET` con la path `/users/me`.
+
+Obtendrás un error de "Usuario inactivo", como:
+
+```JSON
+{
+ "detail": "Inactive user"
+}
+```
+
+## Recapitulación { #recap }
+
+Ahora tienes las herramientas para implementar un sistema de seguridad completo basado en `username` y `password` para tu API.
+
+Usando estas herramientas, puedes hacer que el sistema de seguridad sea compatible con cualquier base de datos y con cualquier modelo de usuario o de datos.
+
+El único detalle que falta es que en realidad no es "seguro" aún.
+
+En el próximo capítulo verás cómo usar un paquete de hashing de passwords seguro y tokens JWT.
diff --git a/docs/es/docs/tutorial/server-sent-events.md b/docs/es/docs/tutorial/server-sent-events.md
new file mode 100644
index 0000000000000..0a008c0de64e2
--- /dev/null
+++ b/docs/es/docs/tutorial/server-sent-events.md
@@ -0,0 +1,120 @@
+# Server-Sent Events (SSE) { #server-sent-events-sse }
+
+Puedes enviar datos en streaming al cliente usando **Server-Sent Events** (SSE).
+
+Esto es similar a [Stream JSON Lines](stream-json-lines.md), pero usa el formato `text/event-stream`, que los navegadores soportan de forma nativa con la [`EventSource` API](https://developer.mozilla.org/en-US/docs/Web/API/EventSource).
+
+/// info | Información
+
+Añadido en FastAPI 0.135.0.
+
+///
+
+## ¿Qué son los Server-Sent Events? { #what-are-server-sent-events }
+
+SSE es un estándar para hacer streaming de datos desde el servidor al cliente sobre HTTP.
+
+Cada evento es un pequeño bloque de texto con “campos” como `data`, `event`, `id` y `retry`, separados por líneas en blanco.
+
+Se ve así:
+
+```
+data: {"name": "Portal Gun", "price": 999.99}
+
+data: {"name": "Plumbus", "price": 32.99}
+
+```
+
+SSE se usa comúnmente para streaming de chat de IA, notificaciones en vivo, logs y observabilidad, y otros casos donde el servidor envía actualizaciones al cliente.
+
+/// tip | Consejo
+
+Si quieres hacer streaming de datos binarios, por ejemplo video o audio, Revisa la guía avanzada: [Stream Data](../advanced/stream-data.md).
+
+///
+
+## Streaming de SSE con FastAPI { #stream-sse-with-fastapi }
+
+Para hacer streaming de SSE con FastAPI, usa `yield` en tu path operation function y establece `response_class=EventSourceResponse`.
+
+import `EventSourceResponse` de `fastapi.sse`:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[4,22] *}
+
+Cada ítem producido con `yield` se codifica como JSON y se envía en el campo `data:` de un evento SSE.
+
+Si declaras el tipo de retorno como `AsyncIterable[Item]`, FastAPI lo usará para **validar**, **documentar** y **serializar** los datos usando Pydantic.
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[10:12,23] *}
+
+/// tip | Consejo
+
+Como Pydantic lo serializará en el lado de **Rust**, obtendrás un **rendimiento** mucho mayor que si no declaras un tipo de retorno.
+
+///
+
+### No async *path operation functions* { #non-async-path-operation-functions }
+
+También puedes usar funciones `def` normales (sin `async`), y usar `yield` de la misma manera.
+
+FastAPI se asegurará de ejecutarlo correctamente para que no bloquee el event loop.
+
+Como en este caso la función no es async, el tipo de retorno correcto sería `Iterable[Item]`:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[28:31] hl[29] *}
+
+### Sin tipo de retorno { #no-return-type }
+
+También puedes omitir el tipo de retorno. FastAPI usará el [`jsonable_encoder`](./encoder.md) para convertir los datos y enviarlos.
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[34:37] hl[35] *}
+
+## `ServerSentEvent` { #serversentevent }
+
+Si necesitas configurar campos SSE como `event`, `id`, `retry` o `comment`, puedes hacer `yield` de objetos `ServerSentEvent` en lugar de datos simples.
+
+import `ServerSentEvent` de `fastapi.sse`:
+
+{* ../../docs_src/server_sent_events/tutorial002_py310.py hl[4,26] *}
+
+El campo `data` siempre se codifica como JSON. Puedes pasar cualquier valor que pueda serializarse como JSON, incluidos modelos de Pydantic.
+
+## Datos sin procesar { #raw-data }
+
+Si necesitas enviar datos **sin** codificarlos a JSON, usa `raw_data` en lugar de `data`.
+
+Esto es útil para enviar texto preformateado, líneas de log, o valores especiales de "centinela" como `[DONE]`.
+
+{* ../../docs_src/server_sent_events/tutorial003_py310.py hl[17] *}
+
+/// note | Nota
+
+`data` y `raw_data` son mutuamente excluyentes. Solo puedes establecer uno de ellos en cada `ServerSentEvent`.
+
+///
+
+## Reanudar con `Last-Event-ID` { #resuming-with-last-event-id }
+
+Cuando un navegador se reconecta después de una caída de la conexión, envía el último `id` recibido en el header `Last-Event-ID`.
+
+Puedes leerlo como un parámetro de header y usarlo para reanudar el stream desde donde el cliente se quedó:
+
+{* ../../docs_src/server_sent_events/tutorial004_py310.py hl[25,27,31] *}
+
+## SSE con `POST` { #sse-with-post }
+
+SSE funciona con **cualquier método HTTP**, no solo con `GET`.
+
+Esto es útil para protocolos como [MCP](https://modelcontextprotocol.io) que hacen streaming de SSE sobre `POST`:
+
+{* ../../docs_src/server_sent_events/tutorial005_py310.py hl[14] *}
+
+## Detalles técnicos { #technical-details }
+
+FastAPI implementa algunas mejores prácticas de SSE desde el primer momento.
+
+- Enviar un comentario de **"keep alive" `ping`** cada 15 segundos cuando no ha habido ningún mensaje, para evitar que algunos proxies cierren la conexión, como se sugiere en la [Especificación HTML: Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes).
+- Configurar el header `Cache-Control: no-cache` para **evitar el almacenamiento en caché** del stream.
+- Configurar un header especial `X-Accel-Buffering: no` para **evitar el buffering** en algunos proxies como Nginx.
+
+No tienes que hacer nada, funciona tal cual viene. 🤓
diff --git a/docs/es/docs/tutorial/sql-databases.md b/docs/es/docs/tutorial/sql-databases.md
new file mode 100644
index 0000000000000..7131716ee8668
--- /dev/null
+++ b/docs/es/docs/tutorial/sql-databases.md
@@ -0,0 +1,357 @@
+# Bases de Datos SQL (Relacionales) { #sql-relational-databases }
+
+**FastAPI** no requiere que uses una base de datos SQL (relacional). Pero puedes utilizar **cualquier base de datos** que desees.
+
+Aquí veremos un ejemplo usando [SQLModel](https://sqlmodel.tiangolo.com/).
+
+**SQLModel** está construido sobre [SQLAlchemy](https://www.sqlalchemy.org/) y Pydantic. Fue creado por el mismo autor de **FastAPI** para ser la combinación perfecta para aplicaciones de FastAPI que necesiten usar **bases de datos SQL**.
+
+/// tip | Consejo
+
+Puedes usar cualquier otro paquete de bases de datos SQL o NoSQL que quieras (en algunos casos llamadas "ORMs"), FastAPI no te obliga a usar nada. 😎
+
+///
+
+Como SQLModel se basa en SQLAlchemy, puedes usar fácilmente **cualquier base de datos soportada** por SQLAlchemy (lo que las hace también soportadas por SQLModel), como:
+
+* PostgreSQL
+* MySQL
+* SQLite
+* Oracle
+* Microsoft SQL Server, etc.
+
+En este ejemplo, usaremos **SQLite**, porque utiliza un solo archivo y Python tiene soporte integrado. Así que puedes copiar este ejemplo y ejecutarlo tal cual.
+
+Más adelante, para tu aplicación en producción, es posible que desees usar un servidor de base de datos como **PostgreSQL**.
+
+/// tip | Consejo
+
+Hay un generador de proyectos oficial con **FastAPI** y **PostgreSQL** que incluye un frontend y más herramientas: [https://github.com/fastapi/full-stack-fastapi-template](https://github.com/fastapi/full-stack-fastapi-template)
+
+///
+
+Este es un tutorial muy simple y corto, si deseas aprender sobre bases de datos en general, sobre SQL o más funcionalidades avanzadas, ve a la [documentación de SQLModel](https://sqlmodel.tiangolo.com/).
+
+## Instalar `SQLModel` { #install-sqlmodel }
+
+Primero, asegúrate de crear tu [entorno virtual](../virtual-environments.md), actívalo, y luego instala `sqlmodel`:
+
+
+
+
-
-و سپس اسناد زیر برنامه را در آدرس http://127.0.0.1:8000/subapi/docs. باز کنید.
-
-اسناد API خودکار برای زیر برنامه را خواهید دید، که فقط شامل path operations خود می شود، همه در زیر مسیر `/subapi` قرار دارند:
-
-
-
-اگر سعی کنید با هر یک از این دو رابط کاربری تعامل داشته باشید، آنها به درستی کار می کنند، زیرا مرورگر می تواند با هر یک از برنامه ها یا زیر برنامه های خاص صحبت کند.
-
-### جرئیات فنی : `root_path`
-
-هنگامی که یک زیر برنامه را همانطور که در بالا توضیح داده شد متصل می کنید, FastAPI با استفاده از مکانیزمی از مشخصات ASGI به نام `root_path` ارتباط مسیر mount را برای زیر برنامه انجام می دهد.
-
-به این ترتیب، زیر برنامه می داند که از آن پیشوند مسیر برای رابط کاربری اسناد (docs UI) استفاده کند.
-
-و زیر برنامه ها نیز می تواند زیر برنامه های متصل شده خود را داشته باشد و همه چیز به درستی کار کند، زیرا FastAPI تمام این مسیرهای `root_path` را به طور خودکار مدیریت می کند.
-
-در بخش [پشت پراکسی](./behind-a-proxy.md){.internal-link target=_blank}. درباره `root_path` و نحوه استفاده درست از آن بیشتر خواهید آموخت.
diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md
deleted file mode 100644
index 2480843891c5e..0000000000000
--- a/docs/fa/docs/index.md
+++ /dev/null
@@ -1,461 +0,0 @@
-
-- فریمورک FastAPI، کارایی بالا، یادگیری آسان، کدنویسی سریع، آماده برای استفاده در محیط پروداکشن -
- - ---- - -**مستندات**: https://fastapi.tiangolo.com - -**کد منبع**: https://github.com/tiangolo/fastapi - ---- -FastAPI یک وب فریمورک مدرن و سریع (با کارایی بالا) برای ایجاد APIهای متنوع (وب، وبسوکت و غبره) با زبان پایتون نسخه +۳.۶ است. این فریمورک با رعایت کامل راهنمای نوع داده (Type Hint) ایجاد شده است. - -ویژگیهای کلیدی این فریمورک عبارتند از: - -* **سرعت**: کارایی بسیار بالا و قابل مقایسه با **NodeJS** و **Go** (با تشکر از Starlette و Pydantic). [یکی از سریعترین فریمورکهای پایتونی موجود](#performance). - -* **کدنویسی سریع**: افزایش ۲۰۰ تا ۳۰۰ درصدی سرعت توسعه فابلیتهای جدید. * -* **باگ کمتر**: کاهش ۴۰ درصدی خطاهای انسانی (برنامهنویسی). * -* **غریزی**: پشتیبانی فوقالعاده در محیطهای توسعه یکپارچه (IDE). تکمیل در همه بخشهای کد. کاهش زمان رفع باگ. -* **آسان**: طراحی شده برای یادگیری و استفاده آسان. کاهش زمان مورد نیاز برای مراجعه به مستندات. -* **کوچک**: کاهش تکرار در کد. چندین قابلیت برای هر پارامتر (منظور پارامترهای ورودی تابع هندلر میباشد، به بخش خلاصه در همین صفحه مراجعه شود). باگ کمتر. -* **استوار**: ایجاد کدی آماده برای استفاده در محیط پروداکشن و تولید خودکار مستندات تعاملی -* **مبتنی بر استانداردها**: مبتنی بر (و منطبق با) استانداردهای متن باز مربوط به API: OpenAPI (سوگر سابق) و JSON Schema. - -* تخمینها بر اساس تستهای انجام شده در یک تیم توسعه داخلی که مشغول ایجاد برنامههای کاربردی واقعی بودند صورت گرفته است. - -## اسپانسرهای طلایی - - - -{% if sponsors %} -{% for sponsor in sponsors.gold -%} -async def... نیز استفاده کنیدuvicorn main:app --reload...email_validator - برای اعتبارسنجی آدرسهای ایمیل.
-
-استفاده شده توسط Starlette:
-
-* HTTPX - در صورتی که میخواهید از `TestClient` استفاده کنید.
-* aiofiles - در صورتی که میخواهید از `FileResponse` و `StaticFiles` استفاده کنید.
-* jinja2 - در صورتی که بخواهید از پیکربندی پیشفرض برای قالبها استفاده کنید.
-* python-multipart - در صورتی که بخواهید با استفاده از `request.form()` از قابلیت "تجزیه (parse)" فرم استفاده کنید.
-* itsdangerous - در صورتی که بخواید از `SessionMiddleware` پشتیبانی کنید.
-* pyyaml - برای پشتیبانی `SchemaGenerator` در Starlet (به احتمال زیاد برای کار کردن با FastAPI به آن نیازی پیدا نمیکنید.).
-* graphene - در صورتی که از `GraphQLApp` پشتیبانی میکنید.
-* ujson - در صورتی که بخواهید از `UJSONResponse` استفاده کنید.
-
-استفاده شده توسط FastAPI / Starlette:
-
-* uvicorn - برای سرور اجرا کننده برنامه وب.
-* orjson - در صورتی که بخواهید از `ORJSONResponse` استفاده کنید.
-
-میتوان همه این موارد را با استفاده از دستور `pip install fastapi[all]`. به صورت یکجا نصب کرد.
-
-## لایسنس
-
-این پروژه مشمول قوانین و مقررات لایسنس MIT است.
diff --git a/docs/fa/mkdocs.yml b/docs/fa/mkdocs.yml
deleted file mode 100644
index de18856f445aa..0000000000000
--- a/docs/fa/mkdocs.yml
+++ /dev/null
@@ -1 +0,0 @@
-INHERIT: ../en/mkdocs.yml
diff --git a/docs/fr/docs/_llm-test.md b/docs/fr/docs/_llm-test.md
new file mode 100644
index 0000000000000..74f9c9903c015
--- /dev/null
+++ b/docs/fr/docs/_llm-test.md
@@ -0,0 +1,503 @@
+# Fichier de test LLM { #llm-test-file }
+
+Ce document teste si le LLM, qui traduit la documentation, comprend le `general_prompt` dans `scripts/translate.py` et l’invite spécifique à la langue dans `docs/{language code}/llm-prompt.md`. L’invite spécifique à la langue est ajoutée à la fin de `general_prompt`.
+
+Les tests ajoutés ici seront visibles par tous les concepteurs d’invites spécifiques à chaque langue.
+
+Utiliser comme suit :
+
+* Avoir une invite spécifique à la langue - `docs/{language code}/llm-prompt.md`.
+* Effectuer une nouvelle traduction de ce document dans votre langue cible souhaitée (voir par exemple la commande `translate-page` de `translate.py`). Cela créera la traduction sous `docs/{language code}/docs/_llm-test.md`.
+* Vérifier si tout est correct dans la traduction.
+* Si nécessaire, améliorer votre invite spécifique à la langue, l’invite générale, ou le document anglais.
+* Corriger ensuite manuellement les problèmes restants dans la traduction, afin que ce soit une bonne traduction.
+* Retraduire, en ayant la bonne traduction en place. Le résultat idéal serait que le LLM ne fasse plus aucun changement à la traduction. Cela signifie que l’invite générale et votre invite spécifique à la langue sont aussi bonnes que possible (il fera parfois quelques changements apparemment aléatoires, la raison étant que [les LLM ne sont pas des algorithmes déterministes](https://doublespeak.chat/#/handbook#deterministic-output)).
+
+Les tests :
+
+## Extraits de code { #code-snippets }
+
+//// tab | Test
+
+Ceci est un extrait de code : `foo`. Et ceci est un autre extrait de code : `bar`. Et encore un autre : `baz quux`.
+
+////
+
+//// tab | Info
+
+Le contenu des extraits de code doit être laissé tel quel.
+
+Voir la section `### Content of code snippets` dans l’invite générale dans `scripts/translate.py`.
+
+////
+
+## Guillemets { #quotes }
+
+//// tab | Test
+
+Hier, mon ami a écrit : « Si vous écrivez « incorrectly » correctement, vous l’avez écrit de façon incorrecte ». À quoi j’ai répondu : « Correct, mais ‘incorrectly’ est incorrectement non pas ‘« incorrectly »’ ».
+
+/// note | Remarque
+
+Le LLM traduira probablement ceci de manière erronée. Il est seulement intéressant de voir s’il conserve la traduction corrigée lors d’une retraduction.
+
+///
+
+////
+
+//// tab | Info
+
+Le concepteur de l’invite peut choisir s’il souhaite convertir les guillemets neutres en guillemets typographiques. Il est acceptable de les laisser tels quels.
+
+Voir par exemple la section `### Quotes` dans `docs/de/llm-prompt.md`.
+
+////
+
+## Guillemets dans les extraits de code { #quotes-in-code-snippets }
+
+//// tab | Test
+
+`pip install "foo[bar]"`
+
+Exemples de littéraux de chaîne dans des extraits de code : `"this"`, `'that'`.
+
+Un exemple difficile de littéraux de chaîne dans des extraits de code : `f"I like {'oranges' if orange else "apples"}"`
+
+Hardcore: `Yesterday, my friend wrote: "If you spell incorrectly correctly, you have spelled it incorrectly". To which I answered: "Correct, but 'incorrectly' is incorrectly not '"incorrectly"'"`
+
+////
+
+//// tab | Info
+
+... Cependant, les guillemets à l’intérieur des extraits de code doivent rester tels quels.
+
+////
+
+## Blocs de code { #code-blocks }
+
+//// tab | Test
+
+Un exemple de code Bash ...
+
+```bash
+# Afficher un message de bienvenue à l'univers
+echo "Hello universe"
+```
+
+... et un exemple de code console ...
+
+```console
+$ fastapi run main.py
+ FastAPI Starting server
+ Searching for package file structure
+```
+
+... et un autre exemple de code console ...
+
+```console
+// Créer un répertoire "Code"
+$ mkdir code
+// Aller dans ce répertoire
+$ cd code
+```
+
+... et un exemple de code Python ...
+
+```Python
+wont_work() # Cela ne fonctionnera pas 😱
+works(foo="bar") # Cela fonctionne 🎉
+```
+
+... et c’est tout.
+
+////
+
+//// tab | Info
+
+Le code dans les blocs de code ne doit pas être modifié, à l’exception des commentaires.
+
+Voir la section `### Content of code blocks` dans l’invite générale dans `scripts/translate.py`.
+
+////
+
+## Onglets et encadrés colorés { #tabs-and-colored-boxes }
+
+//// tab | Test
+
+/// info | Info
+Du texte
+///
+
+/// note | Remarque
+Du texte
+///
+
+/// note | Détails techniques
+Du texte
+///
+
+/// check | Vérifications
+Du texte
+///
+
+/// tip | Astuce
+Du texte
+///
+
+/// warning | Alertes
+Du texte
+///
+
+/// danger | Danger
+Du texte
+///
+
+////
+
+//// tab | Info
+
+Les onglets et les blocs « Info »/« Note »/« Warning »/etc. doivent avoir la traduction de leur titre ajoutée après une barre verticale (« | »).
+
+Voir les sections `### Special blocks` et `### Tab blocks` dans l’invite générale dans `scripts/translate.py`.
+
+////
+
+## Liens Web et internes { #web-and-internal-links }
+
+//// tab | Test
+
+Le texte du lien doit être traduit, l’adresse du lien doit rester inchangée :
+
+* [Lien vers le titre ci-dessus](#code-snippets)
+* [Lien interne](index.md#installation)
+* [Lien externe](https://sqlmodel.tiangolo.com/)
+* [Lien vers une feuille de style](https://fastapi.tiangolo.com/css/styles.css)
+* [Lien vers un script](https://fastapi.tiangolo.com/js/logic.js)
+* [Lien vers une image](https://fastapi.tiangolo.com/img/foo.jpg)
+
+Le texte du lien doit être traduit, l’adresse du lien doit pointer vers la traduction :
+
+* [Lien FastAPI](https://fastapi.tiangolo.com/fr/)
+
+////
+
+//// tab | Info
+
+Les liens doivent être traduits, mais leur adresse doit rester inchangée. Exception faite des liens absolus vers des pages de la documentation FastAPI. Dans ce cas, il faut pointer vers la traduction.
+
+Voir la section `### Links` dans l’invite générale dans `scripts/translate.py`.
+
+////
+
+## Éléments HTML « abbr » { #html-abbr-elements }
+
+//// tab | Test
+
+Voici quelques éléments entourés d’un élément HTML « abbr » (certains sont inventés) :
+
+### L’abbr fournit une expression complète { #the-abbr-gives-a-full-phrase }
+
+* GTD
+* lt
+* XWT
+* PSGI
+
+### L’abbr donne une expression complète et une explication { #the-abbr-gives-a-full-phrase-and-an-explanation }
+
+* MDN
+* I/O.
+
+////
+
+//// tab | Info
+
+Les attributs « title » des éléments « abbr » sont traduits en suivant des consignes spécifiques.
+
+Les traductions peuvent ajouter leurs propres éléments « abbr » que le LLM ne doit pas supprimer. Par exemple pour expliquer des mots anglais.
+
+Voir la section `### HTML abbr elements` dans l’invite générale dans `scripts/translate.py`.
+
+////
+
+## Éléments HTML « dfn » { #html-dfn-elements }
+
+* grappe
+* Apprentissage profond
+
+## Titres { #headings }
+
+//// tab | Test
+
+### Créer une application Web - un tutoriel { #develop-a-webapp-a-tutorial }
+
+Bonjour.
+
+### Annotations de type et annotations de type { #type-hints-and-annotations }
+
+Rebonjour.
+
+### Superclasses et sous-classes { #super-and-subclasses }
+
+Rebonjour.
+
+////
+
+//// tab | Info
+
+La seule règle stricte pour les titres est que le LLM laisse la partie hachage entre accolades inchangée, ce qui garantit que les liens ne se rompent pas.
+
+Voir la section `### Headings` dans l’invite générale dans `scripts/translate.py`.
+
+Pour certaines consignes spécifiques à la langue, voir par exemple la section `### Headings` dans `docs/de/llm-prompt.md`.
+
+////
+
+## Termes utilisés dans les documents { #terms-used-in-the-docs }
+
+//// tab | Test
+
+* vous
+* votre
+
+* p. ex.
+* etc.
+
+* `foo` en tant que `int`
+* `bar` en tant que `str`
+* `baz` en tant que `list`
+
+* le Tutoriel - Guide utilisateur
+* le Guide utilisateur avancé
+* la documentation SQLModel
+* la documentation de l’API
+* la documentation automatique
+
+* Data Science
+* Apprentissage profond
+* Apprentissage automatique
+* Injection de dépendances
+* authentification HTTP Basic
+* HTTP Digest
+* format ISO
+* la norme JSON Schema
+* le schéma JSON
+* la définition de schéma
+* Flux Password
+* Mobile
+
+* déprécié
+* conçu
+* invalide
+* à la volée
+* standard
+* par défaut
+* sensible à la casse
+* insensible à la casse
+
+* servir l’application
+* servir la page
+
+* l’app
+* l’application
+
+* la requête
+* la réponse
+* la réponse d’erreur
+
+* le chemin d’accès
+* le décorateur de chemin d’accès
+* la fonction de chemin d’accès
+
+* le corps
+* le corps de la requête
+* le corps de la réponse
+* le corps JSON
+* le corps de formulaire
+* le corps de fichier
+* le corps de la fonction
+
+* le paramètre
+* le paramètre de corps
+* le paramètre de chemin
+* le paramètre de requête
+* le paramètre de cookie
+* le paramètre d’en-tête
+* le paramètre de formulaire
+* le paramètre de fonction
+
+* l’événement
+* l’événement de démarrage
+* le démarrage du serveur
+* l’événement d’arrêt
+* l’événement de cycle de vie
+
+* le gestionnaire
+* le gestionnaire d’événements
+* le gestionnaire d’exceptions
+* gérer
+
+* le modèle
+* le modèle Pydantic
+* le modèle de données
+* le modèle de base de données
+* le modèle de formulaire
+* l’objet modèle
+
+* la classe
+* la classe de base
+* la classe parente
+* la sous-classe
+* la classe enfant
+* la classe sœur
+* la méthode de classe
+
+* l’en-tête
+* les en-têtes
+* l’en-tête d’autorisation
+* l’en-tête `Authorization`
+* l’en-tête transféré
+
+* le système d’injection de dépendances
+* la dépendance
+* l’élément dépendable
+* le dépendant
+
+* lié aux E/S
+* lié au processeur
+* concurrence
+* parallélisme
+* multi-traitement
+
+* la variable d’env
+* la variable d’environnement
+* le `PATH`
+* la variable `PATH`
+
+* l’authentification
+* le fournisseur d’authentification
+* l’autorisation
+* le formulaire d’autorisation
+* le fournisseur d’autorisation
+* l’utilisateur s’authentifie
+* le système authentifie l’utilisateur
+
+* la CLI
+* l’interface en ligne de commande
+
+* le serveur
+* le client
+
+* le fournisseur cloud
+* le service cloud
+
+* le développement
+* les étapes de développement
+
+* le dict
+* le dictionnaire
+* l’énumération
+* l’enum
+* le membre d’enum
+
+* l’encodeur
+* le décodeur
+* encoder
+* décoder
+
+* l’exception
+* lever
+
+* l’expression
+* l’instruction
+
+* le frontend
+* le backend
+
+* la discussion GitHub
+* le ticket GitHub
+
+* la performance
+* l’optimisation des performances
+
+* le type de retour
+* la valeur de retour
+
+* la sécurité
+* le schéma de sécurité
+
+* la tâche
+* la tâche d’arrière-plan
+* la fonction de tâche
+
+* le template
+* le moteur de templates
+
+* l’annotation de type
+* l’annotation de type
+
+* le worker du serveur
+* le worker Uvicorn
+* le Worker Gunicorn
+* le processus worker
+* la classe de worker
+* la charge de travail
+
+* le déploiement
+* déployer
+
+* le SDK
+* le kit de développement logiciel
+
+* le `APIRouter`
+* le `requirements.txt`
+* le jeton Bearer
+* le changement majeur incompatible
+* le bogue
+* le bouton
+* l’appelable
+* le code
+* le commit
+* le gestionnaire de contexte
+* la coroutine
+* la session de base de données
+* le disque
+* le domaine
+* le moteur
+* le faux X
+* la méthode HTTP GET
+* l’élément
+* la bibliothèque
+* le cycle de vie
+* le verrou
+* le middleware
+* l’application mobile
+* le module
+* le montage
+* le réseau
+* l’origine
+* la surcharge
+* le payload
+* le processeur
+* la propriété
+* le proxy
+* la pull request
+* la requête
+* la RAM
+* la machine distante
+* le code d’état
+* la chaîne
+* l’étiquette
+* le framework Web
+* le joker
+* retourner
+* valider
+
+////
+
+//// tab | Info
+
+Il s’agit d’une liste non exhaustive et non normative de termes (principalement) techniques présents dans les documents. Elle peut aider le concepteur de l’invite à déterminer pour quels termes le LLM a besoin d’un coup de main. Par exemple, lorsqu’il continue de remplacer une bonne traduction par une traduction sous-optimale. Ou lorsqu’il a des difficultés à conjuguer/décliner un terme dans votre langue.
+
+Voir par exemple la section `### List of English terms and their preferred German translations` dans `docs/de/llm-prompt.md`.
+
+////
diff --git a/docs/fr/docs/about/index.md b/docs/fr/docs/about/index.md
new file mode 100644
index 0000000000000..f6ec12a4f807f
--- /dev/null
+++ b/docs/fr/docs/about/index.md
@@ -0,0 +1,3 @@
+# À propos { #about }
+
+À propos de FastAPI, de sa conception, de ses sources d'inspiration et plus encore. 🤓
diff --git a/docs/fr/docs/advanced/additional-responses.md b/docs/fr/docs/advanced/additional-responses.md
index 35b57594d5975..e7b684e36c4f8 100644
--- a/docs/fr/docs/advanced/additional-responses.md
+++ b/docs/fr/docs/advanced/additional-responses.md
@@ -1,19 +1,22 @@
-# Réponses supplémentaires dans OpenAPI
+# Réponses supplémentaires dans OpenAPI { #additional-responses-in-openapi }
-!!! Attention
- Ceci concerne un sujet plutôt avancé.
+/// warning | Alertes
- Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin.
+Ceci concerne un sujet plutôt avancé.
-Vous pouvez déclarer des réponses supplémentaires, avec des codes HTTP, des types de médias, des descriptions, etc.
+Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin.
+
+///
+
+Vous pouvez déclarer des réponses supplémentaires, avec des codes d'état supplémentaires, des types de médias, des descriptions, etc.
Ces réponses supplémentaires seront incluses dans le schéma OpenAPI, elles apparaîtront donc également dans la documentation de l'API.
Mais pour ces réponses supplémentaires, vous devez vous assurer de renvoyer directement une `Response` comme `JSONResponse`, avec votre code HTTP et votre contenu.
-## Réponse supplémentaire avec `model`
+## Réponse supplémentaire avec `model` { #additional-response-with-model }
-Vous pouvez ajouter à votre décorateur de *paramètre de chemin* un paramètre `responses`.
+Vous pouvez passer à vos décorateurs de *chemin d'accès* un paramètre `responses`.
Il prend comme valeur un `dict` dont les clés sont des codes HTTP pour chaque réponse, comme `200`, et la valeur de ces clés sont d'autres `dict` avec des informations pour chacun d'eux.
@@ -23,26 +26,30 @@ Chacun de ces `dict` de réponse peut avoir une clé `model`, contenant un modè
Par exemple, pour déclarer une autre réponse avec un code HTTP `404` et un modèle Pydantic `Message`, vous pouvez écrire :
-```Python hl_lines="18 22"
-{!../../../docs_src/additional_responses/tutorial001.py!}
-```
+{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}
+
+/// note | Remarque
+
+Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`.
+
+///
+
+/// info
-!!! Remarque
- Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`.
+La clé `model` ne fait pas partie d'OpenAPI.
-!!! Info
- La clé `model` ne fait pas partie d'OpenAPI.
+**FastAPI** prendra le modèle Pydantic à partir de là, générera le `JSON Schema` et le placera au bon endroit.
- **FastAPI** prendra le modèle Pydantic à partir de là, générera le `JSON Schema` et le placera au bon endroit.
+Le bon endroit est :
- Le bon endroit est :
+* Dans la clé `content`, qui a pour valeur un autre objet JSON (`dict`) qui contient :
+ * Une clé avec le type de support, par ex. `application/json`, qui contient comme valeur un autre objet JSON, qui contient :
+ * Une clé `schema`, qui a pour valeur le schéma JSON du modèle, voici le bon endroit.
+ * **FastAPI** ajoute ici une référence aux schémas JSON globaux à un autre endroit de votre OpenAPI au lieu de l'inclure directement. De cette façon, d'autres applications et clients peuvent utiliser ces schémas JSON directement, fournir de meilleurs outils de génération de code, etc.
- * Dans la clé `content`, qui a pour valeur un autre objet JSON (`dict`) qui contient :
- * Une clé avec le type de support, par ex. `application/json`, qui contient comme valeur un autre objet JSON, qui contient :
- * Une clé `schema`, qui a pour valeur le schéma JSON du modèle, voici le bon endroit.
- * **FastAPI** ajoute ici une référence aux schémas JSON globaux à un autre endroit de votre OpenAPI au lieu de l'inclure directement. De cette façon, d'autres applications et clients peuvent utiliser ces schémas JSON directement, fournir de meilleurs outils de génération de code, etc.
+///
-Les réponses générées au format OpenAPI pour cette *opération de chemin* seront :
+Les réponses générées au format OpenAPI pour ce *chemin d'accès* seront :
```JSON hl_lines="3-12"
{
@@ -162,25 +169,29 @@ Les schémas sont référencés à un autre endroit du modèle OpenAPI :
}
```
-## Types de médias supplémentaires pour la réponse principale
+## Types de médias supplémentaires pour la réponse principale { #additional-media-types-for-the-main-response }
Vous pouvez utiliser ce même paramètre `responses` pour ajouter différents types de médias pour la même réponse principale.
-Par exemple, vous pouvez ajouter un type de média supplémentaire `image/png`, en déclarant que votre *opération de chemin* peut renvoyer un objet JSON (avec le type de média `application/json`) ou une image PNG :
+Par exemple, vous pouvez ajouter un type de média supplémentaire `image/png`, en déclarant que votre *chemin d'accès* peut renvoyer un objet JSON (avec le type de média `application/json`) ou une image PNG :
-```Python hl_lines="19-24 28"
-{!../../../docs_src/additional_responses/tutorial002.py!}
-```
+{* ../../docs_src/additional_responses/tutorial002_py310.py hl[17:22,26] *}
+
+/// note | Remarque
+
+Notez que vous devez retourner l'image en utilisant directement un `FileResponse`.
+
+///
-!!! Remarque
- Notez que vous devez retourner l'image en utilisant directement un `FileResponse`.
+/// info
-!!! Info
- À moins que vous ne spécifiiez explicitement un type de média différent dans votre paramètre `responses`, FastAPI supposera que la réponse a le même type de média que la classe de réponse principale (par défaut `application/json`).
+À moins que vous ne spécifiiez explicitement un type de média différent dans votre paramètre `responses`, FastAPI supposera que la réponse a le même type de média que la classe de réponse principale (par défaut `application/json`).
- Mais si vous avez spécifié une classe de réponse personnalisée avec `None` comme type de média, FastAPI utilisera `application/json` pour toute réponse supplémentaire associée à un modèle.
+Mais si vous avez spécifié une classe de réponse personnalisée avec `None` comme type de média, FastAPI utilisera `application/json` pour toute réponse supplémentaire associée à un modèle.
-## Combinaison d'informations
+///
+
+## Combiner les informations { #combining-information }
Vous pouvez également combiner des informations de réponse provenant de plusieurs endroits, y compris les paramètres `response_model`, `status_code` et `responses`.
@@ -192,21 +203,19 @@ Par exemple, vous pouvez déclarer une réponse avec un code HTTP `404` qui util
Et une réponse avec un code HTTP `200` qui utilise votre `response_model`, mais inclut un `example` personnalisé :
-```Python hl_lines="20-31"
-{!../../../docs_src/additional_responses/tutorial003.py!}
-```
+{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}
Tout sera combiné et inclus dans votre OpenAPI, et affiché dans la documentation de l'API :
-## Combinez les réponses prédéfinies et les réponses personnalisées
+## Combinez les réponses prédéfinies et les réponses personnalisées { #combine-predefined-responses-and-custom-ones }
-Vous voulez peut-être avoir des réponses prédéfinies qui s'appliquent à de nombreux *paramètre de chemin*, mais vous souhaitez les combiner avec des réponses personnalisées nécessaires à chaque *opération de chemin*.
+Vous voulez peut-être avoir des réponses prédéfinies qui s'appliquent à de nombreux *chemins d'accès*, mais vous souhaitez les combiner avec des réponses personnalisées nécessaires à chaque *chemin d'accès*.
-Dans ces cas, vous pouvez utiliser la technique Python "d'affection par décomposition" (appelé _unpacking_ en anglais) d'un `dict` avec `**dict_to_unpack` :
+Dans ces cas, vous pouvez utiliser la technique Python « unpacking » d'un `dict` avec `**dict_to_unpack` :
-``` Python
+```Python
old_dict = {
"old key": "old value",
"second old key": "second old value",
@@ -216,7 +225,7 @@ new_dict = {**old_dict, "new key": "new value"}
Ici, `new_dict` contiendra toutes les paires clé-valeur de `old_dict` plus la nouvelle paire clé-valeur :
-``` Python
+```Python
{
"old key": "old value",
"second old key": "second old value",
@@ -224,17 +233,15 @@ Ici, `new_dict` contiendra toutes les paires clé-valeur de `old_dict` plus la n
}
```
-Vous pouvez utiliser cette technique pour réutiliser certaines réponses prédéfinies dans vos *paramètres de chemin* et les combiner avec des réponses personnalisées supplémentaires.
+Vous pouvez utiliser cette technique pour réutiliser certaines réponses prédéfinies dans vos *chemins d'accès* et les combiner avec des réponses personnalisées supplémentaires.
Par exemple:
-```Python hl_lines="13-17 26"
-{!../../../docs_src/additional_responses/tutorial004.py!}
-```
+{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}
-## Plus d'informations sur les réponses OpenAPI
+## Plus d'informations sur les réponses OpenAPI { #more-information-about-openapi-responses }
Pour voir exactement ce que vous pouvez inclure dans les réponses, vous pouvez consulter ces sections dans la spécification OpenAPI :
-* Objet Responses de OpenAPI , il inclut le `Response Object`.
-* Objet Response de OpenAPI , vous pouvez inclure n'importe quoi directement dans chaque réponse à l'intérieur de votre paramètre `responses`. Y compris `description`, `headers`, `content` (à l'intérieur de cela, vous déclarez différents types de médias et schémas JSON) et `links`.
+* [Objet Responses de OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responses-object), il inclut le `Response Object`.
+* [Objet Response de OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#response-object), vous pouvez inclure n'importe quoi directement dans chaque réponse à l'intérieur de votre paramètre `responses`. Y compris `description`, `headers`, `content` (à l'intérieur de cela, vous déclarez différents types de médias et schémas JSON) et `links`.
diff --git a/docs/fr/docs/advanced/additional-status-codes.md b/docs/fr/docs/advanced/additional-status-codes.md
index e7b003707bf84..59e8c3eae9ce9 100644
--- a/docs/fr/docs/advanced/additional-status-codes.md
+++ b/docs/fr/docs/advanced/additional-status-codes.md
@@ -1,37 +1,41 @@
-# Codes HTTP supplémentaires
+# Codes HTTP supplémentaires { #additional-status-codes }
Par défaut, **FastAPI** renverra les réponses à l'aide d'une structure de données `JSONResponse`, en plaçant la réponse de votre *chemin d'accès* à l'intérieur de cette `JSONResponse`.
Il utilisera le code HTTP par défaut ou celui que vous avez défini dans votre *chemin d'accès*.
-## Codes HTTP supplémentaires
+## Codes HTTP supplémentaires { #additional-status-codes_1 }
Si vous souhaitez renvoyer des codes HTTP supplémentaires en plus du code principal, vous pouvez le faire en renvoyant directement une `Response`, comme une `JSONResponse`, et en définissant directement le code HTTP supplémentaire.
-Par exemple, disons que vous voulez avoir un *chemin d'accès* qui permet de mettre à jour les éléments et renvoie les codes HTTP 200 "OK" en cas de succès.
+Par exemple, disons que vous voulez avoir un *chemin d'accès* qui permet de mettre à jour les éléments et renvoie les codes HTTP 200 « OK » en cas de succès.
-Mais vous voulez aussi qu'il accepte de nouveaux éléments. Et lorsque les éléments n'existaient pas auparavant, il les crée et renvoie un code HTTP de 201 "Créé".
+Mais vous voulez aussi qu'il accepte de nouveaux éléments. Et lorsque les éléments n'existaient pas auparavant, il les crée et renvoie un code HTTP de 201 « Créé ».
Pour y parvenir, importez `JSONResponse` et renvoyez-y directement votre contenu, en définissant le `status_code` que vous souhaitez :
-```Python hl_lines="4 25"
-{!../../../docs_src/additional_status_codes/tutorial001.py!}
-```
+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
-!!! Attention
- Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement.
+/// warning | Alertes
- Elle ne sera pas sérialisée avec un modèle.
+Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement.
- Assurez-vous qu'il contient les données souhaitées et que les valeurs soient dans un format JSON valides (si vous utilisez une `JSONResponse`).
+Elle ne sera pas sérialisée avec un modèle, etc.
-!!! note "Détails techniques"
- Vous pouvez également utiliser `from starlette.responses import JSONResponse`.
+Vous devez vous assurer qu'elle contient les données souhaitées et que les valeurs sont dans un format JSON valide (si vous utilisez une `JSONResponse`).
- Pour plus de commodités, **FastAPI** fournit les objets `starlette.responses` sous forme d'un alias accessible par `fastapi.responses`. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en est de même avec l'objet `statut`.
+///
-## Documents OpenAPI et API
+/// note | Détails techniques
-Si vous renvoyez directement des codes HTTP et des réponses supplémentaires, ils ne seront pas inclus dans le schéma OpenAPI (la documentation de l'API), car FastAPI n'a aucun moyen de savoir à l'avance ce que vous allez renvoyer.
+Vous pouvez également utiliser `from starlette.responses import JSONResponse`.
-Mais vous pouvez documenter cela dans votre code, en utilisant : [Réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}.
+Par commodité pour vous, le développeur, **FastAPI** fournit les mêmes `starlette.responses` sous la forme de `fastapi.responses`. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en est de même avec `status`.
+
+///
+
+## Documents OpenAPI et API { #openapi-and-api-docs }
+
+Si vous renvoyez directement des codes HTTP et des réponses supplémentaires, ils ne seront pas inclus dans le schéma OpenAPI (les documents de l'API), car FastAPI n'a aucun moyen de savoir à l'avance ce que vous allez renvoyer.
+
+Mais vous pouvez documenter cela dans votre code, en utilisant : [Réponses supplémentaires](additional-responses.md).
diff --git a/docs/fr/docs/advanced/advanced-dependencies.md b/docs/fr/docs/advanced/advanced-dependencies.md
new file mode 100644
index 0000000000000..d5066ca25ab1d
--- /dev/null
+++ b/docs/fr/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,163 @@
+# Dépendances avancées { #advanced-dependencies }
+
+## Dépendances paramétrées { #parameterized-dependencies }
+
+Toutes les dépendances que nous avons vues étaient des fonctions ou des classes fixes.
+
+Mais il peut y avoir des cas où vous souhaitez pouvoir définir des paramètres sur la dépendance, sans devoir déclarer de nombreuses fonctions ou classes différentes.
+
+Imaginons que nous voulions avoir une dépendance qui vérifie si le paramètre de requête `q` contient un contenu fixe.
+
+Mais nous voulons pouvoir paramétrer ce contenu fixe.
+
+## Une instance « callable » { #a-callable-instance }
+
+En Python, il existe un moyen de rendre une instance de classe « callable ».
+
+Pas la classe elle‑même (qui est déjà un callable), mais une instance de cette classe.
+
+Pour cela, nous déclarons une méthode `__call__` :
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}
+
+Dans ce cas, ce `__call__` est ce que **FastAPI** utilisera pour détecter des paramètres supplémentaires et des sous‑dépendances, et c’est ce qui sera appelé pour transmettre ensuite une valeur au paramètre dans votre *fonction de chemin d'accès*.
+
+## Paramétrer l'instance { #parameterize-the-instance }
+
+Et maintenant, nous pouvons utiliser `__init__` pour déclarer les paramètres de l’instance, que nous utiliserons pour « paramétrer » la dépendance :
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}
+
+Dans ce cas, **FastAPI** n’accèdera pas à `__init__` et ne s’en souciera pas ; nous l’utiliserons directement dans notre code.
+
+## Créer une instance { #create-an-instance }
+
+Nous pouvons créer une instance de cette classe avec :
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}
+
+Et de cette façon, nous pouvons « paramétrer » notre dépendance, qui contient maintenant « bar », en tant qu’attribut `checker.fixed_content`.
+
+## Utiliser l'instance comme dépendance { #use-the-instance-as-a-dependency }
+
+Ensuite, nous pourrions utiliser ce `checker` dans un `Depends(checker)`, au lieu de `Depends(FixedContentQueryChecker)`, car la dépendance est l’instance, `checker`, et non la classe elle‑même.
+
+Et lors de la résolution de la dépendance, **FastAPI** appellera ce `checker` comme ceci :
+
+```Python
+checker(q="somequery")
+```
+
+... et passera ce que cela renvoie comme valeur de la dépendance à notre *fonction de chemin d'accès*, en tant que paramètre `fixed_content_included` :
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}
+
+/// tip | Astuce
+
+Tout cela peut sembler artificiel. Et il n’est peut‑être pas encore très clair en quoi c’est utile.
+
+Ces exemples sont volontairement simples, mais ils montrent comment tout cela fonctionne.
+
+Dans les chapitres sur la sécurité, il existe des fonctions utilitaires implémentées de la même manière.
+
+Si vous avez compris tout cela, vous savez déjà comment ces outils utilitaires pour la sécurité fonctionnent en interne.
+
+///
+
+## Dépendances avec `yield`, `HTTPException`, `except` et tâches d'arrière‑plan { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+/// warning | Alertes
+
+Vous n’avez très probablement pas besoin de ces détails techniques.
+
+Ces détails sont utiles principalement si vous aviez une application FastAPI antérieure à la version 0.121.0 et que vous rencontrez des problèmes avec des dépendances utilisant `yield`.
+
+///
+
+Les dépendances avec `yield` ont évolué au fil du temps pour couvrir différents cas d’utilisation et corriger certains problèmes ; voici un résumé de ce qui a changé.
+
+### Dépendances avec `yield` et `scope` { #dependencies-with-yield-and-scope }
+
+Dans la version 0.121.0, **FastAPI** a ajouté la prise en charge de `Depends(scope="function")` pour les dépendances avec `yield`.
+
+Avec `Depends(scope="function")`, le code d’arrêt après `yield` s’exécute immédiatement après la fin de la *fonction de chemin d'accès*, avant que la réponse ne soit renvoyée au client.
+
+Et lorsque vous utilisez `Depends(scope="request")` (valeur par défaut), le code d’arrêt après `yield` s’exécute après l’envoi de la réponse.
+
+Vous pouvez en lire davantage dans les documents pour [Dépendances avec `yield` - Sortie anticipée et `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope).
+
+### Dépendances avec `yield` et `StreamingResponse`, Détails techniques { #dependencies-with-yield-and-streamingresponse-technical-details }
+
+Avant FastAPI 0.118.0, si vous utilisiez une dépendance avec `yield`, elle exécutait le code d’arrêt après que la *fonction de chemin d'accès* a retourné, mais juste avant d’envoyer la réponse.
+
+L’objectif était d’éviter de conserver des ressources plus longtemps que nécessaire pendant que la réponse transitait sur le réseau.
+
+Ce changement impliquait aussi que si vous retourniez une `StreamingResponse`, le code d’arrêt de la dépendance avec `yield` aurait déjà été exécuté.
+
+Par exemple, si vous aviez une session de base de données dans une dépendance avec `yield`, la `StreamingResponse` ne pourrait pas utiliser cette session pendant le streaming des données, car la session aurait déjà été fermée dans le code d’arrêt après `yield`.
+
+Ce comportement a été annulé en 0.118.0, afin que le code d’arrêt après `yield` s’exécute après l’envoi de la réponse.
+
+/// info
+
+Comme vous le verrez ci‑dessous, c’est très similaire au comportement avant la version 0.106.0, mais avec plusieurs améliorations et corrections de bogues pour des cas limites.
+
+///
+
+#### Cas d’utilisation avec sortie anticipée du code { #use-cases-with-early-exit-code }
+
+Il existe certains cas d’utilisation avec des conditions spécifiques qui pourraient bénéficier de l’ancien comportement, où le code d’arrêt des dépendances avec `yield` s’exécute avant l’envoi de la réponse.
+
+Par exemple, imaginez que vous ayez du code qui utilise une session de base de données dans une dépendance avec `yield` uniquement pour vérifier un utilisateur, mais que la session de base de données ne soit plus jamais utilisée dans la *fonction de chemin d'accès*, seulement dans la dépendance, et que la réponse mette longtemps à être envoyée, comme une `StreamingResponse` qui envoie les données lentement mais qui, pour une raison quelconque, n’utilise pas la base de données.
+
+Dans ce cas, la session de base de données serait conservée jusqu’à la fin de l’envoi de la réponse, mais si vous ne l’utilisez pas, il ne serait pas nécessaire de la conserver.
+
+Voici à quoi cela pourrait ressembler :
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
+
+Le code d’arrêt, la fermeture automatique de la `Session` dans :
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
+
+... serait exécuté après que la réponse a fini d’envoyer les données lentes :
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
+
+Mais comme `generate_stream()` n’utilise pas la session de base de données, il n’est pas vraiment nécessaire de garder la session ouverte pendant l’envoi de la réponse.
+
+Si vous avez ce cas d’utilisation spécifique avec SQLModel (ou SQLAlchemy), vous pouvez fermer explicitement la session dès que vous n’en avez plus besoin :
+
+{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}
+
+De cette manière, la session libérera la connexion à la base de données, afin que d’autres requêtes puissent l’utiliser.
+
+Si vous avez un autre cas d’utilisation qui nécessite une sortie anticipée depuis une dépendance avec `yield`, veuillez créer une [Question de discussion GitHub](https://github.com/fastapi/fastapi/discussions/new?category=questions) avec votre cas spécifique et pourquoi vous bénéficieriez d’une fermeture anticipée pour les dépendances avec `yield`.
+
+S’il existe des cas d’utilisation convaincants pour une fermeture anticipée dans les dépendances avec `yield`, j’envisagerai d’ajouter une nouvelle façon d’y opter.
+
+### Dépendances avec `yield` et `except`, Détails techniques { #dependencies-with-yield-and-except-technical-details }
+
+Avant FastAPI 0.110.0, si vous utilisiez une dépendance avec `yield`, puis capturiez une exception avec `except` dans cette dépendance, et que vous ne relanciez pas l’exception, l’exception était automatiquement levée/transmise à tout gestionnaire d’exceptions ou au gestionnaire d’erreur interne du serveur.
+
+Cela a été modifié dans la version 0.110.0 pour corriger une consommation de mémoire non gérée due aux exceptions transmises sans gestionnaire (erreurs internes du serveur), et pour rendre le comportement cohérent avec celui du code Python classique.
+
+### Tâches d'arrière‑plan et dépendances avec `yield`, Détails techniques { #background-tasks-and-dependencies-with-yield-technical-details }
+
+Avant FastAPI 0.106.0, lever des exceptions après `yield` n’était pas possible, le code d’arrêt dans les dépendances avec `yield` s’exécutait après l’envoi de la réponse, donc les [Gestionnaires d'exceptions](../tutorial/handling-errors.md#install-custom-exception-handlers) avaient déjà été exécutés.
+
+Cela avait été conçu ainsi principalement pour permettre d’utiliser les mêmes objets « générés par yield » par les dépendances à l’intérieur de tâches d’arrière‑plan, car le code d’arrêt s’exécutait après la fin des tâches d’arrière‑plan.
+
+Cela a été modifié dans FastAPI 0.106.0 afin de ne pas conserver des ressources pendant l’attente de la transmission de la réponse sur le réseau.
+
+/// tip | Astuce
+
+De plus, une tâche d’arrière‑plan est normalement un ensemble de logique indépendant qui devrait être géré séparément, avec ses propres ressources (par ex. sa propre connexion à la base de données).
+
+Ainsi, vous aurez probablement un code plus propre.
+
+///
+
+Si vous comptiez sur ce comportement, vous devez désormais créer les ressources pour les tâches d’arrière‑plan à l’intérieur de la tâche elle‑même, et n’utiliser en interne que des données qui ne dépendent pas des ressources des dépendances avec `yield`.
+
+Par exemple, au lieu d’utiliser la même session de base de données, vous créeriez une nouvelle session de base de données à l’intérieur de la tâche d’arrière‑plan, et vous obtiendriez les objets depuis la base de données en utilisant cette nouvelle session. Puis, au lieu de passer l’objet obtenu depuis la base de données en paramètre à la fonction de tâche d’arrière‑plan, vous passeriez l’identifiant (ID) de cet objet et vous obtiendriez à nouveau l’objet à l’intérieur de la fonction de la tâche d’arrière‑plan.
diff --git a/docs/fr/docs/advanced/advanced-python-types.md b/docs/fr/docs/advanced/advanced-python-types.md
new file mode 100644
index 0000000000000..3e2d9453b6862
--- /dev/null
+++ b/docs/fr/docs/advanced/advanced-python-types.md
@@ -0,0 +1,61 @@
+# Types Python avancés { #advanced-python-types }
+
+Voici quelques idées supplémentaires qui peuvent être utiles lorsque vous travaillez avec les types Python.
+
+## Utiliser `Union` ou `Optional` { #using-union-or-optional }
+
+Si votre code ne peut pas utiliser `|` pour une raison quelconque, par exemple si ce n'est pas dans une annotation de type mais dans quelque chose comme `response_model=`, au lieu d'utiliser la barre verticale (`|`) vous pouvez utiliser `Union` de `typing`.
+
+Par exemple, vous pourriez déclarer que quelque chose peut être un `str` ou `None` :
+
+```python
+from typing import Union
+
+
+def say_hi(name: Union[str, None]):
+ print(f"Hi {name}!")
+```
+
+`typing` propose également un raccourci pour déclarer que quelque chose peut être `None`, avec `Optional`.
+
+Voici un conseil issu de mon point de vue très subjectif :
+
+- 🚨 Évitez d'utiliser `Optional[SomeType]`
+- À la place ✨ **utilisez `Union[SomeType, None]`** ✨.
+
+Les deux sont équivalents et, en interne, identiques, mais je recommande `Union` plutôt que `Optional` parce que le mot « optional » semble impliquer que la valeur est facultative, alors qu'il signifie en réalité « elle peut être `None` », même si elle n'est pas facultative et reste requise.
+
+Je pense que `Union[SomeType, None]` est plus explicite quant à sa signification.
+
+Il ne s'agit que des mots et des noms. Mais ces mots peuvent influencer la manière dont vous et vos coéquipiers pensez au code.
+
+À titre d'exemple, prenons cette fonction :
+
+```python
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+ print(f"Hey {name}!")
+```
+
+Le paramètre `name` est défini comme `Optional[str]`, mais il n'est pas facultatif, vous ne pouvez pas appeler la fonction sans le paramètre :
+
+```Python
+say_hi() # Oh non, cela lève une erreur ! 😱
+```
+
+Le paramètre `name` est toujours requis (pas facultatif) car il n'a pas de valeur par défaut. En revanche, `name` accepte `None` comme valeur :
+
+```Python
+say_hi(name=None) # Ceci fonctionne, None est valide 🎉
+```
+
+La bonne nouvelle, c'est que, dans la plupart des cas, vous pourrez simplement utiliser `|` pour définir des unions de types :
+
+```python
+def say_hi(name: str | None):
+ print(f"Hey {name}!")
+```
+
+Ainsi, normalement, vous n'avez pas à vous préoccuper de noms comme `Optional` et `Union`. 😎
diff --git a/docs/fr/docs/advanced/async-tests.md b/docs/fr/docs/advanced/async-tests.md
new file mode 100644
index 0000000000000..a59d651bad313
--- /dev/null
+++ b/docs/fr/docs/advanced/async-tests.md
@@ -0,0 +1,99 @@
+# Tests asynchrones { #async-tests }
+
+Vous avez déjà vu comment tester vos applications **FastAPI** en utilisant le `TestClient` fourni. Jusqu'à présent, vous n'avez vu que comment écrire des tests synchrones, sans utiliser de fonctions `async`.
+
+Pouvoir utiliser des fonctions asynchrones dans vos tests peut être utile, par exemple lorsque vous interrogez votre base de données de manière asynchrone. Imaginez que vous vouliez tester l'envoi de requêtes à votre application FastAPI puis vérifier que votre backend a bien écrit les bonnes données dans la base, tout en utilisant une bibliothèque de base de données asynchrone.
+
+Voyons comment procéder.
+
+## pytest.mark.anyio { #pytest-mark-anyio }
+
+Si nous voulons appeler des fonctions asynchrones dans nos tests, nos fonctions de test doivent être asynchrones. AnyIO fournit un plug-in pratique qui nous permet d'indiquer que certaines fonctions de test doivent être appelées de manière asynchrone.
+
+## HTTPX { #httpx }
+
+Même si votre application **FastAPI** utilise des fonctions `def` normales au lieu de `async def`, c'est toujours une application `async` en interne.
+
+Le `TestClient` fait un peu de magie pour appeler l'application FastAPI asynchrone depuis vos fonctions de test `def` normales, en utilisant pytest standard. Mais cette magie ne fonctionne plus lorsque nous l'utilisons dans des fonctions asynchrones. En exécutant nos tests de manière asynchrone, nous ne pouvons plus utiliser le `TestClient` dans nos fonctions de test.
+
+Le `TestClient` est basé sur [HTTPX](https://www.python-httpx.org) et, heureusement, nous pouvons l'utiliser directement pour tester l'API.
+
+## Exemple { #example }
+
+Pour un exemple simple, considérons une structure de fichiers similaire à celle décrite dans [Applications plus grandes](../tutorial/bigger-applications.md) et [Tests](../tutorial/testing.md) :
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+Le fichier `main.py` contiendrait :
+
+{* ../../docs_src/async_tests/app_a_py310/main.py *}
+
+Le fichier `test_main.py` contiendrait les tests pour `main.py`, il pourrait maintenant ressembler à ceci :
+
+{* ../../docs_src/async_tests/app_a_py310/test_main.py *}
+
+## Exécuter { #run-it }
+
+Vous pouvez lancer vos tests comme d'habitude via :
+
+
+
+Mais si nous accédons à l'interface de documents à l'URL « officielle » en utilisant le proxy avec le port `9999`, à `/api/v1/docs`, cela fonctionne correctement ! 🎉
+
+Vous pouvez le vérifier sur [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs) :
+
+
+
+Exactement comme nous le voulions. ✔️
+
+C'est parce que FastAPI utilise ce `root_path` pour créer le `server` par défaut dans OpenAPI avec l'URL fournie par `root_path`.
+
+## Serveurs supplémentaires { #additional-servers }
+
+/// warning | Alertes
+
+Ceci est un cas d'utilisation plus avancé. N'hésitez pas à l'ignorer.
+
+///
+
+Par défaut, **FastAPI** créera un `server` dans le schéma OpenAPI avec l'URL correspondant au `root_path`.
+
+Mais vous pouvez aussi fournir d'autres `servers` alternatifs, par exemple si vous voulez que la même interface de documents interagisse avec un environnement de staging et un environnement de production.
+
+Si vous passez une liste personnalisée de `servers` et qu'il y a un `root_path` (parce que votre API vit derrière un proxy), **FastAPI** insérera un « server » avec ce `root_path` au début de la liste.
+
+Par exemple :
+
+{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}
+
+Générera un schéma OpenAPI comme :
+
+```JSON hl_lines="5-7"
+{
+ "openapi": "3.1.0",
+ // Plus d'éléments ici
+ "servers": [
+ {
+ "url": "/api/v1"
+ },
+ {
+ "url": "https://stag.example.com",
+ "description": "Staging environment"
+ },
+ {
+ "url": "https://prod.example.com",
+ "description": "Production environment"
+ }
+ ],
+ "paths": {
+ // Plus d'éléments ici
+ }
+}
+```
+
+/// tip | Astuce
+
+Remarquez le serveur généré automatiquement avec une valeur `url` de `/api/v1`, repris depuis le `root_path`.
+
+///
+
+Dans l'interface de documents sur [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs), cela ressemblera à ceci :
+
+
+
+/// tip | Astuce
+
+L'interface de documents interagit avec le serveur que vous sélectionnez.
+
+///
+
+/// note | Détails techniques
+
+La propriété `servers` dans la spécification OpenAPI est facultative.
+
+Si vous ne spécifiez pas le paramètre `servers` et que `root_path` est égal à `/`, la propriété `servers` dans le schéma OpenAPI généré sera entièrement omise par défaut, ce qui équivaut à un seul serveur avec une valeur `url` de `/`.
+
+///
+
+### Désactiver le serveur automatique issu de `root_path` { #disable-automatic-server-from-root-path }
+
+Si vous ne voulez pas que **FastAPI** inclue un serveur automatique utilisant le `root_path`, vous pouvez utiliser le paramètre `root_path_in_servers=False` :
+
+{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}
+
+et il ne l'inclura alors pas dans le schéma OpenAPI.
+
+## Monter une sous-application { #mounting-a-sub-application }
+
+Si vous avez besoin de monter une sous‑application (comme décrit dans [Sous‑applications - montages](sub-applications.md)) tout en utilisant un proxy avec `root_path`, vous pouvez le faire normalement, comme vous vous y attendez.
+
+FastAPI utilisera intelligemment le `root_path` en interne, donc cela fonctionnera simplement. ✨
diff --git a/docs/fr/docs/advanced/custom-response.md b/docs/fr/docs/advanced/custom-response.md
new file mode 100644
index 0000000000000..a1a60ebf64777
--- /dev/null
+++ b/docs/fr/docs/advanced/custom-response.md
@@ -0,0 +1,272 @@
+# Réponse personnalisée - HTML, flux, fichier, autres { #custom-response-html-stream-file-others }
+
+Par défaut, **FastAPI** renvoie des réponses JSON.
+
+Vous pouvez le remplacer en renvoyant une `Response` directement comme vu dans [Renvoyer une Response directement](response-directly.md).
+
+Mais si vous renvoyez directement une `Response` (ou n'importe quelle sous-classe, comme `JSONResponse`), les données ne seront pas automatiquement converties (même si vous déclarez un `response_model`), et la documentation ne sera pas générée automatiquement (par exemple, l'inclusion du « media type », dans l'en-tête HTTP `Content-Type` comme partie de l'OpenAPI généré).
+
+Vous pouvez aussi déclarer la `Response` que vous voulez utiliser (par ex. toute sous-classe de `Response`), dans le décorateur de *chemin d'accès* en utilisant le paramètre `response_class`.
+
+Le contenu que vous renvoyez depuis votre *fonction de chemin d'accès* sera placé à l'intérieur de cette `Response`.
+
+/// note | Remarque
+
+Si vous utilisez une classe de réponse sans media type, FastAPI s'attendra à ce que votre réponse n'ait pas de contenu ; il ne documentera donc pas le format de la réponse dans la documentation OpenAPI générée.
+
+///
+
+## Réponses JSON { #json-responses }
+
+Par défaut, FastAPI renvoie des réponses JSON.
+
+Si vous déclarez un [Modèle de réponse](../tutorial/response-model.md), FastAPI l'utilisera pour sérialiser les données en JSON, en utilisant Pydantic.
+
+Si vous ne déclarez pas de modèle de réponse, FastAPI utilisera le `jsonable_encoder` expliqué dans [Encodeur compatible JSON](../tutorial/encoder.md) et le placera dans une `JSONResponse`.
+
+Si vous déclarez une `response_class` avec un media type JSON (`application/json`), comme c'est le cas avec `JSONResponse`, les données que vous renvoyez seront automatiquement converties (et filtrées) avec tout `response_model` Pydantic que vous avez déclaré dans le décorateur de *chemin d'accès*. Mais les données ne seront pas sérialisées en octets JSON avec Pydantic, elles seront converties avec le `jsonable_encoder` puis passées à la classe `JSONResponse`, qui les sérialisera en octets en utilisant la bibliothèque JSON standard de Python.
+
+### Performance JSON { #json-performance }
+
+En bref, si vous voulez la performance maximale, utilisez un [Modèle de réponse](../tutorial/response-model.md) et ne déclarez pas de `response_class` dans le décorateur de *chemin d'accès*.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py ln[15:17] hl[16] *}
+
+## Réponse HTML { #html-response }
+
+Pour renvoyer une réponse avec du HTML directement depuis **FastAPI**, utilisez `HTMLResponse`.
+
+- Importez `HTMLResponse`.
+- Passez `HTMLResponse` comme paramètre `response_class` de votre *décorateur de chemin d'accès*.
+
+{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}
+
+/// info
+
+Le paramètre `response_class` sera aussi utilisé pour définir le « media type » de la réponse.
+
+Dans ce cas, l'en-tête HTTP `Content-Type` sera défini à `text/html`.
+
+Et il sera documenté comme tel dans OpenAPI.
+
+///
+
+### Renvoyer une `Response` { #return-a-response }
+
+Comme vu dans [Renvoyer une Response directement](response-directly.md), vous pouvez aussi remplacer la réponse directement dans votre *chemin d'accès*, en la renvoyant.
+
+Le même exemple ci-dessus, renvoyant une `HTMLResponse`, pourrait ressembler à :
+
+{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}
+
+/// warning | Alertes
+
+Une `Response` renvoyée directement par votre *fonction de chemin d'accès* ne sera pas documentée dans OpenAPI (par exemple, le `Content-Type` ne sera pas documenté) et ne sera pas visible dans les documents interactifs automatiques.
+
+///
+
+/// info
+
+Bien sûr, l'en-tête `Content-Type` réel, le code d'état, etc., proviendront de l'objet `Response` que vous avez renvoyé.
+
+///
+
+### Documenter dans OpenAPI et remplacer `Response` { #document-in-openapi-and-override-response }
+
+Si vous voulez remplacer la réponse depuis l'intérieur de la fonction mais en même temps documenter le « media type » dans OpenAPI, vous pouvez utiliser le paramètre `response_class` ET renvoyer un objet `Response`.
+
+`response_class` sera alors utilisé uniquement pour documenter l’*opération de chemin d'accès* OpenAPI, mais votre `Response` sera utilisée telle quelle.
+
+#### Renvoyer directement une `HTMLResponse` { #return-an-htmlresponse-directly }
+
+Par exemple, cela pourrait être quelque chose comme :
+
+{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}
+
+Dans cet exemple, la fonction `generate_html_response()` génère déjà et renvoie une `Response` au lieu de renvoyer le HTML dans une `str`.
+
+En renvoyant le résultat de l'appel à `generate_html_response()`, vous renvoyez déjà une `Response` qui remplacera le comportement par défaut de **FastAPI**.
+
+Mais comme vous avez aussi passé `HTMLResponse` dans `response_class`, **FastAPI** saura comment la documenter dans OpenAPI et les documents interactifs comme HTML avec `text/html` :
+
+
+
+## Réponses disponibles { #available-responses }
+
+Voici certaines des réponses disponibles.
+
+Gardez à l'esprit que vous pouvez utiliser `Response` pour renvoyer autre chose, ou même créer une sous-classe personnalisée.
+
+/// note | Détails techniques
+
+Vous pourriez aussi utiliser `from starlette.responses import HTMLResponse`.
+
+**FastAPI** fournit les mêmes `starlette.responses` sous `fastapi.responses` simplement pour votre confort de développement. Mais la plupart des réponses disponibles viennent directement de Starlette.
+
+///
+
+### `Response` { #response }
+
+La classe principale `Response`, toutes les autres réponses en héritent.
+
+Vous pouvez la renvoyer directement.
+
+Elle accepte les paramètres suivants :
+
+- `content` - Une `str` ou des `bytes`.
+- `status_code` - Un code d'état HTTP de type `int`.
+- `headers` - Un `dict` de chaînes.
+- `media_type` - Une `str` donnant le media type. Par exemple « text/html ».
+
+FastAPI (en fait Starlette) inclura automatiquement un en-tête Content-Length. Il inclura aussi un en-tête Content-Type, basé sur `media_type` et en ajoutant un charset pour les types textuels.
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+### `HTMLResponse` { #htmlresponse }
+
+Prend du texte ou des octets et renvoie une réponse HTML, comme vous l'avez vu ci-dessus.
+
+### `PlainTextResponse` { #plaintextresponse }
+
+Prend du texte ou des octets et renvoie une réponse en texte brut.
+
+{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}
+
+### `JSONResponse` { #jsonresponse }
+
+Prend des données et renvoie une réponse encodée en `application/json`.
+
+C'est la réponse par défaut utilisée dans **FastAPI**, comme vous l'avez lu ci-dessus.
+
+/// note | Détails techniques
+
+Mais si vous déclarez un modèle de réponse ou un type de retour, il sera utilisé directement pour sérialiser les données en JSON, et une réponse avec le bon media type pour JSON sera renvoyée directement, sans utiliser la classe `JSONResponse`.
+
+C'est la manière idéale d'obtenir la meilleure performance.
+
+///
+
+### `RedirectResponse` { #redirectresponse }
+
+Renvoie une redirection HTTP. Utilise par défaut un code d'état 307 (Temporary Redirect).
+
+Vous pouvez renvoyer directement une `RedirectResponse` :
+
+{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}
+
+---
+
+Ou vous pouvez l'utiliser dans le paramètre `response_class` :
+
+{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}
+
+Si vous faites cela, vous pouvez alors renvoyer directement l'URL depuis votre *fonction de chemin d'accès*.
+
+Dans ce cas, le `status_code` utilisé sera celui par défaut pour `RedirectResponse`, c'est-à-dire `307`.
+
+---
+
+Vous pouvez aussi utiliser le paramètre `status_code` combiné avec le paramètre `response_class` :
+
+{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}
+
+### `StreamingResponse` { #streamingresponse }
+
+Prend un générateur async ou un générateur/itérateur normal (une fonction avec `yield`) et diffuse le corps de la réponse.
+
+{* ../../docs_src/custom_response/tutorial007_py310.py hl[3,16] *}
+
+/// note | Détails techniques
+
+Une tâche `async` ne peut être annulée que lorsqu'elle atteint un `await`. S'il n'y a pas de `await`, le générateur (fonction avec `yield`) ne peut pas être annulé correctement et peut continuer à s'exécuter même après la demande d'annulation.
+
+Comme ce petit exemple n'a besoin d'aucune instruction `await`, nous ajoutons un `await anyio.sleep(0)` pour donner une chance à la boucle d'événements de gérer l'annulation.
+
+Cela serait encore plus important avec des flux volumineux ou infinis.
+
+///
+
+/// tip | Astuce
+
+Au lieu de renvoyer une `StreamingResponse` directement, vous devriez probablement suivre le style de [Diffuser des données](./stream-data.md), c'est beaucoup plus pratique et gère l'annulation en arrière-plan pour vous.
+
+Si vous diffusez des JSON Lines, suivez le didacticiel [Diffuser des JSON Lines](../tutorial/stream-json-lines.md).
+
+///
+
+### `FileResponse` { #fileresponse }
+
+Diffuse de façon asynchrone un fichier comme réponse.
+
+Prend un ensemble de paramètres différent à l'instanciation par rapport aux autres types de réponse :
+
+- `path` - Le chemin du fichier à diffuser.
+- `headers` - D'éventuels en-têtes personnalisés à inclure, sous forme de dictionnaire.
+- `media_type` - Une chaîne donnant le media type. Si non défini, le nom du fichier ou le chemin sera utilisé pour en déduire un media type.
+- `filename` - Si défini, sera inclus dans l'en-tête `Content-Disposition` de la réponse.
+
+Les réponses de type fichier incluront les en-têtes appropriés `Content-Length`, `Last-Modified` et `ETag`.
+
+{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}
+
+Vous pouvez aussi utiliser le paramètre `response_class` :
+
+{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}
+
+Dans ce cas, vous pouvez renvoyer directement le chemin du fichier depuis votre *fonction de chemin d'accès*.
+
+## Classe de réponse personnalisée { #custom-response-class }
+
+Vous pouvez créer votre propre classe de réponse personnalisée, héritant de `Response`, et l'utiliser.
+
+Par exemple, disons que vous voulez utiliser [`orjson`](https://github.com/ijl/orjson) avec certains réglages.
+
+Disons que vous voulez renvoyer du JSON indenté et formaté, donc vous voulez utiliser l'option orjson `orjson.OPT_INDENT_2`.
+
+Vous pourriez créer une `CustomORJSONResponse`. L'essentiel est de créer une méthode `Response.render(content)` qui renvoie le contenu en `bytes` :
+
+{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}
+
+Maintenant, au lieu de renvoyer :
+
+```json
+{"message": "Hello World"}
+```
+
+... cette réponse renverra :
+
+```json
+{
+ "message": "Hello World"
+}
+```
+
+Bien sûr, vous trouverez probablement des moyens bien meilleurs de tirer parti de cela que de formater du JSON. 😉
+
+### `orjson` ou Modèle de réponse { #orjson-or-response-model }
+
+Si ce que vous recherchez est la performance, vous aurez probablement de meilleurs résultats en utilisant un [Modèle de réponse](../tutorial/response-model.md) qu'une réponse `orjson`.
+
+Avec un modèle de réponse, FastAPI utilisera Pydantic pour sérialiser les données en JSON, sans étapes intermédiaires, comme la conversion avec `jsonable_encoder`, qui se produirait dans tout autre cas.
+
+Et en interne, Pydantic utilise les mêmes mécanismes Rust sous-jacents que `orjson` pour sérialiser en JSON, vous obtiendrez donc déjà la meilleure performance avec un modèle de réponse.
+
+## Classe de réponse par défaut { #default-response-class }
+
+Lors de la création d'une instance de classe **FastAPI** ou d'un `APIRouter`, vous pouvez spécifier quelle classe de réponse utiliser par défaut.
+
+Le paramètre qui le définit est `default_response_class`.
+
+Dans l'exemple ci-dessous, **FastAPI** utilisera `HTMLResponse` par défaut, dans tous les *chemins d'accès*, au lieu de JSON.
+
+{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}
+
+/// tip | Astuce
+
+Vous pouvez toujours remplacer `response_class` dans les *chemins d'accès* comme auparavant.
+
+///
+
+## Documentation supplémentaire { #additional-documentation }
+
+Vous pouvez aussi déclarer le media type et de nombreux autres détails dans OpenAPI en utilisant `responses` : [Réponses supplémentaires dans OpenAPI](additional-responses.md).
diff --git a/docs/fr/docs/advanced/dataclasses.md b/docs/fr/docs/advanced/dataclasses.md
new file mode 100644
index 0000000000000..b63a995d9f67e
--- /dev/null
+++ b/docs/fr/docs/advanced/dataclasses.md
@@ -0,0 +1,95 @@
+# Utiliser des dataclasses { #using-dataclasses }
+
+FastAPI est construit au‑dessus de **Pydantic**, et je vous ai montré comment utiliser des modèles Pydantic pour déclarer les requêtes et les réponses.
+
+Mais FastAPI prend aussi en charge l'utilisation de [`dataclasses`](https://docs.python.org/3/library/dataclasses.html) de la même manière :
+
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
+
+Cela fonctionne grâce à **Pydantic**, qui offre une [prise en charge interne des `dataclasses`](https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel).
+
+Ainsi, même avec le code ci‑dessus qui n'emploie pas explicitement Pydantic, FastAPI utilise Pydantic pour convertir ces dataclasses standard en la variante de dataclasses de Pydantic.
+
+Et bien sûr, cela prend en charge la même chose :
+
+* validation des données
+* sérialisation des données
+* documentation des données, etc.
+
+Cela fonctionne de la même manière qu'avec les modèles Pydantic. Et, en réalité, c'est mis en œuvre de la même façon en interne, en utilisant Pydantic.
+
+/// info
+
+Gardez à l'esprit que les dataclasses ne peuvent pas tout ce que peuvent faire les modèles Pydantic.
+
+Vous pourriez donc avoir encore besoin d'utiliser des modèles Pydantic.
+
+Mais si vous avez déjà un ensemble de dataclasses sous la main, c'est une astuce pratique pour les utiliser afin d'alimenter une API Web avec FastAPI. 🤓
+
+///
+
+## Utiliser des dataclasses dans `response_model` { #dataclasses-in-response-model }
+
+Vous pouvez aussi utiliser `dataclasses` dans le paramètre `response_model` :
+
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
+
+La dataclass sera automatiquement convertie en dataclass Pydantic.
+
+Ainsi, son schéma apparaîtra dans l'interface utilisateur de la documentation de l'API :
+
+
+
+## Utiliser des dataclasses dans des structures de données imbriquées { #dataclasses-in-nested-data-structures }
+
+Vous pouvez aussi combiner `dataclasses` avec d'autres annotations de type pour créer des structures de données imbriquées.
+
+Dans certains cas, vous devrez peut‑être encore utiliser la version `dataclasses` de Pydantic. Par exemple, si vous rencontrez des erreurs avec la documentation d'API générée automatiquement.
+
+Dans ce cas, vous pouvez simplement remplacer les `dataclasses` standard par `pydantic.dataclasses`, qui est un remplacement drop‑in :
+
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+
+1. Nous continuons à importer `field` depuis les `dataclasses` standard.
+
+2. `pydantic.dataclasses` est un remplacement drop‑in pour `dataclasses`.
+
+3. La dataclass `Author` inclut une liste de dataclasses `Item`.
+
+4. La dataclass `Author` est utilisée comme paramètre `response_model`.
+
+5. Vous pouvez utiliser d'autres annotations de type standard avec des dataclasses comme corps de la requête.
+
+ Dans ce cas, il s'agit d'une liste de dataclasses `Item`.
+
+6. Ici, nous renvoyons un dictionnaire qui contient `items`, qui est une liste de dataclasses.
+
+ FastAPI est toujours capable de sérialiser les données en JSON.
+
+7. Ici, `response_model` utilise une annotation de type correspondant à une liste de dataclasses `Author`.
+
+ Là encore, vous pouvez combiner `dataclasses` avec des annotations de type standard.
+
+8. Notez que cette *fonction de chemin d'accès* utilise un `def` classique au lieu de `async def`.
+
+ Comme toujours, avec FastAPI vous pouvez combiner `def` et `async def` selon vos besoins.
+
+ Si vous avez besoin d'un rappel sur quand utiliser l'un ou l'autre, consultez la section _« In a hurry? »_ dans la documentation à propos de [`async` et `await`](../async.md#in-a-hurry).
+
+9. Cette *fonction de chemin d'accès* ne renvoie pas des dataclasses (même si elle le pourrait), mais une liste de dictionnaires contenant des données internes.
+
+ FastAPI utilisera le paramètre `response_model` (qui inclut des dataclasses) pour convertir la réponse.
+
+Vous pouvez combiner `dataclasses` avec d'autres annotations de type, selon de nombreuses combinaisons, pour former des structures de données complexes.
+
+Reportez‑vous aux annotations dans le code ci‑dessus pour voir plus de détails spécifiques.
+
+## En savoir plus { #learn-more }
+
+Vous pouvez aussi combiner `dataclasses` avec d'autres modèles Pydantic, en hériter, les inclure dans vos propres modèles, etc.
+
+Pour en savoir plus, consultez la [documentation Pydantic sur les dataclasses](https://docs.pydantic.dev/latest/concepts/dataclasses/).
+
+## Version { #version }
+
+C'est disponible depuis FastAPI version `0.67.0`. 🔖
diff --git a/docs/fr/docs/advanced/events.md b/docs/fr/docs/advanced/events.md
new file mode 100644
index 0000000000000..c585dd563c6c8
--- /dev/null
+++ b/docs/fr/docs/advanced/events.md
@@ -0,0 +1,165 @@
+# Événements de cycle de vie { #lifespan-events }
+
+Vous pouvez définir une logique (du code) qui doit être exécutée avant que l'application ne **démarre**. Cela signifie que ce code sera exécuté **une seule fois**, **avant** que l'application ne **commence à recevoir des requêtes**.
+
+De la même manière, vous pouvez définir une logique (du code) qui doit être exécutée lorsque l'application **s'arrête**. Dans ce cas, ce code sera exécuté **une seule fois**, **après** avoir traité potentiellement **de nombreuses requêtes**.
+
+Comme ce code est exécuté avant que l'application ne **commence** à recevoir des requêtes, et juste après qu'elle **termine** de les traiter, il couvre tout le **cycle de vie** de l'application (le mot « lifespan » va être important dans un instant 😉).
+
+Cela peut être très utile pour configurer des **ressources** dont vous avez besoin pour l'ensemble de l'application, qui sont **partagées** entre les requêtes, et/ou que vous devez **nettoyer** ensuite. Par exemple, un pool de connexions à une base de données, ou le chargement d'un modèle d'apprentissage automatique partagé.
+
+## Cas d'utilisation { #use-case }
+
+Commençons par un exemple de **cas d'utilisation**, puis voyons comment le résoudre avec ceci.
+
+Imaginons que vous ayez des **modèles d'apprentissage automatique** que vous souhaitez utiliser pour traiter des requêtes. 🤖
+
+Les mêmes modèles sont partagés entre les requêtes, ce n'est donc pas un modèle par requête, ni un par utilisateur, ou quelque chose de similaire.
+
+Imaginons que le chargement du modèle puisse **prendre pas mal de temps**, car il doit lire beaucoup de **données depuis le disque**. Vous ne voulez donc pas le faire pour chaque requête.
+
+Vous pourriez le charger au niveau supérieur du module/fichier, mais cela signifierait aussi qu'il **chargerait le modèle** même si vous exécutez simplement un test automatisé simple ; ce test serait alors **lent** car il devrait attendre le chargement du modèle avant de pouvoir exécuter une partie indépendante du code.
+
+C'est ce que nous allons résoudre : chargeons le modèle avant que les requêtes ne soient traitées, mais seulement juste avant que l'application ne commence à recevoir des requêtes, pas pendant le chargement du code.
+
+## Cycle de vie { #lifespan }
+
+Vous pouvez définir cette logique de *démarrage* et d'*arrêt* en utilisant le paramètre `lifespan` de l'application `FastAPI`, et un « gestionnaire de contexte » (je vais vous montrer ce que c'est dans un instant).
+
+Commençons par un exemple, puis voyons-le en détail.
+
+Nous créons une fonction async `lifespan()` avec `yield` comme ceci :
+
+{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}
+
+Ici, nous simulons l'opération de *démarrage* coûteuse de chargement du modèle en plaçant la fonction (factice) du modèle dans le dictionnaire avec les modèles d'apprentissage automatique avant le `yield`. Ce code sera exécuté **avant** que l'application ne **commence à recevoir des requêtes**, pendant le *démarrage*.
+
+Puis, juste après le `yield`, nous déchargeons le modèle. Ce code sera exécuté **après** que l'application **a fini de traiter les requêtes**, juste avant l'*arrêt*. Cela pourrait, par exemple, libérer des ressources comme la mémoire ou un GPU.
+
+/// tip | Astuce
+
+Le `shutdown` se produit lorsque vous **arrêtez** l'application.
+
+Peut-être devez-vous démarrer une nouvelle version, ou vous en avez simplement assez de l'exécuter. 🤷
+
+///
+
+### Fonction de cycle de vie { #lifespan-function }
+
+La première chose à remarquer est que nous définissons une fonction async avec `yield`. C'est très similaire aux Dépendances avec `yield`.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}
+
+La première partie de la fonction, avant le `yield`, sera exécutée **avant** le démarrage de l'application.
+
+Et la partie après le `yield` sera exécutée **après** que l'application a terminé.
+
+### Gestionnaire de contexte asynchrone { #async-context-manager }
+
+Si vous regardez, la fonction est décorée avec `@asynccontextmanager`.
+
+Cela convertit la fonction en quelque chose appelé un « **gestionnaire de contexte asynchrone** ».
+
+{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}
+
+Un **gestionnaire de contexte** en Python est quelque chose que vous pouvez utiliser dans une instruction `with`. Par exemple, `open()` peut être utilisé comme gestionnaire de contexte :
+
+```Python
+with open("file.txt") as file:
+ file.read()
+```
+
+Dans les versions récentes de Python, il existe aussi un **gestionnaire de contexte asynchrone**. Vous l'utiliseriez avec `async with` :
+
+```Python
+async with lifespan(app):
+ await do_stuff()
+```
+
+Quand vous créez un gestionnaire de contexte ou un gestionnaire de contexte asynchrone comme ci-dessus, ce qu'il fait, c'est qu'avant d'entrer dans le bloc `with`, il exécute le code avant le `yield`, et après être sorti du bloc `with`, il exécute le code après le `yield`.
+
+Dans notre exemple de code ci-dessus, nous ne l'utilisons pas directement, mais nous le transmettons à FastAPI pour qu'il l'utilise.
+
+Le paramètre `lifespan` de l'application `FastAPI` accepte un **gestionnaire de contexte asynchrone**, nous pouvons donc lui passer notre nouveau gestionnaire de contexte asynchrone `lifespan`.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[22] *}
+
+## Événements alternatifs (déprécié) { #alternative-events-deprecated }
+
+/// warning | Alertes
+
+La méthode recommandée pour gérer le *démarrage* et l'*arrêt* est d'utiliser le paramètre `lifespan` de l'application `FastAPI` comme décrit ci-dessus. Si vous fournissez un paramètre `lifespan`, les gestionnaires d'événements `startup` et `shutdown` ne seront plus appelés. C'est soit tout en `lifespan`, soit tout en événements, pas les deux.
+
+Vous pouvez probablement passer cette partie.
+
+///
+
+Il existe une autre manière de définir cette logique à exécuter au *démarrage* et à l'*arrêt*.
+
+Vous pouvez définir des gestionnaires d'événements (fonctions) qui doivent être exécutés avant le démarrage de l'application, ou lorsque l'application s'arrête.
+
+Ces fonctions peuvent être déclarées avec `async def` ou un `def` normal.
+
+### Événement `startup` { #startup-event }
+
+Pour ajouter une fonction qui doit être exécutée avant le démarrage de l'application, déclarez-la avec l'événement « startup » :
+
+{* ../../docs_src/events/tutorial001_py310.py hl[8] *}
+
+Dans ce cas, la fonction gestionnaire de l'événement `startup` initialisera la « base de données » des items (juste un `dict`) avec quelques valeurs.
+
+Vous pouvez ajouter plusieurs fonctions de gestion d'événements.
+
+Et votre application ne commencera pas à recevoir des requêtes avant que tous les gestionnaires de l'événement `startup` aient terminé.
+
+### Événement `shutdown` { #shutdown-event }
+
+Pour ajouter une fonction qui doit être exécutée lorsque l'application s'arrête, déclarez-la avec l'événement « shutdown » :
+
+{* ../../docs_src/events/tutorial002_py310.py hl[6] *}
+
+Ici, la fonction gestionnaire de l'événement `shutdown` écrira une ligne de texte « Application shutdown » dans un fichier `log.txt`.
+
+/// info
+
+Dans la fonction `open()`, le `mode="a"` signifie « append » (ajouter) ; la ligne sera donc ajoutée après ce qui se trouve déjà dans ce fichier, sans écraser le contenu précédent.
+
+///
+
+/// tip | Astuce
+
+Notez que dans ce cas, nous utilisons une fonction Python standard `open()` qui interagit avec un fichier.
+
+Cela implique des E/S (input/output), qui nécessitent « d'attendre » que des choses soient écrites sur le disque.
+
+Mais `open()` n'utilise pas `async` et `await`.
+
+Nous déclarons donc la fonction gestionnaire d'événement avec un `def` standard plutôt qu'avec `async def`.
+
+///
+
+### `startup` et `shutdown` ensemble { #startup-and-shutdown-together }
+
+Il y a de fortes chances que la logique de votre *démarrage* et de votre *arrêt* soit liée : vous pourriez vouloir démarrer quelque chose puis le terminer, acquérir une ressource puis la libérer, etc.
+
+Faire cela dans des fonctions séparées qui ne partagent pas de logique ni de variables est plus difficile, car vous devriez stocker des valeurs dans des variables globales ou recourir à des astuces similaires.
+
+Pour cette raison, il est désormais recommandé d'utiliser plutôt le `lifespan` comme expliqué ci-dessus.
+
+## Détails techniques { #technical-details }
+
+Juste un détail technique pour les nerds curieux. 🤓
+
+Sous le capot, dans la spécification technique ASGI, cela fait partie du [protocole Lifespan](https://asgi.readthedocs.io/en/latest/specs/lifespan.html), et il y définit des événements appelés `startup` et `shutdown`.
+
+/// info
+
+Vous pouvez en lire plus sur les gestionnaires `lifespan` de Starlette dans la [documentation « Lifespan » de Starlette](https://www.starlette.dev/lifespan/).
+
+Y compris comment gérer l'état de cycle de vie qui peut être utilisé dans d'autres parties de votre code.
+
+///
+
+## Sous-applications { #sub-applications }
+
+🚨 Gardez à l'esprit que ces événements de cycle de vie (démarrage et arrêt) ne seront exécutés que pour l'application principale, pas pour [Sous-applications - Montages](sub-applications.md).
diff --git a/docs/fr/docs/advanced/generate-clients.md b/docs/fr/docs/advanced/generate-clients.md
new file mode 100644
index 0000000000000..58bd48181ec63
--- /dev/null
+++ b/docs/fr/docs/advanced/generate-clients.md
@@ -0,0 +1,208 @@
+# Générer des SDK { #generating-sdks }
+
+Parce que **FastAPI** est basé sur la spécification **OpenAPI**, ses API peuvent être décrites dans un format standard compris par de nombreux outils.
+
+Cela facilite la génération de **documentation** à jour, de bibliothèques clientes (**SDKs**) dans plusieurs langages, ainsi que de **tests** ou de **workflows d’automatisation** qui restent synchronisés avec votre code.
+
+Dans ce guide, vous apprendrez à générer un **SDK TypeScript** pour votre backend FastAPI.
+
+## Générateurs de SDK open source { #open-source-sdk-generators }
+
+Une option polyvalente est le [OpenAPI Generator](https://openapi-generator.tech/), qui prend en charge **de nombreux langages de programmation** et peut générer des SDK à partir de votre spécification OpenAPI.
+
+Pour les **clients TypeScript**, [Hey API](https://heyapi.dev/) est une solution dédiée, offrant une expérience optimisée pour l’écosystème TypeScript.
+
+Vous pouvez découvrir davantage de générateurs de SDK sur [OpenAPI.Tools](https://openapi.tools/#sdk).
+
+/// tip | Astuce
+
+FastAPI génère automatiquement des spécifications **OpenAPI 3.1**, donc tout outil que vous utilisez doit prendre en charge cette version.
+
+///
+
+## Générateurs de SDK par les sponsors de FastAPI { #sdk-generators-from-fastapi-sponsors }
+
+Cette section met en avant des solutions **soutenues par des fonds** et **par des entreprises** qui sponsorisent FastAPI. Ces produits offrent **des fonctionnalités supplémentaires** et **des intégrations** en plus de SDK de haute qualité générés.
+
+En ✨ [**sponsorisant FastAPI**](../help-fastapi.md#sponsor-the-author) ✨, ces entreprises contribuent à garantir que le framework et son **écosystème** restent sains et **durables**.
+
+Leur sponsoring démontre également un fort engagement envers la **communauté** FastAPI (vous), montrant qu’elles se soucient non seulement d’offrir un **excellent service**, mais aussi de soutenir un **framework robuste et florissant**, FastAPI. 🙇
+
+Par exemple, vous pourriez essayer :
+
+* [Speakeasy](https://speakeasy.com/editor?utm_source=fastapi+repo&utm_medium=github+sponsorship)
+* [Stainless](https://www.stainless.com/?utm_source=fastapi&utm_medium=referral)
+* [liblab](https://developers.liblab.com/tutorials/sdk-for-fastapi?utm_source=fastapi)
+
+Certaines de ces solutions peuvent aussi être open source ou proposer des niveaux gratuits, afin que vous puissiez les essayer sans engagement financier. D’autres générateurs de SDK commerciaux existent et peuvent être trouvés en ligne. 🤓
+
+## Créer un SDK TypeScript { #create-a-typescript-sdk }
+
+Commençons par une application FastAPI simple :
+
+{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}
+
+Remarquez que les *chemins d'accès* définissent les modèles qu’ils utilisent pour le payload de requête et le payload de réponse, en utilisant les modèles `Item` et `ResponseMessage`.
+
+### Documentation de l’API { #api-docs }
+
+Si vous allez sur `/docs`, vous verrez qu’elle contient les **schémas** pour les données à envoyer dans les requêtes et reçues dans les réponses :
+
+
+
+Vous voyez ces schémas parce qu’ils ont été déclarés avec les modèles dans l’application.
+
+Ces informations sont disponibles dans le **schéma OpenAPI** de l’application, puis affichées dans la documentation de l’API.
+
+Ces mêmes informations issues des modèles, incluses dans OpenAPI, peuvent être utilisées pour **générer le code client**.
+
+### Hey API { #hey-api }
+
+Une fois que vous avez une application FastAPI avec les modèles, vous pouvez utiliser Hey API pour générer un client TypeScript. Le moyen le plus rapide de le faire est via npx.
+
+```sh
+npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
+```
+
+Cela générera un SDK TypeScript dans `./src/client`.
+
+Vous pouvez apprendre à [installer `@hey-api/openapi-ts`](https://heyapi.dev/openapi-ts/get-started) et lire à propos du [résultat généré](https://heyapi.dev/openapi-ts/output) sur leur site.
+
+### Utiliser le SDK { #using-the-sdk }
+
+Vous pouvez maintenant importer et utiliser le code client. Cela pourrait ressembler à ceci, remarquez que vous obtenez l’autocomplétion pour les méthodes :
+
+
+
+Vous obtiendrez également l’autocomplétion pour le payload à envoyer :
+
+
+
+/// tip | Astuce
+
+Remarquez l’autocomplétion pour `name` et `price`, qui a été définie dans l’application FastAPI, dans le modèle `Item`.
+
+///
+
+Vous aurez des erreurs en ligne pour les données que vous envoyez :
+
+
+
+L’objet de réponse aura également l’autocomplétion :
+
+
+
+## Application FastAPI avec des tags { #fastapi-app-with-tags }
+
+Dans de nombreux cas, votre application FastAPI sera plus grande, et vous utiliserez probablement des tags pour séparer différents groupes de *chemins d'accès*.
+
+Par exemple, vous pourriez avoir une section pour les **items** et une autre section pour les **users**, et elles pourraient être séparées par des tags :
+
+{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}
+
+### Générer un client TypeScript avec des tags { #generate-a-typescript-client-with-tags }
+
+Si vous générez un client pour une application FastAPI utilisant des tags, il séparera normalement aussi le code client en fonction des tags.
+
+De cette façon, vous pourrez avoir les éléments ordonnés et correctement groupés côté client :
+
+
+
+Dans ce cas, vous avez :
+
+* `ItemsService`
+* `UsersService`
+
+### Noms des méthodes du client { #client-method-names }
+
+À l’heure actuelle, les noms de méthodes générés comme `createItemItemsPost` ne sont pas très propres :
+
+```TypeScript
+ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
+```
+
+... c’est parce que le générateur de client utilise l’**operation ID** interne OpenAPI pour chaque *chemin d'accès*.
+
+OpenAPI exige que chaque operation ID soit unique parmi tous les *chemins d'accès*, donc FastAPI utilise le **nom de la fonction**, le **chemin**, et la **méthode/opération HTTP** pour générer cet operation ID, car de cette façon il peut s’assurer que les operation IDs sont uniques.
+
+Mais je vais vous montrer comment améliorer cela ensuite. 🤓
+
+## IDs d’opération personnalisés et meilleurs noms de méthodes { #custom-operation-ids-and-better-method-names }
+
+Vous pouvez **modifier** la façon dont ces operation IDs sont **générés** pour les simplifier et obtenir des **noms de méthodes plus simples** dans les clients.
+
+Dans ce cas, vous devez vous assurer que chaque operation ID est **unique** d’une autre manière.
+
+Par exemple, vous pouvez vous assurer que chaque *chemin d'accès* a un tag, puis générer l’operation ID à partir du **tag** et du **nom** du *chemin d'accès* (le nom de la fonction).
+
+### Fonction personnalisée de génération d’ID unique { #custom-generate-unique-id-function }
+
+FastAPI utilise un **ID unique** pour chaque *chemin d'accès*, qui est utilisé pour l’**operation ID** et également pour les noms des modèles personnalisés nécessaires, pour les requêtes ou les réponses.
+
+Vous pouvez personnaliser cette fonction. Elle prend un `APIRoute` et retourne une chaîne.
+
+Par exemple, ici elle utilise le premier tag (vous n’en aurez probablement qu’un) et le nom du *chemin d'accès* (le nom de la fonction).
+
+Vous pouvez ensuite passer cette fonction personnalisée à **FastAPI** via le paramètre `generate_unique_id_function` :
+
+{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}
+
+### Générer un client TypeScript avec des IDs d’opération personnalisés { #generate-a-typescript-client-with-custom-operation-ids }
+
+Maintenant, si vous régénérez le client, vous verrez qu’il possède des noms de méthodes améliorés :
+
+
+
+Comme vous le voyez, les noms de méthodes contiennent maintenant le tag puis le nom de la fonction ; ils n’incluent plus d’informations provenant du chemin d’URL et de l’opération HTTP.
+
+### Prétraiter la spécification OpenAPI pour le générateur de client { #preprocess-the-openapi-specification-for-the-client-generator }
+
+Le code généré contient encore des **informations dupliquées**.
+
+Nous savons déjà que cette méthode est liée aux **items** parce que ce mot figure dans `ItemsService` (issu du tag), mais nous avons encore le nom du tag préfixé dans le nom de la méthode. 😕
+
+Nous voudrons probablement le conserver pour OpenAPI en général, car cela garantira que les operation IDs sont **uniques**.
+
+Mais pour le client généré, nous pourrions **modifier** les operation IDs d’OpenAPI juste avant de générer les clients, simplement pour rendre ces noms de méthodes plus agréables et **plus clairs**.
+
+Nous pourrions télécharger le JSON OpenAPI dans un fichier `openapi.json` puis **supprimer ce tag préfixé** avec un script comme celui-ci :
+
+{* ../../docs_src/generate_clients/tutorial004_py310.py *}
+
+//// tab | Node.js
+
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
+```
+
+////
+
+Avec cela, les operation IDs seraient renommés de `items-get_items` en simplement `get_items`, de sorte que le générateur de client puisse produire des noms de méthodes plus simples.
+
+### Générer un client TypeScript avec l’OpenAPI prétraité { #generate-a-typescript-client-with-the-preprocessed-openapi }
+
+Puisque le résultat final se trouve maintenant dans un fichier `openapi.json`, vous devez mettre à jour l’emplacement d’entrée :
+
+```sh
+npx @hey-api/openapi-ts -i ./openapi.json -o src/client
+```
+
+Après avoir généré le nouveau client, vous aurez désormais des **noms de méthodes propres**, avec toute l’**autocomplétion**, les **erreurs en ligne**, etc. :
+
+
+
+## Avantages { #benefits }
+
+En utilisant les clients générés automatiquement, vous obtiendrez de l’**autocomplétion** pour :
+
+* Méthodes.
+* Payloads de requête dans le corps, paramètres de requête, etc.
+* Payloads de réponse.
+
+Vous auriez également des **erreurs en ligne** pour tout.
+
+Et chaque fois que vous mettez à jour le code du backend et **régénérez** le frontend, il inclura les nouveaux *chemins d'accès* disponibles en tant que méthodes, supprimera les anciens, et tout autre changement sera reflété dans le code généré. 🤓
+
+Cela signifie aussi que si quelque chose change, cela sera **reflété** automatiquement dans le code client. Et si vous **bâtissez** le client, il échouera en cas de **discordance** dans les données utilisées.
+
+Ainsi, vous **détecterez de nombreuses erreurs** très tôt dans le cycle de développement au lieu d’attendre qu’elles apparaissent pour vos utilisateurs finaux en production puis de tenter de déboguer l’origine du problème. ✨
diff --git a/docs/fr/docs/advanced/index.md b/docs/fr/docs/advanced/index.md
index f4fa5ecf69624..03fdc21020593 100644
--- a/docs/fr/docs/advanced/index.md
+++ b/docs/fr/docs/advanced/index.md
@@ -1,24 +1,21 @@
-# Guide de l'utilisateur avancé
+# Guide de l'utilisateur avancé { #advanced-user-guide }
-## Caractéristiques supplémentaires
+## Caractéristiques supplémentaires { #additional-features }
-Le [Tutoriel - Guide de l'utilisateur](../tutorial/){.internal-link target=_blank} devrait suffire à vous faire découvrir toutes les fonctionnalités principales de **FastAPI**.
+Le [Tutoriel - Guide de l'utilisateur](../tutorial/index.md) devrait suffire à vous faire découvrir toutes les fonctionnalités principales de **FastAPI**.
Dans les sections suivantes, vous verrez des options, configurations et fonctionnalités supplémentaires.
-!!! Note
- Les sections de ce chapitre ne sont **pas nécessairement "avancées"**.
+/// tip | Astuce
- Et il est possible que pour votre cas d'utilisation, la solution se trouve dans l'un d'entre eux.
+Les sections suivantes ne sont **pas nécessairement « avancées »**.
-## Lisez d'abord le didacticiel
+Et il est possible que, pour votre cas d'utilisation, la solution se trouve dans l'une d'entre elles.
-Vous pouvez utiliser la plupart des fonctionnalités de **FastAPI** grâce aux connaissances du [Tutoriel - Guide de l'utilisateur](../tutorial/){.internal-link target=_blank}.
+///
-Et les sections suivantes supposent que vous l'avez lu et que vous en connaissez les idées principales.
-
-## Cours TestDriven.io
+## Lire d'abord le tutoriel { #read-the-tutorial-first }
-Si vous souhaitez suivre un cours pour débutants avancés pour compléter cette section de la documentation, vous pouvez consulter : Développement piloté par les tests avec FastAPI et Docker par **TestDriven.io**.
+Vous pouvez utiliser la plupart des fonctionnalités de **FastAPI** grâce aux connaissances du [Tutoriel - Guide de l'utilisateur](../tutorial/index.md).
-10 % de tous les bénéfices de ce cours sont reversés au développement de **FastAPI**. 🎉 😄
+Et les sections suivantes supposent que vous l'avez lu et que vous en connaissez les idées principales.
diff --git a/docs/fr/docs/advanced/json-base64-bytes.md b/docs/fr/docs/advanced/json-base64-bytes.md
new file mode 100644
index 0000000000000..1b5acb08116d0
--- /dev/null
+++ b/docs/fr/docs/advanced/json-base64-bytes.md
@@ -0,0 +1,63 @@
+# JSON avec des octets en Base64 { #json-with-bytes-as-base64 }
+
+Si votre application doit recevoir et envoyer des données JSON, mais que vous devez y inclure des données binaires, vous pouvez les encoder en base64.
+
+## Base64 vs fichiers { #base64-vs-files }
+
+Envisagez d'abord d'utiliser [Fichiers de requête](../tutorial/request-files.md) pour téléverser des données binaires et [Réponse personnalisée - FileResponse](./custom-response.md#fileresponse--fileresponse-) pour envoyer des données binaires, plutôt que de les encoder dans du JSON.
+
+JSON ne peut contenir que des chaînes encodées en UTF-8, il ne peut donc pas contenir d'octets bruts.
+
+Base64 peut encoder des données binaires en chaînes, mais pour cela il doit utiliser plus de caractères que les données binaires originales ; c'est donc en général moins efficace que des fichiers classiques.
+
+N'utilisez base64 que si vous devez absolument inclure des données binaires dans du JSON et que vous ne pouvez pas utiliser des fichiers pour cela.
+
+## Pydantic `bytes` { #pydantic-bytes }
+
+Vous pouvez déclarer un modèle Pydantic avec des champs `bytes`, puis utiliser `val_json_bytes` dans la configuration du modèle pour lui indiquer d'utiliser base64 pour valider les données JSON en entrée ; dans le cadre de cette validation, il décodera la chaîne base64 en octets.
+
+{* ../../docs_src/json_base64_bytes/tutorial001_py310.py ln[1:9,29:35] hl[9] *}
+
+Si vous allez sur les `/docs`, vous verrez que le champ `data` attend des octets encodés en base64 :
+
+
+
diff --git a/docs/fr/docs/advanced/openapi-webhooks.md b/docs/fr/docs/advanced/openapi-webhooks.md
new file mode 100644
index 0000000000000..c36c2f82bacf9
--- /dev/null
+++ b/docs/fr/docs/advanced/openapi-webhooks.md
@@ -0,0 +1,55 @@
+# Webhooks OpenAPI { #openapi-webhooks }
+
+Il existe des cas où vous voulez informer les utilisateurs de votre API que votre application peut appeler leur application (en envoyant une requête) avec des données, généralement pour notifier un type d'événement.
+
+Cela signifie qu'au lieu du processus habituel où vos utilisateurs envoient des requêtes à votre API, c'est votre API (ou votre application) qui peut envoyer des requêtes vers leur système (vers leur API, leur application).
+
+On appelle généralement cela un webhook.
+
+## Étapes des webhooks { #webhooks-steps }
+
+Le processus consiste généralement à définir dans votre code le message que vous enverrez, c'est-à-dire le corps de la requête.
+
+Vous définissez également, d'une manière ou d'une autre, à quels moments votre application enverra ces requêtes ou événements.
+
+Et vos utilisateurs définissent aussi, d'une manière ou d'une autre (par exemple dans un tableau de bord Web), l'URL à laquelle votre application doit envoyer ces requêtes.
+
+Toute la logique de gestion des URL des webhooks et le code qui envoie effectivement ces requêtes vous incombent. Vous l'implémentez comme vous le souhaitez dans votre propre code.
+
+## Documenter des webhooks avec FastAPI et OpenAPI { #documenting-webhooks-with-fastapi-and-openapi }
+
+Avec FastAPI, en utilisant OpenAPI, vous pouvez définir les noms de ces webhooks, les types d'opérations HTTP que votre application peut envoyer (par exemple `POST`, `PUT`, etc.) et les corps des requêtes que votre application enverra.
+
+Cela peut grandement faciliter la tâche de vos utilisateurs pour implémenter leurs API afin de recevoir vos requêtes de webhook ; ils pourront même peut-être générer automatiquement une partie de leur propre code d'API.
+
+/// info
+
+Les webhooks sont disponibles dans OpenAPI 3.1.0 et versions ultérieures, pris en charge par FastAPI `0.99.0` et versions ultérieures.
+
+///
+
+## Créer une application avec des webhooks { #an-app-with-webhooks }
+
+Lorsque vous créez une application FastAPI, il existe un attribut `webhooks` que vous pouvez utiliser pour définir des webhooks, de la même manière que vous définiriez des chemins d'accès, par exemple avec `@app.webhooks.post()`.
+
+{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}
+
+Les webhooks que vous définissez apparaîtront dans le schéma OpenAPI et dans l'interface de documentation automatique.
+
+/// info
+
+L'objet `app.webhooks` est en fait simplement un `APIRouter`, le même type que vous utiliseriez pour structurer votre application en plusieurs fichiers.
+
+///
+
+Notez qu'avec les webhooks, vous ne déclarez pas réellement un chemin (comme `/items/`), le texte que vous y passez est simplement un identifiant du webhook (le nom de l'événement). Par exemple, dans `@app.webhooks.post("new-subscription")`, le nom du webhook est `new-subscription`.
+
+C'est parce qu'on s'attend à ce que vos utilisateurs définissent, par un autre moyen (par exemple un tableau de bord Web), le véritable chemin d'URL où ils souhaitent recevoir la requête de webhook.
+
+### Consulter la documentation { #check-the-docs }
+
+Vous pouvez maintenant démarrer votre application et aller sur [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).
+
+Vous verrez que votre documentation contient les chemins d'accès habituels et désormais aussi des webhooks :
+
+
diff --git a/docs/fr/docs/advanced/path-operation-advanced-configuration.md b/docs/fr/docs/advanced/path-operation-advanced-configuration.md
index 7ded97ce1755a..67a5d46d41893 100644
--- a/docs/fr/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/fr/docs/advanced/path-operation-advanced-configuration.md
@@ -1,101 +1,108 @@
-# Configuration avancée des paramètres de chemin
+# Configuration avancée des chemins d'accès { #path-operation-advanced-configuration }
-## ID d'opération OpenAPI
+## ID d’opération OpenAPI { #openapi-operationid }
-!!! Attention
- Si vous n'êtes pas un "expert" en OpenAPI, vous n'en avez probablement pas besoin.
+/// warning | Alertes
-Dans OpenAPI, les chemins sont des ressources, tels que /users/ ou /items/, exposées par votre API, et les opérations sont les méthodes HTTP utilisées pour manipuler ces chemins, telles que GET, POST ou DELETE. Les operationId sont des chaînes uniques facultatives utilisées pour identifier une opération d'un chemin. Vous pouvez définir l'OpenAPI `operationId` à utiliser dans votre *opération de chemin* avec le paramètre `operation_id`.
+Si vous n’êtes pas un « expert » d’OpenAPI, vous n’en avez probablement pas besoin.
-Vous devez vous assurer qu'il est unique pour chaque opération.
+///
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
-```
+Vous pouvez définir l’OpenAPI `operationId` à utiliser dans votre chemin d’accès avec le paramètre `operation_id`.
-### Utilisation du nom *path operation function* comme operationId
+Vous devez vous assurer qu’il est unique pour chaque opération.
-Si vous souhaitez utiliser les noms de fonction de vos API comme `operationId`, vous pouvez les parcourir tous et remplacer chaque `operation_id` de l'*opération de chemin* en utilisant leur `APIRoute.name`.
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
-Vous devriez le faire après avoir ajouté toutes vos *paramètres de chemin*.
+### Utiliser le nom de la fonction de chemin d’accès comme operationId { #using-the-path-operation-function-name-as-the-operationid }
-```Python hl_lines="2 12-21 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
-```
+Si vous souhaitez utiliser les noms de fonction de vos API comme `operationId`, vous pouvez les parcourir tous et remplacer l’`operation_id` de chaque chemin d’accès en utilisant leur `APIRoute.name`.
-!!! Astuce
- Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant.
+Vous devez le faire après avoir ajouté tous vos chemins d’accès.
-!!! Attention
- Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique.
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *}
- Même s'ils se trouvent dans des modules différents (fichiers Python).
+/// tip | Astuce
-## Exclusion d'OpenAPI
+Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant cela.
-Pour exclure un *chemin* du schéma OpenAPI généré (et donc des systèmes de documentation automatiques), utilisez le paramètre `include_in_schema` et assignez-lui la valeur `False` :
+///
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
-```
+/// warning | Alertes
-## Description avancée de docstring
+Si vous faites cela, vous devez vous assurer que chacune de vos fonctions de chemin d’accès a un nom unique.
-Vous pouvez limiter le texte utilisé de la docstring d'une *fonction de chemin* qui sera affiché sur OpenAPI.
+Même si elles se trouvent dans des modules différents (fichiers Python).
-L'ajout d'un `\f` (un caractère d'échappement "form feed") va permettre à **FastAPI** de tronquer la sortie utilisée pour OpenAPI à ce stade.
+///
-Il n'apparaîtra pas dans la documentation, mais d'autres outils (tel que Sphinx) pourront utiliser le reste.
+## Exclusion d’OpenAPI { #exclude-from-openapi }
-```Python hl_lines="19-29"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
-```
+Pour exclure un chemin d’accès du schéma OpenAPI généré (et donc des systèmes de documentation automatiques), utilisez le paramètre `include_in_schema` et définissez-le à `False` :
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}
+
+## Description avancée depuis la docstring { #advanced-description-from-docstring }
-## Réponses supplémentaires
+Vous pouvez limiter les lignes utilisées de la docstring d’une fonction de chemin d’accès pour OpenAPI.
-Vous avez probablement vu comment déclarer le `response_model` et le `status_code` pour une *opération de chemin*.
+L’ajout d’un `\f` (un caractère « form feed » échappé) amène **FastAPI** à tronquer la sortie utilisée pour OpenAPI à cet endroit.
-Cela définit les métadonnées sur la réponse principale d'une *opération de chemin*.
+Cela n’apparaîtra pas dans la documentation, mais d’autres outils (comme Sphinx) pourront utiliser le reste.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}
+
+## Réponses supplémentaires { #additional-responses }
+
+Vous avez probablement vu comment déclarer le `response_model` et le `status_code` pour un chemin d’accès.
+
+Cela définit les métadonnées sur la réponse principale d’un chemin d’accès.
Vous pouvez également déclarer des réponses supplémentaires avec leurs modèles, codes de statut, etc.
-Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le lire sur [Réponses supplémentaires dans OpenAPI](./additional-responses.md){.internal-link target=_blank}.
+Il y a un chapitre entier dans la documentation à ce sujet, vous pouvez le lire dans [Réponses supplémentaires dans OpenAPI](additional-responses.md).
+
+## OpenAPI supplémentaire { #openapi-extra }
-## OpenAPI supplémentaire
+Lorsque vous déclarez un chemin d’accès dans votre application, **FastAPI** génère automatiquement les métadonnées pertinentes à propos de ce chemin d’accès à inclure dans le schéma OpenAPI.
-Lorsque vous déclarez un *chemin* dans votre application, **FastAPI** génère automatiquement les métadonnées concernant ce *chemin* à inclure dans le schéma OpenAPI.
+/// note | Détails techniques
-!!! note "Détails techniques"
- La spécification OpenAPI appelle ces métadonnées des Objets d'opération.
+Dans la spécification OpenAPI, cela s’appelle l’[objet Operation](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object).
-Il contient toutes les informations sur le *chemin* et est utilisé pour générer automatiquement la documentation.
+///
+
+Il contient toutes les informations sur le chemin d’accès et est utilisé pour générer la documentation automatique.
Il inclut les `tags`, `parameters`, `requestBody`, `responses`, etc.
-Ce schéma OpenAPI spécifique aux *operations* est normalement généré automatiquement par **FastAPI**, mais vous pouvez également l'étendre.
+Ce schéma OpenAPI spécifique à un chemin d’accès est normalement généré automatiquement par **FastAPI**, mais vous pouvez également l’étendre.
-!!! Astuce
- Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](./additional-responses.md){.internal-link target=_blank}.
+/// tip | Astuce
-Vous pouvez étendre le schéma OpenAPI pour une *opération de chemin* en utilisant le paramètre `openapi_extra`.
+Ceci est un point d’extension de bas niveau.
-### Extensions OpenAPI
+Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d’utiliser [Réponses supplémentaires dans OpenAPI](additional-responses.md).
-Cet `openapi_extra` peut être utile, par exemple, pour déclarer [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) :
+///
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!}
-```
+Vous pouvez étendre le schéma OpenAPI pour un chemin d’accès en utilisant le paramètre `openapi_extra`.
+
+### Extensions OpenAPI { #openapi-extensions }
+
+Cet `openapi_extra` peut être utile, par exemple, pour déclarer des [Extensions OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) :
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py310.py hl[6] *}
-Si vous ouvrez la documentation automatique de l'API, votre extension apparaîtra au bas du *chemin* spécifique.
+Si vous ouvrez la documentation automatique de l’API, votre extension apparaîtra en bas du chemin d’accès spécifique.
-Et dans le fichier openapi généré (`/openapi.json`), vous verrez également votre extension dans le cadre du *chemin* spécifique :
+Et si vous consultez l’OpenAPI résultant (à `/openapi.json` dans votre API), vous verrez également votre extension comme partie du chemin d’accès spécifique :
```JSON hl_lines="22"
{
- "openapi": "3.0.2",
+ "openapi": "3.1.0",
"info": {
"title": "FastAPI",
"version": "0.1.0"
@@ -122,47 +129,44 @@ Et dans le fichier openapi généré (`/openapi.json`), vous verrez également v
}
```
-### Personnalisation du Schéma OpenAPI pour un chemin
+### Personnaliser le schéma OpenAPI d’un chemin d’accès { #custom-openapi-path-operation-schema }
-Le dictionnaire contenu dans la variable `openapi_extra` sera fusionné avec le schéma OpenAPI généré automatiquement pour l'*opération de chemin*.
+Le dictionnaire dans `openapi_extra` sera fusionné en profondeur avec le schéma OpenAPI généré automatiquement pour le chemin d’accès.
Ainsi, vous pouvez ajouter des données supplémentaires au schéma généré automatiquement.
-Par exemple, vous pouvez décider de lire et de valider la requête avec votre propre code, sans utiliser les fonctionnalités automatiques de validation proposée par Pydantic, mais vous pouvez toujours définir la requête dans le schéma OpenAPI.
+Par exemple, vous pourriez décider de lire et de valider la requête avec votre propre code, sans utiliser les fonctionnalités automatiques de FastAPI avec Pydantic, mais vous pourriez tout de même vouloir définir la requête dans le schéma OpenAPI.
-Vous pouvez le faire avec `openapi_extra` :
+Vous pourriez le faire avec `openapi_extra` :
-```Python hl_lines="20-37 39-40"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py !}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py310.py hl[19:36, 39:40] *}
-Dans cet exemple, nous n'avons déclaré aucun modèle Pydantic. En fait, le corps de la requête n'est même pas parsé en tant que JSON, il est lu directement en tant que `bytes`, et la fonction `magic_data_reader()` serait chargé de l'analyser d'une manière ou d'une autre.
+Dans cet exemple, nous n’avons déclaré aucun modèle Pydantic. En fait, le corps de la requête n’est même pas parsé en JSON, il est lu directement en tant que `bytes`, et la fonction `magic_data_reader()` serait chargée de l’analyser d’une manière ou d’une autre.
Néanmoins, nous pouvons déclarer le schéma attendu pour le corps de la requête.
-### Type de contenu OpenAPI personnalisé
+### Type de contenu OpenAPI personnalisé { #custom-openapi-content-type }
-En utilisant cette même astuce, vous pouvez utiliser un modèle Pydantic pour définir le schéma JSON qui est ensuite inclus dans la section de schéma OpenAPI personnalisée pour le *chemin* concerné.
+En utilisant cette même astuce, vous pourriez utiliser un modèle Pydantic pour définir le JSON Schema qui est ensuite inclus dans la section de schéma OpenAPI personnalisée pour le chemin d’accès.
-Et vous pouvez le faire même si le type de données dans la requête n'est pas au format JSON.
+Et vous pourriez le faire même si le type de données dans la requête n’est pas du JSON.
-Dans cet exemple, nous n'utilisons pas les fonctionnalités de FastAPI pour extraire le schéma JSON des modèles Pydantic ni la validation automatique pour JSON. En fait, nous déclarons le type de contenu de la requête en tant que YAML, et non JSON :
+Par exemple, dans cette application nous n’utilisons pas la fonctionnalité intégrée de FastAPI pour extraire le JSON Schema des modèles Pydantic ni la validation automatique pour le JSON. En fait, nous déclarons le type de contenu de la requête comme YAML, pas JSON :
-```Python hl_lines="17-22 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[15:20, 22] *}
-Néanmoins, bien que nous n'utilisions pas la fonctionnalité par défaut, nous utilisons toujours un modèle Pydantic pour générer manuellement le schéma JSON pour les données que nous souhaitons recevoir en YAML.
+Néanmoins, bien que nous n’utilisions pas la fonctionnalité intégrée par défaut, nous utilisons toujours un modèle Pydantic pour générer manuellement le JSON Schema pour les données que nous souhaitons recevoir en YAML.
-Ensuite, nous utilisons directement la requête et extrayons son contenu en tant qu'octets. Cela signifie que FastAPI n'essaiera même pas d'analyser le payload de la requête en tant que JSON.
+Ensuite, nous utilisons directement la requête et extrayons le corps en tant que `bytes`. Cela signifie que FastAPI n’essaiera même pas d’analyser le payload de la requête en JSON.
-Et nous analysons directement ce contenu YAML, puis nous utilisons à nouveau le même modèle Pydantic pour valider le contenu YAML :
+Ensuite, dans notre code, nous analysons directement ce contenu YAML, puis nous utilisons à nouveau le même modèle Pydantic pour valider le contenu YAML :
-```Python hl_lines="26-33"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *}
+
+/// tip | Astuce
+
+Ici, nous réutilisons le même modèle Pydantic.
-!!! Astuce
- Ici, nous réutilisons le même modèle Pydantic.
+Mais de la même manière, nous aurions pu le valider autrement.
- Mais nous aurions pu tout aussi bien pu le valider d'une autre manière.
+///
diff --git a/docs/fr/docs/advanced/response-change-status-code.md b/docs/fr/docs/advanced/response-change-status-code.md
new file mode 100644
index 0000000000000..2228257029874
--- /dev/null
+++ b/docs/fr/docs/advanced/response-change-status-code.md
@@ -0,0 +1,31 @@
+# Réponse - Modifier le code d'état { #response-change-status-code }
+
+Vous avez probablement déjà lu que vous pouvez définir un [Code d'état de la réponse](../tutorial/response-status-code.md) par défaut.
+
+Mais dans certains cas, vous devez renvoyer un code d'état différent de celui par défaut.
+
+## Cas d'utilisation { #use-case }
+
+Par exemple, imaginez que vous vouliez renvoyer par défaut un code d'état HTTP « OK » `200`.
+
+Mais si les données n'existent pas, vous voulez les créer et renvoyer un code d'état HTTP « CREATED » `201`.
+
+Mais vous souhaitez toujours pouvoir filtrer et convertir les données que vous renvoyez avec un `response_model`.
+
+Pour ces cas, vous pouvez utiliser un paramètre `Response`.
+
+## Utiliser un paramètre `Response` { #use-a-response-parameter }
+
+Vous pouvez déclarer un paramètre de type `Response` dans votre fonction de chemin d'accès (comme vous pouvez le faire pour les cookies et les en-têtes).
+
+Vous pouvez ensuite définir le `status_code` dans cet objet de réponse *temporaire*.
+
+{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}
+
+Vous pouvez ensuite renvoyer n'importe quel objet nécessaire, comme d'habitude (un `dict`, un modèle de base de données, etc.).
+
+Et si vous avez déclaré un `response_model`, il sera toujours utilisé pour filtrer et convertir l'objet que vous avez renvoyé.
+
+**FastAPI** utilisera cette réponse *temporaire* pour extraire le code d'état (ainsi que les cookies et les en-têtes), et les placera dans la réponse finale qui contient la valeur que vous avez renvoyée, filtrée par tout `response_model`.
+
+Vous pouvez également déclarer le paramètre `Response` dans des dépendances et y définir le code d'état. Mais gardez à l'esprit que la dernière valeur définie prévaut.
diff --git a/docs/fr/docs/advanced/response-cookies.md b/docs/fr/docs/advanced/response-cookies.md
new file mode 100644
index 0000000000000..174c9a72dc71d
--- /dev/null
+++ b/docs/fr/docs/advanced/response-cookies.md
@@ -0,0 +1,51 @@
+# Cookies de réponse { #response-cookies }
+
+## Utiliser un paramètre `Response` { #use-a-response-parameter }
+
+Vous pouvez déclarer un paramètre de type `Response` dans votre *fonction de chemin d'accès*.
+
+Vous pouvez ensuite définir des cookies dans cet objet de réponse *temporaire*.
+
+{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}
+
+Vous pouvez ensuite renvoyer n'importe quel objet dont vous avez besoin, comme d'habitude (un `dict`, un modèle de base de données, etc.).
+
+Et si vous avez déclaré un `response_model`, il sera toujours utilisé pour filtrer et convertir l'objet que vous avez renvoyé.
+
+**FastAPI** utilisera cette réponse *temporaire* pour extraire les cookies (ainsi que les en-têtes et le code d'état), et les placera dans la réponse finale qui contient la valeur que vous avez renvoyée, filtrée par tout `response_model`.
+
+Vous pouvez également déclarer le paramètre `Response` dans des dépendances, et y définir des cookies (et des en-têtes).
+
+## Renvoyer une `Response` directement { #return-a-response-directly }
+
+Vous pouvez également créer des cookies en renvoyant une `Response` directement dans votre code.
+
+Pour ce faire, vous pouvez créer une réponse comme décrit dans [Renvoyer une Response directement](response-directly.md).
+
+Définissez ensuite des cookies dessus, puis renvoyez-la :
+
+{* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *}
+
+/// tip | Astuce
+
+Gardez à l'esprit que si vous renvoyez une réponse directement au lieu d'utiliser le paramètre `Response`, FastAPI la renverra telle quelle.
+
+Vous devez donc vous assurer que vos données sont du type correct. Par exemple, qu'elles sont compatibles avec JSON si vous renvoyez une `JSONResponse`.
+
+Et également que vous n'envoyez pas de données qui auraient dû être filtrées par un `response_model`.
+
+///
+
+### En savoir plus { #more-info }
+
+/// note | Détails techniques
+
+Vous pouvez également utiliser `from starlette.responses import Response` ou `from starlette.responses import JSONResponse`.
+
+**FastAPI** fournit les mêmes `starlette.responses` que `fastapi.responses` simplement pour votre commodité, en tant que développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette.
+
+Et comme `Response` peut être utilisé fréquemment pour définir des en-têtes et des cookies, **FastAPI** la met également à disposition via `fastapi.Response`.
+
+///
+
+Pour voir tous les paramètres et options disponibles, consultez la [documentation de Starlette](https://www.starlette.dev/responses/#set-cookie).
diff --git a/docs/fr/docs/advanced/response-directly.md b/docs/fr/docs/advanced/response-directly.md
index 1c923fb82ca3d..5ef479584ead2 100644
--- a/docs/fr/docs/advanced/response-directly.md
+++ b/docs/fr/docs/advanced/response-directly.md
@@ -1,63 +1,83 @@
-# Renvoyer directement une réponse
+# Renvoyer directement une réponse { #return-a-response-directly }
-Lorsque vous créez une *opération de chemins* **FastAPI**, vous pouvez normalement retourner n'importe quelle donnée : un `dict`, une `list`, un modèle Pydantic, un modèle de base de données, etc.
+Lorsque vous créez un *chemin d'accès* **FastAPI**, vous pouvez normalement renvoyer n'importe quelle donnée : un `dict`, une `list`, un modèle Pydantic, un modèle de base de données, etc.
-Par défaut, **FastAPI** convertirait automatiquement cette valeur de retour en JSON en utilisant le `jsonable_encoder` expliqué dans [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank}.
+Si vous déclarez un [Modèle de réponse](../tutorial/response-model.md), FastAPI l'utilise pour sérialiser les données en JSON, en utilisant Pydantic.
-Ensuite, en arrière-plan, il mettra ces données JSON-compatible (par exemple un `dict`) à l'intérieur d'un `JSONResponse` qui sera utilisé pour envoyer la réponse au client.
+Si vous ne déclarez pas de modèle de réponse, FastAPI utilise le `jsonable_encoder` expliqué dans [Encodeur compatible JSON](../tutorial/encoder.md) et le place dans une `JSONResponse`.
-Mais vous pouvez retourner une `JSONResponse` directement à partir de vos *opérations de chemin*.
+Vous pouvez également créer directement une `JSONResponse` et la renvoyer.
-Cela peut être utile, par exemple, pour retourner des en-têtes personnalisés ou des cookies.
+/// tip | Astuce
-## Renvoyer une `Response`
+Vous aurez normalement une bien meilleure performance en utilisant un [Modèle de réponse](../tutorial/response-model.md) qu'en renvoyant directement une `JSONResponse`, car de cette façon la sérialisation des données est effectuée par Pydantic, en Rust.
-En fait, vous pouvez retourner n'importe quelle `Response` ou n'importe quelle sous-classe de celle-ci.
+///
-!!! Note
- `JSONResponse` est elle-même une sous-classe de `Response`.
+## Renvoyer une `Response` { #return-a-response }
-Et quand vous retournez une `Response`, **FastAPI** la transmet directement.
+Vous pouvez renvoyer une `Response` ou n'importe laquelle de ses sous-classes.
-Elle ne fera aucune conversion de données avec les modèles Pydantic, elle ne convertira pas le contenu en un type quelconque.
+/// info
-Cela vous donne beaucoup de flexibilité. Vous pouvez retourner n'importe quel type de données, surcharger n'importe quelle déclaration ou validation de données.
+`JSONResponse` est elle-même une sous-classe de `Response`.
-## Utiliser le `jsonable_encoder` dans une `Response`
+///
-Parce que **FastAPI** n'apporte aucune modification à une `Response` que vous retournez, vous devez vous assurer que son contenu est prêt à être utilisé (sérialisable).
+Et lorsque vous renvoyez une `Response`, **FastAPI** la transmet directement.
-Par exemple, vous ne pouvez pas mettre un modèle Pydantic dans une `JSONResponse` sans d'abord le convertir en un `dict` avec tous les types de données (comme `datetime`, `UUID`, etc.) convertis en types compatibles avec JSON.
+Il n'effectue aucune conversion de données avec les modèles Pydantic, il ne convertit pas le contenu en un autre type, etc.
-Pour ces cas, vous pouvez spécifier un appel à `jsonable_encoder` pour convertir vos données avant de les passer à une réponse :
+Cela vous donne beaucoup de flexibilité. Vous pouvez renvoyer n'importe quel type de données, surcharger toute déclaration ou validation de données, etc.
-```Python hl_lines="6-7 21-22"
-{!../../../docs_src/response_directly/tutorial001.py!}
-```
+Cela vous donne aussi beaucoup de responsabilité. Vous devez vous assurer que les données que vous renvoyez sont correctes, dans le bon format, qu'elles peuvent être sérialisées, etc.
-!!! note "Détails techniques"
- Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`.
+## Utiliser le `jsonable_encoder` dans une `Response` { #using-the-jsonable-encoder-in-a-response }
- **FastAPI** fournit le même objet `starlette.responses` que `fastapi.responses` juste par commodité pour le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette.
+Comme **FastAPI** n'apporte aucune modification à une `Response` que vous renvoyez, vous devez vous assurer que son contenu est prêt pour cela.
-## Renvoyer une `Response` personnalisée
+Par exemple, vous ne pouvez pas mettre un modèle Pydantic dans une `JSONResponse` sans d'abord le convertir en un `dict` avec tous les types de données (comme `datetime`, `UUID`, etc.) convertis en types compatibles JSON.
-L'exemple ci-dessus montre toutes les parties dont vous avez besoin, mais il n'est pas encore très utile, car vous auriez pu retourner l'`item` directement, et **FastAPI** l'aurait mis dans une `JSONResponse` pour vous, en le convertissant en `dict`, etc. Tout cela par défaut.
+Pour ces cas, vous pouvez utiliser le `jsonable_encoder` pour convertir vos données avant de les passer à une réponse :
-Maintenant, voyons comment vous pourriez utiliser cela pour retourner une réponse personnalisée.
+{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}
-Disons que vous voulez retourner une réponse XML.
+/// note | Détails techniques
-Vous pouvez mettre votre contenu XML dans une chaîne de caractères, la placer dans une `Response`, et la retourner :
+Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`.
-```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
-```
+**FastAPI** fournit le même `starlette.responses` que `fastapi.responses` uniquement par commodité pour vous, développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette.
-## Notes
+///
+
+## Renvoyer une `Response` personnalisée { #returning-a-custom-response }
+
+L'exemple ci-dessus montre toutes les parties dont vous avez besoin, mais il n'est pas encore très utile, car vous auriez pu renvoyer l'`item` directement, et **FastAPI** l'aurait placé dans une `JSONResponse` pour vous, en le convertissant en `dict`, etc. Tout cela par défaut.
+
+Voyons maintenant comment vous pourriez utiliser cela pour renvoyer une réponse personnalisée.
+
+Disons que vous voulez renvoyer une [réponse XML](https://en.wikipedia.org/wiki/XML).
+
+Vous pouvez placer votre contenu XML dans une chaîne de caractères, le mettre dans une `Response` et le renvoyer :
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+## Comprendre le fonctionnement d'un Modèle de réponse { #how-a-response-model-works }
+
+Lorsque vous déclarez un [Modèle de réponse - Type de retour](../tutorial/response-model.md) dans un chemin d'accès, **FastAPI** l'utilise pour sérialiser les données en JSON, en utilisant Pydantic.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+Comme cela se passe côté Rust, la performance sera bien meilleure que si cela était fait avec le Python classique et la classe `JSONResponse`.
+
+Lorsque vous utilisez un `response_model` ou un type de retour, FastAPI n'utilise ni le `jsonable_encoder` pour convertir les données (ce qui serait plus lent) ni la classe `JSONResponse`.
+
+À la place, il prend les octets JSON générés avec Pydantic en utilisant le modèle de réponse (ou le type de retour) et renvoie directement une `Response` avec le type de média approprié pour JSON (`application/json`).
+
+## Notes { #notes }
Lorsque vous renvoyez une `Response` directement, ses données ne sont pas validées, converties (sérialisées), ni documentées automatiquement.
-Mais vous pouvez toujours les documenter comme décrit dans [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}.
+Mais vous pouvez toujours les documenter comme décrit dans [Réponses supplémentaires dans OpenAPI](additional-responses.md).
-Vous pouvez voir dans les sections suivantes comment utiliser/déclarer ces `Response`s personnalisées tout en conservant la conversion automatique des données, la documentation, etc.
+Vous pouvez voir dans les sections suivantes comment utiliser/déclarer ces `Response` personnalisées tout en conservant la conversion automatique des données, la documentation, etc.
diff --git a/docs/fr/docs/advanced/response-headers.md b/docs/fr/docs/advanced/response-headers.md
new file mode 100644
index 0000000000000..b7568b51fcdaf
--- /dev/null
+++ b/docs/fr/docs/advanced/response-headers.md
@@ -0,0 +1,41 @@
+# En-têtes de réponse { #response-headers }
+
+## Utiliser un paramètre `Response` { #use-a-response-parameter }
+
+Vous pouvez déclarer un paramètre de type `Response` dans votre fonction de chemin d'accès (comme vous pouvez le faire pour les cookies).
+
+Vous pouvez ensuite définir des en-têtes dans cet objet de réponse temporaire.
+
+{* ../../docs_src/response_headers/tutorial002_py310.py hl[1, 7:8] *}
+
+Ensuite, vous pouvez renvoyer n'importe quel objet dont vous avez besoin, comme d'habitude (un `dict`, un modèle de base de données, etc.).
+
+Et si vous avez déclaré un `response_model`, il sera toujours utilisé pour filtrer et convertir l'objet que vous avez renvoyé.
+
+**FastAPI** utilisera cette réponse temporaire pour extraire les en-têtes (ainsi que les cookies et le code de statut), et les placera dans la réponse finale qui contient la valeur que vous avez renvoyée, filtrée par tout `response_model`.
+
+Vous pouvez également déclarer le paramètre `Response` dans des dépendances, et y définir des en-têtes (et des cookies).
+
+## Renvoyer une `Response` directement { #return-a-response-directly }
+
+Vous pouvez également ajouter des en-têtes lorsque vous renvoyez une `Response` directement.
+
+Créez une réponse comme décrit dans [Renvoyer une Response directement](response-directly.md) et passez les en-têtes comme paramètre supplémentaire :
+
+{* ../../docs_src/response_headers/tutorial001_py310.py hl[10:12] *}
+
+/// note | Détails techniques
+
+Vous pouvez également utiliser `from starlette.responses import Response` ou `from starlette.responses import JSONResponse`.
+
+**FastAPI** fournit les mêmes `starlette.responses` sous `fastapi.responses` simplement pour votre commodité, en tant que développeur. Mais la plupart des réponses disponibles viennent directement de Starlette.
+
+Et comme `Response` peut être utilisée fréquemment pour définir des en-têtes et des cookies, **FastAPI** la fournit aussi via `fastapi.Response`.
+
+///
+
+## En-têtes personnalisés { #custom-headers }
+
+Gardez à l'esprit que des en-têtes propriétaires personnalisés peuvent être ajoutés [en utilisant le préfixe `X-`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers).
+
+Mais si vous avez des en-têtes personnalisés que vous voulez qu'un client dans un navigateur puisse voir, vous devez les ajouter à vos configurations CORS (en savoir plus dans [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md)), en utilisant le paramètre `expose_headers` documenté dans [la documentation CORS de Starlette](https://www.starlette.dev/middleware/#corsmiddleware).
diff --git a/docs/fr/docs/advanced/security/http-basic-auth.md b/docs/fr/docs/advanced/security/http-basic-auth.md
new file mode 100644
index 0000000000000..97e9df6ce5d76
--- /dev/null
+++ b/docs/fr/docs/advanced/security/http-basic-auth.md
@@ -0,0 +1,107 @@
+# Authentification HTTP Basic { #http-basic-auth }
+
+Pour les cas les plus simples, vous pouvez utiliser l'authentification HTTP Basic.
+
+Avec l'authentification HTTP Basic, l'application attend un en-tête contenant un nom d'utilisateur et un mot de passe.
+
+Si elle ne le reçoit pas, elle renvoie une erreur HTTP 401 « Unauthorized ».
+
+Et elle renvoie un en-tête `WWW-Authenticate` avec la valeur `Basic`, et un paramètre optionnel `realm`.
+
+Cela indique au navigateur d'afficher l'invite intégrée pour saisir un nom d'utilisateur et un mot de passe.
+
+Ensuite, lorsque vous saisissez ce nom d'utilisateur et ce mot de passe, le navigateur les envoie automatiquement dans l'en-tête.
+
+## Authentification HTTP Basic simple { #simple-http-basic-auth }
+
+- Importer `HTTPBasic` et `HTTPBasicCredentials`.
+- Créer un « schéma de sécurité » en utilisant `HTTPBasic`.
+- Utiliser ce `security` avec une dépendance dans votre chemin d'accès.
+- Cela renvoie un objet de type `HTTPBasicCredentials` :
+ - Il contient le `username` et le `password` envoyés.
+
+{* ../../docs_src/security/tutorial006_an_py310.py hl[4,8,12] *}
+
+Lorsque vous essayez d'ouvrir l'URL pour la première fois (ou cliquez sur le bouton « Execute » dans les documents) le navigateur vous demandera votre nom d'utilisateur et votre mot de passe :
+
+
+
+## Vérifier le nom d'utilisateur { #check-the-username }
+
+Voici un exemple plus complet.
+
+Utilisez une dépendance pour vérifier si le nom d'utilisateur et le mot de passe sont corrects.
+
+Pour cela, utilisez le module standard Python [`secrets`](https://docs.python.org/3/library/secrets.html) pour vérifier le nom d'utilisateur et le mot de passe.
+
+`secrets.compare_digest()` doit recevoir des `bytes` ou une `str` ne contenant que des caractères ASCII (ceux de l'anglais), ce qui signifie qu'elle ne fonctionnerait pas avec des caractères comme `á`, comme dans `Sebastián`.
+
+Pour gérer cela, nous convertissons d'abord `username` et `password` en `bytes` en les encodant en UTF-8.
+
+Nous pouvons ensuite utiliser `secrets.compare_digest()` pour vérifier que `credentials.username` est « stanleyjobson » et que `credentials.password` est « swordfish ».
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[1,12:24] *}
+
+Cela serait équivalent à :
+
+```Python
+if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
+ # Renvoyer une erreur
+ ...
+```
+
+Mais en utilisant `secrets.compare_digest()`, cela sera sécurisé contre un type d'attaques appelé « attaques par chronométrage ».
+
+### Attaques par chronométrage { #timing-attacks }
+
+Mais qu'est-ce qu'une « attaque par chronométrage » ?
+
+Imaginons que des attaquants essaient de deviner le nom d'utilisateur et le mot de passe.
+
+Ils envoient alors une requête avec un nom d'utilisateur `johndoe` et un mot de passe `love123`.
+
+Le code Python de votre application serait alors équivalent à quelque chose comme :
+
+```Python
+if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Mais au moment où Python compare le premier `j` de `johndoe` au premier `s` de `stanleyjobson`, il retournera `False`, car il sait déjà que ces deux chaînes ne sont pas identiques, en se disant qu'« il n'est pas nécessaire de gaspiller plus de calcul pour comparer le reste des lettres ». Et votre application dira « Nom d'utilisateur ou mot de passe incorrect ».
+
+Mais ensuite, les attaquants essaient avec le nom d'utilisateur `stanleyjobsox` et le mot de passe `love123`.
+
+Et le code de votre application fait quelque chose comme :
+
+```Python
+if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Python devra comparer tout `stanleyjobso` dans `stanleyjobsox` et `stanleyjobson` avant de réaliser que les deux chaînes ne sont pas identiques. Cela prendra donc quelques microsecondes supplémentaires pour répondre « Nom d'utilisateur ou mot de passe incorrect ».
+
+#### Le temps de réponse aide les attaquants { #the-time-to-answer-helps-the-attackers }
+
+À ce stade, en remarquant que le serveur a mis quelques microsecondes de plus à envoyer la réponse « Nom d'utilisateur ou mot de passe incorrect », les attaquants sauront qu'ils ont trouvé quelque chose de juste : certaines des premières lettres étaient correctes.
+
+Ils peuvent alors réessayer en sachant que c'est probablement quelque chose de plus proche de `stanleyjobsox` que de `johndoe`.
+
+#### Une attaque « professionnelle » { #a-professional-attack }
+
+Bien sûr, les attaquants n'essaieraient pas tout cela à la main ; ils écriraient un programme pour le faire, avec éventuellement des milliers ou des millions de tests par seconde. Ils obtiendraient une lettre correcte supplémentaire à la fois.
+
+Ce faisant, en quelques minutes ou heures, les attaquants devineraient le nom d'utilisateur et le mot de passe corrects, avec « l'aide » de notre application, simplement en se basant sur le temps de réponse.
+
+#### Corrigez-le avec `secrets.compare_digest()` { #fix-it-with-secrets-compare-digest }
+
+Mais dans notre code nous utilisons justement `secrets.compare_digest()`.
+
+En bref, il faudra le même temps pour comparer `stanleyjobsox` à `stanleyjobson` que pour comparer `johndoe` à `stanleyjobson`. Il en va de même pour le mot de passe.
+
+Ainsi, en utilisant `secrets.compare_digest()` dans le code de votre application, votre application sera protégée contre toute cette gamme d'attaques de sécurité.
+
+### Renvoyer l'erreur { #return-the-error }
+
+Après avoir détecté que les identifiants sont incorrects, renvoyez une `HTTPException` avec un code d'état 401 (le même que lorsque aucun identifiant n'est fourni) et ajoutez l'en-tête `WWW-Authenticate` pour que le navigateur affiche à nouveau l'invite de connexion :
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[26:30] *}
diff --git a/docs/fr/docs/advanced/security/index.md b/docs/fr/docs/advanced/security/index.md
new file mode 100644
index 0000000000000..f4cde6098717b
--- /dev/null
+++ b/docs/fr/docs/advanced/security/index.md
@@ -0,0 +1,19 @@
+# Sécurité avancée { #advanced-security }
+
+## Fonctionnalités supplémentaires { #additional-features }
+
+Il existe des fonctionnalités supplémentaires pour gérer la sécurité en plus de celles couvertes dans le [Tutoriel - Guide utilisateur : Sécurité](../../tutorial/security/index.md).
+
+/// tip | Astuce
+
+Les sections suivantes **ne sont pas nécessairement « advanced »**.
+
+Et il est possible que, pour votre cas d’utilisation, la solution se trouve dans l’une d’entre elles.
+
+///
+
+## Lire d’abord le tutoriel { #read-the-tutorial-first }
+
+Les sections suivantes partent du principe que vous avez déjà lu le [Tutoriel - Guide utilisateur : Sécurité](../../tutorial/security/index.md) principal.
+
+Elles s’appuient toutes sur les mêmes concepts, mais permettent des fonctionnalités supplémentaires.
diff --git a/docs/fr/docs/advanced/security/oauth2-scopes.md b/docs/fr/docs/advanced/security/oauth2-scopes.md
new file mode 100644
index 0000000000000..f27b95b4b7fbd
--- /dev/null
+++ b/docs/fr/docs/advanced/security/oauth2-scopes.md
@@ -0,0 +1,274 @@
+# Scopes OAuth2 { #oauth2-scopes }
+
+Vous pouvez utiliser des scopes OAuth2 directement avec **FastAPI**, ils sont intégrés pour fonctionner de manière transparente.
+
+Cela vous permettrait d’avoir un système d’autorisations plus fin, conforme au standard OAuth2, intégré à votre application OpenAPI (et à la documentation de l’API).
+
+OAuth2 avec scopes est le mécanisme utilisé par de nombreux grands fournisseurs d’authentification, comme Facebook, Google, GitHub, Microsoft, X (Twitter), etc. Ils l’utilisent pour fournir des permissions spécifiques aux utilisateurs et aux applications.
+
+Chaque fois que vous « log in with » Facebook, Google, GitHub, Microsoft, X (Twitter), cette application utilise OAuth2 avec scopes.
+
+Dans cette section, vous verrez comment gérer l’authentification et l’autorisation avec le même OAuth2 avec scopes dans votre application **FastAPI**.
+
+/// warning | Alertes
+
+C’est une section plus ou moins avancée. Si vous débutez, vous pouvez la passer.
+
+Vous n’avez pas nécessairement besoin des scopes OAuth2, et vous pouvez gérer l’authentification et l’autorisation comme vous le souhaitez.
+
+Mais OAuth2 avec scopes peut s’intégrer élégamment à votre API (avec OpenAPI) et à votre documentation d’API.
+
+Néanmoins, c’est toujours à vous de faire appliquer ces scopes, ou toute autre exigence de sécurité/autorisation, selon vos besoins, dans votre code.
+
+Dans de nombreux cas, OAuth2 avec scopes peut être excessif.
+
+Mais si vous savez que vous en avez besoin, ou si vous êtes curieux, continuez à lire.
+
+///
+
+## Scopes OAuth2 et OpenAPI { #oauth2-scopes-and-openapi }
+
+La spécification OAuth2 définit des « scopes » comme une liste de chaînes séparées par des espaces.
+
+Le contenu de chacune de ces chaînes peut avoir n’importe quel format, mais ne doit pas contenir d’espaces.
+
+Ces scopes représentent des « permissions ».
+
+Dans OpenAPI (par ex. la documentation de l’API), vous pouvez définir des « schémas de sécurité ».
+
+Lorsqu’un de ces schémas de sécurité utilise OAuth2, vous pouvez aussi déclarer et utiliser des scopes.
+
+Chaque « scope » est juste une chaîne (sans espaces).
+
+Ils sont généralement utilisés pour déclarer des permissions de sécurité spécifiques, par exemple :
+
+* `users:read` ou `users:write` sont des exemples courants.
+* `instagram_basic` est utilisé par Facebook / Instagram.
+* `https://www.googleapis.com/auth/drive` est utilisé par Google.
+
+/// info
+
+Dans OAuth2, un « scope » est simplement une chaîne qui déclare une permission spécifique requise.
+
+Peu importe s’il contient d’autres caractères comme `:` ou si c’est une URL.
+
+Ces détails dépendent de l’implémentation.
+
+Pour OAuth2, ce ne sont que des chaînes.
+
+///
+
+## Vue d’ensemble { #global-view }
+
+Voyons d’abord rapidement les parties qui changent par rapport aux exemples du **Tutoriel - Guide utilisateur** pour [OAuth2 avec mot de passe (et hachage), Bearer avec jetons JWT](../../tutorial/security/oauth2-jwt.md). Cette fois, en utilisant des scopes OAuth2 :
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}
+
+Passons maintenant en revue ces changements étape par étape.
+
+## Déclarer le schéma de sécurité OAuth2 { #oauth2-security-scheme }
+
+Le premier changement est que nous déclarons maintenant le schéma de sécurité OAuth2 avec deux scopes disponibles, `me` et `items`.
+
+Le paramètre `scopes` reçoit un `dict` avec chaque scope en clé et la description en valeur :
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *}
+
+Comme nous déclarons maintenant ces scopes, ils apparaîtront dans la documentation de l’API lorsque vous vous authentifiez/autorisez.
+
+Et vous pourrez sélectionner à quels scopes vous souhaitez accorder l’accès : `me` et `items`.
+
+C’est le même mécanisme utilisé lorsque vous donnez des permissions en vous connectant avec Facebook, Google, GitHub, etc. :
+
+
+
+## Jeton JWT avec scopes { #jwt-token-with-scopes }
+
+Modifiez maintenant le *chemin d’accès* du jeton pour renvoyer les scopes demandés.
+
+Nous utilisons toujours le même `OAuth2PasswordRequestForm`. Il inclut une propriété `scopes` avec une `list` de `str`, contenant chaque scope reçu dans la requête.
+
+Et nous renvoyons les scopes comme partie du jeton JWT.
+
+/// danger | Danger
+
+Pour simplifier, ici nous ajoutons directement au jeton les scopes reçus.
+
+Mais dans votre application, pour la sécurité, vous devez vous assurer de n’ajouter que les scopes que l’utilisateur est réellement autorisé à avoir, ou ceux que vous avez prédéfinis.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}
+
+## Déclarer des scopes dans les chemins d’accès et les dépendances { #declare-scopes-in-path-operations-and-dependencies }
+
+Nous déclarons maintenant que le *chemin d’accès* `/users/me/items/` nécessite le scope `items`.
+
+Pour cela, nous importons et utilisons `Security` depuis `fastapi`.
+
+Vous pouvez utiliser `Security` pour déclarer des dépendances (comme `Depends`), mais `Security` reçoit aussi un paramètre `scopes` avec une liste de scopes (chaînes).
+
+Dans ce cas, nous passons une fonction de dépendance `get_current_active_user` à `Security` (de la même manière que nous le ferions avec `Depends`).
+
+Mais nous passons aussi une `list` de scopes, ici avec un seul scope : `items` (il pourrait y en avoir plus).
+
+Et la fonction de dépendance `get_current_active_user` peut également déclarer des sous-dépendances, non seulement avec `Depends` mais aussi avec `Security`. En déclarant sa propre fonction de sous-dépendance (`get_current_user`), et davantage d’exigences de scopes.
+
+Dans ce cas, elle nécessite le scope `me` (elle pourrait en exiger plusieurs).
+
+/// note | Remarque
+
+Vous n’avez pas nécessairement besoin d’ajouter des scopes différents à différents endroits.
+
+Nous le faisons ici pour montrer comment **FastAPI** gère des scopes déclarés à différents niveaux.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}
+
+/// info | Détails techniques
+
+`Security` est en réalité une sous-classe de `Depends`, et elle n’a qu’un paramètre supplémentaire que nous verrons plus tard.
+
+Mais en utilisant `Security` au lieu de `Depends`, **FastAPI** saura qu’il peut déclarer des scopes de sécurité, les utiliser en interne et documenter l’API avec OpenAPI.
+
+Cependant, lorsque vous importez `Query`, `Path`, `Depends`, `Security` et d’autres depuis `fastapi`, ce sont en fait des fonctions qui renvoient des classes spéciales.
+
+///
+
+## Utiliser `SecurityScopes` { #use-securityscopes }
+
+Mettez maintenant à jour la dépendance `get_current_user`.
+
+C’est celle utilisée par les dépendances ci-dessus.
+
+C’est ici que nous utilisons le même schéma OAuth2 que nous avons créé auparavant, en le déclarant comme dépendance : `oauth2_scheme`.
+
+Comme cette fonction de dépendance n’a pas elle-même d’exigences de scope, nous pouvons utiliser `Depends` avec `oauth2_scheme`, nous n’avons pas à utiliser `Security` quand nous n’avons pas besoin de spécifier des scopes de sécurité.
+
+Nous déclarons également un paramètre spécial de type `SecurityScopes`, importé de `fastapi.security`.
+
+Cette classe `SecurityScopes` est similaire à `Request` (`Request` servait à obtenir directement l’objet requête).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}
+
+## Utiliser les `scopes` { #use-the-scopes }
+
+Le paramètre `security_scopes` sera de type `SecurityScopes`.
+
+Il aura une propriété `scopes` avec une liste contenant tous les scopes requis par lui-même et par toutes les dépendances qui l’utilisent comme sous-dépendance. Cela signifie, tous les « dépendants » ... cela peut paraître déroutant, c’est expliqué à nouveau plus bas.
+
+L’objet `security_scopes` (de classe `SecurityScopes`) fournit aussi un attribut `scope_str` avec une chaîne unique, contenant ces scopes séparés par des espaces (nous allons l’utiliser).
+
+Nous créons une `HTTPException` que nous pouvons réutiliser (`raise`) plus tard à plusieurs endroits.
+
+Dans cette exception, nous incluons les scopes requis (le cas échéant) sous forme de chaîne séparée par des espaces (en utilisant `scope_str`). Nous plaçons cette chaîne contenant les scopes dans l’en-tête `WWW-Authenticate` (cela fait partie de la spécification).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}
+
+## Vérifier le `username` et la structure des données { #verify-the-username-and-data-shape }
+
+Nous vérifions que nous obtenons un `username`, et extrayons les scopes.
+
+Nous validons ensuite ces données avec le modèle Pydantic (en capturant l’exception `ValidationError`), et si nous obtenons une erreur lors de la lecture du jeton JWT ou de la validation des données avec Pydantic, nous levons la `HTTPException` que nous avons créée auparavant.
+
+Pour cela, nous mettons à jour le modèle Pydantic `TokenData` avec une nouvelle propriété `scopes`.
+
+En validant les données avec Pydantic, nous pouvons nous assurer que nous avons, par exemple, exactement une `list` de `str` pour les scopes et un `str` pour le `username`.
+
+Au lieu, par exemple, d’un `dict`, ou autre chose, ce qui pourrait casser l’application plus tard et constituer un risque de sécurité.
+
+Nous vérifions également que nous avons un utilisateur avec ce nom d’utilisateur, et sinon, nous levons la même exception que précédemment.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}
+
+## Vérifier les `scopes` { #verify-the-scopes }
+
+Nous vérifions maintenant que tous les scopes requis, par cette dépendance et tous les dépendants (y compris les *chemins d’accès*), sont inclus dans les scopes fournis dans le jeton reçu, sinon nous levons une `HTTPException`.
+
+Pour cela, nous utilisons `security_scopes.scopes`, qui contient une `list` avec tous ces scopes en `str`.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}
+
+## Arbre de dépendances et scopes { #dependency-tree-and-scopes }
+
+Revoyons encore cet arbre de dépendances et les scopes.
+
+Comme la dépendance `get_current_active_user` a une sous-dépendance `get_current_user`, le scope « me » déclaré dans `get_current_active_user` sera inclus dans la liste des scopes requis dans `security_scopes.scopes` passé à `get_current_user`.
+
+Le *chemin d’accès* lui-même déclare également un scope, « items », il sera donc aussi présent dans la liste `security_scopes.scopes` passée à `get_current_user`.
+
+Voici à quoi ressemble la hiérarchie des dépendances et des scopes :
+
+* Le *chemin d’accès* `read_own_items` a :
+ * Des scopes requis `["items"]` avec la dépendance :
+ * `get_current_active_user` :
+ * La fonction de dépendance `get_current_active_user` a :
+ * Des scopes requis `["me"]` avec la dépendance :
+ * `get_current_user` :
+ * La fonction de dépendance `get_current_user` a :
+ * Aucun scope requis par elle-même.
+ * Une dépendance utilisant `oauth2_scheme`.
+ * Un paramètre `security_scopes` de type `SecurityScopes` :
+ * Ce paramètre `security_scopes` a une propriété `scopes` avec une `list` contenant tous les scopes déclarés ci-dessus, donc :
+ * `security_scopes.scopes` contiendra `["me", "items"]` pour le *chemin d’accès* `read_own_items`.
+ * `security_scopes.scopes` contiendra `["me"]` pour le *chemin d’accès* `read_users_me`, car il est déclaré dans la dépendance `get_current_active_user`.
+ * `security_scopes.scopes` contiendra `[]` (rien) pour le *chemin d’accès* `read_system_status`, car il n’a déclaré aucun `Security` avec des `scopes`, et sa dépendance, `get_current_user`, ne déclare pas non plus de `scopes`.
+
+/// tip | Astuce
+
+L’élément important et « magique » ici est que `get_current_user` aura une liste différente de `scopes` à vérifier pour chaque *chemin d’accès*.
+
+Tout dépend des `scopes` déclarés dans chaque *chemin d’accès* et chaque dépendance dans l’arbre de dépendances pour ce *chemin d’accès* spécifique.
+
+///
+
+## Détails supplémentaires sur `SecurityScopes` { #more-details-about-securityscopes }
+
+Vous pouvez utiliser `SecurityScopes` à n’importe quel endroit, et à de multiples endroits, il n’a pas besoin d’être dans la dépendance « root ».
+
+Il aura toujours les scopes de sécurité déclarés dans les dépendances `Security` actuelles et tous les dépendants pour **ce** *chemin d’accès* spécifique et **cet** arbre de dépendances spécifique.
+
+Comme `SecurityScopes` contient tous les scopes déclarés par les dépendants, vous pouvez l’utiliser pour vérifier qu’un jeton possède les scopes requis dans une fonction de dépendance centrale, puis déclarer des exigences de scopes différentes dans différents *chemins d’accès*.
+
+Elles seront vérifiées indépendamment pour chaque *chemin d’accès*.
+
+## Tester { #check-it }
+
+Si vous ouvrez la documentation de l’API, vous pouvez vous authentifier et spécifier quels scopes vous voulez autoriser.
+
+
+
+Si vous ne sélectionnez aucun scope, vous serez « authenticated », mais lorsque vous essayerez d’accéder à `/users/me/` ou `/users/me/items/`, vous obtiendrez une erreur indiquant que vous n’avez pas suffisamment de permissions. Vous pourrez toujours accéder à `/status/`.
+
+Et si vous sélectionnez le scope `me` mais pas le scope `items`, vous pourrez accéder à `/users/me/` mais pas à `/users/me/items/`.
+
+C’est ce qui arriverait à une application tierce qui tenterait d’accéder à l’un de ces *chemins d’accès* avec un jeton fourni par un utilisateur, selon le nombre de permissions que l’utilisateur a accordées à l’application.
+
+## À propos des intégrations tierces { #about-third-party-integrations }
+
+Dans cet exemple, nous utilisons le flux OAuth2 « password ».
+
+C’est approprié lorsque nous nous connectons à notre propre application, probablement avec notre propre frontend.
+
+Parce que nous pouvons lui faire confiance pour recevoir le `username` et le `password`, puisque nous le contrôlons.
+
+Mais si vous construisez une application OAuth2 à laquelle d’autres se connecteraient (c.-à-d., si vous construisez un fournisseur d’authentification équivalent à Facebook, Google, GitHub, etc.), vous devez utiliser l’un des autres flux.
+
+Le plus courant est le flux implicite.
+
+Le plus sûr est le flux « code », mais il est plus complexe à implémenter car il nécessite plus d’étapes. Comme il est plus complexe, de nombreux fournisseurs finissent par recommander le flux implicite.
+
+/// note | Remarque
+
+Il est courant que chaque fournisseur d’authentification nomme ses flux différemment, pour en faire une partie de sa marque.
+
+Mais au final, ils implémentent le même standard OAuth2.
+
+///
+
+**FastAPI** inclut des utilitaires pour tous ces flux d’authentification OAuth2 dans `fastapi.security.oauth2`.
+
+## `Security` dans les dépendances du décorateur `dependencies` { #security-in-decorator-dependencies }
+
+De la même manière que vous pouvez définir une `list` de `Depends` dans le paramètre `dependencies` du décorateur (comme expliqué dans [Dépendances dans les décorateurs de chemins d’accès](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md)), vous pouvez aussi utiliser `Security` avec des `scopes` à cet endroit.
diff --git a/docs/fr/docs/advanced/settings.md b/docs/fr/docs/advanced/settings.md
new file mode 100644
index 0000000000000..e6eb52a4ee0eb
--- /dev/null
+++ b/docs/fr/docs/advanced/settings.md
@@ -0,0 +1,302 @@
+# Paramètres et variables d'environnement { #settings-and-environment-variables }
+
+Dans de nombreux cas, votre application peut avoir besoin de paramètres ou de configurations externes, par exemple des clés secrètes, des identifiants de base de données, des identifiants pour des services d'e-mail, etc.
+
+La plupart de ces paramètres sont variables (peuvent changer), comme les URL de base de données. Et beaucoup peuvent être sensibles, comme les secrets.
+
+C'est pourquoi il est courant de les fournir via des variables d'environnement lues par l'application.
+
+/// tip | Astuce
+
+Pour comprendre les variables d'environnement, vous pouvez lire [Variables d'environnement](../environment-variables.md).
+
+///
+
+## Types et validation { #types-and-validation }
+
+Ces variables d'environnement ne gèrent que des chaînes de texte, car elles sont externes à Python et doivent être compatibles avec d'autres programmes et le reste du système (et même avec différents systèmes d'exploitation, comme Linux, Windows, macOS).
+
+Cela signifie que toute valeur lue en Python depuis une variable d'environnement sera une `str`, et toute conversion vers un autre type ou toute validation doit être effectuée dans le code.
+
+## Pydantic `Settings` { #pydantic-settings }
+
+Heureusement, Pydantic fournit un excellent utilitaire pour gérer ces paramètres provenant des variables d'environnement avec [Pydantic : gestion des paramètres](https://docs.pydantic.dev/latest/concepts/pydantic_settings/).
+
+### Installer `pydantic-settings` { #install-pydantic-settings }
+
+D'abord, vous devez créer votre [environnement virtuel](../virtual-environments.md), l'activer, puis installer le paquet `pydantic-settings` :
+
+
+
+Ensuite, ouvrez la documentation de la sous‑application à [http://127.0.0.1:8000/subapi/docs](http://127.0.0.1:8000/subapi/docs).
+
+Vous verrez la documentation API automatique pour la sous‑application, n'incluant que ses propres _chemins d'accès_, tous sous le préfixe de sous‑chemin correct `/subapi` :
+
+
+
+Si vous essayez d'interagir avec l'une ou l'autre des deux interfaces, elles fonctionneront correctement, car le navigateur pourra communiquer avec chaque application ou sous‑application spécifique.
+
+### Détails techniques : `root_path` { #technical-details-root-path }
+
+Lorsque vous montez une sous‑application comme ci‑dessus, FastAPI se charge de communiquer le chemin de montage à la sous‑application au moyen d'un mécanisme de la spécification ASGI appelé `root_path`.
+
+De cette manière, la sous‑application saura utiliser ce préfixe de chemin pour l'interface de documentation.
+
+La sous‑application peut également avoir ses propres sous‑applications montées et tout fonctionnera correctement, car FastAPI gère automatiquement tous ces `root_path`.
+
+Vous en apprendrez davantage sur `root_path` et sur la façon de l'utiliser explicitement dans la section [Derrière un proxy](behind-a-proxy.md).
diff --git a/docs/fr/docs/advanced/templates.md b/docs/fr/docs/advanced/templates.md
new file mode 100644
index 0000000000000..582cf925baaae
--- /dev/null
+++ b/docs/fr/docs/advanced/templates.md
@@ -0,0 +1,126 @@
+# Templates { #templates }
+
+Vous pouvez utiliser n'importe quel moteur de templates avec **FastAPI**.
+
+Un choix courant est Jinja2, le même que celui utilisé par Flask et d'autres outils.
+
+Il existe des utilitaires pour le configurer facilement que vous pouvez utiliser directement dans votre application **FastAPI** (fournis par Starlette).
+
+## Installer les dépendances { #install-dependencies }
+
+Vous devez créer un [environnement virtuel](../virtual-environments.md), l'activer, puis installer `jinja2` :
+
+
+
+Vous pouvez saisir des messages dans le champ de saisie et les envoyer :
+
+
+
+Et votre application **FastAPI** avec WebSockets vous répondra :
+
+
+
+Vous pouvez envoyer (et recevoir) de nombreux messages :
+
+
+
+Et tous utiliseront la même connexion WebSocket.
+
+## Utiliser `Depends` et autres { #using-depends-and-others }
+
+Dans les endpoints WebSocket, vous pouvez importer depuis `fastapi` et utiliser :
+
+* `Depends`
+* `Security`
+* `Cookie`
+* `Header`
+* `Path`
+* `Query`
+
+Ils fonctionnent de la même manière que pour les autres endpoints/*chemins d'accès* FastAPI :
+
+{* ../../docs_src/websockets_/tutorial002_an_py310.py hl[68:69,82] *}
+
+/// info
+
+Comme il s'agit d'un WebSocket, il n'est pas vraiment logique de lever une `HTTPException`, nous levons plutôt une `WebSocketException`.
+
+Vous pouvez utiliser un code de fermeture parmi les [codes valides définis dans la spécification](https://tools.ietf.org/html/rfc6455#section-7.4.1).
+
+///
+
+### Essayez les WebSockets avec des dépendances { #try-the-websockets-with-dependencies }
+
+Exécutez votre application :
+
+
+
+## Gérer les déconnexions et plusieurs clients { #handling-disconnections-and-multiple-clients }
+
+Lorsqu'une connexion WebSocket est fermée, l'instruction `await websocket.receive_text()` lèvera une exception `WebSocketDisconnect`, que vous pouvez ensuite intercepter et gérer comme dans cet exemple.
+
+{* ../../docs_src/websockets_/tutorial003_py310.py hl[79:81] *}
+
+Pour l'essayer :
+
+* Ouvrez l'application dans plusieurs onglets du navigateur.
+* Écrivez des messages depuis ceux-ci.
+* Puis fermez l'un des onglets.
+
+Cela lèvera l'exception `WebSocketDisconnect`, et tous les autres clients recevront un message comme :
+
+```
+Client #1596980209979 left the chat
+```
+
+/// tip | Astuce
+
+L'application ci-dessus est un exemple minimal et simple pour montrer comment gérer et diffuser des messages à plusieurs connexions WebSocket.
+
+Mais gardez à l'esprit que, comme tout est géré en mémoire, dans une seule liste, cela ne fonctionnera que tant que le processus s'exécute et uniquement avec un seul processus.
+
+Si vous avez besoin de quelque chose de facile à intégrer avec FastAPI mais plus robuste, pris en charge par Redis, PostgreSQL ou autres, consultez [encode/broadcaster](https://github.com/encode/broadcaster).
+
+///
+
+## Plus d'informations { #more-info }
+
+Pour en savoir plus sur les options, consultez la documentation de Starlette concernant :
+
+* [La classe `WebSocket`](https://www.starlette.dev/websockets/).
+* [Gestion des WebSocket basée sur des classes](https://www.starlette.dev/endpoints/#websocketendpoint).
diff --git a/docs/fr/docs/advanced/wsgi.md b/docs/fr/docs/advanced/wsgi.md
new file mode 100644
index 0000000000000..fe39729f7f405
--- /dev/null
+++ b/docs/fr/docs/advanced/wsgi.md
@@ -0,0 +1,51 @@
+# Inclure WSGI - Flask, Django, autres { #including-wsgi-flask-django-others }
+
+Vous pouvez monter des applications WSGI comme vous l'avez vu avec [Sous-applications - Montages](sub-applications.md), [Derrière un proxy](behind-a-proxy.md).
+
+Pour cela, vous pouvez utiliser `WSGIMiddleware` et l'utiliser pour envelopper votre application WSGI, par exemple Flask, Django, etc.
+
+## Utiliser `WSGIMiddleware` { #using-wsgimiddleware }
+
+/// info
+
+Cela nécessite l'installation de `a2wsgi`, par exemple avec `pip install a2wsgi`.
+
+///
+
+Vous devez importer `WSGIMiddleware` depuis `a2wsgi`.
+
+Ensuite, enveloppez l'application WSGI (par ex. Flask) avec le middleware.
+
+Puis, montez-la sous un chemin.
+
+{* ../../docs_src/wsgi/tutorial001_py310.py hl[1,3,23] *}
+
+/// note | Remarque
+
+Auparavant, il était recommandé d'utiliser `WSGIMiddleware` depuis `fastapi.middleware.wsgi`, mais il est désormais déprécié.
+
+Il est conseillé d'utiliser le package `a2wsgi` à la place. L'utilisation reste la même.
+
+Assurez-vous simplement que le package `a2wsgi` est installé et importez `WSGIMiddleware` correctement depuis `a2wsgi`.
+
+///
+
+## Vérifiez { #check-it }
+
+Désormais, chaque requête sous le chemin `/v1/` sera gérée par l'application Flask.
+
+Et le reste sera géré par **FastAPI**.
+
+Si vous l'exécutez et allez à [http://localhost:8000/v1/](http://localhost:8000/v1/) vous verrez la réponse de Flask :
+
+```txt
+Hello, World from Flask!
+```
+
+Et si vous allez à [http://localhost:8000/v2](http://localhost:8000/v2) vous verrez la réponse de FastAPI :
+
+```JSON
+{
+ "message": "Hello World"
+}
+```
diff --git a/docs/fr/docs/alternatives.md b/docs/fr/docs/alternatives.md
index 8e58a3dfa9da4..54ad83ae84e78 100644
--- a/docs/fr/docs/alternatives.md
+++ b/docs/fr/docs/alternatives.md
@@ -1,8 +1,8 @@
-# Alternatives, inspiration et comparaisons
+# Alternatives, inspiration et comparaisons { #alternatives-inspiration-and-comparisons }
Ce qui a inspiré **FastAPI**, comment il se compare à d'autres solutions et ce qu'il en a appris.
-## Intro
+## Intro { #intro }
**FastAPI** n'existerait pas sans les précédentes contributions d'autres projets.
@@ -13,11 +13,11 @@ fonctionnalités couvertes par **FastAPI** en utilisant de nombreux frameworks,
Mais à un moment donné il n'y avait pas d'autre option que de créer quelque chose qui offrait toutes ces
fonctionnalités, en reprenant et en combinant de la meilleure façon possible les meilleures idées des outils
-précédents, en utilisant des fonctionnalités du langage qui n'étaient même pas disponibles auparavant (type hints depuis Python 3.6+).
+précédents, en utilisant des fonctionnalités du langage qui n'étaient même pas disponibles auparavant (annotations de type depuis Python 3.6+).
-## Outils précédents
+## Outils précédents { #previous-tools }
-### Django
+### [Django](https://www.djangoproject.com/) { #django }
C'est le framework Python le plus populaire et il bénéficie d'une grande confiance. Il est utilisé pour construire
des systèmes tel qu'Instagram.
@@ -26,26 +26,32 @@ Il est relativement fortement couplé aux bases de données relationnelles (comm
n'est pas très facile d'utiliser une base de données NoSQL (comme Couchbase, MongoDB, Cassandra, etc.) comme principal moyen de
stockage.
-Il a été créé pour générer le HTML en backend, pas pour créer des API consommées par un frontend moderne (comme React, Vue.js et Angular) ou par d'autres systèmes (comme les appareils IoT) communiquant avec lui.
+Il a été créé pour générer le HTML en backend, pas pour créer des API consommées par un frontend moderne (comme React, Vue.js et Angular) ou par d'autres systèmes (comme les appareils IoT) communiquant avec lui.
-### Django REST Framework
+### [Django REST Framework](https://www.django-rest-framework.org/) { #django-rest-framework }
-Django REST framework a été conçu comme une boîte à outils flexible permettant de construire des API Web à partir de Django, afin d'améliorer ses capacités en matière d'API.
+Django REST Framework a été conçu comme une boîte à outils flexible permettant de construire des API Web à partir de Django, afin d'améliorer ses capacités en matière d'API.
Il est utilisé par de nombreuses entreprises, dont Mozilla, Red Hat et Eventbrite.
Il s'agissait de l'un des premiers exemples de **documentation automatique pour API**, et c'est précisément l'une des
-premières idées qui a inspiré "la recherche de" **FastAPI**.
+premières idées qui a inspiré « la recherche de » **FastAPI**.
-!!! note
-Django REST framework a été créé par Tom Christie. Le créateur de Starlette et Uvicorn, sur lesquels **FastAPI** est basé.
+/// note | Remarque
+
+Django REST Framework a été créé par Tom Christie. Le créateur de Starlette et Uvicorn, sur lesquels **FastAPI** est basé.
+
+///
+
+/// check | A inspiré **FastAPI** à
-!!! check "A inspiré **FastAPI** à"
Avoir une interface de documentation automatique de l'API.
-### Flask
+///
+
+### [Flask](https://flask.palletsprojects.com) { #flask }
-Flask est un "micro-framework", il ne comprend pas d'intégrations de bases de données ni beaucoup de choses qui sont fournies par défaut dans Django.
+Flask est un « micro‑framework », il ne comprend pas d'intégrations de bases de données ni beaucoup de choses qui sont fournies par défaut dans Django.
Cette simplicité et cette flexibilité permettent d'utiliser des bases de données NoSQL comme principal système de stockage de données.
@@ -54,17 +60,20 @@ technique par moments.
Il est aussi couramment utilisé pour d'autres applications qui n'ont pas nécessairement besoin d'une base de données, de gestion des utilisateurs ou de l'une des nombreuses fonctionnalités préinstallées dans Django. Bien que beaucoup de ces fonctionnalités puissent être ajoutées avec des plug-ins.
-Ce découplage des parties, et le fait d'être un "micro-framework" qui puisse être étendu pour couvrir exactement ce
+Ce découplage des parties, et le fait d'être un « micro‑framework » qui puisse être étendu pour couvrir exactement ce
qui est nécessaire, était une caractéristique clé que je voulais conserver.
-Compte tenu de la simplicité de Flask, il semblait bien adapté à la création d'API. La prochaine chose à trouver était un "Django REST Framework" pour Flask.
+Compte tenu de la simplicité de Flask, il semblait bien adapté à la création d'API. La prochaine chose à trouver était un « Django REST Framework » pour Flask.
-!!! check "A inspiré **FastAPI** à"
-Être un micro-framework. Il est donc facile de combiner les outils et les pièces nécessaires.
+/// check | A inspiré **FastAPI** à
+
+Être un micro‑framework. Il est donc facile de combiner les outils et les pièces nécessaires.
Proposer un système de routage simple et facile à utiliser.
-### Requests
+///
+
+### [Requests](https://requests.readthedocs.io) { #requests }
**FastAPI** n'est pas réellement une alternative à **Requests**. Leur cadre est très différent.
@@ -88,7 +97,7 @@ La façon dont vous l'utilisez est très simple. Par exemple, pour faire une req
response = requests.get("http://example.com/some/url")
```
-En contrepartie l'API _des opérations de chemin_ de FastAPI pourrait ressembler à ceci :
+L’opération de chemin d'accès correspondante dans **FastAPI** pourrait ressembler à ceci :
```Python hl_lines="1"
@app.get("/some/url")
@@ -98,11 +107,15 @@ def read_url():
Notez les similitudes entre `requests.get(...)` et `@app.get(...)`.
-!!! check "A inspiré **FastAPI** à"
-_ Avoir une API simple et intuitive.
-_ Utiliser les noms de méthodes HTTP (opérations) directement, de manière simple et intuitive. \* Avoir des valeurs par défaut raisonnables, mais des personnalisations puissantes.
+/// check | A inspiré **FastAPI** à
+
+* Avoir une API simple et intuitive.
+* Utiliser les noms de méthodes HTTP (opérations) directement, de manière simple et intuitive.
+* Avoir des valeurs par défaut raisonnables, mais des personnalisations puissantes.
-### Swagger / OpenAPI
+///
+
+### [Swagger](https://swagger.io/) / [OpenAPI](https://github.com/OAI/OpenAPI-Specification/) { #swagger-openapi }
La principale fonctionnalité que j'ai emprunté à Django REST Framework était la documentation automatique des API.
@@ -113,28 +126,30 @@ Swagger pour une API permettrait d'utiliser cette interface utilisateur web auto
À un moment donné, Swagger a été cédé à la Fondation Linux, puis a été rebaptisé OpenAPI.
-C'est pourquoi, lorsqu'on parle de la version 2.0, il est courant de dire "Swagger", et pour la version 3+ "OpenAPI".
+C'est pourquoi, lorsqu'on parle de la version 2.0, il est courant de dire « Swagger », et pour la version 3+ « OpenAPI ».
+
+/// check | A inspiré **FastAPI** à
-!!! check "A inspiré **FastAPI** à"
Adopter et utiliser une norme ouverte pour les spécifications des API, au lieu d'un schéma personnalisé.
- Intégrer des outils d'interface utilisateur basés sur des normes :
+Intégrer des outils d'interface utilisateur basés sur des normes :
+
+* [Swagger UI](https://github.com/swagger-api/swagger-ui)
+* [ReDoc](https://github.com/Rebilly/ReDoc)
- * Swagger UI
- * ReDoc
+Ces deux-là ont été choisis parce qu'ils sont populaires et stables, mais en faisant une recherche rapide, vous pourriez trouver des dizaines d'alternatives supplémentaires pour OpenAPI (que vous pouvez utiliser avec **FastAPI**).
- Ces deux-là ont été choisis parce qu'ils sont populaires et stables, mais en faisant une recherche rapide, vous pourriez trouver des dizaines d'alternatives supplémentaires pour OpenAPI (que vous pouvez utiliser avec **FastAPI**).
+///
-### Frameworks REST pour Flask
+### Frameworks REST pour Flask { #flask-rest-frameworks }
Il y a plusieurs frameworks REST pour Flask, mais après avoir investi du temps et du travail pour les étudier, j'ai
découvert que le développement de beaucoup d'entre eux sont suspendus ou abandonnés, avec plusieurs problèmes
permanents qui les rendent inadaptés.
-### Marshmallow
+### [Marshmallow](https://marshmallow.readthedocs.io/en/stable/) { #marshmallow }
-L'une des principales fonctionnalités nécessaires aux systèmes API est la "sérialisation" des données, qui consiste à prendre les données du code (Python) et à
+L'une des principales fonctionnalités nécessaires aux systèmes API est la « sérialisation » des données, qui consiste à prendre les données du code (Python) et à
les convertir en quelque chose qui peut être envoyé sur le réseau. Par exemple, convertir un objet contenant des
données provenant d'une base de données en un objet JSON. Convertir des objets `datetime` en strings, etc.
@@ -147,16 +162,17 @@ Sans un système de validation des données, vous devriez effectuer toutes les v
Ces fonctionnalités sont ce pourquoi Marshmallow a été construit. C'est une excellente bibliothèque, et je l'ai déjà beaucoup utilisée.
-Mais elle a été créée avant que les type hints n'existent en Python. Ainsi, pour définir chaque schéma, vous devez utiliser des utilitaires et des classes spécifiques fournies par Marshmallow.
+Mais elle a été créée avant que les annotations de type n'existent en Python. Ainsi, pour définir chaque schéma, vous devez utiliser des utilitaires et des classes spécifiques fournies par Marshmallow.
-!!! check "A inspiré **FastAPI** à"
-Utilisez du code pour définir des "schémas" qui fournissent automatiquement les types de données et la validation.
+/// check | A inspiré **FastAPI** à
-### Webargs
+Utiliser du code pour définir des « schémas » qui fournissent automatiquement les types de données et la validation.
-Une autre grande fonctionnalité requise par les API est le parsing des données provenant des requêtes entrantes.
+///
+
+### [Webargs](https://webargs.readthedocs.io/en/latest/) { #webargs }
+
+Une autre grande fonctionnalité requise par les API est l’analyse des données provenant des requêtes entrantes.
Webargs est un outil qui a été créé pour fournir cela par-dessus plusieurs frameworks, dont Flask.
@@ -164,13 +180,19 @@ Il utilise Marshmallow pour effectuer la validation des données. Et il a été
C'est un outil formidable et je l'ai beaucoup utilisé aussi, avant d'avoir **FastAPI**.
-!!! info
+/// info
+
Webargs a été créé par les développeurs de Marshmallow.
-!!! check "A inspiré **FastAPI** à"
+///
+
+/// check | A inspiré **FastAPI** à
+
Disposer d'une validation automatique des données des requêtes entrantes.
-### APISpec
+///
+
+### [APISpec](https://apispec.readthedocs.io/en/stable/) { #apispec }
Marshmallow et Webargs fournissent la validation, l'analyse et la sérialisation en tant que plug-ins.
@@ -188,13 +210,19 @@ Mais alors, nous avons à nouveau le problème d'avoir une micro-syntaxe, dans u
L'éditeur ne peut guère aider en la matière. Et si nous modifions les paramètres ou les schémas Marshmallow et que nous oublions de modifier également cette docstring YAML, le schéma généré deviendrait obsolète.
-!!! info
+/// info
+
APISpec a été créé par les développeurs de Marshmallow.
-!!! check "A inspiré **FastAPI** à"
+///
+
+/// check | A inspiré **FastAPI** à
+
Supporter la norme ouverte pour les API, OpenAPI.
-### Flask-apispec
+///
+
+### [Flask-apispec](https://flask-apispec.readthedocs.io/en/latest/) { #flask-apispec }
C'est un plug-in pour Flask, qui relie Webargs, Marshmallow et APISpec.
@@ -209,99 +237,118 @@ Cette combinaison de Flask, Flask-apispec avec Marshmallow et Webargs était ma
Son utilisation a conduit à la création de plusieurs générateurs Flask full-stack. Ce sont les principales stacks que
j'ai (ainsi que plusieurs équipes externes) utilisées jusqu'à présent :
-- https://github.com/tiangolo/full-stack
-- https://github.com/tiangolo/full-stack-flask-couchbase
-- https://github.com/tiangolo/full-stack-flask-couchdb
+* [https://github.com/tiangolo/full-stack](https://github.com/tiangolo/full-stack)
+* [https://github.com/tiangolo/full-stack-flask-couchbase](https://github.com/tiangolo/full-stack-flask-couchbase)
+* [https://github.com/tiangolo/full-stack-flask-couchdb](https://github.com/tiangolo/full-stack-flask-couchdb)
-Ces mêmes générateurs full-stack ont servi de base aux [Générateurs de projets pour **FastAPI**](project-generation.md){.internal-link target=\_blank}.
+Ces mêmes générateurs full-stack ont servi de base aux [Générateurs de projets pour **FastAPI**](project-generation.md).
+
+/// info
-!!! info
Flask-apispec a été créé par les développeurs de Marshmallow.
-!!! check "A inspiré **FastAPI** à"
+///
+
+/// check | A inspiré **FastAPI** à
+
Générer le schéma OpenAPI automatiquement, à partir du même code qui définit la sérialisation et la validation.
-### NestJS (et Angular)
+///
+
+### [NestJS](https://nestjs.com/) (et [Angular](https://angular.io/)) { #nestjs-and-angular }
Ce n'est même pas du Python, NestJS est un framework JavaScript (TypeScript) NodeJS inspiré d'Angular.
Il réalise quelque chose de similaire à ce qui peut être fait avec Flask-apispec.
-Il possède un système d'injection de dépendances intégré, inspiré d'Angular 2. Il nécessite de pré-enregistrer les "injectables" (comme tous les autres systèmes d'injection de dépendances que je connais), donc, cela ajoute à la verbosité et à la répétition du code.
+Il possède un système d'injection de dépendances intégré, inspiré d'Angular 2. Il nécessite de pré-enregistrer les « injectables » (comme tous les autres systèmes d'injection de dépendances que je connais), donc, cela ajoute à la verbosité et à la répétition du code.
-Comme les paramètres sont décrits avec des types TypeScript (similaires aux type hints de Python), la prise en charge
+Comme les paramètres sont décrits avec des types TypeScript (similaires aux annotations de type de Python), la prise en charge
par l'éditeur est assez bonne.
Mais comme les données TypeScript ne sont pas préservées après la compilation en JavaScript, il ne peut pas compter sur les types pour définir la validation, la sérialisation et la documentation en même temps. En raison de cela et de certaines décisions de conception, pour obtenir la validation, la sérialisation et la génération automatique de schémas, il est nécessaire d'ajouter des décorateurs à de nombreux endroits. Cela devient donc assez verbeux.
Il ne peut pas très bien gérer les modèles imbriqués. Ainsi, si le corps JSON de la requête est un objet JSON comportant des champs internes qui sont à leur tour des objets JSON imbriqués, il ne peut pas être correctement documenté et validé.
-!!! check "A inspiré **FastAPI** à"
+/// check | A inspiré **FastAPI** à
+
Utiliser les types Python pour bénéficier d'un excellent support de l'éditeur.
- Disposer d'un puissant système d'injection de dépendances. Trouver un moyen de minimiser la répétition du code.
+Disposer d'un puissant système d'injection de dépendances. Trouver un moyen de minimiser la répétition du code.
+
+///
-### Sanic
+### [Sanic](https://sanic.readthedocs.io/en/latest/) { #sanic }
C'était l'un des premiers frameworks Python extrêmement rapides basés sur `asyncio`. Il a été conçu pour être très similaire à Flask.
-!!! note "Détails techniques"
-Il utilisait `uvloop` au lieu du système par défaut de Python `asyncio`. C'est ce qui l'a rendu si rapide.
+/// note | Détails techniques
- Il a clairement inspiré Uvicorn et Starlette, qui sont actuellement plus rapides que Sanic dans les benchmarks.
+Il utilisait [`uvloop`](https://github.com/MagicStack/uvloop) au lieu du système par défaut de Python `asyncio`. C'est ce qui l'a rendu si rapide.
-!!! check "A inspiré **FastAPI** à"
-Trouvez un moyen d'avoir une performance folle.
+Il a clairement inspiré Uvicorn et Starlette, qui sont actuellement plus rapides que Sanic dans les benchmarks.
- C'est pourquoi **FastAPI** est basé sur Starlette, car il s'agit du framework le plus rapide disponible (testé par des benchmarks tiers).
+///
-### Falcon
+/// check | A inspiré **FastAPI** à
-Falcon est un autre framework Python haute performance, il est conçu pour être minimal, et est utilisé comme fondation pour d'autres frameworks comme Hug.
+Trouver un moyen d'avoir une performance folle.
+
+C'est pourquoi **FastAPI** est basé sur Starlette, car il s'agit du framework le plus rapide disponible (testé par des benchmarks tiers).
-Il utilise le standard précédent pour les frameworks web Python (WSGI) qui est synchrone, donc il ne peut pas gérer les WebSockets et d'autres cas d'utilisation. Néanmoins, il offre de très bonnes performances.
+///
-Il est conçu pour avoir des fonctions qui reçoivent deux paramètres, une "requête" et une "réponse". Ensuite, vous
-"lisez" des parties de la requête et "écrivez" des parties dans la réponse. En raison de cette conception, il n'est
+### [Falcon](https://falconframework.org/) { #falcon }
+
+Falcon est un autre framework Python haute performance, il est conçu pour être minimal, et est utilisé comme fondation pour d'autres frameworks comme Hug.
+
+Il est conçu pour avoir des fonctions qui reçoivent deux paramètres, une « requête » et une « réponse ». Ensuite, vous
+« lisez » des parties de la requête et « écrivez » des parties dans la réponse. En raison de cette conception, il n'est
pas possible de déclarer des paramètres de requête et des corps avec des indications de type Python standard comme paramètres de fonction.
Ainsi, la validation, la sérialisation et la documentation des données doivent être effectuées dans le code, et non pas automatiquement. Ou bien elles doivent être implémentées comme un framework au-dessus de Falcon, comme Hug. Cette même distinction se retrouve dans d'autres frameworks qui s'inspirent de la conception de Falcon, qui consiste à avoir un objet de requête et un objet de réponse comme paramètres.
-!!! check "A inspiré **FastAPI** à"
+/// check | A inspiré **FastAPI** à
+
Trouver des moyens d'obtenir de bonnes performances.
- Avec Hug (puisque Hug est basé sur Falcon), **FastAPI** a inspiré la déclaration d'un paramètre `response` dans les fonctions.
+Avec Hug (puisque Hug est basé sur Falcon), cela a inspiré **FastAPI** à déclarer un paramètre `response` dans les fonctions.
+
+Bien que dans FastAPI, il est facultatif, et est utilisé principalement pour définir les en-têtes, les cookies, et les codes de statut alternatifs.
- Bien que dans FastAPI, il est facultatif, et est utilisé principalement pour définir les en-têtes, les cookies, et les codes de statut alternatifs.
+///
-### Molten
+### [Molten](https://moltenframework.com/) { #molten }
J'ai découvert Molten lors des premières étapes de développement de **FastAPI**. Et il a des idées assez similaires :
-- Basé sur les type hints Python.
-- Validation et documentation via ces types.
-- Système d'injection de dépendances.
+* Basé sur les annotations de type Python.
+* Validation et documentation via ces types.
+* Système d'injection de dépendances.
Il n'utilise pas une librairie tiers de validation, sérialisation et de documentation tel que Pydantic, il utilise son propre système. Ainsi, ces définitions de types de données ne sont pas réutilisables aussi facilement.
-Il nécessite une configuration un peu plus verbeuse. Et comme il est basé sur WSGI (au lieu dASGI), il n'est pas
+Il nécessite une configuration un peu plus verbeuse. Et comme il est basé sur WSGI (au lieu d'ASGI), il n'est pas
conçu pour profiter des hautes performances fournies par des outils comme Uvicorn, Starlette et Sanic.
-Le système d'injection de dépendances exige le pré-enregistrement des dépendances et les dépendances sont résolues sur la base des types déclarés. Ainsi, il n'est pas possible de déclarer plus d'un "composant" qui fournit un certain type.
+Le système d'injection de dépendances exige le pré-enregistrement des dépendances et les dépendances sont résolues sur la base des types déclarés. Ainsi, il n'est pas possible de déclarer plus d'un « composant » qui fournit un certain type.
Les routes sont déclarées à un seul endroit, en utilisant des fonctions déclarées à d'autres endroits (au lieu
d'utiliser des décorateurs qui peuvent être placés juste au-dessus de la fonction qui gère l'endpoint). Cette
méthode est plus proche de celle de Django que de celle de Flask (et Starlette). Il sépare dans le code des choses
qui sont relativement fortement couplées.
-!!! check "A inspiré **FastAPI** à"
-Définir des validations supplémentaires pour les types de données utilisant la valeur "par défaut" des attributs du modèle. Ceci améliore le support de l'éditeur, et n'était pas disponible dans Pydantic auparavant.
+/// check | A inspiré **FastAPI** à
- Cela a en fait inspiré la mise à jour de certaines parties de Pydantic, afin de supporter le même style de déclaration de validation (toute cette fonctionnalité est maintenant déjà disponible dans Pydantic).
+Définir des validations supplémentaires pour les types de données utilisant la valeur « par défaut » des attributs du modèle. Ceci améliore le support de l'éditeur, et n'était pas disponible dans Pydantic auparavant.
-### Hug
+Cela a en fait inspiré la mise à jour de certaines parties de Pydantic, afin de supporter le même style de déclaration de validation (toute cette fonctionnalité est maintenant déjà disponible dans Pydantic).
-Hug a été l'un des premiers frameworks à implémenter la déclaration des types de paramètres d'API en utilisant les type hints Python. C'était une excellente idée qui a inspiré d'autres outils à faire de même.
+///
+
+### [Hug](https://github.com/hugapi/hug) { #hug }
+
+Hug a été l'un des premiers frameworks à implémenter la déclaration des types de paramètres d'API en utilisant les annotations de type Python. C'était une excellente idée qui a inspiré d'autres outils à faire de même.
Il utilisait des types personnalisés dans ses déclarations au lieu des types Python standard, mais c'était tout de même un énorme pas en avant.
@@ -314,28 +361,34 @@ API et des CLI.
Comme il est basé sur l'ancienne norme pour les frameworks web Python synchrones (WSGI), il ne peut pas gérer les Websockets et autres, bien qu'il soit également très performant.
-!!! info
-Hug a été créé par Timothy Crosley, le créateur de `isort`, un excellent outil pour trier automatiquement les imports dans les fichiers Python.
+/// info
+
+Hug a été créé par Timothy Crosley, le créateur de [`isort`](https://github.com/timothycrosley/isort), un excellent outil pour trier automatiquement les imports dans les fichiers Python.
+
+///
+
+/// check | Idées ayant inspiré **FastAPI**
-!!! check "A inspiré **FastAPI** à"
Hug a inspiré certaines parties d'APIStar, et était l'un des outils que je trouvais les plus prometteurs, à côté d'APIStar.
- Hug a contribué à inspirer **FastAPI** pour utiliser les type hints Python
- pour déclarer les paramètres, et pour générer automatiquement un schéma définissant l'API.
+Hug a contribué à inspirer **FastAPI** pour utiliser les annotations de type Python
+pour déclarer les paramètres, et pour générer automatiquement un schéma définissant l'API.
+
+Hug a inspiré **FastAPI** pour déclarer un paramètre `response` dans les fonctions pour définir les en-têtes et les cookies.
- Hug a inspiré **FastAPI** pour déclarer un paramètre `response` dans les fonctions pour définir les en-têtes et les cookies.
+///
-### APIStar (<= 0.5)
+### [APIStar](https://github.com/encode/apistar) (<= 0.5) { #apistar-0-5 }
Juste avant de décider de développer **FastAPI**, j'ai trouvé le serveur **APIStar**. Il contenait presque tout ce
que je recherchais et avait un beau design.
-C'était l'une des premières implémentations d'un framework utilisant les type hints Python pour déclarer les paramètres
+C'était l'une des premières implémentations d'un framework utilisant les annotations de type Python pour déclarer les paramètres
et les requêtes que j'ai vues (avant NestJS et Molten). Je l'ai trouvé plus ou moins en même temps que Hug. Mais APIStar utilisait le standard OpenAPI.
-Il disposait de la validation automatique, sérialisation des données et d'une génération de schéma OpenAPI basée sur les mêmes type hints à plusieurs endroits.
+Il disposait de la validation automatique, sérialisation des données et d'une génération de schéma OpenAPI basée sur les mêmes annotations de type à plusieurs endroits.
-La définition du schéma de corps de requête n'utilisait pas les mêmes type hints Python que Pydantic, il était un peu plus proche de Marshmallow, donc le support de l'éditeur n'était pas aussi bon, mais APIStar était quand même la meilleure option disponible.
+La définition du schéma de corps de requête n'utilisait pas les mêmes annotations de type Python que Pydantic, il était un peu plus proche de Marshmallow, donc le support de l'éditeur n'était pas aussi bon, mais APIStar était quand même la meilleure option disponible.
Il avait les meilleures performances d'après les benchmarks de l'époque (seulement surpassé par Starlette).
@@ -351,43 +404,52 @@ Il ne s'agissait plus d'un framework web API, le créateur devant se concentrer
Maintenant, APIStar est un ensemble d'outils pour valider les spécifications OpenAPI, et non un framework web.
-!!! info
+/// info
+
APIStar a été créé par Tom Christie. Le même gars qui a créé :
- * Django REST Framework
- * Starlette (sur lequel **FastAPI** est basé)
- * Uvicorn (utilisé par Starlette et **FastAPI**)
+* Django REST Framework
+* Starlette (sur lequel **FastAPI** est basé)
+* Uvicorn (utilisé par Starlette et **FastAPI**)
+
+///
+
+/// check | A inspiré **FastAPI** à
-!!! check "A inspiré **FastAPI** à"
Exister.
- L'idée de déclarer plusieurs choses (validation des données, sérialisation et documentation) avec les mêmes types Python, tout en offrant un excellent support pour les éditeurs, était pour moi une idée brillante.
+L'idée de déclarer plusieurs choses (validation des données, sérialisation et documentation) avec les mêmes types Python, tout en offrant un excellent support pour les éditeurs, était pour moi une idée brillante.
- Et après avoir longtemps cherché un framework similaire et testé de nombreuses alternatives, APIStar était la meilleure option disponible.
+Et après avoir longtemps cherché un framework similaire et testé de nombreuses alternatives, APIStar était la meilleure option disponible.
- Puis APIStar a cessé d'exister en tant que serveur et Starlette a été créé, et a constitué une meilleure base pour un tel système. Ce fut l'inspiration finale pour construire **FastAPI**.
+Puis APIStar a cessé d'exister en tant que serveur et Starlette a été créé, et a constitué une meilleure base pour un tel système. Ce fut l'inspiration finale pour construire **FastAPI**.
- Je considère **FastAPI** comme un "successeur spirituel" d'APIStar, tout en améliorant et en augmentant les fonctionnalités, le système de typage et d'autres parties, sur la base des enseignements tirés de tous ces outils précédents.
+Je considère **FastAPI** comme un « successeur spirituel » d'APIStar, tout en améliorant et en augmentant les fonctionnalités, le système de typage et d'autres parties, sur la base des enseignements tirés de tous ces outils précédents.
-## Utilisés par **FastAPI**
+///
-### Pydantic
+## Utilisés par **FastAPI** { #used-by-fastapi }
-Pydantic est une bibliothèque permettant de définir la validation, la sérialisation et la documentation des données (à l'aide de JSON Schema) en se basant sur les Python type hints.
+### [Pydantic](https://docs.pydantic.dev/) { #pydantic }
+
+Pydantic est une bibliothèque permettant de définir la validation, la sérialisation et la documentation des données (à l'aide de JSON Schema) en se basant sur les annotations de type Python.
Cela le rend extrêmement intuitif.
Il est comparable à Marshmallow. Bien qu'il soit plus rapide que Marshmallow dans les benchmarks. Et comme il est
-basé sur les mêmes type hints Python, le support de l'éditeur est grand.
+basé sur les mêmes annotations de type Python, le support de l'éditeur est grand.
+
+/// check | **FastAPI** l'utilise pour
-!!! check "**FastAPI** l'utilise pour"
Gérer toute la validation des données, leur sérialisation et la documentation automatique du modèle (basée sur le schéma JSON).
- **FastAPI** prend ensuite ces données JSON Schema et les place dans OpenAPI, en plus de toutes les autres choses qu'il fait.
+**FastAPI** prend ensuite ces données JSON Schema et les place dans OpenAPI, en plus de toutes les autres choses qu'il fait.
+
+///
-### Starlette
+### [Starlette](https://www.starlette.dev/) { #starlette }
-Starlette est un framework/toolkit léger ASGI, qui est idéal pour construire des services asyncio performants.
+Starlette est un framework/toolkit léger ASGI, qui est idéal pour construire des services asyncio performants.
Il est très simple et intuitif. Il est conçu pour être facilement extensible et avoir des composants modulaires.
@@ -395,37 +457,42 @@ Il offre :
- Des performances vraiment impressionnantes.
- Le support des WebSockets.
-- Le support de GraphQL.
- Les tâches d'arrière-plan.
- Les événements de démarrage et d'arrêt.
-- Un client de test basé sur request.
+- Un client de test basé sur HTTPX.
- CORS, GZip, fichiers statiques, streaming des réponses.
- Le support des sessions et des cookies.
- Une couverture de test à 100 %.
- 100 % de la base de code avec des annotations de type.
-- Zéro forte dépendance à d'autres packages.
+- Peu de dépendances strictes.
Starlette est actuellement le framework Python le plus rapide testé. Seulement dépassé par Uvicorn, qui n'est pas un framework, mais un serveur.
-Starlette fournit toutes les fonctionnalités de base d'un micro-framework web.
+Starlette fournit toutes les fonctionnalités de base d'un micro‑framework web.
Mais il ne fournit pas de validation automatique des données, de sérialisation ou de documentation.
-C'est l'une des principales choses que **FastAPI** ajoute par-dessus, le tout basé sur les type hints Python (en utilisant Pydantic). Cela, plus le système d'injection de dépendances, les utilitaires de sécurité, la génération de schémas OpenAPI, etc.
+C'est l'une des principales choses que **FastAPI** ajoute par-dessus, le tout basé sur les annotations de type Python (en utilisant Pydantic). Cela, plus le système d'injection de dépendances, les utilitaires de sécurité, la génération de schémas OpenAPI, etc.
-!!! note "Détails techniques"
-ASGI est une nouvelle "norme" développée par les membres de l'équipe principale de Django. Il ne s'agit pas encore d'une "norme Python" (un PEP), bien qu'ils soient en train de le faire.
+/// note | Détails techniques
- Néanmoins, il est déjà utilisé comme "standard" par plusieurs outils. Cela améliore grandement l'interopérabilité, puisque vous pouvez remplacer Uvicorn par n'importe quel autre serveur ASGI (comme Daphne ou Hypercorn), ou vous pouvez ajouter des outils compatibles ASGI, comme `python-socketio`.
+ASGI est une nouvelle « norme » développée par les membres de l'équipe principale de Django. Il ne s'agit pas encore d'une « norme Python » (un PEP), bien qu'ils soient en train de le faire.
+
+Néanmoins, il est déjà utilisé comme « standard » par plusieurs outils. Cela améliore grandement l'interopérabilité, puisque vous pouvez remplacer Uvicorn par n'importe quel autre serveur ASGI (comme Daphne ou Hypercorn), ou vous pouvez ajouter des outils compatibles ASGI, comme `python-socketio`.
+
+///
+
+/// check | **FastAPI** l'utilise pour
-!!! check "**FastAPI** l'utilise pour"
Gérer toutes les parties web de base. Ajouter des fonctionnalités par-dessus.
- La classe `FastAPI` elle-même hérite directement de la classe `Starlette`.
+La classe `FastAPI` elle-même hérite directement de la classe `Starlette`.
- Ainsi, tout ce que vous pouvez faire avec Starlette, vous pouvez le faire directement avec **FastAPI**, car il s'agit en fait de Starlette sous stéroïdes.
+Ainsi, tout ce que vous pouvez faire avec Starlette, vous pouvez le faire directement avec **FastAPI**, car il s'agit en fait de Starlette sous stéroïdes.
-### Uvicorn
+///
+
+### [Uvicorn](https://www.uvicorn.dev/) { #uvicorn }
Uvicorn est un serveur ASGI rapide comme l'éclair, basé sur uvloop et httptools.
@@ -434,13 +501,16 @@ quelque chose qu'un framework comme Starlette (ou **FastAPI**) fournirait par-de
C'est le serveur recommandé pour Starlette et **FastAPI**.
-!!! check "**FastAPI** le recommande comme"
+/// check | **FastAPI** le recommande comme
+
Le serveur web principal pour exécuter les applications **FastAPI**.
- Vous pouvez le combiner avec Gunicorn, pour avoir un serveur multi-processus asynchrone.
+Vous pouvez également utiliser l'option de ligne de commande `--workers` pour avoir un serveur multi‑processus asynchrone.
+
+Pour plus de détails, consultez la section [Déploiement](deployment/index.md).
- Pour plus de détails, consultez la section [Déploiement](deployment/index.md){.internal-link target=_blank}.
+///
-## Benchmarks et vitesse
+## Benchmarks et vitesse { #benchmarks-and-speed }
-Pour comprendre, comparer et voir la différence entre Uvicorn, Starlette et FastAPI, consultez la section sur les [Benchmarks](benchmarks.md){.internal-link target=\_blank}.
+Pour comprendre, comparer et voir la différence entre Uvicorn, Starlette et FastAPI, consultez la section sur les [Benchmarks](benchmarks.md).
diff --git a/docs/fr/docs/async.md b/docs/fr/docs/async.md
index af4d6ca060e58..f2afba9c6d7e7 100644
--- a/docs/fr/docs/async.md
+++ b/docs/fr/docs/async.md
@@ -1,17 +1,18 @@
-# Concurrence et les mots-clés async et await
+# Concurrence et async / await { #concurrency-and-async-await }
-Cette page vise à fournir des détails sur la syntaxe `async def` pour les *fonctions de chemins* et quelques rappels sur le code asynchrone, la concurrence et le parallélisme.
+Détails sur la syntaxe `async def` pour les *fonctions de chemin d'accès* et quelques rappels sur le code asynchrone, la concurrence et le parallélisme.
-## Vous êtes pressés ?
+## Vous êtes pressés ? { #in-a-hurry }
-TL;DR :
+TL;DR :
Si vous utilisez des bibliothèques tierces qui nécessitent d'être appelées avec `await`, telles que :
```Python
results = await some_library()
```
-Alors, déclarez vos *fonctions de chemins* avec `async def` comme ceci :
+
+Alors, déclarez vos *fonctions de chemin d'accès* avec `async def` comme ceci :
```Python hl_lines="2"
@app.get('/')
@@ -20,12 +21,15 @@ async def read_results():
return results
```
-!!! note
- Vous pouvez uniquement utiliser `await` dans les fonctions créées avec `async def`.
+/// note | Remarque
+
+Vous pouvez uniquement utiliser `await` dans les fonctions créées avec `async def`.
+
+///
---
-Si vous utilisez une bibliothèque externe qui communique avec quelque chose (une BDD, une API, un système de fichiers, etc.) et qui ne supporte pas l'utilisation d'`await` (ce qui est actuellement le cas pour la majorité des bibliothèques de BDD), alors déclarez vos *fonctions de chemin* normalement, avec le classique `def`, comme ceci :
+Si vous utilisez une bibliothèque externe qui communique avec quelque chose (une base de données, une API, le système de fichiers, etc.) et qui ne supporte pas l'utilisation d'`await` (ce qui est actuellement le cas pour la majorité des bibliothèques de base de données), alors déclarez vos *fonctions de chemin d'accès* normalement, avec le classique `def`, comme ceci :
```Python hl_lines="2"
@app.get('/')
@@ -36,23 +40,23 @@ def results():
---
-Si votre application n'a pas à communiquer avec une bibliothèque externe et pas à attendre de réponse, utilisez `async def`.
+Si votre application (d'une certaine manière) n'a pas à communiquer avec une autre chose et à attendre sa réponse, utilisez `async def`, même si vous n'avez pas besoin d'utiliser `await` à l'intérieur.
---
-Si vous ne savez pas, utilisez seulement `def` comme vous le feriez habituellement.
+Si vous ne savez pas, utilisez seulement `def`.
---
-**Note** : vous pouvez mélanger `def` et `async def` dans vos *fonctions de chemin* autant que nécessaire, **FastAPI** saura faire ce qu'il faut avec.
+Note : vous pouvez mélanger `def` et `async def` dans vos *fonctions de chemin d'accès* autant que nécessaire, et définir chacune avec l’option la plus adaptée pour vous. FastAPI fera ce qu'il faut avec elles.
-Au final, peu importe le cas parmi ceux ci-dessus, **FastAPI** fonctionnera de manière asynchrone et sera extrêmement rapide.
+Au final, peu importe le cas parmi ceux ci-dessus, FastAPI fonctionnera de manière asynchrone et sera extrêmement rapide.
-Mais si vous suivez bien les instructions ci-dessus, alors **FastAPI** pourra effectuer quelques optimisations et ainsi améliorer les performances.
+Mais si vous suivez bien les instructions ci-dessus, il pourra effectuer quelques optimisations et ainsi améliorer les performances.
-## Détails techniques
+## Détails techniques { #technical-details }
-Les versions modernes de Python supportent le **code asynchrone** grâce aux **"coroutines"** avec les syntaxes **`async` et `await`**.
+Les versions modernes de Python supportent le **code asynchrone** grâce aux **« coroutines »** avec les syntaxes **`async` et `await`**.
Analysons les différentes parties de cette phrase dans les sections suivantes :
@@ -60,88 +64,108 @@ Analysons les différentes parties de cette phrase dans les sections suivantes :
* **`async` et `await`**
* **Coroutines**
-## Code asynchrone
+## Code asynchrone { #asynchronous-code }
-Faire du code asynchrone signifie que le langage 💬 est capable de dire à l'ordinateur / au programme 🤖 qu'à un moment du code, il 🤖 devra attendre que *quelque chose d'autre* se termine autre part. Disons que ce *quelque chose d'autre* est appelé "fichier-lent" 📝.
+Faire du code asynchrone signifie que le langage 💬 est capable de dire à l'ordinateur / au programme 🤖 qu'à un moment du code, il 🤖 devra attendre que *quelque chose d'autre* se termine autre part. Disons que ce *quelque chose d'autre* est appelé « slow-file » 📝.
-Donc, pendant ce temps, l'ordinateur pourra effectuer d'autres tâches, pendant que "fichier-lent" 📝 se termine.
+Donc, pendant ce temps, l'ordinateur pourra effectuer d'autres tâches, pendant que « slow-file » 📝 se termine.
Ensuite l'ordinateur / le programme 🤖 reviendra à chaque fois qu'il en a la chance que ce soit parce qu'il attend à nouveau, ou car il 🤖 a fini tout le travail qu'il avait à faire. Il 🤖 regardera donc si les tâches qu'il attend ont terminé d'être effectuées.
-Ensuite, il 🤖 prendra la première tâche à finir (disons, notre "fichier-lent" 📝) et continuera à faire avec cette dernière ce qu'il était censé.
+Ensuite, il 🤖 prendra la première tâche à finir (disons, notre « slow-file » 📝) et continuera à faire avec cette dernière ce qu'il était censé.
-Ce "attendre quelque chose d'autre" fait généralement référence à des opérations I/O qui sont relativement "lentes" (comparées à la vitesse du processeur et de la mémoire RAM) telles qu'attendre que :
+Ce « attendre quelque chose d'autre » fait généralement référence à des opérations I/O qui sont relativement « lentes » (comparées à la vitesse du processeur et de la mémoire RAM) telles qu'attendre que :
* de la donnée soit envoyée par le client à travers le réseau
* de la donnée envoyée depuis votre programme soit reçue par le client à travers le réseau
* le contenu d'un fichier sur le disque soit lu par le système et passé à votre programme
* le contenu que votre programme a passé au système soit écrit sur le disque
* une opération effectuée à distance par une API se termine
-* une opération en BDD se termine
-* une requête à une BDD renvoie un résultat
+* une opération en base de données se termine
+* une requête à une base de données renvoie un résultat
* etc.
-Le temps d'exécution étant consommé majoritairement par l'attente d'opérations I/O on appelle ceci des opérations "I/O bound".
+Le temps d'exécution étant consommé majoritairement par l'attente d'opérations I/O, on appelle ceci des opérations « I/O bound ».
-Ce concept se nomme l'"asynchronisme" car l'ordinateur / le programme n'a pas besoin d'être "synchronisé" avec la tâche, attendant le moment exact où cette dernière se terminera en ne faisant rien, pour être capable de récupérer le résultat de la tâche et l'utiliser dans la suite des opérations.
+Ce concept se nomme « asynchrone » car l'ordinateur / le programme n'a pas besoin d'être « synchronisé » avec la tâche, attendant le moment exact où cette dernière se terminera en ne faisant rien, pour être capable de récupérer le résultat de la tâche et l'utiliser dans la suite des opérations.
-À la place, en étant "asynchrone", une fois terminée, une tâche peut légèrement attendre (quelques microsecondes) que l'ordinateur / le programme finisse ce qu'il était en train de faire, et revienne récupérer le résultat.
+À la place, en étant « asynchrone », une fois terminée, une tâche peut légèrement attendre (quelques microsecondes) que l'ordinateur / le programme finisse ce qu'il était en train de faire, et revienne récupérer le résultat.
-Pour parler de tâches "synchrones" (en opposition à "asynchrones"), on utilise souvent le terme "séquentiel", car l'ordinateur / le programme va effectuer toutes les étapes d'une tâche séquentiellement avant de passer à une autre tâche, même si ces étapes impliquent de l'attente.
+Pour parler de tâches « synchrones » (en opposition à « asynchrones »), on utilise souvent le terme « séquentiel », car l'ordinateur / le programme va effectuer toutes les étapes d'une tâche séquentiellement avant de passer à une autre tâche, même si ces étapes impliquent de l'attente.
-### Concurrence et Burgers
+### Concurrence et Burgers { #concurrency-and-burgers }
-L'idée de code **asynchrone** décrite ci-dessus est parfois aussi appelée **"concurrence"**. Ce qui est différent du **"parallélisme"**.
+L'idée de code **asynchrone** décrite ci-dessus est parfois aussi appelée **« concurrence »**. Ce qui est différent du **« parallélisme »**.
-La **concurrence** et le **parallélisme** sont tous deux liés à l'idée de "différentes choses arrivant plus ou moins au même moment".
+La **concurrence** et le **parallélisme** sont tous deux liés à l'idée de « différentes choses arrivant plus ou moins au même moment ».
Mais les détails entre la **concurrence** et le **parallélisme** diffèrent sur de nombreux points.
Pour expliquer la différence, voici une histoire de burgers :
-#### Burgers concurrents
+### Burgers concurrents { #concurrent-burgers }
Vous amenez votre crush 😍 dans votre fast food 🍔 favori, et faites la queue pendant que le serveur 💁 prend les commandes des personnes devant vous.
+
+
Puis vient votre tour, vous commandez alors 2 magnifiques burgers 🍔 pour votre crush 😍 et vous.
-Vous payez 💸.
+
Le serveur 💁 dit quelque chose à son collègue dans la cuisine 👨🍳 pour qu'il sache qu'il doit préparer vos burgers 🍔 (bien qu'il soit déjà en train de préparer ceux des clients précédents).
+
+
+Vous payez 💸.
+
Le serveur 💁 vous donne le numéro assigné à votre commande.
-Pendant que vous attendez, vous allez choisir une table avec votre crush 😍, vous discutez avec votre crush 😍 pendant un long moment (les burgers étant "magnifiques" ils sont très longs à préparer ✨🍔✨).
+
+
+Pendant que vous attendez, vous allez choisir une table avec votre crush 😍, vous discutez avec votre crush 😍 pendant un long moment (les burgers étant « magnifiques » ils sont très longs à préparer ✨🍔✨).
Pendant que vous êtes assis à table, en attendant que les burgers 🍔 soient prêts, vous pouvez passer ce temps à admirer à quel point votre crush 😍 est géniale, mignonne et intelligente ✨😍✨.
-Pendant que vous discutez avec votre crush 😍, de temps en temps vous jetez un coup d'oeil au nombre affiché au-dessus du comptoir pour savoir si c'est à votre tour d'être servis.
+
+
+Pendant que vous discutez avec votre crush 😍, de temps en temps vous jetez un coup d’œil au nombre affiché au-dessus du comptoir pour savoir si c'est à votre tour d'être servis.
Jusqu'au moment où c'est (enfin) votre tour. Vous allez au comptoir, récupérez vos burgers 🍔 et revenez à votre table.
+
+
Vous et votre crush 😍 mangez les burgers 🍔 et passez un bon moment ✨.
+
+
+/// info
+
+Illustrations proposées par [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨
+
+///
+
---
Imaginez que vous êtes l'ordinateur / le programme 🤖 dans cette histoire.
-Pendant que vous faites la queue, vous être simplement inactif 😴, attendant votre tour, ne faisant rien de "productif". Mais la queue est rapide car le serveur 💁 prend seulement les commandes (et ne les prépare pas), donc tout va bien.
+Pendant que vous faites la queue, vous être simplement inactif 😴, attendant votre tour, ne faisant rien de « productif ». Mais la queue est rapide car le serveur 💁 prend seulement les commandes (et ne les prépare pas), donc tout va bien.
-Ensuite, quand c'est votre tour, vous faites des actions "productives" 🤓, vous étudiez le menu, décidez ce que vous voulez, demandez à votre crush 😍 son choix, payez 💸, vérifiez que vous utilisez la bonne carte de crédit, vérifiez que le montant débité sur la carte est correct, vérifiez que la commande contient les bons produits, etc.
+Ensuite, quand c'est votre tour, vous faites des actions « productives » 🤓, vous étudiez le menu, décidez ce que vous voulez, demandez à votre crush 😍 son choix, payez 💸, vérifiez que vous utilisez la bonne carte de crédit, vérifiez que le montant débité sur la carte est correct, vérifiez que la commande contient les bons produits, etc.
-Mais ensuite, même si vous n'avez pas encore vos burgers 🍔, votre travail avec le serveur 💁 est "en pause" ⏸, car vous devez attendre 🕙 que vos burgers soient prêts.
+Mais ensuite, même si vous n'avez pas encore vos burgers 🍔, votre travail avec le serveur 💁 est « en pause » ⏸, car vous devez attendre 🕙 que vos burgers soient prêts.
-Après vous être écarté du comptoir et vous être assis à votre table avec le numéro de votre commande, vous pouvez tourner 🔀 votre attention vers votre crush 😍, et "travailler" ⏯ 🤓 là-dessus. Vous êtes donc à nouveau en train de faire quelque chose de "productif" 🤓, vous flirtez avec votre crush 😍.
+Après vous être écarté du comptoir et vous être assis à votre table avec le numéro de votre commande, vous pouvez tourner 🔀 votre attention vers votre crush 😍, et « travailler » ⏯ 🤓 là-dessus. Vous êtes donc à nouveau en train de faire quelque chose de « productif » 🤓, vous flirtez avec votre crush 😍.
-Puis le serveur 💁 dit "J'ai fini de préparer les burgers" 🍔 en mettant votre numéro sur l'affichage du comptoir, mais vous ne courrez pas immédiatement au moment où votre numéro s'affiche. Vous savez que personne ne volera vos burgers 🍔 car vous avez votre numéro et les autres clients ont le leur.
+Puis le serveur 💁 dit « J'ai fini de préparer les burgers » 🍔 en mettant votre numéro sur l'affichage du comptoir, mais vous ne courez pas immédiatement au moment où votre numéro s'affiche. Vous savez que personne ne volera vos burgers 🍔 car vous avez votre numéro et les autres clients ont le leur.
Vous attendez donc que votre crush 😍 finisse son histoire, souriez gentiment et dites que vous allez chercher les burgers ⏸.
-Pour finir vous allez au comptoir 🔀, vers la tâche initiale qui est désormais terminée ⏯, récupérez les burgers 🍔, remerciez le serveur et ramenez les burgers 🍔 à votre table. Ceci termine l'étape / la tâche d'interaction avec le comptoir ⏹. Ce qui ensuite, crée une nouvelle tâche de "manger les burgers" 🔀 ⏯, mais la précédente, "récupérer les burgers" est terminée ⏹.
+Pour finir vous allez au comptoir 🔀, vers la tâche initiale qui est désormais terminée ⏯, récupérez les burgers 🍔, remerciez le serveur et ramenez les burgers 🍔 à votre table. Ceci termine l'étape / la tâche d'interaction avec le comptoir ⏹. Ce qui ensuite, crée une nouvelle tâche de « manger les burgers » 🔀 ⏯, mais la précédente, « récupérer les burgers » est terminée ⏹.
-#### Burgers parallèles
+### Burgers parallèles { #parallel-burgers }
-Imaginons désormais que ce ne sont pas des "burgers concurrents" mais des "burgers parallèles".
+Imaginons désormais que ce ne sont pas des « burgers concurrents » mais des « burgers parallèles ».
Vous allez avec votre crush 😍 dans un fast food 🍔 parallélisé.
@@ -149,29 +173,47 @@ Vous attendez pendant que plusieurs (disons 8) serveurs qui sont aussi des cuisi
Chaque personne devant vous attend 🕙 que son burger 🍔 soit prêt avant de quitter le comptoir car chacun des 8 serveurs va lui-même préparer le burger directement avant de prendre la commande suivante.
+
+
Puis c'est enfin votre tour, vous commandez 2 magnifiques burgers 🍔 pour vous et votre crush 😍.
Vous payez 💸.
+
+
Le serveur va dans la cuisine 👨🍳.
Vous attendez devant le comptoir afin que personne ne prenne vos burgers 🍔 avant vous, vu qu'il n'y a pas de numéro de commande.
+
+
Vous et votre crush 😍 étant occupés à vérifier que personne ne passe devant vous prendre vos burgers au moment où ils arriveront 🕙, vous ne pouvez pas vous préoccuper de votre crush 😞.
-C'est du travail "synchrone", vous être "synchronisés" avec le serveur/cuisinier 👨🍳. Vous devez attendre 🕙 et être présent au moment exact où le serveur/cuisinier 👨🍳 finira les burgers 🍔 et vous les donnera, sinon quelqu'un risque de vous les prendre.
+C'est du travail « synchrone », vous être « synchronisés » avec le serveur/cuisinier 👨🍳. Vous devez attendre 🕙 et être présent au moment exact où le serveur/cuisinier 👨🍳 finira les burgers 🍔 et vous les donnera, sinon quelqu'un risque de vous les prendre.
+
+
Puis le serveur/cuisinier 👨🍳 revient enfin avec vos burgers 🍔, après un long moment d'attente 🕙 devant le comptoir.
+
+
Vous prenez vos burgers 🍔 et allez à une table avec votre crush 😍
Vous les mangez, et vous avez terminé 🍔 ⏹.
+
+
Durant tout ce processus, il n'y a presque pas eu de discussions ou de flirts car la plupart de votre temps à été passé à attendre 🕙 devant le comptoir 😞.
+/// info
+
+Illustrations proposées par [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨
+
+///
+
---
-Dans ce scénario de burgers parallèles, vous êtes un ordinateur / programme 🤖 avec deux processeurs (vous et votre crush 😍) attendant 🕙 à deux et dédiant votre attention 🕙 à "attendre devant le comptoir" pour une longue durée.
+Dans ce scénario de burgers parallèles, vous êtes un ordinateur / programme 🤖 avec deux processeurs (vous et votre crush 😍) attendant 🕙 à deux et dédiant votre attention ⏯ à « attendre devant le comptoir » 🕙 pour une longue durée.
Le fast-food a 8 processeurs (serveurs/cuisiniers) 👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳. Alors que le fast-food de burgers concurrents en avait 2 (un serveur et un cuisinier).
@@ -181,7 +223,7 @@ Et pourtant l'expérience finale n'est pas meilleure 😞.
C'est donc l'histoire équivalente parallèle pour les burgers 🍔.
-Pour un exemple plus courant dans la "vie réelle", imaginez une banque.
+Pour un exemple plus courant dans la « vie réelle », imaginez une banque.
Jusqu'à récemment, la plupart des banques avaient plusieurs caisses (et banquiers) 👨💼👨💼👨💼👨💼 et une unique file d'attente 🕙🕙🕙🕙🕙🕙🕙🕙.
@@ -191,9 +233,9 @@ Et vous deviez attendre 🕙 dans la file pendant un long moment ou vous perdiez
Vous n'auriez donc probablement pas envie d'amener votre crush 😍 avec vous à la banque 🏦.
-#### Conclusion
+### Conclusion sur les burgers { #burger-conclusion }
-Dans ce scénario des "burgers du fast-food avec votre crush", comme il y a beaucoup d'attente 🕙, il est très logique d'avoir un système concurrent ⏸🔀⏯.
+Dans ce scénario des « burgers du fast-food avec votre crush », comme il y a beaucoup d'attente 🕙, il est très logique d'avoir un système concurrent ⏸🔀⏯.
Et c'est le cas pour la plupart des applications web.
@@ -201,17 +243,17 @@ Vous aurez de nombreux, nombreux utilisateurs, mais votre serveur attendra 🕙
Puis vous attendrez 🕙 de nouveau que leurs réponses reviennent.
-Cette "attente" 🕙 se mesure en microsecondes, mais tout de même, en cumulé cela fait beaucoup d'attente.
+Cette « attente » 🕙 se mesure en microsecondes, mais tout de même, en cumulé cela fait beaucoup d'attente.
C'est pourquoi il est logique d'utiliser du code asynchrone ⏸🔀⏯ pour des APIs web.
-Ce type d'asynchronicité est ce qui a rendu NodeJS populaire (bien que NodeJS ne soit pas parallèle) et c'est la force du Go en tant que langage de programmation.
+Ce type d'asynchronicité est ce qui a rendu NodeJS populaire (bien que NodeJS ne soit pas parallèle) et c'est la force de Go en tant que langage de programmation.
Et c'est le même niveau de performance que celui obtenu avec **FastAPI**.
-Et comme on peut avoir du parallélisme et de l'asynchronicité en même temps, on obtient des performances plus hautes que la plupart des frameworks NodeJS et égales à celles du Go, qui est un langage compilé plus proche du C (tout ça grâce à Starlette).
+Et comme on peut avoir du parallélisme et de l'asynchronicité en même temps, on obtient des performances plus hautes que la plupart des frameworks NodeJS testés et égales à celles du Go, qui est un langage compilé plus proche du C [(tout ça grâce à Starlette)](https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=query&l=zijmkf-1).
-### Est-ce que la concurrence est mieux que le parallélisme ?
+### Est-ce que la concurrence est mieux que le parallélisme ? { #is-concurrency-better-than-parallelism }
Nope ! C'est ça la morale de l'histoire.
@@ -235,11 +277,11 @@ Mais dans ce cas, si pouviez amener 8 ex-serveurs/cuisiniers/devenus-nettoyeurs
Dans ce scénario, chacun des nettoyeurs (vous y compris) serait un processeur, faisant sa partie du travail.
-Et comme la plupart du temps d'exécution est pris par du "vrai" travail (et non de l'attente), et que le travail dans un ordinateur est fait par un CPU, ce sont des problèmes dits "CPU bound".
+Et comme la plupart du temps d'exécution est pris par du « vrai » travail (et non de l'attente), et que le travail dans un ordinateur est fait par un CPU, ce sont des problèmes dits « CPU bound ».
---
-Des exemples communs d'opérations "CPU bounds" sont les procédés qui requièrent des traitements mathématiques complexes.
+Des exemples communs d'opérations « CPU bound » sont les procédés qui requièrent des traitements mathématiques complexes.
Par exemple :
@@ -248,19 +290,19 @@ Par exemple :
* L'apprentissage automatique (ou **Machine Learning**) : cela nécessite de nombreuses multiplications de matrices et vecteurs. Imaginez une énorme feuille de calcul remplie de nombres que vous multiplierez entre eux tous au même moment.
* L'apprentissage profond (ou **Deep Learning**) : est un sous-domaine du **Machine Learning**, donc les mêmes raisons s'appliquent. Avec la différence qu'il n'y a pas une unique feuille de calcul de nombres à multiplier, mais une énorme quantité d'entre elles, et dans de nombreux cas, on utilise un processeur spécial pour construire et / ou utiliser ces modèles.
-### Concurrence + Parallélisme : Web + Machine Learning
+### Concurrence + Parallélisme : Web + Machine Learning { #concurrency-parallelism-web-machine-learning }
Avec **FastAPI** vous pouvez bénéficier de la concurrence qui est très courante en développement web (c'est l'attrait principal de NodeJS).
-Mais vous pouvez aussi profiter du parallélisme et multiprocessing afin de gérer des charges **CPU bound** qui sont récurrentes dans les systèmes de *Machine Learning*.
+Mais vous pouvez aussi profiter du parallélisme et du multiprocessing (plusieurs processus s'exécutant en parallèle) afin de gérer des charges **CPU bound** qui sont récurrentes dans les systèmes de *Machine Learning*.
Ça, ajouté au fait que Python soit le langage le plus populaire pour la **Data Science**, le **Machine Learning** et surtout le **Deep Learning**, font de **FastAPI** un très bon choix pour les APIs et applications de **Data Science** / **Machine Learning**.
-Pour comprendre comment mettre en place ce parallélisme en production, allez lire la section [Déploiement](deployment/index.md){.internal-link target=_blank}.
+Pour comprendre comment mettre en place ce parallélisme en production, allez lire la section [Déploiement](deployment/index.md).
-## `async` et `await`
+## `async` et `await` { #async-and-await }
-Les versions modernes de Python ont une manière très intuitive de définir le code asynchrone, tout en gardant une apparence de code "séquentiel" classique en laissant Python faire l'attente pour vous au bon moment.
+Les versions modernes de Python ont une manière très intuitive de définir le code asynchrone, tout en gardant une apparence de code « séquentiel » classique en laissant Python faire l'attente pour vous au bon moment.
Pour une opération qui nécessite de l'attente avant de donner un résultat et qui supporte ces nouvelles fonctionnalités Python, vous pouvez l'utiliser comme tel :
@@ -278,12 +320,12 @@ async def get_burgers(number: int):
return burgers
```
-...et non `def` :
+... et non `def` :
```Python hl_lines="2"
# Ceci n'est pas asynchrone
def get_sequential_burgers(number: int):
- # Opérations asynchrones pour créer les burgers
+ # Opérations séquentielles pour créer les burgers
return burgers
```
@@ -298,7 +340,7 @@ burgers = get_burgers(2)
---
-Donc, si vous utilisez une bibliothèque qui nécessite que ses fonctions soient appelées avec `await`, vous devez définir la *fonction de chemin* en utilisant `async def` comme dans :
+Donc, si vous utilisez une bibliothèque qui nécessite que ses fonctions soient appelées avec `await`, vous devez définir la *fonction de chemin d'accès* en utilisant `async def` comme dans :
```Python hl_lines="2-3"
@app.get('/burgers')
@@ -307,84 +349,96 @@ async def read_burgers():
return burgers
```
-### Plus de détails techniques
+### Plus de détails techniques { #more-technical-details }
Vous avez donc compris que `await` peut seulement être utilisé dans des fonctions définies avec `async def`.
Mais en même temps, les fonctions définies avec `async def` doivent être appelées avec `await` et donc dans des fonctions définies elles aussi avec `async def`.
-Vous avez donc remarqué ce paradoxe d'oeuf et de la poule, comment appelle-t-on la première fonction `async` ?
+Vous avez donc remarqué ce paradoxe d'œuf et de la poule, comment appelle-t-on la première fonction `async` ?
-Si vous utilisez **FastAPI**, pas besoin de vous en inquiéter, car cette "première" fonction sera votre *fonction de chemin* ; et **FastAPI** saura comment arriver au résultat attendu.
+Si vous utilisez **FastAPI**, pas besoin de vous en inquiéter, car cette « première » fonction sera votre *fonction de chemin d'accès* ; et **FastAPI** saura comment arriver au résultat attendu.
-Mais si vous utilisez `async` / `await` sans **FastAPI**, allez jetez un coup d'oeil à la documentation officielle de Python.
+Mais si vous souhaitez utiliser `async` / `await` sans FastAPI, vous pouvez également le faire.
-### Autres formes de code asynchrone
+### Écrire votre propre code async { #write-your-own-async-code }
+
+Starlette (et **FastAPI**) s’appuie sur [AnyIO](https://anyio.readthedocs.io/en/stable/), ce qui le rend compatible à la fois avec la bibliothèque standard [asyncio](https://docs.python.org/3/library/asyncio-task.html) de Python et avec [Trio](https://trio.readthedocs.io/en/stable/).
+
+En particulier, vous pouvez utiliser directement [AnyIO](https://anyio.readthedocs.io/en/stable/) pour vos cas d’usage de concurrence avancés qui nécessitent des schémas plus élaborés dans votre propre code.
+
+Et même si vous n’utilisiez pas FastAPI, vous pourriez aussi écrire vos propres applications async avec [AnyIO](https://anyio.readthedocs.io/en/stable/) pour une grande compatibilité et pour bénéficier de ses avantages (par ex. la « structured concurrency »).
+
+J’ai créé une autre bibliothèque au-dessus d’AnyIO, comme une fine surcouche, pour améliorer un peu les annotations de type et obtenir une meilleure **autocomplétion**, des **erreurs en ligne**, etc. Elle propose également une introduction et un tutoriel accessibles pour vous aider à **comprendre** et écrire **votre propre code async** : [Asyncer](https://asyncer.tiangolo.com/). Elle sera particulièrement utile si vous devez **combiner du code async avec du code classique** (bloquant/synchrone).
+
+### Autres formes de code asynchrone { #other-forms-of-asynchronous-code }
L'utilisation d'`async` et `await` est relativement nouvelle dans ce langage.
Mais cela rend la programmation asynchrone bien plus simple.
-Cette même syntaxe (ou presque) était aussi incluse dans les versions modernes de Javascript (dans les versions navigateur et NodeJS).
+Cette même syntaxe (ou presque) a aussi été incluse récemment dans les versions modernes de JavaScript (dans les navigateurs et NodeJS).
Mais avant ça, gérer du code asynchrone était bien plus complexe et difficile.
-Dans les versions précédentes de Python, vous auriez utilisé des *threads* ou Gevent. Mais le code aurait été bien plus difficile à comprendre, débugger, et concevoir.
-
-Dans les versions précédentes de Javascript NodeJS / Navigateur, vous auriez utilisé des "callbacks". Menant potentiellement à ce que l'on appelle le "callback hell".
+Dans les versions précédentes de Python, vous auriez utilisé des threads ou [Gevent](https://www.gevent.org/). Mais le code aurait été bien plus difficile à comprendre, débugger, et concevoir.
+Dans les versions précédentes de JavaScript côté navigateur / NodeJS, vous auriez utilisé des « callbacks ». Menant potentiellement à ce que l'on appelle le « callback hell ».
-## Coroutines
+## Coroutines { #coroutines }
-**Coroutine** est juste un terme élaboré pour désigner ce qui est retourné par une fonction définie avec `async def`. Python sait que c'est comme une fonction classique qui va démarrer à un moment et terminer à un autre, mais qu'elle peut aussi être mise en pause ⏸, du moment qu'il y a un `await` dans son contenu.
+« Coroutine » est juste un terme élaboré pour désigner ce qui est retourné par une fonction définie avec `async def`. Python sait que c'est comme une fonction classique qui va démarrer à un moment et terminer à un autre, mais qu'elle peut aussi être mise en pause ⏸, du moment qu'il y a un `await` dans son contenu.
-Mais toutes ces fonctionnalités d'utilisation de code asynchrone avec `async` et `await` sont souvent résumées comme l'utilisation des *coroutines*. On peut comparer cela à la principale fonctionnalité clé de Go, les "Goroutines".
+Mais toutes ces fonctionnalités d'utilisation de code asynchrone avec `async` et `await` sont souvent résumées comme l'utilisation des « coroutines ». On peut comparer cela à la principale fonctionnalité clé de Go, les « Goroutines ».
-## Conclusion
+## Conclusion { #conclusion }
Reprenons la phrase du début de la page :
-> Les versions modernes de Python supportent le **code asynchrone** grâce aux **"coroutines"** avec les syntaxes **`async` et `await`**.
+> Les versions modernes de Python supportent le **code asynchrone** grâce aux **« coroutines »** avec les syntaxes **`async` et `await`**.
Ceci devrait être plus compréhensible désormais. ✨
-Tout ceci est donc ce qui donne sa force à **FastAPI** (à travers Starlette) et lui permet d'avoir des performances aussi impressionnantes.
+Tout ceci est donc ce qui donne sa force à FastAPI (à travers Starlette) et lui permet d'avoir une performance aussi impressionnante.
+
+## Détails très techniques { #very-technical-details }
+
+/// warning | Alertes
-## Détails très techniques
+Vous pouvez probablement ignorer cela.
-!!! warning "Attention !"
- Vous pouvez probablement ignorer cela.
+Ce sont des détails très poussés sur comment **FastAPI** fonctionne en arrière-plan.
- Ce sont des détails très poussés sur comment **FastAPI** fonctionne en arrière-plan.
+Si vous avez de bonnes connaissances techniques (coroutines, threads, code bloquant, etc.) et êtes curieux de comment **FastAPI** gère `async def` versus le `def` classique, cette partie est faite pour vous.
- Si vous avez de bonnes connaissances techniques (coroutines, threads, code bloquant, etc.) et êtes curieux de comment **FastAPI** gère `async def` versus le `def` classique, cette partie est faite pour vous.
+///
-### Fonctions de chemin
+### Fonctions de chemin d'accès { #path-operation-functions }
-Quand vous déclarez une *fonction de chemin* avec un `def` normal et non `async def`, elle est exécutée dans un groupe de threads (threadpool) externe qui est ensuite attendu, plutôt que d'être appelée directement (car cela bloquerait le serveur).
+Quand vous déclarez une *fonction de chemin d'accès* avec un `def` normal et non `async def`, elle est exécutée dans un groupe de threads (threadpool) externe qui est ensuite attendu, plutôt que d'être appelée directement (car cela bloquerait le serveur).
-Si vous venez d'un autre framework asynchrone qui ne fonctionne pas comme de la façon décrite ci-dessus et que vous êtes habitués à définir des *fonctions de chemin* basiques avec un simple `def` pour un faible gain de performance (environ 100 nanosecondes), veuillez noter que dans **FastAPI**, l'effet serait plutôt contraire. Dans ces cas-là, il vaut mieux utiliser `async def` à moins que votre *fonction de chemin* utilise du code qui effectue des opérations I/O bloquantes.
+Si vous venez d'un autre framework asynchrone qui ne fonctionne pas comme de la façon décrite ci-dessus et que vous êtes habitué à définir des *fonctions de chemin d'accès* basiques et purement calculatoires avec un simple `def` pour un faible gain de performance (environ 100 nanosecondes), veuillez noter que dans **FastAPI**, l'effet serait plutôt contraire. Dans ces cas-là, il vaut mieux utiliser `async def` à moins que votre *fonction de chemin d'accès* utilise du code qui effectue des opérations I/O bloquantes.
-Au final, dans les deux situations, il est fort probable que **FastAPI** soit tout de même [plus rapide](/#performance){.internal-link target=_blank} que (ou au moins de vitesse égale à) votre framework précédent.
+Au final, dans les deux situations, il est fort probable que **FastAPI** soit tout de même [plus rapide](index.md#performance) que (ou au moins de vitesse égale à) votre framework précédent.
-### Dépendances
+### Dépendances { #dependencies }
-La même chose s'applique aux dépendances. Si une dépendance est définie avec `def` plutôt que `async def`, elle est exécutée dans la threadpool externe.
+La même chose s'applique aux [dépendances](tutorial/dependencies/index.md). Si une dépendance est définie avec `def` plutôt que `async def`, elle est exécutée dans la threadpool externe.
-### Sous-dépendances
+### Sous-dépendances { #sub-dependencies }
-Vous pouvez avoir de multiples dépendances et sous-dépendances dépendant les unes des autres (en tant que paramètres de la définition de la *fonction de chemin*), certaines créées avec `async def` et d'autres avec `def`. Cela fonctionnerait aussi, et celles définies avec un simple `def` seraient exécutées sur un thread externe (venant de la threadpool) plutôt que d'être "attendues".
+Vous pouvez avoir de multiples dépendances et [sous-dépendances](tutorial/dependencies/sub-dependencies.md) dépendant les unes des autres (en tant que paramètres de la définition de la *fonction de chemin d'accès*), certaines créées avec `async def` et d'autres avec `def`. Cela fonctionnerait aussi, et celles définies avec un simple `def` seraient exécutées sur un thread externe (venant de la threadpool) plutôt que d'être « attendues ».
-### Autres fonctions utilitaires
+### Autres fonctions utilitaires { #other-utility-functions }
-Toute autre fonction utilitaire que vous appelez directement peut être créée avec un classique `def` ou avec `async def` et **FastAPI** n'aura pas d'impact sur la façon dont vous l'appelez.
+Toute autre fonction utilitaire que vous appelez directement peut être créée avec un classique `def` ou avec `async def` et FastAPI n'aura pas d'impact sur la façon dont vous l'appelez.
-Contrairement aux fonctions que **FastAPI** appelle pour vous : les *fonctions de chemin* et dépendances.
+Contrairement aux fonctions que FastAPI appelle pour vous : les *fonctions de chemin d'accès* et dépendances.
-Si votre fonction utilitaire est une fonction classique définie avec `def`, elle sera appelée directement (telle qu'écrite dans votre code), pas dans une threadpool, si la fonction est définie avec `async def` alors vous devrez attendre (avec `await`) que cette fonction se termine avant de passer à la suite du code.
+Si votre fonction utilitaire est une fonction classique définie avec `def`, elle sera appelée directement (telle qu'écrite dans votre code), pas dans une threadpool ; si la fonction est définie avec `async def` alors vous devrez attendre (avec `await`) que cette fonction se termine avant de passer à la suite du code.
---
Encore une fois, ce sont des détails très techniques qui peuvent être utiles si vous venez ici les chercher.
-Sinon, les instructions de la section Vous êtes pressés ? ci-dessus sont largement suffisantes.
+Sinon, les instructions de la section Vous êtes pressés ? ci-dessus sont largement suffisantes.
diff --git a/docs/fr/docs/benchmarks.md b/docs/fr/docs/benchmarks.md
index d33c263a213d2..b895118c8bfe6 100644
--- a/docs/fr/docs/benchmarks.md
+++ b/docs/fr/docs/benchmarks.md
@@ -1,34 +1,34 @@
-# Test de performance
+# Tests de performance { #benchmarks }
-Les tests de performance de TechEmpower montrent que les applications **FastAPI** tournant sous Uvicorn comme étant l'un des frameworks Python les plus rapides disponibles, seulement inférieur à Starlette et Uvicorn (tous deux utilisés au cœur de FastAPI). (*)
+Les benchmarks indépendants de TechEmpower montrent que les applications **FastAPI** s’exécutant avec Uvicorn sont [parmi les frameworks Python les plus rapides disponibles](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7), seulement en dessous de Starlette et Uvicorn eux‑mêmes (tous deux utilisés en interne par FastAPI).
-Mais en prêtant attention aux tests de performance et aux comparaisons, il faut tenir compte de ce qu'il suit.
+Mais en prêtant attention aux tests de performance et aux comparaisons, vous devez tenir compte de ce qui suit.
-## Tests de performance et rapidité
+## Tests de performance et rapidité { #benchmarks-and-speed }
Lorsque vous vérifiez les tests de performance, il est commun de voir plusieurs outils de différents types comparés comme équivalents.
En particulier, on voit Uvicorn, Starlette et FastAPI comparés (parmi de nombreux autres outils).
-Plus le problème résolu par un outil est simple, mieux seront les performances obtenues. Et la plupart des tests de performance ne prennent pas en compte les fonctionnalités additionnelles fournies par les outils.
+Plus le problème résolu par un outil est simple, meilleures seront les performances obtenues. Et la plupart des tests de performance ne prennent pas en compte les fonctionnalités additionnelles fournies par les outils.
La hiérarchie est la suivante :
* **Uvicorn** : un serveur ASGI
- * **Starlette** : (utilise Uvicorn) un micro-framework web
- * **FastAPI**: (utilise Starlette) un micro-framework pour API disposant de fonctionnalités additionnelles pour la création d'API, avec la validation des données, etc.
+ * **Starlette** : (utilise Uvicorn) un microframework web
+ * **FastAPI**: (utilise Starlette) un microframework pour API disposant de fonctionnalités additionnelles pour la création d'API, avec la validation des données, etc.
* **Uvicorn** :
- * A les meilleures performances, étant donné qu'il n'a pas beaucoup de code mis-à-part le serveur en lui-même.
- * On n'écrit pas une application avec uniquement Uvicorn. Cela signifie que le code devrait inclure plus ou moins, au minimum, tout le code offert par Starlette (ou **FastAPI**). Et si on fait cela, l'application finale apportera les mêmes complications que si on avait utilisé un framework et que l'on avait minimisé la quantité de code et de bugs.
- * Si on compare Uvicorn, il faut le comparer à d'autre applications de serveurs comme Daphne, Hypercorn, uWSGI, etc.
+ * A les meilleures performances, étant donné qu'il n'a pas beaucoup de code mis à part le serveur en lui‑même.
+ * On n'écrit pas une application directement avec Uvicorn. Cela signifie que le code devrait inclure, au minimum, plus ou moins tout le code offert par Starlette (ou **FastAPI**). Et si on fait cela, l'application finale aura la même surcharge que si on avait utilisé un framework, tout en minimisant la quantité de code et les bugs.
+ * Si on compare Uvicorn, il faut le comparer à d'autres serveurs d'applications comme Daphne, Hypercorn, uWSGI, etc.
* **Starlette** :
- * A les seconde meilleures performances après Uvicorn. Starlette utilise en réalité Uvicorn. De ce fait, il ne peut qu’être plus "lent" qu'Uvicorn car il requiert l'exécution de plus de code.
- * Cependant il nous apporte les outils pour construire une application web simple, avec un routage basé sur des chemins, etc.
- * Si on compare Starlette, il faut le comparer à d'autres frameworks web (ou micorframework) comme Sanic, Flask, Django, etc.
+ * A les secondes meilleures performances après Uvicorn. En réalité, Starlette utilise Uvicorn. De ce fait, il ne peut qu’être plus « lent » qu'Uvicorn car il requiert l'exécution de plus de code.
+ * Cependant, il apporte les outils pour construire une application web simple, avec un routage basé sur des chemins, etc.
+ * Si on compare Starlette, il faut le comparer à d'autres frameworks web (ou microframeworks) comme Sanic, Flask, Django, etc.
* **FastAPI** :
- * Comme Starlette, FastAPI utilise Uvicorn et ne peut donc pas être plus rapide que ce dernier.
- * FastAPI apporte des fonctionnalités supplémentaires à Starlette. Des fonctionnalités qui sont nécessaires presque systématiquement lors de la création d'une API, comme la validation des données, la sérialisation. En utilisant FastAPI, on obtient une documentation automatiquement (qui ne requiert aucune manipulation pour être mise en place).
- * Si on n'utilisait pas FastAPI mais directement Starlette (ou un outil équivalent comme Sanic, Flask, Responder, etc) il faudrait implémenter la validation des données et la sérialisation par nous-même. Le résultat serait donc le même dans les deux cas mais du travail supplémentaire serait à réaliser avec Starlette, surtout en considérant que la validation des données et la sérialisation représentent la plus grande quantité de code à écrire dans une application.
- * De ce fait, en utilisant FastAPI on minimise le temps de développement, les bugs, le nombre de lignes de code, et on obtient les mêmes performances (si ce n'est de meilleurs performances) que l'on aurait pu avoir sans ce framework (en ayant à implémenter de nombreuses fonctionnalités importantes par nous-mêmes).
- * Si on compare FastAPI, il faut le comparer à d'autres frameworks web (ou ensemble d'outils) qui fournissent la validation des données, la sérialisation et la documentation, comme Flask-apispec, NestJS, Molten, etc.
+ * Comme Starlette utilise Uvicorn et ne peut donc pas être plus rapide que lui, **FastAPI** utilise Starlette et ne peut donc pas être plus rapide que lui.
+ * FastAPI apporte des fonctionnalités supplémentaires à Starlette. Des fonctionnalités dont vous avez presque toujours besoin lors de la création d'une API, comme la validation des données et la sérialisation. En l'utilisant, vous obtenez une documentation automatique « gratuitement » (la documentation automatique n'ajoute même pas de surcharge à l’exécution, elle est générée au démarrage).
+ * Si on n'utilisait pas FastAPI mais directement Starlette (ou un autre outil comme Sanic, Flask, Responder, etc.), il faudrait implémenter toute la validation des données et la sérialisation soi‑même. L'application finale aurait donc la même surcharge que si elle avait été construite avec FastAPI. Et dans de nombreux cas, cette validation des données et cette sérialisation représentent la plus grande quantité de code écrite dans les applications.
+ * De ce fait, en utilisant FastAPI on minimise le temps de développement, les bugs, le nombre de lignes de code, et on obtient probablement les mêmes performances (voire de meilleures performances) que l'on aurait pu avoir sans ce framework (car il aurait fallu tout implémenter dans votre code).
+ * Si on compare FastAPI, il faut le comparer à d'autres frameworks d’application web (ou ensembles d'outils) qui fournissent la validation des données, la sérialisation et la documentation, comme Flask-apispec, NestJS, Molten, etc. Des frameworks avec validation des données, sérialisation et documentation automatiques intégrées.
diff --git a/docs/fr/docs/contributing.md b/docs/fr/docs/contributing.md
deleted file mode 100644
index 8292f14bb9b3e..0000000000000
--- a/docs/fr/docs/contributing.md
+++ /dev/null
@@ -1,501 +0,0 @@
-# Développement - Contribuer
-
-Tout d'abord, vous voudrez peut-être voir les moyens de base pour [aider FastAPI et obtenir de l'aide](help-fastapi.md){.internal-link target=_blank}.
-
-## Développement
-
-Si vous avez déjà cloné le dépôt et que vous savez que vous devez vous plonger dans le code, voici quelques directives pour mettre en place votre environnement.
-
-### Environnement virtuel avec `venv`
-
-Vous pouvez créer un environnement virtuel dans un répertoire en utilisant le module `venv` de Python :
-
-
+
+---
+
+Maintenant que nous connaissons la différence entre les termes **processus** et **programme**, continuons à parler des déploiements.
+
+## Exécuter au démarrage { #running-on-startup }
+
+Dans la plupart des cas, lorsque vous créez une web API, vous voulez qu'elle **tourne en permanence**, sans interruption, afin que vos clients puissent toujours y accéder. Bien sûr, sauf si vous avez une raison spécifique de ne vouloir l'exécuter que dans certaines situations, mais la plupart du temps vous la voulez constamment en cours et **disponible**.
+
+### Sur un serveur distant { #in-a-remote-server }
+
+Lorsque vous configurez un serveur distant (un serveur cloud, une machine virtuelle, etc.), la chose la plus simple à faire est d'utiliser `fastapi run` (qui utilise Uvicorn) ou quelque chose de similaire, manuellement, de la même manière que lorsque vous développez en local.
+
+Et cela fonctionnera et sera utile **pendant le développement**.
+
+Mais si votre connexion au serveur est coupée, le **processus en cours** va probablement s'arrêter.
+
+Et si le serveur est redémarré (par exemple après des mises à jour, ou des migrations chez le fournisseur cloud) vous **ne le remarquerez probablement pas**. Et à cause de cela, vous ne saurez même pas que vous devez redémarrer le processus manuellement. Ainsi, votre API restera tout simplement à l'arrêt. 😱
+
+### Lancer automatiquement au démarrage { #run-automatically-on-startup }
+
+En général, vous voudrez probablement que le programme serveur (par ex. Uvicorn) soit démarré automatiquement au démarrage du serveur, et sans aucune **intervention humaine**, afin d'avoir en permanence un processus exécutant votre API (par ex. Uvicorn exécutant votre app FastAPI).
+
+### Programme séparé { #separate-program }
+
+Pour y parvenir, vous aurez normalement un **programme séparé** qui s'assure que votre application est lancée au démarrage. Et dans de nombreux cas, il s'assurera également que d'autres composants ou applications sont également lancés, par exemple une base de données.
+
+### Exemples d’outils pour lancer au démarrage { #example-tools-to-run-at-startup }
+
+Voici quelques exemples d'outils capables de faire ce travail :
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Docker en mode Swarm
+* Systemd
+* Supervisor
+* Pris en charge en interne par un fournisseur cloud dans le cadre de ses services
+* Autres ...
+
+Je vous donnerai des exemples plus concrets dans les prochains chapitres.
+
+## Redémarrages { #restarts }
+
+De la même manière que vous voulez vous assurer que votre application est lancée au démarrage, vous voulez probablement aussi vous assurer qu'elle est **redémarrée** après des échecs.
+
+### Nous faisons des erreurs { #we-make-mistakes }
+
+Nous, humains, faisons des **erreurs**, tout le temps. Les logiciels ont presque *toujours* des **bugs** cachés à différents endroits. 🐛
+
+Et nous, développeurs, continuons à améliorer le code au fur et à mesure que nous trouvons ces bugs et que nous implémentons de nouvelles fonctionnalités (en ajoutant éventuellement de nouveaux bugs aussi 😅).
+
+### Petites erreurs gérées automatiquement { #small-errors-automatically-handled }
+
+Lors de la création de web API avec FastAPI, s'il y a une erreur dans notre code, FastAPI la contiendra normalement à la seule requête qui a déclenché l'erreur. 🛡
+
+Le client recevra un **500 Internal Server Error** pour cette requête, mais l'application continuera de fonctionner pour les requêtes suivantes au lieu de simplement s'effondrer complètement.
+
+### Erreurs plus importantes - plantages { #bigger-errors-crashes }
+
+Néanmoins, il peut y avoir des cas où nous écrivons du code qui **fait planter l'application entière**, faisant planter Uvicorn et Python. 💥
+
+Et malgré cela, vous ne voudrez probablement pas que l'application reste à l'arrêt parce qu'il y a eu une erreur à un endroit ; vous voudrez probablement qu'elle **continue de tourner**, au moins pour les *chemins d'accès* qui ne sont pas cassés.
+
+### Redémarrer après un plantage { #restart-after-crash }
+
+Mais dans ces cas avec de très mauvaises erreurs qui font planter le **processus** en cours, vous voudrez un composant externe chargé de **redémarrer** le processus, au moins quelques fois ...
+
+/// tip | Astuce
+
+... Bien que si l'application entière **plante immédiatement**, il n'est probablement pas logique de continuer à la redémarrer indéfiniment. Mais dans ces cas, vous le remarquerez probablement pendant le développement, ou au moins juste après le déploiement.
+
+Concentrons‑nous donc sur les cas principaux, où elle pourrait planter entièrement dans certaines situations particulières **à l'avenir**, et où il est toujours logique de la redémarrer.
+
+///
+
+Vous voudrez probablement que l'élément chargé de redémarrer votre application soit un **composant externe**, car à ce stade, l'application elle‑même avec Uvicorn et Python a déjà planté, donc il n'y a rien dans le même code de la même app qui pourrait y faire quoi que ce soit.
+
+### Exemples d’outils pour redémarrer automatiquement { #example-tools-to-restart-automatically }
+
+Dans la plupart des cas, le même outil qui est utilisé pour **lancer le programme au démarrage** est également utilisé pour gérer les **redémarrages** automatiques.
+
+Par exemple, cela peut être géré par :
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Docker en mode Swarm
+* Systemd
+* Supervisor
+* Pris en charge en interne par un fournisseur cloud dans le cadre de ses services
+* Autres ...
+
+## Réplication - Processus et mémoire { #replication-processes-and-memory }
+
+Avec une application FastAPI, en utilisant un programme serveur comme la commande `fastapi` qui exécute Uvicorn, l'exécuter une fois dans **un processus** peut servir plusieurs clients simultanément.
+
+Mais dans de nombreux cas, vous voudrez exécuter plusieurs processus de travail en même temps.
+
+### Multiples processus - Workers { #multiple-processes-workers }
+
+Si vous avez plus de clients que ce qu'un seul processus peut gérer (par exemple si la machine virtuelle n'est pas très grande) et que vous avez **plusieurs cœurs** dans le CPU du serveur, alors vous pouvez avoir **plusieurs processus** exécutant la même application simultanément, et distribuer toutes les requêtes entre eux.
+
+Quand vous exécutez **plusieurs processus** du même programme d'API, on les appelle couramment des **workers**.
+
+### Processus workers et ports { #worker-processes-and-ports }
+
+Rappelez‑vous, d'après les documents [À propos de HTTPS](https.md), qu'un seul processus peut écouter une combinaison de port et d'adresse IP sur un serveur ?
+
+C'est toujours vrai.
+
+Donc, pour pouvoir avoir **plusieurs processus** en même temps, il doit y avoir un **seul processus à l'écoute sur un port** qui transmet ensuite la communication à chaque processus worker d'une manière ou d'une autre.
+
+### Mémoire par processus { #memory-per-process }
+
+Maintenant, lorsque le programme charge des choses en mémoire, par exemple, un modèle de machine learning dans une variable, ou le contenu d'un gros fichier dans une variable, tout cela **consomme une partie de la mémoire (RAM)** du serveur.
+
+Et plusieurs processus **ne partagent normalement pas de mémoire**. Cela signifie que chaque processus en cours a ses propres éléments, variables et mémoire. Et si vous consommez une grande quantité de mémoire dans votre code, **chaque processus** consommera une quantité équivalente de mémoire.
+
+### Mémoire du serveur { #server-memory }
+
+Par exemple, si votre code charge un modèle de Machine Learning de **1 Go**, lorsque vous exécutez un processus avec votre API, il consommera au moins 1 Go de RAM. Et si vous démarrez **4 processus** (4 workers), chacun consommera 1 Go de RAM. Donc au total, votre API consommera **4 Go de RAM**.
+
+Et si votre serveur distant ou votre machine virtuelle n'a que 3 Go de RAM, essayer de charger plus de 4 Go de RAM posera problème. 🚨
+
+### Multiples processus - Un exemple { #multiple-processes-an-example }
+
+Dans cet exemple, il y a un **processus gestionnaire** qui démarre et contrôle deux **processus workers**.
+
+Ce processus gestionnaire serait probablement celui qui écoute sur le **port** de l'IP. Et il transmettrait toute la communication aux processus workers.
+
+Ces processus workers seraient ceux qui exécutent votre application, ils effectueraient les calculs principaux pour recevoir une **requête** et renvoyer une **réponse**, et ils chargeraient tout ce que vous mettez dans des variables en RAM.
+
+@@ -28,7 +28,7 @@ Mais à un moment donné, il n'y avait pas d'autre option que de créer quelque-## Recherche +## Recherche { #investigation } En utilisant toutes les alternatives précédentes, j'ai eu la chance d'apprendre de toutes, de prendre des idées, et de les combiner de la meilleure façon que j'ai pu trouver pour moi-même et les équipes de développeurs avec lesquelles j'ai travaillé. @@ -38,33 +38,33 @@ De plus, la meilleure approche était d'utiliser des normes déjà existantes. Ainsi, avant même de commencer à coder **FastAPI**, j'ai passé plusieurs mois à étudier les spécifications d'OpenAPI, JSON Schema, OAuth2, etc. Comprendre leurs relations, leurs similarités et leurs différences. -## Conception +## Conception { #design } -Ensuite, j'ai passé du temps à concevoir l'"API" de développeur que je voulais avoir en tant qu'utilisateur (en tant que développeur utilisant FastAPI). +Ensuite, j'ai passé du temps à concevoir l'« API » de développeur que je voulais avoir en tant qu'utilisateur (en tant que développeur utilisant FastAPI). J'ai testé plusieurs idées dans les éditeurs Python les plus populaires : PyCharm, VS Code, les éditeurs basés sur Jedi. -D'après la dernière Enquête Développeurs Python, cela couvre environ 80% des utilisateurs. +D'après la dernière [Enquête Développeurs Python](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools), cela couvre environ 80% des utilisateurs. Cela signifie que **FastAPI** a été spécifiquement testé avec les éditeurs utilisés par 80% des développeurs Python. Et comme la plupart des autres éditeurs ont tendance à fonctionner de façon similaire, tous ses avantages devraient fonctionner pour pratiquement tous les éditeurs. -Ainsi, j'ai pu trouver les meilleurs moyens de réduire autant que possible la duplication du code, d'avoir la complétion partout, les contrôles de type et d'erreur, etc. +Ainsi, j'ai pu trouver les meilleurs moyens de réduire autant que possible la duplication du code, d'avoir l'autocomplétion partout, les contrôles de type et d'erreur, etc. Le tout de manière à offrir la meilleure expérience de développement à tous les développeurs. -## Exigences +## Exigences { #requirements } -Après avoir testé plusieurs alternatives, j'ai décidé que j'allais utiliser **Pydantic** pour ses avantages. +Après avoir testé plusieurs alternatives, j'ai décidé que j'allais utiliser [**Pydantic**](https://docs.pydantic.dev/) pour ses avantages. J'y ai ensuite contribué, pour le rendre entièrement compatible avec JSON Schema, pour supporter différentes manières de définir les déclarations de contraintes, et pour améliorer le support des éditeurs (vérifications de type, autocomplétion) sur la base des tests effectués dans plusieurs éditeurs. -Pendant le développement, j'ai également contribué à **Starlette**, l'autre exigence clé. +Pendant le développement, j'ai également contribué à [**Starlette**](https://www.starlette.dev/), l'autre exigence clé. -## Développement +## Développement { #development } Au moment où j'ai commencé à créer **FastAPI** lui-même, la plupart des pièces étaient déjà en place, la conception était définie, les exigences et les outils étaient prêts, et la connaissance des normes et des spécifications était claire et fraîche. -## Futur +## Futur { #future } À ce stade, il est déjà clair que **FastAPI** et ses idées sont utiles pour de nombreuses personnes. @@ -76,4 +76,4 @@ Mais il y a encore de nombreuses améliorations et fonctionnalités à venir. **FastAPI** a un grand avenir devant lui. -Et [votre aide](help-fastapi.md){.internal-link target=\_blank} est grandement appréciée. +Et [votre aide](help-fastapi.md) est grandement appréciée. diff --git a/docs/fr/docs/how-to/authentication-error-status-code.md b/docs/fr/docs/how-to/authentication-error-status-code.md new file mode 100644 index 0000000000000..8cbfe3d7bec25 --- /dev/null +++ b/docs/fr/docs/how-to/authentication-error-status-code.md @@ -0,0 +1,17 @@ +# Utiliser les anciens codes d'erreur d'authentification 403 { #use-old-403-authentication-error-status-codes } + +Avant FastAPI version `0.122.0`, lorsque les utilitaires de sécurité intégrés renvoyaient une erreur au client après un échec d'authentification, ils utilisaient le code d'état HTTP `403 Forbidden`. + +À partir de FastAPI version `0.122.0`, ils utilisent le code d'état HTTP plus approprié `401 Unauthorized`, et renvoient un en-tête `WWW-Authenticate` pertinent dans la réponse, conformément aux spécifications HTTP, [RFC 7235](https://datatracker.ietf.org/doc/html/rfc7235#section-3.1), [RFC 9110](https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized). + +Mais si, pour une raison quelconque, vos clients dépendent de l'ancien comportement, vous pouvez y revenir en surchargeant la méthode `make_not_authenticated_error` dans vos classes de sécurité. + +Par exemple, vous pouvez créer une sous-classe de `HTTPBearer` qui renvoie une erreur `403 Forbidden` au lieu de l'erreur par défaut `401 Unauthorized` : + +{* ../../docs_src/authentication_error_status_code/tutorial001_an_py310.py hl[9:13] *} + +/// tip | Astuce + +Remarquez que la fonction renvoie l'instance de l'exception, elle ne la lève pas. La levée est effectuée dans le reste du code interne. + +/// diff --git a/docs/fr/docs/how-to/conditional-openapi.md b/docs/fr/docs/how-to/conditional-openapi.md new file mode 100644 index 0000000000000..dd72b392959e8 --- /dev/null +++ b/docs/fr/docs/how-to/conditional-openapi.md @@ -0,0 +1,56 @@ +# Configurer OpenAPI de manière conditionnelle { #conditional-openapi } + +Si nécessaire, vous pouvez utiliser des paramètres et des variables d'environnement pour configurer OpenAPI de manière conditionnelle selon l'environnement, et même le désactiver complètement. + +## À propos de la sécurité, des API et des documents { #about-security-apis-and-docs } + +Masquer vos interfaces utilisateur des documents en production ne devrait pas être la manière de protéger votre API. + +Cela n'ajoute aucune sécurité supplémentaire à votre API, les *chemins d'accès* resteront disponibles là où ils se trouvent. + +S'il y a une faille de sécurité dans votre code, elle existera toujours. + +Masquer les documents rend simplement plus difficile la compréhension de la manière d'interagir avec votre API et pourrait aussi rendre son débogage en production plus difficile. Cela pourrait être considéré simplement comme une forme de [Sécurité par l'obscurité](https://en.wikipedia.org/wiki/Security_through_obscurity). + +Si vous voulez sécuriser votre API, il y a plusieurs meilleures approches possibles, par exemple : + +* Vous devez vous assurer d'avoir des modèles Pydantic bien définis pour le corps de la requête et la réponse. +* Configurez toutes les autorisations et tous les rôles nécessaires à l'aide de dépendances. +* Ne stockez jamais de mots de passe en clair, seulement des hachages de mots de passe. +* Implémentez et utilisez des outils cryptographiques reconnus, comme pwdlib et des jetons JWT, ... etc. +* Ajoutez des contrôles d'autorisation plus granulaires avec des scopes OAuth2 lorsque nécessaire. +* ... etc. + +Néanmoins, vous pourriez avoir un cas d'utilisation très spécifique où vous devez vraiment désactiver les documents de l'API pour un certain environnement (par exemple pour la production) ou selon des configurations provenant de variables d'environnement. + +## Configurer OpenAPI de manière conditionnelle avec des paramètres et des variables d'environnement { #conditional-openapi-from-settings-and-env-vars } + +Vous pouvez facilement utiliser les mêmes paramètres Pydantic pour configurer votre OpenAPI généré et les interfaces utilisateur des documents. + +Par exemple : + +{* ../../docs_src/conditional_openapi/tutorial001_py310.py hl[6,11] *} + +Ici nous déclarons le paramètre `openapi_url` avec la même valeur par défaut `"/openapi.json"`. + +Nous l'utilisons ensuite lors de la création de l'application `FastAPI`. + +Vous pouvez alors désactiver OpenAPI (y compris les interfaces utilisateur des documents) en définissant la variable d'environnement `OPENAPI_URL` sur la chaîne vide, comme ceci : + +
+
+Mais vous pouvez la désactiver en définissant `syntaxHighlight` à `False` :
+
+{* ../../docs_src/configure_swagger_ui/tutorial001_py310.py hl[3] *}
+
+... et ensuite Swagger UI n'affichera plus la coloration syntaxique :
+
+
+
+## Modifier le thème { #change-the-theme }
+
+De la même manière, vous pouvez définir le thème de la coloration syntaxique avec la clé « syntaxHighlight.theme » (remarquez le point au milieu) :
+
+{* ../../docs_src/configure_swagger_ui/tutorial002_py310.py hl[3] *}
+
+Cette configuration modifierait le thème de couleurs de la coloration syntaxique :
+
+
+
+## Modifier les paramètres Swagger UI par défaut { #change-default-swagger-ui-parameters }
+
+FastAPI inclut des paramètres de configuration par défaut adaptés à la plupart des cas d'utilisation.
+
+Il inclut ces configurations par défaut :
+
+{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}
+
+Vous pouvez remplacer n'importe lequel d'entre eux en définissant une valeur différente dans l'argument `swagger_ui_parameters`.
+
+Par exemple, pour désactiver `deepLinking`, vous pourriez passer ces paramètres à `swagger_ui_parameters` :
+
+{* ../../docs_src/configure_swagger_ui/tutorial003_py310.py hl[3] *}
+
+## Autres paramètres de Swagger UI { #other-swagger-ui-parameters }
+
+Pour voir toutes les autres configurations possibles que vous pouvez utiliser, lisez les [documents officiels pour les paramètres de Swagger UI](https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/).
+
+## Paramètres JavaScript uniquement { #javascript-only-settings }
+
+Swagger UI permet également d'autres configurations qui sont des objets réservés à JavaScript (par exemple, des fonctions JavaScript).
+
+FastAPI inclut aussi ces paramètres `presets` réservés à JavaScript :
+
+```JavaScript
+presets: [
+ SwaggerUIBundle.presets.apis,
+ SwaggerUIBundle.SwaggerUIStandalonePreset
+]
+```
+
+Ce sont des objets **JavaScript**, pas des chaînes, vous ne pouvez donc pas les passer directement depuis du code Python.
+
+Si vous devez utiliser des configurations réservées à JavaScript comme celles-ci, vous pouvez utiliser l'une des méthodes ci-dessus. Surchargez entièrement le *chemin d'accès* Swagger UI et écrivez manuellement tout JavaScript nécessaire.
diff --git a/docs/fr/docs/how-to/custom-docs-ui-assets.md b/docs/fr/docs/how-to/custom-docs-ui-assets.md
new file mode 100644
index 0000000000000..339b806c30a41
--- /dev/null
+++ b/docs/fr/docs/how-to/custom-docs-ui-assets.md
@@ -0,0 +1,185 @@
+# Héberger en propre les ressources statiques de l’UI des docs personnalisées { #custom-docs-ui-static-assets-self-hosting }
+
+Les documents de l’API utilisent **Swagger UI** et **ReDoc**, et chacune nécessite des fichiers JavaScript et CSS.
+
+Par défaut, ces fichiers sont servis depuis un CDN.
+
+Mais il est possible de le personnaliser : vous pouvez définir un CDN spécifique, ou servir vous‑même les fichiers.
+
+## Configurer un CDN personnalisé pour JavaScript et CSS { #custom-cdn-for-javascript-and-css }
+
+Supposons que vous souhaitiez utiliser un autre CDN, par exemple vous voulez utiliser `https://unpkg.com/`.
+
+Cela peut être utile si, par exemple, vous vivez dans un pays qui restreint certaines URL.
+
+### Désactiver les docs automatiques { #disable-the-automatic-docs }
+
+La première étape consiste à désactiver les docs automatiques, car par défaut elles utilisent le CDN par défaut.
+
+Pour les désactiver, définissez leurs URL sur `None` lors de la création de votre application `FastAPI` :
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[8] *}
+
+### Inclure les docs personnalisées { #include-the-custom-docs }
+
+Vous pouvez maintenant créer les chemins d'accès pour les docs personnalisées.
+
+Vous pouvez réutiliser les fonctions internes de FastAPI pour créer les pages HTML de la documentation et leur passer les arguments nécessaires :
+
+- `openapi_url` : l’URL où la page HTML des docs peut récupérer le schéma OpenAPI de votre API. Vous pouvez utiliser ici l’attribut `app.openapi_url`.
+- `title` : le titre de votre API.
+- `oauth2_redirect_url` : vous pouvez utiliser `app.swagger_ui_oauth2_redirect_url` ici pour utiliser la valeur par défaut.
+- `swagger_js_url` : l’URL où la page HTML de Swagger UI peut récupérer le fichier **JavaScript**. C’est l’URL du CDN personnalisé.
+- `swagger_css_url` : l’URL où la page HTML de Swagger UI peut récupérer le fichier **CSS**. C’est l’URL du CDN personnalisé.
+
+Et de même pour ReDoc ...
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[2:6,11:19,22:24,27:33] *}
+
+/// tip | Astuce
+
+Le chemin d'accès pour `swagger_ui_redirect` est un assistant lorsque vous utilisez OAuth2.
+
+Si vous intégrez votre API à un fournisseur OAuth2, vous pourrez vous authentifier et revenir aux docs de l’API avec les identifiants acquis. Et interagir avec elle en utilisant la véritable authentification OAuth2.
+
+Swagger UI s’en chargera en arrière‑plan pour vous, mais il a besoin de cet assistant « redirect ».
+
+///
+
+### Créer un chemin d'accès pour tester { #create-a-path-operation-to-test-it }
+
+Maintenant, pour pouvoir vérifier que tout fonctionne, créez un chemin d'accès :
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[36:38] *}
+
+### Tester { #test-it }
+
+Vous devriez maintenant pouvoir aller à vos docs sur [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs), puis recharger la page : elle chargera ces ressources depuis le nouveau CDN.
+
+## Héberger en propre JavaScript et CSS pour les docs { #self-hosting-javascript-and-css-for-docs }
+
+Héberger vous‑même le JavaScript et le CSS peut être utile si, par exemple, votre application doit continuer de fonctionner même hors ligne, sans accès Internet ouvert, ou sur un réseau local.
+
+Vous verrez ici comment servir ces fichiers vous‑même, dans la même application FastAPI, et configurer les docs pour les utiliser.
+
+### Structure des fichiers du projet { #project-file-structure }
+
+Supposons que la structure de vos fichiers de projet ressemble à ceci :
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+```
+
+Créez maintenant un répertoire pour stocker ces fichiers statiques.
+
+Votre nouvelle structure de fichiers pourrait ressembler à ceci :
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static/
+```
+
+### Télécharger les fichiers { #download-the-files }
+
+Téléchargez les fichiers statiques nécessaires aux docs et placez‑les dans ce répertoire `static/`.
+
+Vous pouvez probablement cliquer avec le bouton droit sur chaque lien et choisir une option similaire à « Enregistrer le lien sous ... ».
+
+**Swagger UI** utilise les fichiers :
+
+- [`swagger-ui-bundle.js`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js)
+- [`swagger-ui.css`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css)
+
+Et **ReDoc** utilise le fichier :
+
+- [`redoc.standalone.js`](https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js)
+
+Après cela, votre structure de fichiers pourrait ressembler à :
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static
+ ├── redoc.standalone.js
+ ├── swagger-ui-bundle.js
+ └── swagger-ui.css
+```
+
+### Servir les fichiers statiques { #serve-the-static-files }
+
+- Importer `StaticFiles`.
+- « Monter » une instance `StaticFiles()` sur un chemin spécifique.
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[7,11] *}
+
+### Tester les fichiers statiques { #test-the-static-files }
+
+Démarrez votre application et rendez‑vous sur [http://127.0.0.1:8000/static/redoc.standalone.js](http://127.0.0.1:8000/static/redoc.standalone.js).
+
+Vous devriez voir un très long fichier JavaScript pour **ReDoc**.
+
+Il pourrait commencer par quelque chose comme :
+
+```JavaScript
+/*! For license information please see redoc.standalone.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")):
+...
+```
+
+Cela confirme que vous parvenez à servir des fichiers statiques depuis votre application et que vous avez placé les fichiers statiques des docs au bon endroit.
+
+Nous pouvons maintenant configurer l’application pour utiliser ces fichiers statiques pour les docs.
+
+### Désactiver les docs automatiques pour les fichiers statiques { #disable-the-automatic-docs-for-static-files }
+
+Comme lors de l’utilisation d’un CDN personnalisé, la première étape consiste à désactiver les docs automatiques, car elles utilisent un CDN par défaut.
+
+Pour les désactiver, définissez leurs URL sur `None` lors de la création de votre application `FastAPI` :
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[9] *}
+
+### Inclure les docs personnalisées pour les fichiers statiques { #include-the-custom-docs-for-static-files }
+
+Et comme avec un CDN personnalisé, vous pouvez maintenant créer les chemins d'accès pour les docs personnalisées.
+
+Là encore, vous pouvez réutiliser les fonctions internes de FastAPI pour créer les pages HTML de la documentation et leur passer les arguments nécessaires :
+
+- `openapi_url` : l’URL où la page HTML des docs peut récupérer le schéma OpenAPI de votre API. Vous pouvez utiliser ici l’attribut `app.openapi_url`.
+- `title` : le titre de votre API.
+- `oauth2_redirect_url` : vous pouvez utiliser `app.swagger_ui_oauth2_redirect_url` ici pour utiliser la valeur par défaut.
+- `swagger_js_url` : l’URL où la page HTML de Swagger UI peut récupérer le fichier **JavaScript**. **C’est celui que votre propre application sert désormais**.
+- `swagger_css_url` : l’URL où la page HTML de Swagger UI peut récupérer le fichier **CSS**. **C’est celui que votre propre application sert désormais**.
+
+Et de même pour ReDoc ...
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[2:6,14:22,25:27,30:36] *}
+
+/// tip | Astuce
+
+Le chemin d'accès pour `swagger_ui_redirect` est un assistant lorsque vous utilisez OAuth2.
+
+Si vous intégrez votre API à un fournisseur OAuth2, vous pourrez vous authentifier et revenir aux docs de l’API avec les identifiants acquis. Et interagir avec elle en utilisant la véritable authentification OAuth2.
+
+Swagger UI s’en chargera en arrière‑plan pour vous, mais il a besoin de cet assistant « redirect ».
+
+///
+
+### Créer un chemin d'accès pour tester les fichiers statiques { #create-a-path-operation-to-test-static-files }
+
+Maintenant, pour pouvoir vérifier que tout fonctionne, créez un chemin d'accès :
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[39:41] *}
+
+### Tester l’UI avec des fichiers statiques { #test-static-files-ui }
+
+Vous devriez maintenant pouvoir couper votre Wi‑Fi, aller à vos docs sur [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) et recharger la page.
+
+Et même sans Internet, vous pourrez voir la documentation de votre API et interagir avec elle.
diff --git a/docs/fr/docs/how-to/custom-request-and-route.md b/docs/fr/docs/how-to/custom-request-and-route.md
new file mode 100644
index 0000000000000..4acb6464f84a5
--- /dev/null
+++ b/docs/fr/docs/how-to/custom-request-and-route.md
@@ -0,0 +1,109 @@
+# Personnaliser les classes Request et APIRoute { #custom-request-and-apiroute-class }
+
+Dans certains cas, vous pouvez vouloir surcharger la logique utilisée par les classes `Request` et `APIRoute`.
+
+En particulier, cela peut être une bonne alternative à une logique dans un middleware.
+
+Par exemple, si vous voulez lire ou manipuler le corps de la requête avant qu'il ne soit traité par votre application.
+
+/// danger | Danger
+
+Ceci est une fonctionnalité « avancée ».
+
+Si vous débutez avec **FastAPI**, vous pouvez ignorer cette section.
+
+///
+
+## Cas d'utilisation { #use-cases }
+
+Voici quelques cas d'utilisation :
+
+* Convertir des corps de requête non JSON en JSON (par exemple [`msgpack`](https://msgpack.org/index.html)).
+* Décompresser des corps de requête compressés en gzip.
+* Journaliser automatiquement tous les corps de requête.
+
+## Gérer les encodages personnalisés du corps de la requête { #handling-custom-request-body-encodings }
+
+Voyons comment utiliser une sous-classe personnalisée de `Request` pour décompresser des requêtes gzip.
+
+Et une sous-classe d'`APIRoute` pour utiliser cette classe de requête personnalisée.
+
+### Créer une classe `GzipRequest` personnalisée { #create-a-custom-gziprequest-class }
+
+/// tip | Astuce
+
+Il s'agit d'un exemple simplifié pour montrer le fonctionnement ; si vous avez besoin de la prise en charge de Gzip, vous pouvez utiliser le [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware) fourni.
+
+///
+
+Commencez par créer une classe `GzipRequest`, qui va surcharger la méthode `Request.body()` pour décompresser le corps en présence d'un en-tête approprié.
+
+S'il n'y a pas `gzip` dans l'en-tête, elle n'essaiera pas de décompresser le corps.
+
+De cette manière, la même classe de route peut gérer des requêtes gzip compressées ou non compressées.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[9:16] *}
+
+### Créer une classe `GzipRoute` personnalisée { #create-a-custom-gziproute-class }
+
+Ensuite, nous créons une sous-classe personnalisée de `fastapi.routing.APIRoute` qui utilisera `GzipRequest`.
+
+Cette fois, elle va surcharger la méthode `APIRoute.get_route_handler()`.
+
+Cette méthode renvoie une fonction. Et c'est cette fonction qui recevra une requête et retournera une réponse.
+
+Ici, nous l'utilisons pour créer une `GzipRequest` à partir de la requête originale.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[19:27] *}
+
+/// note | Détails techniques
+
+Un `Request` possède un attribut `request.scope`, qui n'est qu'un `dict` Python contenant les métadonnées liées à la requête.
+
+Un `Request` a également un `request.receive`, qui est une fonction pour « recevoir » le corps de la requête.
+
+Le `dict` `scope` et la fonction `receive` font tous deux partie de la spécification ASGI.
+
+Et ces deux éléments, `scope` et `receive`, sont ce dont on a besoin pour créer une nouvelle instance de `Request`.
+
+Pour en savoir plus sur `Request`, consultez [la documentation de Starlette sur les requêtes](https://www.starlette.dev/requests/).
+
+///
+
+La seule chose que fait différemment la fonction renvoyée par `GzipRequest.get_route_handler`, c'est de convertir la `Request` en `GzipRequest`.
+
+Ce faisant, notre `GzipRequest` se chargera de décompresser les données (si nécessaire) avant de les transmettre à nos *chemins d'accès*.
+
+Après cela, toute la logique de traitement est identique.
+
+Mais grâce à nos modifications dans `GzipRequest.body`, le corps de la requête sera automatiquement décompressé lorsque **FastAPI** le chargera, si nécessaire.
+
+## Accéder au corps de la requête dans un gestionnaire d'exceptions { #accessing-the-request-body-in-an-exception-handler }
+
+/// tip | Astuce
+
+Pour résoudre ce même problème, il est probablement beaucoup plus simple d'utiliser `body` dans un gestionnaire personnalisé pour `RequestValidationError` ([Gérer les erreurs](../tutorial/handling-errors.md#use-the-requestvalidationerror-body)).
+
+Mais cet exemple reste valable et montre comment interagir avec les composants internes.
+
+///
+
+Nous pouvons également utiliser cette même approche pour accéder au corps de la requête dans un gestionnaire d'exceptions.
+
+Il suffit de traiter la requête dans un bloc `try`/`except` :
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[14,16] *}
+
+Si une exception se produit, l'instance de `Request` sera toujours dans la portée, ce qui nous permet de lire et d'utiliser le corps de la requête lors du traitement de l'erreur :
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[17:19] *}
+
+## Utiliser une classe `APIRoute` personnalisée dans un routeur { #custom-apiroute-class-in-a-router }
+
+Vous pouvez également définir le paramètre `route_class` d'un `APIRouter` :
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[26] *}
+
+Dans cet exemple, les *chemins d'accès* sous le `router` utiliseront la classe personnalisée `TimedRoute`, et auront un en-tête supplémentaire `X-Response-Time` dans la réponse avec le temps nécessaire pour générer la réponse :
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[13:20] *}
diff --git a/docs/fr/docs/how-to/extending-openapi.md b/docs/fr/docs/how-to/extending-openapi.md
new file mode 100644
index 0000000000000..bdf4eeba93f19
--- /dev/null
+++ b/docs/fr/docs/how-to/extending-openapi.md
@@ -0,0 +1,80 @@
+# Étendre OpenAPI { #extending-openapi }
+
+Il existe des cas où vous pouvez avoir besoin de modifier le schéma OpenAPI généré.
+
+Dans cette section, vous verrez comment faire.
+
+## Le processus normal { #the-normal-process }
+
+Le processus normal (par défaut) est le suivant.
+
+Une application (instance) `FastAPI` a une méthode `.openapi()` censée retourner le schéma OpenAPI.
+
+Lors de la création de l'objet application, un *chemin d'accès* pour `/openapi.json` (ou pour l'URL que vous avez définie dans votre `openapi_url`) est enregistré.
+
+Il renvoie simplement une réponse JSON avec le résultat de la méthode `.openapi()` de l'application.
+
+Par défaut, la méthode `.openapi()` vérifie la propriété `.openapi_schema` pour voir si elle contient des données et les renvoie.
+
+Sinon, elle les génère à l'aide de la fonction utilitaire `fastapi.openapi.utils.get_openapi`.
+
+Et cette fonction `get_openapi()` reçoit comme paramètres :
+
+* `title` : Le titre OpenAPI, affiché dans les documents.
+* `version` : La version de votre API, p. ex. `2.5.0`.
+* `openapi_version` : La version de la spécification OpenAPI utilisée. Par défaut, la plus récente : `3.1.0`.
+* `summary` : Un court résumé de l'API.
+* `description` : La description de votre API ; elle peut inclure du markdown et sera affichée dans la documentation.
+* `routes` : Une liste de routes ; chacune correspond à un *chemin d'accès* enregistré. Elles sont extraites de `app.routes`.
+
+/// info
+
+Le paramètre `summary` est disponible à partir d'OpenAPI 3.1.0, pris en charge par FastAPI 0.99.0 et versions ultérieures.
+
+///
+
+## Remplacer les valeurs par défaut { #overriding-the-defaults }
+
+En vous appuyant sur les informations ci-dessus, vous pouvez utiliser la même fonction utilitaire pour générer le schéma OpenAPI et remplacer chaque partie dont vous avez besoin.
+
+Par exemple, ajoutons [l’extension OpenAPI de ReDoc pour inclure un logo personnalisé](https://github.com/Rebilly/ReDoc/blob/master/docs/redoc-vendor-extensions.md#x-logo).
+
+### **FastAPI** normal { #normal-fastapi }
+
+Tout d’abord, écrivez votre application **FastAPI** comme d’habitude :
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[1,4,7:9] *}
+
+### Générer le schéma OpenAPI { #generate-the-openapi-schema }
+
+Ensuite, utilisez la même fonction utilitaire pour générer le schéma OpenAPI, dans une fonction `custom_openapi()` :
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[2,15:21] *}
+
+### Modifier le schéma OpenAPI { #modify-the-openapi-schema }
+
+Vous pouvez maintenant ajouter l’extension ReDoc, en ajoutant un `x-logo` personnalisé à l’« objet » `info` dans le schéma OpenAPI :
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[22:24] *}
+
+### Mettre en cache le schéma OpenAPI { #cache-the-openapi-schema }
+
+Vous pouvez utiliser la propriété `.openapi_schema` comme « cache » pour stocker votre schéma généré.
+
+Ainsi, votre application n’aura pas à générer le schéma à chaque fois qu’un utilisateur ouvre les documents de votre API.
+
+Il ne sera généré qu’une seule fois, puis le même schéma en cache sera utilisé pour les requêtes suivantes.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[13:14,25:26] *}
+
+### Remplacer la méthode { #override-the-method }
+
+Vous pouvez maintenant remplacer la méthode `.openapi()` par votre nouvelle fonction.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[29] *}
+
+### Vérifier { #check-it }
+
+Une fois que vous allez sur [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc), vous verrez que vous utilisez votre logo personnalisé (dans cet exemple, le logo de **FastAPI**) :
+
+
diff --git a/docs/fr/docs/how-to/general.md b/docs/fr/docs/how-to/general.md
new file mode 100644
index 0000000000000..93ebf8953a34c
--- /dev/null
+++ b/docs/fr/docs/how-to/general.md
@@ -0,0 +1,43 @@
+# Général - Guides pratiques - Recettes { #general-how-to-recipes }
+
+Voici plusieurs renvois vers d'autres endroits dans les documents, pour des questions générales ou fréquentes.
+
+## Filtrer des données - Sécurité { #filter-data-security }
+
+Pour vous assurer que vous ne renvoyez pas plus de données que nécessaire, lisez les documents [Tutoriel - Modèle de réponse - Type de retour](../tutorial/response-model.md).
+
+## Optimiser la performance des réponses - Modèle de réponse - Type de retour { #optimize-response-performance-response-model-return-type }
+
+Pour optimiser la performance lors du renvoi de données JSON, utilisez un type de retour ou un modèle de réponse ; de cette façon, Pydantic prendra en charge la sérialisation en JSON côté Rust, sans passer par Python. Pour en savoir plus, lisez les documents [Tutoriel - Modèle de réponse - Type de retour](../tutorial/response-model.md).
+
+## Étiquettes de documentation - OpenAPI { #documentation-tags-openapi }
+
+Pour ajouter des étiquettes à vos *chemins d'accès* et les regrouper dans l'interface utilisateur de la documentation, lisez les documents [Tutoriel - Configurations de chemin d'accès - Tags](../tutorial/path-operation-configuration.md#tags).
+
+## Résumé et description de la documentation - OpenAPI { #documentation-summary-and-description-openapi }
+
+Pour ajouter un résumé et une description à vos *chemins d'accès* et les afficher dans l'interface utilisateur de la documentation, lisez les documents [Tutoriel - Configurations de chemin d'accès - Résumé et description](../tutorial/path-operation-configuration.md#summary-and-description).
+
+## Description de la réponse dans la documentation - OpenAPI { #documentation-response-description-openapi }
+
+Pour définir la description de la réponse, affichée dans l'interface utilisateur de la documentation, lisez les documents [Tutoriel - Configurations de chemin d'accès - Description de la réponse](../tutorial/path-operation-configuration.md#response-description).
+
+## Déprécier un *chemin d'accès* dans la documentation - OpenAPI { #documentation-deprecate-a-path-operation-openapi }
+
+Pour déprécier un *chemin d'accès* et l'indiquer dans l'interface utilisateur de la documentation, lisez les documents [Tutoriel - Configurations de chemin d'accès - Dépréciation](../tutorial/path-operation-configuration.md#deprecate-a-path-operation).
+
+## Convertir n'importe quelles données au format compatible JSON { #convert-any-data-to-json-compatible }
+
+Pour convertir des données vers un format compatible JSON, lisez les documents [Tutoriel - Encodeur compatible JSON](../tutorial/encoder.md).
+
+## Métadonnées OpenAPI - Documentation { #openapi-metadata-docs }
+
+Pour ajouter des métadonnées à votre schéma OpenAPI, y compris une licence, une version, un contact, etc., lisez les documents [Tutoriel - Métadonnées et URLs de la documentation](../tutorial/metadata.md).
+
+## URL OpenAPI personnalisée { #openapi-custom-url }
+
+Pour personnaliser l'URL OpenAPI (ou la supprimer), lisez les documents [Tutoriel - Métadonnées et URLs de la documentation](../tutorial/metadata.md#openapi-url).
+
+## URL de la documentation OpenAPI { #openapi-docs-urls }
+
+Pour mettre à jour les URL utilisées pour les interfaces utilisateur de documentation générées automatiquement, lisez les documents [Tutoriel - Métadonnées et URLs de la documentation](../tutorial/metadata.md#docs-urls).
diff --git a/docs/fr/docs/how-to/graphql.md b/docs/fr/docs/how-to/graphql.md
new file mode 100644
index 0000000000000..912608a981484
--- /dev/null
+++ b/docs/fr/docs/how-to/graphql.md
@@ -0,0 +1,60 @@
+# GraphQL { #graphql }
+
+Comme **FastAPI** est basé sur la norme **ASGI**, il est très facile d'intégrer toute bibliothèque **GraphQL** également compatible avec ASGI.
+
+Vous pouvez combiner des *chemins d'accès* FastAPI classiques avec GraphQL dans la même application.
+
+/// tip | Astuce
+
+**GraphQL** résout des cas d'utilisation très spécifiques.
+
+Il présente des **avantages** et des **inconvénients** par rapport aux **API web** classiques.
+
+Assurez-vous d'évaluer si les **bénéfices** pour votre cas d'utilisation compensent les **inconvénients**. 🤓
+
+///
+
+## Bibliothèques GraphQL { #graphql-libraries }
+
+Voici quelques bibliothèques **GraphQL** qui prennent en charge **ASGI**. Vous pouvez les utiliser avec **FastAPI** :
+
+* [Strawberry](https://strawberry.rocks/) 🍓
+ * Avec [la documentation pour FastAPI](https://strawberry.rocks/docs/integrations/fastapi)
+* [Ariadne](https://ariadnegraphql.org/)
+ * Avec [la documentation pour FastAPI](https://ariadnegraphql.org/docs/fastapi-integration)
+* [Tartiflette](https://tartiflette.io/)
+ * Avec [Tartiflette ASGI](https://tartiflette.github.io/tartiflette-asgi/) pour fournir l'intégration ASGI
+* [Graphene](https://graphene-python.org/)
+ * Avec [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3)
+
+## GraphQL avec Strawberry { #graphql-with-strawberry }
+
+Si vous avez besoin ou souhaitez travailler avec **GraphQL**, [**Strawberry**](https://strawberry.rocks/) est la bibliothèque **recommandée** car sa conception est la plus proche de celle de **FastAPI**, tout est basé sur des **annotations de type**.
+
+Selon votre cas d'utilisation, vous pourriez préférer une autre bibliothèque, mais si vous me le demandiez, je vous suggérerais probablement d'essayer **Strawberry**.
+
+Voici un petit aperçu de la manière dont vous pouvez intégrer Strawberry avec FastAPI :
+
+{* ../../docs_src/graphql_/tutorial001_py310.py hl[3,22,25] *}
+
+Vous pouvez en apprendre davantage sur Strawberry dans la [documentation de Strawberry](https://strawberry.rocks/).
+
+Et également la documentation sur [Strawberry avec FastAPI](https://strawberry.rocks/docs/integrations/fastapi).
+
+## Ancien `GraphQLApp` de Starlette { #older-graphqlapp-from-starlette }
+
+Les versions précédentes de Starlette incluaient une classe `GraphQLApp` pour s'intégrer à [Graphene](https://graphene-python.org/).
+
+Elle a été dépréciée dans Starlette, mais si vous avez du code qui l'utilisait, vous pouvez facilement **migrer** vers [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3), qui couvre le même cas d'utilisation et propose une **interface presque identique**.
+
+/// tip | Astuce
+
+Si vous avez besoin de GraphQL, je vous recommande tout de même de regarder [Strawberry](https://strawberry.rocks/), car il est basé sur des annotations de type plutôt que sur des classes et types personnalisés.
+
+///
+
+## En savoir plus { #learn-more }
+
+Vous pouvez en apprendre davantage sur **GraphQL** dans la [documentation officielle de GraphQL](https://graphql.org/).
+
+Vous pouvez également en lire davantage sur chacune des bibliothèques décrites ci-dessus via leurs liens.
diff --git a/docs/fr/docs/how-to/index.md b/docs/fr/docs/how-to/index.md
new file mode 100644
index 0000000000000..62e7d0457255a
--- /dev/null
+++ b/docs/fr/docs/how-to/index.md
@@ -0,0 +1,13 @@
+# Comment faire - Recettes { #how-to-recipes }
+
+Vous trouverez ici différentes recettes ou des guides « comment faire » pour **plusieurs sujets**.
+
+La plupart de ces idées sont plus ou moins **indépendantes**, et dans la plupart des cas vous n'avez besoin de les étudier que si elles s'appliquent directement à **votre projet**.
+
+Si quelque chose vous paraît intéressant et utile pour votre projet, allez-y et consultez-le ; sinon, vous pouvez probablement simplement les ignorer.
+
+/// tip | Astuce
+
+Si vous voulez **apprendre FastAPI** de façon structurée (recommandé), allez lire le [Tutoriel - Guide utilisateur](../tutorial/index.md) chapitre par chapitre à la place.
+
+///
diff --git a/docs/fr/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/fr/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
new file mode 100644
index 0000000000000..99d68ba817fe1
--- /dev/null
+++ b/docs/fr/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -0,0 +1,135 @@
+# Migrer de Pydantic v1 à Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 }
+
+Si vous avez une ancienne application FastAPI, vous utilisez peut-être Pydantic version 1.
+
+FastAPI version 0.100.0 prenait en charge soit Pydantic v1 soit v2. Il utilisait celle que vous aviez installée.
+
+FastAPI version 0.119.0 a introduit une prise en charge partielle de Pydantic v1 depuis l'intérieur de Pydantic v2 (comme `pydantic.v1`), pour faciliter la migration vers v2.
+
+FastAPI 0.126.0 a supprimé la prise en charge de Pydantic v1, tout en continuant à prendre en charge `pydantic.v1` pendant un certain temps.
+
+/// warning | Alertes
+
+L'équipe Pydantic a arrêté la prise en charge de Pydantic v1 pour les dernières versions de Python, à partir de **Python 3.14**.
+
+Cela inclut `pydantic.v1`, qui n'est plus pris en charge en Python 3.14 et versions ultérieures.
+
+Si vous souhaitez utiliser les dernières fonctionnalités de Python, vous devez vous assurer que vous utilisez Pydantic v2.
+
+///
+
+Si vous avez une ancienne application FastAPI avec Pydantic v1, je vais vous montrer comment la migrer vers Pydantic v2, et les **fonctionnalités de FastAPI 0.119.0** pour vous aider à une migration progressive.
+
+## Guide officiel { #official-guide }
+
+Pydantic propose un [Guide de migration](https://docs.pydantic.dev/latest/migration/) officiel de la v1 à la v2.
+
+Il inclut aussi ce qui a changé, comment les validations sont désormais plus correctes et strictes, les pièges possibles, etc.
+
+Vous pouvez le lire pour mieux comprendre ce qui a changé.
+
+## Tests { #tests }
+
+Vous devez vous assurer d'avoir des [tests](../tutorial/testing.md) pour votre application et de les exécuter en intégration continue (CI).
+
+De cette façon, vous pouvez effectuer la mise à niveau et vous assurer que tout fonctionne toujours comme prévu.
+
+## `bump-pydantic` { #bump-pydantic }
+
+Dans de nombreux cas, lorsque vous utilisez des modèles Pydantic classiques sans personnalisations, vous pourrez automatiser la majeure partie du processus de migration de Pydantic v1 à Pydantic v2.
+
+Vous pouvez utiliser [`bump-pydantic`](https://github.com/pydantic/bump-pydantic) de la même équipe Pydantic.
+
+Cet outil vous aidera à modifier automatiquement la majeure partie du code à adapter.
+
+Après cela, vous pouvez exécuter les tests et vérifier que tout fonctionne. Si c'est le cas, vous avez terminé. 😎
+
+## Pydantic v1 dans v2 { #pydantic-v1-in-v2 }
+
+Pydantic v2 inclut tout Pydantic v1 sous la forme du sous-module `pydantic.v1`. Mais cela n'est plus pris en charge dans les versions au-delà de Python 3.13.
+
+Cela signifie que vous pouvez installer la dernière version de Pydantic v2 et importer/utiliser les anciens composants de Pydantic v1 depuis ce sous-module, comme si vous aviez l'ancien Pydantic v1 installé.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}
+
+### Prise en charge de FastAPI pour Pydantic v1 dans v2 { #fastapi-support-for-pydantic-v1-in-v2 }
+
+Depuis FastAPI 0.119.0, il existe également une prise en charge partielle de Pydantic v1 depuis l'intérieur de Pydantic v2, pour faciliter la migration vers v2.
+
+Vous pouvez donc mettre à niveau Pydantic vers la dernière version 2 et modifier les imports pour utiliser le sous-module `pydantic.v1`, et dans de nombreux cas cela fonctionnera tel quel.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py hl[2,5,15] *}
+
+/// warning | Alertes
+
+Gardez à l'esprit que, puisque l'équipe Pydantic ne prend plus en charge Pydantic v1 dans les versions récentes de Python à partir de Python 3.14, l'utilisation de `pydantic.v1` n'est pas non plus prise en charge en Python 3.14 et versions ultérieures.
+
+///
+
+### Pydantic v1 et v2 dans la même application { #pydantic-v1-and-v2-on-the-same-app }
+
+Pydantic ne prend pas en charge le fait d'avoir un modèle Pydantic v2 contenant des champs eux-mêmes définis comme des modèles Pydantic v1, et inversement.
+
+```mermaid
+graph TB
+ subgraph "❌ Not Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+... mais vous pouvez avoir des modèles séparés utilisant Pydantic v1 et v2 dans la même application.
+
+```mermaid
+graph TB
+ subgraph "✅ Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+Dans certains cas, il est même possible d'avoir des modèles Pydantic v1 et v2 dans le même **chemin d'accès** de votre application FastAPI :
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}
+
+Dans l'exemple ci-dessus, le modèle d'entrée est un modèle Pydantic v1 et le modèle de sortie (défini dans `response_model=ItemV2`) est un modèle Pydantic v2.
+
+### Paramètres Pydantic v1 { #pydantic-v1-parameters }
+
+Si vous devez utiliser certains des outils spécifiques à FastAPI pour les paramètres comme `Body`, `Query`, `Form`, etc., avec des modèles Pydantic v1, vous pouvez les importer depuis `fastapi.temp_pydantic_v1_params` le temps de terminer la migration vers Pydantic v2 :
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py hl[4,18] *}
+
+### Migrer par étapes { #migrate-in-steps }
+
+/// tip | Astuce
+
+Essayez d'abord avec `bump-pydantic` ; si vos tests passent et que cela fonctionne, vous avez tout terminé en une seule commande. ✨
+
+///
+
+Si `bump-pydantic` ne fonctionne pas pour votre cas d'usage, vous pouvez utiliser la prise en charge des modèles Pydantic v1 et v2 dans la même application pour effectuer la migration vers Pydantic v2 progressivement.
+
+Vous pouvez d'abord mettre à niveau Pydantic pour utiliser la dernière version 2 et modifier les imports pour utiliser `pydantic.v1` pour tous vos modèles.
+
+Ensuite, vous pouvez commencer à migrer vos modèles de Pydantic v1 vers v2 par groupes, par étapes progressives. 🚶
diff --git a/docs/fr/docs/how-to/separate-openapi-schemas.md b/docs/fr/docs/how-to/separate-openapi-schemas.md
new file mode 100644
index 0000000000000..fd767d7388ae6
--- /dev/null
+++ b/docs/fr/docs/how-to/separate-openapi-schemas.md
@@ -0,0 +1,102 @@
+# Séparer les schémas OpenAPI pour l'entrée et la sortie ou non { #separate-openapi-schemas-for-input-and-output-or-not }
+
+Depuis la sortie de **Pydantic v2**, l'OpenAPI généré est un peu plus précis et **correct** qu'avant. 😎
+
+En fait, dans certains cas, il y aura même **deux schémas JSON** dans OpenAPI pour le même modèle Pydantic, pour l'entrée et pour la sortie, selon s'ils ont des **valeurs par défaut**.
+
+Voyons comment cela fonctionne et comment le modifier si vous devez le faire.
+
+## Utiliser des modèles Pydantic pour l'entrée et la sortie { #pydantic-models-for-input-and-output }
+
+Supposons que vous ayez un modèle Pydantic avec des valeurs par défaut, comme celui‑ci :
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *}
+
+### Modèle pour l'entrée { #model-for-input }
+
+Si vous utilisez ce modèle en entrée comme ici :
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *}
+
+... alors, le champ `description` ne sera **pas requis**. Parce qu'il a une valeur par défaut de `None`.
+
+### Modèle d'entrée dans les documents { #input-model-in-docs }
+
+Vous pouvez le confirmer dans les documents, le champ `description` n'a pas d'**astérisque rouge**, il n'est pas indiqué comme requis :
+
+
+
+
+
+
+Framework FastAPI, haute performance, facile à apprendre, rapide à coder, prêt pour la production
--- -**Documentation** : https://fastapi.tiangolo.com +**Documentation** : [https://fastapi.tiangolo.com/fr](https://fastapi.tiangolo.com/fr) -**Code Source** : https://github.com/tiangolo/fastapi +**Code Source** : [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi) --- -FastAPI est un framework web moderne et rapide (haute performance) pour la création d'API avec Python 3.7+, basé sur les annotations de type standard de Python. +FastAPI est un framework web moderne et rapide (haute performance) pour la création d'API avec Python, basé sur les annotations de type standard de Python. Les principales fonctionnalités sont : -* **Rapidité** : De très hautes performances, au niveau de **NodeJS** et **Go** (grâce à Starlette et Pydantic). [L'un des frameworks Python les plus rapides](#performance). -* **Rapide à coder** : Augmente la vitesse de développement des fonctionnalités d'environ 200 % à 300 %. * -* **Moins de bugs** : Réduit d'environ 40 % les erreurs induites par le développeur. * -* **Intuitif** : Excellente compatibilité avec les IDE. Complétion complète. Moins de temps passé à déboguer. -* **Facile** : Conçu pour être facile à utiliser et à apprendre. Moins de temps passé à lire la documentation. -* **Concis** : Diminue la duplication de code. De nombreuses fonctionnalités liées à la déclaration de chaque paramètre. Moins de bugs. -* **Robuste** : Obtenez un code prêt pour la production. Avec une documentation interactive automatique. -* **Basé sur des normes** : Basé sur (et entièrement compatible avec) les standards ouverts pour les APIs : OpenAPI (précédemment connu sous le nom de Swagger) et JSON Schema. +* **Rapide** : très hautes performances, au niveau de **NodeJS** et **Go** (grâce à Starlette et Pydantic). [L'un des frameworks Python les plus rapides](#performance). +* **Rapide à coder** : augmente la vitesse de développement des fonctionnalités d'environ 200 % à 300 %. * +* **Moins de bugs** : réduit d'environ 40 % les erreurs induites par le développeur. * +* **Intuitif** : excellente compatibilité avec les éditeurs. Autocomplétion partout. Moins de temps passé à déboguer. +* **Facile** : conçu pour être facile à utiliser et à apprendre. Moins de temps passé à lire les documents. +* **Concis** : diminue la duplication de code. Plusieurs fonctionnalités à partir de chaque déclaration de paramètre. Moins de bugs. +* **Robuste** : obtenez un code prêt pour la production. Avec une documentation interactive automatique. +* **Basé sur des normes** : basé sur (et entièrement compatible avec) les standards ouverts pour les APIs : [OpenAPI](https://github.com/OAI/OpenAPI-Specification) (précédemment connu sous le nom de Swagger) et [JSON Schema](https://json-schema.org/). * estimation basée sur des tests d'une équipe de développement interne, construisant des applications de production. -## Sponsors +## Sponsors { #sponsors } -{% if sponsors %} +### Sponsor clé de voûte { #keystone-sponsor } + +{% for sponsor in sponsors.keystone -%} +
-## Prérequis
+## **Typer**, le FastAPI des CLIs { #typer-the-fastapi-of-clis }
-Python 3.7+
+async def ...async def...uvicorn main:app --reload ...fastapi dev...email_validator - pour la validation des adresses email.
+🐔 Ready the chicken! Your app is ready at https://myapp.fastapicloud.dev
+```
+
+requests - Obligatoire si vous souhaitez utiliser `TestClient`.
-* jinja2 - Obligatoire si vous souhaitez utiliser la configuration de template par défaut.
-* python-multipart - Obligatoire si vous souhaitez supporter le "décodage" de formulaire avec `request.form()`.
-* itsdangerous - Obligatoire pour la prise en charge de `SessionMiddleware`.
-* pyyaml - Obligatoire pour le support `SchemaGenerator` de Starlette (vous n'en avez probablement pas besoin avec FastAPI).
-* ujson - Obligatoire si vous souhaitez utiliser `UJSONResponse`.
+* [`httpx`](https://www.python-httpx.org) - Obligatoire si vous souhaitez utiliser le `TestClient`.
+* [`jinja2`](https://jinja.palletsprojects.com) - Obligatoire si vous souhaitez utiliser la configuration de template par défaut.
+* [`python-multipart`](https://github.com/Kludex/python-multipart) - Obligatoire si vous souhaitez prendre en charge l’« parsing » de formulaires avec `request.form()`.
+
+Utilisées par FastAPI :
+
+* [`uvicorn`](https://www.uvicorn.dev) - pour le serveur qui charge et sert votre application. Cela inclut `uvicorn[standard]`, qui comprend certaines dépendances (par ex. `uvloop`) nécessaires pour une haute performance.
+* `fastapi-cli[standard]` - pour fournir la commande `fastapi`.
+ * Cela inclut `fastapi-cloud-cli`, qui vous permet de déployer votre application FastAPI sur [FastAPI Cloud](https://fastapicloud.com).
+
+### Sans les dépendances `standard` { #without-standard-dependencies }
+
+Si vous ne souhaitez pas inclure les dépendances optionnelles `standard`, vous pouvez installer avec `pip install fastapi` au lieu de `pip install "fastapi[standard]"`.
+
+### Sans `fastapi-cloud-cli` { #without-fastapi-cloud-cli }
+
+Si vous souhaitez installer FastAPI avec les dépendances standard mais sans `fastapi-cloud-cli`, vous pouvez installer avec `pip install "fastapi[standard-no-fastapi-cloud-cli]"`.
+
+### Dépendances optionnelles supplémentaires { #additional-optional-dependencies }
+
+Il existe des dépendances supplémentaires que vous pourriez vouloir installer.
+
+Dépendances optionnelles supplémentaires pour Pydantic :
-Utilisées par FastAPI / Starlette :
+* [`pydantic-settings`](https://docs.pydantic.dev/latest/usage/pydantic_settings/) - pour la gestion des paramètres.
+* [`pydantic-extra-types`](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/) - pour des types supplémentaires à utiliser avec Pydantic.
-* uvicorn - Pour le serveur qui charge et sert votre application.
-* orjson - Obligatoire si vous voulez utiliser `ORJSONResponse`.
+Dépendances optionnelles supplémentaires pour FastAPI :
-Vous pouvez tout installer avec `pip install fastapi[all]`.
+* [`orjson`](https://github.com/ijl/orjson) - Obligatoire si vous souhaitez utiliser `ORJSONResponse`.
+* [`ujson`](https://github.com/esnme/ultrajson) - Obligatoire si vous souhaitez utiliser `UJSONResponse`.
-## Licence
+## Licence { #license }
Ce projet est soumis aux termes de la licence MIT.
diff --git a/docs/fr/docs/learn/index.md b/docs/fr/docs/learn/index.md
new file mode 100644
index 0000000000000..e595ecf789051
--- /dev/null
+++ b/docs/fr/docs/learn/index.md
@@ -0,0 +1,5 @@
+# Apprendre { #learn }
+
+Voici les sections introductives et les tutoriels pour apprendre **FastAPI**.
+
+Vous pouvez considérer ceci comme un **livre**, un **cours**, la méthode **officielle** et recommandée pour apprendre FastAPI. 😎
diff --git a/docs/fr/docs/project-generation.md b/docs/fr/docs/project-generation.md
index c58d2cd2bc300..e0636bfe55a9d 100644
--- a/docs/fr/docs/project-generation.md
+++ b/docs/fr/docs/project-generation.md
@@ -1,84 +1,28 @@
-# Génération de projets - Modèle
-
-Vous pouvez utiliser un générateur de projet pour commencer, qui réalisera pour vous la mise en place de bases côté architecture globale, sécurité, base de données et premières routes d'API.
-
-Un générateur de projet fera toujours une mise en place très subjective que vous devriez modifier et adapter suivant vos besoins, mais cela reste un bon point de départ pour vos projets.
-
-## Full Stack FastAPI PostgreSQL
-
-GitHub : https://github.com/tiangolo/full-stack-fastapi-postgresql
-
-### Full Stack FastAPI PostgreSQL - Fonctionnalités
-
-* Intégration **Docker** complète (basée sur Docker).
-* Déploiement Docker en mode Swarm
-* Intégration **Docker Compose** et optimisation pour développement local.
-* Serveur web Python **prêt au déploiement** utilisant Uvicorn et Gunicorn.
-* Backend Python **FastAPI** :
- * **Rapide** : Très hautes performances, comparables à **NodeJS** ou **Go** (grâce à Starlette et Pydantic).
- * **Intuitif** : Excellent support des éditeurs. Complétion partout. Moins de temps passé à déboguer.
- * **Facile** : Fait pour être facile à utiliser et apprendre. Moins de temps passé à lire de la documentation.
- * **Concis** : Minimise la duplication de code. Plusieurs fonctionnalités à chaque déclaration de paramètre.
- * **Robuste** : Obtenez du code prêt pour être utilisé en production. Avec de la documentation automatique interactive.
- * **Basé sur des normes** : Basé sur (et totalement compatible avec) les normes ouvertes pour les APIs : OpenAPI et JSON Schema.
- * **Et bien d'autres fonctionnalités** comme la validation automatique, la sérialisation, l'authentification avec OAuth2 JWT tokens, etc.
-* Hashage de **mots de passe sécurisé** par défaut.
-* Authentification par **jetons JWT**.
-* Modèles **SQLAlchemy** (indépendants des extensions Flask, afin qu'ils puissent être utilisés directement avec des *workers* Celery).
-* Modèle de démarrages basiques pour les utilisateurs (à modifier et supprimer au besoin).
-* Migrations **Alembic**.
-* **CORS** (partage des ressources entre origines multiples, ou *Cross Origin Resource Sharing*).
-* *Worker* **Celery** pouvant importer et utiliser les modèles et le code du reste du backend.
-* Tests du backend REST basés sur **Pytest**, intégrés dans Docker, pour que vous puissiez tester toutes les interactions de l'API indépendamment de la base de données. Étant exécutés dans Docker, les tests peuvent utiliser un nouvel entrepôt de données créé de zéro à chaque fois (vous pouvez donc utiliser ElasticSearch, MongoDB, CouchDB, etc. et juste tester que l'API fonctionne).
-* Intégration Python facile avec **Jupyter Kernels** pour le développement à distance ou intra-Docker avec des extensions comme Atom Hydrogen ou Visual Studio Code Jupyter.
-* Frontend **Vue** :
- * Généré avec Vue CLI.
- * Gestion de l'**Authentification JWT**.
- * Page de connexion.
- * Après la connexion, page de tableau de bord principal.
- * Tableau de bord principal avec création et modification d'utilisateurs.
- * Modification de ses propres caractéristiques utilisateur.
- * **Vuex**.
- * **Vue-router**.
- * **Vuetify** pour de magnifiques composants *material design*.
- * **TypeScript**.
- * Serveur Docker basé sur **Nginx** (configuré pour être facilement manipulé avec Vue-router).
- * Utilisation de *Docker multi-stage building*, pour ne pas avoir besoin de sauvegarder ou *commit* du code compilé.
- * Tests frontend exécutés à la compilation (pouvant être désactivés).
- * Fait aussi modulable que possible, pour pouvoir fonctionner comme tel, tout en pouvant être utilisé qu'en partie grâce à Vue CLI.
-* **PGAdmin** pour les bases de données PostgreSQL, facilement modifiable pour utiliser PHPMYAdmin ou MySQL.
-* **Flower** pour la surveillance de tâches Celery.
-* Équilibrage de charge entre le frontend et le backend avec **Traefik**, afin de pouvoir avoir les deux sur le même domaine, séparés par chemins, mais servis par différents conteneurs.
-* Intégration Traefik, comprenant la génération automatique de certificat **HTTPS** Let's Encrypt.
-* GitLab **CI** (intégration continue), comprenant des tests pour le frontend et le backend.
-
-## Full Stack FastAPI Couchbase
-
-GitHub : https://github.com/tiangolo/full-stack-fastapi-couchbase
-
-⚠️ **ATTENTION** ⚠️
-
-Si vous démarrez un nouveau projet de zéro, allez voir les alternatives au début de cette page.
-
-Par exemple, le générateur de projet Full Stack FastAPI PostgreSQL peut être une meilleure alternative, étant activement maintenu et utilisé et comprenant toutes les nouvelles fonctionnalités et améliorations.
-
-Vous êtes toujours libre d'utiliser le générateur basé sur Couchbase si vous le voulez, cela devrait probablement fonctionner correctement, et si vous avez déjà un projet généré en utilisant ce dernier, cela devrait fonctionner aussi (et vous l'avez déjà probablement mis à jour suivant vos besoins).
-
-Vous pouvez en apprendre plus dans la documentation du dépôt GithHub.
-
-## Full Stack FastAPI MongoDB
-
-...viendra surement plus tard, suivant le temps que j'ai. 😅 🎉
-
-## Modèles d'apprentissage automatique avec spaCy et FastAPI
-
-GitHub : https://github.com/microsoft/cookiecutter-spacy-fastapi
-
-## Modèles d'apprentissage automatique avec spaCy et FastAPI - Fonctionnalités
-
-* Intégration d'un modèle NER **spaCy**.
-* Formatage de requête pour **Azure Cognitive Search**.
-* Serveur Python web **prêt à utiliser en production** utilisant Uvicorn et Gunicorn.
-* Déploiement CI/CD Kubernetes pour **Azure DevOps** (AKS).
-* **Multilangues**. Choisissez facilement l'une des langues intégrées à spaCy durant la mise en place du projet.
-* **Facilement généralisable** à d'autres bibliothèques similaires (Pytorch, Tensorflow), et non juste spaCy.
+# Modèle Full Stack FastAPI { #full-stack-fastapi-template }
+
+Les modèles, bien qu'ils soient généralement livrés avec une configuration spécifique, sont conçus pour être flexibles et personnalisables. Cela vous permet de les modifier et de les adapter aux exigences de votre projet, ce qui en fait un excellent point de départ. 🏁
+
+Vous pouvez utiliser ce modèle pour démarrer, car il inclut une grande partie de la configuration initiale, la sécurité, la base de données et quelques endpoints d'API déjà prêts pour vous.
+
+Dépôt GitHub : [Modèle Full Stack FastAPI](https://github.com/tiangolo/full-stack-fastapi-template)
+
+## Modèle Full Stack FastAPI - Pile technologique et fonctionnalités { #full-stack-fastapi-template-technology-stack-and-features }
+
+- ⚡ [**FastAPI**](https://fastapi.tiangolo.com/fr) pour l'API backend Python.
+ - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) pour les interactions avec la base de données SQL en Python (ORM).
+ - 🔍 [Pydantic](https://docs.pydantic.dev), utilisé par FastAPI, pour la validation des données et la gestion des paramètres.
+ - 💾 [PostgreSQL](https://www.postgresql.org) comme base de données SQL.
+- 🚀 [React](https://react.dev) pour le frontend.
+ - 💃 Utilisation de TypeScript, des hooks, de Vite et d'autres éléments d'un stack frontend moderne.
+ - 🎨 [Tailwind CSS](https://tailwindcss.com) et [shadcn/ui](https://ui.shadcn.com) pour les composants frontend.
+ - 🤖 Un client frontend généré automatiquement.
+ - 🧪 [Playwright](https://playwright.dev) pour les tests de bout en bout.
+ - 🦇 Prise en charge du mode sombre.
+- 🐋 [Docker Compose](https://www.docker.com) pour le développement et la production.
+- 🔒 Hachage sécurisé des mots de passe par défaut.
+- 🔑 Authentification JWT (JSON Web Token).
+- 📫 Récupération de mot de passe par e-mail.
+- ✅ Tests avec [Pytest](https://pytest.org).
+- 📞 [Traefik](https://traefik.io) comme proxy inverse / répartiteur de charge.
+- 🚢 Instructions de déploiement avec Docker Compose, y compris la configuration d'un proxy Traefik frontal pour gérer les certificats HTTPS automatiques.
+- 🏭 CI (intégration continue) et CD (déploiement continu) basés sur GitHub Actions.
diff --git a/docs/fr/docs/python-types.md b/docs/fr/docs/python-types.md
index f49fbafd364d6..97230b7b92562 100644
--- a/docs/fr/docs/python-types.md
+++ b/docs/fr/docs/python-types.md
@@ -1,71 +1,68 @@
-# Introduction aux Types Python
+# Introduction aux types Python { #python-types-intro }
-Python supporte des annotations de type (ou *type hints*) optionnelles.
+Python prend en charge des « annotations de type » (aussi appelées « type hints ») facultatives.
-Ces annotations de type constituent une syntaxe spéciale qui permet de déclarer le type d'une variable.
+Ces **« annotations de type »** sont une syntaxe spéciale qui permet de déclarer le type d'une variable.
-En déclarant les types de vos variables, cela permet aux différents outils comme les éditeurs de texte d'offrir un meilleur support.
+En déclarant les types de vos variables, les éditeurs et outils peuvent vous offrir un meilleur support.
-Ce chapitre n'est qu'un **tutoriel rapide / rappel** sur les annotations de type Python.
-Seulement le minimum nécessaire pour les utiliser avec **FastAPI** sera couvert... ce qui est en réalité très peu.
+Ceci est un **tutoriel rapide / rappel** à propos des annotations de type Python. Il couvre uniquement le minimum nécessaire pour les utiliser avec **FastAPI** ... ce qui est en réalité très peu.
-**FastAPI** est totalement basé sur ces annotations de type, qui lui donnent de nombreux avantages.
+**FastAPI** est totalement basé sur ces annotations de type, elles lui donnent de nombreux avantages et bénéfices.
-Mais même si vous n'utilisez pas ou n'utiliserez jamais **FastAPI**, vous pourriez bénéficier d'apprendre quelques choses sur ces dernières.
+Mais même si vous n'utilisez jamais **FastAPI**, vous auriez intérêt à en apprendre un peu à leur sujet.
-!!! note
- Si vous êtes un expert Python, et que vous savez déjà **tout** sur les annotations de type, passez au chapitre suivant.
+/// note | Remarque
-## Motivations
+Si vous êtes un expert Python, et que vous savez déjà tout sur les annotations de type, passez au chapitre suivant.
-Prenons un exemple simple :
+///
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+## Motivation { #motivation }
+
+Commençons par un exemple simple :
+
+{* ../../docs_src/python_types/tutorial001_py310.py *}
-Exécuter ce programe affiche :
+Exécuter ce programme affiche :
```
John Doe
```
-La fonction :
+La fonction fait ce qui suit :
* Prend un `first_name` et un `last_name`.
-* Convertit la première lettre de chaque paramètre en majuscules grâce à `title()`.
-* Concatène les résultats avec un espace entre les deux.
+* Convertit la première lettre de chacun en majuscule avec `title()`.
+* Concatène ces deux valeurs avec un espace au milieu.
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}
-### Limitations
+### Modifier le code { #edit-it }
C'est un programme très simple.
Mais maintenant imaginez que vous l'écriviez de zéro.
-À un certain point vous auriez commencé la définition de la fonction, vous aviez les paramètres prêts.
+À un certain moment, vous auriez commencé la définition de la fonction, vous aviez les paramètres prêts ...
-Mais vous aviez besoin de "cette méthode qui convertit la première lettre en majuscule".
+Mais ensuite vous devez appeler « cette méthode qui convertit la première lettre en majuscule ».
-Était-ce `upper` ? `uppercase` ? `first_uppercase` ? `capitalize` ?
+Était-ce `upper` ? Était-ce `uppercase` ? `first_uppercase` ? `capitalize` ?
-Vous essayez donc d'utiliser le vieil ami du programmeur, l'auto-complétion de l'éditeur.
+Vous essayez alors avec l'ami de toujours des programmeurs, l'autocomplétion de l'éditeur.
-Vous écrivez le premier paramètre, `first_name`, puis un point (`.`) et appuyez sur `Ctrl+Espace` pour déclencher l'auto-complétion.
+Vous tapez le premier paramètre de la fonction, `first_name`, puis un point (`.`) et appuyez sur `Ctrl+Espace` pour déclencher l'autocomplétion.
-Mais malheureusement, rien d'utile n'en résulte :
+Mais, malheureusement, vous n'obtenez rien d'utile :
-### Ajouter des types
+### Ajouter des types { #add-types }
Modifions une seule ligne de la version précédente.
-Nous allons changer seulement cet extrait, les paramètres de la fonction, de :
-
+Nous allons changer exactement ce fragment, les paramètres de la fonction, de :
```Python
first_name, last_name
@@ -79,236 +76,273 @@ Nous allons changer seulement cet extrait, les paramètres de la fonction, de :
C'est tout.
-Ce sont des annotations de types :
+Ce sont les « annotations de type » :
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
-À ne pas confondre avec la déclaration de valeurs par défaut comme ici :
+Ce n'est pas la même chose que de déclarer des valeurs par défaut, ce qui serait :
```Python
first_name="john", last_name="doe"
```
-C'est une chose différente.
+C'est différent.
-On utilise un deux-points (`:`), et pas un égal (`=`).
+Nous utilisons des deux-points (`:`), pas des signes égal (`=`).
-Et ajouter des annotations de types ne crée normalement pas de différence avec le comportement qui aurait eu lieu si elles n'étaient pas là.
+Et ajouter des annotations de type ne change normalement pas ce qui se passe par rapport à ce qui se passerait sans elles.
-Maintenant, imaginez que vous êtes en train de créer cette fonction, mais avec des annotations de type cette fois.
+Mais maintenant, imaginez que vous êtes à nouveau en train de créer cette fonction, mais avec des annotations de type.
-Au même moment que durant l'exemple précédent, vous essayez de déclencher l'auto-complétion et vous voyez :
+Au même moment, vous essayez de déclencher l'autocomplétion avec `Ctrl+Espace` et vous voyez :
-Vous pouvez donc dérouler les options jusqu'à trouver la méthode à laquelle vous pensiez.
+Avec cela, vous pouvez faire défiler en voyant les options, jusqu'à trouver celle qui « vous dit quelque chose » :
-## Plus de motivations
+## Plus de motivation { #more-motivation }
-Cette fonction possède déjà des annotations de type :
+Regardez cette fonction, elle a déjà des annotations de type :
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
-Comme l'éditeur connaît le type des variables, vous n'avez pas seulement l'auto-complétion, mais aussi de la détection d'erreurs :
+Comme l'éditeur connaît les types des variables, vous n'obtenez pas seulement l'autocomplétion, vous obtenez aussi des vérifications d'erreurs :
-Maintenant que vous avez connaissance du problème, convertissez `age` en chaîne de caractères grâce à `str(age)` :
+Vous savez maintenant qu'il faut corriger, convertir `age` en chaîne avec `str(age)` :
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
-## Déclarer des types
+## Déclarer des types { #declaring-types }
-Vous venez de voir là où les types sont généralement déclarés : dans les paramètres de fonctions.
+Vous venez de voir l'endroit principal pour déclarer des annotations de type : dans les paramètres des fonctions.
-C'est aussi ici que vous les utiliseriez avec **FastAPI**.
+C'est aussi l'endroit principal où vous les utiliserez avec **FastAPI**.
-### Types simples
+### Types simples { #simple-types }
-Vous pouvez déclarer tous les types de Python, pas seulement `str`.
+Vous pouvez déclarer tous les types standards de Python, pas seulement `str`.
-Comme par exemple :
+Vous pouvez utiliser, par exemple :
* `int`
* `float`
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
+
+### Module `typing` { #typing-module }
+
+Pour certains cas d'utilisation supplémentaires, vous pourriez avoir besoin d'importer certains éléments depuis le module standard `typing`, par exemple lorsque vous voulez déclarer que quelque chose a « n'importe quel type », vous pouvez utiliser `Any` depuis `typing` :
+
+```python
+from typing import Any
+
+
+def some_function(data: Any):
+ print(data)
```
-### Types génériques avec des paramètres de types
+### Types génériques { #generic-types }
-Il existe certaines structures de données qui contiennent d'autres valeurs, comme `dict`, `list`, `set` et `tuple`. Et les valeurs internes peuvent elles aussi avoir leurs propres types.
+Certains types peuvent prendre des « paramètres de type » entre crochets, pour définir leurs types internes, par exemple une « liste de chaînes » se déclarerait `list[str]`.
-Pour déclarer ces types et les types internes, on utilise le module standard de Python `typing`.
+Ces types qui peuvent prendre des paramètres de type sont appelés des **types génériques** ou **Generics**.
-Il existe spécialement pour supporter ces annotations de types.
+Vous pouvez utiliser les mêmes types intégrés comme génériques (avec des crochets et des types à l'intérieur) :
-#### `List`
+* `list`
+* `tuple`
+* `set`
+* `dict`
-Par exemple, définissons une variable comme `list` de `str`.
+#### Liste { #list }
-Importez `List` (avec un `L` majuscule) depuis `typing`.
+Par exemple, définissons une variable comme une `list` de `str`.
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+Déclarez la variable, en utilisant la même syntaxe avec deux-points (`:`).
-Déclarez la variable, en utilisant la syntaxe des deux-points (`:`).
+Comme type, mettez `list`.
-Et comme type, mettez `List`.
+Comme la liste est un type qui contient des types internes, mettez-les entre crochets :
-Les listes étant un type contenant des types internes, mettez ces derniers entre crochets (`[`, `]`) :
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
-```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+/// info
+
+Ces types internes entre crochets sont appelés « paramètres de type ».
-!!! tip "Astuce"
- Ces types internes entre crochets sont appelés des "paramètres de type".
+Dans ce cas, `str` est le paramètre de type passé à `list`.
- Ici, `str` est un paramètre de type passé à `List`.
+///
-Ce qui signifie : "la variable `items` est une `list`, et chacun de ses éléments a pour type `str`.
+Cela signifie : « la variable `items` est une `list`, et chacun des éléments de cette liste est un `str` ».
-En faisant cela, votre éditeur pourra vous aider, même pendant que vous traitez des éléments de la liste.
+En faisant cela, votre éditeur peut vous fournir de l'aide même pendant le traitement des éléments de la liste :
Sans types, c'est presque impossible à réaliser.
-Vous remarquerez que la variable `item` n'est qu'un des éléments de la list `items`.
+Remarquez que la variable `item` est l'un des éléments de la liste `items`.
-Et pourtant, l'éditeur sait qu'elle est de type `str` et pourra donc vous aider à l'utiliser.
+Et pourtant, l'éditeur sait que c'est un `str` et fournit le support approprié.
-#### `Tuple` et `Set`
+#### Tuple et Set { #tuple-and-set }
-C'est le même fonctionnement pour déclarer un `tuple` ou un `set` :
+Vous feriez la même chose pour déclarer des `tuple` et des `set` :
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
-```
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
-Dans cet exemple :
+Cela signifie :
-* La variable `items_t` est un `tuple` avec 3 éléments, un `int`, un deuxième `int`, et un `str`.
+* La variable `items_t` est un `tuple` avec 3 éléments, un `int`, un autre `int`, et un `str`.
* La variable `items_s` est un `set`, et chacun de ses éléments est de type `bytes`.
-#### `Dict`
+#### Dict { #dict }
-Pour définir un `dict`, il faut lui passer 2 paramètres, séparés par une virgule (`,`).
+Pour définir un `dict`, vous passez 2 paramètres de type, séparés par des virgules.
-Le premier paramètre de type est pour les clés et le second pour les valeurs du dictionnaire (`dict`).
+Le premier paramètre de type est pour les clés du `dict`.
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
-```
+Le second paramètre de type est pour les valeurs du `dict` :
+
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
-Dans cet exemple :
+Cela signifie :
-* La variable `prices` est de type `dict` :
- * Les clés de ce dictionnaire sont de type `str`.
- * Les valeurs de ce dictionnaire sont de type `float`.
+* La variable `prices` est un `dict` :
+ * Les clés de ce `dict` sont de type `str` (disons, le nom de chaque article).
+ * Les valeurs de ce `dict` sont de type `float` (disons, le prix de chaque article).
-#### `Optional`
+#### Union { #union }
-Vous pouvez aussi utiliser `Optional` pour déclarer qu'une variable a un type, comme `str` mais qu'il est "optionnel" signifiant qu'il pourrait aussi être `None`.
+Vous pouvez déclarer qu'une variable peut être **plusieurs types**, par exemple, un `int` ou un `str`.
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+Pour le définir, vous utilisez la barre verticale (`|`) pour séparer les deux types.
+
+C'est ce qu'on appelle une « union », car la variable peut être n'importe quoi dans l'union de ces deux ensembles de types.
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
```
-Utiliser `Optional[str]` plutôt que `str` permettra à l'éditeur de vous aider à détecter les erreurs où vous supposeriez qu'une valeur est toujours de type `str`, alors qu'elle pourrait aussi être `None`.
+Cela signifie que `item` peut être un `int` ou un `str`.
-#### Types génériques
+#### Possiblement `None` { #possibly-none }
-Les types qui peuvent contenir des paramètres de types entre crochets, comme :
+Vous pouvez déclarer qu'une valeur peut avoir un type, comme `str`, mais qu'elle peut aussi être `None`.
-* `List`
-* `Tuple`
-* `Set`
-* `Dict`
-* `Optional`
-* ...et d'autres.
+//// tab | Python 3.10+
-sont appelés des **types génériques** ou **Generics**.
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
+
+////
+
+Utiliser `str | None` au lieu de simplement `str` permettra à l'éditeur de vous aider à détecter des erreurs où vous supposeriez qu'une valeur est toujours un `str`, alors qu'elle pourrait en fait aussi être `None`.
-### Classes en tant que types
+### Classes en tant que types { #classes-as-types }
Vous pouvez aussi déclarer une classe comme type d'une variable.
-Disons que vous avez une classe `Person`, avec une variable `name` :
+Disons que vous avez une classe `Person`, avec un nom :
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
Vous pouvez ensuite déclarer une variable de type `Person` :
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
-Et vous aurez accès, encore une fois, au support complet offert par l'éditeur :
+Et là encore, vous obtenez tout le support de l'éditeur :
-## Les modèles Pydantic
+Remarquez que cela signifie « `one_person` est une **instance** de la classe `Person` ».
-Pydantic est une bibliothèque Python pour effectuer de la validation de données.
+Cela ne signifie pas « `one_person` est la **classe** appelée `Person` ».
-Vous déclarez la forme de la donnée avec des classes et des attributs.
+## Modèles Pydantic { #pydantic-models }
-Chaque attribut possède un type.
+[Pydantic](https://docs.pydantic.dev/) est une bibliothèque Python pour effectuer de la validation de données.
-Puis vous créez une instance de cette classe avec certaines valeurs et **Pydantic** validera les valeurs, les convertira dans le type adéquat (si c'est nécessaire et possible) et vous donnera un objet avec toute la donnée.
+Vous déclarez la « forme » de la donnée sous forme de classes avec des attributs.
-Ainsi, votre éditeur vous offrira un support adapté pour l'objet résultant.
+Et chaque attribut a un type.
-Extrait de la documentation officielle de **Pydantic** :
+Ensuite, vous créez une instance de cette classe avec certaines valeurs et elle validera les valeurs, les convertira dans le type approprié (le cas échéant) et vous donnera un objet avec toutes les données.
-```Python
-{!../../../docs_src/python_types/tutorial011.py!}
-```
+Et vous obtenez tout le support de l'éditeur avec cet objet résultant.
+
+Un exemple tiré de la documentation officielle de Pydantic :
+
+{* ../../docs_src/python_types/tutorial011_py310.py *}
+
+/// info
+
+Pour en savoir plus à propos de [Pydantic, consultez sa documentation](https://docs.pydantic.dev/).
+
+///
+
+**FastAPI** est entièrement basé sur Pydantic.
-!!! info
- Pour en savoir plus à propos de Pydantic, allez jeter un coup d'oeil à sa documentation.
+Vous verrez beaucoup plus de tout cela en pratique dans le [Tutoriel - Guide utilisateur](tutorial/index.md).
-**FastAPI** est basé entièrement sur **Pydantic**.
+## Annotations de type avec métadonnées { #type-hints-with-metadata-annotations }
-Vous verrez bien plus d'exemples de son utilisation dans [Tutoriel - Guide utilisateur](tutorial/index.md){.internal-link target=_blank}.
+Python dispose également d'une fonctionnalité qui permet de mettre des **métadonnées supplémentaires** dans ces annotations de type en utilisant `Annotated`.
-## Les annotations de type dans **FastAPI**
+Vous pouvez importer `Annotated` depuis `typing`.
-**FastAPI** utilise ces annotations pour faire différentes choses.
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
-Avec **FastAPI**, vous déclarez des paramètres grâce aux annotations de types et vous obtenez :
+Python lui-même ne fait rien avec ce `Annotated`. Et pour les éditeurs et autres outils, le type est toujours `str`.
-* **du support de l'éditeur**
-* **de la vérification de types**
+Mais vous pouvez utiliser cet espace dans `Annotated` pour fournir à **FastAPI** des métadonnées supplémentaires sur la façon dont vous voulez que votre application se comporte.
-...et **FastAPI** utilise ces mêmes déclarations pour :
+L'important à retenir est que **le premier « paramètre de type »** que vous passez à `Annotated` est le **type réel**. Le reste n'est que des métadonnées pour d'autres outils.
-* **Définir les prérequis** : depuis les paramètres de chemins des requêtes, les entêtes, les corps, les dépendances, etc.
-* **Convertir des données** : depuis la requête vers les types requis.
-* **Valider des données** : venant de chaque requête :
- * Générant automatiquement des **erreurs** renvoyées au client quand la donnée est invalide.
+Pour l'instant, vous avez juste besoin de savoir que `Annotated` existe, et que c'est du Python standard. 😎
+
+Plus tard, vous verrez à quel point cela peut être **puissant**.
+
+/// tip | Astuce
+
+Le fait que ce soit du **Python standard** signifie que vous bénéficierez toujours de la **meilleure expérience développeur possible** dans votre éditeur, avec les outils que vous utilisez pour analyser et refactoriser votre code, etc. ✨
+
+Et aussi que votre code sera très compatible avec de nombreux autres outils et bibliothèques Python. 🚀
+
+///
+
+## Annotations de type dans **FastAPI** { #type-hints-in-fastapi }
+
+**FastAPI** tire parti de ces annotations de type pour faire plusieurs choses.
+
+Avec **FastAPI**, vous déclarez des paramètres avec des annotations de type et vous obtenez :
+
+* **Du support de l'éditeur**.
+* **Des vérifications de types**.
+
+... et **FastAPI** utilise les mêmes déclarations pour :
+
+* **Définir des prérequis** : à partir des paramètres de chemin de la requête, des paramètres de requête, des en-têtes, des corps, des dépendances, etc.
+* **Convertir des données** : de la requête vers le type requis.
+* **Valider des données** : provenant de chaque requête :
+ * En générant des **erreurs automatiques** renvoyées au client lorsque la donnée est invalide.
* **Documenter** l'API avec OpenAPI :
- * ce qui ensuite utilisé par les interfaces utilisateur automatiques de documentation interactive.
+ * ce qui est ensuite utilisé par les interfaces utilisateur de documentation interactive automatiques.
+
+Tout cela peut sembler abstrait. Ne vous inquiétez pas. Vous verrez tout cela en action dans le [Tutoriel - Guide utilisateur](tutorial/index.md).
+
+L'important est qu'en utilisant les types standards de Python, en un seul endroit (au lieu d'ajouter plus de classes, de décorateurs, etc.), **FastAPI** fera une grande partie du travail pour vous.
-Tout cela peut paraître bien abstrait, mais ne vous inquiétez pas, vous verrez tout ça en pratique dans [Tutoriel - Guide utilisateur](tutorial/index.md){.internal-link target=_blank}.
+/// info
-Ce qu'il faut retenir c'est qu'en utilisant les types standard de Python, à un seul endroit (plutôt que d'ajouter plus de classes, de décorateurs, etc.), **FastAPI** fera une grande partie du travail pour vous.
+Si vous avez déjà parcouru tout le tutoriel et êtes revenu pour en voir plus sur les types, une bonne ressource est [l'« aide-mémoire » de `mypy`](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html).
-!!! info
- Si vous avez déjà lu le tutoriel et êtes revenus ici pour voir plus sur les types, une bonne ressource est la "cheat sheet" de `mypy`.
+///
diff --git a/docs/fr/docs/resources/index.md b/docs/fr/docs/resources/index.md
new file mode 100644
index 0000000000000..e62db346da40b
--- /dev/null
+++ b/docs/fr/docs/resources/index.md
@@ -0,0 +1,3 @@
+# Ressources { #resources }
+
+Ressources supplémentaires, liens externes et plus encore. ✈️
diff --git a/docs/fr/docs/translation-banner.md b/docs/fr/docs/translation-banner.md
new file mode 100644
index 0000000000000..9eaedf1b1bb59
--- /dev/null
+++ b/docs/fr/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 Traduction par IA et humains
+
+Cette traduction a été réalisée par une IA guidée par des humains. 🤝
+
+Elle peut contenir des erreurs d'interprétation du sens original, ou paraître peu naturelle, etc. 🤖
+
+Vous pouvez améliorer cette traduction en [nous aidant à mieux guider le LLM d'IA](https://fastapi.tiangolo.com/fr/contributing/#translations).
+
+[Version anglaise](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/fr/docs/tutorial/background-tasks.md b/docs/fr/docs/tutorial/background-tasks.md
index f7cf1a6ccc17e..c8f66e5258e36 100644
--- a/docs/fr/docs/tutorial/background-tasks.md
+++ b/docs/fr/docs/tutorial/background-tasks.md
@@ -1,4 +1,4 @@
-# Tâches d'arrière-plan
+# Tâches d'arrière-plan { #background-tasks }
Vous pouvez définir des tâches d'arrière-plan qui seront exécutées après avoir retourné une réponse.
@@ -7,22 +7,21 @@ Ceci est utile pour les opérations qui doivent avoir lieu après une requête,
Cela comprend, par exemple :
* Les notifications par email envoyées après l'exécution d'une action :
- * Étant donné que se connecter à un serveur et envoyer un email a tendance à être «lent» (plusieurs secondes), vous pouvez retourner la réponse directement et envoyer la notification en arrière-plan.
+ * Étant donné que se connecter à un serveur et envoyer un email a tendance à être « lent » (plusieurs secondes), vous pouvez retourner la réponse directement et envoyer la notification en arrière-plan.
* Traiter des données :
- * Par exemple, si vous recevez un fichier qui doit passer par un traitement lent, vous pouvez retourner une réponse «Accepted» (HTTP 202) puis faire le traitement en arrière-plan.
+ * Par exemple, si vous recevez un fichier qui doit passer par un traitement lent, vous pouvez retourner une réponse « Accepted » (HTTP 202) puis faire le traitement en arrière-plan.
+## Utiliser `BackgroundTasks` { #using-backgroundtasks }
-## Utiliser `BackgroundTasks`
+Pour commencer, importez `BackgroundTasks` et définissez un paramètre dans votre *fonction de chemin d'accès* avec `BackgroundTasks` comme type déclaré.
-Pour commencer, importez `BackgroundTasks` et définissez un paramètre dans votre *fonction de chemin* avec `BackgroundTasks` comme type déclaré.
-
-```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
**FastAPI** créera l'objet de type `BackgroundTasks` pour vous et le passera comme paramètre.
-## Créer une fonction de tâche
+## Créer une fonction de tâche { #create-a-task-function }
+
+Créez une fonction à exécuter comme tâche d'arrière-plan.
Une fonction à exécuter comme tâche d'arrière-plan est juste une fonction standard qui peut recevoir des paramètres.
@@ -32,18 +31,13 @@ Dans cet exemple, la fonction de tâche écrira dans un fichier (afin de simuler
L'opération d'écriture n'utilisant ni `async` ni `await`, on définit la fonction avec un `def` normal.
-```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
-## Ajouter une tâche d'arrière-plan
+## Ajouter une tâche d'arrière-plan { #add-the-background-task }
-Dans votre *fonction de chemin*, passez votre fonction de tâche à l'objet de type `BackgroundTasks` (`background_tasks` ici) grâce à la méthode `.add_task()` :
+Dans votre *fonction de chemin d'accès*, passez votre fonction de tâche à l'objet de type `BackgroundTasks` (`background_tasks` ici) grâce à la méthode `.add_task()` :
-
-```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
`.add_task()` reçoit comme arguments :
@@ -51,44 +45,40 @@ Dans votre *fonction de chemin*, passez votre fonction de tâche à l'objet de t
* Les arguments positionnels à passer à la fonction de tâche dans l'ordre (`email`).
* Les arguments nommés à passer à la fonction de tâche (`message="some notification"`).
-## Injection de dépendances
+## Injection de dépendances { #dependency-injection }
-Utiliser `BackgroundTasks` fonctionne aussi avec le système d'injection de dépendances. Vous pouvez déclarer un paramètre de type `BackgroundTasks` à différents niveaux : dans une *fonction de chemin*, dans une dépendance, dans une sous-dépendance...
+Utiliser `BackgroundTasks` fonctionne aussi avec le système d'injection de dépendances. Vous pouvez déclarer un paramètre de type `BackgroundTasks` à différents niveaux : dans une *fonction de chemin d'accès*, dans une dépendance (dependable), dans une sous-dépendance, etc.
-**FastAPI** sait quoi faire dans chaque cas et comment réutiliser le même objet, afin que tous les paramètres de type `BackgroundTasks` soient fusionnés et que les tâches soient exécutées en arrière-plan :
+**FastAPI** sait quoi faire dans chaque cas et comment réutiliser le même objet, afin que toutes les tâches d'arrière-plan soient fusionnées et que les tâches soient ensuite exécutées en arrière-plan :
-```Python hl_lines="13 15 22 25"
-{!../../../docs_src/background_tasks/tutorial002.py!}
-```
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
Dans cet exemple, les messages seront écrits dans le fichier `log.txt` après que la réponse soit envoyée.
-S'il y avait une `query` (paramètre nommé `q`) dans la requête, alors elle sera écrite dans `log.txt` via une tâche d'arrière-plan.
+S'il y avait un paramètre de requête dans la requête, alors il sera écrit dans le journal via une tâche d'arrière-plan.
-Et ensuite une autre tâche d'arrière-plan (générée dans les paramètres de la *la fonction de chemin*) écrira un message dans `log.txt` comprenant le paramètre de chemin `email`.
+Et ensuite une autre tâche d'arrière-plan (générée dans la *fonction de chemin d'accès*) écrira un message comprenant le paramètre de chemin `email`.
-## Détails techniques
+## Détails techniques { #technical-details }
-La classe `BackgroundTasks` provient directement de `starlette.background`.
+La classe `BackgroundTasks` provient directement de [`starlette.background`](https://www.starlette.dev/background/).
Elle est importée/incluse directement dans **FastAPI** pour que vous puissiez l'importer depuis `fastapi` et éviter d'importer accidentellement `BackgroundTask` (sans `s` à la fin) depuis `starlette.background`.
-En utilisant seulement `BackgroundTasks` (et non `BackgroundTask`), il est possible de l'utiliser en tant que paramètre de *fonction de chemin* et de laisser **FastAPI** gérer le reste pour vous, comme en utilisant l'objet `Request` directement.
+En utilisant seulement `BackgroundTasks` (et non `BackgroundTask`), il est possible de l'utiliser en tant que paramètre de *fonction de chemin d'accès* et de laisser **FastAPI** gérer le reste pour vous, comme en utilisant l'objet `Request` directement.
Il est tout de même possible d'utiliser `BackgroundTask` seul dans **FastAPI**, mais dans ce cas il faut créer l'objet dans le code et renvoyer une `Response` Starlette l'incluant.
-Plus de détails sont disponibles dans la documentation officielle de Starlette sur les tâches d'arrière-plan (via leurs classes `BackgroundTasks`et `BackgroundTask`).
-
-## Avertissement
+Plus de détails sont disponibles dans [la documentation officielle de Starlette sur les tâches d'arrière-plan](https://www.starlette.dev/background/).
-Si vous avez besoin de réaliser des traitements lourds en tâche d'arrière-plan et que vous n'avez pas besoin que ces traitements aient lieu dans le même process (par exemple, pas besoin de partager la mémoire, les variables, etc.), il peut s'avérer profitable d'utiliser des outils plus importants tels que Celery.
+## Avertissement { #caveat }
-Ces outils nécessitent généralement des configurations plus complexes ainsi qu'un gestionnaire de queue de message, comme RabbitMQ ou Redis, mais ils permettent d'exécuter des tâches d'arrière-plan dans différents process, et potentiellement, sur plusieurs serveurs.
+Si vous avez besoin de réaliser des traitements lourds en tâche d'arrière-plan et que vous n'avez pas besoin que ces traitements aient lieu dans le même process (par exemple, pas besoin de partager la mémoire, les variables, etc.), il peut s'avérer profitable d'utiliser des outils plus importants tels que [Celery](https://docs.celeryq.dev).
-Pour voir un exemple, allez voir les [Générateurs de projets](../project-generation.md){.internal-link target=_blank}, ils incluent tous Celery déjà configuré.
+Ces outils nécessitent généralement des configurations plus complexes ainsi qu'un gestionnaire de queue de message, comme RabbitMQ ou Redis, mais ils permettent d'exécuter des tâches d'arrière-plan dans différents process, et surtout, sur plusieurs serveurs.
Mais si vous avez besoin d'accéder aux variables et objets de la même application **FastAPI**, ou si vous avez besoin d'effectuer de petites tâches d'arrière-plan (comme envoyer des notifications par email), vous pouvez simplement vous contenter d'utiliser `BackgroundTasks`.
-## Résumé
+## Résumé { #recap }
-Importez et utilisez `BackgroundTasks` grâce aux paramètres de *fonction de chemin* et les dépendances pour ajouter des tâches d'arrière-plan.
+Importez et utilisez `BackgroundTasks` grâce aux paramètres de *fonction de chemin d'accès* et les dépendances pour ajouter des tâches d'arrière-plan.
diff --git a/docs/fr/docs/tutorial/bigger-applications.md b/docs/fr/docs/tutorial/bigger-applications.md
new file mode 100644
index 0000000000000..82e204224c87a
--- /dev/null
+++ b/docs/fr/docs/tutorial/bigger-applications.md
@@ -0,0 +1,535 @@
+# Créer des applications plus grandes - Plusieurs fichiers { #bigger-applications-multiple-files }
+
+Si vous créez une application ou une API web, il est rare que vous puissiez tout mettre dans un seul fichier.
+
+**FastAPI** fournit un outil pratique pour structurer votre application tout en conservant toute la flexibilité.
+
+/// info
+
+Si vous venez de Flask, cela équivaut aux Blueprints de Flask.
+
+///
+
+## Exemple de structure de fichiers { #an-example-file-structure }
+
+Supposons que vous ayez une structure de fichiers comme ceci :
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ ├── dependencies.py
+│ └── routers
+│ │ ├── __init__.py
+│ │ ├── items.py
+│ │ └── users.py
+│ └── internal
+│ ├── __init__.py
+│ └── admin.py
+```
+
+/// tip | Astuce
+
+Il y a plusieurs fichiers `__init__.py` : un dans chaque répertoire ou sous-répertoire.
+
+C'est cela qui permet d'importer du code d'un fichier dans un autre.
+
+Par exemple, dans `app/main.py` vous pourriez avoir une ligne comme :
+
+```
+from app.routers import items
+```
+
+///
+
+* Le répertoire `app` contient tout. Et il a un fichier vide `app/__init__.py`, c'est donc un « package Python » (une collection de « modules Python ») : `app`.
+* Il contient un fichier `app/main.py`. Comme il se trouve dans un package Python (un répertoire avec un fichier `__init__.py`), c'est un « module » de ce package : `app.main`.
+* Il y a aussi un fichier `app/dependencies.py`, tout comme `app/main.py`, c'est un « module » : `app.dependencies`.
+* Il y a un sous-répertoire `app/routers/` avec un autre fichier `__init__.py`, c'est donc un « sous-package Python » : `app.routers`.
+* Le fichier `app/routers/items.py` est dans un package, `app/routers/`, c'est donc un sous-module : `app.routers.items`.
+* De même pour `app/routers/users.py`, c'est un autre sous-module : `app.routers.users`.
+* Il y a aussi un sous-répertoire `app/internal/` avec un autre fichier `__init__.py`, c'est donc un autre « sous-package Python » : `app.internal`.
+* Et le fichier `app/internal/admin.py` est un autre sous-module : `app.internal.admin`.
+
+
+
+## Inclure le même routeur plusieurs fois avec des `prefix` différents { #include-the-same-router-multiple-times-with-different-prefix }
+
+Vous pouvez aussi utiliser `.include_router()` plusieurs fois avec le même routeur en utilisant des préfixes différents.
+
+Cela peut être utile, par exemple, pour exposer la même API sous des préfixes différents, p. ex. `/api/v1` et `/api/latest`.
+
+C'est un usage avancé dont vous n'aurez peut-être pas vraiment besoin, mais il est là au cas où.
+
+## Inclure un `APIRouter` dans un autre { #include-an-apirouter-in-another }
+
+De la même manière que vous pouvez inclure un `APIRouter` dans une application `FastAPI`, vous pouvez inclure un `APIRouter` dans un autre `APIRouter` en utilisant :
+
+```Python
+router.include_router(other_router)
+```
+
+Vous devez vous assurer de le faire avant d'inclure `router` dans l'application `FastAPI`, afin que les *chemins d'accès* de `other_router` soient également inclus.
diff --git a/docs/fr/docs/tutorial/body-fields.md b/docs/fr/docs/tutorial/body-fields.md
new file mode 100644
index 0000000000000..9830292c905fe
--- /dev/null
+++ b/docs/fr/docs/tutorial/body-fields.md
@@ -0,0 +1,61 @@
+# Corps - Champs { #body-fields }
+
+De la même manière que vous pouvez déclarer des validations supplémentaires et des métadonnées dans les paramètres d'une fonction de chemin d'accès avec `Query`, `Path` et `Body`, vous pouvez déclarer des validations et des métadonnées à l'intérieur des modèles Pydantic en utilisant `Field` de Pydantic.
+
+## Importer `Field` { #import-field }
+
+D'abord, vous devez l'importer :
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}
+
+
+/// warning | Alertes
+
+Notez que `Field` est importé directement depuis `pydantic`, et non depuis `fastapi` comme le sont les autres (`Query`, `Path`, `Body`, etc.).
+
+///
+
+## Déclarer les attributs du modèle { #declare-model-attributes }
+
+Vous pouvez ensuite utiliser `Field` avec des attributs de modèle :
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}
+
+`Field` fonctionne de la même manière que `Query`, `Path` et `Body`, il dispose des mêmes paramètres, etc.
+
+/// note | Détails techniques
+
+En réalité, `Query`, `Path` et d'autres que vous verrez ensuite créent des objets de sous-classes d'une classe commune `Param`, qui est elle-même une sous-classe de la classe `FieldInfo` de Pydantic.
+
+Et `Field` de Pydantic renvoie également une instance de `FieldInfo`.
+
+`Body` renvoie aussi directement des objets d'une sous-classe de `FieldInfo`. Et il y en a d'autres que vous verrez plus tard qui sont des sous-classes de la classe `Body`.
+
+Rappelez-vous que lorsque vous importez `Query`, `Path` et d'autres depuis `fastapi`, ce sont en réalité des fonctions qui renvoient des classes spéciales.
+
+///
+
+/// tip | Astuce
+
+Remarquez comment chaque attribut de modèle avec un type, une valeur par défaut et `Field` a la même structure qu'un paramètre de fonction de chemin d'accès, avec `Field` au lieu de `Path`, `Query` et `Body`.
+
+///
+
+## Ajouter des informations supplémentaires { #add-extra-information }
+
+Vous pouvez déclarer des informations supplémentaires dans `Field`, `Query`, `Body`, etc. Elles seront incluses dans le JSON Schema généré.
+
+Vous en apprendrez davantage sur l'ajout d'informations supplémentaires plus loin dans les documents, lorsque vous apprendrez à déclarer des exemples.
+
+/// warning | Alertes
+
+Les clés supplémentaires passées à `Field` seront également présentes dans le schéma OpenAPI résultant pour votre application.
+Comme ces clés ne font pas nécessairement partie de la spécification OpenAPI, certains outils OpenAPI, par exemple [le validateur OpenAPI](https://validator.swagger.io/), peuvent ne pas fonctionner avec votre schéma généré.
+
+///
+
+## Récapitulatif { #recap }
+
+Vous pouvez utiliser `Field` de Pydantic pour déclarer des validations supplémentaires et des métadonnées pour les attributs de modèle.
+
+Vous pouvez également utiliser des arguments nommés supplémentaires pour transmettre des métadonnées JSON Schema additionnelles.
diff --git a/docs/fr/docs/tutorial/body-multiple-params.md b/docs/fr/docs/tutorial/body-multiple-params.md
new file mode 100644
index 0000000000000..1c1ab0fcac56b
--- /dev/null
+++ b/docs/fr/docs/tutorial/body-multiple-params.md
@@ -0,0 +1,165 @@
+# Body - Paramètres multiples { #body-multiple-parameters }
+
+Maintenant que nous avons vu comment utiliser `Path` et `Query`, voyons des usages plus avancés des déclarations de paramètres du corps de la requête.
+
+## Mélanger les paramètres `Path`, `Query` et du corps de la requête { #mix-path-query-and-body-parameters }
+
+Tout d'abord, sachez que vous pouvez mélanger librement les déclarations des paramètres `Path`, `Query` et du corps de la requête, **FastAPI** saura quoi faire.
+
+Et vous pouvez également déclarer des paramètres du corps de la requête comme étant optionnels, en leur assignant une valeur par défaut à `None` :
+
+{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
+
+/// note | Remarque
+
+Notez que, dans ce cas, l'élément `item` récupéré depuis le corps de la requête est optionnel. Comme sa valeur par défaut est `None`.
+
+///
+
+## Paramètres multiples du corps de la requête { #multiple-body-parameters }
+
+Dans l'exemple précédent, les chemins d'accès attendraient un corps de la requête JSON avec les attributs d'un `Item`, par exemple :
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+
+Mais vous pouvez également déclarer plusieurs paramètres provenant du corps de la requête, par exemple `item` et `user` :
+
+{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}
+
+Dans ce cas, **FastAPI** détectera qu'il y a plus d'un paramètre du corps de la requête dans la fonction (il y a deux paramètres qui sont des modèles Pydantic).
+
+Il utilisera alors les noms des paramètres comme clés (noms de champs) dans le corps de la requête, et s'attendra à recevoir un corps de la requête semblable à :
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ }
+}
+```
+
+/// note | Remarque
+
+Notez que, bien que `item` ait été déclaré de la même manière qu'auparavant, il est désormais attendu à l'intérieur du corps de la requête sous la clé `item`.
+
+///
+
+**FastAPI** effectuera la conversion automatique depuis la requête, de sorte que le paramètre `item` reçoive son contenu spécifique, et de même pour `user`.
+
+Il effectuera la validation des données composées, et les documentera ainsi pour le schéma OpenAPI et la documentation automatique.
+
+## Valeurs singulières dans le corps de la requête { #singular-values-in-body }
+
+De la même façon qu'il existe `Query` et `Path` pour définir des données supplémentaires pour les paramètres de requête et de chemin, **FastAPI** fournit un équivalent `Body`.
+
+Par exemple, en étendant le modèle précédent, vous pourriez décider d'avoir une autre clé `importance` dans le même corps de la requête, en plus de `item` et `user`.
+
+Si vous le déclarez tel quel, comme c'est une valeur singulière, **FastAPI** supposera qu'il s'agit d'un paramètre de requête.
+
+Mais vous pouvez indiquer à **FastAPI** de la traiter comme une autre clé du corps de la requête en utilisant `Body` :
+
+{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
+
+Dans ce cas, **FastAPI** s'attendra à un corps de la requête semblable à :
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ },
+ "importance": 5
+}
+```
+
+Encore une fois, il convertira les types de données, validera, documentera, etc.
+
+## Paramètres multiples du corps de la requête et paramètres de requête { #multiple-body-params-and-query }
+
+Bien entendu, vous pouvez également déclarer des paramètres de requête supplémentaires quand vous en avez besoin, en plus de tout paramètre du corps de la requête.
+
+Comme, par défaut, les valeurs singulières sont interprétées comme des paramètres de requête, vous n'avez pas besoin d'ajouter explicitement `Query`, vous pouvez simplement écrire :
+
+```Python
+q: str | None = None
+```
+
+Par exemple :
+
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
+
+/// info
+
+`Body` possède également les mêmes paramètres supplémentaires de validation et de métadonnées que `Query`, `Path` et d'autres que vous verrez plus tard.
+
+///
+
+## Intégrer un seul paramètre du corps de la requête { #embed-a-single-body-parameter }
+
+Supposons que vous n'ayez qu'un seul paramètre `item` dans le corps de la requête, provenant d'un modèle Pydantic `Item`.
+
+Par défaut, **FastAPI** attendra alors son contenu directement.
+
+Mais si vous voulez qu'il attende un JSON avec une clé `item` contenant le contenu du modèle, comme lorsqu'on déclare des paramètres supplémentaires du corps de la requête, vous pouvez utiliser le paramètre spécial `embed` de `Body` :
+
+```Python
+item: Item = Body(embed=True)
+```
+
+comme dans :
+
+{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}
+
+Dans ce cas **FastAPI** s'attendra à un corps de la requête semblable à :
+
+```JSON hl_lines="2"
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ }
+}
+```
+
+au lieu de :
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+
+## Récapitulatif { #recap }
+
+Vous pouvez ajouter plusieurs paramètres du corps de la requête à votre fonction de chemin d'accès, même si une requête ne peut avoir qu'un seul corps de la requête.
+
+Mais **FastAPI** s'en chargera, vous fournira les bonnes données dans votre fonction, et validera et documentera le schéma correct dans le chemin d'accès.
+
+Vous pouvez également déclarer des valeurs singulières à recevoir dans le corps de la requête.
+
+Et vous pouvez indiquer à **FastAPI** d'intégrer le corps de la requête sous une clé même lorsqu'un seul paramètre est déclaré.
diff --git a/docs/fr/docs/tutorial/body-nested-models.md b/docs/fr/docs/tutorial/body-nested-models.md
new file mode 100644
index 0000000000000..2d4064310dad9
--- /dev/null
+++ b/docs/fr/docs/tutorial/body-nested-models.md
@@ -0,0 +1,220 @@
+# Corps - Modèles imbriqués { #body-nested-models }
+
+Avec FastAPI, vous pouvez définir, valider, documenter et utiliser des modèles imbriqués à n'importe quelle profondeur (grâce à Pydantic).
+
+## Déclarer des champs de liste { #list-fields }
+
+Vous pouvez définir un attribut comme étant un sous-type. Par exemple, une `list` Python :
+
+{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}
+
+Cela fera de `tags` une liste, bien que le type des éléments de la liste ne soit pas déclaré.
+
+## Champs de liste avec paramètre de type { #list-fields-with-type-parameter }
+
+Mais Python a une manière spécifique de déclarer des listes avec des types internes, ou « paramètres de type » :
+
+### Déclarer une `list` avec un paramètre de type { #declare-a-list-with-a-type-parameter }
+
+Pour déclarer des types qui ont des paramètres de type (types internes), comme `list`, `dict`, `tuple`,
+passez le(s) type(s) interne(s) comme « paramètres de type » à l'aide de crochets : `[` et `]`
+
+```Python
+my_list: list[str]
+```
+
+C'est simplement la syntaxe Python standard pour les déclarations de type.
+
+Utilisez cette même syntaxe standard pour les attributs de modèles avec des types internes.
+
+Ainsi, dans notre exemple, nous pouvons faire de `tags` spécifiquement une « liste de chaînes » :
+
+{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}
+
+## Types set { #set-types }
+
+Mais en y réfléchissant, nous réalisons que les tags ne devraient pas se répéter, ce seraient probablement des chaînes uniques.
+
+Et Python dispose d'un type de données spécial pour les ensembles d'éléments uniques, le `set`.
+
+Nous pouvons alors déclarer `tags` comme un set de chaînes :
+
+{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}
+
+Avec cela, même si vous recevez une requête contenant des doublons, elle sera convertie en un set d'éléments uniques.
+
+Et chaque fois que vous renverrez ces données, même si la source contenait des doublons, elles seront renvoyées sous la forme d'un set d'éléments uniques.
+
+Elles seront également annotées / documentées en conséquence.
+
+## Modèles imbriqués { #nested-models }
+
+Chaque attribut d'un modèle Pydantic a un type.
+
+Mais ce type peut lui-même être un autre modèle Pydantic.
+
+Ainsi, vous pouvez déclarer des « objets » JSON profondément imbriqués avec des noms d'attributs, des types et des validations spécifiques.
+
+Tout cela, de manière arbitrairement imbriquée.
+
+### Définir un sous-modèle { #define-a-submodel }
+
+Par exemple, nous pouvons définir un modèle `Image` :
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}
+
+### Utiliser le sous-modèle comme type { #use-the-submodel-as-a-type }
+
+Nous pouvons ensuite l'utiliser comme type d'un attribut :
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}
+
+Cela signifie que FastAPI attendrait un corps similaire à :
+
+```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"
+ }
+}
+```
+
+Là encore, avec cette simple déclaration, avec FastAPI vous obtenez :
+
+- Prise en charge par l'éditeur (autocomplétion, etc.), même pour les modèles imbriqués
+- Conversion des données
+- Validation des données
+- Documentation automatique
+
+## Types spéciaux et validation { #special-types-and-validation }
+
+Outre les types singuliers normaux comme `str`, `int`, `float`, etc. vous pouvez utiliser des types singuliers plus complexes qui héritent de `str`.
+
+Pour voir toutes les options dont vous disposez, consultez [l’aperçu des types de Pydantic](https://docs.pydantic.dev/latest/concepts/types/). Vous verrez quelques exemples au chapitre suivant.
+
+Par exemple, comme dans le modèle `Image` nous avons un champ `url`, nous pouvons le déclarer comme instance de `HttpUrl` de Pydantic au lieu de `str` :
+
+{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}
+
+La chaîne sera vérifiée comme URL valide et documentée comme telle dans JSON Schema / OpenAPI.
+
+## Attributs avec des listes de sous-modèles { #attributes-with-lists-of-submodels }
+
+Vous pouvez également utiliser des modèles Pydantic comme sous-types de `list`, `set`, etc. :
+
+{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}
+
+Cela attendra (convertira, validera, documentera, etc.) un corps JSON comme :
+
+```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
+
+Remarquez que la clé `images` contient maintenant une liste d'objets image.
+
+///
+
+## Modèles profondément imbriqués { #deeply-nested-models }
+
+Vous pouvez définir des modèles imbriqués à une profondeur arbitraire :
+
+{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}
+
+/// info
+
+Remarquez que `Offer` a une liste d’`Item`, qui à leur tour ont une liste optionnelle d’`Image`.
+
+///
+
+## Corps de listes pures { #bodies-of-pure-lists }
+
+Si la valeur de premier niveau du corps JSON attendu est un `array` JSON (une `list` Python), vous pouvez déclarer le type dans le paramètre de la fonction, de la même manière que dans les modèles Pydantic :
+
+```Python
+images: list[Image]
+```
+
+comme :
+
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
+
+## Bénéficier de la prise en charge de l'éditeur partout { #editor-support-everywhere }
+
+Et vous bénéficiez de la prise en charge de l'éditeur partout.
+
+Même pour les éléments à l'intérieur des listes :
+
+
+
+Vous ne pourriez pas obtenir ce type de prise en charge de l'éditeur si vous travailliez directement avec des `dict` au lieu de modèles Pydantic.
+
+Mais vous n'avez pas à vous en soucier non plus, les `dict` entrants sont convertis automatiquement et votre sortie est également convertie automatiquement en JSON.
+
+## Corps de `dict` arbitraires { #bodies-of-arbitrary-dicts }
+
+Vous pouvez également déclarer un corps comme un `dict` avec des clés d’un certain type et des valeurs d’un autre type.
+
+De cette façon, vous n'avez pas besoin de savoir à l'avance quels sont les noms de champs/attributs valides (comme ce serait le cas avec des modèles Pydantic).
+
+Cela serait utile si vous voulez recevoir des clés que vous ne connaissez pas à l'avance.
+
+---
+
+Un autre cas utile est lorsque vous souhaitez avoir des clés d'un autre type (par exemple `int`).
+
+C'est ce que nous allons voir ici.
+
+Dans ce cas, vous accepteriez n'importe quel `dict` tant qu'il a des clés `int` avec des valeurs `float` :
+
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
+
+/// tip | Astuce
+
+Gardez à l'esprit que JSON ne prend en charge que des `str` comme clés.
+
+Mais Pydantic dispose d'une conversion automatique des données.
+
+Cela signifie que, même si vos clients d'API ne peuvent envoyer que des chaînes comme clés, tant que ces chaînes contiennent des entiers purs, Pydantic les convertira et les validera.
+
+Et le `dict` que vous recevez dans `weights` aura en réalité des clés `int` et des valeurs `float`.
+
+///
+
+## Récapitulatif { #recap }
+
+Avec FastAPI, vous bénéficiez de la flexibilité maximale fournie par les modèles Pydantic, tout en gardant votre code simple, concis et élégant.
+
+Mais avec tous les avantages :
+
+- Prise en charge par l'éditeur (autocomplétion partout !)
+- Conversion des données (a.k.a. parsing / sérialisation)
+- Validation des données
+- Documentation des schémas
+- Documentation automatique
diff --git a/docs/fr/docs/tutorial/body-updates.md b/docs/fr/docs/tutorial/body-updates.md
new file mode 100644
index 0000000000000..f036dd3c081f7
--- /dev/null
+++ b/docs/fr/docs/tutorial/body-updates.md
@@ -0,0 +1,100 @@
+# Corps - Mises à jour { #body-updates }
+
+## Mettre à jour en remplaçant avec `PUT` { #update-replacing-with-put }
+
+Pour mettre à jour un élément, vous pouvez utiliser l’opération [HTTP `PUT`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT).
+
+Vous pouvez utiliser le `jsonable_encoder` pour convertir les données d’entrée en données pouvant être stockées au format JSON (par exemple, avec une base de données NoSQL). Par exemple, convertir `datetime` en `str`.
+
+{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}
+
+On utilise `PUT` pour recevoir des données qui doivent remplacer les données existantes.
+
+### Avertissement concernant le remplacement { #warning-about-replacing }
+
+Cela signifie que si vous souhaitez mettre à jour l’élément `bar` avec `PUT` et un corps contenant :
+
+```Python
+{
+ "name": "Barz",
+ "price": 3,
+ "description": None,
+}
+```
+
+comme il n’inclut pas l’attribut déjà enregistré « tax »: 20.2, le modèle d’entrée prendrait la valeur par défaut « tax »: 10.5.
+
+Et les données seraient enregistrées avec cette « nouvelle » « tax » de 10.5.
+
+## Effectuer des mises à jour partielles avec `PATCH` { #partial-updates-with-patch }
+
+Vous pouvez également utiliser l’opération [HTTP `PATCH`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) pour mettre à jour des données de manière partielle.
+
+Cela signifie que vous pouvez n’envoyer que les données que vous souhaitez mettre à jour, en laissant le reste intact.
+
+/// note | Remarque
+
+`PATCH` est moins utilisé et moins connu que `PUT`.
+
+Et de nombreuses équipes n’utilisent que `PUT`, même pour les mises à jour partielles.
+
+Vous êtes libre de les utiliser comme vous le souhaitez, **FastAPI** n’impose aucune restriction.
+
+Mais ce guide vous montre, plus ou moins, la façon dont ils sont censés être utilisés.
+
+///
+
+### Utiliser le paramètre `exclude_unset` de Pydantic { #using-pydantics-exclude-unset-parameter }
+
+Si vous souhaitez recevoir des mises à jour partielles, il est très utile d’utiliser le paramètre `exclude_unset` dans la méthode `.model_dump()` du modèle Pydantic.
+
+Comme `item.model_dump(exclude_unset=True)`.
+
+Cela génère un `dict` ne contenant que les données définies lors de la création du modèle `item`, en excluant les valeurs par défaut.
+
+Vous pouvez ensuite l’utiliser pour produire un `dict` avec uniquement les données définies (envoyées dans la requête), en omettant les valeurs par défaut :
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}
+
+### Utiliser le paramètre `update` de Pydantic { #using-pydantics-update-parameter }
+
+Vous pouvez maintenant créer une copie du modèle existant avec `.model_copy()`, et passer le paramètre `update` avec un `dict` contenant les données à mettre à jour.
+
+Comme `stored_item_model.model_copy(update=update_data)` :
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}
+
+### Récapitulatif des mises à jour partielles { #partial-updates-recap }
+
+En résumé, pour appliquer des mises à jour partielles, vous procédez ainsi :
+
+* (Optionnel) utilisez `PATCH` au lieu de `PUT`.
+* Récupérez les données stockées.
+* Placez ces données dans un modèle Pydantic.
+* Générez un `dict` sans valeurs par défaut à partir du modèle d’entrée (en utilisant `exclude_unset`).
+ * De cette façon, vous mettez à jour uniquement les valeurs effectivement définies par l’utilisateur, au lieu d’écraser des valeurs déjà stockées par des valeurs par défaut de votre modèle.
+* Créez une copie du modèle stocké, en mettant à jour ses attributs avec les mises à jour partielles reçues (en utilisant le paramètre `update`).
+* Convertissez le modèle copié en quelque chose qui peut être stocké dans votre base de données (par exemple en utilisant le `jsonable_encoder`).
+ * Cela est comparable à l’utilisation à nouveau de la méthode `.model_dump()` du modèle, mais cela vérifie (et convertit) les valeurs vers des types pouvant être convertis en JSON, par exemple `datetime` en `str`.
+* Enregistrez les données dans votre base de données.
+* Retournez le modèle mis à jour.
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *}
+
+/// tip | Astuce
+
+Vous pouvez en réalité utiliser cette même technique avec une opération HTTP `PUT`.
+
+Mais l’exemple ici utilise `PATCH` car il a été créé pour ces cas d’usage.
+
+///
+
+/// note | Remarque
+
+Remarquez que le modèle d’entrée est toujours validé.
+
+Ainsi, si vous souhaitez recevoir des mises à jour partielles pouvant omettre tous les attributs, vous devez disposer d’un modèle avec tous les attributs marqués comme optionnels (avec des valeurs par défaut ou `None`).
+
+Pour distinguer les modèles avec toutes les valeurs optionnelles pour les mises à jour et les modèles avec des valeurs requises pour la création, vous pouvez utiliser les idées décrites dans [Modèles supplémentaires](extra-models.md).
+
+///
diff --git a/docs/fr/docs/tutorial/body.md b/docs/fr/docs/tutorial/body.md
index 89720c973aeb9..6a94667982061 100644
--- a/docs/fr/docs/tutorial/body.md
+++ b/docs/fr/docs/tutorial/body.md
@@ -1,41 +1,40 @@
-# Corps de la requête
+# Corps de la requête { #request-body }
Quand vous avez besoin d'envoyer de la donnée depuis un client (comme un navigateur) vers votre API, vous l'envoyez en tant que **corps de requête**.
Le corps d'une **requête** est de la donnée envoyée par le client à votre API. Le corps d'une **réponse** est la donnée envoyée par votre API au client.
-Votre API aura presque toujours à envoyer un corps de **réponse**. Mais un client n'a pas toujours à envoyer un corps de **requête**.
+Votre API aura presque toujours à envoyer un corps de **réponse**. Mais un client n'a pas toujours à envoyer un **corps de requête** : parfois il demande seulement un chemin, peut-être avec quelques paramètres de requête, mais n'envoie pas de corps.
-Pour déclarer un corps de **requête**, on utilise les modèles de Pydantic en profitant de tous leurs avantages et fonctionnalités.
+Pour déclarer un corps de **requête**, on utilise les modèles de [Pydantic](https://docs.pydantic.dev/) en profitant de tous leurs avantages et fonctionnalités.
-!!! info
- Pour envoyer de la donnée, vous devriez utiliser : `POST` (le plus populaire), `PUT`, `DELETE` ou `PATCH`.
+/// info
- Envoyer un corps dans une requête `GET` a un comportement non défini dans les spécifications, cela est néanmoins supporté par **FastAPI**, seulement pour des cas d'utilisation très complexes/extrêmes.
+Pour envoyer de la donnée, vous devez utiliser : `POST` (le plus populaire), `PUT`, `DELETE` ou `PATCH`.
- Ceci étant découragé, la documentation interactive générée par Swagger UI ne montrera pas de documentation pour le corps d'une requête `GET`, et les proxys intermédiaires risquent de ne pas le supporter.
+Envoyer un corps dans une requête `GET` a un comportement non défini dans les spécifications, cela est néanmoins supporté par **FastAPI**, seulement pour des cas d'utilisation très complexes/extrêmes.
-## Importez le `BaseModel` de Pydantic
+Ceci étant découragé, la documentation interactive générée par Swagger UI ne montrera pas de documentation pour le corps d'une requête `GET`, et les proxys intermédiaires risquent de ne pas le supporter.
+
+///
+
+## Importer le `BaseModel` de Pydantic { #import-pydantics-basemodel }
Commencez par importer la classe `BaseModel` du module `pydantic` :
-```Python hl_lines="4"
-{!../../../docs_src/body/tutorial001.py!}
-```
+{* ../../docs_src/body/tutorial001_py310.py hl[2] *}
-## Créez votre modèle de données
+## Créer votre modèle de données { #create-your-data-model }
Déclarez ensuite votre modèle de données en tant que classe qui hérite de `BaseModel`.
Utilisez les types Python standard pour tous les attributs :
-```Python hl_lines="7-11"
-{!../../../docs_src/body/tutorial001.py!}
-```
+{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}
-Tout comme pour la déclaration de paramètres de requête, quand un attribut de modèle a une valeur par défaut, il n'est pas nécessaire. Sinon, cet attribut doit être renseigné dans le corps de la requête. Pour rendre ce champ optionnel simplement, utilisez `None` comme valeur par défaut.
+Tout comme pour la déclaration de paramètres de requête, quand un attribut de modèle a une valeur par défaut, il n'est pas nécessaire. Sinon, il est requis. Utilisez `None` pour le rendre simplement optionnel.
-Par exemple, le modèle ci-dessus déclare un "objet" JSON (ou `dict` Python) tel que :
+Par exemple, le modèle ci-dessus déclare un JSON « `object` » (ou `dict` Python) tel que :
```JSON
{
@@ -46,7 +45,7 @@ Par exemple, le modèle ci-dessus déclare un "objet" JSON (ou `dict` Python) te
}
```
-...`description` et `tax` étant des attributs optionnels (avec `None` comme valeur par défaut), cet "objet" JSON serait aussi valide :
+... `description` et `tax` étant des attributs optionnels (avec `None` comme valeur par défaut), ce JSON « `object` » serait aussi valide :
```JSON
{
@@ -55,99 +54,94 @@ Par exemple, le modèle ci-dessus déclare un "objet" JSON (ou `dict` Python) te
}
```
-## Déclarez-le comme paramètre
+## Le déclarer comme paramètre { #declare-it-as-a-parameter }
-Pour l'ajouter à votre *opération de chemin*, déclarez-le comme vous déclareriez des paramètres de chemin ou de requête :
+Pour l'ajouter à votre *chemin d'accès*, déclarez-le comme vous déclareriez des paramètres de chemin ou de requête :
-```Python hl_lines="18"
-{!../../../docs_src/body/tutorial001.py!}
-```
+{* ../../docs_src/body/tutorial001_py310.py hl[16] *}
-...et déclarez que son type est le modèle que vous avez créé : `Item`.
+... et déclarez que son type est le modèle que vous avez créé : `Item`.
-## Résultats
+## Résultats { #results }
En utilisant uniquement les déclarations de type Python, **FastAPI** réussit à :
* Lire le contenu de la requête en tant que JSON.
* Convertir les types correspondants (si nécessaire).
* Valider la donnée.
- * Si la donnée est invalide, une erreur propre et claire sera renvoyée, indiquant exactement où était la donnée incorrecte.
+ * Si la donnée est invalide, une erreur propre et claire sera renvoyée, indiquant exactement où et quelle était la donnée incorrecte.
* Passer la donnée reçue dans le paramètre `item`.
- * Ce paramètre ayant été déclaré dans la fonction comme étant de type `Item`, vous aurez aussi tout le support offert par l'éditeur (auto-complétion, etc.) pour tous les attributs de ce paramètre et les types de ces attributs.
-* Générer des définitions JSON Schema pour votre modèle, qui peuvent être utilisées où vous en avez besoin dans votre projet ensuite.
-* Ces schémas participeront à la constitution du schéma généré OpenAPI, et seront donc utilisés par les documentations automatiquement générées.
+ * Ce paramètre ayant été déclaré dans la fonction comme étant de type `Item`, vous aurez aussi tout le support offert par l'éditeur (autocomplétion, etc.) pour tous les attributs de ce paramètre et les types de ces attributs.
+* Générer des définitions [JSON Schema](https://json-schema.org) pour votre modèle ; vous pouvez également les utiliser partout ailleurs si cela a du sens pour votre projet.
+* Ces schémas participeront à la constitution du schéma généré OpenAPI, et seront utilisés par les documentations automatiques UIs.
-## Documentation automatique
+## Documentation automatique { #automatic-docs }
Les schémas JSON de vos modèles seront intégrés au schéma OpenAPI global de votre application, et seront donc affichés dans la documentation interactive de l'API :
-Et seront aussi utilisés dans chaque *opération de chemin* de la documentation utilisant ces modèles :
+Et seront aussi utilisés dans chaque *chemin d'accès* de la documentation utilisant ces modèles :
-## Support de l'éditeur
+## Support de l'éditeur { #editor-support }
-Dans votre éditeur, vous aurez des annotations de types et de l'auto-complétion partout dans votre fonction (ce qui n'aurait pas été le cas si vous aviez utilisé un classique `dict` plutôt qu'un modèle Pydantic) :
+Dans votre éditeur, vous aurez des annotations de type et de l'autocomplétion partout dans votre fonction (ce qui n'aurait pas été le cas si vous aviez reçu un `dict` plutôt qu'un modèle Pydantic) :
-Et vous obtenez aussi de la vérification d'erreur pour les opérations incorrectes de types :
+Et vous obtenez aussi des vérifications d'erreurs pour les opérations de types incorrectes :
Ce n'est pas un hasard, ce framework entier a été bâti avec ce design comme objectif.
-Et cela a été rigoureusement testé durant la phase de design, avant toute implémentation, pour s'assurer que cela fonctionnerait avec tous les éditeurs.
+Et cela a été rigoureusement testé durant la phase de design, avant toute implémentation, pour vous assurer que cela fonctionnerait avec tous les éditeurs.
Des changements sur Pydantic ont même été faits pour supporter cela.
-Les captures d'écrans précédentes ont été prises sur Visual Studio Code.
+Les captures d'écran précédentes ont été prises sur [Visual Studio Code](https://code.visualstudio.com).
-Mais vous auriez le même support de l'éditeur avec PyCharm et la majorité des autres éditeurs de code Python.
+Mais vous auriez le même support de l'éditeur avec [PyCharm](https://www.jetbrains.com/pycharm/) et la majorité des autres éditeurs de code Python :
-!!! tip "Astuce"
- Si vous utilisez PyCharm comme éditeur, vous pouvez utiliser le Plugin Pydantic PyCharm Plugin.
+/// tip | Astuce
+
+Si vous utilisez [PyCharm](https://www.jetbrains.com/pycharm/) comme éditeur, vous pouvez utiliser le plug-in [Pydantic PyCharm Plugin](https://github.com/koxudaxi/pydantic-pycharm-plugin/).
+
+Ce qui améliore le support pour les modèles Pydantic avec :
- Ce qui améliore le support pour les modèles Pydantic avec :
+* de l'autocomplétion
+* des vérifications de type
+* du « refactoring »
+* de la recherche
+* des inspections
- * de l'auto-complétion
- * des vérifications de type
- * du "refactoring" (ou remaniement de code)
- * de la recherche
- * de l'inspection
+///
-## Utilisez le modèle
+## Utiliser le modèle { #use-the-model }
Dans la fonction, vous pouvez accéder à tous les attributs de l'objet du modèle directement :
-```Python hl_lines="21"
-{!../../../docs_src/body/tutorial002.py!}
-```
+{* ../../docs_src/body/tutorial002_py310.py *}
-## Corps de la requête + paramètres de chemin
+## Corps de la requête + paramètres de chemin { #request-body-path-parameters }
-Vous pouvez déclarer des paramètres de chemin et un corps de requête pour la même *opération de chemin*.
+Vous pouvez déclarer des paramètres de chemin et un corps de requête pour la même *chemin d'accès*.
**FastAPI** est capable de reconnaître que les paramètres de la fonction qui correspondent aux paramètres de chemin doivent être **récupérés depuis le chemin**, et que les paramètres de fonctions déclarés comme modèles Pydantic devraient être **récupérés depuis le corps de la requête**.
-```Python hl_lines="17-18"
-{!../../../docs_src/body/tutorial003.py!}
-```
+{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}
-## Corps de la requête + paramètres de chemin et de requête
+## Corps de la requête + paramètres de chemin et de requête { #request-body-path-query-parameters }
-Vous pouvez aussi déclarer un **corps**, et des paramètres de **chemin** et de **requête** dans la même *opération de chemin*.
+Vous pouvez aussi déclarer un **corps**, et des paramètres de **chemin** et de **requête** dans la même *chemin d'accès*.
**FastAPI** saura reconnaître chacun d'entre eux et récupérer la bonne donnée au bon endroit.
-```Python hl_lines="18"
-{!../../../docs_src/body/tutorial004.py!}
-```
+{* ../../docs_src/body/tutorial004_py310.py hl[16] *}
Les paramètres de la fonction seront reconnus comme tel :
@@ -155,11 +149,16 @@ Les paramètres de la fonction seront reconnus comme tel :
* Si le paramètre est d'un **type singulier** (comme `int`, `float`, `str`, `bool`, etc.), il sera interprété comme un paramètre de **requête**.
* Si le paramètre est déclaré comme ayant pour type un **modèle Pydantic**, il sera interprété comme faisant partie du **corps** de la requête.
-!!! note
- **FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `=None`.
+/// note | Remarque
+
+**FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`.
+
+L'annotation de type `str | None` n'est pas utilisée par **FastAPI** pour déterminer que la valeur n'est pas requise, il le saura parce qu'elle a une valeur par défaut `= None`.
+
+Mais ajouter ces annotations de type permettra à votre éditeur de vous offrir un meilleur support et de détecter des erreurs.
- Le type `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI**, mais sera utile à votre éditeur pour améliorer le support offert par ce dernier et détecter plus facilement des erreurs de type.
+///
-## Sans Pydantic
+## Sans Pydantic { #without-pydantic }
-Si vous ne voulez pas utiliser des modèles Pydantic, vous pouvez aussi utiliser des paramètres de **Corps**. Pour cela, allez voir la partie de la documentation sur [Corps de la requête - Paramètres multiples](body-multiple-params.md){.internal-link target=_blank}.
+Si vous ne voulez pas utiliser des modèles Pydantic, vous pouvez aussi utiliser des paramètres de **Body**. Pour cela, allez voir la documentation sur [Corps de la requête - Paramètres multiples : Valeurs singulières dans le corps](body-multiple-params.md#singular-values-in-body).
diff --git a/docs/fr/docs/tutorial/cookie-param-models.md b/docs/fr/docs/tutorial/cookie-param-models.md
new file mode 100644
index 0000000000000..c6fc2f82627c4
--- /dev/null
+++ b/docs/fr/docs/tutorial/cookie-param-models.md
@@ -0,0 +1,76 @@
+# Modèles de paramètres de cookies { #cookie-parameter-models }
+
+Si vous avez un groupe de **cookies** liés, vous pouvez créer un **modèle Pydantic** pour les déclarer. 🍪
+
+Cela vous permet de **réutiliser le modèle** à **plusieurs endroits** et aussi de déclarer des validations et des métadonnées pour tous les paramètres en une seule fois. 😎
+
+/// note | Remarque
+
+Ceci est pris en charge depuis la version `0.115.0` de FastAPI. 🤓
+
+///
+
+/// tip | Astuce
+
+Cette même technique s'applique à `Query`, `Cookie` et `Header`. 😎
+
+///
+
+## Déclarer des cookies avec un modèle Pydantic { #cookies-with-a-pydantic-model }
+
+Déclarez les paramètres de **cookie** dont vous avez besoin dans un **modèle Pydantic**, puis déclarez le paramètre comme `Cookie` :
+
+{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}
+
+**FastAPI** va **extraire** les données pour **chaque champ** à partir des **cookies** reçus dans la requête et vous fournir le modèle Pydantic que vous avez défini.
+
+## Consulter la documentation { #check-the-docs }
+
+Vous pouvez voir les cookies définis dans l'interface de la documentation à `/docs` :
+
+
+
+
+## Raccourci { #shortcut }
+
+Mais vous voyez qu'il y a ici de la duplication de code : nous écrivons `CommonQueryParams` deux fois :
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ sans Annotated
+
+/// tip | Astuce
+
+Privilégiez la version avec `Annotated` si possible.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+**FastAPI** fournit un raccourci pour ces cas, lorsque la dépendance est spécifiquement une classe que **FastAPI** va « appeler » pour créer une instance de la classe elle‑même.
+
+Pour ces cas précis, vous pouvez faire ce qui suit :
+
+Au lieu d'écrire :
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ sans Annotated
+
+/// tip | Astuce
+
+Privilégiez la version avec `Annotated` si possible.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+... vous écrivez :
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
+
+////
+
+//// tab | Python 3.10+ sans Annotated
+
+/// tip | Astuce
+
+Privilégiez la version avec `Annotated` si possible.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
+
+Vous déclarez la dépendance comme type du paramètre et vous utilisez `Depends()` sans aucun paramètre, au lieu d'avoir à réécrire la classe entière à l'intérieur de `Depends(CommonQueryParams)`.
+
+Le même exemple ressemblerait alors à ceci :
+
+{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *}
+
+... et **FastAPI** saura quoi faire.
+
+/// tip | Astuce
+
+Si cela vous semble plus déroutant qu'utile, ignorez‑le, vous n'en avez pas besoin.
+
+Ce n'est qu'un raccourci. Parce que **FastAPI** tient à vous aider à minimiser la duplication de code.
+
+///
diff --git a/docs/fr/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/fr/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
new file mode 100644
index 0000000000000..b32728a304bfc
--- /dev/null
+++ b/docs/fr/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -0,0 +1,69 @@
+# Gérer les dépendances dans les décorateurs de chemins d'accès { #dependencies-in-path-operation-decorators }
+
+Dans certains cas, vous n'avez pas vraiment besoin de la valeur de retour d'une dépendance dans votre *fonction de chemin d'accès*.
+
+Ou la dépendance ne retourne aucune valeur.
+
+Mais vous avez quand même besoin qu'elle soit exécutée/résolue.
+
+Dans ces cas, au lieu de déclarer un paramètre de *fonction de chemin d'accès* avec `Depends`, vous pouvez ajouter une `list` de `dependencies` au *décorateur de chemin d'accès*.
+
+## Ajouter `dependencies` au *décorateur de chemin d'accès* { #add-dependencies-to-the-path-operation-decorator }
+
+Le *décorateur de chemin d'accès* accepte un argument optionnel `dependencies`.
+
+Il doit s'agir d'une `list` de `Depends()` :
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
+
+Ces dépendances seront exécutées/résolues de la même manière que des dépendances normales. Mais leur valeur (si elles en retournent une) ne sera pas transmise à votre *fonction de chemin d'accès*.
+
+/// tip | Astuce
+
+Certains éditeurs vérifient les paramètres de fonction non utilisés et les signalent comme des erreurs.
+
+En utilisant ces `dependencies` dans le *décorateur de chemin d'accès*, vous pouvez vous assurer qu'elles sont exécutées tout en évitant des erreurs de l'éditeur/des outils.
+
+Cela peut également éviter toute confusion pour les nouveaux développeurs qui voient un paramètre inutilisé dans votre code et pourraient penser qu'il est superflu.
+
+///
+
+/// info | Info
+
+Dans cet exemple, nous utilisons des en-têtes personnalisés fictifs `X-Key` et `X-Token`.
+
+Mais dans des cas réels, lors de l'implémentation de la sécurité, vous tirerez davantage d'avantages en utilisant les [utilitaires de sécurité (chapitre suivant)](../security/index.md) intégrés.
+
+///
+
+## Gérer les erreurs et les valeurs de retour des dépendances { #dependencies-errors-and-return-values }
+
+Vous pouvez utiliser les mêmes *fonctions* de dépendance que d'habitude.
+
+### Définir les exigences des dépendances { #dependency-requirements }
+
+Elles peuvent déclarer des exigences pour la requête (comme des en-têtes) ou d'autres sous-dépendances :
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
+
+### Lever des exceptions { #raise-exceptions }
+
+Ces dépendances peuvent `raise` des exceptions, comme des dépendances normales :
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
+
+### Gérer les valeurs de retour { #return-values }
+
+Elles peuvent retourner des valeurs ou non, ces valeurs ne seront pas utilisées.
+
+Vous pouvez donc réutiliser une dépendance normale (qui retourne une valeur) que vous utilisez déjà ailleurs ; même si la valeur n'est pas utilisée, la dépendance sera exécutée :
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
+
+## Définir des dépendances pour un groupe de chemins d'accès { #dependencies-for-a-group-of-path-operations }
+
+Plus tard, en lisant comment structurer des applications plus grandes ([Applications plus grandes - Plusieurs fichiers](../../tutorial/bigger-applications.md)), éventuellement avec plusieurs fichiers, vous apprendrez à déclarer un unique paramètre `dependencies` pour un groupe de *chemins d'accès*.
+
+## Définir des dépendances globales { #global-dependencies }
+
+Ensuite, nous verrons comment ajouter des dépendances à l'application `FastAPI` entière, afin qu'elles s'appliquent à chaque *chemin d'accès*.
diff --git a/docs/fr/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/fr/docs/tutorial/dependencies/dependencies-with-yield.md
new file mode 100644
index 0000000000000..53d4ae4cf3a35
--- /dev/null
+++ b/docs/fr/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -0,0 +1,289 @@
+# Utiliser des dépendances avec `yield` { #dependencies-with-yield }
+
+FastAPI prend en charge des dépendances qui effectuent des étapes supplémentaires après l'exécution.
+
+Pour cela, utilisez `yield` au lieu de `return`, et écrivez les étapes supplémentaires (code) après.
+
+/// tip | Astuce
+
+Vous devez vous assurer d'utiliser `yield` une seule fois par dépendance.
+
+///
+
+/// note | Détails techniques
+
+Toute fonction valide à utiliser avec :
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) ou
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+sera valide comme dépendance **FastAPI**.
+
+En fait, FastAPI utilise ces deux décorateurs en interne.
+
+///
+
+## Créer une dépendance de base de données avec `yield` { #a-database-dependency-with-yield }
+
+Par exemple, vous pouvez l'utiliser pour créer une session de base de données et la fermer après la fin.
+
+Seul le code précédant et incluant l'instruction `yield` est exécuté avant la création de la réponse :
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
+
+La valeur transmise par `yield` est celle qui est injectée dans les *chemins d'accès* et autres dépendances :
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
+
+Le code suivant l'instruction `yield` est exécuté après la réponse :
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
+
+/// tip | Astuce
+
+Vous pouvez utiliser des fonctions `async` ou des fonctions classiques.
+
+**FastAPI** fera ce qu'il faut dans chaque cas, comme avec des dépendances normales.
+
+///
+
+## Créer une dépendance avec `yield` et `try` { #a-dependency-with-yield-and-try }
+
+Si vous utilisez un bloc `try` dans une dépendance avec `yield`, vous recevrez toute exception qui a été levée lors de l'utilisation de la dépendance.
+
+Par exemple, si à un moment donné, dans une autre dépendance ou dans un *chemin d'accès*, un code a effectué un « rollback » de transaction de base de données ou a créé une autre exception, vous recevrez l'exception dans votre dépendance.
+
+Vous pouvez donc rechercher cette exception spécifique dans la dépendance avec `except SomeException`.
+
+De la même manière, vous pouvez utiliser `finally` pour vous assurer que les étapes de sortie sont exécutées, qu'il y ait eu une exception ou non.
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
+
+## Utiliser des sous-dépendances avec `yield` { #sub-dependencies-with-yield }
+
+Vous pouvez avoir des sous-dépendances et des « arbres » de sous-dépendances de toute taille et forme, et certaines ou toutes peuvent utiliser `yield`.
+
+**FastAPI** s'assurera que le « code de sortie » dans chaque dépendance avec `yield` est exécuté dans le bon ordre.
+
+Par exemple, `dependency_c` peut dépendre de `dependency_b`, et `dependency_b` de `dependency_a` :
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
+
+Et elles peuvent toutes utiliser `yield`.
+
+Dans ce cas, `dependency_c`, pour exécuter son code de sortie, a besoin que la valeur de `dependency_b` (appelée ici `dep_b`) soit toujours disponible.
+
+Et, à son tour, `dependency_b` a besoin que la valeur de `dependency_a` (appelée ici `dep_a`) soit disponible pour son code de sortie.
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
+
+De la même manière, vous pouvez avoir certaines dépendances avec `yield` et d'autres avec `return`, et faire en sorte que certaines dépendent des autres.
+
+Et vous pouvez avoir une seule dépendance qui exige plusieurs autres dépendances avec `yield`, etc.
+
+Vous pouvez combiner les dépendances comme vous le souhaitez.
+
+**FastAPI** s'assurera que tout est exécuté dans le bon ordre.
+
+/// note | Détails techniques
+
+Cela fonctionne grâce aux [gestionnaires de contexte](https://docs.python.org/3/library/contextlib.html) de Python.
+
+**FastAPI** les utilise en interne pour y parvenir.
+
+///
+
+## Utiliser des dépendances avec `yield` et `HTTPException` { #dependencies-with-yield-and-httpexception }
+
+Vous avez vu que vous pouvez utiliser des dépendances avec `yield` et avoir des blocs `try` qui tentent d'exécuter du code puis exécutent du code de sortie après `finally`.
+
+Vous pouvez également utiliser `except` pour intercepter l'exception qui a été levée et faire quelque chose avec.
+
+Par exemple, vous pouvez lever une autre exception, comme `HTTPException`.
+
+/// tip | Astuce
+
+C'est une technique plutôt avancée, et dans la plupart des cas vous n'en aurez pas vraiment besoin, car vous pouvez lever des exceptions (y compris `HTTPException`) depuis le reste de votre code applicatif, par exemple, dans la *fonction de chemin d'accès*.
+
+Mais elle est à votre disposition si vous en avez besoin. 🤓
+
+///
+
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
+
+Si vous souhaitez intercepter des exceptions et créer une réponse personnalisée en fonction de cela, créez un [Gestionnaire d'exceptions personnalisé](../handling-errors.md#install-custom-exception-handlers).
+
+## Utiliser des dépendances avec `yield` et `except` { #dependencies-with-yield-and-except }
+
+Si vous interceptez une exception avec `except` dans une dépendance avec `yield` et que vous ne la relancez pas (ou que vous ne levez pas une nouvelle exception), FastAPI ne pourra pas remarquer qu'il y a eu une exception, de la même manière que cela se produirait avec Python classique :
+
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
+
+Dans ce cas, le client verra une réponse *HTTP 500 Internal Server Error* comme il se doit, étant donné que nous ne levons pas de `HTTPException` ou similaire, mais le serveur **n'aura aucun logs** ni aucune autre indication de l'erreur. 😱
+
+### Toujours `raise` dans les dépendances avec `yield` et `except` { #always-raise-in-dependencies-with-yield-and-except }
+
+Si vous interceptez une exception dans une dépendance avec `yield`, à moins de lever une autre `HTTPException` ou similaire, **vous devez relancer l'exception d'origine**.
+
+Vous pouvez relancer la même exception avec `raise` :
+
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
+
+À présent, le client recevra la même réponse *HTTP 500 Internal Server Error*, mais le serveur aura notre `InternalError` personnalisé dans les logs. 😎
+
+## Comprendre l'exécution des dépendances avec `yield` { #execution-of-dependencies-with-yield }
+
+La séquence d'exécution ressemble plus ou moins à ce diagramme. Le temps s'écoule de haut en bas. Et chaque colonne représente une des parties qui interagit ou exécute du code.
+
+```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,operation: Can raise exceptions, including HTTPException
+ client ->> dep: Start request
+ Note over dep: Run code up to yield
+ opt raise Exception
+ dep -->> handler: Raise Exception
+ handler -->> client: HTTP error response
+ end
+ dep ->> operation: Run dependency, e.g. DB session
+ opt raise
+ operation -->> dep: Raise Exception (e.g. HTTPException)
+ opt handle
+ dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception
+ end
+ handler -->> client: HTTP error response
+ 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 -->> tasks: Handle exceptions in the background task code
+ end
+```
+
+/// info
+
+Une **seule réponse** sera envoyée au client. Il peut s'agir d'une des réponses d'erreur ou de la réponse provenant du *chemin d'accès*.
+
+Après l'envoi de l'une de ces réponses, aucune autre réponse ne peut être envoyée.
+
+///
+
+/// tip | Astuce
+
+Si vous levez une exception dans le code de la *fonction de chemin d'accès*, elle sera transmise aux dépendances avec `yield`, y compris `HTTPException`. Dans la plupart des cas, vous voudrez relancer cette même exception ou en lever une nouvelle depuis la dépendance avec `yield` pour vous assurer qu'elle est correctement gérée.
+
+///
+
+## Utiliser la sortie anticipée et `scope` { #early-exit-and-scope }
+
+Normalement, le code de sortie des dépendances avec `yield` est exécuté **après la réponse** envoyée au client.
+
+Mais si vous savez que vous n'aurez pas besoin d'utiliser la dépendance après être revenu de la *fonction de chemin d'accès*, vous pouvez utiliser `Depends(scope="function")` pour indiquer à FastAPI qu'il doit fermer la dépendance après le retour de la *fonction de chemin d'accès*, mais **avant** que la **réponse ne soit envoyée**.
+
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
+
+`Depends()` reçoit un paramètre `scope` qui peut être :
+
+* « function » : démarrer la dépendance avant la *fonction de chemin d'accès* qui gère la requête, terminer la dépendance après la fin de la *fonction de chemin d'accès*, mais **avant** que la réponse ne soit renvoyée au client. Ainsi, la fonction de dépendance sera exécutée **autour** de la *fonction de chemin d'accès*.
+* « request » : démarrer la dépendance avant la *fonction de chemin d'accès* qui gère la requête (similaire à l'utilisation de « function »), mais terminer **après** que la réponse a été renvoyée au client. Ainsi, la fonction de dépendance sera exécutée **autour** du cycle **requête** et réponse.
+
+S'il n'est pas spécifié et que la dépendance utilise `yield`, le `scope` sera par défaut « request ».
+
+### Définir `scope` pour les sous-dépendances { #scope-for-sub-dependencies }
+
+Lorsque vous déclarez une dépendance avec un `scope="request"` (par défaut), toute sous-dépendance doit également avoir un `scope` de « request ».
+
+Mais une dépendance avec un `scope` de « function » peut avoir des dépendances avec un `scope` de « function » et un `scope` de « request ».
+
+Cela vient du fait que toute dépendance doit pouvoir exécuter son code de sortie avant ses sous-dépendances, car elle pourrait encore avoir besoin de les utiliser pendant son code de sortie.
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant dep_req as Dep scope="request"
+participant dep_func as Dep scope="function"
+participant operation as Path Operation
+
+ client ->> dep_req: Start request
+ Note over dep_req: Run code up to yield
+ dep_req ->> dep_func: Pass dependency
+ Note over dep_func: Run code up to yield
+ dep_func ->> operation: Run path operation with dependency
+ operation ->> dep_func: Return from path operation
+ Note over dep_func: Run code after yield
+ Note over dep_func: ✅ Dependency closed
+ dep_func ->> client: Send response to client
+ Note over client: Response sent
+ Note over dep_req: Run code after yield
+ Note over dep_req: ✅ Dependency closed
+```
+
+## Utiliser des dépendances avec `yield`, `HTTPException`, `except` et Background Tasks { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+Les dépendances avec `yield` ont évolué au fil du temps pour couvrir différents cas d'utilisation et corriger certains problèmes.
+
+Si vous souhaitez voir ce qui a changé dans différentes versions de FastAPI, vous pouvez en savoir plus dans le guide avancé, dans [Dépendances avancées - Dépendances avec `yield`, `HTTPException`, `except` et Background Tasks](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks).
+## Gestionnaires de contexte { #context-managers }
+
+### Que sont les « Context Managers » { #what-are-context-managers }
+
+Les « Context Managers » sont des objets Python que vous pouvez utiliser dans une instruction `with`.
+
+Par exemple, [vous pouvez utiliser `with` pour lire un fichier](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files) :
+
+```Python
+with open("./somefile.txt") as f:
+ contents = f.read()
+ print(contents)
+```
+
+En coulisse, `open("./somefile.txt")` crée un objet appelé « Context Manager ».
+
+Lorsque le bloc `with` se termine, il s'assure de fermer le fichier, même s'il y a eu des exceptions.
+
+Lorsque vous créez une dépendance avec `yield`, **FastAPI** créera en interne un gestionnaire de contexte pour celle-ci et le combinera avec d'autres outils associés.
+
+### Utiliser des gestionnaires de contexte dans des dépendances avec `yield` { #using-context-managers-in-dependencies-with-yield }
+
+/// warning | Alertes
+
+C'est, plus ou moins, une idée « avancée ».
+
+Si vous débutez avec **FastAPI**, vous voudrez peut-être l'ignorer pour le moment.
+
+///
+
+En Python, vous pouvez créer des gestionnaires de contexte en [créant une classe avec deux méthodes : `__enter__()` et `__exit__()`](https://docs.python.org/3/reference/datamodel.html#context-managers).
+
+Vous pouvez également les utiliser dans des dépendances **FastAPI** avec `yield` en utilisant
+des instructions `with` ou `async with` à l'intérieur de la fonction de dépendance :
+
+{* ../../docs_src/dependencies/tutorial010_py310.py hl[1:9,13] *}
+
+/// tip | Astuce
+
+Une autre façon de créer un gestionnaire de contexte consiste à utiliser :
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) ou
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+pour décorer une fonction avec un unique `yield`.
+
+C'est ce que **FastAPI** utilise en interne pour les dépendances avec `yield`.
+
+Mais vous n'avez pas à utiliser ces décorateurs pour les dépendances FastAPI (et vous ne devriez pas).
+
+FastAPI le fera pour vous en interne.
+
+///
diff --git a/docs/fr/docs/tutorial/dependencies/global-dependencies.md b/docs/fr/docs/tutorial/dependencies/global-dependencies.md
new file mode 100644
index 0000000000000..f334c5d500b60
--- /dev/null
+++ b/docs/fr/docs/tutorial/dependencies/global-dependencies.md
@@ -0,0 +1,15 @@
+# Dépendances globales { #global-dependencies }
+
+Pour certains types d'applications, vous pourriez vouloir ajouter des dépendances à l'application entière.
+
+Comme vous pouvez [ajouter des `dependencies` aux *décorateurs de chemin d'accès*](dependencies-in-path-operation-decorators.md), vous pouvez les ajouter à l'application `FastAPI`.
+
+Dans ce cas, elles seront appliquées à tous les *chemins d'accès* de l'application :
+
+{* ../../docs_src/dependencies/tutorial012_an_py310.py hl[17] *}
+
+Et toutes les idées de la section sur [l'ajout de `dependencies` aux *décorateurs de chemin d'accès*](dependencies-in-path-operation-decorators.md) s'appliquent toujours, mais dans ce cas à tous les *chemins d'accès* de l'application.
+
+## Dépendances pour des groupes de *chemins d'accès* { #dependencies-for-groups-of-path-operations }
+
+Plus tard, en lisant comment structurer des applications plus grandes ([Applications plus grandes - Plusieurs fichiers](../../tutorial/bigger-applications.md)), éventuellement avec plusieurs fichiers, vous apprendrez comment déclarer un unique paramètre `dependencies` pour un groupe de *chemins d'accès*.
diff --git a/docs/fr/docs/tutorial/dependencies/index.md b/docs/fr/docs/tutorial/dependencies/index.md
new file mode 100644
index 0000000000000..03eea57e326e7
--- /dev/null
+++ b/docs/fr/docs/tutorial/dependencies/index.md
@@ -0,0 +1,250 @@
+# Dépendances { #dependencies }
+
+**FastAPI** dispose d’un système d’**Injection de dépendances** très puissant mais intuitif.
+
+Il est conçu pour être très simple à utiliser, et pour faciliter l’intégration d’autres composants à **FastAPI** pour n’importe quel développeur.
+
+## Qu’est-ce que « l’injection de dépendances » { #what-is-dependency-injection }
+
+L’**« injection de dépendances »** signifie, en programmation, qu’il existe un moyen pour votre code (dans ce cas, vos fonctions de chemins d’accès) de déclarer ce dont il a besoin pour fonctionner et utiliser : « dépendances ».
+
+Ensuite, ce système (dans ce cas **FastAPI**) se charge de faire tout le nécessaire pour fournir à votre code ces dépendances requises (« injecter » les dépendances).
+
+C’est très utile lorsque vous avez besoin de :
+
+* Avoir de la logique partagée (la même logique de code encore et encore).
+* Partager des connexions à la base de données.
+* Imposer la sécurité, l’authentification, des exigences de rôles, etc.
+* Et bien d’autres choses ...
+
+Tout cela, en minimisant la répétition de code.
+
+## Premiers pas { #first-steps }
+
+Voyons un exemple très simple. Il sera tellement simple qu’il n’est pas très utile, pour l’instant.
+
+Mais de cette façon nous pouvons nous concentrer sur le fonctionnement du système d’**injection de dépendances**.
+
+### Créer une dépendance, ou « dependable » { #create-a-dependency-or-dependable }
+
+Concentrons-nous d’abord sur la dépendance.
+
+C’est simplement une fonction qui peut prendre tous les mêmes paramètres qu’une fonction de chemin d’accès peut prendre :
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}
+
+C’est tout.
+
+**2 lignes**.
+
+Et elle a la même forme et structure que toutes vos fonctions de chemins d’accès.
+
+Vous pouvez la considérer comme une fonction de chemin d’accès sans le « décorateur » (sans le `@app.get("/some-path")`).
+
+Et elle peut retourner tout ce que vous voulez.
+
+Dans ce cas, cette dépendance attend :
+
+* Un paramètre de requête optionnel `q` qui est une `str`.
+* Un paramètre de requête optionnel `skip` qui est un `int`, et vaut `0` par défaut.
+* Un paramètre de requête optionnel `limit` qui est un `int`, et vaut `100` par défaut.
+
+Puis elle retourne simplement un `dict` contenant ces valeurs.
+
+/// info
+
+FastAPI a ajouté la prise en charge de `Annotated` (et a commencé à le recommander) dans la version 0.95.0.
+
+Si vous avez une version plus ancienne, vous obtiendrez des erreurs en essayant d’utiliser `Annotated`.
+
+Vous devez vous assurer de [mettre à niveau la version de FastAPI](../../deployment/versions.md#upgrading-the-fastapi-versions) vers au moins la 0.95.1 avant d’utiliser `Annotated`.
+
+///
+
+### Importer `Depends` { #import-depends }
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}
+
+### Déclarer la dépendance, dans le « dependant » { #declare-the-dependency-in-the-dependant }
+
+De la même manière que vous utilisez `Body`, `Query`, etc. avec les paramètres de votre fonction de chemin d’accès, utilisez `Depends` avec un nouveau paramètre :
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}
+
+Même si vous utilisez `Depends` dans les paramètres de votre fonction de la même façon que `Body`, `Query`, etc., `Depends` fonctionne un peu différemment.
+
+Vous ne donnez à `Depends` qu’un seul paramètre.
+
+Ce paramètre doit être quelque chose comme une fonction.
+
+Vous ne l’appelez pas directement (n’ajoutez pas de parenthèses à la fin), vous le passez simplement en paramètre à `Depends()`.
+
+Et cette fonction prend des paramètres de la même manière que les fonctions de chemins d’accès.
+
+/// tip | Astuce
+
+Vous verrez quelles autres « choses », en plus des fonctions, peuvent être utilisées comme dépendances dans le prochain chapitre.
+
+///
+
+Chaque fois qu’une nouvelle requête arrive, **FastAPI** se charge de :
+
+* Appeler votre fonction de dépendance (« dependable ») avec les bons paramètres.
+* Récupérer le résultat de votre fonction.
+* Affecter ce résultat au paramètre dans votre fonction de chemin d’accès.
+
+```mermaid
+graph TB
+
+common_parameters(["common_parameters"])
+read_items["/items/"]
+read_users["/users/"]
+
+common_parameters --> read_items
+common_parameters --> read_users
+```
+
+De cette façon vous écrivez le code partagé une seule fois et **FastAPI** se charge de l’appeler pour vos chemins d’accès.
+
+/// check | Vérifications
+
+Notez que vous n’avez pas à créer une classe spéciale et à la passer quelque part à **FastAPI** pour l’« enregistrer » ou quoi que ce soit de similaire.
+
+Vous la passez simplement à `Depends` et **FastAPI** sait faire le reste.
+
+///
+
+## Partager des dépendances `Annotated` { #share-annotated-dependencies }
+
+Dans les exemples ci-dessus, vous voyez qu’il y a un tout petit peu de **duplication de code**.
+
+Lorsque vous devez utiliser la dépendance `common_parameters()`, vous devez écrire tout le paramètre avec l’annotation de type et `Depends()` :
+
+```Python
+commons: Annotated[dict, Depends(common_parameters)]
+```
+
+Mais comme nous utilisons `Annotated`, nous pouvons stocker cette valeur `Annotated` dans une variable et l’utiliser à plusieurs endroits :
+
+{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}
+
+/// tip | Astuce
+
+C’est simplement du Python standard, cela s’appelle un « alias de type », ce n’est en fait pas spécifique à **FastAPI**.
+
+Mais comme **FastAPI** est basé sur les standards Python, y compris `Annotated`, vous pouvez utiliser cette astuce dans votre code. 😎
+
+///
+
+Les dépendances continueront de fonctionner comme prévu, et la **meilleure partie** est que **l’information de type sera conservée**, ce qui signifie que votre éditeur pourra continuer à vous fournir **l’autocomplétion**, **des erreurs en ligne**, etc. Idem pour d’autres outils comme `mypy`.
+
+Cela sera particulièrement utile lorsque vous l’utiliserez dans une **grande base de code** où vous utilisez **les mêmes dépendances** encore et encore dans **de nombreux chemins d’accès**.
+
+## Utiliser `async` ou non { #to-async-or-not-to-async }
+
+Comme les dépendances seront aussi appelées par **FastAPI** (tout comme vos fonctions de chemins d’accès), les mêmes règles s’appliquent lors de la définition de vos fonctions.
+
+Vous pouvez utiliser `async def` ou un `def` normal.
+
+Et vous pouvez déclarer des dépendances avec `async def` à l’intérieur de fonctions de chemins d’accès `def` normales, ou des dépendances `def` à l’intérieur de fonctions de chemins d’accès `async def`, etc.
+
+Peu importe. **FastAPI** saura quoi faire.
+
+/// note | Remarque
+
+Si vous ne savez pas, consultez la section [Async : *« Pressé ? »*](../../async.md#in-a-hurry) à propos de `async` et `await` dans la documentation.
+
+///
+
+## Intégrer à OpenAPI { #integrated-with-openapi }
+
+Toutes les déclarations de requête, validations et exigences de vos dépendances (et sous-dépendances) seront intégrées dans le même schéma OpenAPI.
+
+Ainsi, la documentation interactive contiendra aussi toutes les informations issues de ces dépendances :
+
+
+
+## Utilisation simple { #simple-usage }
+
+Si vous y regardez de près, les fonctions de chemins d’accès sont déclarées pour être utilisées chaque fois qu’un « chemin » et une « opération » correspondent, puis **FastAPI** se charge d’appeler la fonction avec les bons paramètres, en extrayant les données de la requête.
+
+En réalité, tous (ou la plupart) des frameworks web fonctionnent de cette manière.
+
+Vous n’appelez jamais ces fonctions directement. Elles sont appelées par votre framework (dans ce cas, **FastAPI**).
+
+Avec le système d’injection de dépendances, vous pouvez aussi indiquer à **FastAPI** que votre fonction de chemin d’accès « dépend » également d’autre chose qui doit être exécuté avant votre fonction de chemin d’accès, et **FastAPI** se chargera de l’exécuter et d’« injecter » les résultats.
+
+D’autres termes courants pour cette même idée « d’injection de dépendances » sont :
+
+* ressources
+* fournisseurs
+* services
+* injectables
+* composants
+
+## Plug-ins **FastAPI** { #fastapi-plug-ins }
+
+Les intégrations et « plug-ins » peuvent être construits en utilisant le système d’**injection de dépendances**. Mais en réalité, il n’y a **pas besoin de créer des « plug-ins »**, car en utilisant des dépendances il est possible de déclarer un nombre infini d’intégrations et d’interactions qui deviennent disponibles pour vos fonctions de chemins d’accès.
+
+Et les dépendances peuvent être créées de manière très simple et intuitive, ce qui vous permet d’importer juste les packages Python dont vous avez besoin, et de les intégrer à vos fonctions d’API en quelques lignes de code, *littéralement*.
+
+Vous verrez des exemples de cela dans les prochains chapitres, à propos des bases de données relationnelles et NoSQL, de la sécurité, etc.
+
+## Compatibilité **FastAPI** { #fastapi-compatibility }
+
+La simplicité du système d’injection de dépendances rend **FastAPI** compatible avec :
+
+* toutes les bases de données relationnelles
+* les bases de données NoSQL
+* les packages externes
+* les API externes
+* les systèmes d’authentification et d’autorisation
+* les systèmes de supervision d’usage d’API
+* les systèmes d’injection de données de réponse
+* etc.
+
+## Simple et puissant { #simple-and-powerful }
+
+Bien que le système hiérarchique d’injection de dépendances soit très simple à définir et à utiliser, il reste très puissant.
+
+Vous pouvez définir des dépendances qui, à leur tour, peuvent définir leurs propres dépendances.
+
+Au final, un arbre hiérarchique de dépendances est construit, et le système d’**injection de dépendances** se charge de résoudre toutes ces dépendances pour vous (et leurs sous-dépendances) et de fournir (injecter) les résultats à chaque étape.
+
+Par exemple, supposons que vous ayez 4 endpoints d’API (chemins d’accès) :
+
+* `/items/public/`
+* `/items/private/`
+* `/users/{user_id}/activate`
+* `/items/pro/`
+
+alors vous pourriez ajouter différentes exigences d’autorisations pour chacun d’eux uniquement avec des dépendances et des sous-dépendances :
+
+```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
+```
+
+## Intégrer à **OpenAPI** { #integrated-with-openapi_1 }
+
+Toutes ces dépendances, tout en déclarant leurs exigences, ajoutent également des paramètres, des validations, etc. à vos chemins d’accès.
+
+**FastAPI** se chargera d’ajouter le tout au schéma OpenAPI, afin que cela apparaisse dans les systèmes de documentation interactive.
diff --git a/docs/fr/docs/tutorial/dependencies/sub-dependencies.md b/docs/fr/docs/tutorial/dependencies/sub-dependencies.md
new file mode 100644
index 0000000000000..473ff02ba8cc1
--- /dev/null
+++ b/docs/fr/docs/tutorial/dependencies/sub-dependencies.md
@@ -0,0 +1,105 @@
+# Sous-dépendances { #sub-dependencies }
+
+Vous pouvez créer des dépendances qui ont des sous-dépendances.
+
+Elles peuvent être aussi profondes que nécessaire.
+
+**FastAPI** se chargera de les résoudre.
+
+## Créer une première dépendance « dependable » { #first-dependency-dependable }
+
+Vous pouvez créer une première dépendance (« dependable ») comme :
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}
+
+Elle déclare un paramètre de requête optionnel `q` de type `str`, puis le retourne simplement.
+
+C'est assez simple (pas très utile), mais cela nous aidera à nous concentrer sur le fonctionnement des sous-dépendances.
+
+## Créer une seconde dépendance, « dependable » et « dependant » { #second-dependency-dependable-and-dependant }
+
+Vous pouvez ensuite créer une autre fonction de dépendance (un « dependable ») qui, en même temps, déclare sa propre dépendance (elle est donc aussi un « dependant ») :
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}
+
+Concentrons-nous sur les paramètres déclarés :
+
+- Même si cette fonction est elle‑même une dépendance (« dependable »), elle déclare aussi une autre dépendance (elle « dépend » d'autre chose).
+ - Elle dépend de `query_extractor` et affecte la valeur renvoyée au paramètre `q`.
+- Elle déclare également un cookie `last_query` optionnel, de type `str`.
+ - Si l'utilisateur n'a fourni aucune requête `q`, nous utilisons la dernière requête utilisée, que nous avons enregistrée auparavant dans un cookie.
+
+## Utiliser la dépendance { #use-the-dependency }
+
+Nous pouvons ensuite utiliser la dépendance avec :
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}
+
+/// info
+
+Notez que nous ne déclarons qu'une seule dépendance dans la *fonction de chemin d'accès*, `query_or_cookie_extractor`.
+
+Mais **FastAPI** saura qu'il doit d'abord résoudre `query_extractor`, pour passer ses résultats à `query_or_cookie_extractor` lors de son appel.
+
+///
+
+```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
+```
+
+## Utiliser la même dépendance plusieurs fois { #using-the-same-dependency-multiple-times }
+
+Si l'une de vos dépendances est déclarée plusieurs fois pour le même *chemin d'accès*, par exemple si plusieurs dépendances ont une sous-dépendance commune, **FastAPI** saura n'appeler cette sous-dépendance qu'une seule fois par requête.
+
+Et il enregistrera la valeur renvoyée dans un « cache » et la transmettra à tous les « dependants » qui en ont besoin dans cette requête spécifique, au lieu d'appeler la dépendance plusieurs fois pour la même requête.
+
+Dans un scénario avancé où vous savez que vous avez besoin que la dépendance soit appelée à chaque étape (éventuellement plusieurs fois) dans la même requête au lieu d'utiliser la valeur « mise en cache », vous pouvez définir le paramètre `use_cache=False` lors de l'utilisation de `Depends` :
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+//// tab | Python 3.10+ non annoté
+
+/// tip | Astuce
+
+Privilégiez la version `Annotated` si possible.
+
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+## Récapituler { #recap }
+
+En dehors de tout le jargon utilisé ici, le système d'**injection de dépendances** est assez simple.
+
+Ce ne sont que des fonctions qui ressemblent aux *fonctions de chemin d'accès*.
+
+Mais il est très puissant et vous permet de déclarer des « graphes » (arbres) de dépendances imbriquées aussi profondément que vous le souhaitez.
+
+/// tip | Astuce
+
+Tout cela peut ne pas sembler très utile avec ces exemples simples.
+
+Mais vous verrez à quel point c'est utile dans les chapitres sur la **sécurité**.
+
+Et vous verrez aussi la quantité de code que cela vous fera économiser.
+
+///
diff --git a/docs/fr/docs/tutorial/encoder.md b/docs/fr/docs/tutorial/encoder.md
new file mode 100644
index 0000000000000..15a6479ff39ac
--- /dev/null
+++ b/docs/fr/docs/tutorial/encoder.md
@@ -0,0 +1,35 @@
+# Encodeur compatible JSON { #json-compatible-encoder }
+
+Il existe des cas où vous pourriez avoir besoin de convertir un type de données (comme un modèle Pydantic) en quelque chose de compatible avec JSON (comme un `dict`, `list`, etc.).
+
+Par exemple, si vous devez le stocker dans une base de données.
+
+Pour cela, **FastAPI** fournit une fonction `jsonable_encoder()`.
+
+## Utiliser `jsonable_encoder` { #using-the-jsonable-encoder }
+
+Imaginons que vous ayez une base de données `fake_db` qui ne reçoit que des données compatibles JSON.
+
+Par exemple, elle ne reçoit pas d'objets `datetime`, car ceux-ci ne sont pas compatibles avec JSON.
+
+Ainsi, un objet `datetime` doit être converti en une `str` contenant les données au [format ISO](https://en.wikipedia.org/wiki/ISO_8601).
+
+De la même manière, cette base de données n'accepterait pas un modèle Pydantic (un objet avec des attributs), seulement un `dict`.
+
+Vous pouvez utiliser `jsonable_encoder` pour cela.
+
+Elle reçoit un objet, comme un modèle Pydantic, et renvoie une version compatible JSON :
+
+{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *}
+
+Dans cet exemple, elle convertirait le modèle Pydantic en `dict`, et le `datetime` en `str`.
+
+Le résultat de son appel est quelque chose qui peut être encodé avec la fonction standard de Python [`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps).
+
+Elle ne renvoie pas une grande `str` contenant les données au format JSON (sous forme de chaîne). Elle renvoie une structure de données standard de Python (par ex. un `dict`) avec des valeurs et sous-valeurs toutes compatibles avec JSON.
+
+/// note | Remarque
+
+`jsonable_encoder` est en fait utilisée par **FastAPI** en interne pour convertir des données. Mais elle est utile dans de nombreux autres scénarios.
+
+///
diff --git a/docs/fr/docs/tutorial/extra-data-types.md b/docs/fr/docs/tutorial/extra-data-types.md
new file mode 100644
index 0000000000000..7ee6816c8251d
--- /dev/null
+++ b/docs/fr/docs/tutorial/extra-data-types.md
@@ -0,0 +1,62 @@
+# Types de données supplémentaires { #extra-data-types }
+
+Jusqu'à présent, vous avez utilisé des types de données courants, comme :
+
+* `int`
+* `float`
+* `str`
+* `bool`
+
+Mais vous pouvez aussi utiliser des types de données plus complexes.
+
+Et vous bénéficierez toujours des mêmes fonctionnalités que jusqu'à présent :
+
+* Excellente prise en charge dans l'éditeur.
+* Conversion des données à partir des requêtes entrantes.
+* Conversion des données pour les données de réponse.
+* Validation des données.
+* Annotations et documentation automatiques.
+
+## Autres types de données { #other-data-types }
+
+Voici quelques types de données supplémentaires que vous pouvez utiliser :
+
+* `UUID` :
+ * Un « identifiant universel unique » standard, couramment utilisé comme ID dans de nombreuses bases de données et systèmes.
+ * Dans les requêtes et les réponses, il sera représenté sous forme de `str`.
+* `datetime.datetime` :
+ * Un `datetime.datetime` Python.
+ * Dans les requêtes et les réponses, il sera représenté sous forme de `str` au format ISO 8601, par exemple : `2008-09-15T15:53:00+05:00`.
+* `datetime.date` :
+ * `datetime.date` Python.
+ * Dans les requêtes et les réponses, il sera représenté sous forme de `str` au format ISO 8601, par exemple : `2008-09-15`.
+* `datetime.time` :
+ * Un `datetime.time` Python.
+ * Dans les requêtes et les réponses, il sera représenté sous forme de `str` au format ISO 8601, par exemple : `14:23:55.003`.
+* `datetime.timedelta` :
+ * Un `datetime.timedelta` Python.
+ * Dans les requêtes et les réponses, il sera représenté sous forme de `float` de secondes totales.
+ * Pydantic permet aussi de le représenter sous la forme d'un « encodage de différence de temps ISO 8601 », [voir la documentation pour plus d'informations](https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers).
+* `frozenset` :
+ * Dans les requêtes et les réponses, traité de la même manière qu'un `set` :
+ * Dans les requêtes, une liste sera lue, les doublons éliminés, puis convertie en `set`.
+ * Dans les réponses, le `set` sera converti en `list`.
+ * Le schéma généré indiquera que les valeurs du `set` sont uniques (en utilisant `uniqueItems` de JSON Schema).
+* `bytes` :
+ * `bytes` Python standard.
+ * Dans les requêtes et les réponses, traité comme une `str`.
+ * Le schéma généré indiquera qu'il s'agit d'une `str` avec le « format » `binary`.
+* `Decimal` :
+ * `Decimal` Python standard.
+ * Dans les requêtes et les réponses, géré de la même manière qu'un `float`.
+* Vous pouvez consulter tous les types de données Pydantic valides ici : [Types de données Pydantic](https://docs.pydantic.dev/latest/usage/types/types/).
+
+## Exemple { #example }
+
+Voici un exemple de *chemin d'accès* avec des paramètres utilisant certains des types ci-dessus.
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *}
+
+Notez que les paramètres à l'intérieur de la fonction ont leur type de données naturel et que vous pouvez, par exemple, effectuer des manipulations de dates normales, comme :
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *}
diff --git a/docs/fr/docs/tutorial/extra-models.md b/docs/fr/docs/tutorial/extra-models.md
new file mode 100644
index 0000000000000..24a3fa31b76f9
--- /dev/null
+++ b/docs/fr/docs/tutorial/extra-models.md
@@ -0,0 +1,211 @@
+# Modèles supplémentaires { #extra-models }
+
+En poursuivant l'exemple précédent, il est courant d'avoir plusieurs modèles liés.
+
+C'est particulièrement vrai pour les modèles d'utilisateur, car :
+
+* Le modèle d'entrée doit pouvoir contenir un mot de passe.
+* Le modèle de sortie ne doit pas avoir de mot de passe.
+* Le modèle de base de données devra probablement avoir un mot de passe haché.
+
+/// danger | Danger
+
+Ne stockez jamais les mots de passe des utilisateurs en clair. Stockez toujours un « hachage sécurisé » que vous pourrez ensuite vérifier.
+
+Si vous ne savez pas ce que c'est, vous apprendrez ce qu'est un « hachage de mot de passe » dans les [chapitres sur la sécurité](security/simple-oauth2.md#password-hashing).
+
+///
+
+## Utiliser plusieurs modèles { #multiple-models }
+
+Voici une idée générale de l'apparence des modèles avec leurs champs de mot de passe et les endroits où ils sont utilisés :
+
+{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}
+
+### À propos de `**user_in.model_dump()` { #about-user-in-model-dump }
+
+#### La méthode `.model_dump()` de Pydantic { #pydantics-model-dump }
+
+`user_in` est un modèle Pydantic de classe `UserIn`.
+
+Les modèles Pydantic ont une méthode `.model_dump()` qui renvoie un `dict` avec les données du modèle.
+
+Ainsi, si nous créons un objet Pydantic `user_in` comme :
+
+```Python
+user_in = UserIn(username="john", password="secret", email="john.doe@example.com")
+```
+
+et que nous appelons ensuite :
+
+```Python
+user_dict = user_in.model_dump()
+```
+
+nous avons maintenant un `dict` avec les données dans la variable `user_dict` (c'est un `dict` au lieu d'un objet modèle Pydantic).
+
+Et si nous appelons :
+
+```Python
+print(user_dict)
+```
+
+nous obtiendrions un `dict` Python contenant :
+
+```Python
+{
+ 'username': 'john',
+ 'password': 'secret',
+ 'email': 'john.doe@example.com',
+ 'full_name': None,
+}
+```
+
+#### Déballer un `dict` { #unpacking-a-dict }
+
+Si nous prenons un `dict` comme `user_dict` et que nous le passons à une fonction (ou une classe) avec `**user_dict`, Python va « déballer » ce `dict`. Il passera les clés et valeurs de `user_dict` directement comme arguments nommés.
+
+Ainsi, en reprenant `user_dict` ci-dessus, écrire :
+
+```Python
+UserInDB(**user_dict)
+```
+
+aurait pour résultat quelque chose d'équivalent à :
+
+```Python
+UserInDB(
+ username="john",
+ password="secret",
+ email="john.doe@example.com",
+ full_name=None,
+)
+```
+
+Ou plus exactement, en utilisant `user_dict` directement, quels que soient ses contenus futurs :
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ password = user_dict["password"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+)
+```
+
+#### Créer un modèle Pydantic à partir du contenu d'un autre { #a-pydantic-model-from-the-contents-of-another }
+
+Comme dans l'exemple ci-dessus nous avons obtenu `user_dict` depuis `user_in.model_dump()`, ce code :
+
+```Python
+user_dict = user_in.model_dump()
+UserInDB(**user_dict)
+```
+
+serait équivalent à :
+
+```Python
+UserInDB(**user_in.model_dump())
+```
+
+... parce que `user_in.model_dump()` est un `dict`, et nous demandons ensuite à Python de « déballer » ce `dict` en le passant à `UserInDB` précédé de `**`.
+
+Ainsi, nous obtenons un modèle Pydantic à partir des données d'un autre modèle Pydantic.
+
+#### Déballer un `dict` et ajouter des mots-clés supplémentaires { #unpacking-a-dict-and-extra-keywords }
+
+Et en ajoutant ensuite l'argument nommé supplémentaire `hashed_password=hashed_password`, comme ici :
+
+```Python
+UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
+```
+
+... revient à :
+
+```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 | Alertes
+
+Les fonctions auxiliaires `fake_password_hasher` et `fake_save_user` ne servent qu'à démontrer un flux de données possible, mais elles n'offrent évidemment aucune sécurité réelle.
+
+///
+
+## Réduire la duplication { #reduce-duplication }
+
+Réduire la duplication de code est l'une des idées centrales de **FastAPI**.
+
+La duplication de code augmente les risques de bogues, de problèmes de sécurité, de désynchronisation du code (lorsque vous mettez à jour un endroit mais pas les autres), etc.
+
+Et ces modèles partagent beaucoup de données et dupliquent des noms et types d'attributs.
+
+Nous pouvons faire mieux.
+
+Nous pouvons déclarer un modèle `UserBase` qui sert de base à nos autres modèles. Ensuite, nous pouvons créer des sous-classes de ce modèle qui héritent de ses attributs (déclarations de type, validation, etc.).
+
+Toutes les conversions de données, validations, documentation, etc., fonctionneront comme d'habitude.
+
+De cette façon, nous pouvons ne déclarer que les différences entre les modèles (avec `password` en clair, avec `hashed_password` et sans mot de passe) :
+
+{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}
+
+## `Union` ou `anyOf` { #union-or-anyof }
+
+Vous pouvez déclarer qu'une réponse est l'`Union` de deux types ou plus, ce qui signifie que la réponse peut être n'importe lequel d'entre eux.
+
+Cela sera défini dans OpenAPI avec `anyOf`.
+
+Pour ce faire, utilisez l'annotation de type Python standard [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union) :
+
+/// note | Remarque
+
+Lors de la définition d'une [`Union`](https://docs.pydantic.dev/latest/concepts/types/#unions), incluez d'abord le type le plus spécifique, suivi du type le moins spécifique. Dans l'exemple ci-dessous, le type le plus spécifique `PlaneItem` précède `CarItem` dans `Union[PlaneItem, CarItem]`.
+
+///
+
+{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}
+
+### `Union` en Python 3.10 { #union-in-python-3-10 }
+
+Dans cet exemple, nous passons `Union[PlaneItem, CarItem]` comme valeur de l'argument `response_model`.
+
+Comme nous le passons comme valeur d'un argument au lieu de l'utiliser dans une annotation de type, nous devons utiliser `Union` même en Python 3.10.
+
+S'il s'agissait d'une annotation de type, nous pourrions utiliser la barre verticale, comme :
+
+```Python
+some_variable: PlaneItem | CarItem
+```
+
+Mais si nous écrivons cela dans l'affectation `response_model=PlaneItem | CarItem`, nous obtiendrons une erreur, car Python essaierait d'effectuer une « opération invalide » entre `PlaneItem` et `CarItem` au lieu de l'interpréter comme une annotation de type.
+
+## Liste de modèles { #list-of-models }
+
+De la même manière, vous pouvez déclarer des réponses contenant des listes d'objets.
+
+Pour cela, utilisez le `list` Python standard :
+
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
+
+## Réponse avec un `dict` arbitraire { #response-with-arbitrary-dict }
+
+Vous pouvez également déclarer une réponse en utilisant un simple `dict` arbitraire, en déclarant uniquement le type des clés et des valeurs, sans utiliser de modèle Pydantic.
+
+C'est utile si vous ne connaissez pas à l'avance les noms de champs/attributs valides (qui seraient nécessaires pour un modèle Pydantic).
+
+Dans ce cas, vous pouvez utiliser `dict` :
+
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
+
+## Récapitulatif { #recap }
+
+Utilisez plusieurs modèles Pydantic et héritez librement selon chaque cas.
+
+Vous n'avez pas besoin d'avoir un seul modèle de données par entité si cette entité doit pouvoir avoir différents « états ». Comme pour l'« entité » utilisateur, avec un état incluant `password`, `password_hash` et sans mot de passe.
diff --git a/docs/fr/docs/tutorial/first-steps.md b/docs/fr/docs/tutorial/first-steps.md
index e98283f1e2e51..0a82004d2c2fa 100644
--- a/docs/fr/docs/tutorial/first-steps.md
+++ b/docs/fr/docs/tutorial/first-steps.md
@@ -1,106 +1,122 @@
-# Démarrage
+# Démarrer { #first-steps }
-Le fichier **FastAPI** le plus simple possible pourrait ressembler à cela :
+Le fichier **FastAPI** le plus simple possible pourrait ressembler à ceci :
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
-Copiez ce code dans un fichier nommé `main.py`.
+Copiez cela dans un fichier `main.py`.
-Démarrez le serveur :
+Démarrez le serveur en direct :
get
+* en utilisant une get opération
+
+/// info | `@decorator` Info
+
+Cette syntaxe `@something` en Python est appelée un « décorateur ».
-!!! info "`@décorateur` Info"
- Cette syntaxe `@something` en Python est appelée un "décorateur".
+Vous la mettez au-dessus d’une fonction. Comme un joli chapeau décoratif (j’imagine que c’est de là que vient le terme 🤷🏻♂).
- Vous la mettez au dessus d'une fonction. Comme un joli chapeau décoratif (j'imagine que ce terme vient de là 🤷🏻♂).
+Un « décorateur » prend la fonction en dessous et fait quelque chose avec.
- Un "décorateur" prend la fonction en dessous et en fait quelque chose.
+Dans notre cas, ce décorateur indique à **FastAPI** que la fonction en dessous correspond au **chemin** `/` avec une **opération** `get`.
- Dans notre cas, ce décorateur dit à **FastAPI** que la fonction en dessous correspond au **chemin** `/` avec l'**opération** `get`.
+C’est le « décorateur de chemin d’accès ».
- C'est le "**décorateur d'opération de chemin**".
+///
Vous pouvez aussi utiliser les autres opérations :
@@ -268,67 +342,88 @@ Vous pouvez aussi utiliser les autres opérations :
* `@app.put()`
* `@app.delete()`
-Tout comme celles les plus exotiques :
+Ainsi que les plus exotiques :
* `@app.options()`
* `@app.head()`
* `@app.patch()`
* `@app.trace()`
-!!! tip "Astuce"
- Vous êtes libres d'utiliser chaque opération (méthode HTTP) comme vous le désirez.
+/// tip | Astuce
- **FastAPI** n'impose pas de sens spécifique à chacune d'elle.
+Vous êtes libre d’utiliser chaque opération (méthode HTTP) comme vous le souhaitez.
- Les informations qui sont présentées ici forment une directive générale, pas des obligations.
+**FastAPI** n’impose aucune signification spécifique.
- Par exemple, quand l'on utilise **GraphQL**, toutes les actions sont effectuées en utilisant uniquement des opérations `POST`.
+Les informations ici sont présentées comme des lignes directrices, pas comme une obligation.
-### Étape 4 : définir la **fonction de chemin**.
+Par exemple, lorsque vous utilisez GraphQL, vous effectuez normalement toutes les actions en utilisant uniquement des opérations `POST`.
-Voici notre "**fonction de chemin**" (ou fonction d'opération de chemin) :
+///
+
+### Étape 4 : définir la **fonction de chemin d’accès** { #step-4-define-the-path-operation-function }
+
+Voici notre « fonction de chemin d’accès » :
* **chemin** : `/`.
* **opération** : `get`.
-* **fonction** : la fonction sous le "décorateur" (sous `@app.get("/")`).
+* **fonction** : la fonction sous le « décorateur » (sous `@app.get("/")`).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
-C'est une fonction Python.
+C’est une fonction Python.
-Elle sera appelée par **FastAPI** quand une requête sur l'URL `/` sera reçue via une opération `GET`.
+Elle sera appelée par **FastAPI** chaque fois qu’il recevra une requête vers l’URL « / » en utilisant une opération `GET`.
-Ici, c'est une fonction asynchrone (définie avec `async def`).
+Dans ce cas, c’est une fonction `async`.
---
-Vous pourriez aussi la définir comme une fonction classique plutôt qu'avec `async def` :
+Vous pouvez aussi la définir comme une fonction normale au lieu de `async def` :
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
-!!! note
- Si vous ne connaissez pas la différence, allez voir la section [Concurrence : *"Vous êtes pressés ?"*](../async.md#vous-etes-presses){.internal-link target=_blank}.
+/// note | Remarque
-### Étape 5 : retourner le contenu
+Si vous ne connaissez pas la différence, consultez [Asynchrone : « Pressé ? »](../async.md#in-a-hurry).
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+///
+
+### Étape 5 : retourner le contenu { #step-5-return-the-content }
+
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
+
+Vous pouvez retourner un `dict`, une `list`, des valeurs uniques comme `str`, `int`, etc.
+
+Vous pouvez également retourner des modèles Pydantic (vous en verrez plus à ce sujet plus tard).
+
+Il existe de nombreux autres objets et modèles qui seront automatiquement convertis en JSON (y compris des ORM, etc.). Essayez d’utiliser vos favoris, il est fort probable qu’ils soient déjà pris en charge.
+
+### Étape 6 : le déployer { #step-6-deploy-it }
+
+Déployez votre application sur **[FastAPI Cloud](https://fastapicloud.com)** avec une seule commande : `fastapi deploy`. 🎉
+
+#### À propos de FastAPI Cloud { #about-fastapi-cloud }
+
+**[FastAPI Cloud](https://fastapicloud.com)** est construit par le même auteur et l’équipe derrière **FastAPI**.
+
+Il simplifie le processus de **construction**, de **déploiement** et d’**accès** à une API avec un minimum d’effort.
+
+Il apporte la même **expérience développeur** de création d’applications avec FastAPI au **déploiement** dans le cloud. 🎉
+
+FastAPI Cloud est le sponsor principal et le financeur des projets open source *FastAPI and friends*. ✨
-Vous pouvez retourner un dictionnaire (`dict`), une liste (`list`), des valeurs seules comme des chaines de caractères (`str`) et des entiers (`int`), etc.
+#### Déployer sur d’autres fournisseurs cloud { #deploy-to-other-cloud-providers }
-Vous pouvez aussi retourner des models **Pydantic** (qui seront détaillés plus tard).
+FastAPI est open source et basé sur des standards. Vous pouvez déployer des applications FastAPI chez n’importe quel fournisseur cloud de votre choix.
-Il y a de nombreux autres objets et modèles qui seront automatiquement convertis en JSON. Essayez d'utiliser vos favoris, il est fort probable qu'ils soient déjà supportés.
+Suivez les guides de votre fournisseur cloud pour y déployer des applications FastAPI. 🤓
-## Récapitulatif
+## Récapitulatif { #recap }
* Importez `FastAPI`.
-* Créez une instance d'`app`.
-* Ajoutez une **décorateur d'opération de chemin** (tel que `@app.get("/")`).
-* Ajoutez une **fonction de chemin** (telle que `def root(): ...` comme ci-dessus).
-* Lancez le serveur de développement (avec `uvicorn main:app --reload`).
+* Créez une instance `app`.
+* Écrivez un **décorateur de chemin d’accès** avec des décorateurs comme `@app.get("/")`.
+* Définissez une **fonction de chemin d’accès** ; par exemple, `def root(): ...`.
+* Exécutez le serveur de développement avec la commande `fastapi dev`.
+* Déployez éventuellement votre application avec `fastapi deploy`.
diff --git a/docs/fr/docs/tutorial/handling-errors.md b/docs/fr/docs/tutorial/handling-errors.md
new file mode 100644
index 0000000000000..a697571f33caf
--- /dev/null
+++ b/docs/fr/docs/tutorial/handling-errors.md
@@ -0,0 +1,244 @@
+# Gérer les erreurs { #handling-errors }
+
+Il existe de nombreuses situations où vous devez signaler une erreur à un client qui utilise votre API.
+
+Ce client peut être un navigateur avec un frontend, un code d'un tiers, un appareil IoT, etc.
+
+Vous pourriez avoir besoin d'indiquer au client que :
+
+* Le client n'a pas les privilèges suffisants pour cette opération.
+* Le client n'a pas accès à cette ressource.
+* L'élément auquel le client tentait d'accéder n'existe pas.
+* etc.
+
+Dans ces cas, vous retournez normalement un **code d'état HTTP** dans la plage de **400** (de 400 à 499).
+
+C'est similaire aux codes d'état HTTP 200 (de 200 à 299). Ces codes « 200 » signifient que, d'une certaine manière, la requête a été un « succès ».
+
+Les codes d'état dans la plage des 400 signifient qu'il y a eu une erreur côté client.
+
+Vous souvenez-vous de toutes ces erreurs **« 404 Not Found »** (et des blagues) ?
+
+## Utiliser `HTTPException` { #use-httpexception }
+
+Pour renvoyer au client des réponses HTTP avec des erreurs, vous utilisez `HTTPException`.
+
+### Importer `HTTPException` { #import-httpexception }
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
+
+### Lever une `HTTPException` dans votre code { #raise-an-httpexception-in-your-code }
+
+`HTTPException` est une exception Python normale avec des données supplémentaires pertinentes pour les API.
+
+Comme il s'agit d'une exception Python, vous ne la `return` pas, vous la `raise`.
+
+Cela signifie aussi que si vous êtes dans une fonction utilitaire appelée depuis votre fonction de chemin d'accès, et que vous levez la `HTTPException` à l'intérieur de cette fonction utilitaire, le reste du code de la fonction de chemin d'accès ne s'exécutera pas : la requête sera immédiatement interrompue et l'erreur HTTP issue de la `HTTPException` sera envoyée au client.
+
+L'avantage de lever une exception plutôt que de retourner une valeur apparaîtra plus clairement dans la section sur les Dépendances et la Sécurité.
+
+Dans cet exemple, lorsque le client demande un élément par un ID qui n'existe pas, levez une exception avec un code d'état `404` :
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
+
+### Réponse résultante { #the-resulting-response }
+
+Si le client demande `http://example.com/items/foo` (un `item_id` « foo »), il recevra un code d'état HTTP 200 et une réponse JSON :
+
+```JSON
+{
+ "item": "The Foo Wrestlers"
+}
+```
+
+Mais si le client demande `http://example.com/items/bar` (un `item_id` inexistant « bar »), il recevra un code d'état HTTP 404 (l'erreur « not found ») et une réponse JSON :
+
+```JSON
+{
+ "detail": "Item not found"
+}
+```
+
+/// tip | Astuce
+
+Lorsque vous levez une `HTTPException`, vous pouvez passer n'importe quelle valeur convertible en JSON comme paramètre `detail`, pas uniquement un `str`.
+
+Vous pouvez passer un `dict`, une `list`, etc.
+
+Elles sont gérées automatiquement par **FastAPI** et converties en JSON.
+
+///
+
+## Ajouter des en-têtes personnalisés { #add-custom-headers }
+
+Dans certaines situations, il est utile de pouvoir ajouter des en-têtes personnalisés à l'erreur HTTP. Par exemple, pour certains types de sécurité.
+
+Vous n'aurez probablement pas besoin de l'utiliser directement dans votre code.
+
+Mais si vous en aviez besoin pour un scénario avancé, vous pouvez ajouter des en-têtes personnalisés :
+
+{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
+
+## Installer des gestionnaires d'exception personnalisés { #install-custom-exception-handlers }
+
+Vous pouvez ajouter des gestionnaires d'exception personnalisés avec [les mêmes utilitaires d'exception de Starlette](https://www.starlette.dev/exceptions/).
+
+Supposons que vous ayez une exception personnalisée `UnicornException` que vous (ou une bibliothèque que vous utilisez) pourriez `raise`.
+
+Et vous souhaitez gérer cette exception globalement avec FastAPI.
+
+Vous pouvez ajouter un gestionnaire d'exception personnalisé avec `@app.exception_handler()` :
+
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
+
+Ici, si vous appelez `/unicorns/yolo`, le chemin d'accès va `raise` une `UnicornException`.
+
+Mais elle sera gérée par `unicorn_exception_handler`.
+
+Ainsi, vous recevrez une erreur propre, avec un code d'état HTTP `418` et un contenu JSON :
+
+```JSON
+{"message": "Oops! yolo did something. There goes a rainbow..."}
+```
+
+/// note | Détails techniques
+
+Vous pourriez aussi utiliser `from starlette.requests import Request` et `from starlette.responses import JSONResponse`.
+
+**FastAPI** fournit les mêmes `starlette.responses` sous `fastapi.responses` par simple commodité pour vous, développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en va de même pour `Request`.
+
+///
+
+## Remplacer les gestionnaires d'exception par défaut { #override-the-default-exception-handlers }
+
+**FastAPI** fournit des gestionnaires d'exception par défaut.
+
+Ces gestionnaires se chargent de renvoyer les réponses JSON par défaut lorsque vous `raise` une `HTTPException` et lorsque la requête contient des données invalides.
+
+Vous pouvez remplacer ces gestionnaires d'exception par les vôtres.
+
+### Remplacer les exceptions de validation de la requête { #override-request-validation-exceptions }
+
+Lorsqu'une requête contient des données invalides, **FastAPI** lève en interne une `RequestValidationError`.
+
+Et il inclut également un gestionnaire d'exception par défaut pour cela.
+
+Pour la remplacer, importez `RequestValidationError` et utilisez-la avec `@app.exception_handler(RequestValidationError)` pour décorer le gestionnaire d'exception.
+
+Le gestionnaire d'exception recevra une `Request` et l'exception.
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
+
+À présent, si vous allez sur `/items/foo`, au lieu d'obtenir l'erreur JSON par défaut suivante :
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ]
+}
+```
+
+vous obtiendrez une version texte, avec :
+
+```
+Validation errors:
+Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer
+```
+
+### Remplacer le gestionnaire d'erreurs `HTTPException` { #override-the-httpexception-error-handler }
+
+De la même manière, vous pouvez remplacer le gestionnaire de `HTTPException`.
+
+Par exemple, vous pourriez vouloir renvoyer une réponse en texte brut au lieu de JSON pour ces erreurs :
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
+
+/// note | Détails techniques
+
+Vous pourriez aussi utiliser `from starlette.responses import PlainTextResponse`.
+
+**FastAPI** fournit les mêmes `starlette.responses` sous `fastapi.responses` par simple commodité pour vous, le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette.
+
+///
+
+/// warning | Alertes
+
+Gardez à l'esprit que la `RequestValidationError` contient l'information du nom de fichier et de la ligne où l'erreur de validation se produit, afin que vous puissiez l'afficher dans vos journaux avec les informations pertinentes si vous le souhaitez.
+
+Mais cela signifie que si vous vous contentez de la convertir en chaîne et de renvoyer cette information directement, vous pourriez divulguer un peu d'information sur votre système. C'est pourquoi, ici, le code extrait et affiche chaque erreur indépendamment.
+
+///
+
+### Utiliser le corps de `RequestValidationError` { #use-the-requestvalidationerror-body }
+
+La `RequestValidationError` contient le `body` qu'elle a reçu avec des données invalides.
+
+Vous pouvez l'utiliser pendant le développement de votre application pour journaliser le corps et le déboguer, le renvoyer à l'utilisateur, etc.
+
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
+
+Essayez maintenant d'envoyer un élément invalide comme :
+
+```JSON
+{
+ "title": "towel",
+ "size": "XL"
+}
+```
+
+Vous recevrez une réponse vous indiquant que les données sont invalides et contenant le corps reçu :
+
+```JSON hl_lines="12-15"
+{
+ "detail": [
+ {
+ "loc": [
+ "body",
+ "size"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ],
+ "body": {
+ "title": "towel",
+ "size": "XL"
+ }
+}
+```
+
+#### `HTTPException` de FastAPI vs `HTTPException` de Starlette { #fastapis-httpexception-vs-starlettes-httpexception }
+
+**FastAPI** a sa propre `HTTPException`.
+
+Et la classe d'erreur `HTTPException` de **FastAPI** hérite de la classe d'erreur `HTTPException` de Starlette.
+
+La seule différence est que la `HTTPException` de **FastAPI** accepte toute donnée sérialisable en JSON pour le champ `detail`, tandis que la `HTTPException` de Starlette n'accepte que des chaînes.
+
+Ainsi, vous pouvez continuer à lever la `HTTPException` de **FastAPI** normalement dans votre code.
+
+Mais lorsque vous enregistrez un gestionnaire d'exception, vous devez l'enregistrer pour la `HTTPException` de Starlette.
+
+De cette façon, si une partie du code interne de Starlette, ou une extension ou un plug-in Starlette, lève une `HTTPException` de Starlette, votre gestionnaire pourra l'intercepter et la traiter.
+
+Dans cet exemple, afin de pouvoir avoir les deux `HTTPException` dans le même code, les exceptions de Starlette sont renommées en `StarletteHTTPException` :
+
+```Python
+from starlette.exceptions import HTTPException as StarletteHTTPException
+```
+
+### Réutiliser les gestionnaires d'exception de **FastAPI** { #reuse-fastapis-exception-handlers }
+
+Si vous souhaitez utiliser l'exception avec les mêmes gestionnaires d'exception par défaut de **FastAPI**, vous pouvez importer et réutiliser les gestionnaires d'exception par défaut depuis `fastapi.exception_handlers` :
+
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
+
+Dans cet exemple, vous vous contentez d'afficher l'erreur avec un message très expressif, mais vous voyez l'idée. Vous pouvez utiliser l'exception puis simplement réutiliser les gestionnaires d'exception par défaut.
diff --git a/docs/fr/docs/tutorial/header-param-models.md b/docs/fr/docs/tutorial/header-param-models.md
new file mode 100644
index 0000000000000..8fc1a3d366978
--- /dev/null
+++ b/docs/fr/docs/tutorial/header-param-models.md
@@ -0,0 +1,72 @@
+# Modèles de paramètres d'en-tête { #header-parameter-models }
+
+Si vous avez un groupe de **paramètres d'en-tête** liés, vous pouvez créer un **modèle Pydantic** pour les déclarer.
+
+Cela vous permet de **réutiliser le modèle** à **plusieurs endroits** et aussi de déclarer des validations et des métadonnées pour tous les paramètres en une seule fois. 😎
+
+/// note | Remarque
+
+Cela est pris en charge depuis la version `0.115.0` de FastAPI. 🤓
+
+///
+
+## Paramètres d'en-tête avec un modèle Pydantic { #header-parameters-with-a-pydantic-model }
+
+Déclarez les **paramètres d'en-tête** dont vous avez besoin dans un **modèle Pydantic**, puis déclarez le paramètre comme `Header` :
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI** extrait les données de **chaque champ** depuis les **en-têtes** de la requête et vous fournit le modèle Pydantic que vous avez défini.
+
+## Consulter la documentation { #check-the-docs }
+
+Vous pouvez voir les en-têtes requis dans l'interface de la documentation à `/docs` :
+
+
+contact| Paramètre | Type | Description |
|---|---|---|
name | str | Le nom identifiant de la personne/organisation de contact. |
url | str | L’URL pointant vers les informations de contact. DOIT être au format d’une URL. |
email | str | L’adresse e-mail de la personne/organisation de contact. DOIT être au format d’une adresse e-mail. |
license_info| Paramètre | Type | Description |
|---|---|---|
name | str | OBLIGATOIRE (si un license_info est défini). Le nom de la licence utilisée pour l’API. |
identifier | str | Une expression de licence [SPDX](https://spdx.org/licenses/) pour l’API. Le champ identifier est mutuellement exclusif du champ url. Disponible depuis OpenAPI 3.1.0, FastAPI 0.99.0. |
url | str | Une URL vers la licence utilisée pour l’API. DOIT être au format d’une URL. |
+
+## Identifiant de licence { #license-identifier }
+
+Depuis OpenAPI 3.1.0 et FastAPI 0.99.0, vous pouvez également définir `license_info` avec un `identifier` au lieu d’une `url`.
+
+Par exemple :
+
+{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}
+
+## Métadonnées pour les tags { #metadata-for-tags }
+
+Vous pouvez également ajouter des métadonnées supplémentaires pour les différents tags utilisés pour regrouper vos chemins d'accès avec le paramètre `openapi_tags`.
+
+Il prend une liste contenant un dictionnaire pour chaque tag.
+
+Chaque dictionnaire peut contenir :
+
+* `name` (**requis**) : un `str` avec le même nom de tag que vous utilisez dans le paramètre `tags` de vos *chemins d'accès* et `APIRouter`s.
+* `description` : un `str` avec une courte description pour le tag. Il peut contenir du Markdown et sera affiché dans l’interface utilisateur de la documentation.
+* `externalDocs` : un `dict` décrivant une documentation externe avec :
+ * `description` : un `str` avec une courte description pour la documentation externe.
+ * `url` (**requis**) : un `str` avec l’URL de la documentation externe.
+
+### Créer des métadonnées pour les tags { #create-metadata-for-tags }
+
+Essayons cela avec un exemple de tags pour `users` et `items`.
+
+Créez des métadonnées pour vos tags et transmettez-les au paramètre `openapi_tags` :
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}
+
+Notez que vous pouvez utiliser Markdown à l’intérieur des descriptions, par exemple « login » sera affiché en gras (**login**) et « fancy » sera affiché en italique (_fancy_).
+
+/// tip | Astuce
+
+Vous n’avez pas à ajouter des métadonnées pour tous les tags que vous utilisez.
+
+///
+
+### Utiliser vos tags { #use-your-tags }
+
+Utilisez le paramètre `tags` avec vos *chemins d'accès* (et `APIRouter`s) pour les affecter à différents tags :
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}
+
+/// info
+
+En savoir plus sur les tags dans [Configuration de chemins d'accès](path-operation-configuration.md#tags).
+
+///
+
+### Consultez les documents { #check-the-docs }
+
+Désormais, si vous consultez les documents, ils afficheront toutes les métadonnées supplémentaires :
+
+
+
+### Définir l’ordre des tags { #order-of-tags }
+
+L’ordre de chaque dictionnaire de métadonnées de tag définit également l’ordre affiché dans l’interface utilisateur de la documentation.
+
+Par exemple, même si `users` viendrait après `items` par ordre alphabétique, il est affiché avant, car nous avons ajouté ses métadonnées comme premier dictionnaire de la liste.
+
+## URL OpenAPI { #openapi-url }
+
+Par défaut, le schéma OpenAPI est servi à `/openapi.json`.
+
+Mais vous pouvez le configurer avec le paramètre `openapi_url`.
+
+Par exemple, pour qu’il soit servi à `/api/v1/openapi.json` :
+
+{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}
+
+Si vous souhaitez désactiver complètement le schéma OpenAPI, vous pouvez définir `openapi_url=None`, cela désactivera également les interfaces utilisateur de la documentation qui l’utilisent.
+
+## URL des documents { #docs-urls }
+
+Vous pouvez configurer les deux interfaces utilisateur de documentation incluses :
+
+* **Swagger UI** : servie à `/docs`.
+ * Vous pouvez définir son URL avec le paramètre `docs_url`.
+ * Vous pouvez la désactiver en définissant `docs_url=None`.
+* **ReDoc** : servie à `/redoc`.
+ * Vous pouvez définir son URL avec le paramètre `redoc_url`.
+ * Vous pouvez la désactiver en définissant `redoc_url=None`.
+
+Par exemple, pour que Swagger UI soit servi à `/documentation` et désactiver ReDoc :
+
+{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}
diff --git a/docs/fr/docs/tutorial/middleware.md b/docs/fr/docs/tutorial/middleware.md
new file mode 100644
index 0000000000000..860b8041ce189
--- /dev/null
+++ b/docs/fr/docs/tutorial/middleware.md
@@ -0,0 +1,95 @@
+# Middleware { #middleware }
+
+Vous pouvez ajouter des middlewares aux applications **FastAPI**.
+
+Un « middleware » est une fonction qui agit sur chaque **requête** avant qu’elle ne soit traitée par un *chemin d'accès* spécifique. Et aussi sur chaque **réponse** avant son renvoi.
+
+* Il intercepte chaque **requête** qui parvient à votre application.
+* Il peut alors faire quelque chose avec cette **requête** ou exécuter tout code nécessaire.
+* Ensuite, il transmet la **requête** pour qu’elle soit traitée par le reste de l’application (par un *chemin d'accès*).
+* Puis il récupère la **réponse** générée par l’application (par un *chemin d'accès*).
+* Il peut faire quelque chose avec cette **réponse** ou exécuter tout code nécessaire.
+* Enfin, il renvoie la **réponse**.
+
+/// note | Détails techniques
+
+Si vous avez des dépendances avec `yield`, le code de sortie s’exécutera après le middleware.
+
+S’il y avait des tâches d’arrière-plan (présentées dans la section [Tâches d’arrière-plan](background-tasks.md), que vous verrez plus tard), elles s’exécuteront après tous les middlewares.
+
+///
+
+## Créer un middleware { #create-a-middleware }
+
+Pour créer un middleware, utilisez le décorateur `@app.middleware("http")` au-dessus d’une fonction.
+
+La fonction de middleware reçoit :
+
+* La `request`.
+* Une fonction `call_next` qui recevra la `request` en paramètre.
+ * Cette fonction transmettra la `request` au *chemin d'accès* correspondant.
+ * Puis elle renverra la `response` générée par le *chemin d'accès* correspondant.
+* Vous pouvez ensuite modifier la `response` avant de la renvoyer.
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}
+
+/// tip | Astuce
+
+Gardez à l’esprit que des en-têtes propriétaires personnalisés peuvent être ajoutés [en utilisant le préfixe `X-`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers).
+
+Mais si vous avez des en-têtes personnalisés que vous voulez rendre visibles pour un client dans un navigateur, vous devez les ajouter à votre configuration CORS ([CORS (Partage des ressources entre origines)](cors.md)) en utilisant le paramètre `expose_headers` documenté dans [la documentation CORS de Starlette](https://www.starlette.dev/middleware/#corsmiddleware).
+
+///
+
+/// note | Détails techniques
+
+Vous pourriez aussi utiliser `from starlette.requests import Request`.
+
+**FastAPI** le fournit pour votre confort de développeur. Mais cela provient directement de Starlette.
+
+///
+
+### Avant et après la `response` { #before-and-after-the-response }
+
+Vous pouvez ajouter du code à exécuter avec la `request`, avant que tout *chemin d'accès* ne la reçoive.
+
+Et aussi après que la `response` a été générée, avant de la renvoyer.
+
+Par exemple, vous pourriez ajouter un en-tête personnalisé `X-Process-Time` contenant le temps en secondes nécessaire pour traiter la requête et générer une réponse :
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}
+
+/// tip | Astuce
+
+Ici, nous utilisons [`time.perf_counter()`](https://docs.python.org/3/library/time.html#time.perf_counter) au lieu de `time.time()` car cela peut être plus précis pour ces cas d’usage. 🤓
+
+///
+
+## Ordre d’exécution de plusieurs middlewares { #multiple-middleware-execution-order }
+
+Quand vous ajoutez plusieurs middlewares en utilisant soit le décorateur `@app.middleware()`, soit la méthode `app.add_middleware()`, chaque nouveau middleware enveloppe l’application, formant une pile. Le dernier middleware ajouté est le plus externe, et le premier est le plus interne.
+
+Sur le chemin de la requête, le plus externe s’exécute en premier.
+
+Sur le chemin de la réponse, il s’exécute en dernier.
+
+Par exemple :
+
+```Python
+app.add_middleware(MiddlewareA)
+app.add_middleware(MiddlewareB)
+```
+
+Cela aboutit à l’ordre d’exécution suivant :
+
+* **Requête** : MiddlewareB → MiddlewareA → route
+
+* **Réponse** : route → MiddlewareA → MiddlewareB
+
+Ce comportement d’empilement garantit que les middlewares s’exécutent dans un ordre prévisible et contrôlable.
+
+## Autres middlewares { #other-middlewares }
+
+Vous pouvez en lire davantage sur d’autres middlewares dans le [Guide de l’utilisateur avancé : Middleware avancé](../advanced/middleware.md).
+
+Vous verrez comment gérer CORS avec un middleware dans la section suivante.
diff --git a/docs/fr/docs/tutorial/path-operation-configuration.md b/docs/fr/docs/tutorial/path-operation-configuration.md
new file mode 100644
index 0000000000000..185adb6dd9233
--- /dev/null
+++ b/docs/fr/docs/tutorial/path-operation-configuration.md
@@ -0,0 +1,107 @@
+# Configurer les chemins d'accès { #path-operation-configuration }
+
+Vous pouvez passer plusieurs paramètres à votre *décorateur de chemin d'accès* pour le configurer.
+
+/// warning | Alertes
+
+Notez que ces paramètres sont passés directement au *décorateur de chemin d'accès*, et non à votre *fonction de chemin d'accès*.
+
+///
+
+## Définir le code d'état de la réponse { #response-status-code }
+
+Vous pouvez définir le `status_code` (HTTP) à utiliser dans la réponse de votre *chemin d'accès*.
+
+Vous pouvez passer directement le code `int`, comme `404`.
+
+Mais si vous ne vous souvenez pas à quoi correspond chaque code numérique, vous pouvez utiliser les constantes abrégées dans `status` :
+
+{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *}
+
+Ce code d'état sera utilisé dans la réponse et ajouté au schéma OpenAPI.
+
+/// note | Détails techniques
+
+Vous pouvez également utiliser `from starlette import status`.
+
+**FastAPI** fournit le même `starlette.status` sous le nom `fastapi.status` pour votre commodité, en tant que développeur. Mais cela provient directement de Starlette.
+
+///
+
+## Ajouter des tags { #tags }
+
+Vous pouvez ajouter des tags à votre *chemin d'accès*, en passant le paramètre `tags` avec une `list` de `str` (généralement un seul `str`) :
+
+{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *}
+
+Ils seront ajoutés au schéma OpenAPI et utilisés par les interfaces de documentation automatiques :
+
+
+
+### Utiliser des tags avec Enum { #tags-with-enums }
+
+Si vous avez une grande application, vous pourriez finir par accumuler **plusieurs tags**, et vous voudrez vous assurer d'utiliser toujours le **même tag** pour les *chemins d'accès* associés.
+
+Dans ces cas, il peut être judicieux de stocker les tags dans un `Enum`.
+
+**FastAPI** le prend en charge de la même manière qu'avec des chaînes simples :
+
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
+
+## Ajouter un résumé et une description { #summary-and-description }
+
+Vous pouvez ajouter un `summary` et une `description` :
+
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *}
+
+## Utiliser la description depuis la docstring { #description-from-docstring }
+
+Comme les descriptions ont tendance à être longues et à couvrir plusieurs lignes, vous pouvez déclarer la description du *chemin d'accès* dans la docstring de la fonction et **FastAPI** la lira à partir de là.
+
+Vous pouvez écrire [Markdown](https://en.wikipedia.org/wiki/Markdown) dans la docstring, il sera interprété et affiché correctement (en tenant compte de l'indentation de la docstring).
+
+{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}
+
+Elle sera utilisée dans les documents interactifs :
+
+
+
+## Définir la description de la réponse { #response-description }
+
+Vous pouvez spécifier la description de la réponse avec le paramètre `response_description` :
+
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
+
+/// info
+
+Notez que `response_description` se réfère spécifiquement à la réponse, tandis que `description` se réfère au *chemin d'accès* en général.
+
+///
+
+/// check | Vérifications
+
+OpenAPI spécifie que chaque *chemin d'accès* requiert une description de réponse.
+
+Donc, si vous n'en fournissez pas, **FastAPI** en générera automatiquement une « Réponse réussie ».
+
+///
+
+
+
+## Déprécier un *chemin d'accès* { #deprecate-a-path-operation }
+
+Si vous devez marquer un *chemin d'accès* comme déprécié, sans pour autant le supprimer, passez le paramètre `deprecated` :
+
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
+
+Il sera clairement marqué comme déprécié dans les documents interactifs :
+
+
+
+Voyez à quoi ressemblent les *chemins d'accès* dépréciés et non dépréciés :
+
+
+
+## Récapitulatif { #recap }
+
+Vous pouvez facilement configurer et ajouter des métadonnées à vos *chemins d'accès* en passant des paramètres aux *décorateurs de chemin d'accès*.
diff --git a/docs/fr/docs/tutorial/path-params-numeric-validations.md b/docs/fr/docs/tutorial/path-params-numeric-validations.md
new file mode 100644
index 0000000000000..b61b42ef78f0c
--- /dev/null
+++ b/docs/fr/docs/tutorial/path-params-numeric-validations.md
@@ -0,0 +1,154 @@
+# Paramètres de chemin et validations numériques { #path-parameters-and-numeric-validations }
+
+De la même façon que vous pouvez déclarer plus de validations et de métadonnées pour les paramètres de requête avec `Query`, vous pouvez déclarer le même type de validations et de métadonnées pour les paramètres de chemin avec `Path`.
+
+## Importer `Path` { #import-path }
+
+Tout d'abord, importez `Path` de `fastapi`, et importez `Annotated` :
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
+
+/// info
+
+FastAPI a ajouté le support pour `Annotated` (et a commencé à le recommander) dans la version 0.95.0.
+
+Si vous avez une version plus ancienne, vous obtiendrez des erreurs en essayant d'utiliser `Annotated`.
+
+Assurez-vous de [Mettre à niveau la version de FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions) à la version 0.95.1 à minima avant d'utiliser `Annotated`.
+
+///
+
+## Déclarer des métadonnées { #declare-metadata }
+
+Vous pouvez déclarer les mêmes paramètres que pour `Query`.
+
+Par exemple, pour déclarer une valeur de métadonnée `title` pour le paramètre de chemin `item_id`, vous pouvez écrire :
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *}
+
+/// note | Remarque
+
+Un paramètre de chemin est toujours requis car il doit faire partie du chemin. Même si vous l'avez déclaré avec `None` ou défini une valeur par défaut, cela ne changerait rien, il serait toujours requis.
+
+///
+
+## Ordonner les paramètres comme vous le souhaitez { #order-the-parameters-as-you-need }
+
+/// tip | Astuce
+
+Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`.
+
+///
+
+Disons que vous voulez déclarer le paramètre de requête `q` comme un `str` requis.
+
+Et vous n'avez pas besoin de déclarer autre chose pour ce paramètre, donc vous n'avez pas vraiment besoin d'utiliser `Query`.
+
+Mais vous avez toujours besoin d'utiliser `Path` pour le paramètre de chemin `item_id`. Et vous ne voulez pas utiliser `Annotated` pour une raison quelconque.
+
+Python se plaindra si vous mettez une valeur avec une « valeur par défaut » avant une valeur qui n'a pas de « valeur par défaut ».
+
+Mais vous pouvez les réorganiser, et avoir la valeur sans défaut (le paramètre de requête `q`) en premier.
+
+Cela n'a pas d'importance pour **FastAPI**. Il détectera les paramètres par leurs noms, types et déclarations par défaut (`Query`, `Path`, etc), il ne se soucie pas de l'ordre.
+
+Ainsi, vous pouvez déclarer votre fonction comme suit :
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
+
+Mais gardez à l'esprit que si vous utilisez `Annotated`, vous n'aurez pas ce problème, cela n'aura pas d'importance car vous n'utilisez pas les valeurs par défaut des paramètres de fonction pour `Query()` ou `Path()`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
+
+## Ordonner les paramètres comme vous le souhaitez, astuces { #order-the-parameters-as-you-need-tricks }
+
+/// tip | Astuce
+
+Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`.
+
+///
+
+Voici une **petite astuce** qui peut être pratique, mais vous n'en aurez pas souvent besoin.
+
+Si vous voulez :
+
+* déclarer le paramètre de requête `q` sans `Query` ni valeur par défaut
+* déclarer le paramètre de chemin `item_id` en utilisant `Path`
+* les avoir dans un ordre différent
+* ne pas utiliser `Annotated`
+
+... Python a une petite syntaxe spéciale pour cela.
+
+Passez `*`, comme premier paramètre de la fonction.
+
+Python ne fera rien avec ce `*`, mais il saura que tous les paramètres suivants doivent être appelés comme arguments « mots-clés » (paires clé-valeur), également connus sous le nom de kwargs. Même s'ils n'ont pas de valeur par défaut.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
+
+### Mieux avec `Annotated` { #better-with-annotated }
+
+Gardez à l'esprit que si vous utilisez `Annotated`, comme vous n'utilisez pas les valeurs par défaut des paramètres de fonction, vous n'aurez pas ce problème, et vous n'aurez probablement pas besoin d'utiliser `*`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
+
+## Validations numériques : supérieur ou égal { #number-validations-greater-than-or-equal }
+
+Avec `Query` et `Path` (et d'autres que vous verrez plus tard) vous pouvez déclarer des contraintes numériques.
+
+Ici, avec `ge=1`, `item_id` devra être un nombre entier « `g`reater than or `e`qual » à `1`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
+
+## Validations numériques : supérieur et inférieur ou égal { #number-validations-greater-than-and-less-than-or-equal }
+
+La même chose s'applique pour :
+
+* `gt` : `g`reater `t`han
+* `le` : `l`ess than or `e`qual
+
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
+
+## Validations numériques : flottants, supérieur et inférieur { #number-validations-floats-greater-than-and-less-than }
+
+Les validations numériques fonctionnent également pour les valeurs `float`.
+
+C'est ici qu'il devient important de pouvoir déclarer gt et pas seulement ge. Avec cela, vous pouvez exiger, par exemple, qu'une valeur doit être supérieure à `0`, même si elle est inférieure à `1`.
+
+Ainsi, `0.5` serait une valeur valide. Mais `0.0` ou `0` ne le serait pas.
+
+Et la même chose pour lt.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
+
+## Pour résumer { #recap }
+
+Avec `Query`, `Path` (et d'autres que vous verrez plus tard) vous pouvez déclarer des métadonnées et des validations de chaînes de la même manière qu'avec les [Paramètres de requête et validations de chaînes](query-params-str-validations.md).
+
+Et vous pouvez également déclarer des validations numériques :
+
+* `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`, et d'autres classes que vous verrez plus tard sont des sous-classes d'une classe commune `Param`.
+
+Tous partagent les mêmes paramètres pour des validations supplémentaires et des métadonnées que vous avez vu précédemment.
+
+///
+
+/// note | Détails techniques
+
+Lorsque vous importez `Query`, `Path` et d'autres de `fastapi`, ce sont en fait des fonctions.
+
+Ces dernières, lorsqu'elles sont appelées, renvoient des instances de classes du même nom.
+
+Ainsi, vous importez `Query`, qui est une fonction. Et lorsque vous l'appelez, elle renvoie une instance d'une classe également nommée `Query`.
+
+Ces fonctions sont là (au lieu d'utiliser simplement les classes directement) pour que votre éditeur ne marque pas d'erreurs sur leurs types.
+
+De cette façon, vous pouvez utiliser votre éditeur et vos outils de codage habituels sans avoir à ajouter des configurations personnalisées pour ignorer ces erreurs.
+
+///
diff --git a/docs/fr/docs/tutorial/path-params.md b/docs/fr/docs/tutorial/path-params.md
index 894d62dd46108..f84c4c035715c 100644
--- a/docs/fr/docs/tutorial/path-params.md
+++ b/docs/fr/docs/tutorial/path-params.md
@@ -1,200 +1,196 @@
-# Paramètres de chemin
+# Paramètres de chemin { #path-parameters }
-Vous pouvez déclarer des "paramètres" ou "variables" de chemin avec la même syntaxe que celle utilisée par le
-formatage de chaîne Python :
+Vous pouvez déclarer des « paramètres » ou « variables » de chemin avec la même syntaxe utilisée par les chaînes de format Python :
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
-
-La valeur du paramètre `item_id` sera transmise à la fonction dans l'argument `item_id`.
+La valeur du paramètre de chemin `item_id` sera transmise à votre fonction dans l'argument `item_id`.
-Donc, si vous exécutez cet exemple et allez sur http://127.0.0.1:8000/items/foo,
-vous verrez comme réponse :
+Donc, si vous exécutez cet exemple et allez sur [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo), vous verrez comme réponse :
```JSON
{"item_id":"foo"}
```
-## Paramètres de chemin typés
+## Paramètres de chemin typés { #path-parameters-with-types }
-Vous pouvez déclarer le type d'un paramètre de chemin dans la fonction, en utilisant les annotations de type Python :
+Vous pouvez déclarer le type d'un paramètre de chemin dans la fonction, en utilisant les annotations de type Python standard :
-
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
+{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}
Ici, `item_id` est déclaré comme `int`.
-!!! hint "Astuce"
- Ceci vous permettra d'obtenir des fonctionnalités de l'éditeur dans votre fonction, telles
- que des vérifications d'erreur, de l'auto-complétion, etc.
+/// check | Vérifications
-## Conversion de données
+Cela vous apporte la prise en charge par l'éditeur dans votre fonction, avec vérifications d'erreurs, autocomplétion, etc.
-Si vous exécutez cet exemple et allez sur http://127.0.0.1:8000/items/3, vous aurez comme réponse :
+///
+
+## Conversion de données { #data-conversion }
+
+Si vous exécutez cet exemple et ouvrez votre navigateur sur [http://127.0.0.1:8000/items/3](http://127.0.0.1:8000/items/3), vous verrez comme réponse :
```JSON
{"item_id":3}
```
-!!! hint "Astuce"
- Comme vous l'avez remarqué, la valeur reçue par la fonction (et renvoyée ensuite) est `3`,
- en tant qu'entier (`int`) Python, pas la chaîne de caractères (`string`) `"3"`.
+/// check | Vérifications
+
+Remarquez que la valeur reçue par votre fonction (et renvoyée) est `3`, en tant qu'entier (`int`) Python, pas la chaîne de caractères « 3 ».
- Grâce aux déclarations de types, **FastAPI** fournit du
- "parsing" automatique.
+Ainsi, avec cette déclaration de type, **FastAPI** vous fournit automatiquement le « parsing » de la requête.
-## Validation de données
+///
-Si vous allez sur http://127.0.0.1:8000/items/foo, vous aurez une belle erreur HTTP :
+## Validation de données { #data-validation }
+
+Mais si vous allez dans le navigateur sur [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo), vous verrez une belle erreur HTTP :
```JSON
{
- "detail": [
- {
- "loc": [
- "path",
- "item_id"
- ],
- "msg": "value is not a valid integer",
- "type": "type_error.integer"
- }
- ]
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo"
+ }
+ ]
}
```
-car le paramètre de chemin `item_id` possède comme valeur `"foo"`, qui ne peut pas être convertie en entier (`int`).
+car le paramètre de chemin `item_id` a pour valeur « foo », qui n'est pas un `int`.
+
+La même erreur apparaîtrait si vous fournissiez un `float` au lieu d'un `int`, comme ici : [http://127.0.0.1:8000/items/4.2](http://127.0.0.1:8000/items/4.2)
-La même erreur se produira si vous passez un nombre flottant (`float`) et non un entier, comme ici
-http://127.0.0.1:8000/items/4.2.
+/// check | Vérifications
+Ainsi, avec la même déclaration de type Python, **FastAPI** vous fournit la validation de données.
-!!! hint "Astuce"
- Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données.
+Remarquez que l'erreur indique clairement l'endroit exact où la validation n'a pas réussi.
- Notez que l'erreur mentionne le point exact où la validation n'a pas réussi.
+C'est incroyablement utile lors du développement et du débogage du code qui interagit avec votre API.
- Ce qui est incroyablement utile au moment de développer et débugger du code qui interagit avec votre API.
+///
-## Documentation
+## Documentation { #documentation }
-Et quand vous vous rendez sur http://127.0.0.1:8000/docs, vous verrez la
-documentation générée automatiquement et interactive :
+Et lorsque vous ouvrez votre navigateur sur [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs), vous verrez une documentation d'API automatique et interactive comme :
-!!! info
- À nouveau, en utilisant uniquement les déclarations de type Python, **FastAPI** vous fournit automatiquement une documentation interactive (via Swagger UI).
+/// check | Vérifications
+
+À nouveau, simplement avec cette même déclaration de type Python, **FastAPI** vous fournit une documentation interactive automatique (intégrant Swagger UI).
+
+Remarquez que le paramètre de chemin est déclaré comme entier.
- On voit bien dans la documentation que `item_id` est déclaré comme entier.
+///
-## Les avantages d'avoir une documentation basée sur une norme, et la documentation alternative.
+## Les avantages d'une norme, documentation alternative { #standards-based-benefits-alternative-documentation }
-Le schéma généré suivant la norme OpenAPI,
-il existe de nombreux outils compatibles.
+Et comme le schéma généré suit la norme [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md), il existe de nombreux outils compatibles.
-Grâce à cela, **FastAPI** lui-même fournit une documentation alternative (utilisant ReDoc), qui peut être lue
-sur http://127.0.0.1:8000/redoc :
+Grâce à cela, **FastAPI** fournit lui-même une documentation d'API alternative (utilisant ReDoc), accessible sur [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) :
-De la même façon, il existe bien d'autres outils compatibles, y compris des outils de génération de code
-pour de nombreux langages.
+De la même façon, il existe de nombreux outils compatibles, y compris des outils de génération de code pour de nombreux langages.
-## Pydantic
+## Pydantic { #pydantic }
-Toute la validation de données est effectué en arrière-plan avec Pydantic,
-dont vous bénéficierez de tous les avantages. Vous savez donc que vous êtes entre de bonnes mains.
+Toute la validation de données est effectuée sous le capot par [Pydantic](https://docs.pydantic.dev/), vous en bénéficiez donc pleinement. Vous savez ainsi que vous êtes entre de bonnes mains.
-## L'ordre importe
+Vous pouvez utiliser les mêmes déclarations de type avec `str`, `float`, `bool` et de nombreux autres types de données complexes.
-Quand vous créez des *fonctions de chemins*, vous pouvez vous retrouver dans une situation où vous avez un chemin fixe.
+Plusieurs d'entre eux sont explorés dans les prochains chapitres du tutoriel.
-Tel que `/users/me`, disons pour récupérer les données sur l'utilisateur actuel.
+## L'ordre importe { #order-matters }
-Et vous avez un second chemin : `/users/{user_id}` pour récupérer de la donnée sur un utilisateur spécifique grâce à son identifiant d'utilisateur
+Quand vous créez des *chemins d'accès*, vous pouvez vous retrouver dans une situation avec un chemin fixe.
-Les *fonctions de chemin* étant évaluées dans l'ordre, il faut s'assurer que la fonction correspondant à `/users/me` est déclarée avant celle de `/users/{user_id}` :
+Par exemple `/users/me`, disons pour récupérer les données de l'utilisateur actuel.
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
-```
+Et vous pouvez aussi avoir un chemin `/users/{user_id}` pour récupérer des données sur un utilisateur spécifique grâce à un identifiant d'utilisateur.
-Sinon, le chemin `/users/{user_id}` correspondrait aussi à `/users/me`, la fonction "croyant" qu'elle a reçu un paramètre `user_id` avec pour valeur `"me"`.
+Comme les *chemins d'accès* sont évalués dans l'ordre, vous devez vous assurer que le chemin `/users/me` est déclaré avant celui de `/users/{user_id}` :
-## Valeurs prédéfinies
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
-Si vous avez une *fonction de chemin* qui reçoit un *paramètre de chemin*, mais que vous voulez que les valeurs possibles des paramètres soient prédéfinies, vous pouvez utiliser les `Enum` de Python.
+Sinon, le chemin `/users/{user_id}` correspondrait aussi à `/users/me`, « pensant » qu'il reçoit un paramètre `user_id` avec la valeur « me ».
-### Création d'un `Enum`
+De même, vous ne pouvez pas redéfinir un chemin d'accès :
-Importez `Enum` et créez une sous-classe qui hérite de `str` et `Enum`.
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
-En héritant de `str` la documentation sera capable de savoir que les valeurs doivent être de type `string` et pourra donc afficher cette `Enum` correctement.
+Le premier sera toujours utilisé puisque le chemin correspond en premier.
-Créez ensuite des attributs de classe avec des valeurs fixes, qui seront les valeurs autorisées pour cette énumération.
+## Valeurs prédéfinies { #predefined-values }
-```Python hl_lines="1 6-9"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+Si vous avez un *chemin d'accès* qui reçoit un *paramètre de chemin*, mais que vous voulez que les valeurs possibles de ce *paramètre de chemin* soient prédéfinies, vous pouvez utiliser une `Enum` Python standard.
-!!! info
- Les énumérations (ou enums) sont disponibles en Python depuis la version 3.4.
+### Créer une classe `Enum` { #create-an-enum-class }
-!!! tip "Astuce"
- Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms de modèles de Machine Learning.
+Importez `Enum` et créez une sous-classe qui hérite de `str` et de `Enum`.
-### Déclarer un paramètre de chemin
+En héritant de `str`, la documentation de l'API saura que les valeurs doivent être de type `string` et pourra donc s'afficher correctement.
-Créez ensuite un *paramètre de chemin* avec une annotation de type désignant l'énumération créée précédemment (`ModelName`) :
+Créez ensuite des attributs de classe avec des valeurs fixes, qui seront les valeurs valides disponibles :
-```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
-### Documentation
+/// tip | Astuce
-Les valeurs disponibles pour le *paramètre de chemin* sont bien prédéfinies, la documentation les affiche correctement :
+Si vous vous demandez, « AlexNet », « ResNet » et « LeNet » sont juste des noms de modèles de Machine Learning.
+
+///
+
+### Déclarer un paramètre de chemin { #declare-a-path-parameter }
+
+Créez ensuite un *paramètre de chemin* avec une annotation de type utilisant la classe d'énumération que vous avez créée (`ModelName`) :
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
+
+### Consulter la documentation { #check-the-docs }
+
+Comme les valeurs disponibles pour le *paramètre de chemin* sont prédéfinies, la documentation interactive peut les afficher clairement :
-### Manipuler les *énumérations* Python
+### Travailler avec les *énumérations* Python { #working-with-python-enumerations }
-La valeur du *paramètre de chemin* sera un des "membres" de l'énumération.
+La valeur du *paramètre de chemin* sera un *membre d'énumération*.
-#### Comparer les *membres d'énumération*
+#### Comparer des *membres d'énumération* { #compare-enumeration-members }
-Vous pouvez comparer ce paramètre avec les membres de votre énumération `ModelName` :
+Vous pouvez le comparer avec le *membre d'énumération* dans votre enum `ModelName` :
-```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}
-#### Récupérer la *valeur de l'énumération*
+#### Obtenir la *valeur de l'énumération* { #get-the-enumeration-value }
-Vous pouvez obtenir la valeur réel d'un membre (une chaîne de caractères ici), avec `model_name.value`, ou en général, `votre_membre_d'enum.value` :
+Vous pouvez obtenir la valeur réelle (une `str` dans ce cas) avec `model_name.value`, ou en général, `votre_membre_d_enum.value` :
-```Python hl_lines="20"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}
-!!! tip "Astuce"
- Vous pouvez aussi accéder la valeur `"lenet"` avec `ModelName.lenet.value`.
+/// tip | Astuce
-#### Retourner des *membres d'énumération*
+Vous pouvez aussi accéder à la valeur « lenet » avec `ModelName.lenet.value`.
-Vous pouvez retourner des *membres d'énumération* dans vos *fonctions de chemin*, même imbriquée dans un JSON (e.g. un `dict`).
+///
-Ils seront convertis vers leurs valeurs correspondantes (chaînes de caractères ici) avant d'être transmis au client :
+#### Retourner des *membres d'énumération* { #return-enumeration-members }
-```Python hl_lines="18 21 23"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+Vous pouvez retourner des *membres d'énumération* depuis votre *chemin d'accès*, même imbriqués dans un corps JSON (par ex. un `dict`).
+
+Ils seront convertis vers leurs valeurs correspondantes (des chaînes de caractères ici) avant d'être renvoyés au client :
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}
-Le client recevra une réponse JSON comme celle-ci :
+Dans votre client, vous recevrez une réponse JSON comme :
```JSON
{
@@ -203,52 +199,53 @@ Le client recevra une réponse JSON comme celle-ci :
}
```
-## Paramètres de chemin contenant des chemins
+## Paramètres de chemin contenant des chemins { #path-parameters-containing-paths }
-Disons que vous avez une *fonction de chemin* liée au chemin `/files/{file_path}`.
+Disons que vous avez un *chemin d'accès* avec un chemin `/files/{file_path}`.
-Mais que `file_path` lui-même doit contenir un *chemin*, comme `home/johndoe/myfile.txt` par exemple.
+Mais vous avez besoin que `file_path` lui-même contienne un *chemin*, comme `home/johndoe/myfile.txt`.
-Donc, l'URL pour ce fichier pourrait être : `/files/home/johndoe/myfile.txt`.
+Ainsi, l'URL pour ce fichier serait : `/files/home/johndoe/myfile.txt`.
-### Support d'OpenAPI
+### Support d'OpenAPI { #openapi-support }
-OpenAPI ne supporte pas de manière de déclarer un paramètre de chemin contenant un *chemin*, cela pouvant causer des scénarios difficiles à tester et définir.
+OpenAPI ne prend pas en charge une manière de déclarer un *paramètre de chemin* contenant un *chemin* à l'intérieur, car cela peut conduire à des scénarios difficiles à tester et à définir.
-Néanmoins, cela reste faisable dans **FastAPI**, via les outils internes de Starlette.
+Néanmoins, vous pouvez toujours le faire dans **FastAPI**, en utilisant l'un des outils internes de Starlette.
-Et la documentation fonctionne quand même, bien qu'aucune section ne soit ajoutée pour dire que la paramètre devrait contenir un *chemin*.
+Et la documentation fonctionnera quand même, même si aucune indication supplémentaire ne sera ajoutée pour dire que le paramètre doit contenir un chemin.
-### Convertisseur de *chemin*
+### Convertisseur de chemin { #path-convertor }
-En utilisant une option de Starlette directement, vous pouvez déclarer un *paramètre de chemin* contenant un *chemin* avec une URL comme :
+En utilisant une option directement depuis Starlette, vous pouvez déclarer un *paramètre de chemin* contenant un *chemin* avec une URL comme :
```
/files/{file_path:path}
```
-Dans ce cas, le nom du paramètre est `file_path`, et la dernière partie, `:path`, indique à Starlette que le paramètre devrait correspondre à un *chemin*.
+Dans ce cas, le nom du paramètre est `file_path`, et la dernière partie, `:path`, indique que le paramètre doit correspondre à n'importe quel *chemin*.
-Vous pouvez donc l'utilisez comme tel :
+Vous pouvez donc l'utiliser ainsi :
-```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
-```
+{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}
+
+/// tip | Astuce
+
+Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash initial (`/`).
-!!! tip "Astuce"
- Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash au début (`/`).
+Dans ce cas, l'URL serait : `/files//home/johndoe/myfile.txt`, avec un double slash (`//`) entre `files` et `home`.
- Dans ce cas, l'URL serait : `/files//home/johndoe/myfile.txt`, avec un double slash (`//`) entre `files` et `home`.
+///
-## Récapitulatif
+## Récapitulatif { #recap }
-Avec **FastAPI**, en utilisant les déclarations de type rapides, intuitives et standards de Python, vous bénéficiez de :
+Avec **FastAPI**, en utilisant des déclarations de type Python courtes, intuitives et standard, vous obtenez :
-* Support de l'éditeur : vérification d'erreurs, auto-complétion, etc.
-* "Parsing" de données.
-* Validation de données.
-* Annotations d'API et documentation automatique.
+* Support de l'éditeur : vérifications d'erreurs, autocomplétion, etc.
+* Données « parsing »
+* Validation de données
+* Annotations d'API et documentation automatique
-Et vous n'avez besoin de le déclarer qu'une fois.
+Et vous n'avez besoin de les déclarer qu'une seule fois.
-C'est probablement l'avantage visible principal de **FastAPI** comparé aux autres *frameworks* (outre les performances pures).
+C'est probablement l'avantage visible principal de **FastAPI** comparé aux autres frameworks (outre les performances pures).
diff --git a/docs/fr/docs/tutorial/query-param-models.md b/docs/fr/docs/tutorial/query-param-models.md
new file mode 100644
index 0000000000000..b9bb1d13787a3
--- /dev/null
+++ b/docs/fr/docs/tutorial/query-param-models.md
@@ -0,0 +1,68 @@
+# Modèles de paramètres de requête { #query-parameter-models }
+
+Si vous avez un groupe de paramètres de requête liés, vous pouvez créer un modèle Pydantic pour les déclarer.
+
+Cela vous permet de réutiliser le modèle à plusieurs endroits et aussi de déclarer des validations et des métadonnées pour tous les paramètres en une seule fois. 😎
+
+/// note | Remarque
+
+Pris en charge depuis FastAPI version `0.115.0`. 🤓
+
+///
+
+## Déclarer des paramètres de requête avec un modèle Pydantic { #query-parameters-with-a-pydantic-model }
+
+Déclarez les paramètres de requête dont vous avez besoin dans un modèle Pydantic, puis déclarez le paramètre en tant que `Query` :
+
+{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}
+
+FastAPI extrait les données pour chaque champ à partir des paramètres de requête de la requête et vous fournit le modèle Pydantic que vous avez défini.
+
+## Consulter les documents { #check-the-docs }
+
+Vous pouvez voir les paramètres de requête dans l'interface des documents à `/docs` :
+
+
+
-### Combiner liste de paramètres et valeurs par défaut
+### Liste de paramètres de requête / valeurs multiples avec valeurs par défaut { #query-parameter-list-multiple-values-with-defaults }
-Et l'on peut aussi définir une liste de valeurs par défaut si aucune n'est fournie :
+Vous pouvez également définir une `list` de valeurs par défaut si aucune n’est fournie :
-```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial012.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
Si vous allez à :
@@ -196,9 +276,7 @@ Si vous allez à :
http://localhost:8000/items/
```
-la valeur par défaut de `q` sera : `["foo", "bar"]`
-
-et la réponse sera :
+la valeur par défaut de `q` sera : `["foo", "bar"]` et votre réponse sera :
```JSON
{
@@ -209,97 +287,163 @@ et la réponse sera :
}
```
-#### Utiliser `list`
+#### Utiliser simplement `list` { #using-just-list }
-Il est aussi possible d'utiliser directement `list` plutôt que `List[str]` :
+Vous pouvez aussi utiliser `list` directement au lieu de `list[str]` :
-```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial013.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
+
+/// note | Remarque
+
+Gardez à l’esprit que dans ce cas, FastAPI ne vérifiera pas le contenu de la liste.
+
+Par exemple, `list[int]` vérifierait (et documenterait) que le contenu de la liste est composé d’entiers. Mais un simple `list` ne le ferait pas.
+
+///
-!!! note
- Dans ce cas-là, **FastAPI** ne vérifiera pas le contenu de la liste.
+## Déclarer plus de métadonnées { #declare-more-metadata }
- Par exemple, `List[int]` vérifiera (et documentera) que la liste est bien entièrement composée d'entiers. Alors qu'un simple `list` ne ferait pas cette vérification.
+Vous pouvez ajouter plus d’informations à propos du paramètre.
-## Déclarer des métadonnées supplémentaires
+Ces informations seront incluses dans l’OpenAPI généré et utilisées par les interfaces de documentation et les outils externes.
-On peut aussi ajouter plus d'informations sur le paramètre.
+/// note | Remarque
-Ces informations seront incluses dans le schéma `OpenAPI` généré et utilisées par la documentation interactive ou les outils externes utilisés.
+Gardez à l’esprit que différents outils peuvent avoir des niveaux de prise en charge d’OpenAPI différents.
-!!! note
- Gardez en tête que les outils externes utilisés ne supportent pas forcément tous parfaitement OpenAPI.
+Certains d’entre eux pourraient ne pas encore afficher toutes les informations supplémentaires déclarées, bien que, dans la plupart des cas, la fonctionnalité manquante soit déjà prévue au développement.
- Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnées que vous avez déclarées pour le moment, bien que dans la plupart des cas, les fonctionnalités manquantes ont prévu d'être implémentées.
+///
Vous pouvez ajouter un `title` :
-```Python hl_lines="10"
-{!../../../docs_src/query_params_str_validations/tutorial007.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *}
Et une `description` :
-```Python hl_lines="13"
-{!../../../docs_src/query_params_str_validations/tutorial008.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *}
-## Alias de paramètres
+## Paramètres avec alias { #alias-parameters }
-Imaginez que vous vouliez que votre paramètre se nomme `item-query`.
+Imaginez que vous vouliez que le paramètre soit `item-query`.
-Comme dans la requête :
+Comme dans :
```
http://127.0.0.1:8000/items/?item-query=foobaritems
```
-Mais `item-query` n'est pas un nom de variable valide en Python.
+Mais `item-query` n’est pas un nom de variable Python valide.
-Le nom le plus proche serait `item_query`.
+Le plus proche serait `item_query`.
-Mais vous avez vraiment envie que ce soit exactement `item-query`...
+Mais vous avez quand même besoin que ce soit exactement `item-query` ...
-Pour cela vous pouvez déclarer un `alias`, et cet alias est ce qui sera utilisé pour trouver la valeur du paramètre :
+Vous pouvez alors déclarer un `alias`, et cet alias sera utilisé pour trouver la valeur du paramètre :
-```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial009.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *}
-## Déprécier des paramètres
+## Déprécier des paramètres { #deprecating-parameters }
-Disons que vous ne vouliez plus utiliser ce paramètre désormais.
+Disons que vous n’aimez plus ce paramètre.
-Il faut qu'il continue à exister pendant un certain temps car vos clients l'utilisent, mais vous voulez que la documentation mentionne clairement que ce paramètre est déprécié.
+Vous devez le laisser là quelque temps car des clients l’utilisent, mais vous voulez que les documents l’affichent clairement comme déprécié.
-On utilise alors l'argument `deprecated=True` de `Query` :
+Passez alors le paramètre `deprecated=True` à `Query` :
-```Python hl_lines="18"
-{!../../../docs_src/query_params_str_validations/tutorial010.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *}
-La documentation le présentera comme il suit :
+Les documents l’afficheront ainsi :
-## Pour résumer
+## Exclure des paramètres d’OpenAPI { #exclude-parameters-from-openapi }
+
+Pour exclure un paramètre de requête du schéma OpenAPI généré (et donc, des systèmes de documentation automatiques), définissez le paramètre `include_in_schema` de `Query` à `False` :
+
+{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *}
+
+## Validation personnalisée { #custom-validation }
+
+Il peut y avoir des cas où vous devez faire une **validation personnalisée** qui ne peut pas être réalisée avec les paramètres montrés ci-dessus.
+
+Dans ces cas, vous pouvez utiliser une **fonction de validation personnalisée** qui est appliquée après la validation normale (par ex. après avoir validé que la valeur est une `str`).
+
+Vous pouvez y parvenir en utilisant [`AfterValidator` de Pydantic](https://docs.pydantic.dev/latest/concepts/validators/#field-after-validator) à l’intérieur de `Annotated`.
+
+/// tip | Astuce
+
+Pydantic a aussi [`BeforeValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-before-validator) et d’autres. 🤓
+
+///
+
+Par exemple, ce validateur personnalisé vérifie que l’ID d’item commence par `isbn-` pour un numéro de livre ISBN ou par `imdb-` pour un ID d’URL de film IMDB :
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
+
+/// info
+
+C’est disponible avec Pydantic version 2 ou supérieure. 😎
+
+///
+
+/// tip | Astuce
+
+Si vous devez faire un type de validation qui nécessite de communiquer avec un **composant externe**, comme une base de données ou une autre API, vous devez plutôt utiliser les **Dépendances de FastAPI**, vous en apprendrez davantage plus tard.
+
+Ces validateurs personnalisés sont destinés aux éléments qui peuvent être vérifiés **uniquement** avec les **mêmes données** fournies dans la requête.
+
+///
+
+### Comprendre ce code { #understand-that-code }
+
+Le point important est simplement d’utiliser **`AfterValidator` avec une fonction à l’intérieur de `Annotated`**. N’hésitez pas à passer cette partie. 🤸
+
+---
+
+Mais si vous êtes curieux de cet exemple de code spécifique et que vous êtes toujours partant, voici quelques détails supplémentaires.
+
+#### Chaîne avec `value.startswith()` { #string-with-value-startswith }
+
+Avez-vous remarqué ? Une chaîne utilisant `value.startswith()` peut prendre un tuple, et elle vérifiera chaque valeur du tuple :
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *}
+
+#### Un élément aléatoire { #a-random-item }
+
+Avec `data.items()` nous obtenons un objet itérable avec des tuples contenant la clé et la valeur pour chaque élément du dictionnaire.
+
+Nous convertissons cet objet itérable en une `list` propre avec `list(data.items())`.
+
+Ensuite, avec `random.choice()` nous pouvons obtenir une **valeur aléatoire** depuis la liste, nous obtenons donc un tuple `(id, name)`. Ce sera quelque chose comme `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")`.
+
+Puis nous **affectons ces deux valeurs** du tuple aux variables `id` et `name`.
+
+Ainsi, si l’utilisateur n’a pas fourni d’ID d’item, il recevra quand même une suggestion aléatoire.
+
+... nous faisons tout cela en **une seule ligne simple**. 🤯 Vous n’adorez pas Python ? 🐍
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *}
+
+## Récapitulatif { #recap }
+
+Vous pouvez déclarer des validations et des métadonnées supplémentaires pour vos paramètres.
-Il est possible d'ajouter des validateurs et métadonnées pour vos paramètres.
+Validations et métadonnées génériques :
-Validateurs et métadonnées génériques:
+- `alias`
+- `title`
+- `description`
+- `deprecated`
-* `alias`
-* `title`
-* `description`
-* `deprecated`
+Validations spécifiques aux chaînes :
-Validateurs spécifiques aux chaînes de caractères :
+- `min_length`
+- `max_length`
+- `pattern`
-* `min_length`
-* `max_length`
-* `regex`
+Validations personnalisées avec `AfterValidator`.
-Parmi ces exemples, vous avez pu voir comment déclarer des validateurs pour les chaînes de caractères.
+Dans ces exemples, vous avez vu comment déclarer des validations pour des valeurs `str`.
-Dans les prochains chapitres, vous verrez comment déclarer des validateurs pour d'autres types, comme les nombres.
+Voyez les prochains chapitres pour apprendre à déclarer des validations pour d’autres types, comme les nombres.
diff --git a/docs/fr/docs/tutorial/query-params.md b/docs/fr/docs/tutorial/query-params.md
index 962135f63eebd..8ecbc2853653a 100644
--- a/docs/fr/docs/tutorial/query-params.md
+++ b/docs/fr/docs/tutorial/query-params.md
@@ -1,12 +1,10 @@
-# Paramètres de requête
+# Paramètres de requête { #query-parameters }
-Quand vous déclarez des paramètres dans votre fonction de chemin qui ne font pas partie des paramètres indiqués dans le chemin associé, ces paramètres sont automatiquement considérés comme des paramètres de "requête".
+Quand vous déclarez d'autres paramètres de fonction qui ne font pas partie des paramètres de chemin, ils sont automatiquement interprétés comme des paramètres de « query ».
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial001.py!}
-```
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
-La partie appelée requête (ou **query**) dans une URL est l'ensemble des paires clés-valeurs placées après le `?` , séparées par des `&`.
+La query est l'ensemble des paires clé-valeur placées après le `?` dans une URL, séparées par des caractères `&`.
Par exemple, dans l'URL :
@@ -14,27 +12,27 @@ Par exemple, dans l'URL :
http://127.0.0.1:8000/items/?skip=0&limit=10
```
-...les paramètres de requête sont :
+... les paramètres de requête sont :
-* `skip` : avec une valeur de`0`
+* `skip` : avec une valeur de `0`
* `limit` : avec une valeur de `10`
-Faisant partie de l'URL, ces valeurs sont des chaînes de caractères (`str`).
+Comme ils font partie de l'URL, ce sont « naturellement » des chaînes de caractères.
-Mais quand on les déclare avec des types Python (dans l'exemple précédent, en tant qu'`int`), elles sont converties dans les types renseignés.
+Mais lorsque vous les déclarez avec des types Python (dans l'exemple ci-dessus, en tant que `int`), ils sont convertis vers ce type et validés par rapport à celui-ci.
-Toutes les fonctionnalités qui s'appliquent aux paramètres de chemin s'appliquent aussi aux paramètres de requête :
+Tous les mêmes processus qui s'appliquaient aux paramètres de chemin s'appliquent aussi aux paramètres de requête :
-* Support de l'éditeur : vérification d'erreurs, auto-complétion, etc.
-* "Parsing" de données.
-* Validation de données.
-* Annotations d'API et documentation automatique.
+* Prise en charge de l'éditeur (évidemment)
+* « parsing » des données
+* Validation des données
+* Documentation automatique
-## Valeurs par défaut
+## Valeurs par défaut { #defaults }
-Les paramètres de requête ne sont pas une partie fixe d'un chemin, ils peuvent être optionnels et avoir des valeurs par défaut.
+Comme les paramètres de requête ne sont pas une partie fixe d'un chemin, ils peuvent être optionnels et avoir des valeurs par défaut.
-Dans l'exemple ci-dessus, ils ont des valeurs par défaut qui sont `skip=0` et `limit=10`.
+Dans l'exemple ci-dessus, ils ont des valeurs par défaut `skip=0` et `limit=10`.
Donc, accéder à l'URL :
@@ -42,51 +40,44 @@ Donc, accéder à l'URL :
http://127.0.0.1:8000/items/
```
-serait équivalent à accéder à l'URL :
+serait équivalent à accéder à :
```
http://127.0.0.1:8000/items/?skip=0&limit=10
```
-Mais si vous accédez à, par exemple :
+Mais si vous accédez, par exemple, à :
```
http://127.0.0.1:8000/items/?skip=20
```
-Les valeurs des paramètres de votre fonction seront :
+Les valeurs des paramètres dans votre fonction seront :
-* `skip=20` : car c'est la valeur déclarée dans l'URL.
-* `limit=10` : car `limit` n'a pas été déclaré dans l'URL, et que la valeur par défaut était `10`.
+* `skip=20` : car vous l'avez défini dans l'URL
+* `limit=10` : car c'était la valeur par défaut
-## Paramètres optionnels
+## Paramètres optionnels { #optional-parameters }
-De la même façon, vous pouvez définir des paramètres de requête comme optionnels, en leur donnant comme valeur par défaut `None` :
+De la même façon, vous pouvez déclarer des paramètres de requête optionnels, en définissant leur valeur par défaut à `None` :
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial002.py!}
-```
+{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *}
-Ici, le paramètre `q` sera optionnel, et aura `None` comme valeur par défaut.
+Dans ce cas, le paramètre de fonction `q` sera optionnel et vaudra `None` par défaut.
-!!! check "Remarque"
- On peut voir que **FastAPI** est capable de détecter que le paramètre de chemin `item_id` est un paramètre de chemin et que `q` n'en est pas un, c'est donc un paramètre de requête.
+/// check | Vérifications
-!!! note
- **FastAPI** saura que `q` est optionnel grâce au `=None`.
+Notez également que **FastAPI** est suffisamment intelligent pour remarquer que le paramètre de chemin `item_id` est un paramètre de chemin et que `q` ne l'est pas, c'est donc un paramètre de requête.
- Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI** n'en utilisera que la partie `str`), mais il servira tout de même à votre éditeur de texte pour détecter des erreurs dans votre code.
+///
+## Conversion des types des paramètres de requête { #query-parameter-type-conversion }
-## Conversion des types des paramètres de requête
+Vous pouvez aussi déclarer des types `bool`, ils seront convertis :
-Vous pouvez aussi déclarer des paramètres de requête comme booléens (`bool`), **FastAPI** les convertira :
+{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *}
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial003.py!}
-```
-
-Avec ce code, en allant sur :
+Dans ce cas, si vous allez sur :
```
http://127.0.0.1:8000/items/foo?short=1
@@ -116,64 +107,61 @@ ou
http://127.0.0.1:8000/items/foo?short=yes
```
-ou n'importe quelle autre variation de casse (tout en majuscules, uniquement la première lettre en majuscule, etc.), votre fonction considérera le paramètre `short` comme ayant une valeur booléenne à `True`. Sinon la valeur sera à `False`.
+ou n'importe quelle autre variation de casse (tout en majuscules, uniquement la première lettre en majuscule, etc.), votre fonction verra le paramètre `short` avec une valeur `bool` à `True`. Sinon la valeur sera à `False`.
-## Multiples paramètres de chemin et de requête
+## Multiples paramètres de chemin et de requête { #multiple-path-and-query-parameters }
-Vous pouvez déclarer plusieurs paramètres de chemin et paramètres de requête dans la même fonction, **FastAPI** saura comment les gérer.
+Vous pouvez déclarer plusieurs paramètres de chemin et paramètres de requête en même temps, **FastAPI** sait lequel est lequel.
Et vous n'avez pas besoin de les déclarer dans un ordre spécifique.
-Ils seront détectés par leurs noms :
+Ils seront détectés par leur nom :
-```Python hl_lines="8 10"
-{!../../../docs_src/query_params/tutorial004.py!}
-```
+{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *}
-## Paramètres de requête requis
+## Paramètres de requête requis { #required-query-parameters }
-Quand vous déclarez une valeur par défaut pour un paramètre qui n'est pas un paramètre de chemin (actuellement, nous n'avons vu que les paramètres de requête), alors ce paramètre n'est pas requis.
+Quand vous déclarez une valeur par défaut pour des paramètres qui ne sont pas des paramètres de chemin (pour l'instant, nous n'avons vu que les paramètres de requête), alors ils ne sont pas requis.
-Si vous ne voulez pas leur donner de valeur par défaut mais juste les rendre optionnels, utilisez `None` comme valeur par défaut.
+Si vous ne voulez pas leur donner de valeur spécifique mais simplement les rendre optionnels, définissez la valeur par défaut à `None`.
-Mais si vous voulez rendre un paramètre de requête obligatoire, vous pouvez juste ne pas y affecter de valeur par défaut :
+Mais si vous voulez rendre un paramètre de requête obligatoire, vous pouvez simplement ne déclarer aucune valeur par défaut :
-```Python hl_lines="6-7"
-{!../../../docs_src/query_params/tutorial005.py!}
-```
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
-Ici le paramètre `needy` est un paramètre requis (ou obligatoire) de type `str`.
+Ici, le paramètre de requête `needy` est un paramètre de requête requis de type `str`.
-Si vous ouvrez une URL comme :
+Si vous ouvrez dans votre navigateur une URL comme :
```
http://127.0.0.1:8000/items/foo-item
```
-...sans ajouter le paramètre requis `needy`, vous aurez une erreur :
+... sans ajouter le paramètre requis `needy`, vous verrez une erreur comme :
```JSON
{
- "detail": [
- {
- "loc": [
- "query",
- "needy"
- ],
- "msg": "field required",
- "type": "value_error.missing"
- }
- ]
+ "detail": [
+ {
+ "type": "missing",
+ "loc": [
+ "query",
+ "needy"
+ ],
+ "msg": "Field required",
+ "input": null
+ }
+ ]
}
```
-La présence de `needy` étant nécessaire, vous auriez besoin de l'insérer dans l'URL :
+Comme `needy` est un paramètre requis, vous devez le définir dans l'URL :
```
http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
```
-...ce qui fonctionnerait :
+... cela fonctionnerait :
```JSON
{
@@ -182,17 +170,18 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
}
```
-Et bien sur, vous pouvez définir certains paramètres comme requis, certains avec des valeurs par défaut et certains entièrement optionnels :
+Et bien sûr, vous pouvez définir certains paramètres comme requis, certains avec une valeur par défaut et certains entièrement optionnels :
-```Python hl_lines="10"
-{!../../../docs_src/query_params/tutorial006.py!}
-```
+{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *}
-Ici, on a donc 3 paramètres de requête :
+Dans ce cas, il y a 3 paramètres de requête :
-* `needy`, requis et de type `str`.
-* `skip`, un `int` avec comme valeur par défaut `0`.
+* `needy`, un `str` requis.
+* `skip`, un `int` avec une valeur par défaut de `0`.
* `limit`, un `int` optionnel.
-!!! tip "Astuce"
- Vous pouvez utiliser les `Enum`s de la même façon qu'avec les [Paramètres de chemin](path-params.md#valeurs-predefinies){.internal-link target=_blank}.
+/// tip | Astuce
+
+Vous pourriez aussi utiliser des `Enum`s de la même façon qu'avec les [Paramètres de chemin](path-params.md#predefined-values).
+
+///
diff --git a/docs/fr/docs/tutorial/request-files.md b/docs/fr/docs/tutorial/request-files.md
new file mode 100644
index 0000000000000..e55f8e57fede6
--- /dev/null
+++ b/docs/fr/docs/tutorial/request-files.md
@@ -0,0 +1,176 @@
+# Envoyer des fichiers { #request-files }
+
+Vous pouvez définir des fichiers à téléverser par le client en utilisant `File`.
+
+/// info
+
+Pour recevoir des fichiers téléversés, installez d'abord [`python-multipart`](https://github.com/Kludex/python-multipart).
+
+Assurez-vous de créer un [environnement virtuel](../virtual-environments.md), de l'activer, puis d'installer le paquet, par exemple :
+
+```console
+$ pip install python-multipart
+```
+
+C'est parce que les fichiers téléversés sont envoyés en « données de formulaire ».
+
+///
+
+## Importer `File` { #import-file }
+
+Importez `File` et `UploadFile` depuis `fastapi` :
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
+
+## Définir des paramètres `File` { #define-file-parameters }
+
+Créez des paramètres de fichier de la même manière que pour `Body` ou `Form` :
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
+
+/// info
+
+`File` est une classe qui hérite directement de `Form`.
+
+Mais souvenez-vous que lorsque vous importez `Query`, `Path`, `File` et d'autres depuis `fastapi`, ce sont en réalité des fonctions qui renvoient des classes spéciales.
+
+///
+
+/// tip | Astuce
+
+Pour déclarer des fichiers dans le corps de la requête, vous devez utiliser `File`, sinon les paramètres seraient interprétés comme des paramètres de requête ou des paramètres de corps (JSON).
+
+///
+
+Les fichiers seront téléversés en « données de formulaire ».
+
+Si vous déclarez le type de votre paramètre de *fonction de chemin d'accès* comme `bytes`, **FastAPI** lira le fichier pour vous et vous recevrez le contenu sous forme de `bytes`.
+
+Gardez à l'esprit que cela signifie que tout le contenu sera stocké en mémoire. Cela fonctionnera bien pour de petits fichiers.
+
+Mais dans plusieurs cas, vous pourriez bénéficier de l'utilisation d'`UploadFile`.
+
+## Paramètres de fichier avec `UploadFile` { #file-parameters-with-uploadfile }
+
+Définissez un paramètre de fichier de type `UploadFile` :
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
+
+Utiliser `UploadFile` présente plusieurs avantages par rapport à `bytes` :
+
+- Vous n'avez pas besoin d'utiliser `File()` comme valeur par défaut du paramètre.
+- Il utilise un fichier « spooled » :
+ - Un fichier stocké en mémoire jusqu'à une taille maximale, puis, au-delà de cette limite, stocké sur le disque.
+- Cela fonctionne donc bien pour des fichiers volumineux comme des images, des vidéos, de gros binaires, etc., sans consommer toute la mémoire.
+- Vous pouvez obtenir des métadonnées à partir du fichier téléversé.
+- Il offre une interface `async` de type [file-like](https://docs.python.org/3/glossary.html#term-file-like-object).
+- Il expose un véritable objet Python [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) que vous pouvez passer directement à d'autres bibliothèques qui attendent un objet « file-like ».
+
+### `UploadFile` { #uploadfile }
+
+`UploadFile` a les attributs suivants :
+
+- `filename` : une `str` contenant le nom de fichier original téléversé (par ex. `myimage.jpg`).
+- `content_type` : une `str` avec le type de contenu (type MIME / type média) (par ex. `image/jpeg`).
+- `file` : un [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) (un objet [file-like](https://docs.python.org/3/glossary.html#term-file-like-object)). C'est l'objet fichier Python réel que vous pouvez passer directement à d'autres fonctions ou bibliothèques qui attendent un objet « file-like ».
+
+`UploadFile` a les méthodes `async` suivantes. Elles appellent toutes les méthodes correspondantes du fichier sous-jacent (en utilisant le `SpooledTemporaryFile` interne).
+
+- `write(data)` : écrit `data` (`str` ou `bytes`) dans le fichier.
+- `read(size)` : lit `size` (`int`) octets/caractères du fichier.
+- `seek(offset)` : se déplace à la position d'octet `offset` (`int`) dans le fichier.
+ - Par ex., `await myfile.seek(0)` irait au début du fichier.
+ - C'est particulièrement utile si vous exécutez `await myfile.read()` une fois puis devez relire le contenu.
+- `close()` : ferme le fichier.
+
+Comme toutes ces méthodes sont `async`, vous devez les « await ».
+
+Par exemple, à l'intérieur d'une *fonction de chemin d'accès* `async`, vous pouvez obtenir le contenu avec :
+
+```Python
+contents = await myfile.read()
+```
+
+Si vous êtes dans une *fonction de chemin d'accès* `def` normale, vous pouvez accéder directement à `UploadFile.file`, par exemple :
+
+```Python
+contents = myfile.file.read()
+```
+
+/// note | Détails techniques `async`
+
+Lorsque vous utilisez les méthodes `async`, **FastAPI** exécute les méthodes de fichier dans un pool de threads et les attend.
+
+///
+
+/// note | Détails techniques Starlette
+
+L'`UploadFile` de **FastAPI** hérite directement de l'`UploadFile` de **Starlette**, mais ajoute certaines parties nécessaires pour le rendre compatible avec **Pydantic** et les autres parties de FastAPI.
+
+///
+
+## Qu'est-ce que les « données de formulaire » { #what-is-form-data }
+
+La façon dont les formulaires HTML (``) envoient les données au serveur utilise normalement un encodage « spécial » pour ces données, différent de JSON.
+
+**FastAPI** s'assure de lire ces données au bon endroit plutôt que depuis JSON.
+
+/// note | Détails techniques
+
+Les données des formulaires sont normalement encodées avec le « type de média » `application/x-www-form-urlencoded` lorsqu'elles n'incluent pas de fichiers.
+
+Mais lorsque le formulaire inclut des fichiers, il est encodé en `multipart/form-data`. Si vous utilisez `File`, **FastAPI** saura qu'il doit récupérer les fichiers depuis la partie appropriée du corps.
+
+Si vous souhaitez en savoir plus sur ces encodages et les champs de formulaire, consultez la [MDN Web Docs pour `POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST).
+
+///
+
+/// warning | Alertes
+
+Vous pouvez déclarer plusieurs paramètres `File` et `Form` dans un *chemin d'accès*, mais vous ne pouvez pas également déclarer des champs `Body` que vous vous attendez à recevoir en JSON, car la requête aura le corps encodé en `multipart/form-data` au lieu de `application/json`.
+
+Ce n'est pas une limitation de **FastAPI**, cela fait partie du protocole HTTP.
+
+///
+
+## Téléversement de fichier facultatif { #optional-file-upload }
+
+Vous pouvez rendre un fichier facultatif en utilisant des annotations de type standard et en définissant une valeur par défaut à `None` :
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## `UploadFile` avec des métadonnées supplémentaires { #uploadfile-with-additional-metadata }
+
+Vous pouvez aussi utiliser `File()` avec `UploadFile`, par exemple pour définir des métadonnées supplémentaires :
+
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
+
+## Téléverser plusieurs fichiers { #multiple-file-uploads }
+
+Il est possible de téléverser plusieurs fichiers en même temps.
+
+Ils seraient associés au même « champ de formulaire » envoyé en « données de formulaire ».
+
+Pour cela, déclarez une `list` de `bytes` ou d'`UploadFile` :
+
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
+
+Vous recevrez, comme déclaré, une `list` de `bytes` ou d'`UploadFile`.
+
+/// note | Détails techniques
+
+Vous pourriez aussi utiliser `from starlette.responses import HTMLResponse`.
+
+**FastAPI** fournit les mêmes `starlette.responses` sous `fastapi.responses` simplement pour votre convenance en tant que développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette.
+
+///
+
+### Téléversements multiples avec métadonnées supplémentaires { #multiple-file-uploads-with-additional-metadata }
+
+Et de la même manière que précédemment, vous pouvez utiliser `File()` pour définir des paramètres supplémentaires, même pour `UploadFile` :
+
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
+
+## Récapitulatif { #recap }
+
+Utilisez `File`, `bytes` et `UploadFile` pour déclarer des fichiers à téléverser dans la requête, envoyés en « données de formulaire ».
diff --git a/docs/fr/docs/tutorial/request-form-models.md b/docs/fr/docs/tutorial/request-form-models.md
new file mode 100644
index 0000000000000..0f1e6dcfd178b
--- /dev/null
+++ b/docs/fr/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Modèles de formulaire { #form-models }
+
+Vous pouvez utiliser des **modèles Pydantic** pour déclarer des **champs de formulaire** dans FastAPI.
+
+/// info
+
+Pour utiliser les formulaires, installez d'abord [`python-multipart`](https://github.com/Kludex/python-multipart).
+
+Assurez-vous de créer un [environnement virtuel](../virtual-environments.md), de l'activer, puis d'installer le paquet, par exemple :
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | Remarque
+
+Ceci est pris en charge depuis la version `0.113.0` de FastAPI. 🤓
+
+///
+
+## Modèles Pydantic pour les formulaires { #pydantic-models-for-forms }
+
+Vous avez simplement besoin de déclarer un **modèle Pydantic** avec les champs que vous souhaitez recevoir comme **champs de formulaire**, puis de déclarer le paramètre comme `Form` :
+
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
+
+**FastAPI** va **extraire** les données pour **chaque champ** à partir des **données de formulaire** de la requête et vous fournir le modèle Pydantic que vous avez défini.
+
+## Consulter les documents { #check-the-docs }
+
+Vous pouvez le vérifier dans l'interface des documents à `/docs` :
+
+
+
+
+Et les deux modèles seront utilisés pour la documentation API interactive :
+
+
+
+## Autres annotations de type de retour { #other-return-type-annotations }
+
+Il peut y avoir des cas où vous renvoyez quelque chose qui n'est pas un champ Pydantic valide et vous l'annotez dans la fonction, uniquement pour obtenir la prise en charge fournie par les outils (l’éditeur, mypy, etc.).
+
+### Renvoyer directement une Response { #return-a-response-directly }
+
+Le cas le plus courant serait [de renvoyer directement une Response comme expliqué plus loin dans la documentation avancée](../advanced/response-directly.md).
+
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
+
+Ce cas simple est géré automatiquement par FastAPI car l'annotation du type de retour est la classe (ou une sous-classe de) `Response`.
+
+Et les outils seront également satisfaits car `RedirectResponse` et `JSONResponse` sont des sous-classes de `Response`, donc l'annotation de type est correcte.
+
+### Annoter une sous-classe de Response { #annotate-a-response-subclass }
+
+Vous pouvez aussi utiliser une sous-classe de `Response` dans l'annotation de type :
+
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
+
+Cela fonctionnera également car `RedirectResponse` est une sous-classe de `Response`, et FastAPI gérera automatiquement ce cas simple.
+
+### Annotations de type de retour invalides { #invalid-return-type-annotations }
+
+Mais lorsque vous renvoyez un autre objet arbitraire qui n'est pas un type Pydantic valide (par exemple un objet de base de données) et que vous l'annotez ainsi dans la fonction, FastAPI essaiera de créer un modèle de réponse Pydantic à partir de cette annotation de type, et échouera.
+
+Il en serait de même si vous aviez quelque chose comme une union entre différents types dont un ou plusieurs ne sont pas des types Pydantic valides, par exemple ceci échouerait 💥 :
+
+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
+
+... cela échoue parce que l'annotation de type n'est pas un type Pydantic et n'est pas juste une unique classe `Response` ou une sous-classe, c'est une union (l'un des deux) entre une `Response` et un `dict`.
+
+### Désactiver le modèle de réponse { #disable-response-model }
+
+En reprenant l'exemple ci-dessus, vous pourriez ne pas vouloir avoir la validation par défaut des données, la documentation, le filtrage, etc. effectués par FastAPI.
+
+Mais vous pourriez vouloir tout de même conserver l’annotation du type de retour dans la fonction pour bénéficier de la prise en charge des outils comme les éditeurs et les vérificateurs de type (par exemple mypy).
+
+Dans ce cas, vous pouvez désactiver la génération du modèle de réponse en définissant `response_model=None` :
+
+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}
+
+Cela fera en sorte que FastAPI ignore la génération du modèle de réponse et vous permettra ainsi d’avoir toutes les annotations de type de retour dont vous avez besoin sans que cela n’affecte votre application FastAPI. 🤓
+
+## Paramètres d'encodage du modèle de réponse { #response-model-encoding-parameters }
+
+Votre modèle de réponse peut avoir des valeurs par défaut, par exemple :
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}
+
+* `description: Union[str, None] = None` (ou `str | None = None` en Python 3.10) a une valeur par défaut `None`.
+* `tax: float = 10.5` a une valeur par défaut `10.5`.
+* `tags: List[str] = []` a une valeur par défaut de liste vide : `[]`.
+
+mais vous pourriez vouloir les omettre du résultat si elles n'ont pas été réellement stockées.
+
+Par exemple, si vous avez des modèles avec de nombreux attributs optionnels dans une base NoSQL, mais que vous ne voulez pas envoyer de très longues réponses JSON remplies de valeurs par défaut.
+
+### Utiliser le paramètre `response_model_exclude_unset` { #use-the-response-model-exclude-unset-parameter }
+
+Vous pouvez définir le paramètre du *décorateur de chemin d'accès* `response_model_exclude_unset=True` :
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}
+
+et ces valeurs par défaut ne seront pas incluses dans la réponse, uniquement les valeurs effectivement définies.
+
+Ainsi, si vous envoyez une requête à ce *chemin d'accès* pour l'article avec l'ID `foo`, la réponse (sans les valeurs par défaut) sera :
+
+```JSON
+{
+ "name": "Foo",
+ "price": 50.2
+}
+```
+
+/// info | Info
+
+Vous pouvez également utiliser :
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+comme décrit dans [la documentation Pydantic](https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict) pour `exclude_defaults` et `exclude_none`.
+
+///
+
+#### Données avec des valeurs pour des champs avec des valeurs par défaut { #data-with-values-for-fields-with-defaults }
+
+Mais si vos données ont des valeurs pour les champs du modèle avec des valeurs par défaut, comme l'article avec l'ID `bar` :
+
+```Python hl_lines="3 5"
+{
+ "name": "Bar",
+ "description": "The bartenders",
+ "price": 62,
+ "tax": 20.2
+}
+```
+
+elles seront incluses dans la réponse.
+
+#### Données avec les mêmes valeurs que les valeurs par défaut { #data-with-the-same-values-as-the-defaults }
+
+Si les données ont les mêmes valeurs que les valeurs par défaut, comme l'article avec l'ID `baz` :
+
+```Python hl_lines="3 5-6"
+{
+ "name": "Baz",
+ "description": None,
+ "price": 50.2,
+ "tax": 10.5,
+ "tags": []
+}
+```
+
+FastAPI est suffisamment intelligent (en fait, Pydantic l’est) pour comprendre que, même si `description`, `tax` et `tags` ont les mêmes valeurs que les valeurs par défaut, elles ont été définies explicitement (au lieu d'être prises depuis les valeurs par défaut).
+
+Elles seront donc incluses dans la réponse JSON.
+
+/// tip | Astuce
+
+Notez que les valeurs par défaut peuvent être n'importe quoi, pas seulement `None`.
+
+Elles peuvent être une liste (`[]`), un `float` de `10.5`, etc.
+
+///
+
+### `response_model_include` et `response_model_exclude` { #response-model-include-and-response-model-exclude }
+
+Vous pouvez également utiliser les paramètres du *décorateur de chemin d'accès* `response_model_include` et `response_model_exclude`.
+
+Ils prennent un `set` de `str` avec les noms des attributs à inclure (en omettant le reste) ou à exclure (en incluant le reste).
+
+Cela peut être utilisé comme un raccourci rapide si vous n'avez qu'un seul modèle Pydantic et que vous souhaitez supprimer certaines données de la sortie.
+
+/// tip | Astuce
+
+Mais il est toujours recommandé d'utiliser les idées ci-dessus, en utilisant plusieurs classes, plutôt que ces paramètres.
+
+En effet, le JSON Schema généré dans l’OpenAPI de votre application (et la documentation) restera celui du modèle complet, même si vous utilisez `response_model_include` ou `response_model_exclude` pour omettre certains attributs.
+
+Cela s'applique également à `response_model_by_alias` qui fonctionne de manière similaire.
+
+///
+
+{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}
+
+/// tip | Astuce
+
+La syntaxe `{"name", "description"}` crée un `set` avec ces deux valeurs.
+
+Elle est équivalente à `set(["name", "description"])`.
+
+///
+
+#### Utiliser des `list` au lieu de `set` { #using-lists-instead-of-sets }
+
+Si vous oubliez d'utiliser un `set` et utilisez une `list` ou un `tuple` à la place, FastAPI le convertira quand même en `set` et cela fonctionnera correctement :
+
+{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}
+
+## Récapitulatif { #recap }
+
+Utilisez le paramètre du *décorateur de chemin d'accès* `response_model` pour définir les modèles de réponse et surtout pour garantir que les données privées sont filtrées.
+
+Utilisez `response_model_exclude_unset` pour ne renvoyer que les valeurs définies explicitement.
diff --git a/docs/fr/docs/tutorial/response-status-code.md b/docs/fr/docs/tutorial/response-status-code.md
new file mode 100644
index 0000000000000..c8e45cd40edf1
--- /dev/null
+++ b/docs/fr/docs/tutorial/response-status-code.md
@@ -0,0 +1,101 @@
+# Code d'état de la réponse { #response-status-code }
+
+De la même manière que vous pouvez spécifier un modèle de réponse, vous pouvez également déclarer le code d'état HTTP utilisé pour la réponse avec le paramètre `status_code` dans n'importe lequel des chemins d'accès :
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* etc.
+
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
+
+/// note | Remarque
+
+Remarquez que `status_code` est un paramètre de la méthode « decorator » (`get`, `post`, etc.). Pas de votre fonction de chemin d'accès, comme tous les paramètres et le corps.
+
+///
+
+Le paramètre `status_code` reçoit un nombre correspondant au code d'état HTTP.
+
+/// info
+
+`status_code` peut aussi recevoir un `IntEnum`, comme le [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus) de Python.
+
+///
+
+Il va :
+
+* Renvoyer ce code d'état dans la réponse.
+* Le documenter comme tel dans le schéma OpenAPI (et donc dans les interfaces utilisateur) :
+
+
+
+/// note | Remarque
+
+Certains codes de réponse (voir la section suivante) indiquent que la réponse n'a pas de corps.
+
+FastAPI le sait et produira une documentation OpenAPI indiquant qu'il n'y a pas de corps de réponse.
+
+///
+
+## À propos des codes d'état HTTP { #about-http-status-codes }
+
+/// note | Remarque
+
+Si vous savez déjà ce que sont les codes d'état HTTP, passez à la section suivante.
+
+///
+
+En HTTP, vous envoyez un code d'état numérique de 3 chiffres dans la réponse.
+
+Ces codes d'état ont un nom associé pour les reconnaître, mais la partie importante est le nombre.
+
+En bref :
+
+* `100 - 199` sont pour « Information ». Vous les utilisez rarement directement. Les réponses avec ces codes d'état ne peuvent pas avoir de corps.
+* **`200 - 299`** sont pour les réponses de « Succès ». Ce sont celles que vous utiliserez le plus.
+ * `200` est le code d'état par défaut, ce qui signifie que tout était « OK ».
+ * Un autre exemple est `201`, « Créé ». Il est couramment utilisé après la création d'un nouvel enregistrement dans la base de données.
+ * Un cas particulier est `204`, « Aucun contenu ». Cette réponse est utilisée lorsqu'il n'y a aucun contenu à renvoyer au client ; la réponse ne doit donc pas avoir de corps.
+* **`300 - 399`** sont pour la « Redirection ». Les réponses avec ces codes d'état peuvent avoir ou non un corps, sauf `304`, « Non modifié », qui ne doit pas en avoir.
+* **`400 - 499`** sont pour les réponses d'« Erreur côté client ». C'est probablement le deuxième type que vous utiliserez le plus.
+ * Un exemple est `404`, pour une réponse « Non trouvé ».
+ * Pour des erreurs génériques du client, vous pouvez simplement utiliser `400`.
+* `500 - 599` sont pour les erreurs côté serveur. Vous ne les utilisez presque jamais directement. Lorsqu'un problème survient quelque part dans le code de votre application ou sur le serveur, il renverra automatiquement l'un de ces codes d'état.
+
+/// tip | Astuce
+
+Pour en savoir plus sur chaque code d'état et à quoi il correspond, consultez la [MDN documentation sur les codes d'état HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status).
+
+///
+
+## Raccourci pour se souvenir des noms { #shortcut-to-remember-the-names }
+
+Reprenons l'exemple précédent :
+
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
+
+`201` est le code d'état pour « Créé ».
+
+Mais vous n'avez pas à mémoriser la signification de chacun de ces codes.
+
+Vous pouvez utiliser les variables pratiques de `fastapi.status`.
+
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
+
+Elles ne sont qu'une commodité, elles contiennent le même nombre, mais de cette façon vous pouvez utiliser l'autocomplétion de l'éditeur pour les trouver :
+
+
+
+/// note | Détails techniques
+
+Vous pourriez aussi utiliser `from starlette import status`.
+
+**FastAPI** fournit le même `starlette.status` que `fastapi.status`, uniquement pour votre commodité de développeur. Mais cela vient directement de Starlette.
+
+///
+
+## Modifier la valeur par défaut { #changing-the-default }
+
+Plus tard, dans le [Guide utilisateur avancé](../advanced/response-change-status-code.md), vous verrez comment renvoyer un code d'état différent de celui par défaut que vous déclarez ici.
diff --git a/docs/fr/docs/tutorial/schema-extra-example.md b/docs/fr/docs/tutorial/schema-extra-example.md
new file mode 100644
index 0000000000000..404edff46d1c8
--- /dev/null
+++ b/docs/fr/docs/tutorial/schema-extra-example.md
@@ -0,0 +1,202 @@
+# Déclarer des exemples de données de requête { #declare-request-example-data }
+
+Vous pouvez déclarer des exemples des données que votre application peut recevoir.
+
+Voici plusieurs façons de le faire.
+
+## Ajouter des données JSON Schema supplémentaires dans les modèles Pydantic { #extra-json-schema-data-in-pydantic-models }
+
+Vous pouvez déclarer `examples` pour un modèle Pydantic qui seront ajoutés au JSON Schema généré.
+
+{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}
+
+Ces informations supplémentaires seront ajoutées telles quelles au **JSON Schema** de sortie pour ce modèle, et elles seront utilisées dans la documentation de l'API.
+
+Vous pouvez utiliser l'attribut `model_config` qui accepte un `dict` comme décrit dans [Documentation de Pydantic : Configuration](https://docs.pydantic.dev/latest/api/config/).
+
+Vous pouvez définir `"json_schema_extra"` avec un `dict` contenant toutes les données supplémentaires que vous souhaitez voir apparaître dans le JSON Schema généré, y compris `examples`.
+
+/// tip | Astuce
+
+Vous pouvez utiliser la même technique pour étendre le JSON Schema et ajouter vos propres informations supplémentaires personnalisées.
+
+Par exemple, vous pourriez l'utiliser pour ajouter des métadonnées pour une interface utilisateur frontend, etc.
+
+///
+
+/// info
+
+OpenAPI 3.1.0 (utilisé depuis FastAPI 0.99.0) a ajouté la prise en charge de `examples`, qui fait partie du standard **JSON Schema**.
+
+Avant cela, seule la clé `example` avec un exemple unique était prise en charge. Elle l'est toujours par OpenAPI 3.1.0, mais elle est dépréciée et ne fait pas partie du standard JSON Schema. Vous êtes donc encouragé à migrer de `example` vers `examples`. 🤓
+
+Vous pouvez en lire davantage à la fin de cette page.
+
+///
+
+## Arguments supplémentaires de `Field` { #field-additional-arguments }
+
+Lorsque vous utilisez `Field()` avec des modèles Pydantic, vous pouvez également déclarer des `examples` supplémentaires :
+
+{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}
+
+## `examples` dans JSON Schema - OpenAPI { #examples-in-json-schema-openapi }
+
+En utilisant l'un des éléments suivants :
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+vous pouvez également déclarer un groupe de `examples` avec des informations supplémentaires qui seront ajoutées à leurs **JSON Schemas** à l'intérieur d'**OpenAPI**.
+
+### `Body` avec `examples` { #body-with-examples }
+
+Ici, nous passons `examples` contenant un exemple des données attendues dans `Body()` :
+
+{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *}
+
+### Exemple dans l'interface des documents { #example-in-the-docs-ui }
+
+Avec l'une des méthodes ci-dessus, cela ressemblerait à ceci dans le `/docs` :
+
+
+
+### `Body` avec plusieurs `examples` { #body-with-multiple-examples }
+
+Vous pouvez bien sûr aussi passer plusieurs `examples` :
+
+{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *}
+
+Lorsque vous faites cela, les exemples feront partie du **JSON Schema** interne pour ces données de corps.
+
+Néanmoins, au moment de la rédaction, Swagger UI, l'outil chargé d'afficher l'interface des documents, ne prend pas en charge l'affichage de plusieurs exemples pour les données dans **JSON Schema**. Mais lisez ci-dessous pour un contournement.
+
+### `examples` spécifiques à OpenAPI { #openapi-specific-examples }
+
+Avant que **JSON Schema** ne prenne en charge `examples`, OpenAPI prenait déjà en charge un autre champ également appelé `examples`.
+
+Ce `examples` **spécifique à OpenAPI** se trouve dans une autre section de la spécification OpenAPI. Il se trouve dans les **détails de chaque *chemin d'accès***, et non à l'intérieur de chaque JSON Schema.
+
+Et Swagger UI prend en charge ce champ particulier `examples` depuis un certain temps. Vous pouvez donc l'utiliser pour **afficher** différents **exemples dans l'interface des documents**.
+
+La forme de ce champ `examples` spécifique à OpenAPI est un `dict` avec **plusieurs exemples** (au lieu d'une `list`), chacun avec des informations supplémentaires qui seront également ajoutées à **OpenAPI**.
+
+Cela ne va pas à l'intérieur de chaque JSON Schema contenu dans OpenAPI, cela se place à l'extérieur, directement dans le *chemin d'accès*.
+
+### Utiliser le paramètre `openapi_examples` { #using-the-openapi-examples-parameter }
+
+Vous pouvez déclarer le `examples` spécifique à OpenAPI dans FastAPI avec le paramètre `openapi_examples` pour :
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+Les clés du `dict` identifient chaque exemple, et chaque valeur est un autre `dict`.
+
+Chaque `dict` d'exemple spécifique dans `examples` peut contenir :
+
+* `summary` : une courte description de l'exemple.
+* `description` : une description longue qui peut contenir du texte Markdown.
+* `value` : c'est l'exemple réel affiché, par ex. un `dict`.
+* `externalValue` : alternative à `value`, une URL pointant vers l'exemple. Cependant, cela pourrait ne pas être pris en charge par autant d'outils que `value`.
+
+Vous pouvez l'utiliser ainsi :
+
+{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *}
+
+### Exemples OpenAPI dans l'interface des documents { #openapi-examples-in-the-docs-ui }
+
+Avec `openapi_examples` ajouté à `Body()`, le `/docs` ressemblerait à :
+
+
+
+## Détails techniques { #technical-details }
+
+/// tip | Astuce
+
+Si vous utilisez déjà **FastAPI** en version **0.99.0 ou supérieure**, vous pouvez probablement **passer** ces détails.
+
+Ils sont plus pertinents pour les versions plus anciennes, avant que OpenAPI 3.1.0 ne soit disponible.
+
+Vous pouvez considérer ceci comme une courte leçon d'histoire d'OpenAPI et de JSON Schema. 🤓
+
+///
+
+/// warning | Alertes
+
+Ce sont des détails très techniques au sujet des standards **JSON Schema** et **OpenAPI**.
+
+Si les idées ci-dessus fonctionnent déjà pour vous, cela pourrait suffire, et vous n'avez probablement pas besoin de ces détails, n'hésitez pas à les ignorer.
+
+///
+
+Avant OpenAPI 3.1.0, OpenAPI utilisait une version plus ancienne et modifiée de **JSON Schema**.
+
+JSON Schema n'avait pas `examples`, donc OpenAPI a ajouté son propre champ `example` à sa version modifiée.
+
+OpenAPI a également ajouté les champs `example` et `examples` à d'autres parties de la spécification :
+
+* [`Parameter Object` (dans la spécification)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object) qui était utilisé par les éléments FastAPI :
+ * `Path()`
+ * `Query()`
+ * `Header()`
+ * `Cookie()`
+* [`Request Body Object`, dans le champ `content`, sur le `Media Type Object` (dans la spécification)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object) qui était utilisé par les éléments FastAPI :
+ * `Body()`
+ * `File()`
+ * `Form()`
+
+/// info
+
+Ce paramètre `examples` ancien et spécifique à OpenAPI est désormais `openapi_examples` depuis FastAPI `0.103.0`.
+
+///
+
+### Le champ `examples` de JSON Schema { #json-schemas-examples-field }
+
+Ensuite, JSON Schema a ajouté un champ [`examples`](https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.9.5) dans une nouvelle version de la spécification.
+
+Puis le nouveau OpenAPI 3.1.0 s'est basé sur la dernière version (JSON Schema 2020-12) qui incluait ce nouveau champ `examples`.
+
+Et désormais, ce nouveau champ `examples` a priorité sur l'ancien champ unique (et personnalisé) `example`, qui est maintenant déprécié.
+
+Ce nouveau champ `examples` dans JSON Schema est **juste une `list`** d'exemples, et non pas un dict avec des métadonnées supplémentaires comme dans les autres endroits d'OpenAPI (décrits ci-dessus).
+
+/// info
+
+Même après la sortie d'OpenAPI 3.1.0 avec cette nouvelle intégration plus simple avec JSON Schema, pendant un temps, Swagger UI, l'outil qui fournit la documentation automatique, ne prenait pas en charge OpenAPI 3.1.0 (il le fait depuis la version 5.0.0 🎉).
+
+À cause de cela, les versions de FastAPI antérieures à 0.99.0 utilisaient encore des versions d'OpenAPI inférieures à 3.1.0.
+
+///
+
+### `examples` avec Pydantic et FastAPI { #pydantic-and-fastapi-examples }
+
+Lorsque vous ajoutez `examples` dans un modèle Pydantic, en utilisant `schema_extra` ou `Field(examples=["something"])`, cet exemple est ajouté au **JSON Schema** de ce modèle Pydantic.
+
+Et ce **JSON Schema** du modèle Pydantic est inclus dans l'**OpenAPI** de votre API, puis il est utilisé dans l'interface de la documentation.
+
+Dans les versions de FastAPI antérieures à 0.99.0 (0.99.0 et supérieures utilisent le nouveau OpenAPI 3.1.0), lorsque vous utilisiez `example` ou `examples` avec l'une des autres utilitaires (`Query()`, `Body()`, etc.), ces exemples n'étaient pas ajoutés au JSON Schema qui décrit ces données (pas même à la version de JSON Schema propre à OpenAPI), ils étaient ajoutés directement à la déclaration du *chemin d'accès* dans OpenAPI (en dehors des parties d'OpenAPI qui utilisent JSON Schema).
+
+Mais maintenant que FastAPI 0.99.0 et supérieures utilisent OpenAPI 3.1.0, qui utilise JSON Schema 2020-12, et Swagger UI 5.0.0 et supérieures, tout est plus cohérent et les exemples sont inclus dans JSON Schema.
+
+### Swagger UI et `examples` spécifiques à OpenAPI { #swagger-ui-and-openapi-specific-examples }
+
+Comme Swagger UI ne prenait pas en charge plusieurs exemples JSON Schema (au 2023-08-26), les utilisateurs n'avaient pas de moyen d'afficher plusieurs exemples dans les documents.
+
+Pour résoudre cela, FastAPI `0.103.0` a **ajouté la prise en charge** de la déclaration du même ancien champ `examples` **spécifique à OpenAPI** avec le nouveau paramètre `openapi_examples`. 🤓
+
+### Résumé { #summary }
+
+Je disais que je n'aimais pas trop l'histoire ... et me voilà maintenant à donner des leçons d'« tech history ». 😅
+
+En bref, **mettez à niveau vers FastAPI 0.99.0 ou supérieur**, et les choses sont bien plus **simples, cohérentes et intuitives**, et vous n'avez pas besoin de connaître tous ces détails historiques. 😎
diff --git a/docs/fr/docs/tutorial/security/first-steps.md b/docs/fr/docs/tutorial/security/first-steps.md
new file mode 100644
index 0000000000000..c1d36d501c96f
--- /dev/null
+++ b/docs/fr/docs/tutorial/security/first-steps.md
@@ -0,0 +1,203 @@
+# Sécurité - Premiers pas { #security-first-steps }
+
+Imaginons que vous ayez votre API de **backend** sur un certain domaine.
+
+Et vous avez un **frontend** sur un autre domaine ou dans un chemin différent du même domaine (ou dans une application mobile).
+
+Et vous voulez que le **frontend** puisse s'authentifier auprès du **backend**, en utilisant un **username** et un **password**.
+
+Nous pouvons utiliser **OAuth2** pour construire cela avec **FastAPI**.
+
+Mais épargnons-vous le temps de lire toute la spécification complète juste pour trouver les petites informations dont vous avez besoin.
+
+Utilisons les outils fournis par **FastAPI** pour gérer la sécurité.
+
+## Voir à quoi cela ressemble { #how-it-looks }
+
+Commençons par utiliser le code et voir comment cela fonctionne, puis nous reviendrons pour comprendre ce qui se passe.
+
+## Créer `main.py` { #create-main-py }
+
+Copiez l'exemple dans un fichier `main.py` :
+
+{* ../../docs_src/security/tutorial001_an_py310.py *}
+
+## Exécuter { #run-it }
+
+/// info
+
+Le package [`python-multipart`](https://github.com/Kludex/python-multipart) est installé automatiquement avec **FastAPI** lorsque vous exécutez la commande `pip install "fastapi[standard]"`.
+
+Cependant, si vous utilisez la commande `pip install fastapi`, le package `python-multipart` n'est pas inclus par défaut.
+
+Pour l'installer manuellement, vous devez vous assurer de créer un [environnement virtuel](../../virtual-environments.md), de l'activer, puis de l'installer avec :
+
+```console
+$ pip install python-multipart
+```
+
+Cela est dû au fait que **OAuth2** utilise des « form data » pour envoyer le `username` et le `password`.
+
+///
+
+Exécutez l'exemple avec :
+
+
+
+/// check | Bouton « Authorize » !
+
+Vous avez déjà un tout nouveau bouton « Authorize ».
+
+Et votre *chemin d'accès* a un petit cadenas dans le coin supérieur droit sur lequel vous pouvez cliquer.
+
+///
+
+Et si vous cliquez dessus, vous obtenez un petit formulaire d'autorisation pour saisir un `username` et un `password` (et d'autres champs optionnels) :
+
+
+
+/// note | Remarque
+
+Peu importe ce que vous saisissez dans le formulaire, cela ne fonctionnera pas encore. Mais nous y viendrons.
+
+///
+
+Ce n'est bien sûr pas le frontend pour les utilisateurs finaux, mais c'est un excellent outil automatique pour documenter de manière interactive toute votre API.
+
+Il peut être utilisé par l'équipe frontend (qui peut aussi être vous-même).
+
+Il peut être utilisé par des applications et des systèmes tiers.
+
+Et il peut aussi être utilisé par vous-même, pour déboguer, vérifier et tester la même application.
+
+## Le flux `password` { #the-password-flow }
+
+Revenons un peu en arrière et comprenons de quoi il s'agit.
+
+Le « flux » `password` est l'une des manières (« flows ») définies dans OAuth2 pour gérer la sécurité et l'authentification.
+
+OAuth2 a été conçu pour que le backend ou l'API puisse être indépendant du serveur qui authentifie l'utilisateur.
+
+Mais dans ce cas, la même application **FastAPI** gérera l'API et l'authentification.
+
+Voyons cela selon ce point de vue simplifié :
+
+- L'utilisateur saisit le `username` et le `password` dans le frontend, puis appuie sur Entrée.
+- Le frontend (exécuté dans le navigateur de l'utilisateur) envoie ce `username` et ce `password` vers une URL spécifique de notre API (déclarée avec `tokenUrl="token"`).
+- L'API vérifie ce `username` et ce `password`, et répond avec un « token » (nous n'avons encore rien implémenté de tout cela).
+ - Un « token » n'est qu'une chaîne contenant des informations que nous pouvons utiliser plus tard pour vérifier cet utilisateur.
+ - Normalement, un token est configuré pour expirer après un certain temps.
+ - Ainsi, l'utilisateur devra se reconnecter à un moment donné.
+ - Et si le token est volé, le risque est moindre. Ce n'est pas une clé permanente qui fonctionnerait indéfiniment (dans la plupart des cas).
+- Le frontend stocke ce token temporairement quelque part.
+- L'utilisateur clique dans le frontend pour aller vers une autre section de l'application web frontend.
+- Le frontend doit récupérer d'autres données depuis l'API.
+ - Mais cela nécessite une authentification pour cet endpoint spécifique.
+ - Donc, pour s'authentifier auprès de notre API, il envoie un en-tête `Authorization` avec une valeur `Bearer ` suivie du token.
+ - Si le token contient `foobar`, le contenu de l'en-tête `Authorization` serait : `Bearer foobar`.
+
+## Le `OAuth2PasswordBearer` de **FastAPI** { #fastapis-oauth2passwordbearer }
+
+**FastAPI** fournit plusieurs outils, à différents niveaux d'abstraction, pour implémenter ces fonctionnalités de sécurité.
+
+Dans cet exemple, nous allons utiliser **OAuth2**, avec le flux **Password**, en utilisant un token **Bearer**. Nous le faisons avec la classe `OAuth2PasswordBearer`.
+
+/// info
+
+Un token « bearer » n'est pas la seule option.
+
+Mais c'est la meilleure pour notre cas d'utilisation.
+
+Et cela pourrait être la meilleure pour la plupart des cas, sauf si vous êtes expert en OAuth2 et savez exactement pourquoi une autre option convient mieux à vos besoins.
+
+Dans ce cas, **FastAPI** vous fournit aussi les outils pour la construire.
+
+///
+
+Lorsque nous créons une instance de la classe `OAuth2PasswordBearer`, nous passons le paramètre `tokenUrl`. Ce paramètre contient l'URL que le client (le frontend s'exécutant dans le navigateur de l'utilisateur) utilisera pour envoyer le `username` et le `password` afin d'obtenir un token.
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
+
+/// tip | Astuce
+
+Ici `tokenUrl="token"` fait référence à une URL relative `token` que nous n'avons pas encore créée. Comme c'est une URL relative, elle est équivalente à `./token`.
+
+Parce que nous utilisons une URL relative, si votre API se trouvait à `https://example.com/`, alors elle ferait référence à `https://example.com/token`. Mais si votre API se trouvait à `https://example.com/api/v1/`, alors elle ferait référence à `https://example.com/api/v1/token`.
+
+Utiliser une URL relative est important pour vous assurer que votre application continue de fonctionner même dans un cas d'usage avancé comme [Derrière un proxy](../../advanced/behind-a-proxy.md).
+
+///
+
+Ce paramètre ne crée pas cet endpoint / *chemin d'accès*, mais déclare que l'URL `/token` sera celle que le client doit utiliser pour obtenir le token. Cette information est utilisée dans OpenAPI, puis dans les systèmes de documentation API interactifs.
+
+Nous créerons bientôt aussi le véritable chemin d'accès.
+
+/// info
+
+Si vous êtes un « Pythonista » très strict, vous pourriez ne pas apprécier le style du nom de paramètre `tokenUrl` au lieu de `token_url`.
+
+C'est parce qu'il utilise le même nom que dans la spécification OpenAPI. Ainsi, si vous devez approfondir l'un de ces schémas de sécurité, vous pouvez simplement copier-coller pour trouver plus d'informations à ce sujet.
+
+///
+
+La variable `oauth2_scheme` est une instance de `OAuth2PasswordBearer`, mais c'est aussi un « callable ».
+
+Elle pourrait être appelée ainsi :
+
+```Python
+oauth2_scheme(some, parameters)
+```
+
+Ainsi, elle peut être utilisée avec `Depends`.
+
+### Utiliser { #use-it }
+
+Vous pouvez maintenant passer ce `oauth2_scheme` en dépendance avec `Depends`.
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+Cette dépendance fournira une `str` qui est affectée au paramètre `token` de la fonction de *chemin d'accès*.
+
+**FastAPI** saura qu'il peut utiliser cette dépendance pour définir un « schéma de sécurité » dans le schéma OpenAPI (et la documentation API automatique).
+
+/// info | Détails techniques
+
+**FastAPI** saura qu'il peut utiliser la classe `OAuth2PasswordBearer` (déclarée dans une dépendance) pour définir le schéma de sécurité dans OpenAPI parce qu'elle hérite de `fastapi.security.oauth2.OAuth2`, qui hérite à son tour de `fastapi.security.base.SecurityBase`.
+
+Tous les utilitaires de sécurité qui s'intègrent à OpenAPI (et à la documentation API automatique) héritent de `SecurityBase`, c'est ainsi que **FastAPI** sait comment les intégrer dans OpenAPI.
+
+///
+
+## Ce que cela fait { #what-it-does }
+
+Il va chercher dans la requête cet en-tête `Authorization`, vérifier si la valeur est `Bearer ` plus un token, et renverra le token en tant que `str`.
+
+S'il ne voit pas d'en-tête `Authorization`, ou si la valeur n'a pas de token `Bearer `, il répondra directement avec une erreur de code d'état 401 (`UNAUTHORIZED`).
+
+Vous n'avez même pas à vérifier si le token existe pour renvoyer une erreur. Vous pouvez être sûr que si votre fonction est exécutée, elle aura une `str` dans ce token.
+
+Vous pouvez déjà l'essayer dans la documentation interactive :
+
+
+
+Nous ne vérifions pas encore la validité du token, mais c'est déjà un début.
+
+## Récapitulatif { #recap }
+
+Ainsi, en seulement 3 ou 4 lignes supplémentaires, vous disposez déjà d'une forme primitive de sécurité.
diff --git a/docs/fr/docs/tutorial/security/get-current-user.md b/docs/fr/docs/tutorial/security/get-current-user.md
new file mode 100644
index 0000000000000..5f73efea9cc80
--- /dev/null
+++ b/docs/fr/docs/tutorial/security/get-current-user.md
@@ -0,0 +1,105 @@
+# Obtenir l'utilisateur actuel { #get-current-user }
+
+Dans le chapitre précédent, le système de sécurité (basé sur le système d'injection de dépendances) fournissait à la *fonction de chemin d'accès* un `token` en tant que `str` :
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+Mais ce n'est pas encore très utile.
+
+Faisons en sorte qu'il nous fournisse l'utilisateur actuel.
+
+## Créer un modèle d'utilisateur { #create-a-user-model }
+
+Commençons par créer un modèle d'utilisateur Pydantic.
+
+De la même manière que nous utilisons Pydantic pour déclarer des corps de requête, nous pouvons l'utiliser ailleurs :
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *}
+
+## Créer une dépendance `get_current_user` { #create-a-get-current-user-dependency }
+
+Créons une dépendance `get_current_user`.
+
+Rappelez-vous que les dépendances peuvent avoir des sous-dépendances ?
+
+`get_current_user` aura une dépendance avec le même `oauth2_scheme` que nous avons créé précédemment.
+
+Comme nous le faisions auparavant directement dans le *chemin d'accès*, notre nouvelle dépendance `get_current_user` recevra un `token` en tant que `str` de la sous-dépendance `oauth2_scheme` :
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *}
+
+## Récupérer l'utilisateur { #get-the-user }
+
+`get_current_user` utilisera une fonction utilitaire (factice) que nous avons créée, qui prend un token en `str` et retourne notre modèle Pydantic `User` :
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *}
+
+## Injecter l'utilisateur actuel { #inject-the-current-user }
+
+Nous pouvons donc utiliser le même `Depends` avec notre `get_current_user` dans le *chemin d'accès* :
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *}
+
+Remarquez que nous déclarons le type de `current_user` comme le modèle Pydantic `User`.
+
+Cela nous aidera dans la fonction avec toute l'autocomplétion et les vérifications de type.
+
+/// tip | Astuce
+
+Vous vous souvenez peut-être que les corps de requête sont également déclarés avec des modèles Pydantic.
+
+Ici, **FastAPI** ne s'y trompera pas car vous utilisez `Depends`.
+
+///
+
+/// check | Vérifications
+
+La manière dont ce système de dépendances est conçu nous permet d'avoir différentes dépendances (différents « dependables ») qui retournent toutes un modèle `User`.
+
+Nous ne sommes pas limités à une seule dépendance pouvant retourner ce type de données.
+
+///
+
+## Autres modèles { #other-models }
+
+Vous pouvez maintenant obtenir l'utilisateur actuel directement dans les *fonctions de chemin d'accès* et gérer les mécanismes de sécurité au niveau de l'**Injection de dépendances**, en utilisant `Depends`.
+
+Et vous pouvez utiliser n'importe quel modèle ou données pour les exigences de sécurité (dans ce cas, un modèle Pydantic `User`).
+
+Mais vous n'êtes pas limité à un modèle, une classe ou un type de données spécifique.
+
+Voulez-vous avoir un `id` et `email` et ne pas avoir de `username` dans votre modèle ? Bien sûr. Vous pouvez utiliser ces mêmes outils.
+
+Voulez-vous simplement avoir un `str` ? Ou juste un `dict` ? Ou directement une instance d'un modèle de classe de base de données ? Tout fonctionne de la même manière.
+
+Vous n'avez en fait pas d'utilisateurs qui se connectent à votre application, mais des robots, bots ou d'autres systèmes, qui n'ont qu'un jeton d'accès ? Là encore, tout fonctionne de la même façon.
+
+Utilisez simplement tout type de modèle, toute sorte de classe, tout type de base de données dont vous avez besoin pour votre application. **FastAPI** vous couvre avec le système d'injection de dépendances.
+
+## Taille du code { #code-size }
+
+Cet exemple peut sembler verbeux. Gardez à l'esprit que nous mélangeons sécurité, modèles de données, fonctions utilitaires et *chemins d'accès* dans le même fichier.
+
+Mais voici le point clé.
+
+La partie sécurité et injection de dépendances est écrite une seule fois.
+
+Et vous pouvez la rendre aussi complexe que vous le souhaitez. Et malgré tout, ne l'écrire qu'une seule fois, en un seul endroit. Avec toute la flexibilité.
+
+Mais vous pouvez avoir des milliers d'endpoints (*chemins d'accès*) utilisant le même système de sécurité.
+
+Et tous (ou seulement une partie d'entre eux, si vous le souhaitez) peuvent profiter de la réutilisation de ces dépendances ou de toute autre dépendance que vous créez.
+
+Et tous ces milliers de *chemins d'accès* peuvent tenir en seulement 3 lignes :
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *}
+
+## Récapitulatif { #recap }
+
+Vous pouvez désormais obtenir l'utilisateur actuel directement dans votre *fonction de chemin d'accès*.
+
+Nous avons déjà fait la moitié du chemin.
+
+Il nous suffit d'ajouter un *chemin d'accès* pour que l'utilisateur/client envoie effectivement le `username` et le `password`.
+
+C'est pour la suite.
diff --git a/docs/fr/docs/tutorial/security/index.md b/docs/fr/docs/tutorial/security/index.md
new file mode 100644
index 0000000000000..6de75aed61c65
--- /dev/null
+++ b/docs/fr/docs/tutorial/security/index.md
@@ -0,0 +1,106 @@
+# Sécurité { #security }
+
+Il existe de nombreuses façons de gérer la sécurité, l'authentification et l'autorisation.
+
+Et c'est normalement un sujet complexe et « difficile ».
+
+Dans de nombreux frameworks et systèmes, le simple fait de gérer la sécurité et l'authentification demande beaucoup d'efforts et de code (dans de nombreux cas, cela peut représenter 50 % ou plus de tout le code écrit).
+
+**FastAPI** fournit plusieurs outils pour vous aider à gérer la **Sécurité** facilement, rapidement, de manière standard, sans avoir à étudier et apprendre toutes les spécifications de sécurité.
+
+Mais d'abord, voyons quelques notions.
+
+## Pressé ? { #in-a-hurry }
+
+Si ces termes ne vous intéressent pas et que vous avez simplement besoin d'ajouter une sécurité avec une authentification basée sur un nom d'utilisateur et un mot de passe immédiatement, passez aux chapitres suivants.
+
+## OAuth2 { #oauth2 }
+
+OAuth2 est une spécification qui définit plusieurs façons de gérer l'authentification et l'autorisation.
+
+C'est une spécification assez vaste qui couvre plusieurs cas d'utilisation complexes.
+
+Elle inclut des moyens de s'authentifier en utilisant un « tiers ».
+
+C'est ce que tous les systèmes avec « connexion avec Facebook, Google, X (Twitter), GitHub » utilisent en arrière-plan.
+
+### OAuth 1 { #oauth-1 }
+
+Il y a eu un OAuth 1, très différent d'OAuth2, et plus complexe, car il incluait des spécifications directes sur la manière de chiffrer la communication.
+
+Il n'est plus très populaire ni utilisé de nos jours.
+
+OAuth2 ne spécifie pas comment chiffrer la communication ; il suppose que votre application est servie en HTTPS.
+
+/// tip | Astuce
+
+Dans la section sur le déploiement, vous verrez comment configurer HTTPS gratuitement, en utilisant Traefik et Let's Encrypt.
+
+///
+
+## OpenID Connect { #openid-connect }
+
+OpenID Connect est une autre spécification, basée sur **OAuth2**.
+
+Elle étend simplement OAuth2 en précisant certains points relativement ambigus dans OAuth2, afin d'essayer de la rendre plus interopérable.
+
+Par exemple, la connexion Google utilise OpenID Connect (qui, en arrière-plan, utilise OAuth2).
+
+Mais la connexion Facebook ne prend pas en charge OpenID Connect. Elle a sa propre variante d'OAuth2.
+
+### OpenID (pas « OpenID Connect ») { #openid-not-openid-connect }
+
+Il y avait aussi une spécification « OpenID ». Elle essayait de résoudre la même chose qu'**OpenID Connect**, mais n'était pas basée sur OAuth2.
+
+C'était donc un système totalement distinct.
+
+Il n'est plus très populaire ni utilisé de nos jours.
+
+## OpenAPI { #openapi }
+
+OpenAPI (précédemment connu sous le nom de Swagger) est la spécification ouverte pour construire des API (désormais partie de la Linux Foundation).
+
+**FastAPI** est basé sur **OpenAPI**.
+
+C'est ce qui rend possibles plusieurs interfaces de documentation interactive automatiques, la génération de code, etc.
+
+OpenAPI propose une manière de définir plusieurs « schémas » de sécurité.
+
+En les utilisant, vous pouvez tirer parti de tous ces outils basés sur des standards, y compris ces systèmes de documentation interactive.
+
+OpenAPI définit les schémas de sécurité suivants :
+
+* `apiKey` : une clé spécifique à l'application qui peut provenir :
+ * D'un paramètre de requête.
+ * D'un en-tête.
+ * D'un cookie.
+* `http` : des systèmes d'authentification HTTP standards, notamment :
+ * `bearer` : un en-tête `Authorization` avec une valeur `Bearer ` plus un jeton. Hérité d'OAuth2.
+ * Authentification HTTP Basic.
+ * HTTP Digest, etc.
+* `oauth2` : toutes les méthodes OAuth2 pour gérer la sécurité (appelées « flows »).
+ * Plusieurs de ces flows conviennent pour construire un fournisseur d'authentification OAuth 2.0 (comme Google, Facebook, X (Twitter), GitHub, etc.) :
+ * `implicit`
+ * `clientCredentials`
+ * `authorizationCode`
+ * Mais il existe un « flow » spécifique qui peut parfaitement être utilisé pour gérer l'authentification directement dans la même application :
+ * `password` : certains des prochains chapitres couvriront des exemples à ce sujet.
+* `openIdConnect` : propose un moyen de définir comment découvrir automatiquement les données d'authentification OAuth2.
+ * Cette découverte automatique est ce qui est défini dans la spécification OpenID Connect.
+
+
+/// tip | Astuce
+
+Intégrer d'autres fournisseurs d'authentification/autorisation comme Google, Facebook, X (Twitter), GitHub, etc. est également possible et relativement facile.
+
+Le problème le plus complexe est de construire un fournisseur d'authentification/autorisation comme ceux-là, mais **FastAPI** vous donne les outils pour le faire facilement, tout en effectuant le gros du travail pour vous.
+
+///
+
+## Outils **FastAPI** { #fastapi-utilities }
+
+FastAPI propose plusieurs outils pour chacun de ces schémas de sécurité dans le module fastapi.security qui simplifient l'utilisation de ces mécanismes de sécurité.
+
+Dans les prochains chapitres, vous verrez comment ajouter de la sécurité à votre API en utilisant ces outils fournis par **FastAPI**.
+
+Et vous verrez aussi comment cela s'intègre automatiquement au système de documentation interactive.
diff --git a/docs/fr/docs/tutorial/security/oauth2-jwt.md b/docs/fr/docs/tutorial/security/oauth2-jwt.md
new file mode 100644
index 0000000000000..eec5ab13c0b57
--- /dev/null
+++ b/docs/fr/docs/tutorial/security/oauth2-jwt.md
@@ -0,0 +1,277 @@
+# OAuth2 avec mot de passe (et hachage), Bearer avec des jetons JWT { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
+
+Maintenant que nous avons tout le flux de sécurité, rendons réellement l'application sécurisée, en utilisant des jetons JWT et un hachage de mot de passe sécurisé.
+
+Ce code est utilisable dans votre application, enregistrez les hachages de mots de passe dans votre base de données, etc.
+
+Nous allons repartir d'où nous nous sommes arrêtés dans le chapitre précédent et l'enrichir.
+
+## À propos de JWT { #about-jwt }
+
+JWT signifie « JSON Web Tokens ».
+
+C'est une norme pour coder un objet JSON dans une longue chaîne compacte sans espaces. Cela ressemble à ceci :
+
+```
+eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
+```
+
+Il n'est pas chiffré ; ainsi, n'importe qui peut récupérer les informations à partir de son contenu.
+
+Mais il est signé. Ainsi, quand vous recevez un jeton que vous avez émis, vous pouvez vérifier que vous l'avez bien émis.
+
+De cette façon, vous pouvez créer un jeton avec une expiration d'une semaine, par exemple. Et quand l'utilisateur revient le lendemain avec ce jeton, vous savez qu'il est toujours connecté à votre système.
+
+Après une semaine, le jeton aura expiré et l'utilisateur ne sera pas autorisé et devra se reconnecter pour obtenir un nouveau jeton. Et si l'utilisateur (ou un tiers) essayait de modifier le jeton pour changer l'expiration, vous pourriez le détecter, car les signatures ne correspondraient pas.
+
+Si vous voulez expérimenter avec des jetons JWT et voir comment ils fonctionnent, consultez [https://jwt.io](https://jwt.io/).
+
+## Installer `PyJWT` { #install-pyjwt }
+
+Nous devons installer `PyJWT` pour générer et vérifier les jetons JWT en Python.
+
+Assurez-vous de créer un [environnement virtuel](../../virtual-environments.md), de l'activer, puis d'installer `pyjwt` :
+
+
+
+Autorisez l'application de la même manière qu'auparavant.
+
+En utilisant les identifiants :
+
+Nom d'utilisateur : `johndoe`
+Mot de passe : `secret`
+
+/// check | Vérifications
+
+Remarquez qu'à aucun endroit du code le mot de passe en clair « secret » n'apparaît, nous n'avons que la version hachée.
+
+///
+
+
+
+Appelez le point de terminaison `/users/me/`, vous obtiendrez la réponse suivante :
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false
+}
+```
+
+
+
+Si vous ouvrez les outils de développement, vous pouvez voir que les données envoyées n'incluent que le jeton ; le mot de passe n'est envoyé que dans la première requête pour authentifier l'utilisateur et obtenir ce jeton d'accès, mais plus ensuite :
+
+
+
+/// note | Remarque
+
+Remarquez l'en-tête `Authorization`, avec une valeur qui commence par `Bearer `.
+
+///
+
+## Utilisation avancée avec `scopes` { #advanced-usage-with-scopes }
+
+OAuth2 comporte la notion de « scopes ».
+
+Vous pouvez les utiliser pour ajouter un ensemble spécifique d'autorisations à un jeton JWT.
+
+Vous pouvez ensuite donner ce jeton directement à un utilisateur ou à un tiers, pour interagir avec votre API avec un ensemble de restrictions.
+
+Vous pouvez apprendre à les utiliser et comment ils sont intégrés à **FastAPI** plus tard dans le **Guide de l'utilisateur avancé**.
+
+## Récapitulatif { #recap }
+
+Avec ce que vous avez vu jusqu'à présent, vous pouvez configurer une application **FastAPI** sécurisée en utilisant des standards comme OAuth2 et JWT.
+
+Dans presque n'importe quel framework, la gestion de la sécurité devient assez rapidement un sujet plutôt complexe.
+
+De nombreux packages qui la simplifient beaucoup doivent faire de nombreux compromis avec le modèle de données, la base de données et les fonctionnalités disponibles. Et certains de ces packages qui simplifient trop les choses comportent en fait des failles de sécurité sous-jacentes.
+
+---
+
+**FastAPI** ne fait aucun compromis avec une base de données, un modèle de données ni un outil.
+
+Il vous donne toute la flexibilité pour choisir ceux qui conviennent le mieux à votre projet.
+
+Et vous pouvez utiliser directement de nombreux packages bien maintenus et largement utilisés comme `pwdlib` et `PyJWT`, car **FastAPI** n'exige aucun mécanisme complexe pour intégrer des packages externes.
+
+Mais il vous fournit les outils pour simplifier le processus autant que possible sans compromettre la flexibilité, la robustesse ou la sécurité.
+
+Et vous pouvez utiliser et implémenter des protocoles sécurisés et standard, comme OAuth2, de manière relativement simple.
+
+Vous pouvez en apprendre davantage dans le **Guide de l'utilisateur avancé** sur la façon d'utiliser les « scopes » OAuth2, pour un système d'autorisations plus fin, en suivant ces mêmes standards. OAuth2 avec scopes est le mécanisme utilisé par de nombreux grands fournisseurs d'authentification, comme Facebook, Google, GitHub, Microsoft, X (Twitter), etc., pour autoriser des applications tierces à interagir avec leurs API au nom de leurs utilisateurs.
diff --git a/docs/fr/docs/tutorial/security/simple-oauth2.md b/docs/fr/docs/tutorial/security/simple-oauth2.md
new file mode 100644
index 0000000000000..f47d94aa206b5
--- /dev/null
+++ b/docs/fr/docs/tutorial/security/simple-oauth2.md
@@ -0,0 +1,289 @@
+# OAuth2 simple avec Password et Bearer { #simple-oauth2-with-password-and-bearer }
+
+Construisons maintenant à partir du chapitre précédent et ajoutons les éléments manquants pour avoir un flux de sécurité complet.
+
+## Obtenir `username` et `password` { #get-the-username-and-password }
+
+Nous allons utiliser les utilités de sécurité de **FastAPI** pour obtenir `username` et `password`.
+
+OAuth2 spécifie que lorsqu'on utilise le « password flow » (ce que nous utilisons), le client/utilisateur doit envoyer des champs `username` et `password` en tant que données de formulaire.
+
+Et la spécification indique que les champs doivent porter exactement ces noms. Ainsi, `user-name` ou `email` ne fonctionneraient pas.
+
+Mais ne vous inquiétez pas, vous pouvez l'afficher comme vous le souhaitez à vos utilisateurs finaux dans le frontend.
+
+Et vos modèles de base de données peuvent utiliser les noms que vous voulez.
+
+Mais pour le chemin d'accès de connexion, nous devons utiliser ces noms pour être compatibles avec la spécification (et pouvoir, par exemple, utiliser le système de documentation API intégré).
+
+La spécification précise également que `username` et `password` doivent être envoyés en données de formulaire (donc pas de JSON ici).
+
+### `scope` { #scope }
+
+La spécification indique aussi que le client peut envoyer un autre champ de formulaire « scope ».
+
+Le nom du champ de formulaire est `scope` (au singulier), mais il s'agit en fait d'une longue chaîne contenant des « scopes » séparés par des espaces.
+
+Chaque « scope » n'est qu'une chaîne (sans espaces).
+
+Ils sont normalement utilisés pour déclarer des permissions de sécurité spécifiques, par exemple :
+
+* `users:read` ou `users:write` sont des exemples courants.
+* `instagram_basic` est utilisé par Facebook / Instagram.
+* `https://www.googleapis.com/auth/drive` est utilisé par Google.
+
+/// info
+
+En OAuth2, un « scope » est simplement une chaîne qui déclare une permission spécifique requise.
+
+Peu importe s'il contient d'autres caractères comme `:` ou si c'est une URL.
+
+Ces détails dépendent de l'implémentation.
+
+Pour OAuth2, ce ne sont que des chaînes.
+
+///
+
+## Écrire le code pour obtenir `username` et `password` { #code-to-get-the-username-and-password }
+
+Utilisons maintenant les utilités fournies par **FastAPI** pour gérer cela.
+
+### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform }
+
+Tout d'abord, importez `OAuth2PasswordRequestForm`, et utilisez-la en tant que dépendance avec `Depends` dans le chemin d'accès pour `/token` :
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}
+
+`OAuth2PasswordRequestForm` est une dépendance de classe qui déclare un corps de formulaire avec :
+
+* Le `username`.
+* Le `password`.
+* Un champ optionnel `scope` sous forme d'une grande chaîne, composée de chaînes séparées par des espaces.
+* Un `grant_type` optionnel.
+
+/// tip | Astuce
+
+La spécification OAuth2 exige en réalité un champ `grant_type` avec la valeur fixe `password`, mais `OAuth2PasswordRequestForm` ne l'impose pas.
+
+Si vous avez besoin de l'imposer, utilisez `OAuth2PasswordRequestFormStrict` au lieu de `OAuth2PasswordRequestForm`.
+
+///
+
+* Un `client_id` optionnel (nous n'en avons pas besoin pour notre exemple).
+* Un `client_secret` optionnel (nous n'en avons pas besoin pour notre exemple).
+
+/// info
+
+La classe `OAuth2PasswordRequestForm` n'est pas une classe spéciale pour **FastAPI** comme l'est `OAuth2PasswordBearer`.
+
+`OAuth2PasswordBearer` indique à **FastAPI** qu'il s'agit d'un schéma de sécurité. Il est donc ajouté de cette façon à OpenAPI.
+
+Mais `OAuth2PasswordRequestForm` est simplement une dépendance de classe que vous auriez pu écrire vous‑même, ou vous auriez pu déclarer des paramètres `Form` directement.
+
+Mais comme c'est un cas d'usage courant, elle est fournie directement par **FastAPI**, simplement pour vous faciliter la vie.
+
+///
+
+### Utiliser les données du formulaire { #use-the-form-data }
+
+/// tip | Astuce
+
+L'instance de la classe de dépendance `OAuth2PasswordRequestForm` n'aura pas d'attribut `scope` contenant la longue chaîne séparée par des espaces ; elle aura plutôt un attribut `scopes` avec la liste réelle des chaînes pour chaque scope envoyé.
+
+Nous n'utilisons pas `scopes` dans cet exemple, mais la fonctionnalité est disponible si vous en avez besoin.
+
+///
+
+Récupérez maintenant les données utilisateur depuis la (fausse) base de données, en utilisant le `username` du champ de formulaire.
+
+S'il n'existe pas d'utilisateur, nous renvoyons une erreur indiquant « Incorrect username or password ».
+
+Pour l'erreur, nous utilisons l'exception `HTTPException` :
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}
+
+### Vérifier le mot de passe { #check-the-password }
+
+À ce stade, nous avons les données utilisateur depuis notre base, mais nous n'avons pas encore vérifié le mot de passe.
+
+Mettons d'abord ces données dans le modèle Pydantic `UserInDB`.
+
+Vous ne devez jamais enregistrer des mots de passe en clair ; nous allons donc utiliser le système (factice) de hachage de mot de passe.
+
+Si les mots de passe ne correspondent pas, nous renvoyons la même erreur.
+
+#### Hachage de mot de passe { #password-hashing }
+
+Le « hachage » signifie : convertir un contenu (un mot de passe, dans ce cas) en une séquence d'octets (juste une chaîne) qui ressemble à du charabia.
+
+Chaque fois que vous fournissez exactement le même contenu (exactement le même mot de passe), vous obtenez exactement le même charabia.
+
+Mais vous ne pouvez pas convertir ce charabia pour retrouver le mot de passe.
+
+##### Pourquoi utiliser le hachage de mot de passe { #why-use-password-hashing }
+
+Si votre base de données est volée, le voleur n'aura pas les mots de passe en clair de vos utilisateurs, seulement les hachages.
+
+Ainsi, il ne pourra pas essayer d'utiliser ces mêmes mots de passe dans un autre système (comme beaucoup d'utilisateurs utilisent le même mot de passe partout, ce serait dangereux).
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}
+
+#### À propos de `**user_dict` { #about-user-dict }
+
+`UserInDB(**user_dict)` signifie :
+
+Passez les clés et valeurs de `user_dict` directement comme arguments clé‑valeur, équivalent à :
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ disabled = user_dict["disabled"],
+ hashed_password = user_dict["hashed_password"],
+)
+```
+
+/// info
+
+Pour une explication plus complète de `**user_dict`, consultez [la documentation pour **Modèles supplémentaires**](../extra-models.md#about-user-in-dict).
+
+///
+
+## Renvoyer le jeton { #return-the-token }
+
+La réponse de l'endpoint `token` doit être un objet JSON.
+
+Il doit contenir un `token_type`. Dans notre cas, comme nous utilisons des jetons « Bearer », le type de jeton doit être « bearer ».
+
+Et il doit contenir un `access_token`, avec une chaîne contenant notre jeton d'accès.
+
+Pour cet exemple simple, nous allons faire quelque chose de complètement non sécurisé et renvoyer le même `username` comme jeton.
+
+/// tip | Astuce
+
+Dans le prochain chapitre, vous verrez une véritable implémentation sécurisée, avec du hachage de mot de passe et des jetons JWT.
+
+Mais pour l'instant, concentrons‑nous sur les détails spécifiques dont nous avons besoin.
+
+///
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}
+
+/// tip | Astuce
+
+D'après la spécification, vous devez renvoyer un JSON avec un `access_token` et un `token_type`, comme dans cet exemple.
+
+C'est quelque chose que vous devez faire vous‑même dans votre code, et vous devez vous assurer d'utiliser ces clés JSON.
+
+C'est presque la seule chose que vous devez vous rappeler de faire correctement vous‑même pour être conforme aux spécifications.
+
+Pour le reste, **FastAPI** s'en charge pour vous.
+
+///
+
+## Mettre à jour les dépendances { #update-the-dependencies }
+
+Nous allons maintenant mettre à jour nos dépendances.
+
+Nous voulons obtenir `current_user` uniquement si cet utilisateur est actif.
+
+Nous créons donc une dépendance supplémentaire `get_current_active_user` qui utilise à son tour `get_current_user` comme dépendance.
+
+Ces deux dépendances renverront simplement une erreur HTTP si l'utilisateur n'existe pas, ou s'il est inactif.
+
+Ainsi, dans notre endpoint, nous n'obtiendrons un utilisateur que si l'utilisateur existe, a été correctement authentifié et est actif :
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}
+
+/// info
+
+L'en‑tête supplémentaire `WWW-Authenticate` avec la valeur `Bearer` que nous renvoyons ici fait également partie de la spécification.
+
+Il est prévu qu'un code d'état HTTP (d'erreur) 401 « UNAUTHORIZED » renvoie également un en‑tête `WWW-Authenticate`.
+
+Dans le cas des jetons bearer (notre cas), la valeur de cet en‑tête doit être `Bearer`.
+
+Vous pouvez en réalité omettre cet en‑tête supplémentaire et cela fonctionnerait quand même.
+
+Mais il est fourni ici pour être conforme aux spécifications.
+
+De plus, il peut exister des outils qui l'attendent et l'utilisent (maintenant ou à l'avenir) et cela pourrait vous être utile, à vous ou à vos utilisateurs, maintenant ou à l'avenir.
+
+C'est l'avantage des standards ...
+
+///
+
+## Voir en action { #see-it-in-action }
+
+Ouvrez la documentation interactive : [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).
+
+### S'authentifier { #authenticate }
+
+Cliquez sur le bouton « Authorize ».
+
+Utilisez les identifiants :
+
+Utilisateur : `johndoe`
+
+Mot de passe : `secret`
+
+
+
+Après vous être authentifié dans le système, vous verrez ceci :
+
+
+
+### Obtenir vos propres données utilisateur { #get-your-own-user-data }
+
+Utilisez maintenant l'opération `GET` avec le chemin `/users/me`.
+
+Vous obtiendrez les données de votre utilisateur, par exemple :
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false,
+ "hashed_password": "fakehashedsecret"
+}
+```
+
+
+
+Si vous cliquez sur l'icône de cadenas et vous vous déconnectez, puis réessayez la même opération, vous obtiendrez une erreur HTTP 401 :
+
+```JSON
+{
+ "detail": "Not authenticated"
+}
+```
+
+### Utilisateur inactif { #inactive-user }
+
+Essayez maintenant avec un utilisateur inactif, authentifiez‑vous avec :
+
+Utilisateur : `alice`
+
+Mot de passe : `secret2`
+
+Et essayez d'utiliser l'opération `GET` avec le chemin `/users/me`.
+
+Vous obtiendrez une erreur « Inactive user », par exemple :
+
+```JSON
+{
+ "detail": "Inactive user"
+}
+```
+
+## Récapitulatif { #recap }
+
+Vous avez maintenant les outils pour implémenter un système de sécurité complet basé sur `username` et `password` pour votre API.
+
+En utilisant ces outils, vous pouvez rendre le système de sécurité compatible avec n'importe quelle base de données et avec n'importe quel modèle d'utilisateur ou de données.
+
+Le seul détail manquant est qu'il n'est pas encore réellement « sécurisé ».
+
+Dans le prochain chapitre, vous verrez comment utiliser une bibliothèque de hachage de mot de passe sécurisée et des jetons JWT.
diff --git a/docs/fr/docs/tutorial/server-sent-events.md b/docs/fr/docs/tutorial/server-sent-events.md
new file mode 100644
index 0000000000000..f4ed506f6b99c
--- /dev/null
+++ b/docs/fr/docs/tutorial/server-sent-events.md
@@ -0,0 +1,120 @@
+# Événements envoyés par le serveur (SSE) { #server-sent-events-sse }
+
+Vous pouvez diffuser des données vers le client en utilisant les **Server-Sent Events** (SSE).
+
+C'est similaire à [Diffuser des JSON Lines](stream-json-lines.md), mais cela utilise le format `text/event-stream`, pris en charge nativement par les navigateurs via l’API [`EventSource`](https://developer.mozilla.org/en-US/docs/Web/API/EventSource).
+
+/// info | Info
+
+Ajouté dans FastAPI 0.135.0.
+
+///
+
+## Que sont les Server-Sent Events ? { #what-are-server-sent-events }
+
+SSE est un standard pour diffuser des données du serveur au client via HTTP.
+
+Chaque événement est un petit bloc de texte avec des « champs » comme `data`, `event`, `id` et `retry`, séparés par des lignes vides.
+
+Cela ressemble à ceci :
+
+```
+data: {"name": "Portal Gun", "price": 999.99}
+
+data: {"name": "Plumbus", "price": 32.99}
+
+```
+
+Les SSE sont couramment utilisés pour le streaming de chat IA, les notifications en direct, les journaux et l’observabilité, et d’autres cas où le serveur envoie des mises à jour au client.
+
+/// tip | Astuce
+
+Si vous souhaitez diffuser des données binaires, par exemple de la vidéo ou de l’audio, consultez le guide avancé : [Diffuser des données](../advanced/stream-data.md).
+
+///
+
+## Diffuser des SSE avec FastAPI { #stream-sse-with-fastapi }
+
+Pour diffuser des SSE avec FastAPI, utilisez `yield` dans votre *fonction de chemin d'accès* et définissez `response_class=EventSourceResponse`.
+
+Importez `EventSourceResponse` depuis `fastapi.sse` :
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[4,22] *}
+
+Chaque élément produit avec `yield` est encodé en JSON et envoyé dans le champ `data:` d’un événement SSE.
+
+Si vous déclarez le type de retour comme `AsyncIterable[Item]`, FastAPI l’utilisera pour **valider**, **documenter** et **sérialiser** les données avec Pydantic.
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[10:12,23] *}
+
+/// tip | Astuce
+
+Comme Pydantic le sérialisera du côté **Rust**, vous obtiendrez une **performance** bien supérieure que si vous ne déclarez pas de type de retour.
+
+///
+
+### Fonctions de chemin d'accès non async { #non-async-path-operation-functions }
+
+Vous pouvez aussi utiliser des fonctions `def` normales (sans `async`), et utiliser `yield` de la même façon.
+
+FastAPI s’assure qu’elles s’exécutent correctement pour ne pas bloquer la boucle d’événements.
+
+Dans ce cas la fonction n’est pas async, le type de retour approprié serait `Iterable[Item]` :
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[28:31] hl[29] *}
+
+### Sans type de retour { #no-return-type }
+
+Vous pouvez aussi omettre le type de retour. FastAPI utilisera le [`jsonable_encoder`](./encoder.md) pour convertir les données et les envoyer.
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[34:37] hl[35] *}
+
+## `ServerSentEvent` { #serversentevent }
+
+Si vous devez définir des champs SSE comme `event`, `id`, `retry` ou `comment`, vous pouvez produire des objets `ServerSentEvent` au lieu de données brutes.
+
+Importez `ServerSentEvent` depuis `fastapi.sse` :
+
+{* ../../docs_src/server_sent_events/tutorial002_py310.py hl[4,26] *}
+
+Le champ `data` est toujours encodé en JSON. Vous pouvez passer toute valeur sérialisable en JSON, y compris des modèles Pydantic.
+
+## Données brutes { #raw-data }
+
+Si vous devez envoyer des données **sans** encodage JSON, utilisez `raw_data` au lieu de `data`.
+
+C’est utile pour envoyer du texte préformaté, des lignes de log, ou des valeurs « sentinelle » spéciales comme `[DONE]`.
+
+{* ../../docs_src/server_sent_events/tutorial003_py310.py hl[17] *}
+
+/// note | Remarque
+
+`data` et `raw_data` s’excluent mutuellement. Vous ne pouvez en définir qu’un seul par `ServerSentEvent`.
+
+///
+
+## Reprendre avec `Last-Event-ID` { #resuming-with-last-event-id }
+
+Quand un navigateur se reconnecte après une coupure, il envoie le dernier `id` reçu dans l’en-tête `Last-Event-ID`.
+
+Vous pouvez le lire comme paramètre d’en-tête et l’utiliser pour reprendre le flux là où le client s’était arrêté :
+
+{* ../../docs_src/server_sent_events/tutorial004_py310.py hl[25,27,31] *}
+
+## SSE avec POST { #sse-with-post }
+
+SSE fonctionne avec **n’importe quelle méthode HTTP**, pas seulement `GET`.
+
+C’est utile pour des protocoles comme [MCP](https://modelcontextprotocol.io) qui diffusent des SSE via `POST` :
+
+{* ../../docs_src/server_sent_events/tutorial005_py310.py hl[14] *}
+
+## Détails techniques { #technical-details }
+
+FastAPI met en œuvre certaines bonnes pratiques SSE prêtes à l’emploi.
+
+- Envoyer un commentaire **« keep alive » `ping`** toutes les 15 secondes quand aucun message n’a été émis, pour éviter que certains proxys ne ferment la connexion, comme suggéré dans la [Spécification HTML : Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes).
+- Définir l’en-tête `Cache-Control: no-cache` pour **empêcher la mise en cache** du flux.
+- Définir un en-tête spécial `X-Accel-Buffering: no` pour **empêcher le buffering** dans certains proxys comme Nginx.
+
+Vous n’avez rien à faire, cela fonctionne prêt à l’emploi. 🤓
diff --git a/docs/fr/docs/tutorial/sql-databases.md b/docs/fr/docs/tutorial/sql-databases.md
new file mode 100644
index 0000000000000..70e5b1dbab638
--- /dev/null
+++ b/docs/fr/docs/tutorial/sql-databases.md
@@ -0,0 +1,357 @@
+# Bases de données SQL (relationnelles) { #sql-relational-databases }
+
+**FastAPI** ne vous oblige pas à utiliser une base de données SQL (relationnelle). Mais vous pouvez utiliser **n'importe quelle base de données** que vous voulez.
+
+Ici, nous allons voir un exemple utilisant [SQLModel](https://sqlmodel.tiangolo.com/).
+
+**SQLModel** est construit au-dessus de [SQLAlchemy](https://www.sqlalchemy.org/) et de Pydantic. Il a été créé par le même auteur que **FastAPI** pour être l'accord parfait pour les applications FastAPI qui ont besoin d'utiliser des **bases de données SQL**.
+
+/// tip | Astuce
+
+Vous pouvez utiliser toute autre bibliothèque SQL ou NoSQL que vous voulez (dans certains cas appelées « ORMs »), FastAPI ne vous impose rien. 😎
+
+///
+
+Comme SQLModel est basé sur SQLAlchemy, vous pouvez facilement utiliser **toute base prise en charge** par SQLAlchemy (ce qui les rend également prises en charge par SQLModel), comme :
+
+* PostgreSQL
+* MySQL
+* SQLite
+* Oracle
+* Microsoft SQL Server, etc.
+
+Dans cet exemple, nous utiliserons **SQLite**, car il utilise un seul fichier et Python a un support intégré. Ainsi, vous pouvez copier cet exemple et l'exécuter tel quel.
+
+Plus tard, pour votre application de production, vous voudrez peut-être utiliser un serveur de base de données comme **PostgreSQL**.
+
+/// tip | Astuce
+
+Il existe un générateur de projet officiel avec **FastAPI** et **PostgreSQL**, incluant un frontend et plus d'outils : [https://github.com/fastapi/full-stack-fastapi-template](https://github.com/fastapi/full-stack-fastapi-template)
+
+///
+
+Il s'agit d'un tutoriel très simple et court ; si vous souhaitez apprendre sur les bases de données en général, sur SQL, ou des fonctionnalités plus avancées, allez voir la [documentation SQLModel](https://sqlmodel.tiangolo.com/).
+
+## Installer `SQLModel` { #install-sqlmodel }
+
+D'abord, assurez-vous de créer votre [environnement virtuel](../virtual-environments.md), de l'activer, puis d'installer `sqlmodel` :
+
+
+
+- תשתית FastAPI, ביצועים גבוהים, קלה ללמידה, מהירה לתכנות, מוכנה לסביבת ייצור -
- - ---- - -**תיעוד**: https://fastapi.tiangolo.com - -**קוד**: https://github.com/tiangolo/fastapi - ---- - -FastAPI היא תשתית רשת מודרנית ומהירה (ביצועים גבוהים) לבניית ממשקי תכנות יישומים (API) עם פייתון 3.6+ בהתבסס על רמזי טיפוסים סטנדרטיים. - -תכונות המפתח הן: - -- **מהירה**: ביצועים גבוהים מאוד, בקנה אחד עם NodeJS ו - Go (תודות ל - Starlette ו - Pydantic). [אחת מתשתיות הפייתון המהירות ביותר](#performance). - -- **מהירה לתכנות**: הגבירו את מהירות פיתוח התכונות החדשות בכ - %200 עד %300. \* -- **פחות שגיאות**: מנעו כ - %40 משגיאות אנוש (מפתחים). \* -- **אינטואיטיבית**: תמיכת עורך מעולה. השלמה בכל מקום. פחות זמן ניפוי שגיאות. -- **קלה**: מתוכננת להיות קלה לשימוש וללמידה. פחות זמן קריאת תיעוד. -- **קצרה**: מזערו שכפול קוד. מספר תכונות מכל הכרזת פרמטר. פחות שגיאות. -- **חסונה**: קבלו קוד מוכן לסביבת ייצור. עם תיעוד אינטרקטיבי אוטומטי. -- **מבוססת סטנדרטים**: מבוססת על (ותואמת לחלוטין ל -) הסטדנרטים הפתוחים לממשקי תכנות יישומים: OpenAPI (ידועים לשעבר כ - Swagger) ו - JSON Schema. - -\* הערכה מבוססת על בדיקות של צוות פיתוח פנימי שבונה אפליקציות בסביבת ייצור. - -## נותני חסות - - - -{% if sponsors %} -{% for sponsor in sponsors.gold -%} -async def...uvicorn main:app --reload...app = FastAPI().
-- --reload: גרמו לשרת להתאתחל לאחר שינויים בקוד. עשו זאת רק בסביבת פיתוח.
-
-/items/{item_id}.
-- שני ה _נתיבים_ מקבלים _בקשות_ `GET` (ידועות גם כ*מתודות* HTTP).
-- ה _נתיב_ /items/{item_id} כולל \*פרמטר נתיב\_ `item_id` שאמור להיות `int`.
-- ה _נתיב_ /items/{item_id} \*פרמטר שאילתא\_ אופציונלי `q`.
-
-### תיעוד API אינטרקטיבי
-
-כעת פנו לכתובת http://127.0.0.1:8000/docs.
-
-אתם תראו את התיעוד האוטומטי (מסופק על ידי Swagger UI):
-
-
-
-### תיעוד אלטרנטיבי
-
-כעת פנו לכתובת http://127.0.0.1:8000/redoc.
-
-אתם תראו תיעוד אלטרנטיבי (מסופק על ידי ReDoc):
-
-
-
-## שדרוג לדוגמא
-
-כעת ערכו את הקובץ `main.py` כך שיוכל לקבל גוף מבקשת `PUT`.
-
-הגדירו את הגוף בעזרת רמזי טיפוסים סטנדרטיים, הודות ל - `Pydantic`.
-
-```Python hl_lines="4 9-12 25-27"
-from typing import Union
-
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-app = FastAPI()
-
-
-class Item(BaseModel):
- name: str
- price: float
- is_offer: Union[bool, None] = None
-
-
-@app.get("/")
-def read_root():
- return {"Hello": "World"}
-
-
-@app.get("/items/{item_id}")
-def read_item(item_id: int, q: Union[str, None] = None):
- return {"item_id": item_id, "q": q}
-
-
-@app.put("/items/{item_id}")
-def update_item(item_id: int, item: Item):
- return {"item_name": item.name, "item_id": item_id}
-```
-
-השרת אמול להתאתחל אוטומטית (מאחר והוספתם --reload לפקודת `uvicorn` שלמעלה).
-
-### שדרוג התיעוד האינטרקטיבי
-
-כעת פנו לכתובת http://127.0.0.1:8000/docs.
-
-- התיעוד האוטומטי יתעדכן, כולל הגוף החדש:
-
-
-
-- לחצו על הכפתור "Try it out", הוא יאפשר לכם למלא את הפרמטרים ולעבוד ישירות מול ה - API.
-
-
-
-- אחר כך לחצו על הכפתור "Execute", האתר יתקשר עם ה - API שלכם, ישלח את הפרמטרים, ישיג את התוצאות ואז יראה אותן על המסך:
-
-
-
-### שדרוג התיעוד האלטרנטיבי
-
-כעת פנו לכתובת http://127.0.0.1:8000/redoc.
-
-- התיעוד האלטרנטיבי גם יראה את פרמטר השאילתא והגוף החדשים.
-
-
-
-### סיכום
-
-לסיכום, אתם מכריזים ** פעם אחת** על טיפוסי הפרמטרים, גוף וכו' כפרמטרים לפונקציה.
-
-אתם עושים את זה עם טיפוסי פייתון מודרניים.
-
-אתם לא צריכים ללמוד תחביר חדש, מתודות או מחלקות של ספרייה ספיציפית, וכו'
-
-רק **פייתון 3.6+** סטנדרטי.
-
-לדוגמא, ל - `int`:
-
-```Python
-item_id: int
-```
-
-או למודל `Item` מורכב יותר:
-
-```Python
-item: Item
-```
-
-...ועם הכרזת הטיפוס האחת הזו אתם מקבלים:
-
-- תמיכת עורך, כולל:
- - השלמות.
- - בדיקת טיפוסים.
-- אימות מידע:
- - שגיאות ברורות ואטומטיות כאשר מוכנס מידע לא חוקי .
- - אימות אפילו לאובייקטי JSON מקוננים.
-- המרה של מידע קלט: המרה של מידע שמגיע מהרשת למידע וטיפוסים של פייתון. קורא מ:
- - JSON.
- - פרמטרי נתיב.
- - פרמטרי שאילתא.
- - עוגיות.
- - כותרות.
- - טפסים.
- - קבצים.
-- המרה של מידע פלט: המרה של מידע וטיפוסים מפייתון למידע רשת (כ - JSON):
- - המירו טיפוסי פייתון (`str`, `int`, `float`, `bool`, `list`, etc).
- - עצמי `datetime`.
- - עצמי `UUID`.
- - מודלי בסיסי נתונים.
- - ...ורבים אחרים.
-- תיעוד API אוטומטי ואינטרקטיבית כולל שתי אלטרנטיבות לממשק המשתמש:
- - Swagger UI.
- - ReDoc.
-
----
-
-בחזרה לדוגמאת הקוד הקודמת, **FastAPI** ידאג:
-
-- לאמת שיש `item_id` בנתיב בבקשות `GET` ו - `PUT`.
-- לאמת שה - `item_id` הוא מטיפוס `int` בבקשות `GET` ו - `PUT`.
- - אם הוא לא, הלקוח יראה שגיאה ברורה ושימושית.
-- לבדוק האם קיים פרמטר שאילתא בשם `q` (קרי `http://127.0.0.1:8000/items/foo?q=somequery`) לבקשות `GET`.
- - מאחר והפרמטר `q` מוגדר עם = None, הוא אופציונלי.
- - לולא ה - `None` הוא היה חובה (כמו הגוף במקרה של `PUT`).
-- לבקשות `PUT` לנתיב /items/{item_id}, לקרוא את גוף הבקשה כ - JSON:
- - לאמת שהוא כולל את מאפיין החובה `name` שאמור להיות מטיפוס `str`.
- - לאמת שהוא כולל את מאפיין החובה `price` שחייב להיות מטיפוס `float`.
- - לבדוק האם הוא כולל את מאפיין הרשות `is_offer` שאמור להיות מטיפוס `bool`, אם הוא נמצא.
- - כל זה יעבוד גם לאובייקט JSON מקונן.
-- להמיר מ - JSON ול- JSON אוטומטית.
-- לתעד הכל באמצעות OpenAPI, תיעוד שבו יוכלו להשתמש:
- - מערכות תיעוד אינטרקטיביות.
- - מערכות ייצור קוד אוטומטיות, להרבה שפות.
-- לספק ישירות שתי מערכות תיעוד רשתיות.
-
----
-
-רק גרדנו את קצה הקרחון, אבל כבר יש לכם רעיון של איך הכל עובד.
-
-נסו לשנות את השורה:
-
-```Python
- return {"item_name": item.name, "item_id": item_id}
-```
-
-...מ:
-
-```Python
- ... "item_name": item.name ...
-```
-
-...ל:
-
-```Python
- ... "item_price": item.price ...
-```
-
-...וראו איך העורך שלכם משלים את המאפיינים ויודע את הטיפוסים שלהם:
-
-
-
-לדוגמא יותר שלמה שכוללת עוד תכונות, ראו את המדריך - למשתמש.
-
-**התראת ספוילרים**: המדריך - למשתמש כולל:
-
-- הכרזה על **פרמטרים** ממקורות אחרים ושונים כגון: **כותרות**, **עוגיות**, **טפסים** ו - **קבצים**.
-- איך לקבוע **מגבלות אימות** בעזרת `maximum_length` או `regex`.
-- דרך חזקה וקלה להשתמש ב**הזרקת תלויות**.
-- אבטחה והתאמתות, כולל תמיכה ב - **OAuth2** עם **JWT** והתאמתות **HTTP Basic**.
-- טכניקות מתקדמות (אבל קלות באותה מידה) להכרזת אובייקטי JSON מקוננים (תודות ל - Pydantic).
-- אינטרקציה עם **GraphQL** דרך Strawberry וספריות אחרות.
-- תכונות נוספות רבות (תודות ל - Starlette) כגון:
- - **WebSockets**
- - בדיקות קלות במיוחד מבוססות על `requests` ו - `pytest`
- - **CORS**
- - **Cookie Sessions**
- - ...ועוד.
-
-## ביצועים
-
-בדיקות עצמאיות של TechEmpower הראו שאפליקציות **FastAPI** שרצות תחת Uvicorn הן מתשתיות הפייתון המהירות ביותר, רק מתחת ל - Starlette ו - Uvicorn עצמן (ש - FastAPI מבוססת עליהן). (\*)
-
-כדי להבין עוד על הנושא, ראו את הפרק Benchmarks.
-
-## תלויות אופציונליות
-
-בשימוש Pydantic:
-
-- email_validator - לאימות כתובות אימייל.
-
-בשימוש Starlette:
-
-- httpx - דרוש אם ברצונכם להשתמש ב - `TestClient`.
-- jinja2 - דרוש אם ברצונכם להשתמש בברירת המחדל של תצורת הטמפלייטים.
-- python-multipart - דרוש אם ברצונכם לתמוך ב "פרסור" טפסים, באצמעות request.form().
-- itsdangerous - דרוש אם ברצונכם להשתמש ב - `SessionMiddleware`.
-- pyyaml - דרוש אם ברצונכם להשתמש ב - `SchemaGenerator` של Starlette (כנראה שאתם לא צריכים את זה עם FastAPI).
-- ujson - דרוש אם ברצונכם להשתמש ב - `UJSONResponse`.
-
-בשימוש FastAPI / Starlette:
-
-- uvicorn - לשרת שטוען ומגיש את האפליקציה שלכם.
-- orjson - דרוש אם ברצונכם להשתמש ב - `ORJSONResponse`.
-
-תוכלו להתקין את כל אלו באמצעות pip install "fastapi[all]".
-
-## רשיון
-
-הפרויקט הזה הוא תחת התנאים של רשיון MIT.
diff --git a/docs/he/mkdocs.yml b/docs/he/mkdocs.yml
deleted file mode 100644
index de18856f445aa..0000000000000
--- a/docs/he/mkdocs.yml
+++ /dev/null
@@ -1 +0,0 @@
-INHERIT: ../en/mkdocs.yml
diff --git a/docs/id/docs/tutorial/index.md b/docs/id/docs/tutorial/index.md
deleted file mode 100644
index b8ed96ae1f6fc..0000000000000
--- a/docs/id/docs/tutorial/index.md
+++ /dev/null
@@ -1,80 +0,0 @@
-# Tutorial - Pedoman Pengguna - Pengenalan
-
-Tutorial ini menunjukan cara menggunakan ***FastAPI*** dengan semua fitur-fiturnya, tahap demi tahap.
-
-Setiap bagian dibangun secara bertahap dari bagian sebelumnya, tetapi terstruktur untuk memisahkan banyak topik, sehingga kamu bisa secara langsung menuju ke topik spesifik untuk menyelesaikan kebutuhan API tertentu.
-
-Ini juga dibangun untuk digunakan sebagai referensi yang akan datang.
-
-Sehingga kamu dapat kembali lagi dan mencari apa yang kamu butuhkan dengan tepat.
-
-## Jalankan kode
-
-Semua blok-blok kode dapat disalin dan digunakan langsung (Mereka semua sebenarnya adalah file python yang sudah teruji).
-
-Untuk menjalankan setiap contoh, salin kode ke file `main.py`, dan jalankan `uvicorn` dengan:
-
-lt
+* XWT
+* PSGI
+
+### abbr が完全な語句と説明を示す { #the-abbr-gives-a-full-phrase-and-an-explanation }
+
+* MDN
+* I/O.
+
+////
+
+//// tab | 情報
+
+"abbr" 要素の "title" 属性は特定の指示に従って翻訳します。
+
+翻訳は、英語の語を説明するために独自の "abbr" 要素を追加してもよく、LLM はそれらを削除してはいけません。
+
+`scripts/translate.py` の general プロンプト内「### HTML abbr elements」の節を参照してください。
+
+////
+
+## HTML "dfn" 要素 { #html-dfn-elements }
+
+* クラスター
+* ディープラーニング
+
+## 見出し { #headings }
+
+//// tab | テスト
+
+### Web アプリを開発する - チュートリアル { #develop-a-webapp-a-tutorial }
+
+こんにちは。
+
+### 型ヒントとアノテーション { #type-hints-and-annotations }
+
+またこんにちは。
+
+### スーパークラスとサブクラス { #super-and-subclasses }
+
+またこんにちは。
+
+////
+
+//// tab | 情報
+
+見出しに関する唯一の厳格なルールは、リンクが壊れないように、LLM が中括弧内のハッシュ部分を変更しないことです。
+
+`scripts/translate.py` の general プロンプト内「### Headings」の節を参照してください。
+
+言語固有の指示については、例として `docs/de/llm-prompt.md` の「### Headings」の節を参照してください。
+
+////
+
+## ドキュメントで使う用語 { #terms-used-in-the-docs }
+
+//// tab | テスト
+
+* you
+* your
+
+* e.g.
+* etc.
+
+* `foo` を `int` として
+* `bar` を `str` として
+* `baz` を `list` として
+
+* チュートリアル - ユーザーガイド
+* 上級ユーザーガイド
+* SQLModel ドキュメント
+* API ドキュメント
+* 自動生成ドキュメント
+
+* データサイエンス
+* ディープラーニング
+* 機械学習
+* 依存性注入
+* HTTP Basic 認証
+* HTTP Digest
+* ISO 形式
+* JSON Schema 規格
+* JSON スキーマ
+* スキーマ定義
+* Password Flow
+* モバイル
+
+* 非推奨
+* 設計された
+* 無効
+* オンザフライ
+* 標準
+* デフォルト
+* 大文字小文字を区別
+* 大文字小文字を区別しない
+
+* アプリケーションを提供する
+* ページを配信する
+
+* アプリ
+* アプリケーション
+
+* リクエスト
+* レスポンス
+* エラーレスポンス
+
+* path operation
+* path operation デコレータ
+* path operation 関数
+
+* ボディ
+* リクエストボディ
+* レスポンスボディ
+* JSON ボディ
+* フォームボディ
+* ファイルボディ
+* 関数本体
+
+* パラメータ
+* ボディパラメータ
+* パスパラメータ
+* クエリパラメータ
+* Cookie パラメータ
+* ヘッダーパラメータ
+* フォームパラメータ
+* 関数パラメータ
+
+* イベント
+* 起動イベント
+* サーバーの起動
+* シャットダウンイベント
+* lifespan イベント
+
+* ハンドラ
+* イベントハンドラ
+* 例外ハンドラ
+* 処理する
+
+* モデル
+* Pydantic モデル
+* データモデル
+* データベースモデル
+* フォームモデル
+* モデルオブジェクト
+
+* クラス
+* 基底クラス
+* 親クラス
+* サブクラス
+* 子クラス
+* 兄弟クラス
+* クラスメソッド
+
+* ヘッダー
+* ヘッダー(複数)
+* 認可ヘッダー
+* `Authorization` ヘッダー
+* Forwarded ヘッダー
+
+* 依存性注入システム
+* 依存関係
+* dependable
+* dependant
+
+* I/O バウンド
+* CPU バウンド
+* 同時実行性
+* 並列性
+* マルチプロセッシング
+
+* env var
+* 環境変数
+* `PATH`
+* `PATH` 環境変数
+
+* 認証
+* 認証プロバイダ
+* 認可
+* 認可フォーム
+* 認可プロバイダ
+* ユーザーが認証する
+* システムがユーザーを認証する
+
+* CLI
+* コマンドラインインターフェース
+
+* サーバー
+* クライアント
+
+* クラウドプロバイダ
+* クラウドサービス
+
+* 開発
+* 開発段階
+
+* dict
+* 辞書
+* 列挙型
+* Enum
+* 列挙メンバー
+
+* エンコーダー
+* デコーダー
+* エンコードする
+* デコードする
+
+* 例外
+* 送出する
+
+* 式
+* 文
+
+* フロントエンド
+* バックエンド
+
+* GitHub ディスカッション
+* GitHub Issue
+
+* パフォーマンス
+* パフォーマンス最適化
+
+* 戻り値の型
+* 戻り値
+
+* セキュリティ
+* セキュリティスキーム
+
+* タスク
+* バックグラウンドタスク
+* タスク関数
+
+* テンプレート
+* テンプレートエンジン
+
+* 型アノテーション
+* 型ヒント
+
+* サーバーワーカー
+* Uvicorn ワーカー
+* Gunicorn ワーカー
+* ワーカープロセス
+* ワーカークラス
+* ワークロード
+
+* デプロイ
+* デプロイする
+
+* SDK
+* ソフトウェア開発キット
+
+* `APIRouter`
+* `requirements.txt`
+* Bearer Token
+* 破壊的変更
+* バグ
+* ボタン
+* 呼び出し可能
+* コード
+* コミット
+* コンテキストマネージャ
+* コルーチン
+* データベースセッション
+* ディスク
+* ドメイン
+* エンジン
+* フェイクの X
+* HTTP GET メソッド
+* アイテム
+* ライブラリ
+* ライフスパン
+* ロック
+* ミドルウェア
+* モバイルアプリケーション
+* モジュール
+* マウント
+* ネットワーク
+* オリジン
+* オーバーライド
+* ペイロード
+* プロセッサ
+* プロパティ
+* プロキシ
+* プルリクエスト
+* クエリ
+* RAM
+* リモートマシン
+* ステータスコード
+* 文字列
+* タグ
+* Web フレームワーク
+* ワイルドカード
+* 返す
+* 検証する
+
+////
+
+//// tab | 情報
+
+これはドキュメントで見られる(主に)技術用語の不完全かつ規範的でない一覧です。プロンプト設計者が、LLM がどの用語で手助けを必要としているかを把握するのに役立つかもしれません。例えば、良い翻訳を最適でない翻訳に戻してしまう場合や、あなたの言語での活用・格変化に問題がある場合などです。
+
+`docs/de/llm-prompt.md` の「### List of English terms and their preferred German translations」の節を参照してください。
+
+////
diff --git a/docs/ja/docs/about/index.md b/docs/ja/docs/about/index.md
new file mode 100644
index 0000000000000..b099df7fab660
--- /dev/null
+++ b/docs/ja/docs/about/index.md
@@ -0,0 +1,3 @@
+# 概要 { #about }
+
+FastAPI の概要、その設計やインスピレーションなどについて解説します。🤓
diff --git a/docs/ja/docs/advanced/additional-responses.md b/docs/ja/docs/advanced/additional-responses.md
new file mode 100644
index 0000000000000..1d7c2f80e1a7f
--- /dev/null
+++ b/docs/ja/docs/advanced/additional-responses.md
@@ -0,0 +1,247 @@
+# OpenAPI の追加レスポンス { #additional-responses-in-openapi }
+
+/// warning | 注意
+
+これは比較的高度なトピックです。
+
+FastAPI を使い始めたばかりであれば、これは不要かもしれません。
+
+///
+
+追加のステータスコード、メディアタイプ、説明などを伴う追加レスポンスを宣言できます。
+
+それらの追加レスポンスは OpenAPI スキーマに含まれ、API ドキュメントにも表示されます。
+
+ただし、それらの追加レスポンスについては、ステータスコードとコンテンツを指定して `JSONResponse` などの `Response` を直接返す必要があります。
+
+## `model` を使った追加レスポンス { #additional-response-with-model }
+
+*path operation デコレータ*に `responses` パラメータを渡せます。
+
+これは `dict` を受け取り、キーは各レスポンスのステータスコード(例: `200`)、値は各レスポンスの情報を含む別の `dict` です。
+
+それぞれのレスポンス `dict` には、`response_model` と同様に Pydantic モデルを格納する `model` キーを含められます。
+
+FastAPI はそのモデルから JSON Schema を生成し、OpenAPI の適切な場所に含めます。
+
+例えば、ステータスコード `404` と Pydantic モデル `Message` を持つ別のレスポンスを宣言するには、次のように書けます:
+
+{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}
+
+/// note | 備考
+
+`JSONResponse` を直接返す必要がある点に注意してください。
+
+///
+
+/// info | 情報
+
+`model` キーは OpenAPI の一部ではありません。
+
+FastAPI はそこから Pydantic モデルを取得して JSON Schema を生成し、適切な場所に配置します。
+
+適切な場所は次のとおりです:
+
+- `content` キーの中。これは値として別の JSON オブジェクト(`dict`)を持ち、その中に次が含まれます:
+ - メディアタイプ(例: `application/json`)をキーとし、値としてさらに別の JSON オブジェクトを持ち、その中に次が含まれます:
+ - `schema` キー。値としてモデル由来の JSON Schema を持ち、ここが正しい配置場所です。
+ - FastAPI はここに、スキーマを直接埋め込む代わりに OpenAPI 内のグローバルな JSON Schema への参照を追加します。これにより、他のアプリケーションやクライアントがそれらの JSON Schema を直接利用し、より良いコード生成ツール等を提供できます。
+
+///
+
+この *path operation* のために OpenAPI に生成されるレスポンスは次のとおりです:
+
+```JSON hl_lines="3-12"
+{
+ "responses": {
+ "404": {
+ "description": "Additional Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Message"
+ }
+ }
+ }
+ },
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+スキーマは OpenAPI スキーマ内の別の場所への参照になります:
+
+```JSON hl_lines="4-16"
+{
+ "components": {
+ "schemas": {
+ "Message": {
+ "title": "Message",
+ "required": [
+ "message"
+ ],
+ "type": "object",
+ "properties": {
+ "message": {
+ "title": "Message",
+ "type": "string"
+ }
+ }
+ },
+ "Item": {
+ "title": "Item",
+ "required": [
+ "id",
+ "value"
+ ],
+ "type": "object",
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
+ },
+ "value": {
+ "title": "Value",
+ "type": "string"
+ }
+ }
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": [
+ "loc",
+ "msg",
+ "type"
+ ],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string"
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string"
+ }
+ }
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+## メインのレスポンスに追加のメディアタイプ { #additional-media-types-for-the-main-response }
+
+同じ `responses` パラメータを使って、同一のメインレスポンスに別のメディアタイプを追加できます。
+
+例えば、`image/png` の追加メディアタイプを加え、あなたの *path operation* が JSON オブジェクト(メディアタイプ `application/json`)または PNG 画像を返せることを宣言できます:
+
+{* ../../docs_src/additional_responses/tutorial002_py310.py hl[17:22,26] *}
+
+/// note | 備考
+
+画像は `FileResponse` を使って直接返す必要がある点に注意してください。
+
+///
+
+/// info | 情報
+
+`responses` パラメータで明示的に別のメディアタイプを指定しない限り、FastAPI はレスポンスがメインのレスポンスクラスと同じメディアタイプ(デフォルトは `application/json`)であるとみなします。
+
+ただし、メディアタイプが `None` のカスタムレスポンスクラスを指定している場合、モデルが関連付けられた追加レスポンスには FastAPI は `application/json` を使用します。
+
+///
+
+## 情報の結合 { #combining-information }
+
+`response_model`、`status_code`、`responses` パラメータなど、複数の場所からのレスポンス情報を組み合わせることもできます。
+
+`response_model` を宣言し、デフォルトのステータスコード `200`(必要なら任意のコード)を使い、その同じレスポンスに対する追加情報を `responses` で OpenAPI スキーマに直接記述できます。
+
+FastAPI は `responses` にある追加情報を保持し、モデルの JSON Schema と結合します。
+
+例えば、Pydantic モデルを用い、独自の `description` を持つステータスコード `404` のレスポンスを宣言できます。
+
+さらに、`response_model` を使うステータスコード `200` のレスポンスに独自の `example` を含めることもできます:
+
+{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}
+
+これらはすべて結合されて OpenAPI に含まれ、API ドキュメントに表示されます:
+
+
+
+## 事前定義レスポンスとカスタムの組み合わせ { #combine-predefined-responses-and-custom-ones }
+
+多くの *path operations* に適用できる事前定義のレスポンスを用意しつつ、各 *path operation* ごとに必要なカスタムレスポンスと組み合わせたい場合があります。
+
+そのような場合、Python の `**dict_to_unpack` による `dict` の「アンパック」テクニックを使えます:
+
+```Python
+old_dict = {
+ "old key": "old value",
+ "second old key": "second old value",
+}
+new_dict = {**old_dict, "new key": "new value"}
+```
+
+ここでは、`new_dict` には `old_dict` のすべてのキーと値に加え、新しいキーと値が含まれます:
+
+```Python
+{
+ "old key": "old value",
+ "second old key": "second old value",
+ "new key": "new value",
+}
+```
+
+このテクニックを使うと、*path operations* で事前定義レスポンスを再利用し、さらにカスタムのレスポンスを組み合わせられます。
+
+例えば:
+
+{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}
+
+## OpenAPI レスポンスの詳細 { #more-information-about-openapi-responses }
+
+レスポンスに正確に何を含められるかは、OpenAPI 仕様の次のセクションを参照してください:
+
+- [OpenAPI の Responses Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responses-object)、ここには `Response Object` が含まれます。
+- [OpenAPI の Response Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#response-object)、`responses` パラメータ内の各レスポンスに、ここで定義されている要素を直接含められます。`description`、`headers`、`content`(ここで異なるメディアタイプや JSON Schema を宣言します)、`links` など。
diff --git a/docs/ja/docs/advanced/additional-status-codes.md b/docs/ja/docs/advanced/additional-status-codes.md
index d1f8e645169f3..ad9bd57dcdd0c 100644
--- a/docs/ja/docs/advanced/additional-status-codes.md
+++ b/docs/ja/docs/advanced/additional-status-codes.md
@@ -1,37 +1,41 @@
-# 追加のステータスコード
+# 追加のステータスコード { #additional-status-codes }
-デフォルトでは、 **FastAPI** は `JSONResponse` を使ってレスポンスを返します。その `JSONResponse` の中には、 *path operation* が返した内容が入ります。
+デフォルトでは、 **FastAPI** は `JSONResponse` を使ってレスポンスを返し、*path operation* から返した内容をその `JSONResponse` の中に入れます。
-それは、デフォルトのステータスコードか、 *path operation* でセットしたものを利用します。
+デフォルトのステータスコード、または *path operation* で設定したステータスコードが使用されます。
-## 追加のステータスコード
+## 追加のステータスコード { #additional-status-codes_1 }
-メインのステータスコードとは別に、他のステータスコードを返したい場合は、`Response` (`JSONResponse` など) に追加のステータスコードを設定して直接返します。
+メインのステータスコードとは別に追加のステータスコードを返したい場合は、`JSONResponse` のような `Response` を直接返し、追加のステータスコードを直接設定できます。
-例えば、itemを更新し、成功した場合は200 "OK"のHTTPステータスコードを返す *path operation* を作りたいとします。
+たとえば、item を更新でき、成功時に HTTP ステータスコード 200 "OK" を返す *path operation* を作りたいとします。
-しかし、新しいitemも許可したいです。itemが存在しない場合は、それらを作成して201 "Created"を返します。
+しかし、新しい item も受け付けたいとします。そして、item が以前存在しなかった場合には作成し、HTTP ステータスコード 201「Created」を返します。
-これを達成するには、 `JSONResponse` をインポートし、 `status_code` を設定して直接内容を返します。
+これを実現するには、`JSONResponse` をインポートし、望む `status_code` を設定して、そこで内容を直接返します。
-```Python hl_lines="4 25"
-{!../../../docs_src/additional_status_codes/tutorial001.py!}
-```
+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
-!!! warning "注意"
- 上記の例のように `Response` を明示的に返す場合、それは直接返されます。
+/// warning
- モデルなどはシリアライズされません。
+上の例のように `Response` を直接返すと、それはそのまま返されます。
- 必要なデータが含まれていることや、値が有効なJSONであること (`JSONResponse` を使う場合) を確認してください。
+モデルなどによってシリアライズされません。
-!!! note "技術詳細"
- `from starlette.responses import JSONResponse` を利用することもできます。
+必要なデータが含まれていること、そして(`JSONResponse` を使用している場合)値が有効な JSON であることを確認してください。
- **FastAPI** は `fastapi.responses` と同じ `starlette.responses` を、開発者の利便性のために提供しています。しかし有効なレスポンスはほとんどStarletteから来ています。 `status` についても同じです。
+///
-## OpenAPIとAPIドキュメント
+/// note | 技術詳細
-ステータスコードとレスポンスを直接返す場合、それらはOpenAPIスキーマ (APIドキュメント) には含まれません。なぜなら、FastAPIは何が返されるのか事前に知ることができないからです。
+`from starlette.responses import JSONResponse` を使うこともできます。
-しかし、 [Additional Responses](additional-responses.md){.internal-link target=_blank} を使ってコードの中にドキュメントを書くことができます。
+**FastAPI** は開発者の利便性のために、`fastapi.responses` と同じ `starlette.responses` を提供しています。しかし、利用可能なレスポンスのほとんどは Starlette から直接提供されています。`status` も同様です。
+
+///
+
+## OpenAPI と API ドキュメント { #openapi-and-api-docs }
+
+追加のステータスコードとレスポンスを直接返す場合、それらは OpenAPI スキーマ(API ドキュメント)には含まれません。FastAPI には、事前に何が返されるかを知る方法がないからです。
+
+しかし、[追加のレスポンス](additional-responses.md) を使ってコード内にドキュメント化できます。
diff --git a/docs/ja/docs/advanced/advanced-dependencies.md b/docs/ja/docs/advanced/advanced-dependencies.md
new file mode 100644
index 0000000000000..5181e39d828a7
--- /dev/null
+++ b/docs/ja/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,163 @@
+# 高度な依存関係 { #advanced-dependencies }
+
+## パラメータ化された依存関係 { #parameterized-dependencies }
+
+これまで見てきた依存関係は、固定の関数またはクラスでした。
+
+しかし、多くの異なる関数やクラスを宣言せずに、その依存関係にパラメータを設定したい場合があります。
+
+たとえば、クエリパラメータ `q` に、ある固定の内容が含まれているかを検査する依存関係が欲しいとします。
+
+ただし、その固定の内容はパラメータ化できるようにしたいです。
+
+## "callable" なインスタンス { #a-callable-instance }
+
+Python には、クラスのインスタンスを "callable" にする方法があります。
+
+クラス自体(これはすでに callable です)ではなく、そのクラスのインスタンスです。
+
+そのためには、`__call__` メソッドを宣言します:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}
+
+この場合、この `__call__` が、**FastAPI** が追加のパラメータやサブ依存関係を確認するために使うものになり、後であなたの *path operation 関数* のパラメータに値を渡すために呼び出されるものになります。
+
+## インスタンスのパラメータ化 { #parameterize-the-instance }
+
+そして、`__init__` を使って、依存関係を「パラメータ化」するために利用できるインスタンスのパラメータを宣言できます:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}
+
+この場合、**FastAPI** は `__init__` に触れたり気にかけたりすることはありません。私たちがコード内で直接使います。
+
+## インスタンスの作成 { #create-an-instance }
+
+このクラスのインスタンスは次のように作成できます:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}
+
+このようにして依存関係を「パラメータ化」できます。いまや `"bar"` が属性 `checker.fixed_content` として中に保持されています。
+
+## インスタンスを依存関係として使う { #use-the-instance-as-a-dependency }
+
+その後、`Depends(FixedContentQueryChecker)` の代わりに `Depends(checker)` でこの `checker` を使えます。依存関係はクラスそのものではなく、インスタンスである `checker` だからです。
+
+依存関係を解決するとき、**FastAPI** はこの `checker` を次のように呼び出します:
+
+```Python
+checker(q="somequery")
+```
+
+...そして、その戻り値を *path operation 関数* 内の依存関係の値として、パラメータ `fixed_content_included` に渡します:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}
+
+/// tip | 豆知識
+
+ここまでの内容は回りくどく感じられるかもしれません。まだどのように役立つかが明確でないかもしれません。
+
+これらの例は意図的に単純ですが、仕組みを示しています。
+
+セキュリティの章では、同じやり方で実装されたユーティリティ関数があります。
+
+ここまでを理解できていれば、そうしたセキュリティ用ユーティリティが内部でどのように動いているかも理解できています。
+
+///
+
+## `yield`、`HTTPException`、`except` とバックグラウンドタスクを伴う依存関係 { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+/// warning | 注意
+
+これらの技術的詳細は、ほとんどの場合は不要です。
+
+主に、0.121.0 より前の FastAPI アプリケーションがあり、`yield` を使う依存関係で問題が発生している場合に有用です。
+
+///
+
+`yield` を使う依存関係は、さまざまなユースケースに対応し、いくつかの問題を修正するために時間とともに進化してきました。ここでは変更点の概要を説明します。
+
+### `yield` と `scope` を伴う依存関係 { #dependencies-with-yield-and-scope }
+
+バージョン 0.121.0 で、`yield` を使う依存関係に対して `Depends(scope="function")` がサポートされました。
+
+`Depends(scope="function")` を使うと、`yield` の後の終了コードは、クライアントへレスポンスが返される前、*path operation 関数* が終了した直後に実行されます。
+
+そして、`Depends(scope="request")`(デフォルト)を使う場合、`yield` の後の終了コードはレスポンス送信後に実行されます。
+
+詳しくはドキュメント「[`yield` を使う依存関係 - 早期終了と `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope)」を参照してください。
+
+### `yield` と `StreamingResponse` を伴う依存関係、技術詳細 { #dependencies-with-yield-and-streamingresponse-technical-details }
+
+FastAPI 0.118.0 より前では、`yield` を使う依存関係を使用すると、*path operation 関数* が戻ってからレスポンス送信直前に終了コードが実行されていました。
+
+これは、レスポンスがネットワーク上を移動するのを待っている間に、不要にリソースを保持しないようにする意図でした。
+
+この変更により、`StreamingResponse` を返す場合、`yield` を持つ依存関係の終了コードはすでに実行されていることになりました。
+
+たとえば、`yield` を持つ依存関係の中でデータベースセッションを持っていた場合、`StreamingResponse` はデータをストリーミングしている間にそのセッションを使えません。というのも、`yield` の後の終了コードでそのセッションがすでにクローズされているからです。
+
+この挙動は 0.118.0 で元に戻され、`yield` の後の終了コードはレスポンス送信後に実行されるようになりました。
+
+/// info | 情報
+
+以下で見るように、これはバージョン 0.106.0 より前の挙動ととても似ていますが、いくつかのコーナーケースに対する改良とバグ修正が含まれています。
+
+///
+
+#### 早期終了コードのユースケース { #use-cases-with-early-exit-code }
+
+特定の条件では、レスポンス送信前に `yield` を持つ依存関係の終了コードを実行する、古い挙動の恩恵を受けられるユースケースがあります。
+
+例えば、`yield` を持つ依存関係でデータベースセッションを使ってユーザ検証だけを行い、その後は *path operation 関数* 内ではそのデータベースセッションを一切使わない、かつレスポンス送信に長い時間がかかる(例えばデータをゆっくり送る `StreamingResponse`)が、何らかの理由でデータベースは使わない、というケースです。
+
+この場合、レスポンスの送信が終わるまでデータベースセッションが保持されますが、使わないのであれば保持する必要はありません。
+
+次のようになります:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
+
+終了コード、すなわち `Session` の自動クローズは:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
+
+...の部分で定義されており、遅いデータ送信が終わった後に実行されます:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
+
+しかし、`generate_stream()` はデータベースセッションを使わないため、レスポンス送信中にセッションを開いたままにしておく必要は実際にはありません。
+
+SQLModel(または SQLAlchemy)でこの特定のユースケースがある場合は、不要になった時点でセッションを明示的にクローズできます:
+
+{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}
+
+このようにすると、セッションはデータベース接続を解放するため、他のリクエストがそれを使えるようになります。
+
+`yield` を持つ依存関係で早期終了が必要な別のユースケースがある場合は、あなたの具体的なユースケースと、なぜ `yield` を持つ依存関係の早期クローズが有益かを説明して、[GitHub Discussion の質問](https://github.com/fastapi/fastapi/discussions/new?category=questions)を作成してください。
+
+`yield` を持つ依存関係の早期クローズに納得できるユースケースがある場合は、早期クローズにオプトインする新しい方法を追加することを検討します。
+
+### `yield` と `except` を伴う依存関係、技術詳細 { #dependencies-with-yield-and-except-technical-details }
+
+FastAPI 0.110.0 より前では、`yield` を持つ依存関係を使い、その依存関係内で `except` によって例外を捕捉し、再度その例外を送出しなかった場合でも、その例外は自動的に送出(フォワード)され、任意の例外ハンドラまたは内部サーバエラーハンドラに渡されていました。
+
+これは、ハンドラのないフォワードされた例外(内部サーバエラー)による未処理のメモリ消費を修正し、通常の Python コードの挙動と一貫性を持たせるため、バージョン 0.110.0 で変更されました。
+
+### バックグラウンドタスクと `yield` を伴う依存関係、技術詳細 { #background-tasks-and-dependencies-with-yield-technical-details }
+
+FastAPI 0.106.0 より前では、`yield` の後で例外を送出することはできませんでした。`yield` を持つ依存関係の終了コードはレスポンス送信「後」に実行されるため、[例外ハンドラ](../tutorial/handling-errors.md#install-custom-exception-handlers)はすでに実行済みでした。
+
+これは主に、依存関係が "yield" した同じオブジェクトをバックグラウンドタスク内で利用できるようにするための設計でした。終了コードはバックグラウンドタスク完了後に実行されるからです。
+
+これは、レスポンスがネットワーク上を移動するのを待っている間にリソースを保持しないようにする意図で、FastAPI 0.106.0 で変更されました。
+
+/// tip | 豆知識
+
+加えて、バックグラウンドタスクは通常、独立したロジックの集合であり、(例えば専用のデータベース接続など)それ自身のリソースで個別に扱うべきです。
+
+そのため、このやり方の方がコードはおそらくよりクリーンになります。
+
+///
+
+この挙動に依存していた場合は、バックグラウンドタスク用のリソースをバックグラウンドタスク内部で作成し、`yield` を持つ依存関係のリソースに依存しないデータだけを内部で使用するようにしてください。
+
+例えば、同じデータベースセッションを使うのではなく、バックグラウンドタスク内で新しいデータベースセッションを作成し、この新しいセッションでデータベースからオブジェクトを取得します。そして、バックグラウンドタスク関数の引数としてデータベースのオブジェクト自体を渡すのではなく、そのオブジェクトの ID を渡し、バックグラウンドタスク関数内でもう一度そのオブジェクトを取得します。
diff --git a/docs/ja/docs/advanced/advanced-python-types.md b/docs/ja/docs/advanced/advanced-python-types.md
new file mode 100644
index 0000000000000..b4409bcf6608a
--- /dev/null
+++ b/docs/ja/docs/advanced/advanced-python-types.md
@@ -0,0 +1,61 @@
+# 高度な Python の型 { #advanced-python-types }
+
+Python の型を扱うときに役立つ追加のアイデアをいくつか紹介します。
+
+## `Union` または `Optional` の利用 { #using-union-or-optional }
+
+何らかの理由で `|` が使えない場合、たとえば型アノテーションではなく `response_model=` のような場所では、縦棒(`|`)の代わりに `typing` の `Union` を使えます。
+
+例えば、`str` または `None` になり得ることを宣言できます:
+
+```python
+from typing import Union
+
+
+def say_hi(name: Union[str, None]):
+ print(f"Hi {name}!")
+```
+
+`typing` には、`None` を取り得ることを宣言するための短縮形として `Optional` もあります。
+
+ここからは私のとても主観的な提案です:
+
+- 🚨 `Optional[SomeType]` の使用は避けましょう
+- 代わりに ✨ **`Union[SomeType, None]` を使いましょう** ✨。
+
+どちらも等価で内部的には同一ですが、「optional(任意)」という語が値が任意だと誤解させやすく、実際の意味は「`None` を取り得る」であり、任意ではなく依然として必須である場合でもそうです。そのため `Optional` より `Union` を勧めます。
+
+`Union[SomeType, None]` の方が意味がより明確だと思います。
+
+これは用語や名前付けの話に過ぎませんが、その言葉があなたやチームメイトのコードの捉え方に影響します。
+
+例として次の関数を見てみましょう:
+
+```python
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+ print(f"Hey {name}!")
+```
+
+パラメータ `name` は `Optional[str]` と定義されていますが、任意ではありません。このパラメータなしで関数を呼び出すことはできません:
+
+```Python
+say_hi() # あっ、これはエラーになります!😱
+```
+
+`name` パラメータにはデフォルト値がないため、依然として必須(任意ではない)です。ただし、`name` は値として `None` を受け付けます:
+
+```Python
+say_hi(name=None) # これは動作します。None は有効です 🎉
+```
+
+朗報として、多くの場合は単純に `|` を使って型の Union を定義できます:
+
+```python
+def say_hi(name: str | None):
+ print(f"Hey {name}!")
+```
+
+したがって、通常は `Optional` や `Union` といった名前を気にする必要はありません。😎
diff --git a/docs/ja/docs/advanced/async-tests.md b/docs/ja/docs/advanced/async-tests.md
new file mode 100644
index 0000000000000..da2968dbf7546
--- /dev/null
+++ b/docs/ja/docs/advanced/async-tests.md
@@ -0,0 +1,99 @@
+# 非同期テスト { #async-tests }
+
+これまでに、提供されている `TestClient` を使って **FastAPI** アプリケーションをテストする方法を見てきました。ここまでは、`async` 関数を使わない同期テストのみでした。
+
+テストで非同期関数を使えると、たとえばデータベースへ非同期にクエリする場合などに便利です。非同期データベースライブラリを使いながら、FastAPI アプリにリクエストを送り、その後バックエンドが正しいデータをデータベースに書き込めたかを検証したい、といったケースを想像してください。
+
+その方法を見ていきます。
+
+## pytest.mark.anyio { #pytest-mark-anyio }
+
+テスト内で非同期関数を呼び出したい場合、テスト関数自体も非同期である必要があります。AnyIO はこれを実現するための便利なプラグインを提供しており、特定のテスト関数を非同期で呼び出すことを指定できます。
+
+## HTTPX { #httpx }
+
+**FastAPI** アプリケーションが通常の `def` 関数を使っていても、その内側は依然として `async` アプリケーションです。
+
+`TestClient` は、標準の pytest を使って通常の `def` のテスト関数から非同期の FastAPI アプリを呼び出すための「おまじない」を内部で行います。しかし、その「おまじない」はテスト関数自体が非同期の場合には機能しません。テストを非同期で実行すると、テスト関数内で `TestClient` は使えなくなります。
+
+`TestClient` は [HTTPX](https://www.python-httpx.org) を基に作られており、幸いなことに API のテストには HTTPX を直接利用できます。
+
+## 例 { #example }
+
+簡単な例として、[大きなアプリケーション](../tutorial/bigger-applications.md) と [テスト](../tutorial/testing.md) で説明したものに似たファイル構成を考えます:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+`main.py` は次のようになります:
+
+{* ../../docs_src/async_tests/app_a_py310/main.py *}
+
+`test_main.py` は `main.py` のテストを持ち、次のようになります:
+
+{* ../../docs_src/async_tests/app_a_py310/test_main.py *}
+
+## 実行 { #run-it }
+
+テストはいつも通り次で実行できます:
+
+
+
+しかし、プロキシ(ポート `9999`)を使った「公式」URL `/api/v1/docs` でドキュメント UI にアクセスすると、正しく動作します!🎉
+
+[http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs) を確認してください:
+
+
+
+ねらいどおりです。✔️
+
+これは、FastAPI が `root_path` を使って、OpenAPI の既定の `server` を `root_path` の URL で生成するためです。
+
+## 追加のサーバー { #additional-servers }
+
+/// warning | 注意
+
+これは高度なユースケースです。読み飛ばしても構いません。
+
+///
+
+既定では、**FastAPI** は OpenAPI スキーマ内に `root_path` の URL を持つ `server` を作成します。
+
+しかし、ステージングと本番の両方と同じドキュメント UI で対話させたい場合など、別の `servers` を指定することもできます。
+
+カスタムの `servers` リストを渡していて、かつ `root_path`(API がプロキシの背後にあるため)が設定されている場合、**FastAPI** はこの `root_path` を用いた「server」をリストの先頭に挿入します。
+
+例えば:
+
+{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}
+
+次のような OpenAPI スキーマが生成されます:
+
+```JSON hl_lines="5-7"
+{
+ "openapi": "3.1.0",
+ // ほかの項目
+ "servers": [
+ {
+ "url": "/api/v1"
+ },
+ {
+ "url": "https://stag.example.com",
+ "description": "Staging environment"
+ },
+ {
+ "url": "https://prod.example.com",
+ "description": "Production environment"
+ }
+ ],
+ "paths": {
+ // ほかの項目
+ }
+}
+```
+
+/// tip | 豆知識
+
+`root_path` から取得した `url` 値 `/api/v1` を持つ server が自動生成されている点に注目してください。
+
+///
+
+ドキュメント UI([http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs))では次のように表示されます:
+
+
+
+/// tip | 豆知識
+
+ドキュメント UI は、選択した server と対話します。
+
+///
+
+/// note | 技術詳細
+
+OpenAPI 仕様の `servers` プロパティは任意です。
+
+`servers` パラメータを指定せず、かつ `root_path` が `/` の場合、生成される OpenAPI スキーマからは `servers` プロパティが既定で完全に省略されます。これは、`url` が `/` の server が 1 つあるのと同等です。
+
+///
+
+### `root_path` 由来の自動 server を無効化 { #disable-automatic-server-from-root-path }
+
+`root_path` を用いた自動的な server を **FastAPI** に含めてほしくない場合は、パラメータ `root_path_in_servers=False` を使用します:
+
+{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}
+
+すると、OpenAPI スキーマには含まれません。
+
+## サブアプリケーションのマウント { #mounting-a-sub-application }
+
+`root_path` を伴うプロキシを使用しつつサブアプリケーションをマウントする必要がある場合でも([サブアプリケーション - マウント](sub-applications.md) 参照)、通常どおりに行えます。
+
+FastAPI は内部で `root_path` を適切に扱うため、そのまま動作します。✨
diff --git a/docs/ja/docs/advanced/custom-response.md b/docs/ja/docs/advanced/custom-response.md
index d8b47629ac3cc..e66b1f4944f5d 100644
--- a/docs/ja/docs/advanced/custom-response.md
+++ b/docs/ja/docs/advanced/custom-response.md
@@ -1,223 +1,272 @@
-# カスタムレスポンス - HTML、ストリーム、ファイル、その他のレスポンス
+# カスタムレスポンス - HTML、ストリーム、ファイル、その他 { #custom-response-html-stream-file-others }
-デフォルトでは、**FastAPI** は `JSONResponse` を使ってレスポンスを返します。
+デフォルトでは、**FastAPI** はJSONレスポンスを返します。
-[レスポンスを直接返す](response-directly.md){.internal-link target=_blank}で見たように、 `Response` を直接返すことでこの挙動をオーバーライドできます。
+[レスポンスを直接返す](response-directly.md)で見たように、`Response` を直接返してこの挙動を上書きできます。
-しかし、`Response` を直接返すと、データは自動的に変換されず、ドキュメントも自動生成されません (例えば、生成されるOpenAPIの一部としてHTTPヘッダー `Content-Type` に特定の「メディアタイプ」を含めるなど) 。
+しかし、`Response`(または `JSONResponse` のような任意のサブクラス)を直接返す場合、(`response_model` を宣言していても)データは自動的に変換されず、ドキュメントも自動生成されません(例えば、生成されるOpenAPIの一部としてHTTPヘッダー `Content-Type` に特定の「メディアタイプ」を含めるなど)。
-しかし、*path operationデコレータ* に、使いたい `Response` を宣言することもできます。
+一方で、*path operation デコレータ* の `response_class` パラメータを使って、使用したい `Response`(`Response` の任意のサブクラス)を宣言することもできます。
-*path operation関数* から返されるコンテンツは、その `Response` に含まれます。
+*path operation 関数* から返したコンテンツは、その `Response` に格納されます。
-そしてもし、`Response` が、`JSONResponse` や `UJSONResponse` の場合のようにJSONメディアタイプ (`application/json`) ならば、データは *path operationデコレータ* に宣言したPydantic `response_model` により自動的に変換 (もしくはフィルタ) されます。
+/// note | 備考
-!!! note "備考"
- メディアタイプを指定せずにレスポンスクラスを利用すると、FastAPIは何もコンテンツがないことを期待します。そのため、生成されるOpenAPIドキュメントにレスポンスフォーマットが記載されません。
+メディアタイプを持たないレスポンスクラスを使用すると、FastAPIはレスポンスにコンテンツがないものと見なします。そのため、生成されるOpenAPIドキュメントにレスポンスフォーマットは記載されません。
-## `ORJSONResponse` を使う
+///
-例えば、パフォーマンスを出したい場合は、`orjson`をインストールし、`ORJSONResponse`をレスポンスとしてセットすることができます。
+## JSONレスポンス { #json-responses }
-使いたい `Response` クラス (サブクラス) をインポートし、 *path operationデコレータ* に宣言します。
+FastAPI はデフォルトでJSONレスポンスを返します。
-```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001b.py!}
-```
+[レスポンスモデル](../tutorial/response-model.md) を宣言すると、FastAPI は Pydantic を使ってデータをJSONにシリアライズします。
-!!! info "情報"
- パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用することもできます。
+レスポンスモデルを宣言しない場合、FastAPI は [JSON Compatible Encoder](../tutorial/encoder.md) で説明した `jsonable_encoder` を使い、その結果を `JSONResponse` に入れます。
- この場合、HTTPヘッダー `Content-Type` には `application/json` がセットされます。
+`JSONResponse` のようにJSONメディアタイプ(`application/json`)を持つ `response_class` を宣言した場合、*path operation デコレータ* に宣言した任意のPydanticの `response_model` に従って、返すデータは自動的に変換(およびフィルタ)されます。ただし、そのデータは Pydantic でJSONのバイト列にシリアライズされるわけではなく、まず `jsonable_encoder` で変換された後に `JSONResponse` クラスへ渡され、Pythonの標準JSONライブラリでバイト列にシリアライズされます。
- そして、OpenAPIにはそのようにドキュメントされます。
+### JSONのパフォーマンス { #json-performance }
-!!! tip "豆知識"
- `ORJSONResponse` は、現在はFastAPIのみで利用可能で、Starletteでは利用できません。
+結論として、最大のパフォーマンスを得たい場合は、[レスポンスモデル](../tutorial/response-model.md) を使い、*path operation デコレータ* で `response_class` は宣言しないでください。
-## HTMLレスポンス
+{* ../../docs_src/response_model/tutorial001_01_py310.py ln[15:17] hl[16] *}
-**FastAPI** からHTMLを直接返す場合は、`HTMLResponse` を使います。
+## HTMLレスポンス { #html-response }
-* `HTMLResponse` をインポートする。
-* *path operation* のパラメータ `content_type` に `HTMLResponse` を渡す。
+**FastAPI** からHTMLを直接返すには、`HTMLResponse` を使います。
-```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial002.py!}
-```
+* `HTMLResponse` をインポートする
+* *path operation デコレータ* のパラメータ `response_class` に `HTMLResponse` を渡す
-!!! info "情報"
- パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用されます。
+{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}
- この場合、HTTPヘッダー `Content-Type` には `text/html` がセットされます。
+/// info | 情報
- そして、OpenAPIにはそのようにドキュメント化されます。
+パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するためにも使用されます。
-### `Response` を返す
+この場合、HTTPヘッダー `Content-Type` には `text/html` が設定されます。
-[レスポンスを直接返す](response-directly.md){.internal-link target=_blank}で見たように、レスポンスを直接返すことで、*path operation* の中でレスポンスをオーバーライドできます。
+そして、OpenAPIにもそのようにドキュメント化されます。
-上記と同じ例において、 `HTMLResponse` を返すと、このようになります:
+///
-```Python hl_lines="2 7 19"
-{!../../../docs_src/custom_response/tutorial003.py!}
-```
+### `Response` を返す { #return-a-response }
-!!! warning "注意"
- *path operation関数* から直接返される `Response` は、OpenAPIにドキュメントされず (例えば、 `Content-Type` がドキュメントされない) 、自動的な対話的ドキュメントからも閲覧できません。
+[レスポンスを直接返す](response-directly.md)で見たように、*path operation* の中でレスポンスを直接返して上書きすることもできます。
-!!! info "情報"
- もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。
+上記と同じ例で、`HTMLResponse` を返すと次のようになります:
-### OpenAPIドキュメントと `Response` のオーバーライド
+{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}
-関数の中でレスポンスをオーバーライドしつつも、OpenAPI に「メディアタイプ」をドキュメント化したいなら、 `response_class` パラメータを使い、 `Response` オブジェクトを返します。
+/// warning | 注意
-`response_class` はOpenAPIの *path operation* ドキュメントにのみ使用されますが、 `Response` はそのまま使用されます。
+*path operation 関数* から直接返される `Response` は、OpenAPIにドキュメント化されず(例えば `Content-Type` がドキュメント化されない)、自動生成の対話的ドキュメントにも表示されません。
-#### `HTMLResponse` を直接返す
+///
-例えば、このようになります:
+/// info | 情報
-```Python hl_lines="7 21 23"
-{!../../../docs_src/custom_response/tutorial004.py!}
-```
+もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返した `Response` オブジェクトに由来します。
+
+///
+
+### OpenAPIにドキュメント化しつつ `Response` を上書き { #document-in-openapi-and-override-response }
+
+関数の中からレスポンスを上書きしつつ、同時にOpenAPIで「メディアタイプ」をドキュメント化したい場合は、`response_class` パラメータを使用し、かつ `Response` オブジェクトを返します。
-この例では、関数 `generate_html_response()` は、`str` のHTMLを返すのではなく `Response` を生成して返しています。
+この場合、`response_class` はOpenAPIの *path operation* をドキュメント化するためだけに使われ、実際には返した `Response` がそのまま使用されます。
-`generate_html_response()` を呼び出した結果を返すことにより、**FastAPI** の振る舞いを上書きする `Response` が既に返されています。
+#### `HTMLResponse` を直接返す { #return-an-htmlresponse-directly }
-しかし、一方では `response_class` に `HTMLResponse` を渡しているため、 **FastAPI** はOpenAPIや対話的ドキュメントでHTMLとして `text/html` でドキュメント化する方法を知っています。
+例えば、次のようになります:
+
+{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}
+
+この例では、関数 `generate_html_response()` はHTMLの `str` を返すのではなく、すでに `Response` を生成して返しています。
+
+`generate_html_response()` の呼び出し結果を返すことで、デフォルトの **FastAPI** の挙動を上書きする `Response` をすでに返しています。
+
+しかし、`response_class` にも `HTMLResponse` を渡しているため、**FastAPI** はOpenAPIおよび対話的ドキュメントで、それが `text/html` のHTMLであると正しくドキュメント化できます:
-## 利用可能なレスポンス
+## 利用可能なレスポンス { #available-responses }
+
+以下は利用可能なレスポンスの一部です。
+
+`Response` を使って他のものを返したり、カスタムサブクラスを作成することもできます。
-以下が利用可能なレスポンスの一部です。
+/// note | 技術詳細
-`Response` を使って他の何かを返せますし、カスタムのサブクラスも作れることを覚えておいてください。
+`from starlette.responses import HTMLResponse` を使うこともできます。
-!!! note "技術詳細"
- `from starlette.responses import HTMLResponse` も利用できます。
+**FastAPI** は開発者の利便性のために、`starlette.responses` と同じものを `fastapi.responses` として提供しています。ただし、利用可能なレスポンスの多くはStarletteから直接提供されています。
- **FastAPI** は開発者の利便性のために `fastapi.responses` として `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
+///
-### `Response`
+### `Response` { #response }
-メインの `Response` クラスで、他の全てのレスポンスはこれを継承しています。
+メインの `Response` クラスで、他のすべてのレスポンスはこれを継承しています。
直接返すことができます。
以下のパラメータを受け付けます。
-* `content` - `str` か `bytes`。
-* `status_code` - `int` のHTTPステータスコード。
-* `headers` - 文字列の `dict` 。
-* `media_type` - メディアタイプを示す `str` 。例えば `"text/html"` 。
+* `content` - `str` または `bytes`
+* `status_code` - `int` のHTTPステータスコード
+* `headers` - 文字列の `dict`
+* `media_type` - メディアタイプを示す `str`。例: `"text/html"`
-FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含みます。また、media_typeに基づいたContent-Typeヘッダーを含み、テキストタイプのためにcharsetを追加します。
+FastAPI(実際にはStarlette)は自動的に Content-Length ヘッダーを含めます。また、`media_type` に基づいた Content-Type ヘッダーを含め、テキストタイプには charset を追加します。
-```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
-```
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
-### `HTMLResponse`
+### `HTMLResponse` { #htmlresponse }
-上で読んだように、テキストやバイトを受け取り、HTMLレスポンスを返します。
+上で読んだように、テキストやバイト列を受け取り、HTMLレスポンスを返します。
-### `PlainTextResponse`
+### `PlainTextResponse` { #plaintextresponse }
-テキストやバイトを受け取り、プレーンテキストのレスポンスを返します。
+テキストやバイト列を受け取り、プレーンテキストのレスポンスを返します。
-```Python hl_lines="2 7 9"
-{!../../../docs_src/custom_response/tutorial005.py!}
-```
+{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}
-### `JSONResponse`
+### `JSONResponse` { #jsonresponse }
-データを受け取り、 `application/json` としてエンコードされたレスポンスを返します。
+データを受け取り、`application/json` としてエンコードされたレスポンスを返します。
-上で読んだように、**FastAPI** のデフォルトのレスポンスとして利用されます。
+これは、上で述べたように **FastAPI** のデフォルトのレスポンスです。
-### `ORJSONResponse`
+/// note | 技術詳細
-上で読んだように、`orjson`を使った、高速な代替のJSONレスポンスです。
+ただし、レスポンスモデルや返却型を宣言した場合は、それが直接データのJSONシリアライズに使われ、適切なJSONのメディアタイプを持つレスポンスが `JSONResponse` クラスを使わずに直接返されます。
-### `UJSONResponse`
+これが最適なパフォーマンスを得る理想的な方法です。
-`ujson`を使った、代替のJSONレスポンスです。
+///
-!!! warning "注意"
- `ujson` は、いくつかのエッジケースの取り扱いについて、Pythonにビルトインされた実装よりも作りこまれていません。
+### `RedirectResponse` { #redirectresponse }
-```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001.py!}
-```
+HTTPリダイレクトを返します。デフォルトでは307ステータスコード(Temporary Redirect)を使用します。
-!!! tip "豆知識"
- `ORJSONResponse` のほうが高速な代替かもしれません。
+`RedirectResponse` を直接返せます:
-### `RedirectResponse`
+{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}
-HTTPリダイレクトを返します。デフォルトでは307ステータスコード (Temporary Redirect) となります。
+---
-```Python hl_lines="2 9"
-{!../../../docs_src/custom_response/tutorial006.py!}
-```
+または、`response_class` パラメータで使用できます:
-### `StreamingResponse`
+{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}
-非同期なジェネレータか通常のジェネレータ・イテレータを受け取り、レスポンスボディをストリームします。
+その場合、*path operation* 関数からURLを直接返せます。
-```Python hl_lines="2 14"
-{!../../../docs_src/custom_response/tutorial007.py!}
-```
+この場合に使用される `status_code` は、`RedirectResponse` のデフォルトである `307` になります。
-#### `StreamingResponse` をファイルライクなオブジェクトとともに使う
+---
-ファイルライクなオブジェクト (例えば、 `open()` で返されたオブジェクト) がある場合、 `StreamingResponse` に含めて返すことができます。
+さらに、`status_code` パラメータを `response_class` パラメータと組み合わせて使うこともできます:
-これにはクラウドストレージとの連携や映像処理など、多くのライブラリが含まれています。
+{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}
-```Python hl_lines="2 10-12 14"
-{!../../../docs_src/custom_response/tutorial008.py!}
-```
+### `StreamingResponse` { #streamingresponse }
-!!! tip "豆知識"
- ここでは `async` や `await` をサポートしていない標準の `open()` を使っているので、通常の `def` でpath operationを宣言していることに注意してください。
+非同期ジェネレータ、または通常のジェネレータ/イテレータ(`yield` を持つ関数)を受け取り、レスポンスボディをストリームします。
-### `FileResponse`
+{* ../../docs_src/custom_response/tutorial007_py310.py hl[3,16] *}
-レスポンスとしてファイルを非同期的にストリームします。
+/// note | 技術詳細
-他のレスポンスタイプとは異なる引数のセットを受け取りインスタンス化します。
+`async` タスクは `await` に到達したときにのみキャンセルできます。`await` がない場合、ジェネレータ(`yield` を持つ関数)は適切にキャンセルできず、キャンセル要求後も実行が続く可能性があります。
-* `path` - ストリームするファイルのファイルパス。
-* `headers` - 含めたい任意のカスタムヘッダーの辞書。
-* `media_type` - メディアタイプを示す文字列。セットされなかった場合は、ファイル名やパスからメディアタイプが推察されます。
-* `filename` - セットされた場合、レスポンスの `Content-Disposition` に含まれます。
+この小さな例では `await` が不要なため、イベントループにキャンセルを処理する機会を与えるために `await anyio.sleep(0)` を追加しています。
-ファイルレスポンスには、適切な `Content-Length` 、 `Last-Modified` 、 `ETag` ヘッダーが含まれます。
+これは大きなストリームや無限ストリームではさらに重要になります。
-```Python hl_lines="2 10"
-{!../../../docs_src/custom_response/tutorial009.py!}
-```
+///
+
+/// tip | 豆知識
+
+`StreamingResponse` を直接返す代わりに、[データをストリームする](./stream-data.md) スタイルに従うことをおすすめします。こちらのほうがはるかに便利で、裏側でキャンセル処理も行ってくれます。
+
+JSON Lines をストリームする場合は、[JSON Lines をストリームする](../tutorial/stream-json-lines.md) チュートリアルを参照してください。
+
+///
+
+### `FileResponse` { #fileresponse }
+
+ファイルをレスポンスとして非同期にストリームします。
-## デフォルトレスポンスクラス
+他のレスポンスタイプとは異なる引数セットでインスタンス化します:
-**FastAPI** クラスのインスタンスか `APIRouter` を生成するときに、デフォルトのレスポンスクラスを指定できます。
+* `path` - ストリームするファイルのファイルパス
+* `headers` - 含めたい任意のカスタムヘッダー(辞書)
+* `media_type` - メディアタイプを示す文字列。未設定の場合、ファイル名やパスから推測されます
+* `filename` - 設定した場合、レスポンスの `Content-Disposition` に含まれます
-定義するためのパラメータは、 `default_response_class` です。
+ファイルレスポンスには、適切な `Content-Length`、`Last-Modified`、`ETag` ヘッダーが含まれます。
-以下の例では、 **FastAPI** は、全ての *path operation* で `JSONResponse` の代わりに `ORJSONResponse` をデフォルトとして利用します。
+{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}
-```Python hl_lines="2 4"
-{!../../../docs_src/custom_response/tutorial010.py!}
+`response_class` パラメータを使うこともできます:
+
+{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}
+
+この場合、*path operation* 関数からファイルパスを直接返せます。
+
+## カスタムレスポンスクラス { #custom-response-class }
+
+`Response` を継承して、独自のカスタムレスポンスクラスを作成し、使用できます。
+
+例えば、[`orjson`](https://github.com/ijl/orjson) を特定の設定で使いたいとします。
+
+インデントされた整形済みJSONを返したいので、orjson のオプション `orjson.OPT_INDENT_2` を使いたいとします。
+
+`CustomORJSONResponse` を作成できます。主に必要なのは、`bytes` を返す `Response.render(content)` メソッドを作ることです:
+
+{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}
+
+これまでは次のように返していたものが:
+
+```json
+{"message": "Hello World"}
+```
+
+...このレスポンスでは次のように返されます:
+
+```json
+{
+ "message": "Hello World"
+}
```
-!!! tip "豆知識"
- 前に見たように、 *path operation* の中で `response_class` をオーバーライドできます。
+もちろん、JSONの整形以外にも、これを活用するもっと良い方法が見つかるはずです。 😉
+
+### `orjson` か レスポンスモデルか { #orjson-or-response-model }
+
+もし求めているのがパフォーマンスであれば、`orjson` レスポンスを使うより、[レスポンスモデル](../tutorial/response-model.md) を使うほうが良い場合が多いです。
+
+レスポンスモデルがあると、FastAPI は中間ステップ(他の場合に行われる `jsonable_encoder` による変換など)を介さずに、Pydantic を使ってデータをJSONにシリアライズします。
+
+内部的には、Pydantic はJSONシリアライズに `orjson` と同じRust由来の仕組みを用いているため、レスポンスモデルを使うだけで最良のパフォーマンスが得られます。
+
+## デフォルトレスポンスクラス { #default-response-class }
+
+**FastAPI** クラスのインスタンスや `APIRouter` を作成する際に、デフォルトで使用するレスポンスクラスを指定できます。
+
+これを定義するパラメータは `default_response_class` です。
+
+以下の例では、**FastAPI** はすべての *path operation* で、JSONの代わりにデフォルトで `HTMLResponse` を使用します。
+
+{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}
+
+/// tip | 豆知識
+
+これまでと同様に、*path operation* ごとに `response_class` をオーバーライドできます。
+
+///
-## その他のドキュメント
+## その他のドキュメント { #additional-documentation }
-また、OpenAPIでは `responses` を使ってメディアタイプやその他の詳細を宣言することもできます: [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}
+OpenAPIでは `responses` を使ってメディアタイプやその他の詳細を宣言することもできます: [OpenAPI の追加レスポンス](additional-responses.md)。
diff --git a/docs/ja/docs/advanced/dataclasses.md b/docs/ja/docs/advanced/dataclasses.md
new file mode 100644
index 0000000000000..e3ad7afb633ff
--- /dev/null
+++ b/docs/ja/docs/advanced/dataclasses.md
@@ -0,0 +1,95 @@
+# Dataclasses の使用 { #using-dataclasses }
+
+FastAPI は **Pydantic** の上に構築されており、これまでにリクエストやレスポンスを宣言するために Pydantic モデルを使う方法を紹介してきました。
+
+しかし FastAPI は、同様の方法で [`dataclasses`](https://docs.python.org/3/library/dataclasses.html) もサポートします:
+
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
+
+これは **Pydantic** によって引き続きサポートされています。Pydantic には [`dataclasses` の内部サポート](https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel) があるためです。
+
+そのため、上記のように明示的に Pydantic を使っていないコードでも、FastAPI は標準の dataclass を Pydantic 独自の dataclass に変換するために Pydantic を使用しています。
+
+そして当然ながら、次の点も同様にサポートされます:
+
+- データ検証
+- データのシリアライズ
+- データのドキュメント化 など
+
+これは Pydantic モデルの場合と同じように動作します。内部的にも同様に Pydantic を使って実現されています。
+
+/// info | 情報
+
+dataclasses は、Pydantic モデルができることをすべては行えない点に留意してください。
+
+そのため、Pydantic モデルを使う必要がある場合もあります。
+
+しかし既存の dataclass が多数あるなら、FastAPI で Web API を構築する際にそれらを活用するちょっとしたテクニックになります。🤓
+
+///
+
+## `response_model` での dataclasses { #dataclasses-in-response-model }
+
+`response_model` パラメータでも `dataclasses` を使用できます:
+
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
+
+dataclass は自動的に Pydantic の dataclass に変換されます。
+
+このため、そのスキーマは API ドキュメントの UI に表示されます:
+
+
+
+## ネストしたデータ構造での dataclasses { #dataclasses-in-nested-data-structures }
+
+`dataclasses` を他の型注釈と組み合わせて、ネストしたデータ構造を作成できます。
+
+場合によっては、自動生成された API ドキュメントでエラーが発生するなどの理由で、Pydantic 版の `dataclasses` を使う必要があるかもしれません。
+
+その場合は、標準の `dataclasses` を `pydantic.dataclasses` に置き換えるだけで済みます。これはドロップイン置換です:
+
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+
+1. 依然として標準の `dataclasses` から `field` をインポートします。
+
+2. `pydantic.dataclasses` は `dataclasses` のドロップイン置換です。
+
+3. `Author` dataclass は `Item` dataclass のリストを含みます。
+
+4. `Author` dataclass を `response_model` パラメータとして使用しています。
+
+5. リクエストボディとしての dataclass と併せて、他の標準の型注釈を使用できます。
+
+ この例では、`Item` dataclass のリストです。
+
+6. ここでは、dataclass のリストである `items` を含む辞書を返しています。
+
+ FastAPI はデータを JSON に シリアライズ できます。
+
+7. ここでは `response_model` に `Author` dataclass のリストという型注釈を使用しています。
+
+ このように、`dataclasses` は標準の型注釈と組み合わせられます。
+
+8. この *path operation 関数* は、`async def` ではなく通常の `def` を使用しています。
+
+ いつもどおり、FastAPI では必要に応じて `def` と `async def` を組み合わせられます。
+
+ どちらをいつ使うかの復習が必要な場合は、[`async` と `await`](../async.md#in-a-hurry) に関するドキュメントの _"In a hurry?"_ セクションを参照してください。
+
+9. この *path operation 関数* は(可能ではありますが)dataclass 自体は返さず、内部データを持つ辞書のリストを返しています。
+
+ FastAPI は dataclass を含む `response_model` パラメータを使ってレスポンスを変換します。
+
+`dataclasses` は他の型注釈と多様な組み合わせが可能で、複雑なデータ構造を構成できます。
+
+上記のコード内コメントのヒントを参照して、より具体的な詳細を確認してください。
+
+## さらに学ぶ { #learn-more }
+
+`dataclasses` を他の Pydantic モデルと組み合わせたり、継承したり、自分のモデルに含めたりもできます。
+
+詳しくは、[dataclasses に関する Pydantic ドキュメント](https://docs.pydantic.dev/latest/concepts/dataclasses/) を参照してください。
+
+## バージョン { #version }
+
+これは FastAPI バージョン `0.67.0` 以降で利用可能です。🔖
diff --git a/docs/ja/docs/advanced/events.md b/docs/ja/docs/advanced/events.md
new file mode 100644
index 0000000000000..e2cbe2eb049e6
--- /dev/null
+++ b/docs/ja/docs/advanced/events.md
@@ -0,0 +1,165 @@
+# Lifespan イベント { #lifespan-events }
+
+アプリケーションが起動する前に一度だけ実行すべきロジック(コード)を定義できます。これは、アプリケーションがリクエストを受け取り始める前に、そのコードが一度だけ実行される、という意味です。
+
+同様に、アプリケーションがシャットダウンするときに実行すべきロジック(コード)も定義できます。この場合、そのコードは、(多くのリクエストを処理した)後に一度だけ実行されます。
+
+このコードは、アプリケーションがリクエストの受け付けを「開始」する前、そして処理を「終了」した直後に実行されるため、アプリケーションの全体の「Lifespan」(この「lifespan」という言葉はすぐ後で重要になります 😉)をカバーします。
+
+これは、アプリ全体で使用し、リクエスト間で「共有」し、かつ後で「クリーンアップ」する必要があるような「リソース」をセットアップするのにとても便利です。たとえば、データベース接続プールや、共有の機械学習モデルの読み込みなどです。
+
+## ユースケース { #use-case }
+
+まずはユースケースの例から始めて、これをどのように解決するかを見ていきます。
+
+リクエストを処理するために使用したい「機械学習モデル」がいくつかあると想像してください。🤖
+
+同じモデルをリクエスト間で共有するので、リクエストごとやユーザーごとに別々のモデルを使うわけではありません。
+
+モデルの読み込みにはディスクから大量のデータを読む必要があり、かなり時間がかかるかもしれません。したがって、リクエストごとに読み込みたくはありません。
+
+モジュール/ファイルのトップレベルで読み込むこともできますが、その場合は、たとえ簡単な自動テストを実行するだけでも「モデルを読み込む」ことになり、そのモデルの読み込みを待つ必要があるため、独立したコード部分を走らせるだけのテストでも「遅く」なってしまいます。
+
+これを解決しましょう。リクエストを処理する前にモデルを読み込みますが、コードがロードされている最中ではなく、アプリケーションがリクエストの受け付けを開始する直前だけにします。
+
+## Lifespan { #lifespan }
+
+この「起動時」と「シャットダウン時」のロジックは、`FastAPI` アプリの `lifespan` パラメータと「コンテキストマネージャ」(これが何かはすぐに示します)を使って定義できます。
+
+まずは例を見てから、詳細を説明します。
+
+次のように、`yield` を使う非同期関数 `lifespan()` を作成します:
+
+{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}
+
+ここでは、`yield` の前で機械学習モデルの辞書に(ダミーの)モデル関数を入れることで、高コストな「起動時」のモデル読み込みをシミュレーションしています。このコードは、アプリケーションがリクエストを「受け付け始める前」に、すなわち起動時に実行されます。
+
+そして `yield` の直後でモデルをアンロードします。このコードは、アプリケーションがリクエスト処理を「終了」した後、シャットダウン直前に実行されます。たとえばメモリや GPU のようなリソースを解放できます。
+
+/// tip | 豆知識
+
+`shutdown` は、アプリケーションを「停止」するときに発生します。
+
+新しいバージョンを開始する必要があるか、単に実行をやめたくなったのかもしれません。🤷
+
+///
+
+### Lifespan 関数 { #lifespan-function }
+
+まず注目すべきは、`yield` を使う非同期関数を定義していることです。これは「yield を使う依存関係(Dependencies)」にとてもよく似ています。
+
+{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}
+
+`yield` の前の前半は、アプリケーションが開始される「前」に実行されます。
+
+`yield` の後半は、アプリケーションの処理が「終了」した「後」に実行されます。
+
+### 非同期コンテキストマネージャ { #async-context-manager }
+
+この関数には `@asynccontextmanager` がデコレートされています。
+
+これにより、この関数は「非同期コンテキストマネージャ」になります。
+
+{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}
+
+Python の「コンテキストマネージャ」は、`with` 文で使えるものです。たとえば、`open()` はコンテキストマネージャとして使えます:
+
+```Python
+with open("file.txt") as file:
+ file.read()
+```
+
+最近の Python には「非同期コンテキストマネージャ」もあります。`async with` で使います:
+
+```Python
+async with lifespan(app):
+ await do_stuff()
+```
+
+このようにコンテキストマネージャ(または非同期コンテキストマネージャ)を作ると、`with` ブロックに入る前に `yield` より前のコードが実行され、`with` ブロックを出た後に `yield` より後ろのコードが実行されます。
+
+上のコード例では直接それを使ってはいませんが、FastAPI に渡して内部で使ってもらいます。
+
+`FastAPI` アプリの `lifespan` パラメータは「非同期コンテキストマネージャ」を受け取るので、新しく作った `lifespan` 非同期コンテキストマネージャを渡せます。
+
+{* ../../docs_src/events/tutorial003_py310.py hl[22] *}
+
+## 代替のイベント(非推奨) { #alternative-events-deprecated }
+
+/// warning | 注意
+
+推奨される方法は、上で説明したとおり `FastAPI` アプリの `lifespan` パラメータを使って「起動」と「シャットダウン」を扱うことです。`lifespan` パラメータを指定すると、`startup` と `shutdown` のイベントハンドラは呼び出されなくなります。`lifespan` かイベントか、どちらか一方であり、両方同時ではありません。
+
+この節は読み飛ばしてもかまいません。
+
+///
+
+起動時とシャットダウン時に実行されるロジックを定義する別の方法もあります。
+
+アプリケーションが起動する前、またはシャットダウンするときに実行する必要があるイベントハンドラ(関数)を定義できます。
+
+これらの関数は `async def` でも、通常の `def` でも構いません。
+
+### `startup` イベント { #startup-event }
+
+アプリケーションが開始される前に実行すべき関数を追加するには、イベント `"startup"` で宣言します:
+
+{* ../../docs_src/events/tutorial001_py310.py hl[8] *}
+
+この場合、`startup` のイベントハンドラ関数は items の「データベース」(単なる `dict`)をいくつかの値で初期化します。
+
+イベントハンドラ関数は複数追加できます。
+
+すべての `startup` イベントハンドラが完了するまで、アプリケーションはリクエストの受け付けを開始しません。
+
+### `shutdown` イベント { #shutdown-event }
+
+アプリケーションがシャットダウンするときに実行すべき関数を追加するには、イベント `"shutdown"` で宣言します:
+
+{* ../../docs_src/events/tutorial002_py310.py hl[6] *}
+
+ここでは、`shutdown` のイベントハンドラ関数が、テキスト行 `"Application shutdown"` をファイル `log.txt` に書き込みます。
+
+/// info | 情報
+
+`open()` 関数の `mode="a"` は「追加」(append)を意味します。つまり、そのファイルに既にある内容を上書きせず、行が後ろに追記されます。
+
+///
+
+/// tip | 豆知識
+
+この例では、ファイルを扱う標準の Python 関数 `open()` を使っています。
+
+そのため、ディスクへの書き込みを「待つ」必要がある I/O(入力/出力)が関わります。
+
+しかし `open()` 自体は `async` や `await` を使いません。
+
+したがって、イベントハンドラ関数は `async def` ではなく通常の `def` で宣言しています。
+
+///
+
+### `startup` と `shutdown` をまとめて { #startup-and-shutdown-together }
+
+起動時とシャットダウン時のロジックは関連していることが多いです。何かを開始してから終了したい、リソースを獲得してから解放したい、などです.
+
+共有するロジックや変数のない別々の関数でそれを行うのは難しく、グローバル変数などに値を保存する必要が出てきます。
+
+そのため、現在は上で説明したとおり `lifespan` を使うことが推奨されています。
+
+## 技術詳細 { #technical-details }
+
+技術が気になる方への細かな詳細です。🤓
+
+内部的には、ASGI の技術仕様において、これは [Lifespan プロトコル](https://asgi.readthedocs.io/en/latest/specs/lifespan.html) の一部であり、`startup` と `shutdown` というイベントが定義されています。
+
+/// info | 情報
+
+Starlette の `lifespan` ハンドラについては、[Starlette の Lifespan ドキュメント](https://www.starlette.dev/lifespan/)で詳しく読むことができます。
+
+コードの他の領域で使える lifespan の状態をどのように扱うかも含まれています。
+
+///
+
+## サブアプリケーション { #sub-applications }
+
+🚨 これらの lifespan イベント(startup と shutdown)はメインのアプリケーションに対してのみ実行され、[サブアプリケーション - マウント](sub-applications.md) には実行されないことに注意してください。
diff --git a/docs/ja/docs/advanced/generate-clients.md b/docs/ja/docs/advanced/generate-clients.md
new file mode 100644
index 0000000000000..b3472880ed700
--- /dev/null
+++ b/docs/ja/docs/advanced/generate-clients.md
@@ -0,0 +1,208 @@
+# SDK の生成 { #generating-sdks }
+
+**FastAPI** は **OpenAPI** 仕様に基づいているため、その API は多くのツールが理解できる標準形式で記述できます。
+
+これにより、最新の**ドキュメント**、複数言語のクライアントライブラリ(**SDKs**)、そしてコードと同期し続ける**テスト**や**自動化ワークフロー**を容易に生成できます。
+
+本ガイドでは、FastAPI バックエンド向けの **TypeScript SDK** を生成する方法を説明します。
+
+## オープンソースの SDK ジェネレータ { #open-source-sdk-generators }
+
+多用途な選択肢として [OpenAPI Generator](https://openapi-generator.tech/) があります。これは**多数のプログラミング言語**をサポートし、OpenAPI 仕様から SDK を生成できます。
+
+**TypeScript クライアント**向けには、[Hey API](https://heyapi.dev/) が目的特化のソリューションで、TypeScript エコシステムに最適化された体験を提供します。
+
+他の SDK ジェネレータは [OpenAPI.Tools](https://openapi.tools/#sdk) でも見つけられます。
+
+/// tip | 豆知識
+
+FastAPI は自動的に **OpenAPI 3.1** の仕様を生成します。したがって、使用するツールはこのバージョンをサポートしている必要があります。
+
+///
+
+## FastAPI スポンサーによる SDK ジェネレータ { #sdk-generators-from-fastapi-sponsors }
+
+このセクションでは、FastAPI をスポンサーしている企業による、**ベンチャー支援**および**企業支援**のソリューションを紹介します。これらの製品は、高品質な生成 SDK に加えて、**追加機能**や**統合**を提供します。
+
+✨ [**FastAPI をスポンサーする**](../help-fastapi.md#sponsor-the-author) ✨ ことで、これらの企業はフレームワークとその**エコシステム**の健全性と**持続可能性**を支援しています。
+
+この支援は、FastAPI の**コミュニティ**(皆さん)への強いコミットメントの表明でもあり、**優れたサービス**の提供だけでなく、堅牢で発展するフレームワーク FastAPI を支える姿勢を示しています。🙇
+
+例えば、次のようなものがあります:
+
+* [Speakeasy](https://speakeasy.com/editor?utm_source=fastapi+repo&utm_medium=github+sponsorship)
+* [Stainless](https://www.stainless.com/?utm_source=fastapi&utm_medium=referral)
+* [liblab](https://developers.liblab.com/tutorials/sdk-for-fastapi?utm_source=fastapi)
+
+これらのソリューションの中にはオープンソースや無料枠を提供するものもあり、金銭的コミットメントなしで試すことができます。他の商用 SDK ジェネレータも存在し、オンラインで見つけられます。🤓
+
+## TypeScript SDK を作成する { #create-a-typescript-sdk }
+
+まずは簡単な FastAPI アプリから始めます:
+
+{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}
+
+ここで、*path operation* はリクエストとレスポンスのペイロードに使用するモデルを定義しており、`Item` と `ResponseMessage` を使っています。
+
+### API ドキュメント { #api-docs }
+
+`/docs` に移動すると、リクエストで送信・レスポンスで受信するデータの**スキーマ**が表示されます:
+
+
+
+これらのスキーマは、アプリ内でモデルとして宣言されているため表示されます。
+
+その情報はアプリの **OpenAPI スキーマ**に含まれ、API ドキュメントに表示されます。
+
+OpenAPI に含まれるこれらのモデル情報を使って、**クライアントコードを生成**できます。
+
+### Hey API { #hey-api }
+
+モデルを備えた FastAPI アプリがあれば、Hey API で TypeScript クライアントを生成できます。最も手早い方法は npx を使うことです。
+
+```sh
+npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
+```
+
+これで TypeScript SDK が `./src/client` に生成されます。
+
+[`@hey-api/openapi-ts` のインストール方法](https://heyapi.dev/openapi-ts/get-started)や、[生成物の詳細](https://heyapi.dev/openapi-ts/output)は公式サイトを参照してください。
+
+### SDK の利用 { #using-the-sdk }
+
+これでクライアントコードを import して利用できます。例えば次のようになり、メソッドに対して補完が効きます:
+
+
+
+送信するペイロードにも補完が適用されます:
+
+
+
+/// tip | 豆知識
+
+FastAPI アプリの `Item` モデルで定義した `name` と `price` に補完が効いている点に注目してください。
+
+///
+
+送信データに対するインラインエラーも表示されます:
+
+
+
+レスポンスオブジェクトにも補完があります:
+
+
+
+## タグ付きの FastAPI アプリ { #fastapi-app-with-tags }
+
+実運用ではアプリは大きくなり、*path operation* のグループ分けにタグを使うことが多いでしょう。
+
+例えば **items** 用と **users** 用のセクションがあり、タグで分けられます:
+
+{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}
+
+### タグ付き TypeScript クライアントの生成 { #generate-a-typescript-client-with-tags }
+
+タグを用いた FastAPI アプリからクライアントを生成すると、通常クライアント側のコードもタグごとに分割されます。
+
+これにより、クライアントコードも正しく整理・グルーピングされます:
+
+
+
+この例では次のようになります:
+
+* `ItemsService`
+* `UsersService`
+
+### クライアントのメソッド名 { #client-method-names }
+
+現状では、生成されるメソッド名(`createItemItemsPost` など)はあまりきれいではありません:
+
+```TypeScript
+ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
+```
+
+これは、クライアントジェネレータが各 *path operation* の OpenAPI 内部の **operation ID** を用いるためです。
+
+OpenAPI では operation ID は全ての *path operation* を通して一意である必要があります。そのため FastAPI は**関数名**、**パス**、**HTTP メソッド/オペレーション**を組み合わせて operation ID を生成し、一意性を保証します。
+
+次にこれを改善する方法を示します。🤓
+
+## カスタム operation ID とより良いメソッド名 { #custom-operation-ids-and-better-method-names }
+
+operation ID の**生成方法**を**変更**して簡潔にし、クライアント側の**メソッド名をシンプル**にできます。
+
+この場合でも各 operation ID が**一意**であることは別の方法で保証する必要があります。
+
+例えば、各 *path operation* にタグを付け、**タグ**と *path operation* の**名前**(関数名)から operation ID を生成できます。
+
+### 一意 ID 生成関数のカスタマイズ { #custom-generate-unique-id-function }
+
+FastAPI は各 *path operation* に**一意 ID**を用いており、これは **operation ID** のほか、必要に応じてリクエストやレスポンスのカスタムモデル名にも使われます。
+
+この関数はカスタマイズ可能です。`APIRoute` を受け取り、文字列を返します。
+
+例えばここでは、最初のタグ(通常は 1 つ)と *path operation* 名(関数名)を使います。
+
+そのカスタム関数を **FastAPI** の `generate_unique_id_function` パラメータに渡します:
+
+{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}
+
+### カスタム operation ID で TypeScript クライアントを生成 { #generate-a-typescript-client-with-custom-operation-ids }
+
+この状態でクライアントを再生成すると、メソッド名が改善されています:
+
+
+
+ご覧のとおり、メソッド名はタグ名と関数名のみになり、URL パスや HTTP オペレーションの情報は含まれません。
+
+### クライアント生成向けの OpenAPI 仕様の前処理 { #preprocess-the-openapi-specification-for-the-client-generator }
+
+それでも生成コードには**重複情報**が残っています。
+
+`ItemsService`(タグ由来)から items 関連であることはすでに分かるのに、メソッド名にもタグ名が前置されています。😕
+
+OpenAPI 全体としては operation ID の**一意性**のために、このプレフィックスを維持したい場合があるでしょう。
+
+しかし生成クライアント用には、クライアントを生成する直前に OpenAPI の operation ID を**加工**して、メソッド名をより**見やすく**、**クリーン**にできます。
+
+OpenAPI の JSON を `openapi.json` として保存し、次のようなスクリプトで**そのタグのプレフィックスを除去**できます:
+
+{* ../../docs_src/generate_clients/tutorial004_py310.py *}
+
+//// tab | Node.js
+
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
+```
+
+////
+
+これにより operation ID は `items-get_items` のような形から単なる `get_items` に置き換わり、クライアントジェネレータはより簡潔なメソッド名を生成できます。
+
+### 前処理済み OpenAPI から TypeScript クライアントを生成 { #generate-a-typescript-client-with-the-preprocessed-openapi }
+
+生成元が `openapi.json` になったので、入力の場所を更新します:
+
+```sh
+npx @hey-api/openapi-ts -i ./openapi.json -o src/client
+```
+
+新しいクライアントを生成すると、**クリーンなメソッド名**になり、**補完**や**インラインエラー**などもそのまま利用できます:
+
+
+
+## 利点 { #benefits }
+
+自動生成されたクライアントを使うと、次のような対象で**補完**が得られます:
+
+* メソッド
+* 本体のリクエストペイロード、クエリパラメータ等
+* レスポンスのペイロード
+
+また、あらゆる箇所で**インラインエラー**も得られます。
+
+バックエンドコードを更新してフロントエンドを**再生成**すれば、新しい *path operation* はメソッドとして追加され、古いものは削除され、その他の変更も生成コードに反映されます。🤓
+
+つまり、変更があれば自動的にクライアントコードに**反映**されます。クライアントを**ビルド**すれば、使用データに**不整合**があればエラーになります。
+
+その結果、多くのエラーを開発の初期段階で**早期発見**でき、本番で最終ユーザーに不具合が現れてから原因をデバッグする必要がなくなります。✨
diff --git a/docs/ja/docs/advanced/index.md b/docs/ja/docs/advanced/index.md
index 0732fc405acf4..026405318f8e0 100644
--- a/docs/ja/docs/advanced/index.md
+++ b/docs/ja/docs/advanced/index.md
@@ -1,24 +1,21 @@
-# 高度なユーザーガイド
+# 高度なユーザーガイド { #advanced-user-guide }
-## さらなる機能
+## さらなる機能 { #additional-features }
-[チュートリアル - ユーザーガイド](../tutorial/){.internal-link target=_blank}により、**FastAPI**の主要な機能は十分に理解できたことでしょう。
+メインの[チュートリアル - ユーザーガイド](../tutorial/index.md)だけで、**FastAPI**の主要な機能を一通り把握するには十分なはずです。
-以降のセクションでは、チュートリアルでは説明しきれなかったオプションや設定、および機能について説明します。
+以降のセクションでは、その他のオプション、設定、追加機能を見ていきます。
-!!! tip "豆知識"
- 以降のセクションは、 **必ずしも"応用編"ではありません**。
+/// tip | 豆知識
- ユースケースによっては、その中から解決策を見つけられるかもしれません。
+以降のセクションは、**必ずしも「高度」ではありません**。
-## 先にチュートリアルを読む
+また、あなたのユースケースに対する解決策が、その中のどれかにある可能性もあります。
-[チュートリアル - ユーザーガイド](../tutorial/){.internal-link target=_blank}の知識があれば、**FastAPI**の主要な機能を利用することができます。
+///
-以降のセクションは、すでにチュートリアルを読んで、その主要なアイデアを理解できていることを前提としています。
+## 先にチュートリアルを読む { #read-the-tutorial-first }
-## テスト駆動開発のコース
+メインの[チュートリアル - ユーザーガイド](../tutorial/index.md)で得た知識があれば、**FastAPI**の機能の多くは引き続き利用できます。
-このセクションの内容を補完するために脱初心者用コースを受けたい場合は、**TestDriven.io**による、Test-Driven Development with FastAPI and Dockerを確認するのがよいかもしれません。
-
-現在、このコースで得られた利益の10%が**FastAPI**の開発のために寄付されています。🎉 😄
+また、以降のセクションでは、すでにそれを読んでいて、主要な考え方を理解していることを前提としています。
diff --git a/docs/ja/docs/advanced/json-base64-bytes.md b/docs/ja/docs/advanced/json-base64-bytes.md
new file mode 100644
index 0000000000000..c3c361a96b4d7
--- /dev/null
+++ b/docs/ja/docs/advanced/json-base64-bytes.md
@@ -0,0 +1,63 @@
+# Base64 にしたバイトを含む JSON { #json-with-bytes-as-base64 }
+
+アプリで JSON データの受信・送信が必要だが、その中にバイナリデータを含める必要がある場合は、base64 にエンコードできます。
+
+## Base64 とファイル { #base64-vs-files }
+
+バイナリデータのアップロードにはまず、JSON にエンコードする代わりに [Request Files](../tutorial/request-files.md) を、バイナリデータの送信には [カスタムレスポンス - FileResponse](./custom-response.md#fileresponse--fileresponse-) を使えるか検討してください。
+
+JSON は UTF-8 でエンコードされた文字列のみを含められるため、生のバイト列は含められません。
+
+Base64 はバイナリデータを文字列にエンコードできますが、そのために元のバイナリより多くの文字を使用する必要があり、通常は通常のファイルより非効率です。
+
+JSON にバイナリデータをどうしても含める必要があり、ファイルを使えない場合にのみ base64 を使用してください。
+
+## Pydantic `bytes` { #pydantic-bytes }
+
+Pydantic モデルで `bytes` 型のフィールドを宣言し、モデル設定で `val_json_bytes` を使うと、入力 JSON データの検証時に base64 を用いるよう指示できます。この検証の一環として、base64 文字列はバイト列へデコードされます。
+
+{* ../../docs_src/json_base64_bytes/tutorial001_py310.py ln[1:9,29:35] hl[9] *}
+
+「/docs」を確認すると、`data` フィールドが base64 でエンコードされたバイト列を期待していることが表示されます。
+
+
+awaitを使用していないので、私たちは`async def`ではなく通常の`def`で関数を宣言する必要があります。
-
-また、Couchbaseは単一の`Bucket`オブジェクトを複数のスレッドで使用しないことを推奨していますので、単に直接Bucketを取得して関数に渡すことが出来ます。
-
-```Python hl_lines="49-53"
-{!../../../docs_src/nosql_databases/tutorial001.py!}
-```
-
-## まとめ
-
-他のサードパーティ製のNoSQLデータベースを利用する場合でも、そのデータベースの標準ライブラリを利用するだけで利用できます。
-
-他の外部ツール、システム、APIについても同じことが言えます。
diff --git a/docs/ja/docs/advanced/openapi-callbacks.md b/docs/ja/docs/advanced/openapi-callbacks.md
new file mode 100644
index 0000000000000..31d17e270b677
--- /dev/null
+++ b/docs/ja/docs/advanced/openapi-callbacks.md
@@ -0,0 +1,186 @@
+# OpenAPI コールバック { #openapi-callbacks }
+
+あなたは、*path operation* を持つ API を作成し、他者(多くの場合、あなたの API を「利用する」同一の開発者)が作成した *外部 API* へリクエストをトリガーできるようにできます。
+
+あなたの API アプリが *外部 API* を呼び出すときに起きる処理は「コールバック」と呼ばれます。なぜなら、外部開発者が作成したソフトウェアがあなたの API にリクエストを送り、その後であなたの API が「呼び返し」、*外部 API*(おそらく同じ開発者が作成)へリクエストを送るためです。
+
+この場合、その *外部 API* がどのようである「べき」かをドキュメント化したくなるでしょう。どんな *path operation* を持ち、どんなボディを受け取り、どんなレスポンスを返すか、などです。
+
+## コールバックのあるアプリ { #an-app-with-callbacks }
+
+例で見ていきます。
+
+あなたが請求書を作成できるアプリを開発していると想像してください。
+
+これらの請求書は `id`、`title`(任意)、`customer`、`total` を持ちます。
+
+あなたの API の利用者(外部開発者)は、POST リクエストであなたの API に請求書を作成します。
+
+その後、あなたの API は(仮にこうしましょう):
+
+* 外部開発者の顧客に請求書を送ります。
+* 代金を回収します。
+* API 利用者(外部開発者)に通知を送り返します。
+ * これは(あなたの API から)外部開発者が提供する *外部 API* に POST リクエストを送ることで行われます(これが「コールバック」です)。
+
+## 通常の FastAPI アプリ { #the-normal-fastapi-app }
+
+まず、コールバックを追加する前の通常の API アプリがどうなるか見てみましょう。
+
+`Invoice` ボディを受け取り、クエリパラメータ `callback_url` にコールバック用の URL を含める *path operation* を持ちます。
+
+この部分はとても普通で、ほとんどのコードはすでに見覚えがあるはずです:
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[7:11,34:51] *}
+
+/// tip | 豆知識
+
+`callback_url` クエリパラメータは、Pydantic の [Url](https://docs.pydantic.dev/latest/api/networks/) 型を使用します。
+
+///
+
+唯一の新しい点は、*path operation デコレータ*の引数として `callbacks=invoices_callback_router.routes` を渡すことです。これが何かは次で見ます。
+
+## コールバックのドキュメント化 { #documenting-the-callback }
+
+実際のコールバックのコードは、あなた自身の API アプリに大きく依存します。
+
+そしてアプリごとに大きく異なるでしょう。
+
+それは次のように 1、2 行のコードかもしれません:
+
+```Python
+callback_url = "https://example.com/api/v1/invoices/events/"
+httpx.post(callback_url, json={"description": "Invoice paid", "paid": True})
+```
+
+しかし、おそらくコールバックで最も重要な点は、あなたの API 利用者(外部開発者)が、*あなたの API* がコールバックのリクエストボディなどで送るデータに従って、*外部 API* を正しく実装することを確実にすることです。
+
+そこで次に行うのは、*あなたの API* からのコールバックを受け取るために、その *外部 API* がどうあるべきかをドキュメント化するコードを追加することです。
+
+そのドキュメントはあなたの API の `/docs` の Swagger UI に表示され、外部開発者に *外部 API* の作り方を知らせます。
+
+この例ではコールバック自体は実装しません(それは 1 行のコードでもよいでしょう)。ドキュメント部分のみです。
+
+/// tip | 豆知識
+
+実際のコールバックは単なる HTTP リクエストです。
+
+自分でコールバックを実装する場合は、[HTTPX](https://www.python-httpx.org) や [Requests](https://requests.readthedocs.io/) のようなものを使えます。
+
+///
+
+## コールバックのドキュメント用コードを書く { #write-the-callback-documentation-code }
+
+このコードはあなたのアプリで実行されません。*外部 API* がどうあるべきかをドキュメント化するためだけに必要です。
+
+しかし、あなたはすでに **FastAPI** で API の自動ドキュメントを簡単に作る方法を知っています。
+
+その知識を使って、*外部 API* がどうあるべきかをドキュメント化します……つまり、外部 API が実装すべき *path operation(s)*(あなたの API が呼び出すもの)を作成します。
+
+/// tip | 豆知識
+
+コールバックをドキュメント化するコードを書くときは、あなたがその「外部開発者」だと想像するのが役に立つかもしれません。いま実装しているのは「あなたの API」ではなく、*外部 API* です。
+
+この(外部開発者の)視点を一時的に採用すると、その *外部 API* に対してパラメータ、ボディ用の Pydantic モデル、レスポンスなどをどこに置くのが自然かがより明確に感じられるでしょう。
+
+///
+
+### コールバック用 APIRouter を作成 { #create-a-callback-apirouter }
+
+まず、1 つ以上のコールバックを含む新しい `APIRouter` を作成します。
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[1,23] *}
+
+### コールバックの path operation を作成 { #create-the-callback-path-operation }
+
+上で作成したのと同じ `APIRouter` を使って、コールバックの *path operation* を作成します。
+
+見た目は通常の FastAPI の *path operation* と同じです:
+
+* 受け取るボディの宣言(例: `body: InvoiceEvent`)が必要でしょう。
+* 返すレスポンスの宣言(例: `response_model=InvoiceEventReceived`)も持てます。
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[14:16,19:20,26:30] *}
+
+通常の *path operation* と異なる主な点が 2 つあります:
+
+* 実際のコードは不要です。あなたのアプリはこのコードを決して呼びません。これは *外部 API* をドキュメント化するためだけに使われます。したがって、関数本体は `pass` で構いません。
+* *パス* には、*あなたの API* に送られた元のリクエストのパラメータや一部を変数として使える [OpenAPI 3 の式](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#key-expression)(後述)を含められます。
+
+### コールバックのパス式 { #the-callback-path-expression }
+
+コールバックの *パス* には、*あなたの API* に送られた元のリクエストの一部を含められる [OpenAPI 3 の式](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#key-expression)を使用できます。
+
+この例では、`str` は次のとおりです:
+
+```Python
+"{$callback_url}/invoices/{$request.body.id}"
+```
+
+つまり、あなたの API 利用者(外部開発者)が *あなたの API* に次のようにリクエストを送った場合:
+
+```
+https://yourapi.com/invoices/?callback_url=https://www.external.org/events
+```
+
+JSON ボディは:
+
+```JSON
+{
+ "id": "2expen51ve",
+ "customer": "Mr. Richie Rich",
+ "total": "9999"
+}
+```
+
+その後 *あなたの API* は請求書を処理し、のちほど `callback_url`(*外部 API*)へコールバックのリクエストを送ります:
+
+```
+https://www.external.org/events/invoices/2expen51ve
+```
+
+JSON ボディは次のような内容です:
+
+```JSON
+{
+ "description": "Payment celebration",
+ "paid": true
+}
+```
+
+そして *外部 API* からは次のような JSON ボディのレスポンスを期待します:
+
+```JSON
+{
+ "ok": true
+}
+```
+
+/// tip | 豆知識
+
+使用されるコールバック URL には、クエリパラメータ `callback_url`(`https://www.external.org/events`)で受け取った URL と、JSON ボディ内の請求書 `id`(`2expen51ve`)が含まれている点に注目してください。
+
+///
+
+### コールバック用ルーターを追加 { #add-the-callback-router }
+
+これで、上で作成したコールバック用ルーター内に、必要なコールバックの *path operation(s)*(*外部開発者* が *外部 API* に実装すべきもの)が用意できました。
+
+次に、*あなたの API の path operation デコレータ*の `callbacks` パラメータに、そのコールバック用ルーターの属性 `.routes`(実体はルート/*path operations* の `list`)を渡します:
+
+{* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[33] *}
+
+/// tip | 豆知識
+
+`callback=` に渡すのはルーター本体(`invoices_callback_router`)ではなく、属性 `.routes`(`invoices_callback_router.routes`)である点に注意してください。
+
+///
+
+### ドキュメントを確認 { #check-the-docs }
+
+アプリを起動して [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) にアクセスします。
+
+あなたの *path operation* に「Callbacks」セクションが含まれ、*外部 API* がどうあるべきかが表示されているのが確認できます:
+
+
diff --git a/docs/ja/docs/advanced/openapi-webhooks.md b/docs/ja/docs/advanced/openapi-webhooks.md
new file mode 100644
index 0000000000000..7f7a7268072a9
--- /dev/null
+++ b/docs/ja/docs/advanced/openapi-webhooks.md
@@ -0,0 +1,55 @@
+# OpenAPI の Webhook { #openapi-webhooks }
+
+アプリがある種の**イベント**を**通知**するために、データ付きで相手のアプリ(リクエスト送信)を呼び出す可能性があることを、API の**ユーザー**に伝えたい場合があります。
+
+これは、通常のようにユーザーがあなたの API にリクエストを送るのではなく、**あなたの API(あなたのアプリ)**が**相手のシステム**(相手の API、アプリ)にリクエストを送る、ということです。
+
+これは一般に**Webhook**と呼ばれます。
+
+## Webhook の手順 { #webhooks-steps }
+
+通常の流れとして、まずあなたのコード内で、送信するメッセージ、すなわちリクエストの**本文(ボディ)**を**定義**します。
+
+加えて、アプリがそれらのリクエスト(イベント)を送信する**タイミング**も何らかの形で定義します。
+
+そして**ユーザー**は、アプリがそのリクエストを送るべき**URL**を(たとえばどこかの Web ダッシュボードで)定義します。
+
+Webhook の URL を登録する方法や実際にリクエストを送るコードなど、これらの**ロジック**はすべてあなた次第です。**あなた自身のコード**で好きなように実装します。
+
+## FastAPI と OpenAPI による Webhook のドキュメント化 { #documenting-webhooks-with-fastapi-and-openapi }
+
+**FastAPI** と OpenAPI を使うと、Webhook の名前、アプリが送信できる HTTP の操作(例: `POST`, `PUT` など)、アプリが送るリクエストの**ボディ**を定義できます。
+
+これにより、ユーザーがあなたの **Webhook** リクエストを受け取るための**API を実装**するのが大幅に簡単になります。場合によっては、ユーザーが自分たちの API コードを自動生成できるかもしれません。
+
+/// info | 情報
+
+Webhook は OpenAPI 3.1.0 以上で利用可能で、FastAPI `0.99.0` 以上が対応しています。
+
+///
+
+## Webhook を持つアプリ { #an-app-with-webhooks }
+
+**FastAPI** アプリケーションを作成すると、`webhooks` という属性があり、ここで *path operations* と同様に(例: `@app.webhooks.post()`)*webhook* を定義できます。
+
+{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}
+
+定義した webhook は **OpenAPI** スキーマおよび自動生成される **ドキュメント UI** に反映されます。
+
+/// info | 情報
+
+`app.webhooks` オブジェクトは実際には単なる `APIRouter` で、複数ファイルでアプリを構成する際に使うものと同じ型です。
+
+///
+
+Webhook では(`/items/` のような)*パス*を宣言しているわけではない点に注意してください。ここで渡す文字列は webhook の**識別子**(イベント名)です。たとえば `@app.webhooks.post("new-subscription")` での webhook 名は `new-subscription` です。
+
+これは、**ユーザー**が実際に Webhook リクエストを受け取りたい**URL パス**を、別の方法(例: Web ダッシュボード)で定義することを想定しているためです。
+
+### ドキュメントの確認 { #check-the-docs }
+
+アプリを起動し、[http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) にアクセスします。
+
+ドキュメントには通常の *path operations* に加えて、**webhooks** も表示されます:
+
+
diff --git a/docs/ja/docs/advanced/path-operation-advanced-configuration.md b/docs/ja/docs/advanced/path-operation-advanced-configuration.md
index 35b381cae040c..65b56dba4ced8 100644
--- a/docs/ja/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/ja/docs/advanced/path-operation-advanced-configuration.md
@@ -1,52 +1,172 @@
-# Path Operationの高度な設定
+# Path Operationの高度な設定 { #path-operation-advanced-configuration }
-## OpenAPI operationId
+## OpenAPI operationId { #openapi-operationid }
-!!! warning "注意"
- あなたがOpenAPIの「エキスパート」でなければ、これは必要ないかもしれません。
+/// warning | 注意
+
+OpenAPIの「エキスパート」でなければ、これはおそらく必要ありません。
+
+///
*path operation* で `operation_id` パラメータを利用することで、OpenAPIの `operationId` を設定できます。
-`operation_id` は各オペレーションで一意にする必要があります。
+各オペレーションで一意になるようにする必要があります。
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
-### *path operation関数* の名前をoperationIdとして使用する
+### *path operation関数* の名前をoperationIdとして使用する { #using-the-path-operation-function-name-as-the-operationid }
-APIの関数名を `operationId` として利用したい場合、すべてのAPIの関数をイテレーションし、各 *path operation* の `operationId` を `APIRoute.name` で上書きすれば可能です。
+APIの関数名を `operationId` として利用したい場合、すべてのAPI関数をイテレーションし、各 *path operation* の `operation_id` を `APIRoute.name` で上書きすれば可能です。
-そうする場合は、すべての *path operation* を追加した後に行う必要があります。
+すべての *path operation* を追加した後に行うべきです。
-```Python hl_lines="2 12-21 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *}
-!!! tip "豆知識"
- `app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。
+/// tip | 豆知識
-!!! warning "注意"
- この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。
+`app.openapi()` を手動で呼び出す場合、その前に `operationId` を更新するべきです。
- それらが異なるモジュール (Pythonファイル) にあるとしてもです。
+///
-## OpenAPIから除外する
+/// warning | 注意
-生成されるOpenAPIスキーマ (つまり、自動ドキュメント生成の仕組み) から *path operation* を除外するには、 `include_in_schema` パラメータを `False` にします。
+この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
-```
+異なるモジュール(Pythonファイル)にある場合でも同様です。
+
+///
+
+## OpenAPIから除外する { #exclude-from-openapi }
+
+生成されるOpenAPIスキーマ(つまり、自動ドキュメント生成の仕組み)から *path operation* を除外するには、`include_in_schema` パラメータを使用して `False` に設定します。
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}
+
+## docstringによる説明の高度な設定 { #advanced-description-from-docstring }
+
+*path operation関数* のdocstringからOpenAPIに使用する行を制限できます。
+
+`\f`(エスケープされた「書式送り(form feed)」文字)を追加すると、**FastAPI** はその地点でOpenAPIに使用される出力を切り詰めます。
+
+ドキュメントには表示されませんが、他のツール(Sphinxなど)は残りの部分を利用できます。
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}
+
+## 追加レスポンス { #additional-responses }
+
+*path operation* に対して `response_model` と `status_code` を宣言する方法はすでに見たことがあるでしょう。
+
+それにより、*path operation* のメインのレスポンスに関するメタデータが定義されます。
+
+追加のレスポンスについても、モデルやステータスコードなどとともに宣言できます。
+
+これについてはドキュメントに章全体があります。 [OpenAPIの追加レスポンス](additional-responses.md) で読めます。
+
+## OpenAPI Extra { #openapi-extra }
+
+アプリケーションで *path operation* を宣言すると、**FastAPI** はOpenAPIスキーマに含めるために、その *path operation* に関連するメタデータを自動的に生成します。
+
+/// note | 技術詳細
+
+OpenAPI仕様では [Operation Object](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object) と呼ばれています。
+
+///
+
+これには *path operation* に関するすべての情報が含まれ、自動ドキュメントを生成するために使われます。
+
+`tags`、`parameters`、`requestBody`、`responses` などが含まれます。
+
+この *path operation* 固有のOpenAPIスキーマは通常 **FastAPI** により自動生成されますが、拡張することもできます。
+
+/// tip | 豆知識
-## docstringによる説明の高度な設定
+これは低レベルな拡張ポイントです。
-*path operation関数* のdocstringからOpenAPIに使用する行を制限することができます。
+追加レスポンスを宣言するだけなら、より便利な方法として [OpenAPIの追加レスポンス](additional-responses.md) を使うことができます。
-`\f` (「書式送り (Form Feed)」のエスケープ文字) を付与することで、**FastAPI** はOpenAPIに使用される出力をその箇所までに制限します。
+///
-ドキュメントには表示されませんが、他のツール (例えばSphinx) では残りの部分を利用できるでしょう。
+`openapi_extra` パラメータを使って、*path operation* のOpenAPIスキーマを拡張できます。
-```Python hl_lines="19-29"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
+### OpenAPI Extensions { #openapi-extensions }
+
+この `openapi_extra` は、例えば [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) を宣言するのに役立ちます。
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py310.py hl[6] *}
+
+自動APIドキュメントを開くと、その拡張は特定の *path operation* の下部に表示されます。
+
+
+
+そして(APIの `/openapi.json` にある)生成されたOpenAPIを見ると、その拡張も特定の *path operation* の一部として確認できます。
+
+```JSON hl_lines="22"
+{
+ "openapi": "3.1.0",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0"
+ },
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ }
+ },
+ "x-aperture-labs-portal": "blue"
+ }
+ }
+ }
+}
```
+
+### カスタムOpenAPI *path operation* スキーマ { #custom-openapi-path-operation-schema }
+
+`openapi_extra` 内の辞書は、*path operation* 用に自動生成されたOpenAPIスキーマと深くマージされます。
+
+そのため、自動生成されたスキーマに追加データを加えることができます。
+
+例えば、Pydanticを使ったFastAPIの自動機能を使わずに独自のコードでリクエストを読み取り・検証することを選べますが、それでもOpenAPIスキーマでリクエストを定義したい場合があります。
+
+それは `openapi_extra` で行えます。
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py310.py hl[19:36, 39:40] *}
+
+この例では、Pydanticモデルを一切宣言していません。実際、リクエストボディはJSONとして パース されず、直接 `bytes` として読み取られます。そして `magic_data_reader()` 関数が、何らかの方法でそれをパースする責務を担います。
+
+それでも、リクエストボディに期待されるスキーマを宣言できます。
+
+### カスタムOpenAPI content type { #custom-openapi-content-type }
+
+同じトリックを使って、PydanticモデルでJSON Schemaを定義し、それを *path operation* 用のカスタムOpenAPIスキーマセクションに含めることができます。
+
+また、リクエスト内のデータ型がJSONでない場合でもこれを行えます。
+
+例えばこのアプリケーションでは、PydanticモデルからJSON Schemaを抽出するFastAPIの統合機能や、JSONの自動バリデーションを使っていません。実際、リクエストのcontent typeをJSONではなくYAMLとして宣言しています。
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[15:20, 22] *}
+
+それでも、デフォルトの統合機能を使っていないにもかかわらず、YAMLで受け取りたいデータのために、Pydanticモデルを使って手動でJSON Schemaを生成しています。
+
+そしてリクエストを直接使い、ボディを `bytes` として抽出します。これは、FastAPIがリクエストペイロードをJSONとしてパースしようとすらしないことを意味します。
+
+その後、コード内でそのYAMLコンテンツを直接パースし、さらに同じPydanticモデルを使ってYAMLコンテンツを検証しています。
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *}
+
+/// tip | 豆知識
+
+ここでは同じPydanticモデルを再利用しています。
+
+ただし同様に、別の方法で検証することもできます。
+
+///
diff --git a/docs/ja/docs/advanced/response-change-status-code.md b/docs/ja/docs/advanced/response-change-status-code.md
new file mode 100644
index 0000000000000..22f5f37018c7f
--- /dev/null
+++ b/docs/ja/docs/advanced/response-change-status-code.md
@@ -0,0 +1,31 @@
+# レスポンス - ステータスコードの変更 { #response-change-status-code }
+
+すでに、デフォルトの[レスポンスのステータスコード](../tutorial/response-status-code.md)を設定できることをご存知かもしれません。
+
+しかし場合によっては、デフォルトとは異なるステータスコードを返す必要があります。
+
+## ユースケース { #use-case }
+
+たとえば、デフォルトでは HTTP ステータスコード "OK" `200` を返したいとします。
+
+しかし、データが存在しなければそれを作成し、HTTP ステータスコード "CREATED" `201` を返したい。
+
+それでも、返すデータは `response_model` でフィルタ・変換できるようにしておきたい。
+
+そのような場合は `Response` パラメータを使えます。
+
+## `Response` パラメータを使う { #use-a-response-parameter }
+
+*path operation* 関数で `Response` 型のパラメータを宣言できます(Cookie やヘッダーと同様です)。
+
+そして、その*一時的な*レスポンスオブジェクトに `status_code` を設定できます。
+
+{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}
+
+その後は通常どおり、必要な任意のオブジェクト(`dict`、データベースモデルなど)を返せます。
+
+そして `response_model` を宣言していれば、返したオブジェクトのフィルタと変換には引き続きそれが使われます。
+
+**FastAPI** はその*一時的な*レスポンスからステータスコード(および Cookie とヘッダー)を取り出し、`response_model` によってフィルタ済みの返却値を含む最終的なレスポンスに反映します。
+
+また、`Response` パラメータは依存関係内に宣言してステータスコードを設定することもできます。ただし、最後に設定されたものが優先される点に注意してください。
diff --git a/docs/ja/docs/advanced/response-cookies.md b/docs/ja/docs/advanced/response-cookies.md
new file mode 100644
index 0000000000000..c395b09c62d9e
--- /dev/null
+++ b/docs/ja/docs/advanced/response-cookies.md
@@ -0,0 +1,51 @@
+# レスポンスの Cookie { #response-cookies }
+
+## `Response` パラメータを使う { #use-a-response-parameter }
+
+*path operation 関数*で `Response` 型のパラメータを宣言できます。
+
+そして、その*一時的*なレスポンスオブジェクトに Cookie を設定できます。
+
+{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}
+
+その後は通常どおり、必要な任意のオブジェクト(`dict`、データベースモデルなど)を返せます。
+
+`response_model` を宣言している場合でも、返したオブジェクトは引き続きフィルタおよび変換されます。
+
+**FastAPI** はその*一時的*なレスポンスから Cookie(およびヘッダーやステータスコード)を取り出し、`response_model` によってフィルタされた返却値を含む最終的なレスポンスに設定します。
+
+`Response` パラメータは依存関係でも宣言でき、そこで Cookie(やヘッダー)を設定することも可能です。
+
+## `Response` を直接返す { #return-a-response-directly }
+
+コードで `Response` を直接返すときに、Cookie を作成することもできます。
+
+そのためには、[Response を直接返す](response-directly.md) で説明されているとおりにレスポンスを作成します。
+
+そのレスポンスに Cookie を設定してから返します:
+
+{* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *}
+
+/// tip | 豆知識
+
+`Response` パラメータを使わずにレスポンスを直接返す場合、FastAPI はそのレスポンスをそのまま返します。
+
+そのため、データの型が正しいことを確認する必要があります。例えば、`JSONResponse` を返すなら、JSON と互換性がある必要があります。
+
+また、`response_model` によってフィルタされるべきデータを送っていないことも確認してください。
+
+///
+
+### 詳細情報 { #more-info }
+
+/// note | 技術詳細
+
+`from starlette.responses import Response` や `from starlette.responses import JSONResponse` を使うこともできます。
+
+**FastAPI** は開発者の利便性のために、`starlette.responses` と同じものを `fastapi.responses` として提供しています。ただし、利用可能なレスポンスの大半は Starlette から直接提供されています。
+
+また、`Response` はヘッダーや Cookie の設定に頻繁に使われるため、`fastapi.Response` としても提供されています。
+
+///
+
+利用可能なすべてのパラメータやオプションについては、[Starlette のドキュメント](https://www.starlette.dev/responses/#set-cookie)を参照してください。
diff --git a/docs/ja/docs/advanced/response-directly.md b/docs/ja/docs/advanced/response-directly.md
index 10ec885488087..b5c9fc5cbfc50 100644
--- a/docs/ja/docs/advanced/response-directly.md
+++ b/docs/ja/docs/advanced/response-directly.md
@@ -1,21 +1,28 @@
-# レスポンスを直接返す
+# レスポンスを直接返す { #return-a-response-directly }
-**FastAPI** の *path operation* では、通常は任意のデータを返すことができます: 例えば、 `dict`、`list`、Pydanticモデル、データベースモデルなどです。
+**FastAPI** の *path operation* では、通常は任意のデータを返すことができます: 例えば、`dict`、`list`、Pydanticモデル、データベースモデルなどです。
-デフォルトでは、**FastAPI** は [JSON互換エンコーダ](../tutorial/encoder.md){.internal-link target=_blank} で説明されている `jsonable_encoder` により、返す値を自動的にJSONに変換します。
+[レスポンスモデル](../tutorial/response-model.md) を宣言した場合、FastAPI は Pydantic を使ってデータをJSONにシリアライズします。
-このとき背後では、JSON互換なデータ (例えば`dict`) を、クライアントへ送信されるレスポンスとして利用される `JSONResponse` の中に含めます。
+レスポンスモデルを宣言しない場合、FastAPI は [JSON互換エンコーダ](../tutorial/encoder.md) で説明されている `jsonable_encoder` を使用し、その結果を `JSONResponse` に入れます。
-しかし、*path operation* から `JSONResponse` を直接返すこともできます。
+また、`JSONResponse` を直接作成して返すこともできます。
-これは例えば、カスタムヘッダーやcookieを返すときに便利です。
+/// tip
-## `Response` を返す
+通常は、`JSONResponse` を直接返すよりも、[レスポンスモデル](../tutorial/response-model.md) を使うほうがパフォーマンスが大幅に良くなります。これは、Pydantic によるシリアライズが Rust で実行されるためです。
+
+///
+
+## `Response` を返す { #return-a-response }
実際は、`Response` やそのサブクラスを返すことができます。
-!!! tip "豆知識"
- `JSONResponse` それ自体は、 `Response` のサブクラスです。
+/// info
+
+`JSONResponse` それ自体は、`Response` のサブクラスです。
+
+///
`Response` を返した場合は、**FastAPI** は直接それを返します。
@@ -23,7 +30,9 @@
これは多くの柔軟性を提供します。任意のデータ型を返したり、任意のデータ宣言やバリデーションをオーバーライドできます。
-## `jsonable_encoder` を `Response` の中で使う
+同時に多くの責任も伴います。返すデータが正しく、正しいフォーマットであり、シリアライズ可能であることなどを、あなたが保証しなければなりません。
+
+## `jsonable_encoder` を `Response` の中で使う { #using-the-jsonable-encoder-in-a-response }
**FastAPI** はあなたが返す `Response` に対して何も変更を加えないので、コンテンツが準備できていることを保証しなければなりません。
@@ -31,33 +40,44 @@
このようなケースでは、レスポンスにデータを含める前に `jsonable_encoder` を使ってデータを変換できます。
-```Python hl_lines="6-7 21-22"
-{!../../../docs_src/response_directly/tutorial001.py!}
-```
+{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}
+
+/// note | 技術詳細
+
+また、`from starlette.responses import JSONResponse` も利用できます。
-!!! note "技術詳細"
- また、`from starlette.responses import JSONResponse` も利用できます。
+**FastAPI** は開発者の利便性のために `fastapi.responses` という `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
- **FastAPI** は開発者の利便性のために `fastapi.responses` という `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
+///
-## カスタム `Response` を返す
+## カスタム `Response` を返す { #returning-a-custom-response }
-上記の例では必要な部分を全て示していますが、あまり便利ではありません。`item` を直接返すことができるし、**FastAPI** はそれを `dict` に変換して `JSONResponse` に含めてくれるなど。すべて、デフォルトの動作です。
+上記の例では必要な部分を全て示していますが、あまり便利ではありません。`item` を直接返すことができるし、**FastAPI** はそれを `dict` に変換して `JSONResponse` に含めてくれるなど。すべて、デフォルトの動作です。
では、これを使ってカスタムレスポンスをどう返すか見てみましょう。
-XMLレスポンスを返したいとしましょう。
+[XML](https://en.wikipedia.org/wiki/XML)レスポンスを返したいとしましょう。
XMLを文字列にし、`Response` に含め、それを返します。
-```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
-```
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+## Response Model の仕組み { #how-a-response-model-works }
+
+path operation で [Response Model - 戻り値の型](../tutorial/response-model.md) を宣言すると、**FastAPI** はそれを使って Pydantic によりデータをJSONにシリアライズします。
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+これは Rust 側で行われるため、通常の Python と `JSONResponse` クラスで行う場合より、パフォーマンスははるかに良くなります。
+
+`response_model` や戻り値の型を使用する場合、FastAPI はデータ変換に(低速になりうる)`jsonable_encoder` も `JSONResponse` クラスも使いません。
+
+代わりに、response model(または戻り値の型)を使って Pydantic が生成した JSON のバイト列をそのまま用い、JSON 用の正しいメディアタイプ(`application/json`)を持つ `Response` を直接返します。
-## 備考
+## 備考 { #notes }
`Response` を直接返す場合、バリデーションや、変換 (シリアライズ) や、自動ドキュメントは行われません。
-しかし、[Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}に記載されたようにドキュメントを書くこともできます。
+しかし、[Additional Responses in OpenAPI](additional-responses.md)に記載されたようにドキュメントを書くこともできます。
後のセクションで、カスタム `Response` を使用・宣言しながら、自動的なデータ変換やドキュメンテーションを行う方法を説明します。
diff --git a/docs/ja/docs/advanced/response-headers.md b/docs/ja/docs/advanced/response-headers.md
new file mode 100644
index 0000000000000..3a61f57428c26
--- /dev/null
+++ b/docs/ja/docs/advanced/response-headers.md
@@ -0,0 +1,41 @@
+# レスポンスヘッダー { #response-headers }
+
+## `Response` パラメータを使う { #use-a-response-parameter }
+
+(Cookie と同様に)*path operation 関数*で `Response` 型のパラメータを宣言できます。
+
+そして、その*一時的*なレスポンスオブジェクトにヘッダーを設定できます。
+
+{* ../../docs_src/response_headers/tutorial002_py310.py hl[1, 7:8] *}
+
+その後は通常どおり、必要な任意のオブジェクト(`dict`、データベースモデルなど)を返せます。
+
+`response_model` を宣言している場合は、返したオブジェクトのフィルタと変換に引き続き使用されます。
+
+**FastAPI** はその*一時的*なレスポンスからヘッダー(Cookie やステータスコードも含む)を取り出し、`response_model` によってフィルタされた返却値を含む最終的なレスポンスに反映します。
+
+また、依存関係の中で `Response` パラメータを宣言し、その中でヘッダー(や Cookie)を設定することもできます。
+
+## `Response` を直接返す { #return-a-response-directly }
+
+`Response` を直接返す場合にもヘッダーを追加できます。
+
+[Response を直接返す](response-directly.md) で説明したようにレスポンスを作成し、ヘッダーを追加のパラメータとして渡します:
+
+{* ../../docs_src/response_headers/tutorial001_py310.py hl[10:12] *}
+
+/// note | 技術詳細
+
+`from starlette.responses import Response` や `from starlette.responses import JSONResponse` を使うこともできます。
+
+**FastAPI** は、開発者であるあなたへの便宜として、`starlette.responses` と同じものを `fastapi.responses` として提供しています。しかし、利用可能なレスポンスの大半は直接 Starlette から来ています。
+
+また、`Response` はヘッダーや Cookie を設定するのによく使われるため、**FastAPI** は `fastapi.Response` でも提供しています。
+
+///
+
+## カスタムヘッダー { #custom-headers }
+
+独自のカスタムヘッダーは、[`X-` プレフィックスを使って](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers)追加できることに注意してください。
+
+ただし、ブラウザのクライアントに見えるようにしたいカスタムヘッダーがある場合は、CORS 設定にそれらを追加する必要があります([CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md) を参照)。このとき、[Starlette の CORS ドキュメント](https://www.starlette.dev/middleware/#corsmiddleware)に記載の `expose_headers` パラメータを使用します。
diff --git a/docs/ja/docs/advanced/security/http-basic-auth.md b/docs/ja/docs/advanced/security/http-basic-auth.md
new file mode 100644
index 0000000000000..b8e47dcbb76a0
--- /dev/null
+++ b/docs/ja/docs/advanced/security/http-basic-auth.md
@@ -0,0 +1,107 @@
+# HTTP Basic 認証 { #http-basic-auth }
+
+最もシンプルなケースでは、HTTP Basic 認証を利用できます。
+
+HTTP Basic 認証では、アプリケーションはユーザー名とパスワードを含むヘッダーを期待します。
+
+それを受け取れない場合、HTTP 401 "Unauthorized" エラーを返します。
+
+そして、値が `Basic` のヘッダー `WWW-Authenticate` を、任意の `realm` パラメータとともに返します。
+
+これにより、ブラウザは組み込みのユーザー名とパスワード入力プロンプトを表示します。
+
+その後、そのユーザー名とパスワードを入力すると、ブラウザはそれらをヘッダーに自動的に付与して送信します。
+
+## シンプルな HTTP Basic 認証 { #simple-http-basic-auth }
+
+- `HTTPBasic` と `HTTPBasicCredentials` をインポートします。
+- `HTTPBasic` を使って「`security` スキーム」を作成します。
+- その `security` を依存関係として path operation に使用します。
+- `HTTPBasicCredentials` 型のオブジェクトが返ります:
+ - 送信された `username` と `password` を含みます。
+
+{* ../../docs_src/security/tutorial006_an_py310.py hl[4,8,12] *}
+
+URL を最初に開こうとしたとき(またはドキュメントで「Execute」ボタンをクリックしたとき)、ブラウザはユーザー名とパスワードの入力を求めます:
+
+
+
+## ユーザー名の確認 { #check-the-username }
+
+より完全な例です。
+
+依存関係を使ってユーザー名とパスワードが正しいかを確認します。
+
+これには、Python 標準モジュール [`secrets`](https://docs.python.org/3/library/secrets.html) を用いてユーザー名とパスワードを検証します。
+
+`secrets.compare_digest()` は `bytes` か、ASCII 文字(英語の文字)のみを含む `str` を受け取る必要があります。つまり、`Sebastián` のように `á` を含む文字ではそのままでは動作しません。
+
+これに対処するため、まず `username` と `password` を UTF-8 でエンコードして `bytes` に変換します。
+
+そのうえで、`secrets.compare_digest()` を使って、`credentials.username` が `"stanleyjobson"` であり、`credentials.password` が `"swordfish"` であることを確認します。
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[1,12:24] *}
+
+これは次のようなコードに相当します:
+
+```Python
+if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
+ # 何らかのエラーを返す
+ ...
+```
+
+しかし `secrets.compare_digest()` を使うことで、「タイミング攻撃」と呼ばれる種類の攻撃に対して安全になります。
+
+### タイミング攻撃 { #timing-attacks }
+
+「タイミング攻撃」とは何でしょうか?
+
+攻撃者がユーザー名とパスワードを推測しようとしていると想像してください。
+
+そして、ユーザー名 `johndoe`、パスワード `love123` を使ってリクエストを送ります。
+
+その場合、アプリケーション内の Python コードは次のようなものと等価になります:
+
+```Python
+if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+しかし、Python は `johndoe` の最初の `j` と `stanleyjobson` の最初の `s` を比較した時点で、両者の文字列が同じでないと判断してすぐに `False` を返します。つまり「残りの文字を比較して計算資源を無駄にする必要はない」と考えるわけです。そしてアプリケーションは「ユーザー名またはパスワードが正しくありません」と返します。
+
+次に、攻撃者がユーザー名 `stanleyjobsox`、パスワード `love123` で試すとします。
+
+アプリケーションのコードは次のようになります:
+
+```Python
+if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+この場合、Python は `stanleyjobsox` と `stanleyjobson` の両方で `stanleyjobso` 全体を比較してから、文字列が同じでないと気づきます。したがって、「ユーザー名またはパスワードが正しくありません」と応答するまでに余分に数マイクロ秒かかります。
+
+#### 応答時間が攻撃者を助ける { #the-time-to-answer-helps-the-attackers }
+
+ここで、サーバーが「ユーザー名またはパスワードが正しくありません」というレスポンスを返すまでに、わずかに長い時間がかかったことに気づけば、攻撃者は何かしら正解に近づいた、すなわち先頭のいくつかの文字が正しかったことを知ることができます。
+
+すると、`johndoe` よりも `stanleyjobsox` に近いものを狙って再試行できます。
+
+#### 「プロ」レベルの攻撃 { #a-professional-attack }
+
+もちろん、攻撃者はこれらを手作業では行わず、プログラムを書いて、1 秒間に数千〜数百万回のテストを行うでしょう。そして 1 回に 1 文字ずつ正しい文字を見つけていきます。
+
+そうすることで、数分から数時間のうちに、攻撃者は私たちのアプリケーションの「助け」(応答にかかった時間)だけを利用して、正しいユーザー名とパスワードを推測できてしまいます。
+
+#### `secrets.compare_digest()` で対策 { #fix-it-with-secrets-compare-digest }
+
+しかし、私たちのコードでは実際に `secrets.compare_digest()` を使用しています。
+
+要するに、`stanleyjobsox` と `stanleyjobson` を比較するのにかかる時間は、`johndoe` と `stanleyjobson` を比較するのにかかる時間と同じになります。パスワードでも同様です。
+
+このように、アプリケーションコードで `secrets.compare_digest()` を使うと、この種の一連のセキュリティ攻撃に対して安全になります。
+
+### エラーを返す { #return-the-error }
+
+認証情報が不正であることを検出したら、ステータスコード 401(認証情報が提供されない場合と同じ)で `HTTPException` を返し、ブラウザに再度ログインプロンプトを表示させるためにヘッダー `WWW-Authenticate` を追加します:
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[26:30] *}
diff --git a/docs/ja/docs/advanced/security/index.md b/docs/ja/docs/advanced/security/index.md
new file mode 100644
index 0000000000000..5b4c480fe94b2
--- /dev/null
+++ b/docs/ja/docs/advanced/security/index.md
@@ -0,0 +1,19 @@
+# 高度なセキュリティ { #advanced-security }
+
+## 追加機能 { #additional-features }
+
+[チュートリアル - ユーザーガイド: セキュリティ](../../tutorial/security/index.md)で扱ったもの以外にも、セキュリティを扱うための追加機能がいくつかあります。
+
+/// tip | 豆知識
+
+次の節は**必ずしも「高度」ではありません**。
+
+あなたのユースケースでは、その中のいずれかに解決策があるかもしれません。
+
+///
+
+## まずチュートリアルを読む { #read-the-tutorial-first }
+
+以下の節は、すでにメインの[チュートリアル - ユーザーガイド: セキュリティ](../../tutorial/security/index.md)を読んでいることを前提とします。
+
+いずれも同じ概念に基づいていますが、いくつかの追加機能を利用できます。
diff --git a/docs/ja/docs/advanced/security/oauth2-scopes.md b/docs/ja/docs/advanced/security/oauth2-scopes.md
new file mode 100644
index 0000000000000..3afc26e3ae1ff
--- /dev/null
+++ b/docs/ja/docs/advanced/security/oauth2-scopes.md
@@ -0,0 +1,274 @@
+# OAuth2 のスコープ { #oauth2-scopes }
+
+OAuth2 のスコープは **FastAPI** で直接利用でき、シームレスに統合されています。
+
+これにより、OAuth2 標準に従った、よりきめ細かな権限システムを、OpenAPI 対応アプリケーション(および API ドキュメント)に統合できます。
+
+スコープ付きの OAuth2 は、Facebook、Google、GitHub、Microsoft、X (Twitter) など、多くの大手認証プロバイダで使われている仕組みです。ユーザーやアプリケーションに特定の権限を付与するために利用されます。
+
+「Facebook でログイン」「Google でログイン」「GitHub でログイン」「Microsoft でログイン」「X (Twitter) でログイン」するたびに、そのアプリケーションはスコープ付きの OAuth2 を使っています。
+
+この節では、同じスコープ付き OAuth2 を使って、**FastAPI** アプリケーションで認証と認可を管理する方法を見ていきます。
+
+/// warning | 注意
+
+これはやや高度な内容です。はじめたばかりであれば読み飛ばしても構いません。
+
+OAuth2 のスコープは必ずしも必要ではなく、認証と認可は好きなやり方で実装できます。
+
+ただし、スコープ付きの OAuth2 は、API(OpenAPI)や API ドキュメントにきれいに統合できます。
+
+とはいえ、これらのスコープやその他のセキュリティ/認可要件の適用は、必要に応じてコードの中で行う必要があります。
+
+多くの場合、スコープ付き OAuth2 はオーバースペックになりえます。
+
+それでも必要だと分かっている場合や、興味がある場合は、このまま読み進めてください。
+
+///
+
+## OAuth2 のスコープと OpenAPI { #oauth2-scopes-and-openapi }
+
+OAuth2 仕様では、「スコープ」は空白で区切られた文字列の一覧として定義されています。
+
+各文字列の内容は任意ですが、空白は含められません。
+
+これらのスコープは「権限」を表します。
+
+OpenAPI(例: API ドキュメント)では、「セキュリティスキーム」を定義できます。
+
+これらのセキュリティスキームの一つが OAuth2 を使う場合、スコープを宣言して利用できます。
+
+各「スコープ」は、ただの文字列(空白なし)です。
+
+通常、特定のセキュリティ権限を宣言するために使われます。例えば:
+
+- `users:read` や `users:write` は一般的な例です。
+- `instagram_basic` は Facebook / Instagram で使われています。
+- `https://www.googleapis.com/auth/drive` は Google で使われています。
+
+/// info | 情報
+
+OAuth2 において「スコープ」は、必要な特定の権限を宣言する単なる文字列です。
+
+`:` のような他の文字が含まれていても、URL であっても問題ありません。
+
+それらの詳細は実装依存です。
+
+OAuth2 にとっては、単に文字列に過ぎません。
+
+///
+
+## 全体像 { #global-view }
+
+まず、メインの**チュートリアル - ユーザーガイド**にある [OAuth2(パスワード[ハッシュ化あり])、Bearer と JWT トークン](../../tutorial/security/oauth2-jwt.md) の例から変更される部分を、スコープ付き OAuth2 を使って手早く見てみましょう。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}
+
+では、これらの変更を一つずつ確認していきます。
+
+## OAuth2 のセキュリティスキーム { #oauth2-security-scheme }
+
+最初の変更点は、`me` と `items` の 2 つのスコープを持つ OAuth2 セキュリティスキームを宣言していることです。
+
+`scopes` パラメータは、各スコープをキー、その説明を値とする `dict` を受け取ります:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *}
+
+これらのスコープを宣言しているため、ログイン/認可時に API ドキュメントに表示されます。
+
+そして、付与するスコープ(`me`、`items`)を選択できます。
+
+これは、Facebook、Google、GitHub などでログイン時に権限を付与する際と同じ仕組みです:
+
+
+
+## スコープ付きの JWT トークン { #jwt-token-with-scopes }
+
+次に、トークンの path operation を修正して、要求されたスコープを返すようにします。
+
+引き続き同じ `OAuth2PasswordRequestForm` を使用します。これには、リクエストで受け取った各スコープを含む、`str` の `list` である `scopes` プロパティが含まれます。
+
+そして、そのスコープを JWT トークンの一部として返します。
+
+/// danger | 警告
+
+簡単のため、ここでは受け取ったスコープをそのままトークンに追加しています。
+
+しかし、本番アプリケーションではセキュリティのため、ユーザーが実際に持つことができるスコープ、または事前に定義したスコープだけを追加するようにしてください。
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}
+
+## path operation と依存関係でスコープを宣言 { #declare-scopes-in-path-operations-and-dependencies }
+
+ここでは、`/users/me/items/` の path operation が `items` スコープを必要とするように宣言します。
+
+そのために、`fastapi` から `Security` をインポートして使います。
+
+`Security` は(`Depends` と同様に)依存関係を宣言できますが、さらにスコープ(文字列)のリストを受け取る `scopes` パラメータも持ちます。
+
+この場合、`Security` に依存関数 `get_current_active_user` を渡します(`Depends` と同様です)。
+
+加えて、`items` という 1 つのスコープ(複数でも可)を含む `list` も渡します。
+
+依存関数 `get_current_active_user` は、`Depends` だけでなく `Security` でもサブ依存関係を宣言できます。自身のサブ依存関数(`get_current_user`)を宣言し、さらにスコープ要件を追加します。
+
+この場合、`me` スコープを要求します(複数のスコープも可)。
+
+/// note | 備考
+
+異なる場所で異なるスコープを追加する必要は必ずしもありません。
+
+ここでは、**FastAPI** が異なるレベルで宣言されたスコープをどのように扱うかを示すためにそうしています。
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}
+
+/// info | 技術詳細
+
+`Security` は実際には `Depends` のサブクラスで、後述する追加パラメータが 1 つあるだけです。
+
+しかし `Depends` の代わりに `Security` を使うことで、**FastAPI** はセキュリティスコープを宣言・内部利用でき、OpenAPI で API をドキュメント化できると判断します。
+
+なお、`fastapi` から `Query`、`Path`、`Depends`、`Security` などをインポートする際、それらは実際には特殊なクラスを返す関数です。
+
+///
+
+## `SecurityScopes` を使う { #use-securityscopes }
+
+次に、依存関数 `get_current_user` を更新します。
+
+これは上記の依存関係から使用されます。
+
+ここで、先ほど作成した同じ OAuth2 スキームを依存関係(`oauth2_scheme`)として宣言して使います。
+
+この依存関数自体はスコープ要件を持たないため、`oauth2_scheme` には `Depends` を使えます。セキュリティスコープを指定する必要がない場合は `Security` を使う必要はありません。
+
+さらに、`fastapi.security` からインポートする特別な型 `SecurityScopes` のパラメータを宣言します。
+
+この `SecurityScopes` クラスは `Request` に似ています(`Request` はリクエストオブジェクトを直接取得するために使いました)。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}
+
+## `scopes` を使う { #use-the-scopes }
+
+パラメータ `security_scopes` は `SecurityScopes` 型になります。
+
+このオブジェクトは、自身およびこれをサブ依存として使うすべての依存関係で要求されるスコープを含む `scopes` プロパティ(リスト)を持ちます。つまり、すべての「依存元」... 少し分かりにくいかもしれませんが、後で再度説明します。
+
+`security_scopes`(`SecurityScopes` クラスのインスタンス)は、要求されたスコープを空白で連結した 1 つの文字列を返す `scope_str` も提供します(これを使います)。
+
+後で複数箇所で再利用(raise)できるように、`HTTPException` を 1 つ作成します。
+
+この例外には、要求されたスコープがあればそれらを空白区切りの文字列(`scope_str` を使用)として含めます。このスコープ文字列は `WWW-Authenticate` ヘッダに入れます(仕様の一部です)。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}
+
+## `username` とデータ構造の検証 { #verify-the-username-and-data-shape }
+
+`username` を取得できていることを確認し、スコープを取り出します。
+
+そして、そのデータを Pydantic モデルで検証します(`ValidationError` 例外を捕捉)。JWT トークンの読み取りや Pydantic によるデータ検証でエラーが発生した場合は、先ほど作成した `HTTPException` を送出します。
+
+そのために、Pydantic モデル `TokenData` に新しいプロパティ `scopes` を追加します。
+
+Pydantic でデータを検証することで、例えばスコープは `str` の `list`、`username` は `str` といった、正確な型になっていることを保証できます。
+
+そうしておけば、例えば誤って `dict` などが入って後でアプリケーションを破壊してしまい、セキュリティリスクになる、といった事態を避けられます。
+
+また、その `username` を持つユーザーが存在することも確認し、存在しなければ、やはり先ほどの例外を送出します。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}
+
+## `scopes` の検証 { #verify-the-scopes }
+
+この依存関数およびすべての依存元(path operation を含む)が要求するすべてのスコープが、受け取ったトークンに含まれていることを検証し、含まれていなければ `HTTPException` を送出します。
+
+そのために、これらすべてのスコープを `str` の `list` として含む `security_scopes.scopes` を使います。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}
+
+## 依存関係ツリーとスコープ { #dependency-tree-and-scopes }
+
+依存関係ツリーとスコープをもう一度見てみましょう。
+
+`get_current_active_user` 依存関係は `get_current_user` をサブ依存として持つため、`get_current_active_user` で宣言された `"me"` スコープは、`get_current_user` に渡される `security_scopes.scopes` の必須スコープ一覧に含まれます。
+
+path operation 自体も `"items"` スコープを宣言するため、これも `get_current_user` に渡される `security_scopes.scopes` に含まれます。
+
+依存関係とスコープの階層は次のようになります:
+
+- *path operation* `read_own_items` には:
+ - 依存関係に対して必須スコープ `["items"]` がある:
+ - `get_current_active_user`:
+ - 依存関数 `get_current_active_user` には:
+ - 依存関係に対して必須スコープ `["me"]` がある:
+ - `get_current_user`:
+ - 依存関数 `get_current_user` には:
+ - 自身に必須スコープはない。
+ - `oauth2_scheme` を使う依存関係がある。
+ - `SecurityScopes` 型の `security_scopes` パラメータがある:
+ - この `security_scopes` パラメータは、上で宣言されたすべてのスコープを含む `list` を持つ `scopes` プロパティを持つ。したがって:
+ - *path operation* `read_own_items` では、`security_scopes.scopes` は `["me", "items"]` を含む。
+ - *path operation* `read_users_me` では、`security_scopes.scopes` は `["me"]` を含む。これは依存関係 `get_current_active_user` に宣言されているため。
+ - *path operation* `read_system_status` では、`security_scopes.scopes` は `[]`(空)になる。`scopes` を持つ `Security` を宣言しておらず、その依存関係 `get_current_user` も `scopes` を宣言していないため。
+
+/// tip | 豆知識
+
+重要で「魔法のよう」な点は、`get_current_user` が path operation ごとに異なる `scopes` のリストをチェックすることになる、ということです。
+
+それは、それぞれの path operation と、その path operation の依存関係ツリー内の各依存関係で宣言された `scopes` によって決まります。
+
+///
+
+## `SecurityScopes` の詳細 { #more-details-about-securityscopes }
+
+`SecurityScopes` はどの地点でも、複数箇所でも使えます。「ルート」の依存関係である必要はありません。
+
+常に、その時点の `Security` 依存関係と、**その特定の** path operation と **その特定の** 依存関係ツリーにおける、すべての依存元で宣言されたセキュリティスコープを持ちます。
+
+`SecurityScopes` には依存元で宣言されたすべてのスコープが入るため、トークンが必要なスコープを持っているかどうかを中央の依存関数で検証し、path operation ごとに異なるスコープ要件を宣言する、といった使い方ができます。
+
+これらは path operation ごとに独立して検証されます。
+
+## チェック { #check-it }
+
+API ドキュメントを開くと、認証して、許可するスコープを指定できます。
+
+
+
+どのスコープも選択しない場合は「認証済み」にはなりますが、`/users/me/` や `/users/me/items/` にアクセスしようとすると、権限が不足しているというエラーになります。`/status/` には引き続きアクセスできます。
+
+`me` スコープだけを選択し、`items` スコープを選択しない場合は、`/users/me/` にはアクセスできますが、`/users/me/items/` にはアクセスできません。
+
+これは、ユーザーがアプリケーションに与えた権限の範囲に応じて、サードパーティアプリケーションがこれらの path operation のいずれかに、ユーザーから提供されたトークンでアクセスしようとしたときに起こる動作です。
+
+## サードパーティ統合について { #about-third-party-integrations }
+
+この例では、OAuth2 の「password」フローを使用しています。
+
+これは、(おそらく自前のフロントエンドで)自分たちのアプリケーションにログインする場合に適しています。
+
+自分たちで管理しているため、`username` と `password` を受け取る相手を信頼できるからです。
+
+しかし、他者が接続する OAuth2 アプリケーション(Facebook、Google、GitHub などに相当する認証プロバイダ)を構築する場合は、他のいずれかのフローを使用すべきです。
+
+最も一般的なのは implicit フローです。
+
+最も安全なのは code フローですが、手順が多く実装がより複雑です。複雑なため、多くのプロバイダは結局 implicit フローを推奨することがあります。
+
+/// note | 備考
+
+各認証プロバイダがフローに独自の名称を付け、自社のブランドの一部にするのは一般的です。
+
+しかし、最終的には同じ OAuth2 標準を実装しています。
+
+///
+
+**FastAPI** には、これらすべての OAuth2 認証フロー向けのユーティリティが `fastapi.security.oauth2` に含まれています。
+
+## デコレータ `dependencies` での `Security` { #security-in-decorator-dependencies }
+
+デコレータの `dependencies` パラメータに `Depends` の `list` を定義できるのと同様([path operation デコレータでの依存関係](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md) 参照)、ここで `scopes` を指定した `Security` も使用できます。
diff --git a/docs/ja/docs/advanced/settings.md b/docs/ja/docs/advanced/settings.md
new file mode 100644
index 0000000000000..e42ec845c6c8b
--- /dev/null
+++ b/docs/ja/docs/advanced/settings.md
@@ -0,0 +1,302 @@
+# 設定と環境変数 { #settings-and-environment-variables }
+
+多くの場合、アプリケーションは外部の設定や構成を必要とします。たとえば、シークレットキー、データベース認証情報、メールサービスの認証情報などです。
+
+これらの設定の多くは可変(変更されうる)で、データベースのURLのようなものがあります。また、多くはシークレットのように機微な情報です。
+
+そのため、アプリケーションが読み取る環境変数で提供するのが一般的です。
+
+/// tip | 豆知識
+
+環境変数について理解するには、[環境変数](../environment-variables.md)を参照してください。
+
+///
+
+## 型とバリデーション { #types-and-validation }
+
+これらの環境変数は Python の外部にあり、他のプログラムやシステム全体(Linux、Windows、macOS といった異なるOSを含む)と互換性が必要なため、文字列テキストのみを扱えます。
+
+つまり、Python で環境変数から読み取られる値はすべて `str` になり、他の型への変換やバリデーションはコードで行う必要があります。
+
+## Pydantic の `Settings` { #pydantic-settings }
+
+幸いなことに、Pydantic には環境変数から来る設定を扱うための優れたユーティリティがあり、[Pydantic: Settings management](https://docs.pydantic.dev/latest/concepts/pydantic_settings/) で提供されています。
+
+### `pydantic-settings` のインストール { #install-pydantic-settings }
+
+まず、[仮想環境](../virtual-environments.md)を作成して有効化し、`pydantic-settings` パッケージをインストールします:
+
+
+
+次に、サブアプリケーションのドキュメント [http://127.0.0.1:8000/subapi/docs](http://127.0.0.1:8000/subapi/docs) を開きます。
+
+サブアプリケーション用の自動 API ドキュメントが表示され、そのアプリ自身の path operation のみが、正しいサブパス接頭辞 `/subapi` の下で表示されます:
+
+
+
+どちらの UI でも操作すれば正しく動作します。ブラウザがそれぞれのアプリ/サブアプリと通信できるためです。
+
+### 技術詳細: `root_path` { #technical-details-root-path }
+
+上記のようにサブアプリケーションをマウントすると、FastAPI は ASGI 仕様の `root_path` と呼ばれる仕組みを使って、そのサブアプリケーションへのマウントパスを伝播します。
+
+このため、サブアプリケーションはドキュメント UI でそのパス接頭辞を使用すべきことを認識できます。
+
+さらに、サブアプリケーション自身が別のサブアプリケーションをマウントしていても問題ありません。FastAPI がこれらの `root_path` をすべて自動的に処理するためです。
+
+`root_path` の詳細や明示的な指定方法については、[プロキシの背後で](behind-a-proxy.md) の節で学べます。
diff --git a/docs/ja/docs/advanced/templates.md b/docs/ja/docs/advanced/templates.md
new file mode 100644
index 0000000000000..5495b73a0bba1
--- /dev/null
+++ b/docs/ja/docs/advanced/templates.md
@@ -0,0 +1,126 @@
+# テンプレート { #templates }
+
+**FastAPI** では任意のテンプレートエンジンを使用できます。
+
+Flask などでも使われている Jinja2 が一般的な選択肢です。
+
+Starlette によって提供され、**FastAPI** アプリで直接使える、簡単に設定できるユーティリティがあります。
+
+## 依存関係のインストール { #install-dependencies }
+
+[仮想環境](../virtual-environments.md) を作成して有効化し、`jinja2` をインストールします:
+
+
-そして、 WebSocketを使用した**FastAPI**アプリケーションが応答します。
+そして、 WebSocketsを使用した**FastAPI**アプリケーションが応答します。
@@ -99,7 +96,7 @@ $ uvicorn main:app --reload
そして、これらの通信はすべて同じWebSocket接続を使用します。
-## 依存関係
+## `Depends` などの使用 { #using-depends-and-others }
WebSocketエンドポイントでは、`fastapi` から以下をインポートして使用できます。
@@ -110,54 +107,54 @@ WebSocketエンドポイントでは、`fastapi` から以下をインポート
* `Path`
* `Query`
-これらは、他のFastAPI エンドポイント/*path operation* の場合と同じように機能します。
+これらは、他のFastAPI エンドポイント/*path operations* の場合と同じように機能します。
-```Python hl_lines="58-65 68-83"
-{!../../../docs_src/websockets/tutorial002.py!}
-```
+{* ../../docs_src/websockets_/tutorial002_an_py310.py hl[68:69,82] *}
-!!! info "情報"
- WebSocket で `HTTPException` を発生させることはあまり意味がありません。したがって、WebSocketの接続を直接閉じる方がよいでしょう。
+/// info | 情報
- クロージングコードは、仕様で定義された有効なコードの中から使用することができます。
+これはWebSocketであるため、`HTTPException` を発生させることはあまり意味がありません。代わりに `WebSocketException` を発生させます。
- 将来的には、どこからでも `raise` できる `WebSocketException` が用意され、専用の例外ハンドラを追加できるようになる予定です。これは、Starlette の PR #527 に依存するものです。
+クロージングコードは、[仕様で定義された有効なコード](https://tools.ietf.org/html/rfc6455#section-7.4.1)の中から使用することができます。
-### 依存関係を用いてWebSocketsを試してみる
+///
-ファイル名が `main.py` である場合、以下の方法でアプリケーションを実行します。
+### 依存関係を用いてWebSocketsを試してみる { #try-the-websockets-with-dependencies }
+
+アプリケーションを実行します。
-## 切断や複数クライアントへの対応
+## 切断や複数クライアントの処理 { #handling-disconnections-and-multiple-clients }
WebSocket接続が閉じられると、 `await websocket.receive_text()` は例外 `WebSocketDisconnect` を発生させ、この例のようにキャッチして処理することができます。
-```Python hl_lines="81-83"
-{!../../../docs_src/websockets/tutorial003.py!}
-```
+{* ../../docs_src/websockets_/tutorial003_py310.py hl[79:81] *}
試してみるには、
@@ -171,16 +168,19 @@ WebSocket接続が閉じられると、 `await websocket.receive_text()` は例
Client #1596980209979 left the chat
```
-!!! tip "豆知識"
- 上記のアプリは、複数の WebSocket 接続に対してメッセージを処理し、ブロードキャストする方法を示すための最小限のシンプルな例です。
+/// tip | 豆知識
+
+上記のアプリは、複数の WebSocket 接続に対してメッセージを処理し、ブロードキャストする方法を示すための最小限のシンプルな例です。
+
+しかし、すべてがメモリ内の単一のリストで処理されるため、プロセスの実行中にのみ機能し、単一のプロセスでのみ機能することに注意してください。
- しかし、すべての接続がメモリ内の単一のリストで処理されるため、プロセスの実行中にのみ機能し、単一のプロセスでのみ機能することに注意してください。
+FastAPIと簡単に統合できて、RedisやPostgreSQLなどでサポートされている、より堅牢なものが必要なら、[encode/broadcaster](https://github.com/encode/broadcaster) を確認してください。
- もしFastAPIと簡単に統合できて、RedisやPostgreSQLなどでサポートされている、より堅牢なものが必要なら、encode/broadcaster を確認してください。
+///
-## その他のドキュメント
+## 詳細情報 { #more-info }
オプションの詳細については、Starletteのドキュメントを確認してください。
-* `WebSocket` クラス
-* クラスベースのWebSocket処理
+* [`WebSocket` クラス](https://www.starlette.dev/websockets/)。
+* [クラスベースのWebSocket処理](https://www.starlette.dev/endpoints/#websocketendpoint)。
diff --git a/docs/ja/docs/advanced/wsgi.md b/docs/ja/docs/advanced/wsgi.md
new file mode 100644
index 0000000000000..6895eb658443b
--- /dev/null
+++ b/docs/ja/docs/advanced/wsgi.md
@@ -0,0 +1,51 @@
+# WSGI の組み込み - Flask、Django など { #including-wsgi-flask-django-others }
+
+[サブアプリケーション - マウント](sub-applications.md)、[プロキシの背後](behind-a-proxy.md) で見たように、WSGI アプリケーションをマウントできます。
+
+そのために `WSGIMiddleware` を使用して、Flask や Django などの WSGI アプリをラップできます。
+
+## `WSGIMiddleware` の使用 { #using-wsgimiddleware }
+
+/// info | 情報
+
+これには `a2wsgi` のインストールが必要です。例: `pip install a2wsgi`。
+
+///
+
+`a2wsgi` から `WSGIMiddleware` をインポートします。
+
+次に、そのミドルウェアで WSGI(例: Flask)アプリをラップします。
+
+そして、それをあるパスの下にマウントします。
+
+{* ../../docs_src/wsgi/tutorial001_py310.py hl[1,3,23] *}
+
+/// note | 備考
+
+以前は `fastapi.middleware.wsgi` の `WSGIMiddleware` を使用することが推奨されていましたが、現在は非推奨です。
+
+代わりに `a2wsgi` パッケージを使用することを推奨します。使い方は同じです。
+
+`a2wsgi` パッケージがインストールされていることを確認し、`a2wsgi` から `WSGIMiddleware` を正しくインポートしてください。
+
+///
+
+## チェック { #check-it }
+
+これで、パス `/v1/` 配下へのすべてのリクエストは Flask アプリケーションが処理します。
+
+それ以外は **FastAPI** が処理します。
+
+実行して [http://localhost:8000/v1/](http://localhost:8000/v1/) にアクセスすると、Flask からのレスポンスが表示されます:
+
+```txt
+Hello, World from Flask!
+```
+
+さらに [http://localhost:8000/v2](http://localhost:8000/v2) にアクセスすると、FastAPI からのレスポンスが表示されます:
+
+```JSON
+{
+ "message": "Hello World"
+}
+```
diff --git a/docs/ja/docs/alternatives.md b/docs/ja/docs/alternatives.md
index ca6b29a0776db..34017b00e9605 100644
--- a/docs/ja/docs/alternatives.md
+++ b/docs/ja/docs/alternatives.md
@@ -1,8 +1,8 @@
-# 代替ツールから受けたインスピレーションと比較
+# 代替ツールから受けたインスピレーションと比較 { #alternatives-inspiration-and-comparisons }
何が**FastAPI**にインスピレーションを与えたのか、他の代替ツールと比較してどうか、そしてそこから何を学んだのかについて。
-## はじめに
+## はじめに { #intro }
**FastAPI**は、代替ツールのこれまでの働きがなければ存在しなかったでしょう。
@@ -12,17 +12,17 @@
しかし、その時点では、これらの機能をすべて提供し、以前のツールから優れたアイデアを取り入れ、可能な限り最高の方法でそれらを組み合わせ、それまで利用できなかった言語機能 (Python 3.6以降の型ヒント) を利用したものを作る以外に選択肢はありませんでした。
-## 以前のツール
+## 以前のツール { #previous-tools }
-### Django
+### [Django](https://www.djangoproject.com/) { #django }
Pythonのフレームワークの中で最もポピュラーで、広く信頼されています。Instagramのようなシステムの構築に使われています。
リレーショナルデータベース (MySQLやPostgreSQLなど) と比較的強固に結合されているので、NoSQLデータベース (Couchbase、MongoDB、Cassandraなど) をメインに利用することは簡単ではありません。
-バックエンドでHTMLを生成するために作られたものであり、現代的なフロントエンド (ReactやVue.js、Angularなど) や、他のシステム (IoTデバイスなど) と通信するAPIを構築するために作られたものではありません。
+バックエンドでHTMLを生成するために作られたものであり、現代的なフロントエンド (ReactやVue.js、Angularなど) や、他のシステム (IoTデバイスなど) と通信するAPIを構築するために作られたものではありません。
-### Django REST Framework
+### [Django REST Framework](https://www.django-rest-framework.org/) { #django-rest-framework }
Django REST Frameworkは、Djangoを下敷きにしてWeb APIを構築する柔軟なツールキットとして、APIの機能を向上させるために作られました。
@@ -30,13 +30,19 @@ Mozilla、Red Hat、Eventbrite など多くの企業で利用されています
これは**自動的なAPIドキュメント生成**の最初の例であり、これは**FastAPI**に向けた「調査」を触発した最初のアイデアの一つでした。
-!!! note "備考"
- Django REST Framework は Tom Christie によって作成されました。StarletteとUvicornの生みの親であり、**FastAPI**のベースとなっています。
+/// note | 備考
-!!! check "**FastAPI**へ与えたインスピレーション"
- 自動でAPIドキュメントを生成するWebユーザーインターフェースを持っている点。
+Django REST Framework は Tom Christie によって作成されました。StarletteとUvicornの生みの親であり、**FastAPI**のベースとなっています。
-### Flask
+///
+
+/// check | **FastAPI**へ与えたインスピレーション
+
+自動でAPIドキュメントを生成するWebユーザーインターフェースを持っている点。
+
+///
+
+### [Flask](https://flask.palletsprojects.com) { #flask }
Flask は「マイクロフレームワーク」であり、データベースとの統合のようなDjangoがデフォルトで持つ多くの機能は含まれていません。
@@ -50,13 +56,15 @@ Flask は「マイクロフレームワーク」であり、データベース
Flaskのシンプルさを考えると、APIを構築するのに適しているように思えました。次に見つけるべきは、Flask 用の「Django REST Framework」でした。
-!!! check "**FastAPI**へ与えたインスピレーション"
- マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。
+/// check | **FastAPI**へ与えたインスピレーション
- シンプルで簡単なルーティングの仕組みを持っている点。
+マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。
+シンプルで簡単なルーティングの仕組みを持っている点。
-### Requests
+///
+
+### [Requests](https://requests.readthedocs.io) { #requests }
**FastAPI**は実際には**Requests**の代替ではありません。それらのスコープは大きく異なります。
@@ -72,7 +80,7 @@ Requestsは非常にシンプルかつ直感的なデザインで使いやすく
公式サイトで以下のように言われているのは、それが理由です。
-> Requestsは今までで最もダウンロードされたPythonパッケージである
+> Requestsは史上最もダウンロードされたPythonパッケージのひとつです
使い方はとても簡単です。例えば、`GET`リクエストを実行するには、このように書けば良いです:
@@ -80,7 +88,7 @@ Requestsは非常にシンプルかつ直感的なデザインで使いやすく
response = requests.get("http://example.com/some/url")
```
-対応するFastAPIのパスオペレーションはこのようになります:
+対応するFastAPIのAPIのpath operationはこのようになります:
```Python hl_lines="1"
@app.get("/some/url")
@@ -90,13 +98,15 @@ def read_url():
`requests.get(...)` と`@app.get(...)` には類似点が見受けられます。
-!!! check "**FastAPI**へ与えたインスピレーション"
- * シンプルで直感的なAPIを持っている点。
- * HTTPメソッド名を直接利用し、単純で直感的である。
- * 適切なデフォルト値を持ちつつ、強力なカスタマイズ性を持っている。
+/// check | **FastAPI**へ与えたインスピレーション
+
+* シンプルで直感的なAPIを持っている点。
+* HTTPメソッド名を直接利用し、単純で直感的である。
+* 適切なデフォルト値を持ちつつ、強力なカスタマイズ性を持っている。
+///
-### Swagger / OpenAPI
+### [Swagger](https://swagger.io/) / [OpenAPI](https://github.com/OAI/OpenAPI-Specification/) { #swagger-openapi }
私がDjango REST Frameworkに求めていた主な機能は、APIの自動的なドキュメント生成でした。
@@ -108,23 +118,26 @@ def read_url():
そのため、バージョン2.0では「Swagger」、バージョン3以上では「OpenAPI」と表記するのが一般的です。
-!!! check "**FastAPI**へ与えたインスピレーション"
- 独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。
+/// check | **FastAPI**へ与えたインスピレーション
+
+独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。
- そして、標準に基づくユーザーインターフェースツールを統合しています。
+そして、標準に基づくユーザーインターフェースツールを統合しています。
- * Swagger UI
- * ReDoc
+* [Swagger UI](https://github.com/swagger-api/swagger-ui)
+* [ReDoc](https://github.com/Rebilly/ReDoc)
- この二つは人気で安定したものとして選択されましたが、少し検索してみると、 (**FastAPI**と同時に使用できる) OpenAPIのための多くの代替となるツールを見つけることができます。
+この二つは人気で安定したものとして選択されましたが、少し検索してみると、 (**FastAPI**と同時に使用できる) OpenAPIのための多くの代替となるツールを見つけることができます。
-### Flask REST フレームワーク
+///
+
+### Flask REST フレームワーク { #flask-rest-frameworks }
いくつかのFlask RESTフレームワークがありますが、それらを調査してみたところ、多くのものが不適切な問題が残ったまま、中断されたり放置されていることがわかりました。
-### Marshmallow
+### [Marshmallow](https://marshmallow.readthedocs.io/en/stable/) { #marshmallow }
-APIシステムで必要とされる主な機能の一つに、コード (Python) からデータを取り出して、ネットワークを介して送れるものに変換するデータの「シリアライゼーション」があります。例えば、データベースのデータを含むオブジェクトをJSONオブジェクトに変換したり、`datetime` オブジェクトを文字列に変換するなどです。
+APIシステムで必要とされる主な機能の一つに、コード (Python) からデータを取り出して、ネットワークを介して送れるものに変換するデータの「シリアライゼーション」があります。例えば、データベースのデータを含むオブジェクトをJSONオブジェクトに変換したり、`datetime` オブジェクトを文字列に変換するなどです。
APIが必要とするもう一つの大きな機能はデータのバリデーションであり、特定のパラメータが与えられた場合にデータが有効であることを確認することです。例えば、あるフィールドがランダムな文字列ではなく `int` であることなどです。これは特に受信するデータに対して便利です。
@@ -132,14 +145,17 @@ APIが必要とするもう一つの大きな機能はデータのバリデー
これらの機能は、Marshmallowが提供するものです。Marshmallowは素晴らしいライブラリで、私も以前に何度も使ったことがあります。
-しかし、それはPythonの型ヒントが存在する前に作られたものです。そのため、すべてのスキーマを定義するためには、Marshmallowが提供する特定のユーティリティやクラスを使用する必要があります。
+しかし、それはPythonの型ヒントが存在する前に作られたものです。そのため、すべてのスキーマを定義するためには、Marshmallowが提供する特定のユーティリティやクラスを使用する必要があります。
+
+/// check | **FastAPI**へ与えたインスピレーション
+
+コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。
-!!! check "**FastAPI**へ与えたインスピレーション"
- コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。
+///
-### Webargs
+### [Webargs](https://webargs.readthedocs.io/en/latest/) { #webargs }
-APIに求められる他の大きな機能として、受信したリクエストデータのパースがあります。
+APIに求められる他の大きな機能として、受信したリクエストデータのパースがあります。
WebargsはFlaskをはじめとするいくつかのフレームワークの上にそれを提供するために作られたツールです。
@@ -147,13 +163,19 @@ WebargsはFlaskをはじめとするいくつかのフレームワークの上
素晴らしいツールで、私も**FastAPI**を持つ前はよく使っていました。
-!!! info "情報"
- Webargsは、Marshmallowと同じ開発者により作られました。
+/// info | 情報
+
+Webargsは、Marshmallowと同じ開発者により作られました。
+
+///
+
+/// check | **FastAPI**へ与えたインスピレーション
-!!! check "**FastAPI**へ与えたインスピレーション"
- 受信したデータに対する自動的なバリデーションを持っている点。
+受信したデータに対する自動的なバリデーションを持っている点。
-### APISpec
+///
+
+### [APISpec](https://apispec.readthedocs.io/en/stable/) { #apispec }
MarshmallowとWebargsはバリデーション、パース、シリアライゼーションをプラグインとして提供しています。
@@ -171,13 +193,19 @@ Flask, Starlette, Responderなどにおいてはそのように動作します
エディタでは、この問題を解決することはできません。また、パラメータやMarshmallowスキーマを変更したときに、YAMLのdocstringを変更するのを忘れてしまうと、生成されたスキーマが古くなってしまいます。
-!!! info "情報"
- APISpecは、Marshmallowと同じ開発者により作成されました。
+/// info | 情報
+
+APISpecは、Marshmallowと同じ開発者により作成されました。
+
+///
-!!! check "**FastAPI**へ与えたインスピレーション"
- OpenAPIという、APIについてのオープンな標準をサポートしている点。
+/// check | **FastAPI**へ与えたインスピレーション
-### Flask-apispec
+OpenAPIという、APIについてのオープンな標準をサポートしている点。
+
+///
+
+### [Flask-apispec](https://flask-apispec.readthedocs.io/en/latest/) { #flask-apispec }
Webargs、Marshmallow、APISpecを連携させたFlaskプラグインです。
@@ -191,19 +219,25 @@ Flask、Flask-apispec、Marshmallow、Webargsの組み合わせは、**FastAPI**
これを使うことで、いくつかのFlaskフルスタックジェネレータを作成することになりました。これらは私 (といくつかの外部のチーム) が今まで使ってきたメインのスタックです。
-* https://github.com/tiangolo/full-stack
-* https://github.com/tiangolo/full-stack-flask-couchbase
-* https://github.com/tiangolo/full-stack-flask-couchdb
+* [https://github.com/tiangolo/full-stack](https://github.com/tiangolo/full-stack)
+* [https://github.com/tiangolo/full-stack-flask-couchbase](https://github.com/tiangolo/full-stack-flask-couchbase)
+* [https://github.com/tiangolo/full-stack-flask-couchdb](https://github.com/tiangolo/full-stack-flask-couchdb)
+
+そして、これらのフルスタックジェネレーターは、[**FastAPI** Project Generators](project-generation.md)の元となっていました。
-そして、これらのフルスタックジェネレーターは、[**FastAPI** Project Generators](project-generation.md){.internal-link target=_blank}の元となっていました。
+/// info | 情報
-!!! info "情報"
- Flask-apispecはMarshmallowと同じ開発者により作成されました。
+Flask-apispecはMarshmallowと同じ開発者により作成されました。
-!!! check "**FastAPI**へ与えたインスピレーション"
- シリアライゼーションとバリデーションを定義したコードから、OpenAPIスキーマを自動的に生成する点。
+///
-### NestJS (とAngular)
+/// check | **FastAPI**へ与えたインスピレーション
+
+シリアライゼーションとバリデーションを定義したコードから、OpenAPIスキーマを自動的に生成する点。
+
+///
+
+### [NestJS](https://nestjs.com/) (と[Angular](https://angular.io/)) { #nestjs-and-angular }
NestJSはAngularにインスパイアされたJavaScript (TypeScript) NodeJSフレームワークで、Pythonですらありません。
@@ -217,43 +251,53 @@ Angular 2にインスピレーションを受けた、統合された依存性
入れ子になったモデルをうまく扱えません。そのため、リクエストのJSONボディが内部フィールドを持つJSONオブジェクトで、それが順番にネストされたJSONオブジェクトになっている場合、適切にドキュメント化やバリデーションをすることができません。
-!!! check "**FastAPI**へ与えたインスピレーション"
- 素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。
+/// check | **FastAPI**へ与えたインスピレーション
- 強力な依存性注入の仕組みを持ち、コードの繰り返しを最小化する方法を見つけた点。
+素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。
-### Sanic
+強力な依存性注入の仕組みを持ち、コードの繰り返しを最小化する方法を見つけた点。
+
+///
+
+### [Sanic](https://sanic.readthedocs.io/en/latest/) { #sanic }
`asyncio`に基づいた、Pythonのフレームワークの中でも非常に高速なものの一つです。Flaskと非常に似た作りになっています。
-!!! note "技術詳細"
- Pythonの`asyncio`ループの代わりに、`uvloop`が利用されています。それにより、非常に高速です。
+/// note | 技術詳細
- `Uvicorn`と`Starlette`に明らかなインスピレーションを与えており、それらは現在オープンなベンチマークにおいてSanicより高速です。
+Pythonの`asyncio`ループの代わりに、[`uvloop`](https://github.com/MagicStack/uvloop)が利用されています。それにより、非常に高速です。
-!!! check "**FastAPI**へ与えたインスピレーション"
- 物凄い性能を出す方法を見つけた点。
+`Uvicorn`と`Starlette`に明らかなインスピレーションを与えており、それらは現在オープンなベンチマークにおいてSanicより高速です。
- **FastAPI**が、(サードパーティのベンチマークによりテストされた) 最も高速なフレームワークであるStarletteに基づいている理由です。
+///
-### Falcon
+/// check | **FastAPI**へ与えたインスピレーション
-Falconはもう一つの高性能Pythonフレームワークで、ミニマムに設計されており、Hugのような他のフレームワークの基盤として動作します。
+物凄い性能を出す方法を見つけた点。
-Pythonのウェブフレームワーク標準規格 (WSGI) を使用していますが、それは同期的であるためWebSocketなどの利用には対応していません。とはいえ、それでも非常に高い性能を持っています。
+**FastAPI**が、(サードパーティのベンチマークによりテストされた) 最も高速なフレームワークであるStarletteに基づいている理由です。
+
+///
+
+### [Falcon](https://falconframework.org/) { #falcon }
+
+Falconはもう一つの高性能Pythonフレームワークで、ミニマムに設計されており、Hugのような他のフレームワークの基盤として動作します。
これは、「リクエスト」と「レスポンス」の2つのパラメータを受け取る関数を持つように設計されています。そして、リクエストからデータを「読み込み」、レスポンスにデータを「書き込み」ます。この設計のため、Python標準の型ヒントでリクエストのパラメータやボディを関数の引数として宣言することはできません。
そのため、データのバリデーション、シリアライゼーション、ドキュメント化は、自動的にできずコードの中で行わなければなりません。あるいは、HugのようにFalconの上にフレームワークとして実装されなければなりません。このような分断は、パラメータとして1つのリクエストオブジェクトと1つのレスポンスオブジェクトを持つというFalconのデザインにインスピレーションを受けた他のフレームワークでも起こります。
-!!! check "**FastAPI**へ与えたインスピレーション"
- 素晴らしい性能を得るための方法を見つけた点。
+/// check | **FastAPI**へ与えたインスピレーション
+
+素晴らしい性能を得るための方法を見つけた点。
+
+Hug (HugはFalconをベースにしています) と一緒に、**FastAPI**が`response`引数を関数に持つことにインスピレーションを与えました。
- Hug (HugはFalconをベースにしています) と一緒に、**FastAPI**が`response`引数を関数に持つことにインスピレーションを与えました。
+**FastAPI**では任意ですが、ヘッダーやCookieやステータスコードを設定するために利用されています。
- **FastAPI**では任意ですが、ヘッダーやCookieやステータスコードを設定するために利用されています。
+///
-### Molten
+### [Molten](https://moltenframework.com/) { #molten }
**FastAPI**を構築する最初の段階でMoltenを発見しました。そして、それは非常に似たようなアイデアを持っています。
@@ -269,12 +313,15 @@ Pydanticのようなデータのバリデーション、シリアライゼーシ
ルーティングは一つの場所で宣言され、他の場所で宣言された関数を使用します (エンドポイントを扱う関数のすぐ上に配置できるデコレータを使用するのではなく) 。これはFlask (やStarlette) よりも、Djangoに近いです。これは、比較的緊密に結合されているものをコードの中で分離しています。
-!!! check "**FastAPI**へ与えたインスピレーション"
- モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。
+/// check | **FastAPI**へ与えたインスピレーション
- 同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピーレションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。)
+モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。
-### Hug
+同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピーレションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。)
+
+///
+
+### [Hug](https://github.com/hugapi/hug) { #hug }
Hugは、Pythonの型ヒントを利用してAPIパラメータの型宣言を実装した最初のフレームワークの1つです。これは素晴らしいアイデアで、他のツールが同じことをするきっかけとなりました。
@@ -288,17 +335,23 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ
以前のPythonの同期型Webフレームワーク標準 (WSGI) をベースにしているため、Websocketなどは扱えませんが、それでも高性能です。
-!!! info "情報"
- HugはTimothy Crosleyにより作成されました。彼は`isort`など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。
+/// info | 情報
+
+HugはTimothy Crosleyにより作成されました。彼は[`isort`](https://github.com/timothycrosley/isort)など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。
+
+///
+
+/// check | **FastAPI**へ与えたインスピレーション
+
+HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。
-!!! check "**FastAPI**へ与えたインスピレーション"
- HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。
+Hugは、**FastAPI**がPythonの型ヒントを用いてパラメータを宣言し自動的にAPIを定義するスキーマを生成することを触発しました。
- Hugは、**FastAPI**がPythonの型ヒントを用いてパラメータを宣言し自動的にAPIを定義するスキーマを生成することを触発しました。
+Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数に `response`引数を宣言することにインスピレーションを与えました。
- Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数に `response`引数を宣言することにインスピレーションを与えました。
+///
-### APIStar (<= 0.5)
+### [APIStar](https://github.com/encode/apistar) (<= 0.5) { #apistar-0-5 }
**FastAPI**を構築することを決める直前に、**APIStar**サーバーを見つけました。それは私が探していたものがほぼすべて含まれており、素晴らしいデザインでした。
@@ -322,27 +375,33 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ
今ではAPIStarはOpenAPI仕様を検証するためのツールセットであり、ウェブフレームワークではありません。
-!!! info "情報"
- APIStarはTom Christieにより開発されました。以下の開発者でもあります:
+/// info | 情報
- * Django REST Framework
- * Starlette (**FastAPI**のベースになっています)
- * Uvicorn (Starletteや**FastAPI**で利用されています)
+APIStarはTom Christieにより開発されました。以下の開発者でもあります:
-!!! check "**FastAPI**へ与えたインスピレーション"
- 存在そのもの。
+* Django REST Framework
+* Starlette (**FastAPI**のベースになっています)
+* Uvicorn (Starletteや**FastAPI**で利用されています)
- 複数の機能 (データのバリデーション、シリアライゼーション、ドキュメント化) を同じPython型で宣言し、同時に優れたエディタの補助を提供するというアイデアは、私にとって素晴らしいアイデアでした。
+///
- そして、長い間同じようなフレームワークを探し、多くの異なる代替ツールをテストした結果、APIStarが最良の選択肢となりました。
+/// check | **FastAPI**へ与えたインスピレーション
- その後、APIStarはサーバーとして存在しなくなり、Starletteが作られ、そのようなシステムのための新しくより良い基盤となりました。これが**FastAPI**を構築するための最終的なインスピレーションでした。
+存在そのもの。
- 私は、これまでのツールから学んだことをもとに、機能や型システムなどの部分を改善・拡充しながら、**FastAPI**をAPIStarの「精神的な後継者」と考えています。
+複数の機能 (データのバリデーション、シリアライゼーション、ドキュメント化) を同じPython型で宣言し、同時に優れたエディタの補助を提供するというアイデアは、私にとって素晴らしいアイデアでした。
-## **FastAPI**が利用しているもの
+そして、長い間同じようなフレームワークを探し、多くの異なる代替ツールをテストした結果、APIStarが最良の選択肢となりました。
-### Pydantic
+その後、APIStarはサーバーとして存在しなくなり、Starletteが作られ、そのようなシステムのための新しくより良い基盤となりました。これが**FastAPI**を構築するための最終的なインスピレーションでした。
+
+私は、これまでのツールから学んだことをもとに、機能や型システムなどの部分を改善・拡充しながら、**FastAPI**をAPIStarの「精神的な後継者」と考えています。
+
+///
+
+## **FastAPI**が利用しているもの { #used-by-fastapi }
+
+### [Pydantic](https://docs.pydantic.dev/) { #pydantic }
Pydanticは、Pythonの型ヒントを元にデータのバリデーション、シリアライゼーション、 (JSON Schemaを使用した) ドキュメントを定義するライブラリです。
@@ -350,14 +409,17 @@ Pydanticは、Pythonの型ヒントを元にデータのバリデーション、
Marshmallowに匹敵しますが、ベンチマークではMarshmallowよりも高速です。また、Pythonの型ヒントを元にしているので、エディタの補助が素晴らしいです。
-!!! check "**FastAPI**での使用用途"
- データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。
+/// check | **FastAPI**での使用用途
+
+データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。
+
+**FastAPI**はそのJSON SchemaデータをOpenAPIに取り込みます (それ以外にも多くのことを行います)。
- **FastAPI**はJSON SchemaのデータをOpenAPIに利用します。
+///
-### Starlette
+### [Starlette](https://www.starlette.dev/) { #starlette }
-Starletteは、軽量なASGIフレームワーク/ツールキットで、高性能な非同期サービスの構築に最適です。
+Starletteは、軽量なASGIフレームワーク/ツールキットで、高性能な非同期サービスの構築に最適です。
非常にシンプルで直感的です。簡単に拡張できるように設計されており、モジュール化されたコンポーネントを持っています。
@@ -365,15 +427,14 @@ Starletteは、軽量なUvicorn
+webに関するコアな部分を全て扱います。その上に機能を追加します。
+
+`FastAPI`クラスそのものは、`Starlette`クラスを直接継承しています。
+
+基本的にはStarletteの強化版であるため、Starletteで可能なことは**FastAPI**で直接可能です。
+
+///
+
+### [Uvicorn](https://www.uvicorn.dev/) { #uvicorn }
Uvicornは非常に高速なASGIサーバーで、uvloopとhttptoolsにより構成されています。
@@ -403,13 +470,16 @@ Uvicornは非常に高速なASGIサーバーで、uvloopとhttptoolsにより構
Starletteや**FastAPI**のサーバーとして推奨されています。
-!!! check "**FastAPI**が推奨する理由"
- **FastAPI**アプリケーションを実行するメインのウェブサーバーである点。
+/// check | **FastAPI**が推奨する理由
+
+**FastAPI**アプリケーションを実行するメインのウェブサーバーである点。
+
+コマンドラインオプション `--workers` を使って、非同期のマルチプロセスサーバーにできます。
- Gunicornと組み合わせることで、非同期でマルチプロセスなサーバーを持つことがきます。
+詳細は[デプロイ](deployment/index.md)の項目で確認してください。
- 詳細は[デプロイ](deployment/index.md){.internal-link target=_blank}の項目で確認してください。
+///
-## ベンチマーク と スピード
+## ベンチマーク と スピード { #benchmarks-and-speed }
-Uvicorn、Starlette、FastAPIの違いを理解、比較、確認するには、[ベンチマーク](benchmarks.md){.internal-link target=_blank}を確認してください。
+Uvicorn、Starlette、FastAPIの違いを理解、比較、確認するには、[ベンチマーク](benchmarks.md)を確認してください。
diff --git a/docs/ja/docs/async.md b/docs/ja/docs/async.md
index 8fac2cb38632e..e2886d74e219b 100644
--- a/docs/ja/docs/async.md
+++ b/docs/ja/docs/async.md
@@ -1,18 +1,18 @@
-# 並行処理と async / await
+# 並行処理と async / await { #concurrency-and-async-await }
-*path operation 関数*のための `async def` に関する詳細と非同期 (asynchronous) コード、並行処理 (Concurrency)、そして、並列処理 (Parallelism) の背景について。
+*path operation 関数*のための `async def` 構文に関する詳細と、非同期コード、並行処理、並列処理の背景についてです。
-## 急いでいますか?
+## 急いでいますか? { #in-a-hurry }
-TL;DR:
+TL;DR:
-次のような、`await` を使用して呼び出すべきサードパーティライブラリを使用している場合:
+次のように `await` で呼び出すよう指示されているサードパーティライブラリを使っているなら:
```Python
results = await some_library()
```
-以下の様に `async def` を使用して*path operation 関数*を宣言します。
+*path operation 関数*は次のように `async def` で宣言します:
```Python hl_lines="2"
@app.get('/')
@@ -21,12 +21,15 @@ async def read_results():
return results
```
-!!! note "備考"
- `async def` を使用して作成された関数の内部でしか `await` は使用できません。
+/// note | 備考
+
+`await` は `async def` で作られた関数の内部でしか使えません。
+
+///
---
-データベース、API、ファイルシステムなどと通信し、`await` の使用をサポートしていないサードパーティライブラリ (現在のほとんどのデータベースライブラリに当てはまります) を使用している場合、次の様に、単に `def` を使用して通常通り *path operation 関数* を宣言してください:
+データベース、API、ファイルシステムなどと通信しつつ `await` の使用をサポートしていないサードパーティライブラリ (現在のところ多くのデータベースライブラリが該当します) を使っている場合、*path operation 関数*は通常どおり `def` で宣言してください:
```Python hl_lines="2"
@app.get('/')
@@ -37,272 +40,307 @@ def results():
---
-アプリケーションが (どういうわけか) 他の何とも通信せず、応答を待つ必要がない場合は、`async def` を使用して下さい。
+アプリケーションが (何らかの理由で) ほかの何とも通信せず応答を待つ必要がないなら、`await` を内部で使わなくても `async def` を使ってください。
---
-よく分からない場合は、通常の `def` を使用して下さい。
+よく分からない場合は、通常の `def` を使ってください。
---
-**備考**: *path operation 関数*に必要なだけ `def` と `async def` を混在させ、それぞれに最適なオプションを使用して定義できます。それに応じてFastAPIは正しい処理を行います。
+**備考**: 必要に応じて *path operation 関数* では `def` と `async def` を混在させ、それぞれに最適な選択肢で定義できます。FastAPI は適切に処理します。
-とにかく、上記のいずれの場合でもFastAPIは非同期で動作し、非常に高速です。
+いずれの場合でも、FastAPI は非同期で動作し非常に高速です。
-しかし、上記のステップに従うことで、パフォーマンスの最適化を行えます。
+ただし上記の手順に従うことで、さらにパフォーマンス最適化が可能になります。
-## 技術詳細
+## 技術詳細 { #technical-details }
-現代版のPythonは「**非同期コード**」を、「**コルーチン**」と称されるものを利用してサポートしています。これは **`async` と `await`** 構文を用います。
+モダンな Python は **「非同期コード」** を **「コルーチン」** と呼ばれる仕組みでサポートしており、構文は **`async` と `await`** です。
-次のセクションで、フレーズ内のパーツを順に見ていきましょう:
+以下のセクションで、このフレーズをパーツごとに見ていきます:
* **非同期コード**
* **`async` と `await`**
* **コルーチン**
-## 非同期コード
+## 非同期コード { #asynchronous-code }
-非同期コードとは、言語💬がコード内のどこかで、コンピュータ/プログラム🤖に *他の何か* がどこか別の箇所で終了するのを待つように伝える手段を持っていることを意味します。*他の何か* は「遅いファイル📝」と呼ばれているとしましょう.
+非同期コードとは、言語 💬 がコードのどこかの時点で、コンピュータ/プログラム 🤖 に「どこか別のところで終わるまで、別の何か」を待つ必要があると伝える手段を持っている、ということです。その「別の何か」を「遅いファイル」📝 と呼ぶことにしましょう。
-したがって、コンピュータは「遅いファイル📝」が終了するまで、他の処理ができます。
+その間、コンピュータは「遅いファイル」📝 が終わるまで、他の作業を進められます。
-コンピュータ/プログラム🤖は再び待機する機会があるときや、その時点で行っていたすべての作業が完了するたびに戻ってきます。そして、必要な処理をしながら、コンピュータ/プログラム🤖が待っていた処理のどれかが終わっているかどうか確認します。
+その後、コンピュータ/プログラム 🤖 は、また待つ機会が来たときや、その時点で抱えていた作業をすべて終えたときに戻ってきます。そして、待っていたタスクのどれかが終わっていないか確認し、必要な処理を実行します。
-次に、それ🤖が最初のタスク (要するに、先程の「遅いファイル📝」)を終わらせて、そのタスクの結果を使う必要がある処理を続けます。
+次に、最初に終わったタスク (たとえば「遅いファイル」📝) を取り、続きの処理を行います。
-この「他の何かを待つ」とは、通常以下の様なものを待つような (プロセッサとRAMメモリの速度に比べて) 相対的に「遅い」I/O 操作を指します:
+この「別の何かを待つ」は、通常 I/O 操作を指し、(プロセッサや RAM の速度に比べて) 相対的に「遅い」待機を伴います。例えば次のようなものです:
-* ネットワーク経由でクライアントから送信されるデータ
-* ネットワーク経由でクライアントが受信する、プログラムから送信されたデータ
-* システムによって読み取られ、プログラムに渡されるディスク内のファイル内容
-* プログラムがシステムに渡して、ディスクに書き込む内容
-* リモートAPI操作
+* クライアントからネットワーク経由でデータが送られてくるのを待つ
+* プログラムが送信したデータをクライアントがネットワーク経由で受け取るのを待つ
+* ディスク上のファイル内容がシステムにより読み取られ、プログラムに渡されるのを待つ
+* プログラムがシステムに渡した内容がディスクに書き込まれるのを待つ
+* リモート API 操作
* データベース操作の完了
-* データベースクエリが結果を返すこと
-* など。
+* データベースクエリが結果を返すのを待つ
+* など
+
+実行時間の大半が I/O 操作の待ち時間に費やされるため、これらは「I/O バウンド」な操作と呼ばれます。
+
+「非同期」と呼ばれるのは、コンピュータ/プログラムがその遅いタスクと「同期」(タスクがちょうど終わる瞬間を、何もせずに待つ) する必要がないからです。結果を受け取って処理を続けるために、空待ちする必要がありません。
+
+代わりに「非同期」システムでは、タスクが終わったら、コンピュータ/プログラムが取りかかっている作業が終わるまで (数マイクロ秒ほど) 少し待ち、結果を受け取りに戻って処理を続けられます。
+
+「非同期」と対になる「同期」は、「シーケンシャル」と呼ばれることもあります。待機が含まれていても、別のタスクに切り替える前にコンピュータ/プログラムが手順を順番に実行するためです。
+
+### 並行処理とハンバーガー { #concurrency-and-burgers }
+
+上で説明した**非同期**コードの考え方は、**「並行処理」** と呼ばれることもあります。これは **「並列処理」** とは異なります。
-実行時間のほとんどがI/O 操作の待ち時間が占めるため、このような操作を「I/O バウンド」操作と言います。
+**並行処理** も **並列処理** も、「複数のことがだいたい同時に起きる」ことに関係します。
-コンピュータ/プログラムがこのような遅いタスクと「同期 (タスクの結果を取得して作業を続行するために、何もせずに、タスクが完了する瞬間を正確に待つ)」する必要がないため、「非同期」と呼ばれます。
+ただし、*並行処理* と *並列処理* の詳細はかなり異なります。
-その代わりに、「非同期」システムであることにより、いったん終了すると、タスクは、コンピュータ/プログラムが既に開始した処理がすべて完了するのをほんの少し (数マイクロ秒) 待って、結果を受け取りに戻ってきます。そして、処理を継続します。
+違いを見るために、ハンバーガーに関する次の物語を想像してみてください。
-「同期」の場合 (「非同期」とは異なり)、「シーケンシャル」という用語もよく使用されます。これは、コンピュータ/プログラムがすべてのステップを (待機が伴う場合でも別のタスクに切り替えることなく) 順番に実行するためです。
+### 並行ハンバーガー { #concurrent-burgers }
-### 並行処理とハンバーガー
+あなたは好きな人とファストフードを買いに行き、前の人たちの注文をレジ係が受ける間、列に並びます。😍
-上記の**非同期**コードのアイデアは、**「並行処理」**と呼ばれることもあります。 **「並列処理」**とは異なります。
+
-**並行処理**と**並列処理**はどちらも「多かれ少なかれ同時に発生するさまざまなこと」に関連しています。
+やがてあなたの番になり、好きな人と自分のために、とても豪華なハンバーガーを2つ注文します。🍔🍔
-ただし、*並行処理*と*並列処理*の詳細はまったく異なります。
+
-違いを確認するには、ハンバーガーに関する次の物語を想像してみてください:
+レジ係はキッチンの料理人に、あなたのハンバーガーを用意するよう声をかけます (料理人はいま前のお客さんの分を作っています)。
-### 並行ハンバーガー
+
-ファストフード🍔を食べようと、好きな人😍とレジに並んでおり、レジ係💁があなたの前にいる人達の注文を受けつけています。
+支払いをします。💸
-それからあなたの番になり、好きな人😍と自分のために、2つの非常に豪華なハンバーガー🍔を注文します。
+レジ係はあなたに番号札を渡します。
-料金を支払います💸。
+
-レジ係💁はキッチンの男👨🍳に向かって、あなたのハンバーガー🍔を準備しなければならないと伝えるために何か言いました (彼は現在、前のお客さんの商品を準備していますが)。
+待っている間、好きな人とテーブルに移動して座り、(豪華なハンバーガーは時間がかかるので) しばらく話します。
-レジ係💁はあなたに番号札を渡します。
+テーブルで待っている間、好きな人がどれだけ素敵で、かわいくて、頭が良いかを眺めて時間を過ごせます ✨😍✨。
-待っている間、好きな人😍と一緒にテーブルを選んで座り、好きな人😍と長い間話をします (注文したハンバーガーは非常に豪華で、準備に少し時間がかかるので✨🍔✨)。
+
-ハンバーガー🍔を待ちながら好きな人😍とテーブルに座っている間、あなたの好きな人がなんて素晴らしく、かわいくて頭がいいんだと✨😍✨惚れ惚れしながら時間を費やすことができます。
+時々カウンターの表示を見て、自分の番号になっているか確認します。
-好きな人😍と話しながら待っている間、ときどき、カウンターに表示されている番号をチェックして、自分の番かどうかを確認します。
+やがてあなたの番になります。カウンターに行き、ハンバーガーを受け取り、テーブルに戻ります。
-その後、ついにあなたの番になりました。カウンターに行き、ハンバーガー🍔を手に入れてテーブルに戻ります。
+
-あなたとあなたの好きな人😍はハンバーガー🍔を食べて、楽しい時間を過ごします✨。
+あなたと好きな人はハンバーガーを食べて、楽しい時間を過ごします。✨
+
+
+
+/// info | 情報
+
+美しいイラストは [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot) によるものです。🎨
+
+///
---
-上記のストーリーで、あなたがコンピュータ/プログラム🤖だと想像してみてください。
+この物語で、あなた自身がコンピュータ/プログラム 🤖 だと想像してみてください。
-列にいる間、あなたはアイドル状態です😴。何も「生産的」なことをせず、ただ自分の番を待っています。しかし、レジ係💁は注文を受け取るだけなので (商品の準備をしているわけではない)、列は高速です。したがって、何も問題ありません。
+列にいる間は、何も「生産的」なことをせず、自分の番を待つだけのアイドル状態 😴 です。ただしレジ係は注文を取るだけ (作りはしない) なので列は速く進み、問題ありません。
-それから、あなたの番になったら、実に「生産的な」作業を行います🤓、メニューを確認し、欲しいものを決め、好きな人😍の欲しいものを聞き、料金を支払い💸、現金またはカードを正しく渡したか確認し、正しく清算されたことを確認し、注文が正しく通っているかなどを確認します。
+あなたの番になると、実際に「生産的」な作業をします。メニューを見て注文を決め、好きな人の分も確認し、支払い、正しい紙幣/カードを渡したか、正しく決済されたか、注文内容が正しいかなどを確認します。
-しかし、ハンバーガー🍔をまだできていないので、ハンバーガーの準備ができるまで待機🕙する必要があるため、レジ係💁との作業は「一時停止⏸」になります。
+しかし、ハンバーガーはまだ出来上がっていないので、レジ係とのやり取りは「一時停止」⏸ になります。ハンバーガーができるまで待つ 🕙 必要があるからです。
-しかし、カウンターから離れて、番号札を持ってテーブルに座っているときは、注意を好きな人😍に切り替えて🔀、その上で「仕事⏯🤓」を行なえます。その後、好きな人😍といちゃつくかのような、非常に「生産的な🤓」ことを再び行います。
+ただし、番号札を持ってカウンターから離れテーブルに座れば、注意を好きな人に切り替え 🔀、「その作業」⏯ 🤓 に取り組めます。好きな人といちゃつくという、とても「生産的」🤓 なことがまたできます。
-次に、レジ係💁は、「ハンバーガーの準備ができました🍔」と言って、カウンターのディスプレイに番号を表示しますが、表示番号があなたの番号に変わっても、すぐに狂ったように飛んで行くようなことはありません。あなたは自分の番号札を持っていって、他の人も自分の番号札があるので、あなたのハンバーガー🍔を盗む人がいないことは知っています。
+レジ係 💁 がカウンターの表示にあなたの番号を出して「ハンバーガーができました」と知らせても、あなたは表示が切り替わった瞬間に飛び跳ねたりしません。自分の番号札があり、他の人にもそれぞれ番号札があるので、ハンバーガーを盗られることはないと知っているからです。
-なので、あなたは好きな人😍が話し終えるのを待って (現在の仕事⏯ / 処理中のタスクを終了します🤓)、優しく微笑んで、ハンバーガーを貰ってくるねと言います⏸。
+だから、好きな人の話が終わるのを待ち (現在の作業 ⏯ / 処理中のタスクを完了し 🤓)、微笑んで「ハンバーガー取ってくるね」と言います ⏸。
-次に、カウンターへ、いまから完了する最初のタスク⏯へ向かい、ハンバーガー🍔を受け取り、感謝の意を表して、テーブルに持っていきます。これで、カウンターとのやり取りのステップ/タスクが完了しました⏹。これにより、「ハンバーガーを食べる🔀⏯」という新しいタスクが作成されます。しかし、前の「ハンバーガーを取得する」というタスクは終了しました⏹。
+それからカウンターへ行き 🔀、いま完了した初期のタスク ⏯ に戻って、ハンバーガーを受け取り、礼を言ってテーブルに持っていきます。これでカウンターとのやり取りというステップ/タスクは完了 ⏹ です。その結果として「ハンバーガーを食べる」🔀 ⏯ という新しいタスクが生まれますが、先の「ハンバーガーを受け取る」タスクは完了 ⏹ しています。
-### 並列ハンバーガー
+### 並列ハンバーガー { #parallel-burgers }
-これらが「並行ハンバーガー」ではなく、「並列ハンバーガー」であるとしましょう。
+今度は、これが「並行ハンバーガー」ではなく「並列ハンバーガー」だと想像しましょう。
-あなたは好きな人😍と並列ファストフード🍔を買おうとしています。
+あなたは好きな人と「並列」ファストフードを買いに行きます。
-列に並んでいますが、何人かの料理人兼、レジ係 (8人としましょう) 👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳があなたの前にいる人達の注文を受けつけています。
+複数のレジ係 (例えば 8 人) が同時に料理人でもあり、前の人たちの注文を受けています。
-8人のレジ係がそれぞれ自分で注文を受けるや否や、次の注文を受ける前にハンバーガーを準備するので、あなたの前の人達はカウンターを離れずに、ハンバーガー🍔ができるのを待っています🕙。
+8 人のレジ係はそれぞれ、次の注文を取る前にすぐに調理に取りかかるため、あなたの前の人たちはカウンターを離れず、ハンバーガーができるのを待っています。
-それからいよいよあなたの番になり、好きな人😍と自分のために、2つの非常に豪華なハンバーガー🍔を注文します。
+
-料金を支払います💸。
+ようやくあなたの番になり、好きな人と自分のために豪華なハンバーガーを 2 つ注文します。
-レジ係はキッチンに行きます👨🍳。
+支払いをします 💸。
-あなたはカウンターの前に立って待ちます🕙。番号札がないので誰もあなたよりも先にハンバーガー🍔を取らないようにします。
+
-あなたと好きな人😍は忙しいので、誰もあなたの前に来させませんし、あなたのハンバーガーが到着したとき🕙に誰にも取ることを許しません。あなたは好きな人に注意を払えません😞。
+レジ係はキッチンに向かいます。
-これは「同期」作業であり、レジ係/料理人👨🍳と「同期」します。レジ係/料理人👨🍳がハンバーガー🍔を完成させてあなたに渡すまで待つ🕙必要があり、ちょうどその完成の瞬間にそこにいる必要があります。そうでなければ、他の誰かに取られるかもしれません。
+番号札がないため、他の誰かに先に取られないよう、カウンターの前で立って待ちます 🕙。
-その後、カウンターの前で長い時間待ってから🕙、ついにレジ係/料理人👨🍳がハンバーガー🍔を渡しに戻ってきます。
+
-ハンバーガー🍔を取り、好きな人😍とテーブルに行きます。
+あなたと好きな人は、誰にも割り込まれずハンバーガーが来たらすぐ受け取れるよう見張っているので、好きな人に注意を向けられません。😞
-ただ食べるだけ、それでおしまいです。🍔⏹。
+これは「同期」的な作業です。レジ係/料理人 👨🍳 と「同期」しています。レジ係/料理人 👨🍳 がハンバーガーを作り終えて手渡すその瞬間に、待って 🕙 その場にいなければなりません。そうでないと他の誰かに取られるかもしれません。
-ほとんどの時間、カウンターの前で待つのに費やされていたので🕙、あまり話したりいちゃつくことはありませんでした😞。
+
----
+長い時間 🕙 カウンター前で待った後、ようやくレジ係/料理人 👨🍳 がハンバーガーを持って戻ってきます。
+
+
+
+ハンバーガーを受け取り、好きな人とテーブルに行きます。
+
+食べて、おしまいです。⏹
-この並列ハンバーガーのシナリオでは、あなたは2つのプロセッサを備えたコンピュータ/プログラム🤖 (あなたとあなたの好きな人😍) であり、両方とも待機🕙していて、彼らは「カウンターで待機🕙」することに専念しています⏯。
+
-ファストフード店には8つのプロセッサ (レジ係/料理人) 👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳があります。一方、並行ハンバーガー店には2人 (レジ係と料理人) 💁👨🍳しかいなかったかもしれません。
+ほとんどの時間をカウンター前で待つ 🕙 のに費やしたため、あまり話したり、いちゃついたりできませんでした。😞
-しかし、それでも、最終的な体験は最高ではありません😞。
+/// info | 情報
+
+美しいイラストは [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot) によるものです。🎨
+
+///
---
-これは、ハンバーガー🍔の話と同等な話になります。
+この「並列ハンバーガー」のシナリオでは、あなたは 2 つのプロセッサ (あなたと好きな人) を持つコンピュータ/プログラム 🤖 で、どちらも長い間 🕙「カウンターでの待機」に注意 ⏯ を専念しています。
-より「現実的な」例として、銀行を想像してみてください。
+ファストフード店には 8 個のプロセッサ (レジ係/料理人) があります。一方、並行ハンバーガーの店には (レジ係 1、人、料理人 1 人の) 2 個しかなかったかもしれません。
+
+それでも、最終的な体験は最良とは言えません。😞
-最近まで、ほとんどの銀行は複数の窓口👨💼👨💼👨💼👨💼に、行列🕙🕙🕙🕙🕙🕙🕙🕙ができていました。
+---
+
+これはハンバーガーにおける並列版の物語です。🍔
-すべての窓口で、次々と、一人の客とすべての作業を行います👨💼⏯.
+より「現実的な」例として、銀行を想像してみてください。
-その上、長時間、列に並ばなければいけません🕙。そうしないと、順番が回ってきません。
+つい最近まで、ほとんどの銀行には複数の窓口係 👨💼👨💼👨💼👨💼 と長い行列 🕙🕙🕙🕙🕙🕙🕙🕙 がありました。
-銀行🏦での用事にあなたの好きな人😍を連れて行きたくはないでしょう。
+各窓口係が、一人ずつ、すべての作業を順番に行います 👨💼⏯。
-### ハンバーガーのまとめ
+そして、長時間 🕙 行列で待たなければ順番を失います。
-この「好きな人とのファストフードハンバーガー」のシナリオでは、待機🕙が多いため、並行システム⏸🔀⏯を使用する方がはるかに理にかなっています。
+銀行の用事 🏦 に、好きな人 😍 を連れて行きたいとは思わないでしょう。
-これは、ほとんどのWebアプリケーションに当てはまります。
+### ハンバーガーのまとめ { #burger-conclusion }
-多くのユーザーがいますが、サーバーは、あまり強くない回線でのリクエストの送信を待機🕙しています。
+この「好きな人とファストフード」のシナリオでは、待ち時間 🕙 が多いため、並行システム ⏸🔀⏯ を使う方がはるかに理にかなっています。
-そして、レスポンスが返ってくるのをもう一度待機🕙します。
+これは、ほとんどの Web アプリケーションにも当てはまります。
-この「待機🕙」はマイクロ秒単位ですが、それでも、すべて合算すると、最終的にはかなり待機することになります。
+とても多くのユーザーがいますが、サーバは彼らのあまり速くない回線からリクエストが届くのを待ち 🕙、
-これが、Web APIへの非同期⏸🔀⏯コードの利用が理にかなっている理由です。
+その後、レスポンスが戻ってくるのをまた待ちます 🕙。
-ほとんどの既存の人気のあるPythonフレームワーク (FlaskやDjangoを含む) は、Pythonの新しい非同期機能ができる前に作成されました。したがって、それらをデプロイする方法は、並列実行と、新機能ほど強力ではない古い形式の非同期実行をサポートします。
+この「待ち」🕙 はマイクロ秒単位で測られますが、すべてを合計すると、結局かなりの待ちになります。
-しかし、WebSocketのサポートを追加するために、非同期Web Python (ASGI) の主な仕様はDjangoで開発されました。
+だからこそ、Web API には非同期 ⏸🔀⏯ コードを使うのが理にかなっています。
-そのような非同期性がNodeJSを人気にした理由です (NodeJSは並列ではありませんが)。そして、プログラミング言語としてのGoの強みでもあります。
+これが、NodeJS を人気にした要因 (NodeJS 自体は並列ではありません) であり、プログラミング言語としての Go の強みでもあります。
-そして、それは**FastAPI**で得られるパフォーマンスと同じレベルです。
+そして、それが **FastAPI** で得られるパフォーマンスの水準です。
-また、並列処理と非同期処理を同時に実行できるため、テスト済みのほとんどのNodeJSフレームワークよりも高く、Goと同等のパフォーマンスが得られます。Goは、Cに近いコンパイル言語です (Starletteに感謝します)。
+さらに、並列性と非同期性を同時に活用できるため、テストされた多くの NodeJS フレームワークより高い性能を発揮し、C に近いコンパイル言語である Go と同等の性能になります [(すべて Starlette のおかげです)](https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=query&l=zijmkf-1)。
-### 並行は並列よりも優れていますか?
+### 並行処理は並列処理より優れている? { #is-concurrency-better-than-parallelism }
-いや!それはこの話の教訓ではありません。
+いいえ!それがこの話の教訓ではありません。
-並行処理は並列処理とは異なります。多くの待機を伴う**特定の**シナリオに適しています。そのため、一般に、Webアプリケーション開発では並列処理よりもはるかに優れています。しかし、すべてに対してより良いというわけではありません。
+並行処理は並列処理とは異なります。そして多くの待ち時間を伴う**特定の**シナリオでは優れています。そのため、一般に Web アプリ開発では並列処理よりはるかに適しています。しかし、すべてに対して最良というわけではありません。
-なので、バランスをとるために、次の物語を想像して下さい:
+バランスを取るために、次の短い物語を想像してください。
-> あなたは大きくて汚れた家を掃除する必要があります。
+> 大きくて汚れた家を掃除しなければならない。
-*はい、以上です*。
+*はい、これで物語は全部です*。
---
-待機🕙せず、家の中の複数の場所でたくさんの仕事をするだけです。
+どこにも待ち 🕙 はなく、家の複数箇所で大量の作業があるだけです。
-あなたはハンバーガーの例のように、最初はリビングルーム、次にキッチンのように順番にやっていくことができますが、何かを待機🕙しているわけではなく、ただひたすらに掃除をするだけで、順番は何にも影響しません。
+ハンバーガーの例のように順番を決めて、まずリビング、次にキッチン、と進めてもよいのですが、何かを待つ 🕙 わけではなく、ひたすら掃除するだけなので、順番は何も影響しません。
-順番の有無に関係なく (並行に) 同じ時間がかかり、同じ量の作業が行われることになるでしょう。
+順番の有無 (並行性の有無) に関係なく、終了までに同じ時間がかかり、同じ作業量をこなすことになります。
-しかし、この場合、8人の元レジ係/料理人/現役清掃員👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳👨🍳を手配できて、それぞれ (さらにあなたも) が家の別々の場所を掃除できれば、追加の助けを借りて、すべての作業を**並列**に行い、はるかに早く終了できるでしょう。
+しかしこの場合、8 人の元レジ係/料理人/現清掃員を連れてきて、それぞれ (あなたも加えて) 家の別々のエリアを掃除できれば、**並列** に作業でき、より早く終えられます。
-このシナリオでは、清掃員 (あなたを含む) のそれぞれがプロセッサとなり、それぞれの役割を果たします。
+このシナリオでは、各清掃員 (あなたを含む) がプロセッサであり、それぞれが自分の役割を果たします。
-また、実行時間のほとんどは (待機ではなく) 実際の作業に費やされ、コンピュータでの作業はCPUによって行われます。これらの問題は「CPUバウンド」と言います。
+そして実行時間の大半は (待ちではなく) 実作業が占め、コンピュータでの作業は CPU によって行われます。これらの問題は「CPU バウンド」と呼ばれます。
---
-CPUバウンド操作の一般的な例は、複雑な数学処理が必要なものです。
+CPU バウンドな操作の一般的な例は、複雑な数値処理が必要なものです。
例えば:
* **オーディオ** や **画像処理**。
-* **コンピュータビジョン**: 画像は数百万のピクセルで構成され、各ピクセルには3つの値/色があり、通常、これらのピクセルで何かを同時に計算する必要がある処理。
-* **機械学習**: 通常、多くの「行列」と「ベクトル」の乗算が必要です。巨大なスプレッドシートに数字を入れて、それを同時に全部掛け合わせることを考えてみてください。
-* **ディープラーニング**: これは機械学習のサブフィールドであるため、同じことが当てはまります。乗算する数字がある単一のスプレッドシートではなく、それらの膨大な集合で、多くの場合、それらのモデルを構築および/または使用するために特別なプロセッサを使用します。
+* **コンピュータビジョン**: 画像は数百万のピクセルで構成され、各ピクセルには 3 つの値/色があり、通常、それらのピクセル上で同時に何かを計算する必要があります。
+* **機械学習**: 多くの「行列」や「ベクトル」の乗算が必要になります。巨大なスプレッドシートに数字が入っていて、それらを同時にすべて掛け合わせることを想像してください。
+* **ディープラーニング**: 機械学習のサブフィールドなので同様です。掛け合わせる数字が 1 つのスプレッドシートではなく膨大な集合であり、多くの場合、それらのモデルを構築/利用するための特別なプロセッサを使います。
-### 並行処理 + 並列処理: Web + 機械学習
+### 並行処理 + 並列処理: Web + 機械学習 { #concurrency-parallelism-web-machine-learning }
-**FastAPI**を使用すると、Web開発で非常に一般的な並行処理 (NodeJSの主な魅力と同じもの) を利用できます。
+**FastAPI** では、Web 開発で非常に一般的な並行処理 (NodeJS の主な魅力と同じ) を活用できます。
-ただし、機械学習システムのような **CPUバウンド** ワークロードに対して、並列処理とマルチプロセッシング (複数のプロセスが並列で実行される) の利点を活用することもできます。
+同時に、機械学習システムのような **CPU バウンド** なワークロードに対して、並列処理やマルチプロセッシング (複数プロセスの並列実行) の利点も活用できます。
-さらに、Pythonが**データサイエンス**、機械学習、特にディープラーニングの主要言語であるという単純な事実により、FastAPIはデータサイエンス/機械学習のWeb APIおよびアプリケーション (他の多くのアプリケーションとの) に非常によく適合しています。
+さらに、Python が **データサイエンス**、機械学習、特にディープラーニングの主要言語であるという事実も相まって、FastAPI はデータサイエンス/機械学習の Web API やアプリケーション (ほか多数) に非常に適しています。
-本番環境でこの並列処理を実現する方法については、[デプロイ](deployment/index.md){.internal-link target=_blank}に関するセクションを参照してください。
+本番環境でこの並列性を実現する方法は、[デプロイ](deployment/index.md) のセクションを参照してください。
-## `async` と `await`
+## `async` と `await` { #async-and-await }
-現代的なバージョンのPythonには、非同期コードを定義する非常に直感的な方法があります。これにより、通常の「シーケンシャル」コードのように見え、適切なタイミングで「待機」します。
+モダンな Python には、非同期コードをとても直感的に定義する方法があります。これにより、通常の「シーケンシャル」なコードのように書けて、適切なタイミングで「待ち」を行ってくれます。
-結果を返す前に待機する必要があり、これらの新しいPython機能をサポートする操作がある場合は、次のようにコーディングできます。
+結果を返す前に待ちが必要で、これらの新しい Python 機能をサポートしている操作がある場合、次のように書けます。
```Python
burgers = await get_burgers(2)
```
-カギは `await` です。結果を `burgers`に保存する前に、`get_burgers(2)`の処理🕙の完了を待つ⏸必要があることをPythonに伝えます。これでPythonは、その間に (別のリクエストを受信するなど) 何か他のことができる🔀⏯ことを知ります。
+ここでの鍵は `await` です。`burgers` に結果を保存する前に、`get_burgers(2)` がやるべきことを終えるのを ⏸ 待つ 🕙 ように Python に伝えます。これにより Python は、その間に (別のリクエストを受け取るなど) ほかのことを 🔀 ⏯ できると分かります。
-`await` が機能するためには、非同期処理をサポートする関数内にある必要があります。これは、`async def` で関数を宣言するだけでよいです:
+`await` が機能するには、この非同期性をサポートする関数の内部でなければなりません。そのためには `async def` で宣言します:
```Python hl_lines="1"
async def get_burgers(number: int):
- # ハンバーガーを作成するために非同期処理を実行
+ # ハンバーガーを作るために非同期の処理を行う
return burgers
```
-...`def` のかわりに:
+...`def` の代わりに:
```Python hl_lines="2"
-# 非同期ではない
+# これは非同期ではない
def get_sequential_burgers(number: int):
- # ハンバーガーを作成するためにシーケンシャルな処理を実行
+ # ハンバーガーを作るためにシーケンシャルな処理を行う
return burgers
```
-`async def` を使用すると、Pythonにその関数内で `await` 式 (その関数の実行を「一時停止⏸」し、結果が戻るまで他の何かを実行🔀する) を認識しなければならないと伝えることができます。
-`async def` 関数を呼び出すときは、「await」しなければなりません。したがって、これは機能しません:
+`async def` を使うと、Python はその関数内で `await` 式に注意し、関数の実行を「一時停止」⏸ してほかのことをしに行き 🔀、戻ってくることができると分かります。
+
+`async def` な関数を呼ぶときは「await」しなければなりません。したがって、次は動きません:
```Python
-# get_burgersはasync defで定義されているので動作しない
+# 動きません。get_burgers は async def で定義されています
burgers = get_burgers(2)
```
---
-したがって、 `await` で呼び出すことができるライブラリを使用している場合は、次のように `async def` を使用して、それを使用する*path operation 関数*を作成する必要があります:
+そのため、`await` で呼べると謳っているライブラリを使っている場合は、それを使う *path operation 関数* を `async def` で作る必要があります。例えば:
```Python hl_lines="2-3"
@app.get('/burgers')
@@ -311,83 +349,96 @@ async def read_burgers():
return burgers
```
-### より発展的な技術詳細
+### より発展的な技術詳細 { #more-technical-details }
+
+`await` は `async def` で定義された関数の内部でしか使えないことに気づいたかもしれません。
+
+同時に、`async def` で定義された関数は「await」される必要があります。つまり、`async def` を持つ関数は、やはり `async def` で定義された関数の内部からしか呼べません。
+
+では、ニワトリと卵の話のように、最初の `async` 関数はどう呼ぶのでしょうか?
+
+**FastAPI** を使っている場合は心配ありません。その「最初の」関数は *path operation 関数* で、FastAPI が適切に実行してくれます。
+
+しかし、FastAPI を使わずに `async` / `await` を使いたい場合もあります。
+
+### 自分で async コードを書く { #write-your-own-async-code }
+
+Starlette (**FastAPI** も) は [AnyIO](https://anyio.readthedocs.io/en/stable/) の上に構築されており、標準ライブラリの [asyncio](https://docs.python.org/3/library/asyncio-task.html) と [Trio](https://trio.readthedocs.io/en/stable/) の両方に対応しています。
-`await` は `async def` で定義された関数内でのみ使用できることがわかったかと思います。
+特に、あなた自身のコード内で、より高度なパターンを必要とする発展的な並行処理のユースケースに対して、[AnyIO](https://anyio.readthedocs.io/en/stable/) を直接使えます。
-しかし同時に、`async def` で定義された関数は「awaitされる」必要があります。なので、`async def` を持つ関数は、`async def` で定義された関数内でのみ呼び出せます。
+仮に FastAPI を使っていなくても、[AnyIO](https://anyio.readthedocs.io/en/stable/) で独自の async アプリケーションを書けば、高い互換性と利点 (例: 構造化並行性) を得られます。
-では、このニワトリと卵の問題について、最初の `async` 関数をどのように呼び出すのでしょうか?
+私は AnyIO の上に薄い層として、型注釈を少し改善し、より良い**補完**や**インラインエラー**などを得るための別ライブラリも作りました。また、**理解**して**自分で async コードを書く**のに役立つフレンドリーなイントロ/チュートリアルもあります: [Asyncer](https://asyncer.tiangolo.com/)。特に、**async コードと通常の** (ブロッキング/同期) **コードを組み合わせる**必要がある場合に有用です。
-**FastAPI**を使用している場合、その「最初の」関数が*path operation 関数*であり、FastAPIが正しく実行する方法を知っているので、心配する必要はありません。
+### 非同期コードの他の形式 { #other-forms-of-asynchronous-code }
-しかし、FastAPI以外で `async` / `await` を使用したい場合は、公式Pythonドキュメントを参照して下さい。
+`async` と `await` を使うこのスタイルは、言語としては比較的新しいものです。
-### 非同期コードの他の形式
+しかし、これにより非同期コードの取り扱いは大幅に簡単になります。
-`async` と `await` を使用するスタイルは、この言語では比較的新しいものです。
+同等 (ほぼ同一) の構文が最近の JavaScript (ブラウザと NodeJS) にも導入されました。
-非同期コードの操作がはるかに簡単になります。
+それ以前は、非同期コードの扱いはかなり複雑で難解でした。
-等価な (またはほとんど同一の) 構文が、最近のバージョンのJavaScript (ブラウザおよびNodeJS) にも最近組み込まれました。
+以前の Python ではスレッドや [Gevent](https://www.gevent.org/) を使えましたが、コードの理解・デバッグ・思考がはるかに難しくなります。
-しかし、その前は、非同期コードの処理はかなり複雑で難解でした。
+以前の NodeJS / ブラウザ JavaScript では「コールバック」を使っており、「コールバック地獄」を招きました。
-以前のバージョンのPythonでは、スレッドやGeventが利用できました。しかし、コードは理解、デバック、そして、考察がはるかに複雑です。
+## コルーチン { #coroutines }
-以前のバージョンのNodeJS / ブラウザJavaScriptでは、「コールバック」を使用していました。これは、コールバック地獄につながります。
+**コルーチン**は、`async def` 関数が返すものを指す、ちょっと洒落た用語です。Python はそれを、開始できていつか終了する関数のようなものとして扱いますが、内部に `await` があるたびに内部的に一時停止 ⏸ するかもしれないものとして認識します。
-## コルーチン
+`async` と `await` を用いた非同期コードの機能全体は、しばしば「コルーチンを使う」と要約されます。これは Go の主要機能「Goroutines」に相当します。
-**コルーチン**は、`async def` 関数によって返されるものを指す非常に洒落た用語です。これは、開始できて、いつか終了する関数のようなものであるが、内部に `await` があるときは内部的に一時停止⏸されることもあるものだとPythonは認識しています。
+## まとめ { #conclusion }
-`async` と `await` を用いた非同期コードを使用するすべての機能は、「コルーチン」を使用するものとして何度もまとめられています。Goの主要機能である「ゴルーチン」に相当します。
+上のフレーズをもう一度見てみましょう:
-## まとめ
+> モダンな Python は **「非同期コード」** を **「コルーチン」** と呼ばれる仕組みでサポートしており、構文は **`async` と `await`** です。
-上述したフレーズを見てみましょう:
+今なら、より意味が分かるはずです。✨
-> 現代版のPythonは「**非同期コード**」を、「**コルーチン**」と称されるものを利用してサポートしています。これは **`async` と `await`** 構文を用います。
+これらすべてが (Starlette を通じて) FastAPI を支え、印象的なパフォーマンスを実現しています。
-今では、この意味がより理解できるはずです。✨
+## 非常に発展的な技術的詳細 { #very-technical-details }
-(Starletteを介して) FastAPIに力を与えて、印象的なパフォーマンスを実現しているものはこれがすべてです。
+/// warning | 注意
-## 非常に発展的な技術的詳細
+おそらく読み飛ばしても大丈夫です。
-!!! warning "注意"
- 恐らくスキップしても良いでしょう。
+これは **FastAPI** の内部動作に関する、とても技術的な詳細です。
- この部分は**FastAPI**の仕組みに関する非常に技術的な詳細です。
+(コルーチン、スレッド、ブロッキング等の) 技術知識があり、FastAPI が `async def` と通常の `def` をどう扱うかに興味がある場合は、読み進めてください。
- かなりの技術知識 (コルーチン、スレッド、ブロッキングなど) があり、FastAPIが `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。
+///
-### Path operation 関数
+### Path operation 関数 { #path-operation-functions }
-*path operation 関数*を `async def` の代わりに通常の `def` で宣言すると、(サーバーをブロックするので) 直接呼び出す代わりに外部スレッドプール (awaitされる) で実行されます。
+*path operation 関数* を `async def` ではなく通常の `def` で宣言した場合、(サーバをブロックしてしまうため) 直接呼び出されるのではなく、外部のスレッドプールで実行され、それを待機します。
-上記の方法と違った方法の別の非同期フレームワークから来ており、小さなパフォーマンス向上 (約100ナノ秒) のために通常の `def` を使用して些細な演算のみ行う *path operation 関数* を定義するのに慣れている場合は、**FastAPI**ではまったく逆の効果になることに注意してください。このような場合、*path operation 関数* がブロッキングI/Oを実行しないのであれば、`async def` の使用をお勧めします。
+上記とは異なる動作の別の非同期フレームワークから来ており、ほんのわずかなパフォーマンス向上 (約 100 ナノ秒) を狙って、計算のみの些細な *path operation 関数* を素の `def` で定義することに慣れている場合、**FastAPI** では効果がまったく逆になる点に注意してください。これらの場合、*path operation 関数* がブロッキングな I/O を行うコードを使っていない限り、`async def` を使った方が良いです。
-それでも、どちらの状況でも、**FastAPI**が過去のフレームワークよりも (またはそれに匹敵するほど) [高速になる](/#performance){.internal-link target=_blank}可能性があります。
+それでも、どちらの状況でも、**FastAPI** はあなたが以前使っていたフレームワークよりも (少なくとも同等に) [高速である](index.md#performance) 可能性が高いです。
-### 依存関係
+### 依存関係 { #dependencies }
-依存関係についても同様です。依存関係が `async def` ではなく標準の `def` 関数である場合、外部スレッドプールで実行されます。
+[依存関係](tutorial/dependencies/index.md) についても同様です。依存関係が `async def` ではなく標準の `def` 関数である場合、外部のスレッドプールで実行されます。
-### サブ依存関係
+### サブ依存関係 { #sub-dependencies }
-(関数定義のパラメーターとして) 相互に必要な複数の依存関係とサブ依存関係を設定できます。一部は `async def` で作成され、他の一部は通常の `def` で作成されます。それでも動作し、通常の `def`で作成されたものは、「awaitされる」代わりに (スレッドプールから) 外部スレッドで呼び出されます。
+複数の依存関係や [サブ依存関係](tutorial/dependencies/sub-dependencies.md) を (関数定義のパラメータとして) 相互に要求させられます。その一部は `async def`、他は通常の `def` で作られていても動作します。通常の `def` で作られたものは「await」される代わりに、外部スレッドプールからスレッド上で呼び出されます。
-### その他のユーティリティ関数
+### その他のユーティリティ関数 { #other-utility-functions }
-あなたが直接呼び出すユーティリティ関数は通常の `def` または `async def` で作成でき、FastAPIは呼び出す方法に影響を与えません。
+あなたが直接呼び出すユーティリティ関数は、通常の `def` でも `async def` でも構いません。FastAPI はその呼び出し方に影響を与えません。
-これは、FastAPIが呼び出す関数と対照的です: *path operation 関数*と依存関係。
+これは、FastAPI があなたの代わりに呼び出す関数 (すなわち *path operation 関数* と依存関係) とは対照的です。
-ユーティリティ関数が `def` を使用した通常の関数である場合、スレッドプールではなく直接 (コードで記述したとおりに) 呼び出されます。関数が `async def` を使用して作成されている場合は、呼び出す際に `await` する必要があります。
+ユーティリティ関数が `def` の通常関数であれば、(あなたのコードに書いたとおりに) 直接呼び出され、スレッドプールでは実行されません。関数が `async def` で作られている場合は、その関数を呼ぶときに `await` すべきです。
---
-繰り返しになりますが、これらは非常に技術的な詳細であり、検索して辿り着いた場合は役立つでしょう。
+繰り返しになりますが、これらは非常に技術的な詳細で、該当事項を検索してここにたどり着いた場合には役立つでしょう。
-それ以外の場合は、上記のセクションのガイドラインで問題ないはずです: 急いでいますか?。
+それ以外の場合は、上のセクションのガイドラインに従えば十分です: 急いでいますか?。
diff --git a/docs/ja/docs/benchmarks.md b/docs/ja/docs/benchmarks.md
index 966d199c5ed90..b6ed4d6d29780 100644
--- a/docs/ja/docs/benchmarks.md
+++ b/docs/ja/docs/benchmarks.md
@@ -1,34 +1,34 @@
-# ベンチマーク
+# ベンチマーク { #benchmarks }
-TechEmpowerの独立したベンチマークでは、Uvicornの下で動作する**FastAPI**アプリケーションは、利用可能な最速のPythonフレームワークの1つであり、下回っているのはStarletteとUvicorn自体 (FastAPIによって内部で使用される) のみだと示されています。
+TechEmpowerの独立したベンチマークでは、Uvicornの下で動作する**FastAPI**アプリケーションは、[利用可能な最速のPythonフレームワークの1つ](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7)であり、下回っているのはStarletteとUvicorn自体(FastAPIによって内部で使用される)のみだと示されています。
ただし、ベンチマークを確認し、比較する際には下記の内容に気を付けてください。
-## ベンチマークと速度
+## ベンチマークと速度 { #benchmarks-and-speed }
-ベンチマークを確認する時、異なるツールを同等なものと比較するのが一般的です。
+ベンチマークを確認する時、異なるタイプの複数のツールが同等のものとして比較されているのを目にするのが一般的です。
-具体的には、Uvicorn、Starlette、FastAPIを (他の多くのツールと) 比較しました。
+具体的には、Uvicorn、Starlette、FastAPIを(他の多くのツールの中で)まとめて比較しているのを目にすることがあります。
ツールで解決する問題がシンプルなほど、パフォーマンスが向上します。また、ほとんどのベンチマークは、ツールから提供される追加機能をテストしていません。
階層関係はこのようになります。
* **Uvicorn**: ASGIサーバー
- * **Starlette**: (Uvicornを使用) WEBマイクロフレームワーク
- * **FastAPI**: (Starletteを使用) データバリデーションなどの、APIを構築する追加機能を備えたAPIマイクロフレームワーク
+ * **Starlette**: (Uvicornを使用)webマイクロフレームワーク
+ * **FastAPI**: (Starletteを使用)データバリデーションなど、APIを構築するためのいくつかの追加機能を備えたAPIマイクロフレームワーク
* **Uvicorn**:
- * サーバー自体に余分なコードが少ないので、最高のパフォーマンスが得られます。
- * Uvicornにアプリケーションを直接書くことはできません。つまり、あなたのコードには、Starlette (または** FastAPI **) が提供するコードを、多かれ少なかれ含める必要があります。そうすると、最終的なアプリケーションは、フレームワークを使用してアプリのコードとバグを最小限に抑えた場合と同じオーバーヘッドになります。
- * もしUvicornを比較する場合は、Daphne、Hypercorn、uWSGIなどのアプリケーションサーバーと比較してください。
+ * サーバー自体以外に余分なコードがあまりないため、最高のパフォーマンスになります。
+ * Uvicornにアプリケーションを直接書くことはないでしょう。それは、あなたのコードに、Starlette(または**FastAPI**)が提供するコードを、少なくとも多かれ少なかれ含める必要があるということです。そして、もしそうした場合、最終的なアプリケーションは、フレームワークを使用してアプリのコードとバグを最小限に抑えた場合と同じオーバーヘッドになります。
+ * Uvicornを比較する場合は、Daphne、Hypercorn、uWSGIなどのアプリケーションサーバーと比較してください。
* **Starlette**:
- * Uvicornに次ぐ性能を持つでしょう。実際、StarletteはUvicornを使用しています。だから、より多くのコードを実行する必要があり、Uvicornよりも「遅く」なってしまうだけなのです。
- * しかし、パスベースのルーティングなどのシンプルなWEBアプリケーションを構築する機能を提供します。
- * もしStarletteを比較する場合は、Sanic、Flask、DjangoなどのWEBフレームワーク (もしくはマイクロフレームワーク) と比較してください。
+ * Uvicornに次ぐ性能になるでしょう。実際、Starletteは実行にUvicornを使用しています。そのため、おそらく、より多くのコードを実行しなければならない分だけ、Uvicornより「遅く」なるだけです。
+ * しかし、パスに基づくルーティングなどを使って、シンプルなwebアプリケーションを構築するためのツールを提供します。
+ * Starletteを比較する場合は、Sanic、Flask、Djangoなどのwebフレームワーク(またはマイクロフレームワーク)と比較してください。
* **FastAPI**:
- * StarletteがUvicornを使っているのと同じで、**FastAPI**はStarletteを使っており、それより速くできません。
- * FastAPIはStarletteの上にさらに多くの機能を提供します。データの検証やシリアライゼーションなど、APIを構築する際に常に必要な機能です。また、それを使用することで、自動ドキュメント化を無料で取得できます (ドキュメントは実行中のアプリケーションにオーバーヘッドを追加せず、起動時に生成されます) 。
- * FastAPIを使用せず、直接Starlette (またはSanic, Flask, Responderなど) を使用した場合、データの検証とシリアライズをすべて自分で実装する必要があります。そのため、最終的なアプリケーションはFastAPIを使用して構築した場合と同じオーバーヘッドが発生します。そして、多くの場合、このデータ検証とシリアライズは、アプリケーションのコードの中で最大の記述量になります。
- * FastAPIを使用することで、開発時間、バグ、コード行数を節約でき、使用しない場合 (あなたが全ての機能を実装し直した場合) と同じかそれ以上のパフォーマンスを得られます。
- * もしFastAPIを比較する場合は、Flask-apispec、NestJS、Moltenなどのデータ検証や、シリアライズの機能を提供するWEBフレームワーク (や機能のセット) と比較してください。これらはデータの自動検証や、シリアライズ、ドキュメント化が統合されたフレームワークです。
+ * StarletteがUvicornを使用しており、それより速くできないのと同じように、**FastAPI**はStarletteを使用しているため、それより速くできません。
+ * FastAPIはStarletteの上に、より多くの機能を提供します。データバリデーションやシリアライゼーションのように、APIを構築する際にほとんど常に必要な機能です。また、それを使用することで、自動ドキュメント化を無料で利用できます(自動ドキュメントは実行中のアプリケーションにオーバーヘッドを追加せず、起動時に生成されます)。
+ * FastAPIを使用せず、Starletteを直接(またはSanic、Flask、Responderなど別のツールを)使用した場合、データバリデーションとシリアライゼーションをすべて自分で実装する必要があります。そのため、最終的なアプリケーションはFastAPIを使用して構築した場合と同じオーバーヘッドが発生します。そして多くの場合、このデータバリデーションとシリアライゼーションは、アプリケーションで書かれるコードの大部分になります。
+ * そのため、FastAPIを使用することで、開発時間、バグ、コード行数を節約でき、使用しない場合(あなたがそれをすべて自分のコードで実装する必要があるため)と比べて、同じパフォーマンス(またはそれ以上)を得られる可能性があります。
+ * FastAPIを比較する場合は、Flask-apispec、NestJS、Moltenなど、データバリデーション、シリアライゼーション、ドキュメント化を提供するwebアプリケーションフレームワーク(またはツール群)と比較してください。自動データバリデーション、シリアライゼーション、ドキュメント化が統合されたフレームワークです。
diff --git a/docs/ja/docs/contributing.md b/docs/ja/docs/contributing.md
deleted file mode 100644
index 31db51c52b0ae..0000000000000
--- a/docs/ja/docs/contributing.md
+++ /dev/null
@@ -1,470 +0,0 @@
-# 開発 - 貢献
-
-まず、[FastAPIを応援 - ヘルプの入手](help-fastapi.md){.internal-link target=_blank}の基本的な方法を見て、ヘルプを得た方がいいかもしれません。
-
-## 開発
-
-すでにリポジトリをクローンし、コードを詳しく調べる必要があるとわかっている場合に、環境構築のためのガイドラインをいくつか紹介します。
-
-### `venv`を使用した仮想環境
-
-Pythonの`venv`モジュールを使用して、ディレクトリに仮想環境を作成します:
-
--**FastAPI**は、代替ツールのこれまでの働きがなければ存在しなかったでしょう。 +**FastAPI**は、他の人々のこれまでの働きがなければ存在しなかったでしょう。 以前に作られた多くのツールが、作成における刺激として役立ってきました。 @@ -29,7 +28,7 @@-## 調査 +## 調査 { #investigation } すべて既存の代替手段を使うことで、そのすべてを学び、アイデアを得て、自分や一緒に仕事をしてきた開発者のチームにとって最良の方法で組み合わせる機会を得ました。 @@ -39,13 +38,13 @@ そこで、**FastAPI**のコードを書き始める前に、OpenAPI、JSON Schema、OAuth2などの仕様を数ヶ月かけて勉強し、それらの関係、重複する箇所、相違点を理解しました。 -## 設計 +## 設計 { #design } その後、 (FastAPIを使う開発者として) ユーザーが欲しい「API」の設計に時間を費やしました。 もっとも人気のあるPythonエディターでいくつかのアイデアをテストしました。PyCharm、VS Code、Jediベースのエディターです。 -最新の Python開発者調査で、それらのエディターがユーザーの80%をカバーしていました。 +最新の [Python開発者調査](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools)で、それらのエディターがユーザーの80%をカバーしていました。 これは、**FastAPI**がPython開発者の80%が使用しているエディターで特別にテストされたことを意味します。また、ほとんどの他のエディターも同様に動作する傾向があるため、この恩恵は事実上すべてのエディターでうけられるはずです。 @@ -53,19 +52,19 @@ すべての箇所で、すべての開発者に最高の開発体験を提供しました。 -## 要件 +## 要件 { #requirements } -いくつかの代替手法を試したあと、私は**Pydantic**の強みを利用することを決めました。 +いくつかの代替手法を試したあと、私は[**Pydantic**](https://docs.pydantic.dev/)の強みを利用することを決めました。 そして、JSON Schemaに完全に準拠するようにしたり、制約宣言を定義するさまざまな方法をサポートしたり、いくつかのエディターでのテストに基づいてエディターのサポート (型チェック、自動補完) を改善するために貢献しました。 -開発中、もう1つの重要な鍵となる**Starlette**、にも貢献しました。 +開発中、もう1つの重要な鍵となる[**Starlette**](https://www.starlette.dev/)にも貢献しました。 -## 開発 +## 開発 { #development } 私が**FastAPI**自体の作成を開始した時には、ほとんどの部分がすでに準備されており、設計が定義され、必要な条件とツールの準備ができていました。そして規格や仕様に関する知識が、明確になり、更新されていました。 -## これから +## これから { #future } この時点ですでに、これらのアイデアを持った**FastAPI**が多くの人の役に立っていることは明らかです。 @@ -77,4 +76,4 @@ **FastAPI**には大きな未来が待っています。 -そして、[あなたの助け](help-fastapi.md){.internal-link target=_blank}を大いに歓迎します。 +そして、[あなたの助け](help-fastapi.md)を大いに歓迎します。 diff --git a/docs/ja/docs/how-to/authentication-error-status-code.md b/docs/ja/docs/how-to/authentication-error-status-code.md new file mode 100644 index 0000000000000..ec5e25b75bdfe --- /dev/null +++ b/docs/ja/docs/how-to/authentication-error-status-code.md @@ -0,0 +1,17 @@ +# 古い 403 認証エラーのステータスコードを使う { #use-old-403-authentication-error-status-codes } + +FastAPI バージョン `0.122.0` より前は、統合されたセキュリティユーティリティが認証に失敗してクライアントへエラーを返す際、HTTP ステータスコード `403 Forbidden` を使用していました。 + +FastAPI バージョン `0.122.0` 以降では、より適切な HTTP ステータスコード `401 Unauthorized` を使用し、HTTP 仕様に従ってレスポンスに妥当な `WWW-Authenticate` ヘッダーを含めます。[RFC 7235](https://datatracker.ietf.org/doc/html/rfc7235#section-3.1), [RFC 9110](https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized)。 + +しかし、何らかの理由でクライアントが従来の挙動に依存している場合は、セキュリティクラスでメソッド `make_not_authenticated_error` をオーバーライドすることで、その挙動に戻せます。 + +たとえば、既定の `401 Unauthorized` エラーの代わりに `403 Forbidden` エラーを返す `HTTPBearer` のサブクラスを作成できます: + +{* ../../docs_src/authentication_error_status_code/tutorial001_an_py310.py hl[9:13] *} + +/// tip | 豆知識 + +この関数は例外インスタンスを返す点に注意してください。ここでは例外を送出しません。送出は内部の他のコードで行われます。 + +/// diff --git a/docs/ja/docs/how-to/conditional-openapi.md b/docs/ja/docs/how-to/conditional-openapi.md index b892ed6c6489f..b6281ed06fdb7 100644 --- a/docs/ja/docs/how-to/conditional-openapi.md +++ b/docs/ja/docs/how-to/conditional-openapi.md @@ -1,8 +1,8 @@ -# 条件付き OpenAPI +# 条件付き OpenAPI { #conditional-openapi } 必要であれば、設定と環境変数を利用して、環境に応じて条件付きでOpenAPIを構成することが可能です。また、完全にOpenAPIを無効にすることもできます。 -## セキュリティとAPI、およびドキュメントについて +## セキュリティとAPI、およびドキュメントについて { #about-security-apis-and-docs } 本番環境においてドキュメントのUIを非表示にすることによって、APIを保護しようと *すべきではありません*。 @@ -10,28 +10,26 @@ もしセキュリティ上の欠陥がソースコードにあるならば、それは存在したままです。 -ドキュメンテーションを非表示にするのは、単にあなたのAPIへのアクセス方法を難解にするだけでなく、同時にあなた自身の本番環境でのAPIのデバッグを困難にしてしまう可能性があります。単純に、 Security through obscurity の一つの形態として考えられるでしょう。 +ドキュメンテーションを非表示にするのは、単にあなたのAPIへのアクセス方法を難解にするだけでなく、同時にあなた自身の本番環境でのAPIのデバッグを困難にしてしまう可能性があります。単純に、[秘匿によるセキュリティ](https://en.wikipedia.org/wiki/Security_through_obscurity) の一つの形態として考えられるでしょう。 もしあなたのAPIのセキュリティを強化したいなら、いくつかのよりよい方法があります。例を示すと、 * リクエストボディとレスポンスのためのPydanticモデルの定義を見直す。 * 依存関係に基づきすべての必要なパーミッションとロールを設定する。 * パスワードを絶対に平文で保存しない。パスワードハッシュのみを保存する。 -* PasslibやJWTトークンに代表される、よく知られた暗号化ツールを使って実装する。 +* pwdlibやJWTトークンに代表される、よく知られた暗号化ツールを使って実装する。 * そして必要なところでは、もっと細かいパーミッション制御をOAuth2スコープを使って行う。 -* など +* ...など それでも、例えば本番環境のような特定の環境のみで、あるいは環境変数の設定によってAPIドキュメントをどうしても無効にしたいという、非常に特殊なユースケースがあるかもしれません。 -## 設定と環境変数による条件付き OpenAPI +## 設定と環境変数による条件付き OpenAPI { #conditional-openapi-from-settings-and-env-vars } 生成するOpenAPIとドキュメントUIの構成は、共通のPydanticの設定を使用して簡単に切り替えられます。 例えば、 -```Python hl_lines="6 11" -{!../../../docs_src/conditional_openapi/tutorial001.py!} -``` +{* ../../docs_src/conditional_openapi/tutorial001_py310.py hl[6,11] *} ここでは `openapi_url` の設定を、デフォルトの `"/openapi.json"` のまま宣言しています。 diff --git a/docs/ja/docs/how-to/configure-swagger-ui.md b/docs/ja/docs/how-to/configure-swagger-ui.md new file mode 100644 index 0000000000000..2950918575c79 --- /dev/null +++ b/docs/ja/docs/how-to/configure-swagger-ui.md @@ -0,0 +1,70 @@ +# Swagger UI の設定 { #configure-swagger-ui } + +いくつかの追加の [Swagger UI パラメータ](https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/)を設定できます。 + +設定するには、`FastAPI()` のアプリオブジェクトを作成するとき、または `get_swagger_ui_html()` 関数に `swagger_ui_parameters` 引数を渡します。 + +`swagger_ui_parameters` は、Swagger UI に直接渡される設定を含む辞書を受け取ります。 + +FastAPI はそれらの設定を **JSON** に変換し、JavaScript と互換にします。Swagger UI が必要とするのはこの形式です。 + +## シンタックスハイライトを無効化 { #disable-syntax-highlighting } + +例えば、Swagger UI のシンタックスハイライトを無効化できます。 + +設定を変更しなければ、シンタックスハイライトはデフォルトで有効です: + +
+
+しかし、`syntaxHighlight` を `False` に設定すると無効化できます:
+
+{* ../../docs_src/configure_swagger_ui/tutorial001_py310.py hl[3] *}
+
+...その場合、Swagger UI ではシンタックスハイライトが表示されなくなります:
+
+
+
+## テーマの変更 { #change-the-theme }
+
+同様に、キー `"syntaxHighlight.theme"`(途中にドットが含まれている点に注意)でシンタックスハイライトのテーマを設定できます:
+
+{* ../../docs_src/configure_swagger_ui/tutorial002_py310.py hl[3] *}
+
+この設定により、シンタックスハイライトの配色テーマが変わります:
+
+
+
+## 既定の Swagger UI パラメータの変更 { #change-default-swagger-ui-parameters }
+
+FastAPI には、多くのユースケースに適した既定の設定パラメータが含まれています。
+
+既定では次の設定が含まれます:
+
+{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}
+
+引数 `swagger_ui_parameters` に別の値を指定することで、これらを上書きできます。
+
+例えば、`deepLinking` を無効化するには、次の設定を `swagger_ui_parameters` に渡します:
+
+{* ../../docs_src/configure_swagger_ui/tutorial003_py310.py hl[3] *}
+
+## その他の Swagger UI パラメータ { #other-swagger-ui-parameters }
+
+利用可能な他のすべての設定については、公式の [Swagger UI パラメータのドキュメント](https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/)を参照してください。
+
+## JavaScript 専用の設定 { #javascript-only-settings }
+
+Swagger UI では、他にも **JavaScript 専用** のオブジェクト(例: JavaScript の関数)による設定が可能です。
+
+FastAPI には、次の JavaScript 専用の `presets` 設定も含まれています:
+
+```JavaScript
+presets: [
+ SwaggerUIBundle.presets.apis,
+ SwaggerUIBundle.SwaggerUIStandalonePreset
+]
+```
+
+これらは文字列ではなく **JavaScript** のオブジェクトであるため、Python のコードから直接渡すことはできません。
+
+そのような JavaScript 専用の設定を使う必要がある場合は、上記のいずれかの方法を使用し、Swagger UI の path operation をオーバーライドして、必要な JavaScript を手動で記述してください。
diff --git a/docs/ja/docs/how-to/custom-docs-ui-assets.md b/docs/ja/docs/how-to/custom-docs-ui-assets.md
new file mode 100644
index 0000000000000..eb1b96c5afa53
--- /dev/null
+++ b/docs/ja/docs/how-to/custom-docs-ui-assets.md
@@ -0,0 +1,185 @@
+# カスタムドキュメント UI の静的アセット(セルフホスティング) { #custom-docs-ui-static-assets-self-hosting }
+
+API ドキュメントは **Swagger UI** と **ReDoc** を使用しており、それぞれにいくつかの JavaScript と CSS ファイルが必要です。
+
+既定では、これらのファイルは CDN から配信されます。
+
+しかし、カスタマイズすることも可能で、特定の CDN を指定したり、自分でファイルを配信したりできます。
+
+## JavaScript と CSS のカスタム CDN { #custom-cdn-for-javascript-and-css }
+
+別の CDN を使いたいとします。例えば `https://unpkg.com/` を使いたい場合です。
+
+例えば、一部の URL が制限されている国に住んでいる場合に役立ちます。
+
+### 自動ドキュメントの無効化 { #disable-the-automatic-docs }
+
+最初の手順は自動ドキュメントを無効化することです。デフォルトではそれらは既定の CDN を使用します。
+
+無効化するには、`FastAPI` アプリ作成時にそれらの URL を `None` に設定します:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[8] *}
+
+### カスタムドキュメントの追加 { #include-the-custom-docs }
+
+これで、カスタムドキュメント用の *path operations* を作成できます。
+
+FastAPI の内部関数を再利用してドキュメント用の HTML ページを生成し、必要な引数を渡せます:
+
+- `openapi_url`: ドキュメントの HTML ページが API の OpenAPI スキーマを取得する URL。ここでは属性 `app.openapi_url` を使用できます。
+- `title`: API のタイトル。
+- `oauth2_redirect_url`: 既定値を使うにはここで `app.swagger_ui_oauth2_redirect_url` を使用できます。
+- `swagger_js_url`: Swagger UI ドキュメント用の HTML が取得する JavaScript ファイルの URL。これはカスタム CDN の URL です。
+- `swagger_css_url`: Swagger UI ドキュメント用の HTML が取得する CSS ファイルの URL。これはカスタム CDN の URL です。
+
+ReDoc についても同様です...
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[2:6,11:19,22:24,27:33] *}
+
+/// tip | 豆知識
+
+`swagger_ui_redirect` 用の *path operation* は、OAuth2 を使用する場合の補助です。
+
+API を OAuth2 プロバイダと統合すると、認証を実行して取得したクレデンシャルを持った状態で API ドキュメントに戻れます。そして実際の OAuth2 認証を用いてドキュメント上から API と対話できます。
+
+Swagger UI がこの処理を裏側で行いますが、そのためにこの「redirect」の補助が必要です。
+
+///
+
+### テスト用の *path operation* を作成 { #create-a-path-operation-to-test-it }
+
+すべてが動作するかをテストできるように、*path operation* を作成します:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[36:38] *}
+
+### テスト { #test-it }
+
+これで、[http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) にアクセスしてページを再読み込みすると、新しい CDN からそれらのアセットが読み込まれるはずです。
+
+## ドキュメント用 JavaScript と CSS のセルフホスティング { #self-hosting-javascript-and-css-for-docs }
+
+オフライン(インターネット非接続)でも、あるいはローカルネットワークで、アプリを動作させたい場合などには、JavaScript と CSS をセルフホストするのが有用です。
+
+ここでは、同じ FastAPI アプリ内でそれらのファイルを配信し、ドキュメントでそれらを使用するように設定する方法を示します。
+
+### プロジェクトのファイル構成 { #project-file-structure }
+
+プロジェクトのファイル構成が次のようになっているとします:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+```
+
+これらの静的ファイルを保存するためのディレクトリを作成します。
+
+新しいファイル構成は次のようになります:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static/
+```
+
+### ファイルのダウンロード { #download-the-files }
+
+ドキュメントに必要な静的ファイルをダウンロードし、`static/` ディレクトリに配置します。
+
+各リンクを右クリックして「リンク先を別名で保存...」のようなオプションを選べます。
+
+**Swagger UI** では次のファイルを使用します:
+
+- [`swagger-ui-bundle.js`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js)
+- [`swagger-ui.css`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css)
+
+そして **ReDoc** では次のファイルを使用します:
+
+- [`redoc.standalone.js`](https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js)
+
+その後、ファイル構成は次のようになります:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static
+ ├── redoc.standalone.js
+ ├── swagger-ui-bundle.js
+ └── swagger-ui.css
+```
+
+### 静的ファイルの配信 { #serve-the-static-files }
+
+- `StaticFiles` をインポートします。
+- 特定のパスに `StaticFiles()` インスタンスを「マウント」します。
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[7,11] *}
+
+### 静的ファイルのテスト { #test-the-static-files }
+
+アプリケーションを起動し、[http://127.0.0.1:8000/static/redoc.standalone.js](http://127.0.0.1:8000/static/redoc.standalone.js) にアクセスします。
+
+**ReDoc** 用の非常に長い JavaScript ファイルが表示されるはずです。
+
+先頭は次のようになっているかもしれません:
+
+```JavaScript
+/*! For license information please see redoc.standalone.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")):
+...
+```
+
+これで、アプリから静的ファイルを配信できていること、そしてドキュメント用の静的ファイルを正しい場所に配置できていることが確認できます。
+
+次に、ドキュメントでそれらの静的ファイルを使用するようにアプリを設定します。
+
+### 静的ファイル用に自動ドキュメントを無効化 { #disable-the-automatic-docs-for-static-files }
+
+カスタム CDN を使う場合と同様、最初の手順は自動ドキュメントを無効化することです。既定では CDN を使用します。
+
+無効化するには、`FastAPI` アプリ作成時にそれらの URL を `None` に設定します:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[9] *}
+
+### 静的ファイル用のカスタムドキュメントを追加 { #include-the-custom-docs-for-static-files }
+
+カスタム CDN と同様の方法で、カスタムドキュメント用の *path operations* を作成できます。
+
+再び、FastAPI の内部関数を再利用してドキュメント用の HTML ページを生成し、必要な引数を渡します:
+
+- `openapi_url`: ドキュメントの HTML ページが API の OpenAPI スキーマを取得する URL。ここでは属性 `app.openapi_url` を使用できます。
+- `title`: API のタイトル。
+- `oauth2_redirect_url`: 既定値を使うにはここで `app.swagger_ui_oauth2_redirect_url` を使用できます。
+- `swagger_js_url`: Swagger UI ドキュメント用の HTML が取得する **JavaScript** ファイルの URL。**これはあなたのアプリ自身がいま配信しているものです**。
+- `swagger_css_url`: Swagger UI ドキュメント用の HTML が取得する **CSS** ファイルの URL。**これはあなたのアプリ自身がいま配信しているものです**。
+
+ReDoc についても同様です...
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[2:6,14:22,25:27,30:36] *}
+
+/// tip | 豆知識
+
+`swagger_ui_redirect` 用の *path operation* は、OAuth2 を使用する場合の補助です。
+
+API を OAuth2 プロバイダと統合すると、認証を実行して取得したクレデンシャルを持った状態で API ドキュメントに戻れます。そして実際の OAuth2 認証を用いてドキュメント上から API と対話できます。
+
+Swagger UI がこの処理を裏側で行いますが、そのためにこの「redirect」の補助が必要です。
+
+///
+
+### 静的ファイルをテストするための *path operation* を作成 { #create-a-path-operation-to-test-static-files }
+
+すべてが動作するかをテストできるように、*path operation* を作成します:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[39:41] *}
+
+### 静的ファイル UI のテスト { #test-static-files-ui }
+
+これで、WiFi を切断して [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) にアクセスし、ページを再読み込みできるはずです。
+
+インターネットに接続していなくても、API のドキュメントを表示し、API と対話できます。
diff --git a/docs/ja/docs/how-to/custom-request-and-route.md b/docs/ja/docs/how-to/custom-request-and-route.md
new file mode 100644
index 0000000000000..d2b0806e44433
--- /dev/null
+++ b/docs/ja/docs/how-to/custom-request-and-route.md
@@ -0,0 +1,109 @@
+# カスタム Request と APIRoute クラス { #custom-request-and-apiroute-class }
+
+場合によっては、`Request` や `APIRoute` クラスで使われるロジックを上書きしたいことがあります。
+
+特に、ミドルウェアでのロジックの代替として有効な場合があります。
+
+たとえば、アプリケーションで処理される前にリクエストボディを読み取ったり操作したりしたい場合です。
+
+/// danger | 警告
+
+これは「上級」機能です。
+
+FastAPI を始めたばかりの場合は、このセクションは読み飛ばしてもよいでしょう。
+
+///
+
+## ユースケース { #use-cases }
+
+ユースケースの例:
+
+* JSON ではないリクエストボディを JSON に変換する(例: [`msgpack`](https://msgpack.org/index.html))。
+* gzip 圧縮されたリクエストボディの解凍。
+* すべてのリクエストボディの自動ロギング。
+
+## カスタムリクエストボディのエンコーディングの処理 { #handling-custom-request-body-encodings }
+
+gzip のリクエストを解凍するために、カスタムの `Request` サブクラスを使う方法を見ていきます。
+
+そして、そのカスタムリクエストクラスを使うための `APIRoute` サブクラスを用意します。
+
+### カスタム `GzipRequest` クラスの作成 { #create-a-custom-gziprequest-class }
+
+/// tip | 豆知識
+
+これは仕組みを示すためのサンプルです。Gzip 対応が必要な場合は、用意されている [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware) を使用できます。
+
+///
+
+まず、`GzipRequest` クラスを作成します。これは適切なヘッダーがある場合に本体を解凍するよう、`Request.body()` メソッドを上書きします。
+
+ヘッダーに `gzip` がなければ、解凍は試みません。
+
+この方法により、同じルートクラスで gzip 圧縮済み/未圧縮のリクエストの両方を扱えます。
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[9:16] *}
+
+### カスタム `GzipRoute` クラスの作成 { #create-a-custom-gziproute-class }
+
+次に、`GzipRequest` を利用する `fastapi.routing.APIRoute` のカスタムサブクラスを作成します。
+
+ここでは `APIRoute.get_route_handler()` メソッドを上書きします。
+
+このメソッドは関数を返します。そしてその関数がリクエストを受け取り、レスポンスを返します。
+
+ここでは、元のリクエストから `GzipRequest` を作成するために利用します。
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[19:27] *}
+
+/// note | 技術詳細
+
+`Request` には `request.scope` 属性があり、これはリクエストに関するメタデータを含む Python の `dict` です。
+
+`Request` には `request.receive` もあり、これはリクエストの本体を「受信」するための関数です。
+
+`scope` の `dict` と `receive` 関数はいずれも ASGI 仕様の一部です。
+
+そしてこの 2 つ(`scope` と `receive`)が、新しい `Request` インスタンスを作成するために必要なものです。
+
+`Request` について詳しくは、[Starlette の Requests に関するドキュメント](https://www.starlette.dev/requests/) を参照してください。
+
+///
+
+`GzipRequest.get_route_handler` が返す関数が異なるのは、`Request` を `GzipRequest` に変換する点だけです。
+
+これにより、`GzipRequest` は必要に応じてデータを解凍してから *path operations* に渡します。
+
+それ以降の処理ロジックはすべて同じです。
+
+ただし、`GzipRequest.body` を変更しているため、必要に応じて **FastAPI** によって読み込まれる際にリクエストボディが自動的に解凍されます。
+
+## 例外ハンドラでのリクエストボディへのアクセス { #accessing-the-request-body-in-an-exception-handler }
+
+/// tip | 豆知識
+
+同じ問題を解決するには、`RequestValidationError` 用のカスタムハンドラで `body` を使う方がずっと簡単でしょう([エラー処理](../tutorial/handling-errors.md#use-the-requestvalidationerror-body))。
+
+ただし、この例も有効で、内部コンポーネントとどのようにやり取りするかを示しています。
+
+///
+
+同じアプローチを使って、例外ハンドラ内でリクエストボディにアクセスすることもできます。
+
+やることは、`try`/`except` ブロックの中でリクエストを処理するだけです:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[14,16] *}
+
+例外が発生しても、`Request` インスタンスはスコープ内に残るため、エラー処理時にリクエストボディを読み取り、活用できます:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[17:19] *}
+
+## ルーターでのカスタム `APIRoute` クラス { #custom-apiroute-class-in-a-router }
+
+`APIRouter` の `route_class` パラメータを設定することもできます:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[26] *}
+
+この例では、`router` 配下の *path operations* はカスタムの `TimedRoute` クラスを使用し、レスポンスの生成にかかった時間を示す追加の `X-Response-Time` ヘッダーがレスポンスに含まれます:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[13:20] *}
diff --git a/docs/ja/docs/how-to/extending-openapi.md b/docs/ja/docs/how-to/extending-openapi.md
new file mode 100644
index 0000000000000..e9ef9923fd438
--- /dev/null
+++ b/docs/ja/docs/how-to/extending-openapi.md
@@ -0,0 +1,80 @@
+# OpenAPI の拡張 { #extending-openapi }
+
+生成された OpenAPI スキーマを変更する必要がある場合があります。
+
+このセクションではその方法を説明します。
+
+## 通常のプロセス { #the-normal-process }
+
+通常(デフォルト)のプロセスは次のとおりです。
+
+`FastAPI` アプリケーション(インスタンス)には、OpenAPI スキーマを返すことが期待される `.openapi()` メソッドがあります。
+
+アプリケーションオブジェクトの作成時に、`/openapi.json`(または `openapi_url` に設定したパス)への path operation が登録されます。
+
+これは単に、アプリケーションの `.openapi()` メソッドの結果を含む JSON レスポンスを返します。
+
+デフォルトでは、`.openapi()` メソッドはプロパティ `.openapi_schema` に内容があるかを確認し、あればそれを返します。
+
+なければ、`fastapi.openapi.utils.get_openapi` にあるユーティリティ関数を使って生成します。
+
+この関数 `get_openapi()` は次の引数を受け取ります:
+
+- `title`: ドキュメントに表示される OpenAPI のタイトル。
+- `version`: API のバージョン。例: `2.5.0`。
+- `openapi_version`: 使用する OpenAPI 仕様のバージョン。デフォルトは最新の `3.1.0`。
+- `summary`: API の短い概要。
+- `description`: API の説明。Markdown を含めることができ、ドキュメントに表示されます。
+- `routes`: ルートのリスト。登録済みの各 path operation です。`app.routes` から取得されます。
+
+/// info | 情報
+
+パラメータ `summary` は OpenAPI 3.1.0 以降で利用可能で、FastAPI 0.99.0 以降が対応しています。
+
+///
+
+## デフォルトの上書き { #overriding-the-defaults }
+
+上記の情報を使って、同じユーティリティ関数で OpenAPI スキーマを生成し、必要な部分を上書きできます。
+
+たとえば、[カスタムロゴを含めるための ReDoc の OpenAPI 拡張](https://github.com/Rebilly/ReDoc/blob/master/docs/redoc-vendor-extensions.md#x-logo)を追加してみましょう。
+
+### 通常の **FastAPI** { #normal-fastapi }
+
+まず、通常どおりに **FastAPI** アプリケーションを実装します:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[1,4,7:9] *}
+
+### OpenAPI スキーマの生成 { #generate-the-openapi-schema }
+
+次に、`custom_openapi()` 関数内で同じユーティリティ関数を使って OpenAPI スキーマを生成します:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[2,15:21] *}
+
+### OpenAPI スキーマの変更 { #modify-the-openapi-schema }
+
+OpenAPI スキーマの `info`「オブジェクト」にカスタムの `x-logo` を追加して、ReDoc 拡張を加えます:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[22:24] *}
+
+### OpenAPI スキーマのキャッシュ { #cache-the-openapi-schema }
+
+生成したスキーマを保持する「キャッシュ」として `.openapi_schema` プロパティを利用できます。
+
+こうすることで、ユーザーが API ドキュメントを開くたびにスキーマを生成する必要がなくなります。
+
+最初の1回だけ生成され、その後は同じキャッシュ済みスキーマが以降のリクエストで使われます。
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[13:14,25:26] *}
+
+### メソッドの上書き { #override-the-method }
+
+これで、`.openapi()` メソッドを新しい関数に置き換えられます。
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[29] *}
+
+### 確認 { #check-it }
+
+[http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) にアクセスすると、カスタムロゴ(この例では **FastAPI** のロゴ)が使われていることが確認できます:
+
+
diff --git a/docs/ja/docs/how-to/general.md b/docs/ja/docs/how-to/general.md
new file mode 100644
index 0000000000000..ca2de8f3fbf2d
--- /dev/null
+++ b/docs/ja/docs/how-to/general.md
@@ -0,0 +1,43 @@
+# 一般 - ハウツー - レシピ { #general-how-to-recipes }
+
+ここでは、一般的またはよくある質問に対して、ドキュメント内の他の箇所への参照をいくつか示します。
+
+## データのフィルタリング - セキュリティ { #filter-data-security }
+
+返すべき以上のデータを返さないようにするには、[チュートリアル - レスポンスモデル - 戻り値の型](../tutorial/response-model.md) を参照してください。
+
+## レスポンス性能の最適化 - レスポンスモデル - 戻り値の型 { #optimize-response-performance-response-model-return-type }
+
+JSON データを返す際の性能を最適化するには、戻り値の型またはレスポンスモデルを使用してください。そうすることで、Pydantic が Python を経由せずに Rust 側で JSON へのシリアライズを処理します。詳細は [チュートリアル - レスポンスモデル - 戻り値の型](../tutorial/response-model.md) を参照してください。
+
+## ドキュメントのタグ - OpenAPI { #documentation-tags-openapi }
+
+*path operations* にタグを追加し、ドキュメント UI でグループ化するには、[チュートリアル - path operation の設定 - タグ](../tutorial/path-operation-configuration.md#tags) を参照してください。
+
+## ドキュメントの概要と説明 - OpenAPI { #documentation-summary-and-description-openapi }
+
+*path operations* に概要と説明を追加し、ドキュメント UI に表示するには、[チュートリアル - path operation の設定 - 概要と説明](../tutorial/path-operation-configuration.md#summary-and-description) を参照してください。
+
+## ドキュメントのレスポンス説明 - OpenAPI { #documentation-response-description-openapi }
+
+ドキュメント UI に表示されるレスポンスの説明を定義するには、[チュートリアル - path operation の設定 - レスポンスの説明](../tutorial/path-operation-configuration.md#response-description) を参照してください。
+
+## *Path Operation* の非推奨化 - OpenAPI { #documentation-deprecate-a-path-operation-openapi }
+
+*path operation* を非推奨にし、ドキュメント UI に表示するには、[チュートリアル - path operation の設定 - 非推奨](../tutorial/path-operation-configuration.md#deprecate-a-path-operation) を参照してください。
+
+## 任意のデータを JSON 互換に変換 { #convert-any-data-to-json-compatible }
+
+任意のデータを JSON 互換に変換するには、[チュートリアル - JSON 互換エンコーダ](../tutorial/encoder.md) を参照してください。
+
+## OpenAPI メタデータ - ドキュメント { #openapi-metadata-docs }
+
+ライセンス、バージョン、連絡先などを含むメタデータを OpenAPI スキーマに追加するには、[チュートリアル - メタデータとドキュメントの URL](../tutorial/metadata.md) を参照してください。
+
+## OpenAPI のカスタム URL { #openapi-custom-url }
+
+OpenAPI の URL をカスタマイズ(または削除)するには、[チュートリアル - メタデータとドキュメントの URL](../tutorial/metadata.md#openapi-url) を参照してください。
+
+## OpenAPI ドキュメントの URL { #openapi-docs-urls }
+
+自動生成されるドキュメント UI が使用する URL を変更するには、[チュートリアル - メタデータとドキュメントの URL](../tutorial/metadata.md#docs-urls) を参照してください。
diff --git a/docs/ja/docs/how-to/graphql.md b/docs/ja/docs/how-to/graphql.md
new file mode 100644
index 0000000000000..d1356b59a9127
--- /dev/null
+++ b/docs/ja/docs/how-to/graphql.md
@@ -0,0 +1,60 @@
+# GraphQL { #graphql }
+
+**FastAPI** は **ASGI** 標準に基づいているため、ASGI に対応した任意の **GraphQL** ライブラリを簡単に統合できます。
+
+同じアプリケーション内で通常の FastAPI の *path operation* と GraphQL を組み合わせて使えます。
+
+/// tip | 豆知識
+
+**GraphQL** は非常に特定のユースケースを解決します。
+
+一般的な **Web API** と比べると、**長所** と **短所** があります。
+
+ご自身のユースケースで得られる **利点** が **欠点** を補うかどうかを評価してください。 🤓
+
+///
+
+## GraphQL ライブラリ { #graphql-libraries }
+
+**ASGI** をサポートする **GraphQL** ライブラリの一部を以下に示します。**FastAPI** と組み合わせて使用できます:
+
+* [Strawberry](https://strawberry.rocks/) 🍓
+ * [FastAPI 向けドキュメント](https://strawberry.rocks/docs/integrations/fastapi)あり
+* [Ariadne](https://ariadnegraphql.org/)
+ * [FastAPI 向けドキュメント](https://ariadnegraphql.org/docs/fastapi-integration)あり
+* [Tartiflette](https://tartiflette.io/)
+ * ASGI 連携用の [Tartiflette ASGI](https://tartiflette.github.io/tartiflette-asgi/) あり
+* [Graphene](https://graphene-python.org/)
+ * [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3) あり
+
+## Strawberry で GraphQL { #graphql-with-strawberry }
+
+**GraphQL** が必要、または利用したい場合は、[**Strawberry**](https://strawberry.rocks/) を**推奨**します。**FastAPI** の設計に最も近く、すべてが**型アノテーション**に基づいています。
+
+ユースケースによっては他のライブラリを選ぶ方がよい場合もありますが、私に尋ねられれば、おそらく **Strawberry** を試すことを勧めるでしょう。
+
+FastAPI と Strawberry を統合する方法の簡単なプレビューです:
+
+{* ../../docs_src/graphql_/tutorial001_py310.py hl[3,22,25] *}
+
+詳細は [Strawberry のドキュメント](https://strawberry.rocks/)をご覧ください。
+
+また、[Strawberry と FastAPI](https://strawberry.rocks/docs/integrations/fastapi) の連携に関するドキュメントもあります。
+
+## Starlette の旧 `GraphQLApp` { #older-graphqlapp-from-starlette }
+
+以前の Starlette には、[Graphene](https://graphene-python.org/) と統合するための `GraphQLApp` クラスが含まれていました。
+
+これは Starlette からは非推奨になりましたが、もしそれを使用しているコードがある場合は、同じユースケースをカバーし、**ほぼ同一のインターフェース**を持つ [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3) へ容易に**移行**できます。
+
+/// tip | 豆知識
+
+GraphQL が必要であれば、依然として [Strawberry](https://strawberry.rocks/) の利用を推奨します。独自のクラスや型ではなく、型アノテーションに基づいているためです。
+
+///
+
+## さらに学ぶ { #learn-more }
+
+**GraphQL** については、[公式 GraphQL ドキュメント](https://graphql.org/)でさらに学べます。
+
+上記の各ライブラリについては、リンク先のドキュメントをご参照ください。
diff --git a/docs/ja/docs/how-to/index.md b/docs/ja/docs/how-to/index.md
new file mode 100644
index 0000000000000..9d9348abfc860
--- /dev/null
+++ b/docs/ja/docs/how-to/index.md
@@ -0,0 +1,13 @@
+# ハウツー - レシピ { #how-to-recipes }
+
+ここでは、**複数のトピック**に関するさまざまなレシピや「ハウツー」ガイドを紹介します。
+
+これらのアイデアの多くはおおむね**独立**しており、ほとんどの場合、**あなたのプロジェクト**に直接当てはまるものだけを読めば十分です。
+
+プロジェクトにとって興味深く有用だと思うものがあれば、ぜひ確認してください。そうでなければ、読み飛ばしても問題ありません。
+
+/// tip | 豆知識
+
+**FastAPI を学ぶ**ことを体系的に進めたい場合(推奨)、代わりに [チュートリアル - ユーザーガイド](../tutorial/index.md) を章ごとに読んでください。
+
+///
diff --git a/docs/ja/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/ja/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
new file mode 100644
index 0000000000000..320be144436af
--- /dev/null
+++ b/docs/ja/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -0,0 +1,135 @@
+# Pydantic v1 から Pydantic v2 への移行 { #migrate-from-pydantic-v1-to-pydantic-v2 }
+
+古い FastAPI アプリがある場合、Pydantic v1 を使っているかもしれません。
+
+FastAPI 0.100.0 は Pydantic v1 / v2 のどちらにも対応しており、インストールされている方を使用しました。
+
+FastAPI 0.119.0 では、Pydantic v2 内からの Pydantic v1 の部分的サポート(`pydantic.v1`)が導入され、v2 への移行が容易になりました。
+
+FastAPI 0.126.0 で Pydantic v1 のサポートは終了しましたが、しばらくの間は `pydantic.v1` は利用可能でした。
+
+/// warning | 注意
+
+Pydantic チームは Python の最新バージョン、つまり **Python 3.14** から、Pydantic v1 のサポートを終了しました。
+
+これには `pydantic.v1` も含まれ、Python 3.14 以上ではサポートされません。
+
+Python の最新機能を使いたい場合は、Pydantic v2 を使用していることを確認する必要があります。
+
+///
+
+古い FastAPI アプリで Pydantic v1 を使っている場合、ここでは Pydantic v2 への移行方法と、段階的移行を助ける **FastAPI 0.119.0 の機能** を紹介します。
+
+## 公式ガイド { #official-guide }
+
+Pydantic には v1 から v2 への公式の [移行ガイド](https://docs.pydantic.dev/latest/migration/) があります。
+
+変更点、検証がより正確で厳密になった点、注意事項などが含まれます。
+
+何が変わったかをよりよく理解するために参照してください。
+
+## テスト { #tests }
+
+アプリに対する[テスト](../tutorial/testing.md)を用意し、継続的インテグレーション(CI)で実行するようにしてください。
+
+これにより、アップグレード後も期待どおり動作していることを確認できます。
+
+## `bump-pydantic` { #bump-pydantic }
+
+多くの場合、カスタマイズのない通常の Pydantic モデルを使っていれば、v1 から v2 への移行作業の大半を自動化できます。
+
+同じ Pydantic チームが提供する [`bump-pydantic`](https://github.com/pydantic/bump-pydantic) を使用できます。
+
+このツールは必要なコード変更のほとんどを自動で行います。
+
+その後テストを実行し、問題なければ完了です。😎
+
+## v2 における Pydantic v1 { #pydantic-v1-in-v2 }
+
+Pydantic v2 には、Pydantic v1 がサブモジュール `pydantic.v1` として同梱されています。ただし、これは Python 3.13 を超えるバージョンではサポートされません。
+
+つまり、Pydantic v2 の最新バージョンをインストールし、このサブモジュールから旧 Pydantic v1 のコンポーネントをインポートして、あたかも v1 をインストールしているかのように使用できます。
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}
+
+### v2 内の Pydantic v1 に対する FastAPI のサポート { #fastapi-support-for-pydantic-v1-in-v2 }
+
+FastAPI 0.119.0 以降では、移行を容易にするため、Pydantic v2 内の Pydantic v1 に対する部分的サポートもあります。
+
+そのため、Pydantic を v2 の最新に上げ、インポートを `pydantic.v1` サブモジュールに切り替えるだけで、多くの場合そのまま動作します。
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py hl[2,5,15] *}
+
+/// warning | 注意
+
+前述のとおり、Python の最近のバージョン(Python 3.14 以降)では Pydantic v1 がサポートされないため、`pydantic.v1` の使用も Python 3.14 以上ではサポートされません。
+
+///
+
+### 同一アプリでの Pydantic v1 と v2 { #pydantic-v1-and-v2-on-the-same-app }
+
+Pydantic v2 のモデルのフィールドに Pydantic v1 のモデルを(またはその逆を)埋め込むことは、Pydantic では「サポートされていません」。
+
+```mermaid
+graph TB
+ subgraph "❌ Not Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+...しかし、同じアプリ内で Pydantic v1 と v2 を別々のモデルとして分けて使うことは可能です。
+
+```mermaid
+graph TB
+ subgraph "✅ Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+場合によっては、同じ FastAPI の path operation 内で、Pydantic v1 と v2 の両方のモデルを扱うことも可能です:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}
+
+上の例では、入力モデルは Pydantic v1、出力モデル(`response_model=ItemV2` で定義)は Pydantic v2 です。
+
+### Pydantic v1 のパラメータ { #pydantic-v1-parameters }
+
+Pydantic v1 のモデルで `Body`、`Query`、`Form` などの FastAPI 固有のパラメータユーティリティを使う必要がある場合、v2 への移行が完了するまでの間は `fastapi.temp_pydantic_v1_params` からインポートできます:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py hl[4,18] *}
+
+### 段階的に移行 { #migrate-in-steps }
+
+/// tip | 豆知識
+
+まずは `bump-pydantic` を試してください。テストが通り、問題なければコマンド一発で完了です。✨
+
+///
+
+`bump-pydantic` が適用できない場合は、同一アプリで v1 と v2 のモデルを併用できるサポートを利用して、徐々に v2 へ移行できます。
+
+まず Pydantic を v2 の最新にアップグレードし、すべてのモデルのインポートを `pydantic.v1` に切り替えます。
+
+その後、モデルをグループごとに少しずつ Pydantic v1 から v2 へ移行していきます。🚶
diff --git a/docs/ja/docs/how-to/separate-openapi-schemas.md b/docs/ja/docs/how-to/separate-openapi-schemas.md
new file mode 100644
index 0000000000000..46df2aafbaa0f
--- /dev/null
+++ b/docs/ja/docs/how-to/separate-openapi-schemas.md
@@ -0,0 +1,102 @@
+# 入力と出力でOpenAPIのスキーマを分けるかどうか { #separate-openapi-schemas-for-input-and-output-or-not }
+
+**Pydantic v2** のリリース以降、生成される OpenAPI は以前より少し正確で、より正しいものになりました。😎
+
+実際には、場合によっては同じ Pydantic モデルに対して、入力用と出力用で OpenAPI に **2 つの JSON Schema** が含まれることがあります。これは **デフォルト値** の有無に依存します。
+
+その動作と、必要に応じての変更方法を見ていきます。
+
+## 入出力のPydanticモデル { #pydantic-models-for-input-and-output }
+
+次のようにデフォルト値を持つ Pydantic モデルがあるとします。
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *}
+
+### 入力用モデル { #model-for-input }
+
+このモデルを次のように入力として使うと:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *}
+
+...`description` フィールドは **必須ではありません**。デフォルト値が `None` だからです。
+
+### ドキュメントでの入力モデル { #input-model-in-docs }
+
+ドキュメントで確認すると、`description` フィールドには **赤いアスタリスク** が付いておらず、必須としてはマークされていません:
+
+
+
+
+
+
+- FastAPI framework, high performance, easy to learn, fast to code, ready for production + FastAPI フレームワーク、高パフォーマンス、学びやすい、素早くコーディングできる、本番運用に対応
--- -**ドキュメント**: https://fastapi.tiangolo.com +**ドキュメント**: [https://fastapi.tiangolo.com/ja](https://fastapi.tiangolo.com/ja) -**ソースコード**: https://github.com/tiangolo/fastapi +**ソースコード**: [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi) --- -FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.6 以降でAPI を構築するための、モダンで、高速(高パフォーマンス)な、Web フレームワークです。 +FastAPI は、Python の標準である型ヒントに基づいて Python で API を構築するための、モダンで、高速(高パフォーマンス)な Web フレームワークです。 主な特徴: -- **高速**: **NodeJS** や **Go** 並みのとても高いパフォーマンス (Starlette と Pydantic のおかげです)。 [最も高速な Python フレームワークの一つです](#performance). - -- **高速なコーディング**: 開発速度を約 200%~300%向上させます。 \* -- **少ないバグ**: 開発者起因のヒューマンエラーを約 40%削減します。 \* -- **直感的**: 素晴らしいエディタのサポートや オートコンプリート。 デバッグ時間を削減します。 -- **簡単**: 簡単に利用、習得できるようにデザインされています。ドキュメントを読む時間を削減します。 -- **短い**: コードの重複を最小限にしています。各パラメータからの複数の機能。少ないバグ。 -- **堅牢性**: 自動対話ドキュメントを使用して、本番環境で使用できるコードを取得します。 -- **Standards-based**: API のオープンスタンダードに基づいており、完全に互換性があります: OpenAPI (以前は Swagger として知られていました) や JSON スキーマ. +* **高速**: **NodeJS** や **Go** 並みのとても高いパフォーマンス(Starlette と Pydantic のおかげです)。 [利用可能な最も高速な Python フレームワークの一つです](#performance)。 +* **高速なコーディング**: 開発速度を約 200%〜300% 向上させます。* +* **少ないバグ**: 開発者起因のヒューマンエラーを約 40% 削減します。* +* **直感的**: 素晴らしいエディタサポート。補完 があらゆる場所で使えます。デバッグ時間を削減します。 +* **簡単**: 簡単に利用・習得できるようにデザインされています。ドキュメントを読む時間を削減します。 +* **短い**: コードの重複を最小限にします。各パラメータ宣言から複数の機能を得られます。バグも減ります。 +* **堅牢性**: 自動対話型ドキュメントにより、本番環境向けのコードが得られます。 +* **Standards-based**: API のオープンスタンダードに基づいており(そして完全に互換性があります)、[OpenAPI](https://github.com/OAI/OpenAPI-Specification)(以前は Swagger として知られていました)や [JSON Schema](https://json-schema.org/) をサポートします。 -\* 本番アプリケーションを構築している開発チームのテストによる見積もり。 +* 本番アプリケーションを構築している社内開発チームのテストに基づく見積もりです。 -## Sponsors +## Sponsors { #sponsors } -{% if sponsors %} +### Keystone Sponsor { #keystone-sponsor } + +{% for sponsor in sponsors.keystone -%} +
-FastAPI は巨人の肩の上に立っています。
+## **Typer**、CLI 版 FastAPI { #typer-the-fastapi-of-clis }
-- Web の部分はStarlette
-- データの部分はPydantic
+async defを使います...async def を使います...uvicorn main:app --reloadコマンドについてfastapi dev コマンドについてemail_validator - E メールの検証
+* [`email-validator`](https://github.com/JoshData/python-email-validator) - メール検証のため。
Starlette によって使用されるもの:
-- httpx - `TestClient`を使用するために必要です。
-- jinja2 - デフォルトのテンプレート設定を使用する場合は必要です。
-- python-multipart - "parsing"`request.form()`からの変換をサポートしたい場合は必要です。
-- itsdangerous - `SessionMiddleware` サポートのためには必要です。
-- pyyaml - Starlette の `SchemaGenerator` サポートのために必要です。 (FastAPI では必要ないでしょう。)
-- graphene - `GraphQLApp` サポートのためには必要です。
-- ujson - `UJSONResponse`を使用する場合は必須です。
+* [`httpx`](https://www.python-httpx.org) - `TestClient` を使用したい場合に必要です。
+* [`jinja2`](https://jinja.palletsprojects.com) - デフォルトのテンプレート設定を使用したい場合に必要です。
+* [`python-multipart`](https://github.com/Kludex/python-multipart) - `request.form()` とともに、フォームの 「parsing」 をサポートしたい場合に必要です。
+
+FastAPI によって使用されるもの:
+
+* [`uvicorn`](https://www.uvicorn.dev) - アプリケーションをロードして提供するサーバーのため。これには `uvicorn[standard]` も含まれ、高性能なサービングに必要な依存関係(例: `uvloop`)が含まれます。
+* `fastapi-cli[standard]` - `fastapi` コマンドを提供します。
+ * これには `fastapi-cloud-cli` が含まれ、FastAPI アプリケーションを [FastAPI Cloud](https://fastapicloud.com) にデプロイできます。
+
+### `standard` 依存関係なし { #without-standard-dependencies }
+
+`standard` のオプション依存関係を含めたくない場合は、`pip install "fastapi[standard]"` の代わりに `pip install fastapi` でインストールできます。
+
+### `fastapi-cloud-cli` なし { #without-fastapi-cloud-cli }
+
+標準の依存関係を含めつつ `fastapi-cloud-cli` を除外して FastAPI をインストールしたい場合は、`pip install "fastapi[standard-no-fastapi-cloud-cli]"` でインストールできます。
+
+### 追加のオプション依存関係 { #additional-optional-dependencies }
+
+追加でインストールしたい依存関係があります。
+
+追加のオプション Pydantic 依存関係:
-FastAPI / Starlette に使用されるもの:
+* [`pydantic-settings`](https://docs.pydantic.dev/latest/usage/pydantic_settings/) - 設定管理のため。
+* [`pydantic-extra-types`](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/) - Pydantic で使用する追加の型のため。
-- uvicorn - アプリケーションをロードしてサーブするサーバーのため。
-- orjson - `ORJSONResponse`を使用したい場合は必要です。
+追加のオプション FastAPI 依存関係:
-これらは全て `pip install fastapi[all]`でインストールできます。
+* [`orjson`](https://github.com/ijl/orjson) - `ORJSONResponse` を使用したい場合に必要です。
+* [`ujson`](https://github.com/esnme/ultrajson) - `UJSONResponse` を使用したい場合に必要です。
-## ライセンス
+## ライセンス { #license }
-このプロジェクトは MIT ライセンスです。
+このプロジェクトは MIT ライセンスの条項の下でライセンスされています。
diff --git a/docs/ja/docs/learn/index.md b/docs/ja/docs/learn/index.md
new file mode 100644
index 0000000000000..bcdb1e37ee167
--- /dev/null
+++ b/docs/ja/docs/learn/index.md
@@ -0,0 +1,5 @@
+# 学習 { #learn }
+
+ここでは、**FastAPI** を学習するための入門セクションとチュートリアルを紹介します。
+
+これは、**書籍**や**コース**、FastAPIを学習するための**公式**かつ推奨される方法とみなすことができます。😎
diff --git a/docs/ja/docs/project-generation.md b/docs/ja/docs/project-generation.md
index 4b6f0f9fd0cc6..b6550e3ac347a 100644
--- a/docs/ja/docs/project-generation.md
+++ b/docs/ja/docs/project-generation.md
@@ -1,84 +1,28 @@
-# プロジェクト生成 - テンプレート
-
-プロジェクトジェネレーターは、初期設定、セキュリティ、データベース、初期APIエンドポイントなどの多くが含まれているため、プロジェクトの開始に利用できます。
-
-プロジェクトジェネレーターは常に非常に意見が分かれる設定がされており、ニーズに合わせて更新および調整する必要があります。しかしきっと、プロジェクトの良い出発点となるでしょう。
-
-## フルスタック FastAPI PostgreSQL
-
-GitHub: https://github.com/tiangolo/full-stack-fastapi-postgresql
-
-### フルスタック FastAPI PostgreSQL - 機能
-
-* 完全な**Docker**インテグレーション (Dockerベース)。
-* Docker Swarm モードデプロイ。
-* ローカル開発環境向けの**Docker Compose**インテグレーションと最適化。
-* UvicornとGunicornを使用した**リリース可能な** Python web サーバ。
-* Python **FastAPI** バックエンド:
- * **高速**: **NodeJS** や **Go** 並みのとても高いパフォーマンス (Starlette と Pydantic のおかげ)。
- * **直感的**: 素晴らしいエディタのサポートや 補完。 デバッグ時間の短縮。
- * **簡単**: 簡単に利用、習得できるようなデザイン。ドキュメントを読む時間を削減。
- * **短い**: コードの重複を最小限に。パラメータ宣言による複数の機能。
- * **堅牢性**: 自動対話ドキュメントを使用した、本番環境で使用できるコード。
- * **標準規格準拠**: API のオープンスタンダードに基く、完全な互換性: OpenAPIや JSON スキーマ。
- * 自動バリデーション、シリアライゼーション、対話的なドキュメント、OAuth2 JWTトークンを用いた認証などを含む、**その他多くの機能**。
-* **セキュアなパスワード** ハッシュ化 (デフォルトで)。
-* **JWTトークン** 認証。
-* **SQLAlchemy** モデル (Flask用の拡張と独立しているので、Celeryワーカーと直接的に併用できます)。
-* 基本的なユーザーモデル (任意の修正や削除が可能)。
-* **Alembic** マイグレーション。
-* **CORS** (Cross Origin Resource Sharing (オリジン間リソース共有))。
-* **Celery** ワーカー。バックエンドの残りの部分からモデルとコードを選択的にインポートし、使用可能。
-* Dockerと統合された**Pytest**ベースのRESTバックエンドテスト。データベースに依存せずに、全てのAPIをテスト可能。Docker上で動作するので、毎回ゼロから新たなデータストアを構築可能。(ElasticSearch、MongoDB、CouchDBなどを使用して、APIの動作をテスト可能)
-* Atom HydrogenやVisual Studio Code Jupyterなどの拡張機能を使用した、リモートまたはDocker開発用の**Jupyterカーネル**との簡単なPython統合。
-* **Vue** フロントエンド:
- * Vue CLIにより生成。
- * **JWT認証**の処理。
- * ログインビュー。
- * ログイン後の、メインダッシュボードビュー。
- * メインダッシュボードでのユーザー作成と編集。
- * セルフユーザー版
- * **Vuex**。
- * **Vue-router**。
- * 美しいマテリアルデザインコンポーネントのための**Vuetify**。
- * **TypeScript**。
- * **Nginx**ベースのDockerサーバ (Vue-routerとうまく協調する構成)。
- * Dockerマルチステージビルド。コンパイルされたコードの保存やコミットが不要。
- * ビルド時にフロントエンドテスト実行 (無効化も可能)。
- * 可能な限りモジュール化されているのでそのまま使用できますが、Vue CLIで再生成したり、必要に応じて作成したりして、必要なものを再利用可能。
-* PostgreSQLデータベースのための**PGAdmin**。(PHPMyAdminとMySQLを使用できるように簡単に変更可能)
-* Celeryジョブ監視のための**Flower**。
-* **Traefik**を使用してフロントエンドとバックエンド間をロードバランシング。同一ドメインに配置しパスで区切る、ただし、異なるコンテナで処理。
-* Traefik統合。Let's Encrypt **HTTPS**証明書の自動生成を含む。
-* GitLab **CI** (継続的インテグレーション)。フロントエンドおよびバックエンドテストを含む。
-
-## フルスタック FastAPI Couchbase
-
-GitHub: https://github.com/tiangolo/full-stack-fastapi-couchbase
-
-⚠️ **警告** ⚠️
-
-ゼロから新規プロジェクトを始める場合は、ここで代替案を確認してください。
-
-例えば、フルスタック FastAPI PostgreSQLのプロジェクトジェネレーターは、積極的にメンテナンスされ、利用されているのでより良い代替案かもしれません。また、すべての新機能と改善点が含まれています。
-
-Couchbaseベースのジェネレーターは今も無償提供されています。恐らく正常に動作するでしょう。また、すでにそのジェネレーターで生成されたプロジェクトが存在する場合でも (ニーズに合わせてアップデートしているかもしれません)、同様に正常に動作するはずです。
-
-詳細はレポジトリのドキュメントを参照して下さい。
-
-## フルスタック FastAPI MongoDB
-
-...時間の都合等によっては、今後作成されるかもしれません。😅 🎉
-
-## spaCyとFastAPIを使用した機械学習モデル
-
-GitHub: https://github.com/microsoft/cookiecutter-spacy-fastapi
-
-### spaCyとFastAPIを使用した機械学習モデル - 機能
-
-* **spaCy** のNERモデルの統合。
-* **Azure Cognitive Search** のリクエストフォーマットを搭載。
-* **リリース可能な** UvicornとGunicornを使用したPythonウェブサーバ。
-* **Azure DevOps** のKubernetes (AKS) CI/CD デプロイを搭載。
-* **多言語** プロジェクトのために、セットアップ時に言語を容易に選択可能 (spaCyに組み込まれている言語の中から)。
-* **簡単に拡張可能**。spaCyだけでなく、他のモデルフレームワーク (Pytorch、Tensorflow) へ。
+# Full Stack FastAPI テンプレート { #full-stack-fastapi-template }
+
+テンプレートは通常、特定のセットアップが含まれていますが、柔軟でカスタマイズできるように設計されています。これにより、プロジェクトの要件に合わせて変更・適応でき、優れた出発点になります。🏁
+
+このテンプレートを使って開始できます。初期セットアップ、セキュリティ、データベース、いくつかのAPIエンドポイントがすでに用意されています。
+
+GitHubリポジトリ: [Full Stack FastAPI Template](https://github.com/tiangolo/full-stack-fastapi-template)
+
+## Full Stack FastAPI テンプレート - 技術スタックと機能 { #full-stack-fastapi-template-technology-stack-and-features }
+
+- ⚡ PythonバックエンドAPI向けの [**FastAPI**](https://fastapi.tiangolo.com/ja)。
+ - 🧰 PythonのSQLデータベース操作(ORM)向けの [SQLModel](https://sqlmodel.tiangolo.com)。
+ - 🔍 FastAPIで使用される、データバリデーションと設定管理向けの [Pydantic](https://docs.pydantic.dev)。
+ - 💾 SQLデータベースとしての [PostgreSQL](https://www.postgresql.org)。
+- 🚀 フロントエンド向けの [React](https://react.dev)。
+ - 💃 TypeScript、hooks、Vite、その他のモダンなフロントエンドスタックの各要素を使用。
+ - 🎨 フロントエンドコンポーネント向けの [Tailwind CSS](https://tailwindcss.com) と [shadcn/ui](https://ui.shadcn.com)。
+ - 🤖 自動生成されたフロントエンドクライアント。
+ - 🧪 End-to-Endテスト向けの [Playwright](https://playwright.dev)。
+ - 🦇 ダークモードのサポート。
+- 🐋 開発および本番向けの [Docker Compose](https://www.docker.com)。
+- 🔒 デフォルトでの安全なパスワードハッシュ化。
+- 🔑 JWT(JSON Web Token)認証。
+- 📫 メールベースのパスワードリカバリ。
+- ✅ [Pytest](https://pytest.org) によるテスト。
+- 📞 リバースプロキシ / ロードバランサとしての [Traefik](https://traefik.io)。
+- 🚢 Docker Composeを使用したデプロイ手順(自動HTTPS証明書を処理するフロントエンドTraefikプロキシのセットアップ方法を含む)。
+- 🏭 GitHub Actionsに基づくCI(continuous integration)とCD(continuous deployment)。
diff --git a/docs/ja/docs/python-types.md b/docs/ja/docs/python-types.md
new file mode 100644
index 0000000000000..67336c31ef716
--- /dev/null
+++ b/docs/ja/docs/python-types.md
@@ -0,0 +1,348 @@
+# Pythonの型の紹介 { #python-types-intro }
+
+Python にはオプションの「型ヒント」(「型アノテーション」とも呼ばれます)がサポートされています。
+
+これらの **「型ヒント」** やアノテーションは、変数の型を宣言できる特別な構文です。
+
+変数に型を宣言することで、エディターやツールがより良いサポートを提供できます。
+
+これは Python の型ヒントについての **クイックチュートリアル/リフレッシュ** にすぎません。**FastAPI** で使うために必要な最低限のことだけをカバーしています。...実際には本当に少ないです。
+
+**FastAPI** はすべてこれらの型ヒントに基づいており、多くの強みと利点を与えてくれます。
+
+しかし、たとえ **FastAPI** をまったく使用しない場合でも、それらについて少し学ぶことで利点を得られます。
+
+/// note | 備考
+
+もしあなたが Python の専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。
+
+///
+
+## 動機 { #motivation }
+
+簡単な例から始めてみましょう:
+
+{* ../../docs_src/python_types/tutorial001_py310.py *}
+
+このプログラムを呼び出すと、以下が出力されます:
+
+```
+John Doe
+```
+
+この関数は以下のようなことを行います:
+
+* `first_name` と `last_name` を取得します。
+* `title()` を用いて、それぞれの最初の文字を大文字に変換します。
+* 真ん中にスペースを入れて連結します。
+
+{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}
+
+### 編集 { #edit-it }
+
+これはとても簡単なプログラムです。
+
+しかし、今、あなたがそれを一から書いていたと想像してみてください。
+
+パラメータの準備ができていたら、そのとき、関数の定義を始めていたことでしょう...
+
+しかし、そうすると「最初の文字を大文字に変換するあのメソッド」を呼び出す必要があります。
+
+それは `upper` でしたか?`uppercase` でしたか?`first_uppercase`?`capitalize`?
+
+そして、古くからプログラマーの友人であるエディタで自動補完を試してみます。
+
+関数の最初のパラメータ `first_name` を入力し、ドット(`.`)を入力してから、`Ctrl+Space` を押すと補完が実行されます。
+
+しかし、悲しいことに、これはなんの役にも立ちません:
+
+
+
+### 型の追加 { #add-types }
+
+先ほどのコードから一行変更してみましょう。
+
+関数のパラメータである次の断片を、以下から:
+
+```Python
+ first_name, last_name
+```
+
+以下へ変更します:
+
+```Python
+ first_name: str, last_name: str
+```
+
+これだけです。
+
+それが「型ヒント」です:
+
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
+
+これは、以下のようにデフォルト値を宣言するのと同じではありません:
+
+```Python
+ first_name="john", last_name="doe"
+```
+
+それとは別物です。
+
+イコール(`=`)ではなく、コロン(`:`)を使用します。
+
+そして、通常、型ヒントを追加しても、それらがない状態と起こることは何も変わりません。
+
+しかし今、あなたが再びその関数を作成している最中に、型ヒントを使っていると想像してみてください。
+
+同じタイミングで `Ctrl+Space` で自動補完を実行すると、以下のようになります:
+
+
+
+これであれば、あなたは「ベルを鳴らす」ものを見つけるまで、オプションを見てスクロールできます:
+
+
+
+## より強い動機 { #more-motivation }
+
+この関数を見てください。すでに型ヒントを持っています:
+
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
+
+エディタは変数の型を知っているので、補完だけでなく、エラーチェックをすることもできます:
+
+
+
+これで `age` を `str(age)` で文字列に変換して修正する必要があることがわかります:
+
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
+
+## 型の宣言 { #declaring-types }
+
+型ヒントを宣言する主な場所を見てきました。関数のパラメータです。
+
+これは **FastAPI** で使用する主な場所でもあります。
+
+### 単純な型 { #simple-types }
+
+`str` だけでなく、Python の標準的な型すべてを宣言できます。
+
+例えば、以下を使用可能です:
+
+* `int`
+* `float`
+* `bool`
+* `bytes`
+
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
+
+### `typing` モジュール { #typing-module }
+
+いくつかの追加のユースケースでは、標準ライブラリの `typing` モジュールから何かをインポートする必要があるかもしれません。例えば「任意の型」を受け付けることを宣言したい場合、`typing` の `Any` を使えます:
+
+```python
+from typing import Any
+
+
+def some_function(data: Any):
+ print(data)
+```
+
+### ジェネリック型 { #generic-types }
+
+一部の型は、角括弧内で「型パラメータ」を受け取り、内部の型を定義できます。例えば「文字列のリスト」は `list[str]` として宣言します。
+
+このように型パラメータを取れる型は **Generic types**(ジェネリクス)と呼ばれます。
+
+次の組み込み型をジェネリクスとして(角括弧と内部の型で)使えます:
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
+
+#### List { #list }
+
+例えば、`str` の `list` の変数を定義してみましょう。
+
+同じコロン(`:`)の構文で変数を宣言します。
+
+型として、`list` を指定します。
+
+リストはいくつかの内部の型を含む型なので、それらを角括弧で囲みます:
+
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
+
+/// info | 情報
+
+角括弧内の内部の型は「型パラメータ」と呼ばれています。
+
+この場合、`str` は `list` に渡される型パラメータです。
+
+///
+
+つまり: 変数 `items` は `list` であり、このリストの各項目は `str` です。
+
+そうすることで、エディタはリストの項目を処理している間にもサポートを提供できます。
+
+
+
+型がなければ、それはほぼ不可能です。
+
+変数 `item` はリスト `items` の要素の一つであることに注意してください。
+
+それでも、エディタはそれが `str` であることを知っていて、そのためのサポートを提供しています。
+
+#### Tuple と Set { #tuple-and-set }
+
+`tuple` と `set` の宣言も同様です:
+
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
+
+つまり:
+
+* 変数 `items_t` は `int`、別の `int`、`str` の 3 つの項目を持つ `tuple` です。
+* 変数 `items_s` は `set` であり、その各項目は `bytes` 型です。
+
+#### Dict { #dict }
+
+`dict` を定義するには、カンマ区切りで 2 つの型パラメータを渡します。
+
+最初の型パラメータは `dict` のキーです。
+
+2 番目の型パラメータは `dict` の値です:
+
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
+
+つまり:
+
+* 変数 `prices` は `dict` です:
+ * この `dict` のキーは `str` 型です(例えば、各項目の名前)。
+ * この `dict` の値は `float` 型です(例えば、各項目の価格)。
+
+#### Union { #union }
+
+変数が **複数の型のいずれか** になり得ることを宣言できます。例えば、`int` または `str` です。
+
+それを定義するには、両方の型を区切るために 縦棒(`|`) を使います。
+
+これは「ユニオン(union)」と呼ばれます。変数がそれら 2 つの型の集合の和集合のいずれかになり得るからです。
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
+```
+
+これは `item` が `int` または `str` になり得ることを意味します。
+
+#### `None` の可能性 { #possibly-none }
+
+値が `str` のような型を持つ可能性がある一方で、`None` にもなり得ることを宣言できます。
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
+
+////
+
+ただの `str` の代わりに `str | None` を使用することで、値が常に `str` であると仮定しているときに、実際には `None` である可能性もあるというエラーをエディタが検出するのに役立ちます。
+
+### 型としてのクラス { #classes-as-types }
+
+変数の型としてクラスを宣言することもできます。
+
+名前を持つ `Person` クラスがあるとしましょう:
+
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
+
+変数を `Person` 型として宣言できます:
+
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
+
+そして、再び、すべてのエディタのサポートを得ることができます:
+
+
+
+これは「`one_person` はクラス `Person` の **インスタンス** である」ことを意味します。
+
+「`one_person` は `Person` という名前の **クラス** である」という意味ではありません。
+
+## Pydantic のモデル { #pydantic-models }
+
+[Pydantic](https://docs.pydantic.dev/) はデータ検証を行うための Python ライブラリです。
+
+データの「形」を属性付きのクラスとして宣言します。
+
+そして、それぞれの属性は型を持ちます。
+
+さらに、いくつかの値を持つクラスのインスタンスを作成すると、その値を検証し、適切な型に変換して(もしそうであれば)すべてのデータを持つオブジェクトを提供してくれます。
+
+また、その結果のオブジェクトですべてのエディタのサポートを受けることができます。
+
+Pydantic の公式ドキュメントからの例:
+
+{* ../../docs_src/python_types/tutorial011_py310.py *}
+
+/// info | 情報
+
+[ Pydantic の詳細はドキュメントを参照してください](https://docs.pydantic.dev/)。
+
+///
+
+**FastAPI** はすべて Pydantic をベースにしています。
+
+すべてのことは [チュートリアル - ユーザーガイド](tutorial/index.md) で実際に見ることができます。
+
+## メタデータアノテーション付き型ヒント { #type-hints-with-metadata-annotations }
+
+Python には、`Annotated` を使って型ヒントに **追加の メタデータ** を付与できる機能もあります。
+
+`Annotated` は `typing` からインポートできます。
+
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
+
+Python 自体は、この `Annotated` で何かをするわけではありません。また、エディタや他のツールにとっても、型は依然として `str` です。
+
+しかし、`Annotated` 内のこのスペースを使って、アプリケーションをどのように動作させたいかについての追加メタデータを **FastAPI** に提供できます。
+
+覚えておくべき重要な点は、`Annotated` に渡す **最初の「型パラメータ」** が **実際の型** であることです。残りは、他のツール向けのメタデータにすぎません。
+
+今のところは、`Annotated` が存在し、それが標準の Python であることを知っておけば十分です。😎
+
+後で、これがどれほど **強力** になり得るかを見ることになります。
+
+/// tip | 豆知識
+
+これが **標準の Python** であるという事実は、エディタで、使用しているツール(コードの解析やリファクタリングなど)とともに、**可能な限り最高の開発体験** が得られることを意味します。 ✨
+
+また、あなたのコードが他の多くの Python ツールやライブラリとも非常に互換性が高いことも意味します。 🚀
+
+///
+
+## **FastAPI** での型ヒント { #type-hints-in-fastapi }
+
+**FastAPI** はこれらの型ヒントを利用していくつかのことを行います。
+
+**FastAPI** では型ヒントを使ってパラメータを宣言すると以下のものが得られます:
+
+* **エディタサポート**。
+* **型チェック**。
+
+...そして **FastAPI** は同じ宣言を使って、以下のことを行います:
+
+* **要件の定義**: リクエストのパスパラメータ、クエリパラメータ、ヘッダー、ボディ、依存関係などから要件を定義します。
+* **データの変換**: リクエストから必要な型にデータを変換します。
+* **データの検証**: 各リクエストから来るデータについて:
+ * データが無効な場合にクライアントに返される **自動エラー** を生成します。
+* OpenAPI を使用して API を **ドキュメント化** します:
+ * これは自動の対話型ドキュメントのユーザーインターフェイスで使われます。
+
+すべてが抽象的に聞こえるかもしれません。心配しないでください。 この全ての動作は [チュートリアル - ユーザーガイド](tutorial/index.md) で見ることができます。
+
+重要なのは、Python の標準的な型を使うことで、(クラスやデコレータなどを追加するのではなく)1 つの場所で **FastAPI** が多くの作業を代わりにやってくれているということです。
+
+/// info | 情報
+
+すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、良いリソースとして [`mypy` の「チートシート`](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html) があります。
+
+///
diff --git a/docs/ja/docs/resources/index.md b/docs/ja/docs/resources/index.md
new file mode 100644
index 0000000000000..15a949e016b05
--- /dev/null
+++ b/docs/ja/docs/resources/index.md
@@ -0,0 +1,3 @@
+# リソース { #resources }
+
+追加リソース、外部リンクなど。✈️
diff --git a/docs/ja/docs/translation-banner.md b/docs/ja/docs/translation-banner.md
new file mode 100644
index 0000000000000..351a82a35a3b2
--- /dev/null
+++ b/docs/ja/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 AI と人間による翻訳
+
+この翻訳は、人間のガイドに基づいて AI によって作成されました。🤝
+
+原文の意図を取り違えていたり、不自然な表現になっている可能性があります。🤖
+
+[AI LLM をより適切に誘導するのを手伝う](https://fastapi.tiangolo.com/ja/contributing/#translations) ことで、この翻訳を改善できます。
+
+[英語版](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/ja/docs/tutorial/background-tasks.md b/docs/ja/docs/tutorial/background-tasks.md
new file mode 100644
index 0000000000000..0bacbb3947231
--- /dev/null
+++ b/docs/ja/docs/tutorial/background-tasks.md
@@ -0,0 +1,86 @@
+# バックグラウンドタスク { #background-tasks }
+
+レスポンスを返した *後に* 実行されるバックグラウンドタスクを定義できます。
+
+これは、リクエスト後に処理を開始する必要があるが、クライアントがレスポンスを受け取る前に処理を終える必要のない操作に役立ちます。
+
+これには、たとえば次のものが含まれます。
+
+* 作業実行後のメール通知:
+ * メールサーバーへの接続とメールの送信は「遅い」(数秒) 傾向があるため、すぐにレスポンスを返し、バックグラウンドでメール通知ができます。
+* データ処理:
+ * たとえば、時間のかかる処理を必要とするファイル受信時には、「Accepted」(HTTP 202) のレスポンスを返し、バックグラウンドで処理できます。
+
+## `BackgroundTasks` の使用 { #using-backgroundtasks }
+
+まず初めに、`BackgroundTasks` をインポートし、`BackgroundTasks` の型宣言と共に、*path operation function* のパラメーターを定義します:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
+
+**FastAPI** は、`BackgroundTasks` 型のオブジェクトを作成し、そのパラメーターに渡します。
+
+## タスク関数の作成 { #create-a-task-function }
+
+バックグラウンドタスクとして実行される関数を作成します。
+
+これは、パラメーターを受け取ることができる単なる標準的な関数です。
+
+これは `async def` または通常の `def` 関数であり、**FastAPI** はこれを正しく処理します。
+
+ここで、タスク関数はファイル書き込みを実行します (メール送信のシミュレーション)。
+
+また、書き込み操作では `async` と `await` を使用しないため、通常の `def` で関数を定義します。
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
+
+## バックグラウンドタスクの追加 { #add-the-background-task }
+
+*path operation function* 内で、`.add_task()` メソッドを使用してタスク関数を *background tasks* オブジェクトに渡します。
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
+
+`.add_task()` は以下の引数を受け取ります:
+
+* バックグラウンドで実行されるタスク関数 (`write_notification`)。
+* タスク関数に順番に渡す必要のある引数の列 (`email`)。
+* タスク関数に渡す必要のあるキーワード引数 (`message="some notification"`)。
+
+## 依存性注入 { #dependency-injection }
+
+`BackgroundTasks` の使用は依存性注入システムでも機能し、様々な階層 (*path operation function*、依存性 (dependable)、サブ依存性など) で `BackgroundTasks` 型のパラメーターを宣言できます。
+
+**FastAPI** は、それぞれの場合の処理方法と同じオブジェクトの再利用方法を知っているため、すべてのバックグラウンドタスクがマージされ、バックグラウンドで後で実行されます:
+
+
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
+
+
+この例では、レスポンスが送信された *後* にメッセージが `log.txt` ファイルに書き込まれます。
+
+リクエストにクエリがあった場合、バックグラウンドタスクでログに書き込まれます。
+
+そして、*path operation function* で生成された別のバックグラウンドタスクは、`email` パスパラメータを使用してメッセージを書き込みます。
+
+## 技術的な詳細 { #technical-details }
+
+`BackgroundTasks` クラスは、[`starlette.background`](https://www.starlette.dev/background/) から直接取得されます。
+
+これは、FastAPI に直接インポート/インクルードされるため、`fastapi` からインポートできる上に、`starlette.background`から別の `BackgroundTask` (末尾に `s` がない) を誤ってインポートすることを回避できます。
+
+`BackgroundTasks`のみを使用することで (`BackgroundTask` ではなく)、`Request` オブジェクトを直接使用する場合と同様に、それを *path operation function* パラメーターとして使用し、**FastAPI** に残りの処理を任せることができます。
+
+それでも、FastAPI で `BackgroundTask` を単独で使用することは可能ですが、コード内でオブジェクトを作成し、それを含むStarlette `Response` を返す必要があります。
+
+詳細については、[Starlette のバックグラウンドタスクに関する公式ドキュメント](https://www.starlette.dev/background/)を参照して下さい。
+
+## 注意 { #caveat }
+
+大量のバックグラウンド計算が必要であり、必ずしも同じプロセスで実行する必要がない場合 (たとえば、メモリや変数などを共有する必要がない場合)、[Celery](https://docs.celeryq.dev) のようなより大きな他のツールを使用するとメリットがあるかもしれません。
+
+これらは、より複雑な構成、RabbitMQ や Redis などのメッセージ/ジョブキューマネージャーを必要とする傾向がありますが、複数のプロセス、特に複数のサーバーでバックグラウンドタスクを実行できます。
+
+ただし、同じ **FastAPI** アプリから変数とオブジェクトにアクセスする必要がある場合、または小さなバックグラウンドタスク (電子メール通知の送信など) を実行する必要がある場合は、単に `BackgroundTasks` を使用できます。
+
+## まとめ { #recap }
+
+*path operation functions* と依存性のパラメータで `BackgroundTasks`をインポートして使用し、バックグラウンドタスクを追加して下さい。
diff --git a/docs/ja/docs/tutorial/bigger-applications.md b/docs/ja/docs/tutorial/bigger-applications.md
new file mode 100644
index 0000000000000..3518eaed39fcb
--- /dev/null
+++ b/docs/ja/docs/tutorial/bigger-applications.md
@@ -0,0 +1,535 @@
+# 大規模アプリケーション - 複数ファイル { #bigger-applications-multiple-files }
+
+アプリケーションや Web API を作る場合、すべてを1つのファイルに収められることはほとんどありません。
+
+**FastAPI** は、柔軟性を保ったままアプリケーションを構造化できる便利なツールを提供します。
+
+/// info | 情報
+
+Flask 出身であれば、Flask の Blueprint に相当します。
+
+///
+
+## 例のファイル構成 { #an-example-file-structure }
+
+次のようなファイル構成があるとします:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ ├── dependencies.py
+│ └── routers
+│ │ ├── __init__.py
+│ │ ├── items.py
+│ │ └── users.py
+│ └── internal
+│ ├── __init__.py
+│ └── admin.py
+```
+
+/// tip | 豆知識
+
+複数の `__init__.py` ファイルがあります: 各ディレクトリやサブディレクトリに1つずつです。
+
+これにより、あるファイルから別のファイルへコードをインポートできます。
+
+例えば、`app/main.py` では次のように書けます:
+
+```
+from app.routers import items
+```
+
+///
+
+* `app` ディレクトリはすべてを含みます。そして空のファイル `app/__init__.py` があり、「Python パッケージ」(「Python モジュール」の集合): `app` です。
+* `app/main.py` ファイルがあります。Python パッケージ(`__init__.py` のあるディレクトリ)の中にあるため、そのパッケージの「モジュール」: `app.main` です。
+* `app/dependencies.py` ファイルもあり、`app/main.py` と同様に「モジュール」: `app.dependencies` です。
+* `app/routers/` サブディレクトリに別の `__init__.py` があるので、「Python サブパッケージ」: `app.routers` です。
+* `app/routers/items.py` はパッケージ `app/routers/` 内のファイルなので、サブモジュール: `app.routers.items` です。
+* `app/routers/users.py` も同様で、別のサブモジュール: `app.routers.users` です。
+* `app/internal/` サブディレクトリにも `__init__.py` があるので、別の「Python サブパッケージ」: `app.internal` です。
+* `app/internal/admin.py` は別のサブモジュール: `app.internal.admin` です。
+
+
+
+## 同じルーターを異なる `prefix` で複数回取り込む { #include-the-same-router-multiple-times-with-different-prefix }
+
+同じルーターに対して、異なる prefix で `.include_router()` を複数回使うこともできます。
+
+例えば、同じ API を `/api/v1` と `/api/latest` のように異なる prefix で公開する場合に役立ちます。
+
+高度な使い方なので不要かもしれませんが、必要な場合に備えて用意されています。
+
+## `APIRouter` を別の `APIRouter` に取り込む { #include-an-apirouter-in-another }
+
+`APIRouter` を `FastAPI` アプリケーションに取り込めるのと同じように、`APIRouter` を別の `APIRouter` に取り込むこともできます:
+
+```Python
+router.include_router(other_router)
+```
+
+`router` を `FastAPI` アプリに取り込む前にこれを実行して、`other_router` の *path operations* も含まれるようにしてください。
diff --git a/docs/ja/docs/tutorial/body-fields.md b/docs/ja/docs/tutorial/body-fields.md
new file mode 100644
index 0000000000000..234c99d529b23
--- /dev/null
+++ b/docs/ja/docs/tutorial/body-fields.md
@@ -0,0 +1,61 @@
+# ボディ - フィールド { #body-fields }
+
+`Query`や`Path`、`Body`を使って *path operation関数* のパラメータに追加のバリデーションやメタデータを宣言するのと同じように、Pydanticの`Field`を使ってPydanticモデルの内部でバリデーションやメタデータを宣言することができます。
+
+## `Field`のインポート { #import-field }
+
+まず、以下のようにインポートします:
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}
+
+
+/// warning | 注意
+
+`Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。
+
+///
+
+## モデルの属性の宣言 { #declare-model-attributes }
+
+以下のように`Field`をモデルの属性として使用することができます:
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}
+
+`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 関数の*パラメータと同じ構造になっていることに注目してください。
+
+///
+
+## 追加情報の追加 { #add-extra-information }
+
+追加情報は`Field`や`Query`、`Body`などで宣言することができます。そしてそれは生成されたJSONスキーマに含まれます。
+
+後に例を用いて宣言を学ぶ際に、追加情報を追加する方法を学べます。
+
+/// warning | 注意
+
+`Field`に渡された追加のキーは、結果として生成されるアプリケーションのOpenAPIスキーマにも含まれます。
+これらのキーは必ずしもOpenAPI仕様の一部であるとは限らないため、例えば[OpenAPI validator](https://validator.swagger.io/)などの一部のOpenAPIツールは、生成されたスキーマでは動作しない場合があります。
+
+///
+
+## まとめ { #recap }
+
+Pydanticの`Field`を使用して、モデルの属性に追加のバリデーションやメタデータを宣言することができます。
+
+追加のキーワード引数を使用して、追加のJSONスキーマのメタデータを渡すこともできます。
diff --git a/docs/ja/docs/tutorial/body-multiple-params.md b/docs/ja/docs/tutorial/body-multiple-params.md
new file mode 100644
index 0000000000000..0f81f4c46a766
--- /dev/null
+++ b/docs/ja/docs/tutorial/body-multiple-params.md
@@ -0,0 +1,168 @@
+# ボディ - 複数のパラメータ { #body-multiple-parameters }
+
+これまで`Path`と`Query`をどう使うかを見てきましたが、リクエストボディ宣言のより高度な使い方を見てみましょう。
+
+## `Path`、`Query`とボディパラメータを混ぜる { #mix-path-query-and-body-parameters }
+
+まず、もちろん、`Path`と`Query`とリクエストボディのパラメータ宣言は自由に混ぜることができ、 **FastAPI** は何をするべきかを知っています。
+
+また、デフォルトを`None`に設定することで、ボディパラメータをオプションとして宣言することもできます:
+
+{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
+
+/// note | 備考
+
+この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値が`None`になっているためです。
+
+///
+
+## 複数のボディパラメータ { #multiple-body-parameters }
+
+上述の例では、*path operations*は`Item`の属性を持つ以下のようなJSONボディを期待していました:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+
+しかし、`item`と`user`のように複数のボディパラメータを宣言することもできます:
+
+{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}
+
+
+この場合、**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スキーマや自動ドキュメントのように文書化してくれます。
+
+## ボディ内の単数値 { #singular-values-in-body }
+
+クエリとパスパラメータの追加データを定義するための `Query` と `Path` があるのと同じように、 **FastAPI** は同等の `Body` を提供します。
+
+例えば、前のモデルを拡張して、同じボディに `item` と `user` の他にもう一つのキー `importance` を入れたいと決めることができます。
+
+単数値なのでそのまま宣言すると、**FastAPI** はそれがクエリパラメータであるとみなします。
+
+しかし、`Body`を使用して、**FastAPI** に別のボディキーとして扱うように指示することができます:
+
+{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
+
+
+この場合、**FastAPI** は以下のようなボディを期待します:
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ },
+ "importance": 5
+}
+```
+
+繰り返しになりますが、データ型の変換、検証、文書化などを行います。
+
+## 複数のボディパラメータとクエリ { #multiple-body-params-and-query }
+
+もちろん、ボディパラメータに加えて、必要に応じて追加のクエリパラメータを宣言することもできます。
+
+デフォルトでは、単数値はクエリパラメータとして解釈されるので、明示的に `Query` を追加する必要はなく、次のようにできます:
+
+```Python
+q: str | None = None
+```
+
+例えば:
+
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
+
+/// info | 情報
+
+`Body`もまた、後述する `Query` や `Path` などと同様に、すべての追加検証パラメータとメタデータパラメータを持っています。
+
+///
+
+## 単一のボディパラメータの埋め込み { #embed-a-single-body-parameter }
+
+Pydanticモデル`Item`の単一の`item`ボディパラメータしかないとしましょう。
+
+デフォルトでは、**FastAPI**はそのボディを直接期待します。
+
+しかし、追加のボディパラメータを宣言したときのように、キー `item` を持つ JSON と、その中のモデル内容を期待したい場合は、特別な `Body` パラメータ `embed` を使うことができます:
+
+```Python
+item: Item = Body(embed=True)
+```
+
+以下において:
+
+{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}
+
+
+この場合、**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
+}
+```
+
+## まとめ { #recap }
+
+リクエストが単一のボディしか持てない場合でも、*path operation function*に複数のボディパラメータを追加することができます。
+
+しかし、**FastAPI** はそれを処理し、関数内の正しいデータを与え、*path operation*内の正しいスキーマを検証し、文書化します。
+
+また、ボディの一部として受け取る単数値を宣言することもできます。
+
+また、単一のパラメータしか宣言されていない場合でも、ボディをキーに埋め込むように **FastAPI** に指示することができます。
diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md
new file mode 100644
index 0000000000000..5187eb14e5e20
--- /dev/null
+++ b/docs/ja/docs/tutorial/body-nested-models.md
@@ -0,0 +1,221 @@
+# ボディ - ネストされたモデル { #body-nested-models }
+
+**FastAPI** を使用すると、深くネストされた任意のモデルを定義、検証、文書化、使用することができます(Pydanticのおかげです)。
+
+## リストのフィールド { #list-fields }
+
+属性をサブタイプとして定義することができます。例えば、Pythonの`list`:
+
+{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}
+
+これにより、各項目の型は宣言されていませんが、`tags`はリストになります。
+
+## タイプパラメータを持つリストのフィールド { #list-fields-with-type-parameter }
+
+しかし、Pythonには内部の型、または「タイプパラメータ」を使ってリストを宣言するための特定の方法があります:
+
+### タイプパラメータを持つ`list`の宣言 { #declare-a-list-with-a-type-parameter }
+
+`list`、`dict`、`tuple`のようにタイプパラメータ(内部の型)を持つ型を宣言するには、
+角括弧(`[`と`]`)を使って内部の型を「タイプパラメータ」として渡します。
+
+```Python
+my_list: list[str]
+```
+
+型宣言の標準的なPythonの構文はこれだけです。
+
+内部の型を持つモデルの属性にも同じ標準の構文を使用してください。
+
+そのため、以下の例では`tags`を具体的な「文字列のリスト」にすることができます:
+
+{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}
+
+## セット型 { #set-types }
+
+しかし、よく考えてみると、タグは繰り返すべきではなく、おそらくユニークな文字列になるのではないかと気付いたとします。
+
+そして、Pythonにはユニークな項目のセットのための特別なデータ型`set`があります。
+
+そして、`tags`を文字列のセットとして宣言できます:
+
+{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}
+
+これを使えば、データが重複しているリクエストを受けた場合でも、ユニークな項目のセットに変換されます。
+
+そして、そのデータを出力すると、たとえソースに重複があったとしても、固有の項目のセットとして出力されます。
+
+また、それに応じて注釈をつけたり、文書化したりします。
+
+## ネストされたモデル { #nested-models }
+
+Pydanticモデルの各属性には型があります。
+
+しかし、その型はそれ自体が別のPydanticモデルである可能性があります。
+
+そのため、特定の属性名、型、バリデーションを指定して、深くネストしたJSON「オブジェクト」を宣言することができます。
+
+すべては、任意のネストにされています。
+
+### サブモデルの定義 { #define-a-submodel }
+
+例えば、`Image`モデルを定義することができます:
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}
+
+### サブモデルを型として使用 { #use-the-submodel-as-a-type }
+
+そして、それを属性の型として使用することができます:
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}
+
+これは **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** を使用して、その宣言を行うだけで以下のような恩恵を受けられます:
+
+* ネストされたモデルでも対応可能なエディタのサポート(補完など)
+* データ変換
+* データの検証
+* 自動文書化
+
+## 特殊な型とバリデーション { #special-types-and-validation }
+
+`str`や`int`、`float`などの通常の単数型の他にも、`str`を継承したより複雑な単数型を使うこともできます。
+
+すべてのオプションをみるには、[Pydantic の型の概要](https://docs.pydantic.dev/latest/concepts/types/)を確認してください。次の章でいくつかの例をみることができます。
+
+例えば、`Image`モデルのように`url`フィールドがある場合、`str`の代わりにPydanticの`HttpUrl`のインスタンスとして宣言することができます:
+
+{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}
+
+文字列は有効なURLであることが確認され、そのようにJSON Schema / OpenAPIで文書化されます。
+
+## サブモデルのリストを持つ属性 { #attributes-with-lists-of-submodels }
+
+Pydanticモデルを`list`や`set`などのサブタイプとして使用することもできます:
+
+{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}
+
+これは、次のような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`キーが画像オブジェクトのリストを持つようになったことに注目してください。
+
+///
+
+## 深くネストされたモデル { #deeply-nested-models }
+
+深くネストされた任意のモデルを定義することができます:
+
+{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}
+
+/// info | 情報
+
+`Offer`は`Item`のリストであり、それらがさらにオプションの`Image`のリストを持っていることに注目してください。
+
+///
+
+## 純粋なリストのボディ { #bodies-of-pure-lists }
+
+期待するJSONボディのトップレベルの値がJSON`array`(Pythonの`list`)であれば、Pydanticモデルと同じように、関数のパラメータで型を宣言することができます:
+
+```Python
+images: list[Image]
+```
+
+以下のように:
+
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
+
+## あらゆる場所でのエディタサポート { #editor-support-everywhere }
+
+そして、あらゆる場所でエディタサポートを得られます。
+
+以下のようにリストの中の項目でも:
+
+
+
+Pydanticモデルではなく、`dict`を直接使用している場合はこのようなエディタのサポートは得られません。
+
+しかし、それらについて心配する必要はありません。入力されたdictは自動的に変換され、出力も自動的にJSONに変換されます。
+
+## 任意の`dict`のボディ { #bodies-of-arbitrary-dicts }
+
+また、ある型のキーと別の型の値を持つ`dict`としてボディを宣言することもできます。
+
+この方法で、有効なフィールド/属性名を事前に知る必要がありません(Pydanticモデルの場合のように)。
+
+これは、まだ知らないキーを受け取りたいときに便利です。
+
+---
+
+もうひとつ便利なケースは、別の型(例: `int`)のキーを持ちたい場合です。
+
+それをここで見ていきます。
+
+この場合、`int`のキーと`float`の値を持つものであれば、どんな`dict`でも受け入れることができます:
+
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
+
+/// tip | 豆知識
+
+JSONはキーとして`str`しかサポートしていないことに注意してください。
+
+しかしPydanticには自動データ変換機能があります。
+
+これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。
+
+そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。
+
+///
+
+## まとめ { #recap }
+
+**FastAPI** を使用すると、Pydanticモデルが提供する最大限の柔軟性を持ちながら、コードをシンプルに短く、エレガントに保つことができます。
+
+しかし、以下のような利点があります:
+
+* エディタのサポート(どこでも補完!)
+* データ変換(別名:構文解析 / シリアライズ)
+* データの検証
+* スキーマ文書
+* 自動ドキュメント
diff --git a/docs/ja/docs/tutorial/body-updates.md b/docs/ja/docs/tutorial/body-updates.md
index 7a56ef2b9bba3..a4fa8bd7beabb 100644
--- a/docs/ja/docs/tutorial/body-updates.md
+++ b/docs/ja/docs/tutorial/body-updates.md
@@ -1,18 +1,16 @@
-# ボディ - 更新
+# ボディ - 更新 { #body-updates }
-## `PUT`による置換での更新
+## `PUT`による置換での更新 { #update-replacing-with-put }
-項目を更新するにはHTTPの`PUT`操作を使用することができます。
+項目を更新するには[HTTPの`PUT`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT)操作を使用することができます。
-`jsonable_encoder`を用いて、入力データをJSON形式で保存できるデータに変換することができます(例:NoSQLデータベース)。例えば、`datetime`を`str`に変換します。
+`jsonable_encoder`を用いて、入力データをJSONとして保存できるデータに変換することができます(例:NoSQLデータベース)。例えば、`datetime`を`str`に変換します。
-```Python hl_lines="30 31 32 33 34 35"
-{!../../../docs_src/body_updates/tutorial001.py!}
-```
+{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}
-既存のデータを置き換えるべきデータを受け取るために`PUT`は使用されます。
+`PUT`は、既存のデータを置き換えるべきデータを受け取るために使用されます。
-### 置換についての注意
+### 置換についての注意 { #warning-about-replacing }
つまり、`PUT`を使用して以下のボディで項目`bar`を更新したい場合は:
@@ -24,50 +22,49 @@
}
```
-すでに格納されている属性`"tax": 20.2`を含まないため、入力モデルのデフォルト値は`"tax": 10.5`です。
+すでに格納されている属性`"tax": 20.2`を含まないため、入力モデルは`"tax": 10.5`のデフォルト値を取ります。
そして、データはその「新しい」`10.5`の`tax`と共に保存されます。
-## `PATCH`による部分的な更新
+## `PATCH`による部分的な更新 { #partial-updates-with-patch }
-また、HTTPの`PATCH`操作でデータを*部分的に*更新することもできます。
+また、[HTTPの`PATCH`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH)操作でデータを*部分的に*更新することもできます。
つまり、更新したいデータだけを送信して、残りはそのままにしておくことができます。
-!!! Note "備考"
- `PATCH`は`PUT`よりもあまり使われておらず、知られていません。
+/// note | 備考
+
+`PATCH`は`PUT`よりもあまり使われておらず、知られていません。
+
+また、多くのチームは部分的な更新であっても`PUT`だけを使用しています。
- また、多くのチームは部分的な更新であっても`PUT`だけを使用しています。
+**FastAPI** はどんな制限も課けていないので、それらを使うのは **自由** です。
- **FastAPI** はどんな制限も課けていないので、それらを使うのは **自由** です。
+しかし、このガイドでは、それらがどのように使用されることを意図しているかを多かれ少なかれ、示しています。
- しかし、このガイドでは、それらがどのように使用されることを意図しているかを多かれ少なかれ、示しています。
+///
-### Pydanticの`exclude_unset`パラメータの使用
+### Pydanticの`exclude_unset`パラメータの使用 { #using-pydantics-exclude-unset-parameter }
-部分的な更新を受け取りたい場合は、Pydanticモデルの`.dict()`の`exclude_unset`パラメータを使用すると非常に便利です。
+部分的な更新を受け取りたい場合は、Pydanticモデルの`.model_dump()`の`exclude_unset`パラメータを使用すると非常に便利です。
-`item.dict(exclude_unset=True)`のように。
+`item.model_dump(exclude_unset=True)`のように。
これにより、`item`モデルの作成時に設定されたデータのみを持つ`dict`が生成され、デフォルト値は除外されます。
これを使うことで、デフォルト値を省略して、設定された(リクエストで送られた)データのみを含む`dict`を生成することができます:
-```Python hl_lines="34"
-{!../../../docs_src/body_updates/tutorial002.py!}
-```
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}
-### Pydanticの`update`パラメータ
+### Pydanticの`update`パラメータの使用 { #using-pydantics-update-parameter }
-ここで、`.copy()`を用いて既存のモデルのコピーを作成し、`update`パラメータに更新するデータを含む`dict`を渡すことができます。
+ここで、`.model_copy()`を用いて既存のモデルのコピーを作成し、`update`パラメータに更新するデータを含む`dict`を渡すことができます。
-`stored_item_model.copy(update=update_data)`のように:
+`stored_item_model.model_copy(update=update_data)`のように:
-```Python hl_lines="35"
-{!../../../docs_src/body_updates/tutorial002.py!}
-```
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}
-### 部分的更新のまとめ
+### 部分的更新のまとめ { #partial-updates-recap }
まとめると、部分的な更新を適用するには、次のようにします:
@@ -78,22 +75,26 @@
* この方法では、モデル内のデフォルト値ですでに保存されている値を上書きするのではなく、ユーザーが実際に設定した値のみを更新することができます。
* 保存されているモデルのコピーを作成し、受け取った部分的な更新で属性を更新します(`update`パラメータを使用します)。
* コピーしたモデルをDBに保存できるものに変換します(例えば、`jsonable_encoder`を使用します)。
- * これはモデルの`.dict()`メソッドを再度利用することに匹敵しますが、値をJSONに変換できるデータ型、例えば`datetime`を`str`に変換します。
+ * これはモデルの`.model_dump()`メソッドを再度利用することに匹敵しますが、値をJSONに変換できるデータ型になるようにし(変換し)、例えば`datetime`を`str`に変換します。
* データをDBに保存します。
* 更新されたモデルを返します。
-```Python hl_lines="30 31 32 33 34 35 36 37"
-{!../../../docs_src/body_updates/tutorial002.py!}
-```
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *}
+
+/// tip | 豆知識
+
+実際には、HTTPの`PUT`操作でも同じテクニックを使用することができます。
+
+しかし、これらのユースケースのために作成されたので、ここでの例では`PATCH`を使用しています。
+
+///
-!!! tip "豆知識"
- 実際には、HTTPの`PUT`操作でも同じテクニックを使用することができます。
+/// note | 備考
- しかし、これらのユースケースのために作成されたので、ここでの例では`PATCH`を使用しています。
+入力モデルがまだ検証されていることに注目してください。
-!!! note "備考"
- 入力モデルがまだ検証されていることに注目してください。
+そのため、すべての属性を省略できる部分的な変更を受け取りたい場合は、すべての属性をオプションとしてマークしたモデルを用意する必要があります(デフォルト値または`None`を使用して)。
- そのため、すべての属性を省略できる部分的な変更を受け取りたい場合は、すべての属性をオプションとしてマークしたモデルを用意する必要があります(デフォルト値または`None`を使用して)。
+**更新** のためのオプション値がすべて設定されているモデルと、**作成** のための必須値が設定されているモデルを区別するには、[追加モデル](extra-models.md)で説明されている考え方を利用することができます。
- **更新** のためのオプション値がすべて設定されているモデルと、**作成** のための必須値が設定されているモデルを区別するには、[追加モデル](extra-models.md){.internal-link target=_blank}で説明されている考え方を利用することができます。
+///
diff --git a/docs/ja/docs/tutorial/body.md b/docs/ja/docs/tutorial/body.md
index d2559205bd576..9f100738c0d6d 100644
--- a/docs/ja/docs/tutorial/body.md
+++ b/docs/ja/docs/tutorial/body.md
@@ -1,41 +1,41 @@
-# リクエストボディ
+# リクエストボディ { #request-body }
-クライアント (ブラウザなど) からAPIにデータを送信する必要があるとき、データを **リクエストボディ (request body)** として送ります。
+クライアント(例えばブラウザ)からAPIにデータを送信する必要がある場合、**リクエストボディ**として送信します。
-**リクエスト** ボディはクライアントによってAPIへ送られます。**レスポンス** ボディはAPIがクライアントに送るデータです。
+**リクエスト**ボディは、クライアントからAPIへ送信されるデータです。**レスポンス**ボディは、APIがクライアントに送信するデータです。
-APIはほとんどの場合 **レスポンス** ボディを送らなければなりません。しかし、クライアントは必ずしも **リクエスト** ボディを送らなければいけないわけではありません。
+APIはほとんどの場合 **レスポンス** ボディを送信する必要があります。しかしクライアントは、常に **リクエストボディ** を送信する必要があるとは限りません。場合によっては、クエリパラメータ付きのパスだけをリクエストして、ボディを送信しないこともあります。
-**リクエスト** ボディを宣言するために Pydantic モデルを使用します。そして、その全てのパワーとメリットを利用します。
+**リクエスト**ボディを宣言するには、[Pydantic](https://docs.pydantic.dev/) モデルを使用し、その強力な機能とメリットをすべて利用します。
-!!! info "情報"
- データを送るには、`POST` (もっともよく使われる)、`PUT`、`DELETE` または `PATCH` を使うべきです。
+/// info | 情報
- GET リクエストでボディを送信することは、仕様では未定義の動作ですが、FastAPI でサポートされており、非常に複雑な(極端な)ユースケースにのみ対応しています。
+データを送信するには、`POST`(より一般的)、`PUT`、`DELETE`、`PATCH` のいずれかを使用すべきです。
- 非推奨なので、Swagger UIを使った対話型のドキュメントにはGETのボディ情報は表示されません。さらに、中継するプロキシが対応していない可能性があります。
+`GET` リクエストでボディを送信することは仕様上は未定義の動作ですが、それでもFastAPIではサポートされています。ただし、非常に複雑/極端なユースケースのためだけです。
-## Pydanticの `BaseModel` をインポート
+推奨されないため、Swagger UIによる対話的ドキュメントでは `GET` 使用時のボディのドキュメントは表示されず、途中のプロキシが対応していない可能性もあります。
-ます初めに、 `pydantic` から `BaseModel` をインポートする必要があります:
+///
-```Python hl_lines="2"
-{!../../../docs_src/body/tutorial001.py!}
-```
+## Pydanticの `BaseModel` をインポート { #import-pydantics-basemodel }
-## データモデルの作成
+まず、`pydantic` から `BaseModel` をインポートする必要があります:
-そして、`BaseModel` を継承したクラスとしてデータモデルを宣言します。
+{* ../../docs_src/body/tutorial001_py310.py hl[2] *}
-すべての属性にpython標準の型を使用します:
+## データモデルの作成 { #create-your-data-model }
-```Python hl_lines="5-9"
-{!../../../docs_src/body/tutorial001.py!}
-```
+次に、`BaseModel` を継承するクラスとしてデータモデルを宣言します。
+
+すべての属性に標準のPython型を使用します:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}
-クエリパラメータの宣言と同様に、モデル属性がデフォルト値をもつとき、必須な属性ではなくなります。それ以外は必須になります。オプショナルな属性にしたい場合は `None` を使用してください。
-例えば、上記のモデルは以下の様なJSON「`オブジェクト`」(もしくはPythonの `dict` ) を宣言しています:
+クエリパラメータの宣言と同様に、モデル属性がデフォルト値を持つ場合は必須ではありません。そうでなければ必須です。単にオプションにするには `None` を使用してください。
+
+例えば、上記のモデルは次のようなJSON「`object`」(またはPythonの `dict`)を宣言します:
```JSON
{
@@ -46,7 +46,7 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ
}
```
-...`description` と `tax` はオプショナル (デフォルト値は `None`) なので、以下のJSON「`オブジェクト`」も有効です:
+...`description` と `tax` はオプション(デフォルト値が `None`)なので、このJSON「`object`」も有効です:
```JSON
{
@@ -55,111 +55,112 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ
}
```
-## パラメータとして宣言
+## パラメータとして宣言 { #declare-it-as-a-parameter }
-*パスオペレーション* に加えるために、パスパラメータやクエリパラメータと同じ様に宣言します:
+*path operation* に追加するには、パスパラメータやクエリパラメータを宣言したのと同じ方法で宣言します:
-```Python hl_lines="16"
-{!../../../docs_src/body/tutorial001.py!}
-```
+{* ../../docs_src/body/tutorial001_py310.py hl[16] *}
-...そして、作成したモデル `Item` で型を宣言します。
+...そして、作成したモデル `Item` を型として宣言します。
-## 結果
+## 結果 { #results }
-そのPythonの型宣言だけで **FastAPI** は以下のことを行います:
+そのPythonの型宣言だけで **FastAPI** は以下を行います:
-* リクエストボディをJSONとして読み取ります。
-* 適当な型に変換します(必要な場合)。
+* リクエストのボディをJSONとして読み取ります。
+* 対応する型に変換します(必要な場合)。
* データを検証します。
- * データが無効な場合は、明確なエラーが返され、どこが不正なデータであったかを示します。
-* 受け取ったデータをパラメータ `item` に変換します。
- * 関数内で `Item` 型であると宣言したので、すべての属性とその型に対するエディタサポート(補完など)をすべて使用できます。
-* モデルのJSONスキーマ定義を生成し、好きな場所で使用することができます。
-* これらのスキーマは、生成されたOpenAPIスキーマの一部となり、自動ドキュメントのUIに使用されます。
+ * データが無効な場合は、どこで何が不正なデータだったのかを正確に示す、分かりやすい明確なエラーを返します。
+* 受け取ったデータをパラメータ `item` に渡します。
+ * 関数内で `Item` 型として宣言したため、すべての属性とその型について、エディタサポート(補完など)も利用できます。
+* モデル向けの [JSON Schema](https://json-schema.org) 定義を生成します。プロジェクトにとって意味があるなら、他の場所でも好きなように利用できます。
+* それらのスキーマは生成されるOpenAPIスキーマの一部となり、自動ドキュメントの UIs で使用されます。
-## 自動ドキュメント生成
+## 自動ドキュメント { #automatic-docs }
-モデルのJSONスキーマはOpenAPIで生成されたスキーマの一部になり、対話的なAPIドキュメントに表示されます:
+モデルのJSON Schemaは、OpenAPIで生成されたスキーマの一部になり、対話的なAPIドキュメントに表示されます:
-そして、それらが使われる *パスオペレーション* のそれぞれのAPIドキュメントにも表示されます:
+また、それらが必要な各 *path operation* 内のAPIドキュメントでも使用されます:
-## エディターサポート
+## エディタサポート { #editor-support }
-エディターによる型ヒントと補完が関数内で利用できます (Pydanticモデルではなく `dict` を受け取ると、同じサポートは受けられません):
+エディタ上で、関数内のあらゆる場所で型ヒントと補完が得られます(Pydanticモデルの代わりに `dict` を受け取った場合は起きません):
-型によるエラーチェックも可能です:
+不正な型操作に対するエラーチェックも得られます:
-これは偶然ではなく、このデザインに基づいてフレームワークが作られています。
+これは偶然ではなく、フレームワーク全体がその設計を中心に構築されています。
-全てのエディターで機能することを確認するために、実装前の設計時に徹底的にテストしました。
+そして、すべてのエディタで動作することを確実にするために、実装前の設計フェーズで徹底的にテストされました。
-これをサポートするためにPydantic自体にもいくつかの変更がありました。
+これをサポートするために、Pydantic自体にもいくつかの変更が加えられました。
-上記のスクリーンショットはVisual Studio Codeを撮ったものです。
+前述のスクリーンショットは [Visual Studio Code](https://code.visualstudio.com) で撮影されたものです。
-しかし、PyCharmやほとんどのPythonエディタでも同様なエディターサポートを受けられます:
+ただし、[PyCharm](https://www.jetbrains.com/pycharm/) や、他のほとんどのPythonエディタでも同じエディタサポートを得られます:
-!!! tip "豆知識"
- PyCharmエディタを使用している場合は、Pydantic PyCharm Pluginが使用可能です。
+/// tip | 豆知識
- 以下のエディターサポートが強化されます:
+エディタとして [PyCharm](https://www.jetbrains.com/pycharm/) を使用している場合、[Pydantic PyCharm Plugin](https://github.com/koxudaxi/pydantic-pycharm-plugin/) を使用できます。
- * 自動補完
- * 型チェック
- * リファクタリング
- * 検索
- * インスペクション
+以下により、Pydanticモデルに対するエディタサポートが改善されます:
-## モデルの使用
+* auto-completion
+* type checks
+* refactoring
+* searching
+* inspections
-関数内部で、モデルの全ての属性に直接アクセスできます:
+///
-```Python hl_lines="19"
-{!../../../docs_src/body/tutorial002.py!}
-```
+## モデルを使用する { #use-the-model }
+
+関数内では、モデルオブジェクトのすべての属性に直接アクセスできます:
-## リクエストボディ + パスパラメータ
+{* ../../docs_src/body/tutorial002_py310.py *}
+
+## リクエストボディ + パスパラメータ { #request-body-path-parameters }
パスパラメータとリクエストボディを同時に宣言できます。
-**FastAPI** はパスパラメータである関数パラメータは**パスから受け取り**、Pydanticモデルによって宣言された関数パラメータは**リクエストボディから受け取る**ということを認識します。
+**FastAPI** は、パスパラメータに一致する関数パラメータは **パスから取得** し、Pydanticモデルとして宣言された関数パラメータは **リクエストボディから取得** すべきだと認識します。
-```Python hl_lines="15-16"
-{!../../../docs_src/body/tutorial003.py!}
-```
+{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}
-## リクエストボディ + パスパラメータ + クエリパラメータ
-また、**ボディ**と**パス**と**クエリ**のパラメータも同時に宣言できます。
+## リクエストボディ + パス + クエリパラメータ { #request-body-path-query-parameters }
-**FastAPI** はそれぞれを認識し、適切な場所からデータを取得します。
+**body**、**path**、**query** パラメータもすべて同時に宣言できます。
-```Python hl_lines="16"
-{!../../../docs_src/body/tutorial004.py!}
-```
+**FastAPI** はそれぞれを認識し、正しい場所からデータを取得します。
+
+{* ../../docs_src/body/tutorial004_py310.py hl[16] *}
+
+関数パラメータは以下のように認識されます:
+
+* パラメータが **path** でも宣言されている場合、パスパラメータとして使用されます。
+* パラメータが **単数型**(`int`、`float`、`str`、`bool` など)の場合、**query** パラメータとして解釈されます。
+* パラメータが **Pydanticモデル** の型として宣言されている場合、リクエスト **body** として解釈されます。
+
+/// note | 備考
-関数パラメータは以下の様に認識されます:
+FastAPIは、デフォルト値 `= None` があるため、`q` の値が必須ではないことを認識します。
-* パラメータが**パス**で宣言されている場合は、優先的にパスパラメータとして扱われます。
-* パラメータが**単数型** (`int`、`float`、`str`、`bool` など)の場合は**クエリ**パラメータとして解釈されます。
-* パラメータが **Pydantic モデル**型で宣言された場合、リクエスト**ボディ**として解釈されます。
+`str | None` は、値が必須ではないことを判断するためにFastAPIでは使用されません。`= None` というデフォルト値があるため、必須ではないことを認識します。
-!!! note "備考"
- FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。
+しかし、型アノテーションを追加すると、エディタがより良いサポートを提供し、エラーを検出できるようになります。
- `Optional[str]` の`Optional` はFastAPIでは使用されていません(FastAPIは`str`の部分のみ使用します)。しかし、`Optional[str]` はエディタがコードのエラーを見つけるのを助けてくれます。
+///
-## Pydanticを使わない方法
+## Pydanticを使わない方法 { #without-pydantic }
-もしPydanticモデルを使用したくない場合は、**Body**パラメータが利用できます。[Body - Multiple Parameters: Singular values in body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}を確認してください。
+Pydanticモデルを使いたくない場合は、**Body** パラメータも使用できます。[Body - 複数のパラメータ: ボディ内の単一値](body-multiple-params.md#singular-values-in-body) のドキュメントを参照してください。
diff --git a/docs/ja/docs/tutorial/cookie-param-models.md b/docs/ja/docs/tutorial/cookie-param-models.md
new file mode 100644
index 0000000000000..89ae4243889f1
--- /dev/null
+++ b/docs/ja/docs/tutorial/cookie-param-models.md
@@ -0,0 +1,76 @@
+# クッキーパラメータモデル { #cookie-parameter-models }
+
+もし関連する**複数のクッキー**から成るグループがあるなら、それらを宣言するために、**Pydanticモデル**を作成できます。🍪
+
+こうすることで、**複数の場所**で**そのPydanticモデルを再利用**でき、バリデーションやメタデータを、すべてのパラメータに対して一度に宣言できます。😎
+
+/// note | 備考
+
+この機能は、FastAPIのバージョン `0.115.0` からサポートされています。🤓
+
+///
+
+/// tip | 豆知識
+
+これと同じテクニックは `Query` 、 `Cookie` 、 `Header` にも適用できます。 😎
+
+///
+
+## Pydanticモデルを使用したクッキー { #cookies-with-a-pydantic-model }
+
+必要な複数の**クッキー**パラメータを**Pydanticモデル**で宣言し、さらに、パラメータを `Cookie` として宣言しましょう:
+
+{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}
+
+**FastAPI**は、リクエストで受け取った**クッキー**から**それぞれのフィールド**のデータを**抽出**し、定義したPydanticモデルを提供します。
+
+## ドキュメントの確認 { #check-the-docs }
+
+対話的APIドキュメントUI `/docs` で、定義されているクッキーを確認できます:
+
+
+
+
+## ショートカット { #shortcut }
+
+しかし、ここでは`CommonQueryParams`を2回書くというコードの繰り返しが発生していることがわかります:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ 注釈なし
+
+/// tip | 豆知識
+
+可能であれば`Annotated`バージョンを使用することを推奨します。
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+依存関係が、クラス自体のインスタンスを作成するために**FastAPI**が「呼び出す」*特定の*クラスである場合、**FastAPI** はこれらのケースのショートカットを提供しています。
+
+それらの具体的なケースについては以下のようにします:
+
+以下のように書く代わりに:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ 注釈なし
+
+/// tip | 豆知識
+
+可能であれば`Annotated`バージョンを使用することを推奨します。
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+...以下のように書きます:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
+
+////
+
+//// tab | Python 3.10+ 注釈なし
+
+/// tip | 豆知識
+
+可能であれば`Annotated`バージョンを使用することを推奨します。
+
+///
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
+
+パラメータの型として依存関係を宣言し、`Depends()`の中でパラメータを指定せず、`Depends()`をその関数のパラメータの「デフォルト」値(`=`のあとの値)として使用することで、`Depends(CommonQueryParams)`の中でクラス全体を*もう一度*書かなくてもよくなります。
+
+同じ例では以下のようになります:
+
+{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *}
+
+...そして **FastAPI** は何をすべきか知っています。
+
+/// tip | 豆知識
+
+役に立つというよりも、混乱するようであれば無視してください。それをする*必要*はありません。
+
+それは単なるショートカットです。なぜなら **FastAPI** はコードの繰り返しを最小限に抑えることに気を使っているからです。
+
+///
diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
new file mode 100644
index 0000000000000..573ccc1f96c54
--- /dev/null
+++ b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -0,0 +1,69 @@
+# path operation デコレータの依存関係 { #dependencies-in-path-operation-decorators }
+
+場合によっては、*path operation 関数*の中で依存関係の戻り値を実際には必要としないことがあります。
+
+または、依存関係が値を返さない場合もあります。
+
+しかし、それでも実行・解決される必要があります。
+
+そのような場合、`Depends` で *path operation 関数* のパラメータを宣言する代わりに、*path operation デコレータ*に `dependencies` の `list` を追加できます。
+
+## *path operation デコレータ*に`dependencies`を追加 { #add-dependencies-to-the-path-operation-decorator }
+
+*path operation デコレータ*はオプション引数`dependencies`を受け取ります。
+
+それは`Depends()`の`list`であるべきです:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
+
+これらの依存関係は、通常の依存関係と同様に実行・解決されます。しかし、それらの値(何かを返す場合)は*path operation 関数*には渡されません。
+
+/// tip | 豆知識
+
+一部のエディタは、未使用の関数パラメータをチェックしてエラーとして表示します。
+
+これらの`dependencies`を*path operation デコレータ*で使用することで、エディタ/ツールのエラーを回避しつつ、確実に実行されるようにできます。
+
+また、コード内の未使用のパラメータを見た新しい開発者が、それを不要だと思って混乱するのを避ける助けにもなるかもしれません。
+
+///
+
+/// info | 情報
+
+この例では、架空のカスタムヘッダー `X-Key` と `X-Token` を使用しています。
+
+しかし実際のケースでセキュリティを実装する際は、統合された[Security utilities(次の章)](../security/index.md)を使うことで、より多くの利点を得られます。
+
+///
+
+## 依存関係のエラーと戻り値 { #dependencies-errors-and-return-values }
+
+通常使用している依存関係の*関数*と同じものを使用できます。
+
+### 依存関係の要件 { #dependency-requirements }
+
+これらはリクエストの要件(ヘッダーのようなもの)やその他のサブ依存関係を宣言できます:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
+
+### 例外の発生 { #raise-exceptions }
+
+これらの依存関係は、通常の依存関係と同じように例外を`raise`できます:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
+
+### 戻り値 { #return-values }
+
+そして、値を返すことも返さないこともできますが、値は使われません。
+
+つまり、すでにどこかで使っている通常の依存関係(値を返すもの)を再利用でき、値は使われなくても依存関係は実行されます:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
+
+## *path operation*のグループに対する依存関係 { #dependencies-for-a-group-of-path-operations }
+
+後で、より大きなアプリケーションを(おそらく複数ファイルで)構造化する方法([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md))について読むときに、*path operation*のグループに対して単一の`dependencies`パラメータを宣言する方法を学びます。
+
+## グローバル依存関係 { #global-dependencies }
+
+次に、`FastAPI`アプリケーション全体に依存関係を追加して、各*path operation*に適用する方法を見ていきます。
diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md
new file mode 100644
index 0000000000000..83e4f8809858b
--- /dev/null
+++ b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -0,0 +1,288 @@
+# `yield`を持つ依存関係 { #dependencies-with-yield }
+
+FastAPIは、いくつかの終了後の追加のステップを行う依存関係をサポートしています。
+
+これを行うには、`return`の代わりに`yield`を使い、その後に追加のステップ(コード)を書きます。
+
+/// tip | 豆知識
+
+`yield`は必ず依存関係ごとに1回だけ使用するようにしてください。
+
+///
+
+/// note | 技術詳細
+
+以下と一緒に使用できる関数なら何でも有効です:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) または
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+これらは **FastAPI** の依存関係として使用するのに有効です。
+
+実際、FastAPIは内部的にこれら2つのデコレータを使用しています。
+
+///
+
+## `yield`を持つデータベースの依存関係 { #a-database-dependency-with-yield }
+
+例えば、これを使ってデータベースセッションを作成し、終了後にそれを閉じることができます。
+
+レスポンスを作成する前に、`yield`文より前のコード(および`yield`文を含む)が実行されます:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
+
+生成された値は、*path operations*や他の依存関係に注入されるものです:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
+
+`yield`文に続くコードは、レスポンスの後に実行されます:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
+
+/// tip | 豆知識
+
+`async`や通常の関数を使用することができます。
+
+**FastAPI** は、通常の依存関係と同じように、それぞれで正しいことを行います。
+
+///
+
+## `yield`と`try`を持つ依存関係 { #a-dependency-with-yield-and-try }
+
+`yield`を持つ依存関係で`try`ブロックを使用した場合、その依存関係を使用した際にスローされたあらゆる例外を受け取ることになります。
+
+例えば、途中のどこかの時点で、別の依存関係や*path operation*の中で、データベーストランザクションを「ロールバック」したり、その他の例外を作成したりするコードがあった場合、依存関係の中で例外を受け取ることになります。
+
+そのため、依存関係の中にある特定の例外を`except SomeException`で探すことができます。
+
+同様に、`finally`を用いて例外があったかどうかにかかわらず、終了ステップを確実に実行することができます。
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
+
+## `yield`を持つサブ依存関係 { #sub-dependencies-with-yield }
+
+任意の大きさや形のサブ依存関係やサブ依存関係の「ツリー」を持つことができ、その中で`yield`を使用することができます。
+
+**FastAPI** は、`yield`を持つ各依存関係の「終了コード」が正しい順番で実行されていることを確認します。
+
+例えば、`dependency_c`は`dependency_b`に、そして`dependency_b`は`dependency_a`に依存することができます:
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
+
+そして、それらはすべて`yield`を使用することができます。
+
+この場合、`dependency_c`は終了コードを実行するために、`dependency_b`(ここでは`dep_b`という名前)の値がまだ利用可能である必要があります。
+
+そして、`dependency_b`は`dependency_a`(ここでは`dep_a`という名前)の値を終了コードで利用できるようにする必要があります。
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
+
+同様に、`yield`を持つ依存関係と`return`を持つ他の依存関係をいくつか持ち、それらの一部が他の一部に依存するようにもできます。
+
+また、単一の依存関係を持っていて、`yield`を持つ他の依存関係をいくつか必要とすることもできます。
+
+依存関係の組み合わせは自由です。
+
+**FastAPI** は、全てが正しい順序で実行されていることを確認します。
+
+/// note | 技術詳細
+
+これはPythonの[コンテキストマネージャ](https://docs.python.org/3/library/contextlib.html)のおかげで動作します。
+
+**FastAPI** はこれを実現するために内部的に使用しています。
+
+///
+
+## `yield`と`HTTPException`を持つ依存関係 { #dependencies-with-yield-and-httpexception }
+
+`yield`を持つ依存関係を使い、何らかのコードを実行し、その後に`finally`の後で終了コードを実行しようとする`try`ブロックを持てることが分かりました。
+
+また、`except`を使って発生した例外をキャッチし、それに対して何かをすることもできます。
+
+例えば、`HTTPException`のように別の例外を発生させることができます。
+
+/// tip | 豆知識
+
+これはやや高度なテクニックで、ほとんどの場合は本当に必要にはなりません。例えば、*path operation 関数*など、アプリケーションコードの他の場所から(`HTTPException`を含む)例外を発生させられるためです。
+
+ただし必要であれば使えます。 🤓
+
+///
+
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
+
+例外をキャッチして、それに基づいてカスタムレスポンスを作成したい場合は、[カスタム例外ハンドラ](../handling-errors.md#install-custom-exception-handlers)を作成してください。
+
+## `yield`と`except`を持つ依存関係 { #dependencies-with-yield-and-except }
+
+`yield`を持つ依存関係で`except`を使って例外をキャッチし、それを再度raiseしない(または新しい例外をraiseしない)場合、通常のPythonと同じように、FastAPIは例外があったことに気づけません:
+
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
+
+この場合、(`HTTPException`やそれに類するものをraiseしていないため)クライアントには適切に*HTTP 500 Internal Server Error*レスポンスが返りますが、サーバーには**ログが一切残らず**、何がエラーだったのかを示す他の手がかりもありません。 😱
+
+### `yield`と`except`を持つ依存関係では常に`raise`する { #always-raise-in-dependencies-with-yield-and-except }
+
+`yield`を持つ依存関係で例外をキャッチした場合、別の`HTTPException`などをraiseするのでない限り、**元の例外を再raiseすべきです**。
+
+`raise`を使うと同じ例外を再raiseできます:
+
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
+
+これでクライアントは同じ*HTTP 500 Internal Server Error*レスポンスを受け取りますが、サーバーのログにはカスタムの`InternalError`が残ります。 😎
+
+## `yield`を持つ依存関係の実行 { #execution-of-dependencies-with-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,operation: Can raise exceptions, including HTTPException
+ client ->> dep: Start request
+ Note over dep: Run code up to yield
+ opt raise Exception
+ dep -->> handler: Raise Exception
+ handler -->> client: HTTP error response
+ end
+ dep ->> operation: Run dependency, e.g. DB session
+ opt raise
+ operation -->> dep: Raise Exception (e.g. HTTPException)
+ opt handle
+ dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception
+ end
+ handler -->> client: HTTP error response
+ 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 -->> tasks: Handle exceptions in the background task code
+ end
+```
+
+/// info | 情報
+
+**1つのレスポンス** だけがクライアントに送信されます。それはエラーレスポンスの一つかもしれませんし、*path operation*からのレスポンスかもしれません。
+
+いずれかのレスポンスが送信された後、他のレスポンスを送信することはできません。
+
+///
+
+/// tip | 豆知識
+
+*path operation 関数*のコードで例外をraiseした場合、`HTTPException`を含め、それはyieldを持つ依存関係に渡されます。ほとんどの場合、その例外が正しく処理されるように、`yield`を持つ依存関係から同じ例外、または新しい例外を再raiseしたくなるでしょう。
+
+///
+
+## 早期終了と`scope` { #early-exit-and-scope }
+
+通常、`yield`を持つ依存関係の終了コードは、クライアントに**レスポンスが送信された後**に実行されます。
+
+しかし、*path operation 関数*からreturnした後に依存関係を使う必要がないと分かっている場合は、`Depends(scope="function")`を使って、**レスポンスが送信される前**に、*path operation 関数*のreturn後に依存関係を閉じるべきだとFastAPIに伝えられます。
+
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
+
+`Depends()`は、以下のいずれかを取る`scope`パラメータを受け取ります:
+
+* `"function"`: リクエストを処理する*path operation 関数*の前に依存関係を開始し、*path operation 関数*の終了後に依存関係を終了しますが、クライアントにレスポンスが返される**前**に終了します。つまり、依存関係関数は*path operation 関数*の**周囲**で実行されます。
+* `"request"`: リクエストを処理する*path operation 関数*の前に依存関係を開始し(`"function"`を使用する場合と同様)、クライアントにレスポンスが返された**後**に終了します。つまり、依存関係関数は**リクエスト**とレスポンスのサイクルの**周囲**で実行されます。
+
+指定されておらず、依存関係に`yield`がある場合、デフォルトで`scope`は`"request"`になります。
+
+### サブ依存関係の`scope` { #scope-for-sub-dependencies }
+
+`scope="request"`(デフォルト)を持つ依存関係を宣言する場合、どのサブ依存関係も`"request"`の`scope`を持つ必要があります。
+
+しかし、`"function"`の`scope`を持つ依存関係は、`"function"`と`"request"`の`scope`を持つ依存関係を持てます。
+
+これは、いずれの依存関係も、サブ依存関係より前に終了コードを実行できる必要があるためです(終了コードの実行中にサブ依存関係をまだ使う必要がある可能性があるためです)。
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant dep_req as Dep scope="request"
+participant dep_func as Dep scope="function"
+participant operation as Path Operation
+
+ client ->> dep_req: Start request
+ Note over dep_req: Run code up to yield
+ dep_req ->> dep_func: Pass dependency
+ Note over dep_func: Run code up to yield
+ dep_func ->> operation: Run path operation with dependency
+ operation ->> dep_func: Return from path operation
+ Note over dep_func: Run code after yield
+ Note over dep_func: ✅ Dependency closed
+ dep_func ->> client: Send response to client
+ Note over client: Response sent
+ Note over dep_req: Run code after yield
+ Note over dep_req: ✅ Dependency closed
+```
+
+## `yield`、`HTTPException`、`except`、バックグラウンドタスクを持つ依存関係 { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+`yield`を持つ依存関係は、さまざまなユースケースをカバーし、いくつかの問題を修正するために、時間とともに進化してきました。
+
+FastAPIの異なるバージョンで何が変わったのかを知りたい場合は、上級ガイドの[上級の依存関係 - `yield`、`HTTPException`、`except`、バックグラウンドタスクを持つ依存関係](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks)で詳しく読めます。
+## コンテキストマネージャ { #context-managers }
+
+### 「コンテキストマネージャ」とは { #what-are-context-managers }
+
+「コンテキストマネージャ」とは、`with`文の中で使用できるPythonオブジェクトのことです。
+
+例えば、[ファイルを読み込むには`with`を使用することができます](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files):
+
+```Python
+with open("./somefile.txt") as f:
+ contents = f.read()
+ print(contents)
+```
+
+その後の`open("./somefile.txt")`は「コンテキストマネージャ」と呼ばれるオブジェクトを作成します。
+
+`with`ブロックが終了すると、例外があったとしてもファイルを確かに閉じます。
+
+`yield`を持つ依存関係を作成すると、**FastAPI** は内部的にそれをコンテキストマネージャに変換し、他の関連ツールと組み合わせます。
+
+### `yield`を持つ依存関係でのコンテキストマネージャの使用 { #using-context-managers-in-dependencies-with-yield }
+
+/// warning | 注意
+
+これは多かれ少なかれ、「高度な」発想です。
+
+**FastAPI** を使い始めたばかりの方は、とりあえずスキップした方がよいかもしれません。
+
+///
+
+Pythonでは、[以下の2つのメソッドを持つクラスを作成する: `__enter__()`と`__exit__()`](https://docs.python.org/3/reference/datamodel.html#context-managers)ことでコンテキストマネージャを作成することができます。
+
+また、依存関数の中で`with`や`async with`文を使用することによって`yield`を持つ **FastAPI** の依存関係の中でそれらを使用することができます:
+
+{* ../../docs_src/dependencies/tutorial010_py310.py hl[1:9,13] *}
+
+/// tip | 豆知識
+
+コンテキストマネージャを作成するもう一つの方法は次の方法です:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) または
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+これらを使って、関数を単一の`yield`でデコレートすることができます。
+
+これは **FastAPI** が内部的に`yield`を持つ依存関係のために使用しているものです。
+
+しかし、FastAPIの依存関係にデコレータを使う必要はありません(そして使うべきではありません)。
+
+FastAPIが内部的にやってくれます。
+
+///
diff --git a/docs/ja/docs/tutorial/dependencies/global-dependencies.md b/docs/ja/docs/tutorial/dependencies/global-dependencies.md
new file mode 100644
index 0000000000000..35a77a5f76b03
--- /dev/null
+++ b/docs/ja/docs/tutorial/dependencies/global-dependencies.md
@@ -0,0 +1,15 @@
+# グローバルな依存関係 { #global-dependencies }
+
+アプリケーションの種類によっては、アプリ全体に依存関係を追加したい場合があります。
+
+[`dependencies` を path operation のデコレータに追加](dependencies-in-path-operation-decorators.md)できるのと同様に、`FastAPI` アプリケーション自体にも追加できます。
+
+その場合、アプリケーション内のすべての path operation に適用されます:
+
+{* ../../docs_src/dependencies/tutorial012_an_py310.py hl[17] *}
+
+また、[`dependencies` を path operation のデコレータに追加](dependencies-in-path-operation-decorators.md)する節で説明した考え方はすべて引き続き当てはまりますが、この場合はアプリ内のすべての path operation に対して適用されます。
+
+## path operation のグループに対する依存関係 { #dependencies-for-groups-of-path-operations }
+
+後で、複数ファイルを含む大規模アプリケーションの構成方法([大規模アプリケーション - 複数ファイル](../../tutorial/bigger-applications.md))を読むと、path operation のグループに対して 1 つの `dependencies` パラメータを宣言する方法を学びます。
diff --git a/docs/ja/docs/tutorial/dependencies/index.md b/docs/ja/docs/tutorial/dependencies/index.md
new file mode 100644
index 0000000000000..a3cf3e26b5a7e
--- /dev/null
+++ b/docs/ja/docs/tutorial/dependencies/index.md
@@ -0,0 +1,250 @@
+# 依存関係 { #dependencies }
+
+**FastAPI** は非常に強力でありながら直感的な **依存性注入** システムを持っています。
+
+それは非常にシンプルに使用できるように設計されており、開発者が他のコンポーネント **FastAPI** と統合するのが非常に簡単になるように設計されています。
+
+## 「Dependency Injection」とは { #what-is-dependency-injection }
+
+**「Dependency Injection」** とは、プログラミングにおいて、コード(この場合は、*path operation 関数*)が動作したり使用したりするために必要なもの(「依存関係」)を宣言する方法があることを意味します:
+
+そして、そのシステム(この場合は、**FastAPI**)は、必要な依存関係をコードに提供するために必要なことは何でも行います(依存関係を「注入」します)。
+
+これは以下のようなことが必要な時にとても便利です:
+
+* ロジックを共有している。(同じコードロジックを何度も繰り返している)。
+* データベース接続を共有する。
+* セキュリティ、認証、ロール要件などを強制する。
+* そのほかにも多くのこと...
+
+これらすべてを、コードの繰り返しを最小限に抑えながら行います。
+
+## 最初のステップ { #first-steps }
+
+非常にシンプルな例を見てみましょう。あまりにもシンプルなので、今のところはあまり参考にならないでしょう。
+
+しかし、この方法では **Dependency Injection** システムがどのように機能するかに焦点を当てることができます。
+
+### 依存関係(「dependable」)の作成 { #create-a-dependency-or-dependable }
+
+まずは依存関係に注目してみましょう。
+
+以下のように、*path operation 関数*と同じパラメータを全て取ることができる関数にすぎません:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}
+
+これだけです。
+
+**2行**。
+
+そして、それはすべての*path operation 関数*が持っているのと同じ形と構造を持っています。
+
+「デコレータ」を含まない(`@app.get("/some-path")`を含まない)*path operation 関数*と考えることもできます。
+
+そして何でも返すことができます。
+
+この場合、この依存関係は以下を期待しています:
+
+* オプショナルのクエリパラメータ`q`は`str`です。
+* オプショナルのクエリパラメータ`skip`は`int`で、デフォルトは`0`です。
+* オプショナルのクエリパラメータ`limit`は`int`で、デフォルトは`100`です。
+
+そして、これらの値を含む`dict`を返します。
+
+/// info | 情報
+
+FastAPI はバージョン 0.95.0 で `Annotated` のサポートを追加し(そして推奨し始めました)。
+
+古いバージョンを使用している場合、`Annotated` を使おうとするとエラーになります。
+
+`Annotated` を使用する前に、少なくとも 0.95.1 まで [FastAPI のバージョンをアップグレード](../../deployment/versions.md#upgrading-the-fastapi-versions) してください。
+
+///
+
+### `Depends`のインポート { #import-depends }
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}
+
+### 「dependant」での依存関係の宣言 { #declare-the-dependency-in-the-dependant }
+
+*path operation 関数*のパラメータに`Body`や`Query`などを使用するのと同じように、新しいパラメータに`Depends`を使用することができます:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}
+
+関数のパラメータに`Depends`を使用するのは`Body`や`Query`などと同じですが、`Depends`の動作は少し異なります。
+
+`Depends`は1つのパラメータしか与えられません。
+
+このパラメータは関数のようなものである必要があります。
+
+直接**呼び出しません**(末尾に括弧を付けません)。`Depends()` のパラメータとして渡すだけです。
+
+そして、その関数は、*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 operation*のための呼び出しを行います。
+
+/// check | 確認
+
+特別なクラスを作成してどこかで **FastAPI** に渡して「登録」する必要はないことに注意してください。
+
+`Depends`を渡すだけで、**FastAPI** が残りの処理をしてくれます。
+
+///
+
+## `Annotated` 依存関係の共有 { #share-annotated-dependencies }
+
+上の例では、ほんの少し **コードの重複** があることがわかります。
+
+`common_parameters()` 依存関係を使う必要があるときは、型アノテーションと `Depends()` を含むパラメータ全体を書く必要があります:
+
+```Python
+commons: Annotated[dict, Depends(common_parameters)]
+```
+
+しかし、`Annotated` を使用しているので、その `Annotated` 値を変数に格納して複数箇所で使えます:
+
+{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}
+
+/// tip | 豆知識
+
+これはただの標準 Python で、「type alias」と呼ばれ、**FastAPI** 固有のものではありません。
+
+しかし **FastAPI** は `Annotated` を含む Python 標準に基づいているため、このテクニックをコードで使えます。 😎
+
+///
+
+依存関係は期待どおりに動作し続け、**一番良い点** は **型情報が保持される** ことです。つまり、エディタは **自動補完**、**インラインエラー** などを提供し続けられます。`mypy` のような他のツールでも同様です。
+
+これは **大規模なコードベース** で、**同じ依存関係** を **多くの *path operation*** で何度も使う場合に特に役立ちます。
+
+## `async`にするかどうか { #to-async-or-not-to-async }
+
+依存関係は **FastAPI**(*path operation 関数*と同じ)からも呼び出されるため、関数を定義する際にも同じルールが適用されます。
+
+`async def`や通常の`def`を使用することができます。
+
+また、通常の`def`*path operation 関数*の中に`async def`を入れて依存関係を宣言したり、`async def`*path operation 関数*の中に`def`を入れて依存関係を宣言したりすることなどができます。
+
+それは重要ではありません。**FastAPI** は何をすべきかを知っています。
+
+/// note | 備考
+
+わからない場合は、ドキュメントの[Async: *「急いでいますか?」*](../../async.md#in-a-hurry)の中の`async`と`await`についてのセクションを確認してください。
+
+///
+
+## OpenAPIとの統合 { #integrated-with-openapi }
+
+依存関係(およびサブ依存関係)のすべてのリクエスト宣言、検証、および要件は、同じOpenAPIスキーマに統合されます。
+
+つまり、対話型ドキュメントにはこれらの依存関係から得られる全ての情報も含まれているということです:
+
+
+
+## 簡単な使い方 { #simple-usage }
+
+見てみると、*path*と*operation*が一致した時に*path operation 関数*が宣言されていて、**FastAPI** が正しいパラメータで関数を呼び出してリクエストからデータを抽出する処理をしています。
+
+実は、すべての(あるいはほとんどの)Webフレームワークは、このように動作します。
+
+これらの関数を直接呼び出すことはありません。これらの関数はフレームワーク(この場合は、**FastAPI**)によって呼び出されます。
+
+Dependency Injection システムでは、**FastAPI** に*path operation 関数*もまた、*path operation 関数*の前に実行されるべき他の何かに「依存」していることを伝えることができ、**FastAPI** がそれを実行し、結果を「注入」することを引き受けます。
+
+他にも、「dependency injection」と同じような考えの一般的な用語があります:
+
+* resources
+* providers
+* services
+* injectables
+* components
+
+## **FastAPI** プラグイン { #fastapi-plug-ins }
+
+統合や「プラグイン」は **Dependency Injection** システムを使って構築することができます。しかし、実際には、**「プラグイン」を作成する必要はありません**。依存関係を使用することで、無限の数の統合やインタラクションを宣言することができ、それが*path operation 関数*で利用可能になるからです。
+
+依存関係は非常にシンプルで直感的な方法で作成することができ、必要なPythonパッケージをインポートするだけで、*文字通り*数行のコードでAPI関数と統合することができます。
+
+次の章では、リレーショナルデータベースやNoSQLデータベース、セキュリティなどについて、その例を見ていきます。
+
+## **FastAPI** 互換性 { #fastapi-compatibility }
+
+dependency injection システムがシンプルなので、**FastAPI** は以下のようなものと互換性があります:
+
+* すべてのリレーショナルデータベース
+* NoSQLデータベース
+* 外部パッケージ
+* 外部API
+* 認証・認可システム
+* API利用状況監視システム
+* レスポンスデータ注入システム
+* など。
+
+## シンプルでパワフル { #simple-and-powerful }
+
+階層的な dependency injection システムは、定義や使用方法が非常にシンプルであるにもかかわらず、非常に強力なものとなっています。
+
+依存関係が、さらに依存関係を定義することもできます。
+
+最終的には、依存関係の階層ツリーが構築され、**Dependency Injection**システムが、これらの依存関係(およびそのサブ依存関係)をすべて解決し、各ステップで結果を提供(注入)します。
+
+例えば、4つのAPIエンドポイント(*path operation*)があるとします:
+
+* `/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** との統合 { #integrated-with-openapi_1 }
+
+これら全ての依存関係は、要件を宣言すると同時に、*path operation*にパラメータやバリデーションを追加します。
+
+**FastAPI** はそれをすべてOpenAPIスキーマに追加して、対話型のドキュメントシステムに表示されるようにします。
diff --git a/docs/ja/docs/tutorial/dependencies/sub-dependencies.md b/docs/ja/docs/tutorial/dependencies/sub-dependencies.md
new file mode 100644
index 0000000000000..fa27781f954f8
--- /dev/null
+++ b/docs/ja/docs/tutorial/dependencies/sub-dependencies.md
@@ -0,0 +1,105 @@
+# サブ依存関係 { #sub-dependencies }
+
+**サブ依存関係** を持つ依存関係を作成することができます。
+
+それらは必要なだけ **深く** することができます。
+
+**FastAPI** はそれらを解決してくれます。
+
+## 最初の依存関係「依存可能なもの」 { #first-dependency-dependable }
+
+以下のような最初の依存関係(「依存可能なもの」)を作成することができます:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}
+
+これはオプショナルのクエリパラメータ`q`を`str`として宣言し、それを返すだけです。
+
+これは非常にシンプルです(あまり便利ではありません)が、サブ依存関係がどのように機能するかに焦点を当てるのに役立ちます。
+
+## 第二の依存関係 「依存可能なもの」と「依存」 { #second-dependency-dependable-and-dependant }
+
+そして、別の依存関数(「依存可能なもの」)を作成して、同時にそれ自身の依存関係を宣言することができます(つまりそれ自身も「依存」です):
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}
+
+宣言されたパラメータに注目してみましょう:
+
+* この関数は依存関係(「依存可能なもの」)そのものであるにもかかわらず、別の依存関係を宣言しています(何か他のものに「依存」しています)。
+ * これは`query_extractor`に依存しており、それが返す値をパラメータ`q`に代入します。
+* また、オプショナルの`last_query`クッキーを`str`として宣言します。
+ * ユーザーがクエリ`q`を提供しなかった場合、クッキーに保存していた最後に使用したクエリを使用します。
+
+## 依存関係の使用 { #use-the-dependency }
+
+以下のように依存関係を使用することができます:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}
+
+/// 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
+```
+
+## 同じ依存関係の複数回の使用 { #using-the-same-dependency-multiple-times }
+
+依存関係の1つが同じ*path operation*に対して複数回宣言されている場合、例えば、複数の依存関係が共通のサブ依存関係を持っている場合、**FastAPI** はリクエストごとに1回だけそのサブ依存関係を呼び出します。
+
+そして、返された値を「キャッシュ」に保存し、同じリクエストに対して依存関係を何度も呼び出す代わりに、その特定のリクエストでそれを必要とする全ての「依存」に渡すことになります。
+
+高度なシナリオでは、「キャッシュされた」値を使うのではなく、同じリクエストの各ステップ(おそらく複数回)で依存関係を呼び出す必要があることがわかっている場合、`Depends`を使用する際に、`use_cache=False`というパラメータを設定することができます:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+//// tab | Python 3.10+ 非Annotated
+
+/// tip | 豆知識
+
+可能であれば`Annotated`版を使うことを推奨します。
+
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+## まとめ { #recap }
+
+ここで使われている派手な言葉は別にして、**Dependency Injection** システムは非常にシンプルです。
+
+*path operation 関数*と同じように見えるただの関数です。
+
+しかし、それでも非常に強力で、任意の深くネストされた依存関係「グラフ」(ツリー)を宣言することができます。
+
+/// tip | 豆知識
+
+これらの単純な例では、全てが役に立つとは言えないかもしれません。
+
+しかし、**security** についての章で、それがどれほど有用であるかがわかるでしょう。
+
+そして、あなたを救うコードの量もみることになるでしょう。
+
+///
diff --git a/docs/ja/docs/tutorial/encoder.md b/docs/ja/docs/tutorial/encoder.md
new file mode 100644
index 0000000000000..e4745faf7cdcb
--- /dev/null
+++ b/docs/ja/docs/tutorial/encoder.md
@@ -0,0 +1,35 @@
+# JSON互換エンコーダ { #json-compatible-encoder }
+
+データ型(Pydanticモデルのような)をJSONと互換性のあるもの(`dict`や`list`など)に変換する必要があるケースがあります。
+
+例えば、データベースに保存する必要がある場合です。
+
+そのために、**FastAPI** は`jsonable_encoder()`関数を提供しています。
+
+## `jsonable_encoder`の使用 { #using-the-jsonable-encoder }
+
+JSON互換のデータのみを受信するデータベース`fake_db`があるとしましょう。
+
+例えば、`datetime`オブジェクトはJSONと互換性がないので、受け取られません。
+
+そのため、`datetime`オブジェクトは[ISO形式](https://en.wikipedia.org/wiki/ISO_8601)のデータを含む`str`に変換されなければなりません。
+
+同様に、このデータベースはPydanticモデル(属性を持つオブジェクト)を受け取らず、`dict`だけを受け取ります。
+
+そのために`jsonable_encoder`を使用することができます。
+
+Pydanticモデルのようなオブジェクトを受け取り、JSON互換版を返します:
+
+{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *}
+
+この例では、Pydanticモデルを`dict`に、`datetime`を`str`に変換します。
+
+呼び出した結果は、Pythonの標準の[`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps)でエンコードできるものです。
+
+これはJSON形式のデータを含む大きな`str`を(文字列として)返しません。JSONと互換性のある値とサブの値を持つPython標準のデータ構造(例:`dict`)を返します。
+
+/// note | 備考
+
+`jsonable_encoder`は実際には **FastAPI** が内部的にデータを変換するために使用します。しかしこれは他の多くのシナリオで有用です。
+
+///
diff --git a/docs/ja/docs/tutorial/extra-data-types.md b/docs/ja/docs/tutorial/extra-data-types.md
new file mode 100644
index 0000000000000..1bbfeb71e31b5
--- /dev/null
+++ b/docs/ja/docs/tutorial/extra-data-types.md
@@ -0,0 +1,62 @@
+# 追加データ型 { #extra-data-types }
+
+今まで、以下のような一般的なデータ型を使用してきました:
+
+* `int`
+* `float`
+* `str`
+* `bool`
+
+しかし、より複雑なデータ型を使用することもできます。
+
+そして、今まで見てきたのと同じ機能を持つことになります:
+
+* 素晴らしいエディタのサポート。
+* 受信したリクエストからのデータ変換。
+* レスポンスデータのデータ変換。
+* データの検証。
+* 自動注釈と文書化。
+
+## 他のデータ型 { #other-data-types }
+
+ここでは、使用できる追加のデータ型のいくつかを紹介します:
+
+* `UUID`:
+ * 多くのデータベースやシステムで共通のIDとして使用される、標準的な「ユニバーサルにユニークな識別子」です。
+ * リクエストとレスポンスでは`str`として表現されます。
+* `datetime.datetime`:
+ * Pythonの`datetime.datetime`です。
+ * リクエストとレスポンスはISO 8601形式の`str`で表現されます(例: `2008-09-15T15:53:00+05:00`)。
+* `datetime.date`:
+ * Python `datetime.date`。
+ * リクエストとレスポンスはISO 8601形式の`str`で表現されます(例: `2008-09-15`)。
+* `datetime.time`:
+ * Pythonの`datetime.time`。
+ * リクエストとレスポンスはISO 8601形式の`str`で表現されます(例: `14:23:55.003`)。
+* `datetime.timedelta`:
+ * Pythonの`datetime.timedelta`です。
+ * リクエストとレスポンスでは合計秒数の`float`で表現されます。
+ * Pydanticでは「ISO 8601 time diff encoding」として表現することも可能です。[詳細はドキュメントを参照してください](https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers)。
+* `frozenset`:
+ * リクエストとレスポンスでは`set`と同じように扱われます:
+ * リクエストでは、リストが読み込まれ、重複を排除して`set`に変換されます。
+ * レスポンスでは`set`が`list`に変換されます。
+ * 生成されたスキーマは`set`の値が一意であることを指定します(JSON Schemaの`uniqueItems`を使用します)。
+* `bytes`:
+ * Pythonの標準的な`bytes`です。
+ * リクエストとレスポンスでは`str`として扱われます。
+ * 生成されたスキーマは`str`で`binary`の「フォーマット」を持つことを指定します。
+* `Decimal`:
+ * Pythonの標準的な`Decimal`です。
+ * リクエストとレスポンスでは`float`と同じように扱われます。
+* 有効なPydanticのデータ型はここで確認できます: [Pydantic のデータ型](https://docs.pydantic.dev/latest/usage/types/types/)。
+
+## 例 { #example }
+
+ここでは、上記の型のいくつかを使用したパラメータを持つ*path operation*の例を示します。
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *}
+
+関数内のパラメータは自然なデータ型を持っていることに注意してください。そして、例えば、以下のように通常の日付操作を行うことができます:
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *}
diff --git a/docs/ja/docs/tutorial/extra-models.md b/docs/ja/docs/tutorial/extra-models.md
new file mode 100644
index 0000000000000..20883068c2648
--- /dev/null
+++ b/docs/ja/docs/tutorial/extra-models.md
@@ -0,0 +1,211 @@
+# 追加のモデル { #extra-models }
+
+先ほどの例に続き、複数の関連モデルを持つことは一般的です。
+
+これはユーザーモデルの場合は特にそうです。なぜなら:
+
+* **入力モデル** にはパスワードが必要です。
+* **出力モデル**はパスワードをもつべきではありません。
+* **データベースモデル**はおそらくハッシュ化されたパスワードが必要になるでしょう。
+
+/// danger | 警告
+
+ユーザーの平文のパスワードは絶対に保存しないでください。常に検証できる「安全なハッシュ」を保存してください。
+
+知らない方は、[セキュリティの章](security/simple-oauth2.md#password-hashing)で「パスワードハッシュ」とは何かを学ぶことができます。
+
+///
+
+## 複数のモデル { #multiple-models }
+
+ここでは、パスワードフィールドをもつモデルがどのように見えるのか、また、どこで使われるのか、大まかなイメージを紹介します:
+
+{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}
+
+### `**user_in.model_dump()` について { #about-user-in-model-dump }
+
+#### Pydanticの`.model_dump()` { #pydantics-model-dump }
+
+`user_in`は`UserIn`クラスのPydanticモデルです。
+
+Pydanticモデルには、モデルのデータを含む`dict`を返す`.model_dump()`メソッドがあります。
+
+そこで、以下のようなPydanticオブジェクト`user_in`を作成すると:
+
+```Python
+user_in = UserIn(username="john", password="secret", email="john.doe@example.com")
+```
+
+そして呼び出すと:
+
+```Python
+user_dict = user_in.model_dump()
+```
+
+これで変数`user_dict`のデータを持つ`dict`ができました。(これはPydanticモデルのオブジェクトの代わりに`dict`です)。
+
+そして呼び出すと:
+
+```Python
+print(user_dict)
+```
+
+以下のようなPythonの`dict`を得ることができます:
+
+```Python
+{
+ 'username': 'john',
+ 'password': 'secret',
+ 'email': 'john.doe@example.com',
+ 'full_name': None,
+}
+```
+
+#### `dict`の展開 { #unpacking-a-dict }
+
+`user_dict`のような`dict`を受け取り、それを`**user_dict`を持つ関数(またはクラス)に渡すと、Pythonはそれを「展開」します。これは`user_dict`のキーと値を直接キー・バリューの引数として渡します。
+
+そこで上述の`user_dict`の続きを以下のように書くと:
+
+```Python
+UserInDB(**user_dict)
+```
+
+以下と同等の結果になります:
+
+```Python
+UserInDB(
+ username="john",
+ password="secret",
+ email="john.doe@example.com",
+ 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モデル { #a-pydantic-model-from-the-contents-of-another }
+
+上述の例では`user_in.model_dump()`から`user_dict`をこのコードのように取得していますが:
+
+```Python
+user_dict = user_in.model_dump()
+UserInDB(**user_dict)
+```
+
+これは以下と同等です:
+
+```Python
+UserInDB(**user_in.model_dump())
+```
+
+...なぜなら`user_in.model_dump()`は`dict`であり、`**`を付与して`UserInDB`を渡してPythonに「展開」させているからです。
+
+そこで、別のPydanticモデルのデータからPydanticモデルを取得します。
+
+#### `dict`の展開と追加キーワード { #unpacking-a-dict-and-extra-keywords }
+
+そして、追加のキーワード引数`hashed_password=hashed_password`を以下のように追加すると:
+
+```Python
+UserInDB(**user_in.model_dump(), 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 | 注意
+
+追加のサポート関数`fake_password_hasher`と`fake_save_user`は、データの可能な流れをデモするだけであり、もちろん本当のセキュリティを提供しているわけではありません。
+
+///
+
+## 重複の削減 { #reduce-duplication }
+
+コードの重複を減らすことは、**FastAPI**の中核的なアイデアの1つです。
+
+コードの重複が増えると、バグやセキュリティの問題、コードの非同期化問題(ある場所では更新しても他の場所では更新されない場合)などが発生する可能性が高くなります。
+
+そして、これらのモデルは全てのデータを共有し、属性名や型を重複させています。
+
+もっと良い方法があります。
+
+他のモデルのベースとなる`UserBase`モデルを宣言することができます。そして、そのモデルの属性(型宣言、検証など)を継承するサブクラスを作ることができます。
+
+データの変換、検証、文書化などはすべて通常通りに動作します。
+
+このようにして、モデル間の違いだけを宣言することができます(平文の`password`、`hashed_password`、パスワードなし):
+
+{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}
+
+## `Union` または `anyOf` { #union-or-anyof }
+
+レスポンスを2つ以上の型の`Union`として宣言できます。つまり、そのレスポンスはそれらのいずれかになります。
+
+OpenAPIでは`anyOf`で定義されます。
+
+そのためには、標準的なPythonの型ヒント[`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union)を使用します:
+
+/// note | 備考
+
+[`Union`](https://docs.pydantic.dev/latest/concepts/types/#unions)を定義する場合は、最も具体的な型を先に、その後により具体性の低い型を含めてください。以下の例では、より具体的な`PlaneItem`が`Union[PlaneItem, CarItem]`内で`CarItem`より前に来ています。
+
+///
+
+{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}
+
+### Python 3.10の`Union` { #union-in-python-3-10 }
+
+この例では、引数`response_model`の値として`Union[PlaneItem, CarItem]`を渡しています。
+
+**型アノテーション**に書くのではなく、**引数の値**として渡しているため、Python 3.10でも`Union`を使う必要があります。
+
+型アノテーションであれば、次のように縦棒を使用できました:
+
+```Python
+some_variable: PlaneItem | CarItem
+```
+
+しかし、これを代入で`response_model=PlaneItem | CarItem`のように書くと、Pythonはそれを型アノテーションとして解釈するのではなく、`PlaneItem`と`CarItem`の間で**無効な操作**を行おうとしてしまうため、エラーになります。
+
+## モデルのリスト { #list-of-models }
+
+同じように、オブジェクトのリストのレスポンスを宣言できます。
+
+そのためには、標準のPythonの`list`を使用します:
+
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
+
+## 任意の`dict`によるレスポンス { #response-with-arbitrary-dict }
+
+また、Pydanticモデルを使用せずに、キーと値の型だけを定義した任意の`dict`を使ってレスポンスを宣言することもできます。
+
+これは、有効なフィールド・属性名(Pydanticモデルに必要なもの)を事前に知らない場合に便利です。
+
+この場合、`dict`を使用できます:
+
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
+
+## まとめ { #recap }
+
+複数のPydanticモデルを使用し、ケースごとに自由に継承します。
+
+エンティティが異なる「状態」を持たなければならない場合は、エンティティごとに単一のデータモデルを持つ必要はありません。`password`、`password_hash`、パスワードなしを含む状態を持つユーザー「エンティティ」の場合と同様です。
diff --git a/docs/ja/docs/tutorial/first-steps.md b/docs/ja/docs/tutorial/first-steps.md
index c696f7d489e94..26cb49159c09b 100644
--- a/docs/ja/docs/tutorial/first-steps.md
+++ b/docs/ja/docs/tutorial/first-steps.md
@@ -1,10 +1,8 @@
-# 最初のステップ
+# 最初のステップ { #first-steps }
最もシンプルなFastAPIファイルは以下のようになります:
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
これを`main.py`にコピーします。
@@ -13,23 +11,42 @@
get オペレーション
+* get オペレーション
+
+/// info | `@decorator` 情報
-!!! info "`@decorator` について"
- Pythonにおける`@something`シンタックスはデコレータと呼ばれます。
+Pythonにおける`@something`シンタックスはデコレータと呼ばれます。
- 「デコレータ」は関数の上に置きます。かわいらしい装飾的な帽子のようです(この用語の由来はそこにあると思います)。
+「デコレータ」は関数の上に置きます。かわいらしい装飾的な帽子のようです(この用語の由来はそこにあると思います)。
- 「デコレータ」は直下の関数を受け取り、それを使って何かを行います。
+「デコレータ」は直下の関数を受け取り、それを使って何かを行います。
- 私たちの場合、このデコレーターは直下の関数が**オペレーション** `get`を使用した**パス**` / `に対応することを**FastAPI** に通知します。
+私たちの場合、このデコレーターは直下の関数が**オペレーション** `get`を使用した**パス** `/`に対応することを**FastAPI** に通知します。
- これが「*パスオペレーションデコレータ*」です。
+これが「*path operation デコレータ*」です。
+
+///
他のオペレーションも使用できます:
@@ -272,26 +348,27 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを
* `@app.patch()`
* `@app.trace()`
-!!! tip "豆知識"
- 各オペレーション (HTTPメソッド)は自由に使用できます。
+/// tip | 豆知識
+
+各オペレーション (HTTPメソッド)は自由に使用できます。
+
+**FastAPI**は特定の意味づけを強制しません。
- **FastAPI**は特定の意味づけを強制しません。
+ここでの情報は、要件ではなくガイドラインとして提示されます。
- ここでの情報は、要件ではなくガイドラインとして提示されます。
+例えば、GraphQLを使用する場合、通常は`POST`オペレーションのみを使用してすべてのアクションを実行します。
- 例えば、GraphQLを使用する場合、通常は`POST`オペレーションのみを使用してすべてのアクションを実行します。
+///
-### Step 4: **パスオペレーション**を定義
+### Step 4: **path operation 関数**を定義 { #step-4-define-the-path-operation-function }
-以下は「**パスオペレーション関数**」です:
+以下は「**path operation 関数**」です:
* **パス**: は`/`です。
* **オペレーション**: は`get`です。
* **関数**: 「デコレータ」の直下にある関数 (`@app.get("/")`の直下) です。
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
これは、Pythonの関数です。
@@ -303,29 +380,49 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを
`async def`の代わりに通常の関数として定義することもできます:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
-!!! note "備考"
- 違いが分からない場合は、[Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}を確認してください。
+/// note | 備考
-### Step 5: コンテンツの返信
+違いが分からない場合は、[Async: *「急いでいますか?」*](../async.md#in-a-hurry)を確認してください。
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+///
+
+### Step 5: コンテンツの返信 { #step-5-return-the-content }
-`dict`、`list`、`str`、`int`などを返すことができます。
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
+
+`dict`、`list`、`str`、`int`などの単一の値を返すことができます。
Pydanticモデルを返すこともできます(後で詳しく説明します)。
JSONに自動的に変換されるオブジェクトやモデルは他にもたくさんあります(ORMなど)。 お気に入りのものを使ってみてください。すでにサポートされている可能性が高いです。
-## まとめ
+### Step 6: デプロイする { #step-6-deploy-it }
+
+**[FastAPI Cloud](https://fastapicloud.com)**に1コマンドでアプリをデプロイします: `fastapi deploy`. 🎉
+
+#### FastAPI Cloudについて { #about-fastapi-cloud }
+
+**[FastAPI Cloud](https://fastapicloud.com)**は、**FastAPI**の作者とそのチームによって開発されています。
+
+最小限の労力でAPIの**構築**、**デプロイ**、**アクセス**を行うプロセスを合理化します。
+
+FastAPIでアプリを構築するのと同じ**開発体験**を、クラウドへの**デプロイ**にもたらします。 🎉
+
+FastAPI Cloudは、*FastAPI and friends*のオープンソースプロジェクトに対する主要スポンサーであり、資金提供元です。 ✨
+
+#### 他のクラウドプロバイダにデプロイする { #deploy-to-other-cloud-providers }
+
+FastAPIはオープンソースで、標準に基づいています。選択した任意のクラウドプロバイダにFastAPIアプリをデプロイできます。
+
+クラウドプロバイダのガイドに従って、FastAPIアプリをデプロイしてください。 🤓
+
+## まとめ { #recap }
-* `FastAPI`をインポート
-* `app`インスタンスを生成
-* **パスオペレーションデコレータ**を記述 (`@app.get("/")`)
-* **パスオペレーション関数**を定義 (上記の`def root(): ...`のように)
-* 開発サーバーを起動 (`uvicorn main:app --reload`)
+* `FastAPI`をインポートします。
+* `app`インスタンスを生成します。
+* `@app.get("/")`のようなデコレータを使用して、**path operation デコレータ**を記述します。
+* **path operation 関数**を定義します。例: `def root(): ...`。
+* `fastapi dev`コマンドで開発サーバーを起動します。
+* 任意で`fastapi deploy`を使ってアプリをデプロイします。
diff --git a/docs/ja/docs/tutorial/handling-errors.md b/docs/ja/docs/tutorial/handling-errors.md
new file mode 100644
index 0000000000000..8d0190cb0b740
--- /dev/null
+++ b/docs/ja/docs/tutorial/handling-errors.md
@@ -0,0 +1,244 @@
+# エラーハンドリング { #handling-errors }
+
+APIを使用しているクライアントにエラーを通知する必要がある状況はたくさんあります。
+
+このクライアントは、フロントエンドを持つブラウザ、誰かのコード、IoTデバイスなどが考えられます。
+
+クライアントに以下のようなことを伝える必要があるかもしれません:
+
+* クライアントにはその操作のための十分な権限がありません。
+* クライアントはそのリソースにアクセスできません。
+* クライアントがアクセスしようとしていた項目が存在しません。
+* など
+
+これらの場合、通常は **400**(400から499)の範囲内の **HTTPステータスコード** を返すことになります。
+
+これは200のHTTPステータスコード(200から299)に似ています。これらの「200」ステータスコードは、何らかの形でリクエスト「成功」であったことを意味します。
+
+400の範囲にあるステータスコードは、クライアントからのエラーがあったことを意味します。
+
+**"404 Not Found"** のエラー(およびジョーク)を覚えていますか?
+
+## `HTTPException`の使用 { #use-httpexception }
+
+HTTPレスポンスをエラーでクライアントに返すには、`HTTPException`を使用します。
+
+### `HTTPException`のインポート { #import-httpexception }
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
+
+### コード内での`HTTPException`の発生 { #raise-an-httpexception-in-your-code }
+
+`HTTPException`は通常のPythonの例外であり、APIに関連するデータを追加したものです。
+
+Pythonの例外なので、`return`ではなく、`raise`です。
+
+これはまた、*path operation関数*の内部で呼び出しているユーティリティ関数の内部から`HTTPException`を発生させた場合、*path operation関数*の残りのコードは実行されず、そのリクエストを直ちに終了させ、`HTTPException`からのHTTPエラーをクライアントに送信することを意味します。
+
+値を返す`return`よりも例外を発生させることの利点は、「依存関係とセキュリティ」のセクションでより明確になります。
+
+この例では、クライアントが存在しないIDでアイテムを要求した場合、`404`のステータスコードを持つ例外を発生させます:
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
+
+### レスポンス結果 { #the-resulting-response }
+
+クライアントが`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`パラメータとして渡すことができます。
+
+`dict`や`list`などを渡すことができます。
+
+これらは **FastAPI** によって自動的に処理され、JSONに変換されます。
+
+///
+
+## カスタムヘッダーの追加 { #add-custom-headers }
+
+例えば、いくつかのタイプのセキュリティのために、HTTPエラーにカスタムヘッダを追加できると便利な状況がいくつかあります。
+
+おそらくコードの中で直接使用する必要はないでしょう。
+
+しかし、高度なシナリオのために必要な場合には、カスタムヘッダーを追加することができます:
+
+{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
+
+## カスタム例外ハンドラのインストール { #install-custom-exception-handlers }
+
+カスタム例外ハンドラは[Starletteと同じ例外ユーティリティ](https://www.starlette.dev/exceptions/)を使用して追加することができます。
+
+あなた(または使用しているライブラリ)が`raise`するかもしれないカスタム例外`UnicornException`があるとしましょう。
+
+そして、この例外をFastAPIでグローバルに処理したいと思います。
+
+カスタム例外ハンドラを`@app.exception_handler()`で追加することができます:
+
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
+
+ここで、`/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`と同じです。
+
+///
+
+## デフォルトの例外ハンドラのオーバーライド { #override-the-default-exception-handlers }
+
+**FastAPI** にはいくつかのデフォルトの例外ハンドラがあります。
+
+これらのハンドラは、`HTTPException`を`raise`させた場合や、リクエストに無効なデータが含まれている場合にデフォルトのJSONレスポンスを返す役割を担っています。
+
+これらの例外ハンドラを独自のものでオーバーライドすることができます。
+
+### リクエスト検証の例外のオーバーライド { #override-request-validation-exceptions }
+
+リクエストに無効なデータが含まれている場合、**FastAPI** は内部的に`RequestValidationError`を発生させます。
+
+また、そのためのデフォルトの例外ハンドラも含まれています。
+
+これをオーバーライドするには`RequestValidationError`をインポートして`@app.exception_handler(RequestValidationError)`と一緒に使用して例外ハンドラをデコレートします。
+
+この例外ハンドラは`Request`と例外を受け取ります。
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
+
+これで、`/items/foo`にアクセスすると、以下のデフォルトのJSONエラーの代わりに:
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ]
+}
+```
+
+以下のテキスト版を取得します:
+
+```
+Validation errors:
+Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer
+```
+
+### `HTTPException`エラーハンドラのオーバーライド { #override-the-httpexception-error-handler }
+
+同様に、`HTTPException`ハンドラをオーバーライドすることもできます。
+
+例えば、これらのエラーに対しては、JSONではなくプレーンテキストを返すようにすることができます:
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
+
+/// note | 技術詳細
+
+また、`from starlette.responses import PlainTextResponse`を使用することもできます。
+
+**FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
+
+///
+
+/// warning | 注意
+
+`RequestValidationError`には、検証エラーが発生したファイル名と行番号の情報が含まれているため、必要であれば関連情報と一緒にログに表示できます。
+
+しかし、そのまま文字列に変換して直接その情報を返すと、システムに関する情報が多少漏えいする可能性があります。そのため、ここではコードが各エラーを個別に抽出して表示します。
+
+///
+
+### `RequestValidationError`のボディの使用 { #use-the-requestvalidationerror-body }
+
+`RequestValidationError`には無効なデータを含む`body`が含まれています。
+
+アプリ開発中にボディのログを取ってデバッグしたり、ユーザーに返したりなどに使用することができます。
+
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
+
+ここで、以下のような無効な項目を送信してみてください:
+
+```JSON
+{
+ "title": "towel",
+ "size": "XL"
+}
+```
+
+受信したボディを含むデータが無効であることを示すレスポンスが表示されます:
+
+```JSON hl_lines="12-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` { #fastapis-httpexception-vs-starlettes-httpexception }
+
+**FastAPI**は独自の`HTTPException`を持っています。
+
+また、 **FastAPI**の`HTTPException`エラークラスはStarletteの`HTTPException`エラークラスを継承しています。
+
+唯一の違いは、**FastAPI** の`HTTPException`は`detail`フィールドにJSONに変換可能な任意のデータを受け付けるのに対し、Starletteの`HTTPException`は文字列のみを受け付けることです。
+
+そのため、コード内では通常通り **FastAPI** の`HTTPException`を発生させ続けることができます。
+
+しかし、例外ハンドラを登録する際には、Starletteの`HTTPException`に対して登録しておく必要があります。
+
+これにより、Starletteの内部コードやStarletteの拡張機能やプラグインの一部がStarletteの`HTTPException`を発生させた場合、ハンドラがそれをキャッチして処理できるようになります。
+
+この例では、同じコード内で両方の`HTTPException`を使用できるようにするために、Starletteの例外を`StarletteHTTPException`にリネームしています:
+
+```Python
+from starlette.exceptions import HTTPException as StarletteHTTPException
+```
+
+### **FastAPI** の例外ハンドラの再利用 { #reuse-fastapis-exception-handlers }
+
+**FastAPI** から同じデフォルトの例外ハンドラと一緒に例外を使用したい場合は、`fastapi.exception_handlers`からデフォルトの例外ハンドラをインポートして再利用できます:
+
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
+
+この例では、非常に表現力のあるメッセージでエラーを`print`しているだけですが、要点は理解できるはずです。例外を使用し、その後デフォルトの例外ハンドラを再利用できます。
diff --git a/docs/ja/docs/tutorial/header-param-models.md b/docs/ja/docs/tutorial/header-param-models.md
new file mode 100644
index 0000000000000..e1e102c87e76d
--- /dev/null
+++ b/docs/ja/docs/tutorial/header-param-models.md
@@ -0,0 +1,72 @@
+# ヘッダーパラメータのモデル { #header-parameter-models }
+
+関連する**ヘッダーパラメータ**が一式ある場合、それらを宣言するための**Pydantic モデル**を作成できます。
+
+これにより、モデルを**複数箇所**で**再利用**でき、さらにすべてのパラメータに対するバリデーションやメタデータを一括で宣言できます。😎
+
+/// note | 備考
+
+これは FastAPI バージョン `0.115.0` 以降でサポートされています。🤓
+
+///
+
+## Pydantic モデルによるヘッダーパラメータ { #header-parameters-with-a-pydantic-model }
+
+必要な**ヘッダーパラメータ**を**Pydantic モデル**内で宣言し、関数引数ではそのパラメータを `Header` として宣言します:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI** はリクエストの**ヘッダー**から**各フィールド**の値を**抽出**し、定義した Pydantic モデルとして渡します。
+
+## ドキュメントの確認 { #check-the-docs }
+
+`/docs` のドキュメント UI で必要なヘッダーを確認できます:
+
+
+contact fields| Parameter | Type | Description |
|---|---|---|
name | str | 連絡先の個人/組織を識別する名前です。 |
url | str | 連絡先情報を指すURLです。URL形式である必要があります。 |
email | str | 連絡先の個人/組織のメールアドレスです。メールアドレス形式である必要があります。 |
license_info fields| Parameter | Type | Description |
|---|---|---|
name | str | 必須(license_info が設定されている場合)。APIに使用されるライセンス名です。 |
identifier | str | APIの [SPDX](https://spdx.org/licenses/) ライセンス式です。identifier フィールドは url フィールドと同時に指定できません。 OpenAPI 3.1.0、FastAPI 0.99.0 以降で利用できます。 |
url | str | APIに使用されるライセンスへのURLです。URL形式である必要があります。 |
+
+## ライセンス識別子 { #license-identifier }
+
+OpenAPI 3.1.0 および FastAPI 0.99.0 以降では、`license_info` を `url` の代わりに `identifier` で設定することもできます。
+
+例:
+
+{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}
+
+## タグのメタデータ { #metadata-for-tags }
+
+パラメータ `openapi_tags` を使うと、path operation をグループ分けするために使用する各タグに追加のメタデータを追加できます。
+
+それぞれのタグごとに1つの辞書を含むリストを取ります。
+
+それぞれの辞書は以下を含められます:
+
+* `name` (**必須**): *path operation* および `APIRouter` の `tags` パラメータで使用するのと同じタグ名の `str`。
+* `description`: タグの短い説明の `str`。Markdownを含められ、ドキュメントUIに表示されます。
+* `externalDocs`: 外部ドキュメントを説明する `dict`。以下を含みます:
+ * `description`: 外部ドキュメントの短い説明の `str`。
+ * `url` (**必須**): 外部ドキュメントのURLの `str`。
+
+### タグのメタデータの作成 { #create-metadata-for-tags }
+
+`users` と `items` のタグを使った例で試してみましょう。
+
+タグのメタデータを作成し、それを `openapi_tags` パラメータに渡します:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}
+
+説明の中でMarkdownを使用できることに注意してください。たとえば「login」は太字 (**login**) で表示され、「fancy」は斜体 (_fancy_) で表示されます。
+
+/// tip | 豆知識
+
+使用するすべてのタグにメタデータを追加する必要はありません。
+
+///
+
+### タグの使用 { #use-your-tags }
+
+*path operation*(および `APIRouter`)の `tags` パラメータを使用して、それらを異なるタグに割り当てます:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}
+
+/// info | 情報
+
+タグの詳細は [Path Operation の設定](path-operation-configuration.md#tags) を参照してください。
+
+///
+
+### ドキュメントの確認 { #check-the-docs }
+
+ここでドキュメントを確認すると、追加したメタデータがすべて表示されます:
+
+
+
+### タグの順番 { #order-of-tags }
+
+タグのメタデータ辞書の順序は、ドキュメントUIに表示される順序の定義にもなります。
+
+たとえば、`users` はアルファベット順では `items` の後に続きますが、リストの最初の辞書としてメタデータを追加したため、それより前に表示されます。
+
+## OpenAPI URL { #openapi-url }
+
+デフォルトでは、OpenAPIスキーマは `/openapi.json` で提供されます。
+
+ただし、パラメータ `openapi_url` を使用して設定を変更できます。
+
+たとえば、`/api/v1/openapi.json` で提供されるように設定するには:
+
+{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}
+
+OpenAPIスキーマを完全に無効にする場合は、`openapi_url=None` を設定できます。これにより、それを使用するドキュメントUIも無効になります。
+
+## ドキュメントのURL { #docs-urls }
+
+含まれている2つのドキュメントUIを設定できます:
+
+* **Swagger UI**: `/docs` で提供されます。
+ * URL はパラメータ `docs_url` で設定できます。
+ * `docs_url=None` を設定することで無効にできます。
+* **ReDoc**: `/redoc` で提供されます。
+ * URL はパラメータ `redoc_url` で設定できます。
+ * `redoc_url=None` を設定することで無効にできます。
+
+たとえば、`/documentation` でSwagger UIが提供されるように設定し、ReDocを無効にするには:
+
+{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}
diff --git a/docs/ja/docs/tutorial/middleware.md b/docs/ja/docs/tutorial/middleware.md
index 973eb2b1a96a3..20192d0805d9b 100644
--- a/docs/ja/docs/tutorial/middleware.md
+++ b/docs/ja/docs/tutorial/middleware.md
@@ -1,4 +1,4 @@
-# ミドルウェア
+# ミドルウェア { #middleware }
**FastAPI** アプリケーションにミドルウェアを追加できます。
@@ -11,12 +11,15 @@
* その**レスポンス**に対して何かを実行したり、必要なコードを実行したりできます。
* そして、**レスポンス**を返します。
-!!! note "技術詳細"
- `yield` を使った依存関係をもつ場合は、終了コードはミドルウェアの *後に* 実行されます。
+/// note | 技術詳細
- バックグラウンドタスク (後述) がある場合は、それらは全てのミドルウェアの *後に* 実行されます。
+`yield` を使った依存関係をもつ場合は、終了コードはミドルウェアの *後に* 実行されます。
-## ミドルウェアの作成
+バックグラウンドタスク ([バックグラウンドタスク](background-tasks.md) セクションで説明します。後で確認できます) がある場合は、それらは全てのミドルウェアの *後に* 実行されます。
+
+///
+
+## ミドルウェアの作成 { #create-a-middleware }
ミドルウェアを作成するには、関数の上部でデコレータ `@app.middleware("http")` を使用します。
@@ -28,21 +31,25 @@
* 次に、対応する*path operation*によって生成された `response` を返します。
* その後、`response` を返す前にさらに `response` を変更することもできます。
-```Python hl_lines="8-9 11 14"
-{!../../../docs_src/middleware/tutorial001.py!}
-```
+{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}
+
+/// tip | 豆知識
+
+カスタムの独自ヘッダーは [`X-` プレフィックスを使用](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers)して追加できる点に注意してください。
-!!! tip "豆知識"
- 'X-'プレフィックスを使用してカスタムの独自ヘッダーを追加できます。
+ただし、ブラウザのクライアントに表示させたいカスタムヘッダーがある場合は、[CORS (Cross-Origin Resource Sharing)](cors.md) の設定に、[StarletteのCORSドキュメント](https://www.starlette.dev/middleware/#corsmiddleware)に記載されているパラメータ `expose_headers` を使用して、それらを追加する必要があります。
- ただし、ブラウザのクライアントに表示させたいカスタムヘッダーがある場合は、StarletteのCORSドキュメントに記載されているパラメータ `expose_headers` を使用して、それらをCORS設定に追加する必要があります ([CORS (オリジン間リソース共有)](cors.md){.internal-link target=_blank})
+///
-!!! note "技術詳細"
- `from starlette.requests import Request` を使用することもできます。
+/// note | 技術詳細
- **FastAPI**は、開発者の便利のためにこれを提供していますが、Starletteから直接きています。
+`from starlette.requests import Request` を使用することもできます。
-### `response` の前後
+**FastAPI**は、開発者の便利のためにこれを提供していますが、Starletteから直接きています。
+
+///
+
+### `response` の前後 { #before-and-after-the-response }
*path operation* が `request` を受け取る前に、 `request` とともに実行されるコードを追加できます。
@@ -50,12 +57,39 @@
例えば、リクエストの処理とレスポンスの生成にかかった秒数を含むカスタムヘッダー `X-Process-Time` を追加できます:
-```Python hl_lines="10 12-13"
-{!../../../docs_src/middleware/tutorial001.py!}
+{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}
+
+/// tip | 豆知識
+
+ここでは、これらのユースケースに対してより正確になり得るため、`time.time()` の代わりに [`time.perf_counter()`](https://docs.python.org/3/library/time.html#time.perf_counter) を使用しています。 🤓
+
+///
+
+## 複数ミドルウェアの実行順序 { #multiple-middleware-execution-order }
+
+`@app.middleware()` デコレータまたは `app.add_middleware()` メソッドのいずれかを使って複数のミドルウェアを追加すると、新しく追加された各ミドルウェアがアプリケーションをラップし、スタックを形成します。最後に追加されたミドルウェアが *最も外側*、最初に追加されたミドルウェアが *最も内側* になります。
+
+リクエスト経路では、*最も外側* のミドルウェアが最初に実行されます。
+
+レスポンス経路では、最後に実行されます。
+
+例:
+
+```Python
+app.add_middleware(MiddlewareA)
+app.add_middleware(MiddlewareB)
```
-## その他のミドルウェア
+これにより、実行順序は次のようになります:
+
+* **リクエスト**: MiddlewareB → MiddlewareA → route
+
+* **レスポンス**: route → MiddlewareA → MiddlewareB
+
+このスタック動作により、ミドルウェアが予測可能で制御しやすい順序で実行されることが保証されます。
+
+## その他のミドルウェア { #other-middlewares }
-他のミドルウェアの詳細については、[高度なユーザーガイド: 高度なミドルウェア](../advanced/middleware.md){.internal-link target=_blank}を参照してください。
+他のミドルウェアの詳細については、[高度なユーザーガイド: 高度なミドルウェア](../advanced/middleware.md)を参照してください。
-次のセクションでは、ミドルウェアを使用して CORS を処理する方法について説明します。
+次のセクションでは、ミドルウェアを使用して CORS を処理する方法について説明します。
diff --git a/docs/ja/docs/tutorial/path-operation-configuration.md b/docs/ja/docs/tutorial/path-operation-configuration.md
new file mode 100644
index 0000000000000..25a2783ea19f7
--- /dev/null
+++ b/docs/ja/docs/tutorial/path-operation-configuration.md
@@ -0,0 +1,107 @@
+# Path Operationの設定 { #path-operation-configuration }
+
+*path operationデコレータ*を設定するためのパラメータがいくつかあります。
+
+/// warning | 注意
+
+これらのパラメータは*path operationデコレータ*に直接渡され、*path operation関数*に渡されないことに注意してください。
+
+///
+
+## レスポンスステータスコード { #response-status-code }
+
+*path operation*のレスポンスで使用する(HTTP)`status_code`を定義することができます。
+
+`404`のように`int`のコードを直接渡すことができます。
+
+しかし、それぞれの番号コードが何のためのものか覚えていない場合は、`status`のショートカット定数を使用することができます:
+
+{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *}
+
+そのステータスコードはレスポンスで使用され、OpenAPIスキーマに追加されます。
+
+/// note | 技術詳細
+
+`from starlette import status`を使用することもできます。
+
+**FastAPI** は開発者の利便性を考慮して、`fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。
+
+///
+
+## タグ { #tags }
+
+`tags`パラメータを`str`の`list`(通常は1つの`str`)と一緒に渡すと、*path operation*にタグを追加できます:
+
+{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *}
+
+これらはOpenAPIスキーマに追加され、自動ドキュメントのインターフェースで使用されます:
+
+
+
+### Enumを使ったタグ { #tags-with-enums }
+
+大きなアプリケーションの場合、**複数のタグ**が蓄積されていき、関連する*path operations*に対して常に**同じタグ**を使っていることを確認したくなるかもしれません。
+
+このような場合、タグを`Enum`に格納すると理にかなっています。
+
+**FastAPI** は、プレーンな文字列の場合と同じ方法でそれをサポートしています:
+
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
+
+## 概要と説明 { #summary-and-description }
+
+`summary`と`description`を追加できます:
+
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *}
+
+## docstringを用いた説明 { #description-from-docstring }
+
+説明文は長くて複数行におよぶ傾向があるので、関数docstring内に*path operation*の説明文を宣言できます。すると、**FastAPI** は説明文を読み込んでくれます。
+
+docstringに[Markdown](https://en.wikipedia.org/wiki/Markdown)を記述すれば、正しく解釈されて表示されます。(docstringのインデントを考慮して)
+
+{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}
+
+これは対話的ドキュメントで使用されます:
+
+
+
+## レスポンスの説明 { #response-description }
+
+`response_description`パラメータでレスポンスの説明をすることができます。
+
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
+
+/// info | 情報
+
+`response_description`は具体的にレスポンスを参照し、`description`は*path operation*全般を参照していることに注意してください。
+
+///
+
+/// check | 確認
+
+OpenAPIは*path operation*ごとにレスポンスの説明を必要としています。
+
+そのため、それを提供しない場合は、**FastAPI** が自動的に「成功のレスポンス」を生成します。
+
+///
+
+
+
+## *path operation*を非推奨にする { #deprecate-a-path-operation }
+
+*path operation*をdeprecatedとしてマークする必要があるが、それを削除しない場合は、`deprecated`パラメータを渡します:
+
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
+
+対話的ドキュメントでは非推奨と明記されます:
+
+
+
+*path operations*が非推奨である場合とそうでない場合でどのように見えるかを確認してください:
+
+
+
+## まとめ { #recap }
+
+*path operationデコレータ*にパラメータを渡すことで、*path operations*のメタデータを簡単に設定・追加することができます。
diff --git a/docs/ja/docs/tutorial/path-params-numeric-validations.md b/docs/ja/docs/tutorial/path-params-numeric-validations.md
new file mode 100644
index 0000000000000..55930eece2eb1
--- /dev/null
+++ b/docs/ja/docs/tutorial/path-params-numeric-validations.md
@@ -0,0 +1,154 @@
+# パスパラメータと数値の検証 { #path-parameters-and-numeric-validations }
+
+クエリパラメータに対して`Query`でより多くのバリデーションとメタデータを宣言できるのと同じように、パスパラメータに対しても`Path`で同じ種類のバリデーションとメタデータを宣言することができます。
+
+## `Path`のインポート { #import-path }
+
+まず初めに、`fastapi`から`Path`をインポートし、`Annotated`もインポートします:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
+
+/// info | 情報
+
+FastAPI はバージョン 0.95.0 で`Annotated`のサポートを追加し(そして推奨し始めました)。
+
+古いバージョンの場合、`Annotated`を使おうとするとエラーになります。
+
+`Annotated`を使用する前に、FastAPI のバージョンを少なくとも 0.95.1 まで[アップグレードしてください](../deployment/versions.md#upgrading-the-fastapi-versions)。
+
+///
+
+## メタデータの宣言 { #declare-metadata }
+
+パラメータは`Query`と同じものを宣言することができます。
+
+例えば、パスパラメータ`item_id`に対して`title`のメタデータを宣言するには以下のようにします:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *}
+
+/// note | 備考
+
+パスパラメータはパスの一部でなければならないので、常に必須です。`None`で宣言したりデフォルト値を設定したりしても何も影響せず、常に必須のままです。
+
+///
+
+## 必要に応じてパラメータを並び替える { #order-the-parameters-as-you-need }
+
+/// tip | 豆知識
+
+`Annotated`を使う場合、これはおそらくそれほど重要でも必要でもありません。
+
+///
+
+クエリパラメータ`q`を必須の`str`として宣言したいとしましょう。
+
+また、このパラメータには何も宣言する必要がないので、`Query`を使う必要はありません。
+
+しかし、パスパラメータ`item_id`のために`Path`を使用する必要があります。そして何らかの理由で`Annotated`を使いたくないとします。
+
+Pythonは「デフォルト」を持つ値を「デフォルト」を持たない値の前に置くとエラーになります。
+
+しかし、それらを並び替えることができ、デフォルト値を持たない値(クエリパラメータ`q`)を最初に持つことができます。
+
+**FastAPI**では関係ありません。パラメータは名前、型、デフォルトの宣言(`Query`、`Path`など)で検出され、順番は気にしません。
+
+そのため、以下のように関数を宣言することができます:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
+
+ただし、`Annotated`を使う場合はこの問題は起きないことを覚えておいてください。`Query()`や`Path()`に関数パラメータのデフォルト値を使わないためです。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
+
+## 必要に応じてパラメータを並び替えるトリック { #order-the-parameters-as-you-need-tricks }
+
+/// tip | 豆知識
+
+`Annotated`を使う場合、これはおそらくそれほど重要でも必要でもありません。
+
+///
+
+これは**小さなトリック**で、便利な場合がありますが、頻繁に必要になることはありません。
+
+次のことをしたい場合:
+
+* `q`クエリパラメータを`Query`もデフォルト値もなしで宣言する
+* パスパラメータ`item_id`を`Path`を使って宣言する
+* それらを別の順番にする
+* `Annotated`を使わない
+
+...Pythonにはそのための少し特殊な構文があります。
+
+関数の最初のパラメータとして`*`を渡します。
+
+Pythonはその`*`で何かをすることはありませんが、それ以降のすべてのパラメータがキーワード引数(キーと値のペア)として呼ばれるべきものであると知っているでしょう。それはkwargsとしても知られています。たとえデフォルト値がなくても。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
+
+### `Annotated`のほうがよい { #better-with-annotated }
+
+`Annotated`を使う場合は、関数パラメータのデフォルト値を使わないため、この問題は起きず、おそらく`*`を使う必要もありません。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
+
+## 数値の検証: 以上 { #number-validations-greater-than-or-equal }
+
+`Query`と`Path`(、そして後述する他のもの)を用いて、数値の制約を宣言できます。
+
+ここで、`ge=1`の場合、`item_id`は`1`「より大きい`g`か、同じ`e`」整数でなければなりません。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
+
+## 数値の検証: より大きいと小なりイコール { #number-validations-greater-than-and-less-than-or-equal }
+
+以下も同様です:
+
+* `gt`: `g`reater `t`han
+* `le`: `l`ess than or `e`qual
+
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
+
+## 数値の検証: 浮動小数点、 大なり小なり { #number-validations-floats-greater-than-and-less-than }
+
+数値のバリデーションは`float`の値に対しても有効です。
+
+ここで重要になってくるのはgtだけでなくgeも宣言できることです。これと同様に、例えば、値が`1`より小さくても`0`より大きくなければならないことを要求することができます。
+
+したがって、`0.5`は有効な値ですが、`0.0`や`0`はそうではありません。
+
+これはltも同じです。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
+
+## まとめ { #recap }
+
+`Query`と`Path`(そしてまだ見たことない他のもの)では、[クエリパラメータと文字列の検証](query-params-str-validations.md)と同じようにメタデータと文字列の検証を宣言することができます。
+
+また、数値のバリデーションを宣言することもできます:
+
+* `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`という名前のクラスのインスタンスが返されます。
+
+これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。
+
+この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。
+
+///
diff --git a/docs/ja/docs/tutorial/path-params.md b/docs/ja/docs/tutorial/path-params.md
index 66de05afb1339..8556b1c375184 100644
--- a/docs/ja/docs/tutorial/path-params.md
+++ b/docs/ja/docs/tutorial/path-params.md
@@ -1,105 +1,114 @@
-# パスパラメータ
+# パスパラメータ { #path-parameters }
Pythonのformat文字列と同様のシンタックスで「パスパラメータ」や「パス変数」を宣言できます:
-```Python hl_lines="6 7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
パスパラメータ `item_id` の値は、引数 `item_id` として関数に渡されます。
-しがたって、この例を実行して http://127.0.0.1:8000/items/foo にアクセスすると、次のレスポンスが表示されます。
+したがって、この例を実行して [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo) にアクセスすると、次のレスポンスが表示されます。
```JSON
{"item_id":"foo"}
```
-## パスパラメータと型
+## 型付きパスパラメータ { #path-parameters-with-types }
標準のPythonの型アノテーションを使用して、関数内のパスパラメータの型を宣言できます:
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
+{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}
ここでは、 `item_id` は `int` として宣言されています。
-!!! check "確認"
- これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。
+/// check | 確認
+
+これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。
+
+///
-## データ変換
+## データ変換 { #data-conversion }
-この例を実行し、ブラウザで http://127.0.0.1:8000/items/3 を開くと、次のレスポンスが表示されます:
+この例を実行し、ブラウザで [http://127.0.0.1:8000/items/3](http://127.0.0.1:8000/items/3) を開くと、次のレスポンスが表示されます:
```JSON
{"item_id":3}
```
-!!! check "確認"
- 関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。
+/// check | 確認
- したがって、型宣言を使用すると、**FastAPI**は自動リクエスト "解析" を行います。
+関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。
-## データバリデーション
+したがって、その型宣言を使うと、**FastAPI**は自動リクエスト "解析" を行います。
-しかしブラウザで http://127.0.0.1:8000/items/foo を開くと、次のHTTPエラーが表示されます:
+///
+
+## データバリデーション { #data-validation }
+
+しかしブラウザで [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo) を開くと、次のHTTPエラーが表示されます:
```JSON
{
- "detail": [
- {
- "loc": [
- "path",
- "item_id"
- ],
- "msg": "value is not a valid integer",
- "type": "type_error.integer"
- }
- ]
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo"
+ }
+ ]
}
```
これは、パスパラメータ `item_id` が `int` ではない値 `"foo"` だからです。
-http://127.0.0.1:8000/items/4.2 で見られるように、intのかわりに `float` が与えられた場合にも同様なエラーが表示されます。
+[http://127.0.0.1:8000/items/4.2](http://127.0.0.1:8000/items/4.2) で見られるように、`int` のかわりに `float` が与えられた場合にも同様なエラーが表示されます。
+
+/// check | 確認
-!!! check "確認"
- したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。
+したがって、同じPythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。
- 表示されたエラーには問題のある箇所が明確に指摘されていることに注意してください。
+表示されたエラーには、バリデーションが通らなかった箇所が明確に示されていることに注意してください。
- これは、APIに関連するコードの開発およびデバッグに非常に役立ちます。
+これは、APIとやり取りするコードを開発・デバッグする際に非常に役立ちます。
-## ドキュメント
+///
-そしてブラウザで http://127.0.0.1:8000/docs を開くと、以下の様な自動的に生成された対話的なドキュメントが表示されます。
+## ドキュメント { #documentation }
+
+そしてブラウザで [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) を開くと、以下の様な自動的に生成された対話的なAPIドキュメントが表示されます。
-!!! check "確認"
- 繰り返しになりますが、Python型宣言を使用するだけで、**FastAPI**は対話的なAPIドキュメントを自動的に生成します(Swagger UIを統合)。
+/// check | 確認
+
+繰り返しになりますが、同じPython型宣言を使用するだけで、**FastAPI**は対話的なドキュメントを自動的に生成します(Swagger UIを統合)。
+
+パスパラメータが整数として宣言されていることに注意してください。
- パスパラメータが整数として宣言されていることに注意してください。
+///
-## 標準であることのメリット、ドキュメンテーションの代替物
+## 標準ベースのメリット、ドキュメンテーションの代替物 { #standards-based-benefits-alternative-documentation }
-また、生成されたスキーマが OpenAPI 標準に従っているので、互換性のあるツールが多数あります。
+また、生成されたスキーマが [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md) 標準に従っているので、互換性のあるツールが多数あります。
-このため、**FastAPI**自体が代替のAPIドキュメントを提供します(ReDocを使用)。これは、 http://127.0.0.1:8000/redoc にアクセスすると確認できます。
+このため、**FastAPI**自体が代替のAPIドキュメントを提供します(ReDocを使用)。これは、 [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) にアクセスすると確認できます。
-同様に、互換性のあるツールが多数あります(多くの言語用のコード生成ツールを含む)。
+同様に、互換性のあるツールが多数あります。多くの言語用のコード生成ツールを含みます。
-## Pydantic
+## Pydantic { #pydantic }
-すべてのデータバリデーションは Pydantic によって内部で実行されるため、Pydanticの全てのメリットが得られます。そして、安心して利用することができます。
+すべてのデータバリデーションは [Pydantic](https://docs.pydantic.dev/) によって内部で実行されるため、Pydanticの全てのメリットが得られます。そして、安心して利用することができます。
`str`、 `float` 、 `bool` および他の多くの複雑なデータ型を型宣言に使用できます。
これらのいくつかについては、チュートリアルの次の章で説明します。
-## 順序の問題
+## 順序の問題 { #order-matters }
*path operations* を作成する際、固定パスをもつ状況があり得ます。
@@ -109,80 +118,77 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
*path operations* は順に評価されるので、 `/users/me` が `/users/{user_id}` よりも先に宣言されているか確認する必要があります:
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
-```
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
+
+それ以外の場合、 `/users/{user_id}` は `/users/me` としてもマッチします。値が `"me"` であるパラメータ `user_id` を受け取ると「考え」ます。
+
+同様に、path operation を再定義することはできません:
-それ以外の場合、 `/users/{users_id}` は `/users/me` としてもマッチします。値が「"me"」であるパラメータ `user_id` を受け取ると「考え」ます。
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
-## 定義済みの値
+パスは最初にマッチしたものが常に使われるため、最初のものが常に使用されます。
-*パスパラメータ*を受け取る *path operation* をもち、有効な*パスパラメータ*の値を事前に定義したい場合は、標準のPython `Enum` を利用できます。
+## 定義済みの値 { #predefined-values }
-### `Enum` クラスの作成
+*パスパラメータ*を受け取る *path operation* をもち、有効な*パスパラメータ*の値を事前に定義したい場合は、標準のPython `Enum` を利用できます。
+
+### `Enum` クラスの作成 { #create-an-enum-class }
`Enum` をインポートし、 `str` と `Enum` を継承したサブクラスを作成します。
-`str` を継承することで、APIドキュメントは値が `文字列` でなければいけないことを知り、正確にレンダリングできるようになります。
+`str` を継承することで、APIドキュメントは値が `string` 型でなければいけないことを知り、正確にレンダリングできるようになります。
そして、固定値のクラス属性を作ります。すると、その値が使用可能な値となります:
-```Python hl_lines="1 6 7 8 9"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
+
+/// tip | 豆知識
-!!! info "情報"
- Enumerations (もしくは、enums)はPython 3.4以降で利用できます。
+"AlexNet"、"ResNet"そして"LeNet"は機械学習モデルの名前です。
-!!! tip "豆知識"
- "AlexNet"、"ResNet"そして"LeNet"は機械学習モデルの名前です。
+///
-### *パスパラメータ*の宣言
+### *パスパラメータ*の宣言 { #declare-a-path-parameter }
次に、作成したenumクラスである`ModelName`を使用した型アノテーションをもつ*パスパラメータ*を作成します:
-```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
-### ドキュメントの確認
+### ドキュメントの確認 { #check-the-docs }
*パスパラメータ*の利用可能な値が事前に定義されているので、対話的なドキュメントで適切に表示できます:
-### Python*列挙型*の利用
+### Python*列挙型*の利用 { #working-with-python-enumerations }
*パスパラメータ*の値は*列挙型メンバ*となります。
-#### *列挙型メンバ*の比較
+#### *列挙型メンバ*の比較 { #compare-enumeration-members }
これは、作成した列挙型 `ModelName` の*列挙型メンバ*と比較できます:
-```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}
-#### *列挙値*の取得
+#### *列挙値*の取得 { #get-the-enumeration-value }
`model_name.value` 、もしくは一般に、 `your_enum_member.value` を使用して実際の値 (この場合は `str`) を取得できます。
-```Python hl_lines="20"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}
-!!! tip "豆知識"
- `ModelName.lenet.value` でも `"lenet"` 値にアクセスできます。
+/// tip | 豆知識
-#### *列挙型メンバ*の返却
+`ModelName.lenet.value` でも `"lenet"` 値にアクセスできます。
-*path operation* から*列挙型メンバ*を返すことができます。JSONボディ(`dict` など)でネストすることもできます。
+///
+
+#### *列挙型メンバ*の返却 { #return-enumeration-members }
+
+*path operation* から*列挙型メンバ*を返すことができます。JSONボディ(例: `dict`)でネストすることもできます。
それらはクライアントに返される前に適切な値 (この場合は文字列) に変換されます。
-```Python hl_lines="18 21 23"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}
クライアントは以下の様なJSONレスポンスを得ます:
@@ -193,23 +199,23 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー
}
```
-## パスを含んだパスパラメータ
+## パスを含んだパスパラメータ { #path-parameters-containing-paths }
パス `/files/{file_path}` となる *path operation* を持っているとしましょう。
ただし、 `home/johndoe/myfile.txt` のような*パス*を含んだ `file_path` が必要です。
-したがって、URLは `/files/home/johndoe/myfile.txt` の様になります。
+したがって、そのファイルのURLは `/files/home/johndoe/myfile.txt` の様になります。
-### OpenAPIサポート
+### OpenAPIサポート { #openapi-support }
OpenAPIはテストや定義が困難なシナリオにつながる可能性があるため、内部に*パス*を含む*パスパラメータ*の宣言をサポートしていません。
それにも関わらず、Starletteの内部ツールのひとつを使用することで、**FastAPI**はそれが実現できます。
-そして、パラメータがパスを含むべきであることを明示的にドキュメントに追加することなく、機能します。
+そして、パラメータがパスを含むべきであることを示すドキュメントを追加しなくても、ドキュメントは動作します。
-### パス変換
+### パスコンバーター { #path-convertor }
Starletteのオプションを直接使用することで、以下のURLの様な*パス*を含んだ、*パスパラメータ*の宣言ができます:
@@ -221,21 +227,22 @@ Starletteのオプションを直接使用することで、以下のURLの様
したがって、以下の様に使用できます:
-```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
-```
+{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}
+
+/// tip | 豆知識
+
+最初のスラッシュ (`/`)が付いている `/home/johndoe/myfile.txt` をパラメータが含んでいる必要があるかもしれません。
-!!! tip "豆知識"
- 最初のスラッシュ (`/`)が付いている `/home/johndoe/myfile.txt` をパラメータが含んでいる必要があります。
+この場合、URLは `files` と `home` の間にダブルスラッシュ (`//`) のある、 `/files//home/johndoe/myfile.txt` になります。
- この場合、URLは `files` と `home` の間にダブルスラッシュ (`//`) のある、 `/files//home/johndoe/myfile.txt` になります。
+///
-## まとめ
+## まとめ { #recap }
簡潔で、本質的で、標準的なPythonの型宣言を使用することで、**FastAPI**は以下を行います:
* エディターサポート: エラーチェック、自動補完、など
-* データ「解析」
+* データ「解析」
* データバリデーション
* APIアノテーションと自動ドキュメント生成
diff --git a/docs/ja/docs/tutorial/query-param-models.md b/docs/ja/docs/tutorial/query-param-models.md
new file mode 100644
index 0000000000000..d892a57d22747
--- /dev/null
+++ b/docs/ja/docs/tutorial/query-param-models.md
@@ -0,0 +1,68 @@
+# クエリパラメータモデル { #query-parameter-models }
+
+もし関連する**複数のクエリパラメータ**から成るグループがあるなら、それらを宣言するために、**Pydanticモデル**を作成できます。
+
+こうすることで、**複数の場所**で**そのモデルを再利用**でき、バリデーションやメタデータを、すべてのパラメータに対して一度に宣言できます。😎
+
+/// note | 備考
+
+この機能は、FastAPIのバージョン `0.115.0` からサポートされています。🤓
+
+///
+
+## Pydanticモデルを使ったクエリパラメータ { #query-parameters-with-a-pydantic-model }
+
+必要な**クエリパラメータ**を**Pydanticモデル**で宣言し、さらに、そのパラメータを `Query` として宣言しましょう:
+
+{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}
+
+**FastAPI**は、リクエストの**クエリパラメータ**からそれぞれの**フィールド**のデータを**抽出**し、定義したPydanticモデルを提供します。
+
+## ドキュメントの確認 { #check-the-docs }
+
+対話的APIドキュメント `/docs` でクエリパラメータを確認できます:
+
+
+
+
-### デフォルト値を持つ、クエリパラメータのリスト / 複数の値
+### デフォルト値を持つ、クエリパラメータのリスト / 複数の値 { #query-parameter-list-multiple-values-with-defaults }
-また、値が指定されていない場合はデフォルトの`list`を定義することもできます。
+また、値が指定されていない場合はデフォルトの `list` を定義することもできます。
-```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial012.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
-以下のURLを開くと:
+以下にアクセスすると:
```
http://localhost:8000/items/
@@ -206,43 +288,43 @@ http://localhost:8000/items/
}
```
-#### `list`を使う
+#### `list` だけを使う { #using-just-list }
-`List[str]`の代わりに直接`list`を使うこともできます:
+`list[str]` の代わりに直接 `list` を使うこともできます:
-```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial013.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
+
+/// note | 備考
-!!! note "備考"
- この場合、FastAPIはリストの内容をチェックしないことを覚えておいてください。
+この場合、FastAPIはリストの内容をチェックしないことを覚えておいてください。
- 例えば`List[int]`はリストの内容が整数であるかどうかをチェックします(そして、文書化します)。しかし`list`だけではそうしません。
+例えば`list[int]`はリストの内容が整数であるかどうかをチェックします(そして、文書化します)。しかし`list`だけではそうしません。
-## より多くのメタデータを宣言する
+///
+
+## より多くのメタデータを宣言する { #declare-more-metadata }
パラメータに関する情報をさらに追加することができます。
その情報は、生成されたOpenAPIに含まれ、ドキュメントのユーザーインターフェースや外部のツールで使用されます。
-!!! note "備考"
- ツールによってOpenAPIのサポートのレベルが異なる可能性があることを覚えておいてください。
+/// note | 備考
+
+ツールによってOpenAPIのサポートのレベルが異なる可能性があることを覚えておいてください。
- その中には、宣言されたすべての追加情報が表示されていないものもあるかもしれませんが、ほとんどの場合、不足している機能はすでに開発の計画がされています。
+その中には、宣言されたすべての追加情報が表示されていないものもあるかもしれませんが、ほとんどの場合、不足している機能はすでに開発の計画がされています。
+
+///
`title`を追加できます:
-```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial007.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *}
`description`を追加できます:
-```Python hl_lines="13"
-{!../../../docs_src/query_params_str_validations/tutorial008.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *}
-## エイリアスパラメータ
+## エイリアスパラメータ { #alias-parameters }
パラメータに`item-query`を指定するとします.
@@ -260,27 +342,91 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
それならば、`alias`を宣言することができます。エイリアスはパラメータの値を見つけるのに使用されます:
-```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial009.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *}
-## 非推奨パラメータ
+## パラメータを非推奨にする { #deprecating-parameters }
-さて、このパラメータが気に入らなくなったとしましょう
+さて、このパラメータが気に入らなくなったとしましょう。
-それを使っているクライアントがいるので、しばらくは残しておく必要がありますが、ドキュメントには非推奨と明記しておきたいです。
+それを使っているクライアントがいるので、しばらくは残しておく必要がありますが、ドキュメントには廃止予定と明記しておきたいです。
その場合、`Query`にパラメータ`deprecated=True`を渡します:
-```Python hl_lines="18"
-{!../../../docs_src/query_params_str_validations/tutorial010.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *}
ドキュメントは以下のようになります:
-
+
+
+## OpenAPI からパラメータを除外する { #exclude-parameters-from-openapi }
+
+生成される OpenAPI スキーマ(つまり自動ドキュメントシステム)からクエリパラメータを除外するには、`Query` のパラメータ `include_in_schema` を `False` に設定します:
+
+{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *}
+
+## カスタムバリデーション { #custom-validation }
+
+上で示したパラメータではできない **カスタムバリデーション** が必要になる場合があります。
+
+その場合、通常のバリデーション(例: 値が `str` であることの検証)の後に適用される **カスタムバリデータ関数** を使えます。
+
+これを行うには、`Annotated` の中で [Pydantic の `AfterValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-after-validator) を使います。
-## まとめ
+/// tip | 豆知識
+
+Pydantic には [`BeforeValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-before-validator) などもあります。 🤓
+
+///
+
+例えば、このカスタムバリデータは、ISBN の書籍番号なら item ID が `isbn-` で始まること、IMDB の movie URL ID なら `imdb-` で始まることをチェックします:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
+
+/// info | 情報
+
+これは Pydantic バージョン 2 以上で利用できます。 😎
+
+///
+
+/// tip | 豆知識
+
+データベースや別の API など、何らかの **外部コンポーネント** との通信が必要なタイプのバリデーションを行う必要がある場合は、代わりに **FastAPI Dependencies** を使うべきです。これについては後で学びます。
+
+これらのカスタムバリデータは、リクエストで提供された **同じデータのみ** でチェックできるもの向けです。
+
+///
+
+### そのコードを理解する { #understand-that-code }
+
+重要なのは、**`Annotated` の中で関数と一緒に `AfterValidator` を使うこと** だけです。この部分は飛ばしても構いません。 🤸
+
+---
+
+ただし、この具体的なコード例が気になっていて、まだ興味が続くなら、追加の詳細を示します。
+
+#### `value.startswith()` を使う文字列 { #string-with-value-startswith }
+
+気づきましたか?`value.startswith()` を使う文字列はタプルを受け取れ、そのタプル内の各値をチェックします:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *}
+
+#### ランダムなアイテム { #a-random-item }
+
+`data.items()` で、辞書の各アイテムのキーと値を含むタプルを持つ 反復可能オブジェクト を取得します。
+
+この反復可能オブジェクトを `list(data.items())` で適切な `list` に変換します。
+
+そして `random.choice()` でその `list` から **ランダムな値** を取得するので、`(id, name)` のタプルを得ます。これは `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")` のようになります。
+
+次に、そのタプルの **2つの値を代入** して、変数 `id` と `name` に入れます。
+
+つまり、ユーザーが item ID を提供しなかった場合でも、ランダムな提案を受け取ります。
+
+...これを **単一のシンプルな1行** で行っています。 🤯 Python が好きになりませんか? 🐍
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *}
+
+## まとめ { #recap }
パラメータに追加のバリデーションとメタデータを宣言することができます。
@@ -291,12 +437,14 @@ http://127.0.0.1:8000/items/?item-query=foobaritems
* `description`
* `deprecated`
-文字列のためのバリデーション:
+文字列に固有のバリデーション:
* `min_length`
* `max_length`
-* `regex`
+* `pattern`
+
+`AfterValidator` を使ったカスタムバリデーション。
-この例では、`str`の値のバリデーションを宣言する方法を見てきました。
+この例では、`str` の値のバリデーションを宣言する方法を見てきました。
数値のような他の型のバリデーションを宣言する方法は次の章を参照してください。
diff --git a/docs/ja/docs/tutorial/query-params.md b/docs/ja/docs/tutorial/query-params.md
index 5202009ef8676..51e4eb944f4d2 100644
--- a/docs/ja/docs/tutorial/query-params.md
+++ b/docs/ja/docs/tutorial/query-params.md
@@ -1,11 +1,8 @@
+# クエリパラメータ { #query-parameters }
-# クエリパラメータ
+パスパラメータではない関数パラメータを宣言すると、それらは自動的に「クエリ」パラメータとして解釈されます。
-パスパラメータではない関数パラメータを宣言すると、それらは自動的に "クエリ" パラメータとして解釈されます。
-
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial001.py!}
-```
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
クエリはURL内で `?` の後に続くキーとバリューの組で、 `&` で区切られています。
@@ -27,11 +24,11 @@ http://127.0.0.1:8000/items/?skip=0&limit=10
パスパラメータに適用される処理と完全に同様な処理がクエリパラメータにも施されます:
* エディターサポート (明らかに)
-* データ「解析」
+* データ 「解析」
* データバリデーション
* 自動ドキュメント生成
-## デフォルト
+## デフォルト { #defaults }
クエリパラメータはパスの固定部分ではないので、オプショナルとしたり、デフォルト値をもつことができます。
@@ -58,33 +55,27 @@ http://127.0.0.1:8000/items/?skip=20
関数内のパラメータの値は以下の様になります:
* `skip=20`: URL内にセットしたため
-* `limit=10`: デフォルト値
+* `limit=10`: デフォルト値だったため
-## オプショナルなパラメータ
+## オプショナルなパラメータ { #optional-parameters }
同様に、デフォルト値を `None` とすることで、オプショナルなクエリパラメータを宣言できます:
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial002.py!}
-```
+{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *}
この場合、関数パラメータ `q` はオプショナルとなり、デフォルトでは `None` になります。
-!!! check "確認"
- パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。
+/// check | 確認
-!!! note "備考"
- FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。
+パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。
- `Optional[str]` の`Optional` はFastAPIでは使用されていません(FastAPIは`str`の部分のみ使用します)。しかし、`Optional[str]` はエディタがコードのエラーを見つけるのを助けてくれます。
+///
-## クエリパラメータの型変換
+## クエリパラメータの型変換 { #query-parameter-type-conversion }
-`bool` 型も宣言できます。これは以下の様に変換されます:
+`bool` 型も宣言でき、変換されます:
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial003.py!}
-```
+{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *}
この場合、以下にアクセスすると:
@@ -118,31 +109,28 @@ http://127.0.0.1:8000/items/foo?short=yes
もしくは、他の大文字小文字のバリエーション (アッパーケース、最初の文字だけアッパーケース、など)で、関数は `short` パラメータを `True` な `bool` 値として扱います。それ以外は `False` になります。
-## 複数のパスパラメータとクエリパラメータ
-複数のパスパラメータとクエリパラメータを同時に宣言できます。**FastAPI**は互いを区別できます。
+## 複数のパスパラメータとクエリパラメータ { #multiple-path-and-query-parameters }
+
+複数のパスパラメータとクエリパラメータを同時に宣言できます。**FastAPI**はどれがどれかを把握しています。
そして特定の順序で宣言しなくてもよいです。
名前で判別されます:
-```Python hl_lines="8 10"
-{!../../../docs_src/query_params/tutorial004.py!}
-```
+{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *}
-## 必須のクエリパラメータ
+## 必須のクエリパラメータ { #required-query-parameters }
-パスパラメータ以外のパラメータ (今のところ、クエリパラメータのみ説明しました) のデフォルト値を宣言した場合、そのパラメータは必須ではなくなります。
+パスパラメータ以外のパラメータ (今のところ、クエリパラメータのみ見てきました) のデフォルト値を宣言した場合、そのパラメータは必須ではなくなります。
特定の値を与えずにただオプショナルにしたい場合はデフォルト値を `None` にして下さい。
しかしクエリパラメータを必須にしたい場合は、ただデフォルト値を宣言しなければよいです:
-```Python hl_lines="6-7"
-{!../../../docs_src/query_params/tutorial005.py!}
-```
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
-ここで、クエリパラメータ `needy` は `str` 型の必須のクエリパラメータです
+ここで、クエリパラメータ `needy` は `str` 型の必須のクエリパラメータです。
以下のURLをブラウザで開くと:
@@ -154,16 +142,17 @@ http://127.0.0.1:8000/items/foo-item
```JSON
{
- "detail": [
- {
- "loc": [
- "query",
- "needy"
- ],
- "msg": "field required",
- "type": "value_error.missing"
- }
- ]
+ "detail": [
+ {
+ "type": "missing",
+ "loc": [
+ "query",
+ "needy"
+ ],
+ "msg": "Field required",
+ "input": null
+ }
+ ]
}
```
@@ -182,11 +171,9 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
}
```
-そして当然、あるパラメータを必須に、別のパラメータにデフォルト値を設定し、また別のパラメータをオプショナルにできます:
+そして当然、あるパラメータを必須に、あるパラメータにデフォルト値を設定し、またあるパラメータを完全にオプショナルにできます:
-```Python hl_lines="10"
-{!../../../docs_src/query_params/tutorial006.py!}
-```
+{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *}
この場合、3つのクエリパラメータがあります。:
@@ -194,6 +181,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
* `skip`、デフォルト値を `0` とする `int` 。
* `limit`、オプショナルな `int` 。
-!!! tip "豆知識"
+/// tip | 豆知識
+
+[パスパラメータ](path-params.md#predefined-values)と同様に `Enum` を使用できます。
- [パスパラメータ](path-params.md#predefined-values){.internal-link target=_blank}と同様に `Enum` を使用できます。
+///
diff --git a/docs/ja/docs/tutorial/request-files.md b/docs/ja/docs/tutorial/request-files.md
new file mode 100644
index 0000000000000..30a494afb015a
--- /dev/null
+++ b/docs/ja/docs/tutorial/request-files.md
@@ -0,0 +1,176 @@
+# リクエストファイル { #request-files }
+
+`File` を使って、クライアントがアップロードするファイルを定義できます。
+
+/// info | 情報
+
+アップロードされたファイルを受け取るには、まず [`python-multipart`](https://github.com/Kludex/python-multipart) をインストールします。
+
+[仮想環境](../virtual-environments.md)を作成して有効化し、次のようにインストールしてください:
+
+```console
+$ pip install python-multipart
+```
+
+アップロードされたファイルは「form data」として送信されるためです。
+
+///
+
+## `File` をインポート { #import-file }
+
+`fastapi` から `File` と `UploadFile` をインポートします:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
+
+## `File` パラメータの定義 { #define-file-parameters }
+
+`Body` や `Form` と同様の方法でファイルのパラメータを作成します:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
+
+/// info | 情報
+
+`File` は `Form` を直接継承したクラスです。
+
+ただし、`fastapi` から `Query`、`Path`、`File` などをインポートするとき、それらは実際には特殊なクラスを返す関数であることに注意してください。
+
+///
+
+/// tip | 豆知識
+
+ファイルのボディを宣言するには `File` を使う必要があります。そうしないと、パラメータはクエリパラメータやボディ(JSON)パラメータとして解釈されます。
+
+///
+
+ファイルは「form data」としてアップロードされます。
+
+*path operation 関数* のパラメータの型を `bytes` として宣言すると、**FastAPI** がファイルを読み取り、内容を `bytes` として受け取ります。
+
+これは内容全体がメモリに保持されることを意味します。小さなファイルには有効です。
+
+しかし、多くの場合は `UploadFile` を使う方が有利です。
+
+## `UploadFile` によるファイルパラメータ { #file-parameters-with-uploadfile }
+
+型を `UploadFile` にしてファイルパラメータを定義します:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
+
+`UploadFile` を使うことには `bytes` に対する次の利点があります:
+
+- パラメータのデフォルト値に `File()` を使う必要がありません。
+- 「spooled」ファイルを使います:
+ - 最大サイズまではメモリに保持し、それを超えるとディスクに格納されるファイルです。
+- そのため、画像・動画・大きなバイナリなどの大きなファイルでも、メモリを使い果たすことなくうまく動作します。
+- アップロードされたファイルからメタデータを取得できます。
+- [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) な `async` インターフェースを持ちます。
+- 実際の Python の [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) オブジェクトを公開しており、file-like オブジェクトを期待する他のライブラリにそのまま渡せます。
+
+### `UploadFile` { #uploadfile }
+
+`UploadFile` には次の属性があります:
+
+- `filename`: アップロード時の元のファイル名を表す `str`(例: `myimage.jpg`)
+- `content_type`: コンテントタイプ(MIME タイプ / メディアタイプ)を表す `str`(例: `image/jpeg`)
+- `file`: [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile)([file-like](https://docs.python.org/3/glossary.html#term-file-like-object) なオブジェクト)。これは実際の Python のファイルオブジェクトで、「file-like」オブジェクトを期待する関数やライブラリに直接渡せます。
+
+`UploadFile` には次の `async` メソッドがあります。いずれも内部で対応するファイルメソッド(内部の `SpooledTemporaryFile`)を呼び出します。
+
+- `write(data)`: `data`(`str` または `bytes`)を書き込みます。
+- `read(size)`: `size`(`int`)バイト/文字を読み込みます。
+- `seek(offset)`: ファイル内のバイト位置 `offset`(`int`)に移動します。
+ - 例: `await myfile.seek(0)` はファイルの先頭に移動します。
+ - 一度 `await myfile.read()` を実行して、もう一度内容を読みたい場合に特に便利です。
+- `close()`: ファイルを閉じます。
+
+これらはすべて `async` メソッドなので、`await` する必要があります。
+
+例えば、`async` の *path operation 関数* 内では次のように内容を取得できます:
+
+```Python
+contents = await myfile.read()
+```
+
+通常の `def` の *path operation 関数* 内にいる場合は、`UploadFile.file` に直接アクセスできます。例えば:
+
+```Python
+contents = myfile.file.read()
+```
+
+/// note | `async` の技術詳細
+
+`async` メソッドを使うと、**FastAPI** はファイルメソッドをスレッドプールで実行し、その完了を待機します。
+
+///
+
+/// note | Starlette の技術詳細
+
+**FastAPI** の `UploadFile` は **Starlette** の `UploadFile` を直接継承していますが、**Pydantic** や FastAPI の他の部分と互換にするために必要な要素を追加しています。
+
+///
+
+## 「Form Data」とは { #what-is-form-data }
+
+HTML フォーム(``)がサーバーにデータを送る方法は、そのデータに対して通常「特別な」エンコーディングを用い、JSON とは異なります。
+
+**FastAPI** は JSON ではなく、適切な場所からそのデータを読み取るようにします。
+
+/// note | 技術詳細
+
+ファイルを含まない場合、フォームからのデータは通常「メディアタイプ」`application/x-www-form-urlencoded` でエンコードされます。
+
+ただしフォームにファイルが含まれる場合は、`multipart/form-data` としてエンコードされます。`File` を使うと、**FastAPI** はボディ内の正しい部分からファイルを取得すべきであると認識します。
+
+これらのエンコーディングやフォームフィールドの詳細は、[MDN Web Docs の `POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) を参照してください。
+
+///
+
+/// warning | 注意
+
+1 つの *path operation* に複数の `File` および `Form` パラメータを宣言できますが、同時に JSON として受け取ることを期待する `Body` フィールドを宣言することはできません。リクエストのボディは `application/json` ではなく `multipart/form-data` でエンコードされるためです。
+
+これは **FastAPI** の制限ではなく、HTTP プロトコルの仕様です。
+
+///
+
+## 任意のファイルアップロード { #optional-file-upload }
+
+標準の型アノテーションを使い、デフォルト値を `None` に設定することで、ファイルを任意にできます:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## 追加メタデータつきの `UploadFile` { #uploadfile-with-additional-metadata }
+
+例えば追加のメタデータを設定するために、`UploadFile` と併せて `File()` を使うこともできます:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
+
+## 複数ファイルのアップロード { #multiple-file-uploads }
+
+同時に複数のファイルをアップロードできます。
+
+それらは「form data」で送信される同じ「フォームフィールド」に関連付けられます。
+
+そのためには、`bytes` または `UploadFile` のリストを宣言します:
+
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
+
+宣言どおり、`bytes` または `UploadFile` の `list` を受け取ります。
+
+/// note | 技術詳細
+
+`from starlette.responses import HTMLResponse` を使うこともできます。
+
+**FastAPI** は利便性のため、`starlette.responses` と同じものを `fastapi.responses` として提供しています。ただし、利用可能なレスポンスの多くは Starlette から直接提供されています。
+
+///
+
+### 追加メタデータつきの複数ファイルアップロード { #multiple-file-uploads-with-additional-metadata }
+
+先ほどと同様に、`UploadFile` に対しても `File()` を使って追加のパラメータを設定できます:
+
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
+
+## まとめ { #recap }
+
+リクエストでフォームデータとして送信されるアップロードファイルを宣言するには、`File`、`bytes`、`UploadFile` を使います。
diff --git a/docs/ja/docs/tutorial/request-form-models.md b/docs/ja/docs/tutorial/request-form-models.md
new file mode 100644
index 0000000000000..62aa9e29856bb
--- /dev/null
+++ b/docs/ja/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# フォームモデル { #form-models }
+
+FastAPI では、フォームフィールドを宣言するために **Pydantic モデル**を使用できます。
+
+/// info | 情報
+
+フォームを使うには、まず [`python-multipart`](https://github.com/Kludex/python-multipart) をインストールします。
+
+まず [仮想環境](../virtual-environments.md) を作成して有効化し、そのうえでインストールしてください。例えば:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | 備考
+
+これは FastAPI バージョン `0.113.0` 以降でサポートされています。🤓
+
+///
+
+## フォーム用の Pydantic モデル { #pydantic-models-for-forms }
+
+受け取りたいフィールドを **フォームフィールド** として持つ **Pydantic モデル** を宣言し、パラメータを `Form` として宣言するだけです:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
+
+**FastAPI** はリクエストの **フォームデータ** から **各フィールド** のデータを **抽出** し、定義した Pydantic モデルとして渡します。
+
+## ドキュメントで確認 { #check-the-docs }
+
+`/docs` のドキュメント UI で確認できます:
+
+
+POSTのウェブドキュメントを参照してください。
+*path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/x-www-form-urlencoded`の代わりに`application/json`を使ってボディをエンコードするからです。
-!!! warning "注意"
- *path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。
+これは **FastAPI**の制限ではなく、HTTPプロトコルの一部です。
- これは **FastAPI**の制限ではなく、HTTPプロトコルの一部です。
+///
-## まとめ
+## まとめ { #recap }
フォームデータの入力パラメータを宣言するには、`Form`を使用する。
diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md
new file mode 100644
index 0000000000000..b4024e0a02d0e
--- /dev/null
+++ b/docs/ja/docs/tutorial/response-model.md
@@ -0,0 +1,344 @@
+# レスポンスモデル - 戻り値の型 { #response-model-return-type }
+
+*path operation 関数*の**戻り値の型**にアノテーションを付けることで、レスポンスに使用される型を宣言できます。
+
+関数**パラメータ**の入力データと同じように **型アノテーション** を使用できます。Pydanticモデル、リスト、辞書、整数や真偽値などのスカラー値を使用できます。
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+FastAPIはこの戻り値の型を使って以下を行います:
+
+* 返却データを**検証**します。
+ * データが不正(例: フィールドが欠けている)であれば、それは*あなた*のアプリコードが壊れていて、返すべきものを返していないことを意味し、不正なデータを返す代わりにサーバーエラーを返します。これにより、あなたとクライアントは、期待されるデータとデータ形状を受け取れることを確実にできます。
+* OpenAPIの *path operation* に、レスポンス用の **JSON Schema** を追加します。
+ * これは**自動ドキュメント**で使用されます。
+ * 自動クライアントコード生成ツールでも使用されます。
+* 返却データを Pydantic を使ってJSONに**シリアライズ**します。Pydantic は内部が**Rust**で実装されているため、**非常に高速**です。
+
+しかし、最も重要なのは:
+
+* 戻り値の型で定義された内容に合わせて、出力データを**制限しフィルタリング**します。
+ * これは**セキュリティ**の観点で特に重要です。以下で詳しく見ていきます。
+
+## `response_model`パラメータ { #response-model-parameter }
+
+型が宣言している内容とまったく同じではないデータを返す必要がある、またはそうしたいケースがあります。
+
+例えば、**辞書を返す**、またはデータベースオブジェクトを返したいが、**Pydanticモデルとして宣言**したい場合があります。こうすることで、Pydanticモデルが返したオブジェクト(例: 辞書やデータベースオブジェクト)のドキュメント化、バリデーションなどをすべて行ってくれます。
+
+戻り値の型アノテーションを追加すると、ツールやエディタが(正しく)エラーとして、関数が宣言した型(例: Pydanticモデル)とは異なる型(例: dict)を返していると警告します。
+
+そのような場合、戻り値の型の代わりに、*path operation デコレータ*のパラメータ `response_model` を使用できます。
+
+`response_model`パラメータは、いずれの *path operation* でも使用できます:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* など。
+
+{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *}
+
+/// note | 備考
+
+`response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータです。関数のパラメータやボディなどとは違い、*path operation 関数*のパラメータではありません。
+
+///
+
+`response_model`は、Pydanticモデルのフィールドで宣言するのと同じ型を受け取ります。そのため、Pydanticモデルにもできますし、例えば `List[Item]` のように、Pydanticモデルの `list` にもできます。
+
+FastAPIはこの `response_model` を使って、データのドキュメント化や検証などを行い、さらに出力データを型宣言に合わせて**変換・フィルタリング**します。
+
+/// tip | 豆知識
+
+エディタやmypyなどで厳密な型チェックをしている場合、関数の戻り値の型を `Any` として宣言できます。
+
+そうすると、意図的に何でも返していることをエディタに伝えられます。それでもFastAPIは `response_model` を使って、データのドキュメント化、検証、フィルタリングなどを行います。
+
+///
+
+### `response_model`の優先順位 { #response-model-priority }
+
+戻り値の型と `response_model` の両方を宣言した場合、`response_model` が優先され、FastAPIで使用されます。
+
+これにより、レスポンスモデルとは異なる型を返している場合でも、エディタやmypyなどのツールで使用するために関数へ正しい型アノテーションを追加できます。それでもFastAPIは `response_model` を使用してデータの検証やドキュメント化などを実行できます。
+
+また `response_model=None` を使用して、その*path operation*のレスポンスモデル生成を無効化することもできます。これは、Pydanticのフィールドとして有効ではないものに対して型アノテーションを追加する場合に必要になることがあります。以下のセクションのいずれかで例を示します。
+
+## 同じ入力データの返却 { #return-the-same-input-data }
+
+ここでは `UserIn` モデルを宣言しています。これには平文のパスワードが含まれます:
+
+{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *}
+
+/// info | 情報
+
+`EmailStr` を使用するには、最初に [`email-validator`](https://github.com/JoshData/python-email-validator) をインストールしてください。
+
+[仮想環境](../virtual-environments.md)を作成して有効化してから、例えば次のようにインストールしてください:
+
+```console
+$ pip install email-validator
+```
+
+または次のようにします:
+
+```console
+$ pip install "pydantic[email]"
+```
+
+///
+
+そして、このモデルを使用して入力を宣言し、同じモデルを使って出力を宣言しています:
+
+{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *}
+
+これで、ブラウザがパスワードを使ってユーザーを作成する際に、APIがレスポンスで同じパスワードを返すようになりました。
+
+この場合、同じユーザーがパスワードを送信しているので問題ないかもしれません。
+
+しかし、同じモデルを別の*path operation*に使用すると、すべてのクライアントにユーザーのパスワードを送信してしまう可能性があります。
+
+/// danger | 警告
+
+すべての注意点を理解していて、自分が何をしているか分かっている場合を除き、ユーザーの平文のパスワードを保存したり、このようにレスポンスで送信したりしないでください。
+
+///
+
+## 出力モデルの追加 { #add-an-output-model }
+
+代わりに、平文のパスワードを持つ入力モデルと、パスワードを持たない出力モデルを作成できます:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *}
+
+ここでは、*path operation 関数*がパスワードを含む同じ入力ユーザーを返しているにもかかわらず:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *}
+
+...`response_model`を、パスワードを含まない `UserOut` モデルとして宣言しました:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *}
+
+そのため、**FastAPI** は出力モデルで宣言されていないすべてのデータをフィルタリングしてくれます(Pydanticを使用)。
+
+### `response_model`または戻り値の型 { #response-model-or-return-type }
+
+このケースでは2つのモデルが異なるため、関数の戻り値の型を `UserOut` としてアノテーションすると、エディタやツールは、異なるクラスなので不正な型を返していると警告します。
+
+そのため、この例では `response_model` パラメータで宣言する必要があります。
+
+...しかし、これを解決する方法を以下で確認しましょう。
+
+## 戻り値の型とデータフィルタリング { #return-type-and-data-filtering }
+
+前の例から続けます。**関数に1つの型をアノテーション**したい一方で、関数からは実際には**より多くのデータ**を含むものを返せるようにしたいとします。
+
+FastAPIにはレスポンスモデルを使用してデータを**フィルタリング**し続けてほしいです。つまり、関数がより多くのデータを返しても、レスポンスにはレスポンスモデルで宣言されたフィールドのみが含まれます。
+
+前の例ではクラスが異なるため `response_model` パラメータを使う必要がありました。しかしそれは、エディタやツールによる関数の戻り値の型チェックのサポートを受けられないことも意味します。
+
+しかし、このようなことが必要になる多くのケースでは、この例のようにモデルでデータの一部を**フィルタ/削除**したいだけです。
+
+そのような場合、クラスと継承を利用して関数の**型アノテーション**を活用し、エディタやツールのサポートを改善しつつ、FastAPIの**データフィルタリング**も得られます。
+
+{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *}
+
+これにより、このコードは型として正しいためエディタやmypyからのツール支援を得られますし、FastAPIによるデータフィルタリングも得られます。
+
+これはどのように動作するのでしょうか?確認してみましょう。🤓
+
+### 型アノテーションとツール支援 { #type-annotations-and-tooling }
+
+まず、エディタ、mypy、その他のツールがこれをどう見るかを見てみます。
+
+`BaseUser` には基本フィールドがあります。次に `UserIn` が `BaseUser` を継承して `password` フィールドを追加するため、両方のモデルのフィールドがすべて含まれます。
+
+関数の戻り値の型を `BaseUser` としてアノテーションしますが、実際には `UserIn` インスタンスを返しています。
+
+エディタやmypyなどのツールはこれに文句を言いません。typingの観点では、`UserIn` は `BaseUser` のサブクラスであり、期待されるものが `BaseUser` であれば `UserIn` は*有効*な型だからです。
+
+### FastAPIのデータフィルタリング { #fastapi-data-filtering }
+
+一方FastAPIでは、戻り値の型を見て、返す内容にその型で宣言されたフィールド**だけ**が含まれることを確認します。
+
+FastAPIは、返却データのフィルタリングにクラス継承の同じルールが使われてしまわないようにするため、内部でPydanticを使っていくつかの処理を行っています。そうでないと、期待以上に多くのデータを返してしまう可能性があります。
+
+この方法で、**ツール支援**付きの型アノテーションと**データフィルタリング**の両方という、いいとこ取りができます。
+
+## ドキュメントを見る { #see-it-in-the-docs }
+
+自動ドキュメントを見ると、入力モデルと出力モデルがそれぞれ独自のJSON Schemaを持っていることが確認できます:
+
+
+
+そして、両方のモデルは対話型のAPIドキュメントに使用されます:
+
+
+
+## その他の戻り値の型アノテーション { #other-return-type-annotations }
+
+Pydanticフィールドとして有効ではないものを返し、ツール(エディタやmypyなど)が提供するサポートを得るためだけに、関数でそれをアノテーションするケースがあるかもしれません。
+
+### レスポンスを直接返す { #return-a-response-directly }
+
+最も一般的なケースは、[高度なドキュメントで後述する「Responseを直接返す」](../advanced/response-directly.md)場合です。
+
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
+
+このシンプルなケースは、戻り値の型アノテーションが `Response` のクラス(またはサブクラス)であるため、FastAPIが自動的に処理します。
+
+また `RedirectResponse` と `JSONResponse` の両方は `Response` のサブクラスなので、ツールも型アノテーションが正しいとして問題にしません。
+
+### `Response`のサブクラスをアノテーションする { #annotate-a-response-subclass }
+
+型アノテーションで `Response` のサブクラスを使うこともできます:
+
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
+
+これは `RedirectResponse` が `Response` のサブクラスであり、FastAPIがこのシンプルなケースを自動処理するため、同様に動作します。
+
+### 無効な戻り値の型アノテーション { #invalid-return-type-annotations }
+
+しかし、Pydantic型として有効ではない別の任意のオブジェクト(例: データベースオブジェクト)を返し、関数でそのようにアノテーションすると、FastAPIはその型アノテーションからPydanticレスポンスモデルを作成しようとして失敗します。
+
+同様に、ユニオンのように、複数の型のうち1つ以上がPydantic型として有効でないものを含む場合も起こります。例えば次は失敗します 💥:
+
+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
+
+...これは、型アノテーションがPydantic型ではなく、単一の `Response` クラス(またはサブクラス)でもないために失敗します。`Response` と `dict` の間のunion(どちらか)になっているからです。
+
+### レスポンスモデルを無効化する { #disable-response-model }
+
+上の例を続けると、FastAPIが実行するデフォルトのデータ検証、ドキュメント化、フィルタリングなどを行いたくないこともあるでしょう。
+
+しかし、エディタや型チェッカー(例: mypy)などのツール支援を得るために、関数の戻り値の型アノテーションは残したいかもしれません。
+
+その場合、`response_model=None` を設定することでレスポンスモデルの生成を無効にできます:
+
+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}
+
+これによりFastAPIはレスポンスモデル生成をスキップし、FastAPIアプリケーションに影響させずに必要な戻り値の型アノテーションを付けられます。🤓
+
+## レスポンスモデルのエンコーディングパラメータ { #response-model-encoding-parameters }
+
+レスポンスモデルには次のようにデフォルト値を設定できます:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}
+
+* `description: Union[str, None] = None`(またはPython 3.10では `str | None = None`)はデフォルトが `None` です。
+* `tax: float = 10.5` はデフォルトが `10.5` です。
+* `tags: List[str] = []` はデフォルトが空のリスト `[]` です。
+
+ただし、それらが実際には保存されていない場合、結果から省略したいことがあります。
+
+例えば、NoSQLデータベースに多くのオプション属性を持つモデルがあるが、デフォルト値でいっぱいの非常に長いJSONレスポンスを送信したくない場合です。
+
+### `response_model_exclude_unset`パラメータの使用 { #use-the-response-model-exclude-unset-parameter }
+
+*path operation デコレータ*のパラメータ `response_model_exclude_unset=True` を設定できます:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}
+
+そうすると、デフォルト値はレスポンスに含まれず、実際に設定された値のみが含まれます。
+
+そのため、ID `foo` のitemに対してその *path operation* へリクエストを送ると、レスポンスは以下のようになります(デフォルト値を含まない):
+
+```JSON
+{
+ "name": "Foo",
+ "price": 50.2
+}
+```
+
+/// info | 情報
+
+以下も使用できます:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+`exclude_defaults` と `exclude_none` については、[Pydanticのドキュメント](https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict)で説明されている通りです。
+
+///
+
+#### デフォルト値を持つフィールドに値があるデータ { #data-with-values-for-fields-with-defaults }
+
+しかし、ID `bar` のitemのように、デフォルト値が設定されているモデルのフィールドに値が設定されている場合:
+
+```Python hl_lines="3 5"
+{
+ "name": "Bar",
+ "description": "The bartenders",
+ "price": 62,
+ "tax": 20.2
+}
+```
+
+それらはレスポンスに含まれます。
+
+#### デフォルト値と同じ値を持つデータ { #data-with-the-same-values-as-the-defaults }
+
+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` { #response-model-include-and-response-model-exclude }
+
+*path operation デコレータ*のパラメータ `response_model_include` と `response_model_exclude` も使用できます。
+
+これらは、含める(残りを省略する)または除外する(残りを含む)属性名を持つ `str` の `set` を受け取ります。
+
+これは、Pydanticモデルが1つしかなく、出力からいくつかのデータを削除したい場合のクイックショートカットとして使用できます。
+
+/// tip | 豆知識
+
+それでも、これらのパラメータではなく、上で示したアイデアのように複数のクラスを使うことが推奨されます。
+
+これは、`response_model_include` や `response_model_exclude` を使っていくつかの属性を省略しても、アプリのOpenAPI(とドキュメント)で生成されるJSON Schemaが完全なモデルのままになるためです。
+
+同様に動作する `response_model_by_alias` にも当てはまります。
+
+///
+
+{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}
+
+/// tip | 豆知識
+
+`{"name", "description"}` の構文は、それら2つの値を持つ `set` を作成します。
+
+これは `set(["name", "description"])` と同等です。
+
+///
+
+#### `set`の代わりに`list`を使用する { #using-lists-instead-of-sets }
+
+もし `set` を使用することを忘れて、代わりに `list` や `tuple` を使用しても、FastAPIはそれを `set` に変換して正しく動作します:
+
+{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}
+
+## まとめ { #recap }
+
+*path operation デコレータ*のパラメータ `response_model` を使用してレスポンスモデルを定義し、とくにプライベートデータがフィルタリングされることを保証します。
+
+明示的に設定された値のみを返すには、`response_model_exclude_unset` を使用します。
diff --git a/docs/ja/docs/tutorial/response-status-code.md b/docs/ja/docs/tutorial/response-status-code.md
new file mode 100644
index 0000000000000..9237ac784d6f2
--- /dev/null
+++ b/docs/ja/docs/tutorial/response-status-code.md
@@ -0,0 +1,101 @@
+# レスポンスステータスコード { #response-status-code }
+
+レスポンスモデルを指定するのと同じ方法で、レスポンスに使用されるHTTPステータスコードを以下の*path operations*のいずれかの`status_code`パラメータで宣言することもできます。
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* etc.
+
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
+
+/// note | 備考
+
+`status_code`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation function*のものではありません。
+
+///
+
+`status_code`パラメータはHTTPステータスコードを含む数値を受け取ります。
+
+/// info | 情報
+
+`status_code`は代わりに、Pythonの[`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus)のように、`IntEnum`を受け取ることもできます。
+
+///
+
+これは:
+
+* レスポンスでステータスコードを返します。
+* OpenAPIスキーマ(およびユーザーインターフェース)に以下のように文書化します:
+
+
+
+/// note | 備考
+
+いくつかのレスポンスコード(次のセクションを参照)は、レスポンスにボディがないことを示しています。
+
+FastAPIはこれを知っていて、レスポンスボディがないというOpenAPIドキュメントを生成します。
+
+///
+
+## HTTPステータスコードについて { #about-http-status-codes }
+
+/// note | 備考
+
+すでにHTTPステータスコードが何であるかを知っている場合は、次のセクションにスキップしてください。
+
+///
+
+HTTPでは、レスポンスの一部として3桁の数字のステータスコードを送信します。
+
+これらのステータスコードは、それらを認識するために関連付けられた名前を持っていますが、重要な部分は番号です。
+
+つまり:
+
+* `100 - 199` は「情報」のためのものです。直接使うことはほとんどありません。これらのステータスコードを持つレスポンスはボディを持つことができません。
+* **`200 - 299`** は「成功」のレスポンスのためのものです。これらは最も利用するであろうものです。
+ * `200`はデフォルトのステータスコードで、すべてが「OK」であったことを意味します。
+ * 別の例としては、`201`(Created)があります。これはデータベースに新しいレコードを作成した後によく使用されます。
+ * 特殊なケースとして、`204`(No Content)があります。このレスポンスはクライアントに返すコンテンツがない場合に使用されるため、レスポンスはボディを持ってはいけません。
+* **`300 - 399`** は「リダイレクト」のためのものです。これらのステータスコードを持つレスポンスは`304`(Not Modified)を除き、ボディを持つことも持たないこともできます。`304`はボディを持ってはいけません。
+* **`400 - 499`** は「クライアントエラー」のレスポンスのためのものです。これらは、おそらく最も多用するであろう2番目のタイプです。
+ * 例えば、`404`は「Not Found」レスポンスです。
+ * クライアントからの一般的なエラーについては、`400`を使用することができます。
+* `500 - 599` はサーバーエラーのためのものです。これらを直接使うことはほとんどありません。アプリケーションコードやサーバーのどこかで何か問題が発生した場合、これらのステータスコードのいずれかが自動的に返されます。
+
+/// tip | 豆知識
+
+それぞれのステータスコードとどのコードが何のためのコードなのかについての詳細は、[MDN のHTTPステータスコードに関するドキュメント](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)を参照してください。
+
+///
+
+## 名前を覚えるための近道 { #shortcut-to-remember-the-names }
+
+先ほどの例をもう一度見てみましょう:
+
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
+
+`201`は「作成完了」のためのステータスコードです。
+
+しかし、それぞれのコードの意味を暗記する必要はありません。
+
+`fastapi.status`の便利な変数を利用することができます。
+
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
+
+それらは単なる便利なものであり、同じ番号を保持しています。しかし、その方法ではエディタの自動補完を使用してそれらを見つけることができます。
+
+
+
+/// note | 技術詳細
+
+また、`from starlette import status`を使うこともできます。
+
+**FastAPI** は、開発者の利便性を考慮して、fastapi.statusと同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。
+
+///
+
+## デフォルトの変更 { #changing-the-default }
+
+後に、[高度なユーザーガイド](../advanced/response-change-status-code.md)で、ここで宣言しているデフォルトとは異なるステータスコードを返す方法を見ていきます。
diff --git a/docs/ja/docs/tutorial/schema-extra-example.md b/docs/ja/docs/tutorial/schema-extra-example.md
new file mode 100644
index 0000000000000..87ee85f4025a3
--- /dev/null
+++ b/docs/ja/docs/tutorial/schema-extra-example.md
@@ -0,0 +1,202 @@
+# リクエストのExampleデータの宣言 { #declare-request-example-data }
+
+アプリが受け取れるデータの例を宣言できます。
+
+ここでは、それを行ういくつかの方法を紹介します。
+
+## Pydanticモデルでの追加JSON Schemaデータ { #extra-json-schema-data-in-pydantic-models }
+
+生成されるJSON Schemaに追加されるPydanticモデルの`examples`を宣言できます。
+
+{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}
+
+その追加情報は、そのモデルの出力**JSON Schema**にそのまま追加され、APIドキュメントで使用されます。
+
+[Pydanticのドキュメント: Configuration](https://docs.pydantic.dev/latest/api/config/)で説明されているように、`dict`を受け取る属性`model_config`を使用できます。
+
+生成されるJSON Schemaに表示したい追加データ(`examples`を含む)を含む`dict`を使って、`"json_schema_extra"`を設定できます。
+
+/// tip | 豆知識
+
+同じ手法を使ってJSON Schemaを拡張し、独自のカスタム追加情報を追加できます。
+
+例えば、フロントエンドのユーザーインターフェースのためのメタデータを追加する、などに使えます。
+
+///
+
+/// info | 情報
+
+OpenAPI 3.1.0(FastAPI 0.99.0以降で使用)では、**JSON Schema**標準の一部である`examples`がサポートされました。
+
+それ以前は、単一の例を持つキーワード`example`のみがサポートされていました。これはOpenAPI 3.1.0でも引き続きサポートされていますが、非推奨であり、JSON Schema標準の一部ではありません。そのため、`example`から`examples`への移行が推奨されます。🤓
+
+詳細はこのページの最後で読めます。
+
+///
+
+## `Field`の追加引数 { #field-additional-arguments }
+
+Pydanticモデルで`Field()`を使う場合、追加の`examples`も宣言できます:
+
+{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}
+
+## JSON Schema内の`examples` - OpenAPI { #examples-in-json-schema-openapi }
+
+以下のいずれかを使用する場合:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+追加情報を含む`examples`のグループを宣言でき、それらは**OpenAPI**内のそれぞれの**JSON Schemas**に追加されます。
+
+### `examples`を使う`Body` { #body-with-examples }
+
+ここでは、`Body()`で期待されるデータの例を1つ含む`examples`を渡します:
+
+{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *}
+
+### ドキュメントUIでの例 { #example-in-the-docs-ui }
+
+上記のいずれの方法でも、`/docs`の中では以下のようになります:
+
+
+
+### 複数の`examples`を使う`Body` { #body-with-multiple-examples }
+
+もちろん、複数の`examples`を渡すこともできます:
+
+{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *}
+
+この場合、examplesはそのボディデータの内部**JSON Schema**の一部になります。
+
+それでも、執筆時点では、ドキュメントUIの表示を担当するツールであるSwagger UIは、**JSON Schema**内のデータに対して複数の例を表示することをサポートしていません。しかし、回避策については以下を読んでください。
+
+### OpenAPI固有の`examples` { #openapi-specific-examples }
+
+**JSON Schema**が`examples`をサポートする前から、OpenAPIは同じく`examples`という別のフィールドをサポートしていました。
+
+この**OpenAPI固有**の`examples`は、OpenAPI仕様の別のセクションに入ります。各JSON Schemaの中ではなく、**各*path operation*の詳細**に入ります。
+
+そしてSwagger UIは、この特定の`examples`フィールドを以前からサポートしています。そのため、これを使って**ドキュメントUIに異なる例を表示**できます。
+
+このOpenAPI固有フィールド`examples`の形は**複数の例**(`list`ではなく)を持つ`dict`であり、それぞれに追加情報が含まれ、その追加情報は**OpenAPI**にも追加されます。
+
+これはOpenAPIに含まれる各JSON Schemaの中には入らず、外側の、*path operation*に直接入ります。
+
+### `openapi_examples`パラメータの使用 { #using-the-openapi-examples-parameter }
+
+FastAPIでは、以下に対してパラメータ`openapi_examples`を使って、OpenAPI固有の`examples`を宣言できます:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+`dict`のキーは各例を識別し、各値は別の`dict`です。
+
+`examples`内の各特定の例`dict`には、次の内容を含められます:
+
+* `summary`: 例の短い説明。
+* `description`: Markdownテキストを含められる長い説明。
+* `value`: 実際に表示される例(例: `dict`)。
+* `externalValue`: `value`の代替で、例を指すURLです。ただし、`value`ほど多くのツールでサポートされていない可能性があります。
+
+次のように使えます:
+
+{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *}
+
+### ドキュメントUIのOpenAPI Examples { #openapi-examples-in-the-docs-ui }
+
+`Body()`に`openapi_examples`を追加すると、`/docs`は次のようになります:
+
+
+
+## 技術詳細 { #technical-details }
+
+/// tip | 豆知識
+
+すでに**FastAPI**バージョン**0.99.0以上**を使用している場合、おそらくこれらの詳細は**スキップ**できます。
+
+これらは、OpenAPI 3.1.0が利用可能になる前の古いバージョンにより関連します。
+
+これは簡単なOpenAPIとJSON Schemaの**歴史の授業**だと考えられます。🤓
+
+///
+
+/// warning | 注意
+
+ここでは、標準である**JSON Schema**と**OpenAPI**についての非常に技術的な詳細を扱います。
+
+上のアイデアがすでにうまく動いているなら、それで十分かもしれませんし、おそらくこの詳細は不要です。気軽にスキップしてください。
+
+///
+
+OpenAPI 3.1.0より前は、OpenAPIは古く改変されたバージョンの**JSON Schema**を使用していました。
+
+JSON Schemaには`examples`がなかったため、OpenAPIは自身が改変したバージョンに独自の`example`フィールドを追加しました。
+
+OpenAPIは、仕様の他の部分にも`example`と`examples`フィールドを追加しました:
+
+* [`Parameter Object`(仕様内)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object)。FastAPIの以下で使用されました:
+ * `Path()`
+ * `Query()`
+ * `Header()`
+ * `Cookie()`
+* [`Request Body Object`、`Media Type Object`の`content`フィールド(仕様内)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object)。FastAPIの以下で使用されました:
+ * `Body()`
+ * `File()`
+ * `Form()`
+
+/// info | 情報
+
+この古いOpenAPI固有の`examples`パラメータは、FastAPI `0.103.0`以降は`openapi_examples`になりました。
+
+///
+
+### JSON Schemaの`examples`フィールド { #json-schemas-examples-field }
+
+しかしその後、JSON Schemaは新しいバージョンの仕様に[`examples`](https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.9.5)フィールドを追加しました。
+
+そして、新しいOpenAPI 3.1.0は、この新しいフィールド`examples`を含む最新バージョン(JSON Schema 2020-12)に基づくようになりました。
+
+そして現在、この新しい`examples`フィールドは、古い単一(かつカスタム)の`example`フィールドより優先され、`example`は現在非推奨です。
+
+JSON Schemaのこの新しい`examples`フィールドは、OpenAPIの他の場所(上で説明)にあるような追加メタデータを持つdictではなく、**単なる例の`list`**です。
+
+/// info | 情報
+
+OpenAPI 3.1.0がこのJSON Schemaとの新しいよりシンプルな統合とともにリリースされた後も、しばらくの間、自動ドキュメントを提供するツールであるSwagger UIはOpenAPI 3.1.0をサポートしていませんでした(バージョン5.0.0からサポートされています🎉)。
+
+そのため、FastAPI 0.99.0より前のバージョンは、OpenAPI 3.1.0より低いバージョンのOpenAPIをまだ使用していました。
+
+///
+
+### PydanticとFastAPIの`examples` { #pydantic-and-fastapi-examples }
+
+Pydanticモデル内で、`schema_extra`または`Field(examples=["something"])`を使って`examples`を追加すると、その例はそのPydanticモデルの**JSON Schema**に追加されます。
+
+そしてそのPydanticモデルの**JSON Schema**はAPIの**OpenAPI**に含まれ、ドキュメントUIで使用されます。
+
+FastAPI 0.99.0より前のバージョン(0.99.0以上は新しいOpenAPI 3.1.0を使用)では、他のユーティリティ(`Query()`、`Body()`など)で`example`または`examples`を使っても、それらの例はそのデータを説明するJSON Schema(OpenAPI独自版のJSON Schemaでさえ)には追加されず、OpenAPI内の*path operation*宣言に直接追加されていました(JSON Schemaを使用するOpenAPIの部分の外側)。
+
+しかし、FastAPI 0.99.0以上ではOpenAPI 3.1.0を使用し、それはJSON Schema 2020-12とSwagger UI 5.0.0以上を使うため、すべてがより一貫し、例はJSON Schemaに含まれます。
+
+### Swagger UIとOpenAPI固有の`examples` { #swagger-ui-and-openapi-specific-examples }
+
+Swagger UIは複数のJSON Schema examplesをサポートしていなかった(2023-08-26時点)ため、ユーザーはドキュメントで複数の例を表示する手段がありませんでした。
+
+それを解決するため、FastAPI `0.103.0`は、新しいパラメータ`openapi_examples`で、同じ古い**OpenAPI固有**の`examples`フィールドを宣言するための**サポートを追加**しました。🤓
+
+### まとめ { #summary }
+
+昔は歴史があまり好きではないと言っていました...が、今の私は「技術の歴史」の授業をしています。😅
+
+要するに、**FastAPI 0.99.0以上にアップグレード**してください。そうすれば、物事はもっと**シンプルで一貫性があり直感的**になり、これらの歴史的詳細を知る必要もありません。😎
diff --git a/docs/ja/docs/tutorial/security/first-steps.md b/docs/ja/docs/tutorial/security/first-steps.md
index f83b59cfd124b..e678ebce1cb02 100644
--- a/docs/ja/docs/tutorial/security/first-steps.md
+++ b/docs/ja/docs/tutorial/security/first-steps.md
@@ -1,4 +1,4 @@
-# セキュリティ - 最初の一歩
+# セキュリティ - 最初の一歩 { #security-first-steps }
あるドメインに、**バックエンド** APIを持っているとしましょう。
@@ -12,58 +12,71 @@
**FastAPI**が提供するツールを使って、セキュリティを制御してみましょう。
-## どう見えるか
+## どう見えるか { #how-it-looks }
まずはこのコードを使って、どう動くか観察します。その後で、何が起こっているのか理解しましょう。
-## `main.py`を作成
+## `main.py`を作成 { #create-main-py }
`main.py`に、下記の例をコピーします:
-```Python
-{!../../../docs_src/security/tutorial001.py!}
-```
+{* ../../docs_src/security/tutorial001_an_py310.py *}
+
+## 実行 { #run-it }
-## 実行
+/// info | 情報
-!!! info "情報"
- まず`python-multipart`をインストールします。
+[`python-multipart`](https://github.com/Kludex/python-multipart) パッケージは、`pip install "fastapi[standard]"` コマンドを実行すると **FastAPI** と一緒に自動的にインストールされます。
- 例えば、`pip install python-multipart`。
+しかし、`pip install fastapi` コマンドを使用する場合、`python-multipart` パッケージはデフォルトでは含まれません。
- これは、**OAuth2**が `ユーザー名` や `パスワード` を送信するために、「フォームデータ」を使うからです。
+手動でインストールするには、[仮想環境](../../virtual-environments.md)を作成して有効化し、次のコマンドでインストールしてください:
+
+```console
+$ pip install python-multipart
+```
+
+これは、**OAuth2**が `username` と `password` を送信するために、「フォームデータ」を使うからです。
+
+///
例を実行します:
-!!! check "Authorizeボタン!"
- すでにピカピカの新しい「Authorize」ボタンがあります。
+/// check | Authorizeボタン!
+
+すでにピカピカの新しい「Authorize」ボタンがあります。
- そして、あなたの*path operation*には、右上にクリックできる小さな鍵アイコンがあります。
+そして、あなたの*path operation*には、右上にクリックできる小さな鍵アイコンがあります。
-それをクリックすると、`ユーザー名`と`パスワード` (およびその他のオプションフィールド) を入力する小さな認証フォームが表示されます:
+///
+
+それをクリックすると、`username` と `password`(およびその他のオプションフィールド)を入力する小さな認可フォームが表示されます:
-!!! note "備考"
- フォームに何を入力しても、まだうまくいきません。ですが、これから動くようになります。
+/// note | 備考
+
+フォームに何を入力しても、まだうまくいきません。ですが、これから動くようになります。
+
+///
もちろんエンドユーザーのためのフロントエンドではありません。しかし、すべてのAPIをインタラクティブにドキュメント化するための素晴らしい自動ツールです。
@@ -73,11 +86,11 @@ $ uvicorn main:app --reload
また、同じアプリケーションのデバッグ、チェック、テストのためにも利用できます。
-## `パスワード` フロー
+## `password` フロー { #the-password-flow }
では、少し話を戻して、どうなっているか理解しましょう。
-`パスワード`の「フロー」は、OAuth2で定義されているセキュリティと認証を扱う方法 (「フロー」) の1つです。
+`password`の「フロー」は、OAuth2で定義されているセキュリティと認証を扱う方法 (「フロー」) の1つです。
OAuth2は、バックエンドやAPIがユーザーを認証するサーバーから独立したものとして設計されていました。
@@ -85,9 +98,9 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー
そこで、簡略化した箇所から見直してみましょう:
-* ユーザーはフロントエンドで`ユーザー名`と`パスワード`を入力し、`Enter`を押します。
-* フロントエンド (ユーザーのブラウザで実行中) は、`ユーザー名`と`パスワード`をAPIの特定のURL (`tokenUrl="token"`で宣言された) に送信します。
-* APIは`ユーザー名`と`パスワード`をチェックし、「トークン」を返却します (まだ実装していません)。
+* ユーザーはフロントエンドで`username`と`password`を入力し、`Enter`を押します。
+* フロントエンド (ユーザーのブラウザで実行中) は、`username`と`password`をAPIの特定のURL (`tokenUrl="token"`で宣言された) に送信します。
+* APIは`username`と`password`をチェックし、「トークン」を返却します (まだ実装していません)。
* 「トークン」はただの文字列であり、あとでこのユーザーを検証するために使用します。
* 通常、トークンは時間が経つと期限切れになるように設定されています。
* トークンが期限切れの場合は、再度ログインする必要があります。
@@ -99,42 +112,49 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー
* したがって、APIで認証するため、HTTPヘッダー`Authorization`に`Bearer`の文字列とトークンを加えた値を送信します。
* トークンに`foobar`が含まれている場合、`Authorization`ヘッダーの内容は次のようになります: `Bearer foobar`。
-## **FastAPI**の`OAuth2PasswordBearer`
+## **FastAPI**の`OAuth2PasswordBearer` { #fastapis-oauth2passwordbearer }
**FastAPI**は、これらのセキュリティ機能を実装するために、抽象度の異なる複数のツールを提供しています。
-この例では、**Bearer**トークンを使用して**OAuth2**を**パスワード**フローで使用します。これには`OAuth2PasswordBearer`クラスを使用します。
+この例では、**Bearer**トークンを使用して**OAuth2**を**Password**フローで使用します。これには`OAuth2PasswordBearer`クラスを使用します。
-!!! info "情報"
- 「bearer」トークンが、唯一の選択肢ではありません。
+/// info | 情報
- しかし、私たちのユースケースには最適です。
+「bearer」トークンが、唯一の選択肢ではありません。
- あなたがOAuth2の専門家で、あなたのニーズに適した別のオプションがある理由を正確に知っている場合を除き、ほとんどのユースケースに最適かもしれません。
+しかし、私たちのユースケースには最適です。
- その場合、**FastAPI**はそれを構築するためのツールも提供します。
+あなたがOAuth2の専門家で、あなたのニーズに適した別のオプションがある理由を正確に知っている場合を除き、ほとんどのユースケースに最適かもしれません。
-`OAuth2PasswordBearer` クラスのインスタンスを作成する時に、パラメーター`tokenUrl`を渡します。このパラメーターには、クライアント (ユーザーのブラウザで動作するフロントエンド) がトークンを取得するために`ユーザー名`と`パスワード`を送信するURLを指定します。
+その場合、**FastAPI**はそれを構築するためのツールも提供します。
-```Python hl_lines="6"
-{!../../../docs_src/security/tutorial001.py!}
-```
+///
+
+`OAuth2PasswordBearer` クラスのインスタンスを作成する時に、パラメーター`tokenUrl`を渡します。このパラメーターには、クライアント (ユーザーのブラウザで動作するフロントエンド) がトークンを取得するために`username`と`password`を送信するURLを指定します。
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
+
+/// tip | 豆知識
+
+ここで、`tokenUrl="token"`は、まだ作成していない相対URL`token`を指します。相対URLなので、`./token`と同じです。
-!!! tip "豆知識"
- ここで、`tokenUrl="token"`は、まだ作成していない相対URL`token`を指します。相対URLなので、`./token`と同じです。
+相対URLを使っているので、APIが`https://example.com/`にある場合、`https://example.com/token`を参照します。しかし、APIが`https://example.com/api/v1/`にある場合は`https://example.com/api/v1/token`を参照することになります。
- 相対URLを使っているので、APIが`https://example.com/`にある場合、`https://example.com/token`を参照します。しかし、APIが`https://example.com/api/v1/`にある場合は`https://example.com/api/v1/token`を参照することになります。
+相対 URL を使うことは、[プロキシの背後](../../advanced/behind-a-proxy.md)のような高度なユースケースでもアプリケーションを動作させ続けるために重要です。
- 相対 URL を使うことは、[プロキシと接続](./.../advanced/behind-a-proxy.md){.internal-link target=_blank}のような高度なユースケースでもアプリケーションを動作させ続けるために重要です。
+///
このパラメーターはエンドポイント/ *path operation*を作成しません。しかし、URL`/token`はクライアントがトークンを取得するために使用するものであると宣言します。この情報は OpenAPI やインタラクティブな API ドキュメントシステムで使われます。
-実際のpath operationもすぐに作ります。
+実際の path operation もすぐに作ります。
-!!! info "情報"
- 非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`token_url`ではなく`tokenUrl`であることを気に入らないかもしれません。
+/// info | 情報
- それはOpenAPI仕様と同じ名前を使用しているからです。そのため、これらのセキュリティスキームについてもっと調べる必要がある場合は、それをコピーして貼り付ければ、それについての詳細な情報を見つけることができます。
+非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`tokenUrl`ではなく`token_url`であることを気に入らないかもしれません。
+
+それはOpenAPI仕様と同じ名前を使用しているからです。そのため、これらのセキュリティスキームについてもっと調べる必要がある場合は、それをコピーして貼り付ければ、それについての詳細な情報を見つけることができます。
+
+///
変数`oauth2_scheme`は`OAuth2PasswordBearer`のインスタンスですが、「呼び出し可能」です。
@@ -146,30 +166,31 @@ oauth2_scheme(some, parameters)
そのため、`Depends`と一緒に使うことができます。
-### 使い方
+### 使い方 { #use-it }
これで`oauth2_scheme`を`Depends`で依存関係に渡すことができます。
-```Python hl_lines="10"
-{!../../../docs_src/security/tutorial001.py!}
-```
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
-この依存関係は、*path operation function*のパラメーター`token`に代入される`str`を提供します。
+この依存関係は、*path operation 関数*のパラメーター`token`に代入される`str`を提供します。
**FastAPI**は、この依存関係を使用してOpenAPIスキーマ (および自動APIドキュメント) で「セキュリティスキーム」を定義できることを知っています。
-!!! info "技術詳細"
- **FastAPI**は、`OAuth2PasswordBearer` クラス (依存関係で宣言されている) を使用してOpenAPIのセキュリティスキームを定義できることを知っています。これは`fastapi.security.oauth2.OAuth2`、`fastapi.security.base.SecurityBase`を継承しているからです。
+/// info | 技術詳細
+
+**FastAPI**は、`OAuth2PasswordBearer` クラス (依存関係で宣言されている) を使用してOpenAPIのセキュリティスキームを定義できることを知っています。これは`fastapi.security.oauth2.OAuth2`、`fastapi.security.base.SecurityBase`を継承しているからです。
+
+OpenAPIと統合するセキュリティユーティリティ (および自動APIドキュメント) はすべて`SecurityBase`を継承しています。それにより、**FastAPI**はそれらをOpenAPIに統合する方法を知ることができます。
- OpenAPIと統合するセキュリティユーティリティ (および自動APIドキュメント) はすべて`SecurityBase`を継承しています。それにより、**FastAPI**はそれらをOpenAPIに統合する方法を知ることができます。
+///
-## どのように動作するか
+## 何をするか { #what-it-does }
-リクエストの中に`Authorization`ヘッダーを探しに行き、その値が`Bearer`と何らかのトークンを含んでいるかどうかをチェックし、そのトークンを`str`として返します。
+リクエストの中に`Authorization`ヘッダーを探しに行き、その値が`Bearer `と何らかのトークンを含んでいるかどうかをチェックし、そのトークンを`str`として返します。
-もし`Authorization`ヘッダーが見つからなかったり、値が`Bearer`トークンを持っていなかったりすると、401 ステータスコードエラー (`UNAUTHORIZED`) で直接応答します。
+もし`Authorization`ヘッダーが見つからなかったり、値が`Bearer `トークンを持っていなかったりすると、401 ステータスコードエラー (`UNAUTHORIZED`) で直接応答します。
-トークンが存在するかどうかをチェックしてエラーを返す必要はありません。関数が実行された場合、そのトークンに`str`が含まれているか確認できます。
+トークンが存在するかどうかをチェックしてエラーを返す必要はありません。関数が実行された場合、そのトークンに`str`が含まれていることを確信できます。
インタラクティブなドキュメントですでに試すことができます:
@@ -177,6 +198,6 @@ oauth2_scheme(some, parameters)
まだトークンの有効性を検証しているわけではありませんが、これはもう始まっています。
-## まとめ
+## まとめ { #recap }
つまり、たった3~4行の追加で、すでに何らかの基礎的なセキュリティの形になっています。
diff --git a/docs/ja/docs/tutorial/security/get-current-user.md b/docs/ja/docs/tutorial/security/get-current-user.md
new file mode 100644
index 0000000000000..60378fd9814a3
--- /dev/null
+++ b/docs/ja/docs/tutorial/security/get-current-user.md
@@ -0,0 +1,105 @@
+# 現在のユーザーの取得 { #get-current-user }
+
+一つ前の章では、(依存性注入システムに基づいた)セキュリティシステムは、 *path operation 関数* に `str` として `token` を与えていました:
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+しかし、それはまだそんなに有用ではありません。
+
+現在のユーザーを取得するようにしてみましょう。
+
+## ユーザーモデルの作成 { #create-a-user-model }
+
+まずは、Pydanticのユーザーモデルを作成しましょう。
+
+ボディを宣言するのにPydanticを使用するのと同じやり方で、Pydanticを別のどんなところでも使うことができます:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *}
+
+## 依存関係 `get_current_user` を作成 { #create-a-get-current-user-dependency }
+
+依存関係 `get_current_user` を作ってみましょう。
+
+依存関係はサブ依存関係を持つことができるのを覚えていますか?
+
+`get_current_user` は前に作成した `oauth2_scheme` と同じ依存関係を持ちます。
+
+以前直接 *path operation* の中でしていたのと同じように、新しい依存関係である `get_current_user` はサブ依存関係である `oauth2_scheme` から `str` として `token` を受け取るようになります:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *}
+
+## ユーザーの取得 { #get-the-user }
+
+`get_current_user` は作成した(偽物の)ユーティリティ関数を使って、 `str` としてトークンを受け取り、先ほどのPydanticの `User` モデルを返却します:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *}
+
+## 現在のユーザーの注入 { #inject-the-current-user }
+
+ですので、 `get_current_user` に対して同様に *path operation* の中で `Depends` を利用できます。
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *}
+
+Pydanticモデルの `User` として、 `current_user` の型を宣言することに注意してください。
+
+その関数の中ですべての入力補完や型チェックを行う際に役に立ちます。
+
+/// tip | 豆知識
+
+リクエストボディはPydanticモデルでも宣言できることを覚えているかもしれません。
+
+ここでは `Depends` を使っているおかげで、 **FastAPI** が混乱することはありません。
+
+///
+
+/// check | 確認
+
+依存関係システムがこのように設計されているおかげで、 `User` モデルを返却する別の依存関係(別の「dependables」)を持つことができます。
+
+同じデータ型を返却する依存関係は一つだけしか持てない、という制約が入ることはないのです。
+
+///
+
+## 別のモデル { #other-models }
+
+これで、*path operation 関数* の中で現在のユーザーを直接取得し、`Depends` を使って、 **依存性注入** レベルでセキュリティメカニズムを処理できるようになりました。
+
+そして、セキュリティ要件のためにどんなモデルやデータでも利用することができます。(この場合は、 Pydanticモデルの `User`)
+
+しかし、特定のデータモデルやクラス、型に制限されることはありません。
+
+モデルを、 `id` と `email` は持つが、 `username` は全く持たないようにしたいですか? わかりました。同じ手段でこうしたこともできます。
+
+ある `str` だけを持ちたい? あるいはある `dict` だけですか? それとも、データベースクラスのモデルインスタンスを直接持ちたいですか? すべて同じやり方で機能します。
+
+実際には、あなたのアプリケーションにはログインするようなユーザーはおらず、単にアクセストークンを持つロボットやボット、別のシステムがありますか?ここでも、全く同じようにすべて機能します。
+
+あなたのアプリケーションに必要なのがどんな種類のモデル、どんな種類のクラス、どんな種類のデータベースであったとしても、 **FastAPI** は依存性注入システムでカバーしてくれます。
+
+## コードサイズ { #code-size }
+
+この例は冗長に見えるかもしれません。セキュリティとデータモデルユーティリティ関数および *path operation* が同じファイルに混在しているということを覚えておいてください。
+
+しかし、ここに重要なポイントがあります。
+
+セキュリティと依存性注入に関するものは、一度だけ書きます。
+
+そして、それは好きなだけ複雑にすることができます。それでも、一箇所に、一度だけ書くのです。すべての柔軟性を備えます。
+
+しかし、同じセキュリティシステムを使って何千ものエンドポイント(*path operation*)を持つことができます。
+
+そして、それらエンドポイントのすべて(必要な、どの部分でも)がこうした依存関係や、あなたが作成する別の依存関係を再利用する利点を享受できるのです。
+
+さらに、こうした何千もの *path operation* は、たった3行で表現できるのです:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *}
+
+## まとめ { #recap }
+
+これで、 *path operation 関数* の中で直接現在のユーザーを取得できるようになりました。
+
+既に半分のところまで来ています。
+
+あとは、ユーザー/クライアントが実際に `username` と `password` を送信するための *path operation* を追加する必要があるだけです。
+
+次はそれを説明します。
diff --git a/docs/ja/docs/tutorial/security/index.md b/docs/ja/docs/tutorial/security/index.md
new file mode 100644
index 0000000000000..b96021b7ff774
--- /dev/null
+++ b/docs/ja/docs/tutorial/security/index.md
@@ -0,0 +1,106 @@
+# セキュリティ入門 { #security }
+
+セキュリティ、認証、認可を扱うには多くの方法があります。
+
+そして、通常、それは複雑で「難しい」トピックです。
+
+多くのフレームワークやシステムでは、セキュリティと認証を処理するだけで、膨大な労力とコードが必要になります(多くの場合、書かれた全コードの50%以上を占めることがあります)。
+
+**FastAPI** は、セキュリティの仕様をすべて勉強して学ぶことなく、標準的な方法で簡単に、迅速に**セキュリティ**を扱うためのツールをいくつか提供します。
+
+しかし、その前に、いくつかの小さな概念を確認しましょう。
+
+## お急ぎですか? { #in-a-hurry }
+
+もし、これらの用語に興味がなく、ユーザー名とパスワードに基づく認証でセキュリティを**今すぐ**確保する必要がある場合は、次の章に進んでください。
+
+## OAuth2 { #oauth2 }
+
+OAuth2は、認証と認可を処理するためのいくつかの方法を定義した仕様です。
+
+かなり広範囲な仕様で、いくつかの複雑なユースケースをカバーしています。
+
+これには「サードパーティ」を使用して認証する方法が含まれています。
+
+これが、「Facebook、Google、X (Twitter)、GitHubを使ってログイン」を使用したすべてのシステムの背後で使われている仕組みです。
+
+### OAuth 1 { #oauth-1 }
+
+OAuth 1というものもありましたが、これはOAuth2とは全く異なり、通信をどのように暗号化するかという仕様が直接的に含まれており、より複雑なものとなっています。
+
+現在ではあまり普及していませんし、使われてもいません。
+
+OAuth2は、通信を暗号化する方法を指定せず、アプリケーションがHTTPSで提供されることを想定しています。
+
+/// tip | 豆知識
+
+**デプロイ**のセクションでは、TraefikとLet's Encryptを使用して、無料でHTTPSを設定する方法が紹介されています。
+
+///
+
+## OpenID Connect { #openid-connect }
+
+OpenID Connectは、**OAuth2**をベースにした別の仕様です。
+
+これはOAuth2を拡張したもので、OAuth2ではやや曖昧だった部分を明確にし、より相互運用性を高めようとしたものです。
+
+例として、GoogleのログインはOpenID Connectを使用しています(これはOAuth2がベースになっています)。
+
+しかし、FacebookのログインはOpenID Connectをサポートしていません。OAuth2を独自にアレンジしています。
+
+### OpenID (「OpenID Connect」ではない) { #openid-not-openid-connect }
+
+また、「OpenID」という仕様もありました。それは、**OpenID Connect**と同じことを解決しようとしたものですが、OAuth2に基づいているわけではありませんでした。
+
+つまり、完全な追加システムだったのです。
+
+現在ではあまり普及していませんし、使われてもいません。
+
+## OpenAPI { #openapi }
+
+OpenAPI(以前はSwaggerとして知られていました)は、APIを構築するためのオープンな仕様です(現在はLinux Foundationの一部になっています)。
+
+**FastAPI**は、**OpenAPI**をベースにしています。
+
+それが、複数の自動対話型ドキュメント・インターフェースやコード生成などを可能にしているのです。
+
+OpenAPIには、複数のセキュリティ「スキーム」を定義する方法があります。
+
+それらを使用することで、これらの対話型ドキュメントシステムを含む、標準ベースのツールをすべて活用できます。
+
+OpenAPIでは、以下のセキュリティスキームを定義しています:
+
+* `apiKey`: アプリケーション固有のキーで、これらのものから取得できます。
+ * クエリパラメータ
+ * ヘッダー
+ * クッキー
+* `http`: 標準的なHTTP認証システムで、これらのものを含みます。
+ * `bearer`: ヘッダ `Authorization` の値が `Bearer ` で、トークンが含まれます。これはOAuth2から継承しています。
+ * HTTP Basic認証
+ * HTTP ダイジェスト認証など
+* `oauth2`: OAuth2のセキュリティ処理方法(「フロー」と呼ばれます)のすべて。
+ * これらのフローのいくつかは、OAuth 2.0認証プロバイダ(Google、Facebook、X (Twitter)、GitHubなど)を構築するのに適しています。
+ * `implicit`
+ * `clientCredentials`
+ * `authorizationCode`
+ * しかし、同じアプリケーション内で認証を直接処理するために完全に機能する特定の「フロー」があります。
+ * `password`: 次のいくつかの章では、その例を紹介します。
+* `openIdConnect`: OAuth2認証データを自動的に発見する方法を定義できます。
+ * この自動検出メカニズムは、OpenID Connectの仕様で定義されているものです。
+
+
+/// tip | 豆知識
+
+Google、Facebook、X (Twitter)、GitHubなど、他の認証/認可プロバイダを統合することも可能で、比較的簡単です。
+
+最も複雑な問題は、それらのような認証/認可プロバイダを構築することですが、**FastAPI**は、あなたのために重い仕事をこなしながら、それを簡単に行うためのツールを提供します。
+
+///
+
+## **FastAPI** ユーティリティ { #fastapi-utilities }
+
+FastAPIは `fastapi.security` モジュールの中で、これらのセキュリティスキームごとにいくつかのツールを提供し、これらのセキュリティメカニズムを簡単に使用できるようにします。
+
+次の章では、**FastAPI** が提供するこれらのツールを使って、あなたのAPIにセキュリティを追加する方法について見ていきます。
+
+また、それがどのようにインタラクティブなドキュメントシステムに自動的に統合されるかも見ていきます。
diff --git a/docs/ja/docs/tutorial/security/oauth2-jwt.md b/docs/ja/docs/tutorial/security/oauth2-jwt.md
index 348ffda0163e9..9c527121ea1dd 100644
--- a/docs/ja/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/ja/docs/tutorial/security/oauth2-jwt.md
@@ -1,12 +1,12 @@
-# パスワード(およびハッシュ化)によるOAuth2、JWTトークンによるBearer
+# パスワード(およびハッシュ化)によるOAuth2、JWTトークンによるBearer { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
-これでセキュリティの流れが全てわかったので、JWTトークンと安全なパスワードのハッシュ化を使用して、実際にアプリケーションを安全にしてみましょう。
+これでセキュリティの流れが全てわかったので、JWTトークンと安全なパスワードのハッシュ化を使用して、実際にアプリケーションを安全にしてみましょう。
このコードは、アプリケーションで実際に使用したり、パスワードハッシュをデータベースに保存するといった用途に利用できます。
本章では、前章の続きから始めて、コードをアップデートしていきます。
-## JWT について
+## JWT について { #about-jwt }
JWTとは「JSON Web Tokens」の略称です。
@@ -24,32 +24,33 @@ eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4
1週間後、トークンが期限切れとなるとどうなるでしょうか?ユーザーは認可されず、新しいトークンを得るために再びサインインしなければなりません。また、ユーザー(または第三者)がトークンを修正して有効期限を変更しようとした場合、署名が一致しないため、トークンの修正を検知できます。
-JWT トークンを使って遊んでみたいという方は、https://jwt.io をチェックしてください。
+JWT トークンを使って遊んでみたいという方は、[https://jwt.io](https://jwt.io/) をチェックしてください。
-## `python-jose` のインストール
+## `PyJWT` のインストール { #install-pyjwt }
-PythonでJWTトークンの生成と検証を行うために、`python-jose`をインストールする必要があります:
+PythonでJWTトークンの生成と検証を行うために、`PyJWT`をインストールする必要があります。
+
+[仮想環境](../../virtual-environments.md)を作成し、アクティベートしてから、`pyjwt`をインストールしてください。
@@ -226,14 +234,17 @@ Password: `secret`
-開発者ツールを開くと、送信されるデータにはトークンだけが含まれており、パスワードはユーザーを認証してアクセストークンを取得する最初のリクエストでのみ送信され、その後は送信されないことがわかります。
+開発者ツールを開くと、送信されるデータにはトークンだけが含まれており、パスワードはユーザーを認証してアクセストークンを取得する最初のリクエストでのみ送信され、その後は送信されないことがわかります:
-!!! note "備考"
- ヘッダーの`Authorization`には、`Bearer`で始まる値があります。
+/// note | 備考
+
+ヘッダーの`Authorization`には、`Bearer `で始まる値があります。
+
+///
-## `scopes` を使った高度なユースケース
+## `scopes` を使った高度なユースケース { #advanced-usage-with-scopes }
OAuth2には、「スコープ」という概念があります。
@@ -243,7 +254,7 @@ OAuth2には、「スコープ」という概念があります。
これらの使用方法や**FastAPI**への統合方法については、**高度なユーザーガイド**で後ほど説明します。
-## まとめ
+## まとめ { #recap }
ここまでの説明で、OAuth2やJWTなどの規格を使った安全な**FastAPI**アプリケーションを設定することができます。
@@ -257,10 +268,10 @@ OAuth2には、「スコープ」という概念があります。
そのため、プロジェクトに合わせて自由に選択することができます。
-また、**FastAPI**は外部パッケージを統合するために複雑な仕組みを必要としないため、`passlib`や`python-jose`のようなよく整備され広く使われている多くのパッケージを直接使用することができます。
+また、**FastAPI**は外部パッケージを統合するために複雑な仕組みを必要としないため、`pwdlib`や`PyJWT`のようなよく整備され広く使われている多くのパッケージを直接使用することができます。
しかし、柔軟性、堅牢性、セキュリティを損なうことなく、可能な限りプロセスを簡素化するためのツールを提供します。
また、OAuth2のような安全で標準的なプロトコルを比較的簡単な方法で使用できるだけではなく、実装することもできます。
-OAuth2の「スコープ」を使って、同じ基準でより細かい権限システムを実現する方法については、**高度なユーザーガイド**で詳しく説明しています。スコープ付きのOAuth2は、Facebook、Google、GitHub、Microsoft、Twitterなど、多くの大手認証プロバイダが、サードパーティのアプリケーションと自社のAPIとのやり取りをユーザーに代わって認可するために使用している仕組みです。
+OAuth2の「スコープ」を使って、同じ基準でより細かい権限システムを実現する方法については、**高度なユーザーガイド**で詳しく説明しています。スコープ付きのOAuth2は、Facebook、Google、GitHub、Microsoft、X (Twitter)など、多くの大手認証プロバイダが、サードパーティのアプリケーションと自社のAPIとのやり取りをユーザーに代わって認可するために使用している仕組みです。
diff --git a/docs/ja/docs/tutorial/security/simple-oauth2.md b/docs/ja/docs/tutorial/security/simple-oauth2.md
new file mode 100644
index 0000000000000..842cd02e5be56
--- /dev/null
+++ b/docs/ja/docs/tutorial/security/simple-oauth2.md
@@ -0,0 +1,289 @@
+# パスワードとBearerによるシンプルなOAuth2 { #simple-oauth2-with-password-and-bearer }
+
+前章から発展させて、完全なセキュリティフローに必要な不足部分を追加していきます。
+
+## `username` と `password` を取得する { #get-the-username-and-password }
+
+`username` と `password` を取得するために **FastAPI** のセキュリティユーティリティを使います。
+
+OAuth2 では、「password flow」(ここで使用するフロー)を使う場合、クライアント/ユーザーはフォームデータとして `username` と `password` フィールドを送信する必要があります。
+
+しかも、フィールド名はこの通りでなければなりません。つまり、`user-name` や `email` では動作しません。
+
+ただし、フロントエンドで最終ユーザーにどう表示するかは自由です。
+
+また、データベースのモデルでは任意の別名を使って構いません。
+
+しかし、ログイン用の path operation では、仕様との互換性を保つ(たとえば組み込みのAPIドキュメントシステムを使えるようにする)ために、これらの名前を使う必要があります。
+
+また、仕様では `username` と `password` はフォームデータとして送らなければならない(つまり、ここではJSONは使わない)ことも定められています。
+
+### `scope` { #scope }
+
+仕様では、クライアントは追加のフォームフィールド「`scope`」を送ることができるとも書かれています。
+
+フォームフィールド名は `scope`(単数形)ですが、実態はスペース区切りの「スコープ」文字列を並べた長い文字列です。
+
+各「スコープ」は(スペースを含まない)単なる文字列です。
+
+通常、特定のセキュリティ権限を宣言するために使われます。例えば:
+
+- `users:read` や `users:write` はよくある例です。
+- `instagram_basic` は Facebook / Instagram で使われます。
+- `https://www.googleapis.com/auth/drive` は Google で使われます。
+
+/// info | 情報
+
+OAuth2 における「スコープ」は、要求される特定の権限を表す単なる文字列です。
+
+`:` のような他の文字を含んでいても、URL であっても構いません。
+
+それらの詳細は実装依存です。
+
+OAuth2 にとっては単なる文字列です。
+
+///
+
+## `username` と `password` を取得するコード { #code-to-get-the-username-and-password }
+
+では、これを処理するために **FastAPI** が提供するユーティリティを使いましょう。
+
+### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform }
+
+まず、`OAuth2PasswordRequestForm` をインポートし、`/token` の path operation に `Depends` で依存関係として使います:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}
+
+`OAuth2PasswordRequestForm` は次のフォームボディを宣言するクラス依存関係です:
+
+- `username`
+- `password`
+- スペース区切りの文字列で構成される、オプションの `scope` フィールド
+- オプションの `grant_type`
+
+/// tip | 豆知識
+
+OAuth2 の仕様では、固定値 `password` を持つフィールド `grant_type` が実際には必須ですが、`OAuth2PasswordRequestForm` はそれを強制しません。
+
+強制したい場合は、`OAuth2PasswordRequestForm` の代わりに `OAuth2PasswordRequestFormStrict` を使ってください。
+
+///
+
+- オプションの `client_id`(この例では不要)
+- オプションの `client_secret`(この例では不要)
+
+/// info | 情報
+
+`OAuth2PasswordRequestForm` は、`OAuth2PasswordBearer` のように **FastAPI** にとって特別なクラスではありません。
+
+`OAuth2PasswordBearer` は **FastAPI** にセキュリティスキームであることを認識させます。そのため OpenAPI にそのように追加されます。
+
+一方、`OAuth2PasswordRequestForm` は、あなた自身でも書けるような単なるクラス依存関係であり、直接 `Form` パラメータを宣言することもできます。
+
+ただし一般的なユースケースなので、簡単に使えるよう **FastAPI** が直接提供しています。
+
+///
+
+### フォームデータの利用 { #use-the-form-data }
+
+/// tip | 豆知識
+
+依存関係クラス `OAuth2PasswordRequestForm` のインスタンスは、スペース区切りの長い文字列を持つ `scope` 属性は持ちません。代わりに、送られてきた各スコープの実際の文字列リストを格納する `scopes` 属性を持ちます。
+
+この例では `scopes` は使いませんが、必要ならその機能が利用できます。
+
+///
+
+次に、フォームフィールドの `username` を使って(疑似の)データベースからユーザーデータを取得します。
+
+そのユーザーが存在しない場合は、「Incorrect username or password」というエラーを返します。
+
+エラーには `HTTPException` 例外を使います:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}
+
+### パスワードのチェック { #check-the-password }
+
+この時点でデータベースからユーザーデータは取得できましたが、まだパスワードを確認していません。
+
+まず、そのデータを Pydantic の `UserInDB` モデルに入れます。
+
+プレーンテキストのパスワードを保存してはいけないので、(疑似の)パスワードハッシュ化システムを使います。
+
+パスワードが一致しなければ、同じエラーを返します。
+
+#### パスワードハッシュ化 { #password-hashing }
+
+「ハッシュ化」とは、ある内容(ここではパスワード)を、乱雑に見えるバイト列(単なる文字列)に変換することを指します。
+
+まったく同じ内容(まったく同じパスワード)を渡すと、毎回まったく同じ乱雑な文字列が得られます。
+
+しかし、その乱雑な文字列から元のパスワードに戻すことはできません。
+
+##### なぜパスワードをハッシュ化するのか { #why-use-password-hashing }
+
+もしデータベースが盗まれても、盗んだ側が手にするのはユーザーのプレーンテキストのパスワードではなく、ハッシュだけです。
+
+したがって、盗んだ側は同じパスワードを別のシステムで試すことができません(多くのユーザーがあらゆる場所で同じパスワードを使っているため、これは危険になり得ます)。
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}
+
+#### `**user_dict` について { #about-user-dict }
+
+`UserInDB(**user_dict)` は次を意味します:
+
+`user_dict` のキーと値を、そのままキーワード引数として渡します。つまり次と同等です:
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ disabled = user_dict["disabled"],
+ hashed_password = user_dict["hashed_password"],
+)
+```
+
+/// info | 情報
+
+`**user_dict` のより完全な解説は、[**追加モデル**のドキュメント](../extra-models.md#about-user-in-dict)を参照してください。
+
+///
+
+## トークンを返す { #return-the-token }
+
+`token` エンドポイントのレスポンスは JSON オブジェクトでなければなりません。
+
+`token_type` を含める必要があります。ここでは「Bearer」トークンを使うので、トークンタイプは「`bearer`」です。
+
+そして `access_token` を含め、その中にアクセストークンの文字列を入れます。
+
+この単純な例では、完全に安全ではありませんが、トークンとして同じ `username` をそのまま返します。
+
+/// tip | 豆知識
+
+次の章では、パスワードハッシュ化と JWT トークンを使った本当に安全な実装を見ます。
+
+しかし今は、必要な特定の詳細に集中しましょう。
+
+///
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}
+
+/// tip | 豆知識
+
+仕様に従うと、この例と同じく `access_token` と `token_type` を含む JSON を返す必要があります。
+
+これはあなた自身のコードで実装する必要があり、これらのJSONキーを使っていることを確認してください。
+
+仕様に準拠するために、あなた自身が正しく覚えて実装すべきことは、ほぼこれだけです。
+
+それ以外は **FastAPI** が面倒を見てくれます。
+
+///
+
+## 依存関係の更新 { #update-the-dependencies }
+
+ここで依存関係を更新します。
+
+アクティブなユーザーの場合にのみ `current_user` を取得したいとします。
+
+そこで、`get_current_active_user` を依存関係として利用する追加の依存関係 `get_current_active_user` を作成します。
+
+これら2つの依存関係は、ユーザーが存在しない、または非アクティブである場合に、HTTPエラーを返すだけです。
+
+したがって、エンドポイントでは、ユーザーが存在し、正しく認証され、かつアクティブである場合にのみ、ユーザーを取得します:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}
+
+/// info | 情報
+
+ここで返している値が `Bearer` の追加ヘッダー `WWW-Authenticate` も仕様の一部です。
+
+HTTP(エラー)ステータスコード 401「UNAUTHORIZED」は、`WWW-Authenticate` ヘッダーも返すことになっています。
+
+ベアラートークン(今回のケース)の場合、そのヘッダーの値は `Bearer` であるべきです。
+
+実際のところ、この追加ヘッダーを省略しても動作はします。
+
+しかし、仕様に準拠するためにここでは付与しています。
+
+また、(今または将来)それを想定して利用するツールがあるかもしれず、あなたやユーザーにとって有用になる可能性があります。
+
+これが標準の利点です…。
+
+///
+
+## 動作確認 { #see-it-in-action }
+
+インタラクティブドキュメントを開きます: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)。
+
+### 認証 { #authenticate }
+
+「Authorize」ボタンをクリックします。
+
+次の認証情報を使います:
+
+User: `johndoe`
+
+Password: `secret`
+
+
+
+システムで認証されると、次のように表示されます:
+
+
+
+### 自分のユーザーデータを取得 { #get-your-own-user-data }
+
+`GET` の path `/users/me` を使います。
+
+次のようなユーザーデータが取得できます:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false,
+ "hashed_password": "fakehashedsecret"
+}
+```
+
+
+
+錠前アイコンをクリックしてログアウトし、同じ操作を再度試すと、次のような HTTP 401 エラーになります:
+
+```JSON
+{
+ "detail": "Not authenticated"
+}
+```
+
+### 非アクティブユーザー { #inactive-user }
+
+今度は非アクティブなユーザーで試してみます。次で認証してください:
+
+User: `alice`
+
+Password: `secret2`
+
+そして `GET` の path `/users/me` を使います。
+
+次のような「Inactive user」エラーになります:
+
+```JSON
+{
+ "detail": "Inactive user"
+}
+```
+
+## まとめ { #recap }
+
+これで、API のために `username` と `password` に基づく完全なセキュリティシステムを実装するための道具が揃いました。
+
+これらの道具を使えば、任意のデータベース、任意のユーザー/データモデルと互換性のあるセキュリティシステムを構築できます。
+
+ただし、実際にはまだ「安全」ではありません。
+
+次の章では、安全なパスワードハッシュライブラリと JWT トークンの使い方を見ていきます。
diff --git a/docs/ja/docs/tutorial/server-sent-events.md b/docs/ja/docs/tutorial/server-sent-events.md
new file mode 100644
index 0000000000000..d8168cef309b9
--- /dev/null
+++ b/docs/ja/docs/tutorial/server-sent-events.md
@@ -0,0 +1,120 @@
+# Server-Sent Events (SSE) { #server-sent-events-sse }
+
+**Server-Sent Events** (SSE) を使うと、クライアントへデータをストリーミングできます。
+
+これは[JSON Lines のストリーミング](stream-json-lines.md)に似ていますが、`text/event-stream` フォーマットを使用します。これはブラウザがネイティブに [`EventSource` API](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) でサポートしています。
+
+/// info | 情報
+
+FastAPI 0.135.0 で追加されました。
+
+///
+
+## Server-Sent Events とは { #what-are-server-sent-events }
+
+SSE は、HTTP 経由でサーバーからクライアントへデータをストリーミングするための標準です。
+
+各イベントは、`data`、`event`、`id`、`retry` などの「フィールド」を含む小さなテキストブロックで、空行で区切られます。
+
+次のようになります:
+
+```
+data: {"name": "Portal Gun", "price": 999.99}
+
+data: {"name": "Plumbus", "price": 32.99}
+
+```
+
+SSE は、AI チャットのストリーミング、ライブ通知、ログやオブザビリティなど、サーバーがクライアントへ更新をプッシュする用途で一般的に使われます。
+
+/// tip | 豆知識
+
+バイナリデータ(例: 動画や音声)をストリーミングしたい場合は、上級ガイド [データのストリーミング](../advanced/stream-data.md) を参照してください。
+
+///
+
+## FastAPI で SSE をストリーミング { #stream-sse-with-fastapi }
+
+FastAPI で SSE をストリーミングするには、*path operation 関数*で `yield` を使い、`response_class=EventSourceResponse` を設定します。
+
+`EventSourceResponse` は `fastapi.sse` からインポートします:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[4,22] *}
+
+yield された各アイテムは JSON にエンコードされ、SSE イベントの `data:` フィールドで送信されます。
+
+戻り値の型を `AsyncIterable[Item]` と宣言すると、FastAPI は Pydantic を用いてデータを**検証**、**ドキュメント化**、**シリアライズ**します。
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[10:12,23] *}
+
+/// tip | 豆知識
+
+Pydantic が**Rust** 側でシリアライズを行うため、戻り値の型を宣言しない場合に比べて大幅に**高性能**になります。
+
+///
+
+### 非 async の *path operation 関数* { #non-async-path-operation-functions }
+
+通常の `def` 関数(`async` なし)も使用でき、同様に `yield` を使えます。
+
+イベントループをブロックしないよう、FastAPI が正しく実行されるように調整します。
+
+この場合は関数が async ではないため、適切な戻り値の型は `Iterable[Item]` です:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[28:31] hl[29] *}
+
+### 戻り値の型なし { #no-return-type }
+
+戻り値の型を省略することもできます。FastAPI は [`jsonable_encoder`](./encoder.md) を使ってデータを変換し、送信します。
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[34:37] hl[35] *}
+
+## `ServerSentEvent` { #serversentevent }
+
+`event`、`id`、`retry`、`comment` などの SSE フィールドを設定する必要がある場合は、生データの代わりに `ServerSentEvent` オブジェクトを `yield` できます。
+
+`ServerSentEvent` は `fastapi.sse` からインポートします:
+
+{* ../../docs_src/server_sent_events/tutorial002_py310.py hl[4,26] *}
+
+`data` フィールドは常に JSON にエンコードされます。Pydantic モデルを含む、JSON にシリアライズ可能な任意の値を渡せます。
+
+## 生データ { #raw-data }
+
+JSON エンコードせずにデータを送る必要がある場合は、`data` の代わりに `raw_data` を使用します。
+
+これは、整形済みテキスト、ログ行、または `[DONE]` のような特別な "センチネル" 値を送るのに有用です。
+
+{* ../../docs_src/server_sent_events/tutorial003_py310.py hl[17] *}
+
+/// note | 備考
+
+`data` と `raw_data` は相互排他的です。各 `ServerSentEvent` ではどちらか一方しか設定できません。
+
+///
+
+## `Last-Event-ID` での再開 { #resuming-with-last-event-id }
+
+接続が途切れた後にブラウザが再接続すると、最後に受信した `id` を `Last-Event-ID` ヘッダーで送信します。
+
+これをヘッダーパラメータとして受け取り、クライアントが離脱した位置からストリームを再開できます:
+
+{* ../../docs_src/server_sent_events/tutorial004_py310.py hl[25,27,31] *}
+
+## POST での SSE { #sse-with-post }
+
+SSE は `GET` だけでなく、**任意の HTTP メソッド**で動作します。
+
+これは、`POST` 上で SSE をストリーミングする [MCP](https://modelcontextprotocol.io) のようなプロトコルで有用です:
+
+{* ../../docs_src/server_sent_events/tutorial005_py310.py hl[14] *}
+
+## 技術詳細 { #technical-details }
+
+FastAPI は SSE のいくつかのベストプラクティスを標準で実装しています。
+
+- メッセージがない場合は 15 秒ごとに「キープアライブ」用の `ping` コメントを送信し、一部のプロキシが接続を閉じるのを防ぎます([HTML 仕様: Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes) の推奨に従います)。
+- ストリームの**キャッシュを防止**するため、`Cache-Control: no-cache` ヘッダーを設定します。
+- Nginx など一部のプロキシでの**バッファリングを防ぐ**ため、特別なヘッダー `X-Accel-Buffering: no` を設定します。
+
+追加の設定は不要で、そのまま動作します。🤓
diff --git a/docs/ja/docs/tutorial/sql-databases.md b/docs/ja/docs/tutorial/sql-databases.md
new file mode 100644
index 0000000000000..13c71fdb2a370
--- /dev/null
+++ b/docs/ja/docs/tutorial/sql-databases.md
@@ -0,0 +1,357 @@
+# SQL(リレーショナル)データベース { #sql-relational-databases }
+
+FastAPI は SQL(リレーショナル)データベースの使用を必須にはしません。必要であれば、任意のデータベースを使用できます。
+
+ここでは [SQLModel](https://sqlmodel.tiangolo.com/) を使った例を見ていきます。
+
+SQLModel は [SQLAlchemy](https://www.sqlalchemy.org/) と Pydantic の上に構築されています。FastAPI と同じ作者により、SQL データベースを使う必要がある FastAPI アプリに最適になるように作られています。
+
+/// tip | 豆知識
+
+他の任意の SQL あるいは NoSQL のデータベースライブラリ(場合によっては "ORMs" と呼ばれます)を使うこともできます。FastAPI は何も強制しません。😎
+
+///
+
+SQLModel は SQLAlchemy をベースにしているため、SQLAlchemy がサポートする任意のデータベース(SQLModel からもサポートされます)を簡単に使えます。例えば:
+
+* PostgreSQL
+* MySQL
+* SQLite
+* Oracle
+* Microsoft SQL Server など
+
+この例では、単一ファイルで動作し、Python に統合サポートがあるため、SQLite を使います。つまり、この例をそのままコピーして実行できます。
+
+本番アプリでは、PostgreSQL のようなデータベースサーバーを使いたくなるかもしれません。
+
+/// tip | 豆知識
+
+フロントエンドやその他のツールを含む、FastAPI と PostgreSQL の公式プロジェクトジェネレーターがあります: [https://github.com/fastapi/full-stack-fastapi-template](https://github.com/fastapi/full-stack-fastapi-template)
+
+///
+
+これはとてもシンプルで短いチュートリアルです。データベースや SQL、より高度な機能について学びたい場合は、[SQLModel のドキュメント](https://sqlmodel.tiangolo.com/)をご覧ください。
+
+## `SQLModel` のインストール { #install-sqlmodel }
+
+まずは [仮想環境](../virtual-environments.md) を作成・有効化し、`sqlmodel` をインストールします:
+
+
+
+lt
+* XWT
+* PSGI
+
+### abbr가 전체 문구와 설명을 제공 { #the-abbr-gives-a-full-phrase-and-an-explanation }
+
+* MDN
+* I/O.
+
+////
+
+//// tab | 정보
+
+"abbr" 요소의 "title" 속성은 몇 가지 구체적인 지침에 따라 번역됩니다.
+
+번역에서는(영어 단어를 설명하기 위해) 자체 "abbr" 요소를 추가할 수 있으며, LLM은 이를 제거하면 안 됩니다.
+
+`scripts/translate.py`의 일반 프롬프트에서 `### HTML abbr elements` 섹션을 참고하세요.
+
+////
+
+## HTML "dfn" 요소 { #html-dfn-elements }
+
+* 클러스터
+* 딥 러닝
+
+## 제목 { #headings }
+
+//// tab | 테스트
+
+### 웹앱 개발하기 - 튜토리얼 { #develop-a-webapp-a-tutorial }
+
+안녕하세요.
+
+### 타입 힌트와 -애너테이션 { #type-hints-and-annotations }
+
+다시 안녕하세요.
+
+### super- 및 subclasses { #super-and-subclasses }
+
+다시 안녕하세요.
+
+////
+
+//// tab | 정보
+
+제목에 대한 유일한 강한 규칙은, LLM이 중괄호 안의 해시 부분을 변경하지 않아 링크가 깨지지 않게 하는 것입니다.
+
+`scripts/translate.py`의 일반 프롬프트에서 `### Headings` 섹션을 참고하세요.
+
+언어별 지침은 예를 들어 `docs/de/llm-prompt.md`의 `### Headings` 섹션을 참고하세요.
+
+////
+
+## 문서에서 사용되는 용어 { #terms-used-in-the-docs }
+
+//// tab | 테스트
+
+* 여러분
+* 여러분의
+
+* 예:
+* 등
+
+* `foo`로서의 `int`
+* `bar`로서의 `str`
+* `baz`로서의 `list`
+
+* 튜토리얼 - 사용자 가이드
+* 고급 사용자 가이드
+* SQLModel 문서
+* API 문서
+* 자동 문서
+
+* Data Science
+* Deep Learning
+* Machine Learning
+* Dependency Injection
+* HTTP Basic authentication
+* HTTP Digest
+* ISO format
+* JSON Schema 표준
+* JSON schema
+* schema definition
+* Password Flow
+* Mobile
+
+* deprecated
+* designed
+* invalid
+* on the fly
+* standard
+* default
+* case-sensitive
+* case-insensitive
+
+* 애플리케이션을 서빙하다
+* 페이지를 서빙하다
+
+* 앱
+* 애플리케이션
+
+* 요청
+* 응답
+* 오류 응답
+
+* 경로 처리
+* 경로 처리 데코레이터
+* 경로 처리 함수
+
+* body
+* 요청 body
+* 응답 body
+* JSON body
+* form body
+* file body
+* 함수 body
+
+* parameter
+* body parameter
+* path parameter
+* query parameter
+* cookie parameter
+* header parameter
+* form parameter
+* function parameter
+
+* event
+* startup event
+* 서버 startup
+* shutdown event
+* lifespan event
+
+* handler
+* event handler
+* exception handler
+* 처리하다
+
+* model
+* Pydantic model
+* data model
+* database model
+* form model
+* model object
+
+* class
+* base class
+* parent class
+* subclass
+* child class
+* sibling class
+* class method
+
+* header
+* headers
+* authorization header
+* `Authorization` header
+* forwarded header
+
+* dependency injection system
+* dependency
+* dependable
+* dependant
+
+* I/O bound
+* CPU bound
+* concurrency
+* parallelism
+* multiprocessing
+
+* env var
+* environment variable
+* `PATH`
+* `PATH` variable
+
+* authentication
+* authentication provider
+* authorization
+* authorization form
+* authorization provider
+* 사용자가 인증한다
+* 시스템이 사용자를 인증한다
+
+* CLI
+* command line interface
+
+* server
+* client
+
+* cloud provider
+* cloud service
+
+* development
+* development stages
+
+* dict
+* dictionary
+* enumeration
+* enum
+* enum member
+
+* encoder
+* decoder
+* encode하다
+* decode하다
+
+* exception
+* raise하다
+
+* expression
+* statement
+
+* frontend
+* backend
+
+* GitHub discussion
+* GitHub issue
+
+* performance
+* performance optimization
+
+* return type
+* return value
+
+* security
+* security scheme
+
+* task
+* background task
+* task function
+
+* template
+* template engine
+
+* type annotation
+* type hint
+
+* server worker
+* Uvicorn worker
+* Gunicorn Worker
+* worker process
+* worker class
+* workload
+
+* deployment
+* deploy하다
+
+* SDK
+* software development kit
+
+* `APIRouter`
+* `requirements.txt`
+* Bearer Token
+* breaking change
+* bug
+* button
+* callable
+* code
+* commit
+* context manager
+* coroutine
+* database session
+* disk
+* domain
+* engine
+* fake X
+* HTTP GET method
+* item
+* library
+* lifespan
+* lock
+* middleware
+* mobile application
+* module
+* mounting
+* network
+* origin
+* override
+* payload
+* processor
+* property
+* proxy
+* pull request
+* query
+* RAM
+* remote machine
+* status code
+* string
+* tag
+* web framework
+* wildcard
+* return하다
+* validate하다
+
+////
+
+//// tab | 정보
+
+이것은 문서에서 보이는 (대부분) 기술 용어의 불완전하고 비규범적인 목록입니다. 프롬프트 설계자가 어떤 용어에 대해 LLM에 추가적인 도움이 필요한지 파악하는 데 유용할 수 있습니다. 예를 들어, 좋은 번역을 계속 덜 좋은 번역으로 되돌릴 때, 또는 언어에서 용어의 활용/변화를 처리하는 데 문제가 있을 때 도움이 됩니다.
+
+예를 들어 `docs/de/llm-prompt.md`의 `### List of English terms and their preferred German translations` 섹션을 참고하세요.
+
+////
diff --git a/docs/ko/docs/about/index.md b/docs/ko/docs/about/index.md
new file mode 100644
index 0000000000000..dc2c728740336
--- /dev/null
+++ b/docs/ko/docs/about/index.md
@@ -0,0 +1,3 @@
+# 소개 { #about }
+
+FastAPI, 그 디자인, 영감 등에 대해 🤓
diff --git a/docs/ko/docs/advanced/additional-responses.md b/docs/ko/docs/advanced/additional-responses.md
new file mode 100644
index 0000000000000..e43d7c727ffd8
--- /dev/null
+++ b/docs/ko/docs/advanced/additional-responses.md
@@ -0,0 +1,247 @@
+# OpenAPI에서 추가 응답 { #additional-responses-in-openapi }
+
+/// warning | 경고
+
+이는 꽤 고급 주제입니다.
+
+**FastAPI**를 막 시작했다면, 이 내용이 필요 없을 수도 있습니다.
+
+///
+
+추가 상태 코드, 미디어 타입, 설명 등을 포함한 추가 응답을 선언할 수 있습니다.
+
+이러한 추가 응답은 OpenAPI 스키마에 포함되므로 API 문서에도 표시됩니다.
+
+하지만 이러한 추가 응답의 경우, 상태 코드와 콘텐츠를 포함하여 `JSONResponse` 같은 `Response`를 직접 반환하도록 반드시 처리해야 합니다.
+
+## `model`을 사용한 추가 응답 { #additional-response-with-model }
+
+*경로 처리 데코레이터*에 `responses` 파라미터를 전달할 수 있습니다.
+
+이는 `dict`를 받습니다. 키는 각 응답의 상태 코드(예: `200`)이고, 값은 각 응답에 대한 정보를 담은 다른 `dict`입니다.
+
+각 응답 `dict`에는 `response_model`처럼 Pydantic 모델을 담는 `model` 키가 있을 수 있습니다.
+
+**FastAPI**는 그 모델을 사용해 JSON Schema를 생성하고, OpenAPI의 올바른 위치에 포함합니다.
+
+예를 들어, 상태 코드 `404`와 Pydantic 모델 `Message`를 사용하는 다른 응답을 선언하려면 다음과 같이 작성할 수 있습니다:
+
+{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}
+
+/// note | 참고
+
+`JSONResponse`를 직접 반환해야 한다는 점을 기억하세요.
+
+///
+
+/// info | 정보
+
+`model` 키는 OpenAPI의 일부가 아닙니다.
+
+**FastAPI**는 여기에서 Pydantic 모델을 가져와 JSON Schema를 생성하고 올바른 위치에 넣습니다.
+
+올바른 위치는 다음과 같습니다:
+
+* 값으로 또 다른 JSON 객체(`dict`)를 가지는 `content` 키 안에:
+ * 미디어 타입(예: `application/json`)을 키로 가지며, 값으로 또 다른 JSON 객체를 포함하고:
+ * `schema` 키가 있고, 그 값이 모델에서 생성된 JSON Schema입니다. 이것이 올바른 위치입니다.
+ * **FastAPI**는 이를 직접 포함하는 대신, OpenAPI의 다른 위치에 있는 전역 JSON Schemas를 참조하도록 여기에서 reference를 추가합니다. 이렇게 하면 다른 애플리케이션과 클라이언트가 그 JSON Schema를 직접 사용할 수 있고, 더 나은 코드 생성 도구 등을 제공할 수 있습니다.
+
+///
+
+이 *경로 처리*에 대해 OpenAPI에 생성되는 응답은 다음과 같습니다:
+
+```JSON hl_lines="3-12"
+{
+ "responses": {
+ "404": {
+ "description": "Additional Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Message"
+ }
+ }
+ }
+ },
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+스키마는 OpenAPI 스키마 내부의 다른 위치를 참조합니다:
+
+```JSON hl_lines="4-16"
+{
+ "components": {
+ "schemas": {
+ "Message": {
+ "title": "Message",
+ "required": [
+ "message"
+ ],
+ "type": "object",
+ "properties": {
+ "message": {
+ "title": "Message",
+ "type": "string"
+ }
+ }
+ },
+ "Item": {
+ "title": "Item",
+ "required": [
+ "id",
+ "value"
+ ],
+ "type": "object",
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
+ },
+ "value": {
+ "title": "Value",
+ "type": "string"
+ }
+ }
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": [
+ "loc",
+ "msg",
+ "type"
+ ],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string"
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string"
+ }
+ }
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+## 주요 응답에 대한 추가 미디어 타입 { #additional-media-types-for-the-main-response }
+
+같은 `responses` 파라미터를 사용해 동일한 주요 응답에 대해 다른 미디어 타입을 추가할 수도 있습니다.
+
+예를 들어, *경로 처리*가 JSON 객체(미디어 타입 `application/json`) 또는 PNG 이미지(미디어 타입 `image/png`)를 반환할 수 있다고 선언하기 위해 `image/png`라는 추가 미디어 타입을 추가할 수 있습니다:
+
+{* ../../docs_src/additional_responses/tutorial002_py310.py hl[17:22,26] *}
+
+/// note | 참고
+
+이미지는 `FileResponse`를 사용해 직접 반환해야 한다는 점에 유의하세요.
+
+///
+
+/// info | 정보
+
+`responses` 파라미터에서 다른 미디어 타입을 명시적으로 지정하지 않는 한, FastAPI는 응답이 주요 응답 클래스와 동일한 미디어 타입(기본값 `application/json`)을 가진다고 가정합니다.
+
+하지만 커스텀 응답 클래스를 지정하면서 미디어 타입을 `None`으로 설정했다면, FastAPI는 연결된 모델이 있는 모든 추가 응답에 대해 `application/json`을 사용합니다.
+
+///
+
+## 정보 결합하기 { #combining-information }
+
+`response_model`, `status_code`, `responses` 파라미터를 포함해 여러 위치의 응답 정보를 결합할 수도 있습니다.
+
+기본 상태 코드 `200`(또는 필요하다면 커스텀 코드)을 사용하여 `response_model`을 선언하고, 그와 동일한 응답에 대한 추가 정보를 `responses`에서 OpenAPI 스키마에 직접 선언할 수 있습니다.
+
+**FastAPI**는 `responses`의 추가 정보를 유지하고, 모델의 JSON Schema와 결합합니다.
+
+예를 들어, Pydantic 모델을 사용하고 커스텀 `description`을 가진 상태 코드 `404` 응답을 선언할 수 있습니다.
+
+또한 `response_model`을 사용하는 상태 코드 `200` 응답을 선언하되, 커스텀 `example`을 포함할 수도 있습니다:
+
+{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}
+
+이 모든 내용은 OpenAPI에 결합되어 포함되고, API 문서에 표시됩니다:
+
+
+
+## 미리 정의된 응답과 커스텀 응답 결합하기 { #combine-predefined-responses-and-custom-ones }
+
+여러 *경로 처리*에 적용되는 미리 정의된 응답이 필요할 수도 있지만, 각 *경로 처리*마다 필요한 커스텀 응답과 결합하고 싶을 수도 있습니다.
+
+그런 경우 Python의 `dict` “unpacking” 기법인 `**dict_to_unpack`을 사용할 수 있습니다:
+
+```Python
+old_dict = {
+ "old key": "old value",
+ "second old key": "second old value",
+}
+new_dict = {**old_dict, "new key": "new value"}
+```
+
+여기서 `new_dict`는 `old_dict`의 모든 키-값 쌍에 더해 새 키-값 쌍까지 포함합니다:
+
+```Python
+{
+ "old key": "old value",
+ "second old key": "second old value",
+ "new key": "new value",
+}
+```
+
+이 기법을 사용해 *경로 처리*에서 일부 미리 정의된 응답을 재사용하고, 추가 커스텀 응답과 결합할 수 있습니다.
+
+예를 들어:
+
+{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}
+
+## OpenAPI 응답에 대한 추가 정보 { #more-information-about-openapi-responses }
+
+응답에 정확히 무엇을 포함할 수 있는지 보려면, OpenAPI 사양의 다음 섹션을 확인하세요:
+
+* [OpenAPI Responses Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responses-object): `Response Object`를 포함합니다.
+* [OpenAPI Response Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#response-object): `responses` 파라미터 안의 각 응답에 이것의 어떤 항목이든 직접 포함할 수 있습니다. `description`, `headers`, `content`(여기에서 서로 다른 미디어 타입과 JSON Schema를 선언합니다), `links` 등을 포함할 수 있습니다.
diff --git a/docs/ko/docs/advanced/additional-status-codes.md b/docs/ko/docs/advanced/additional-status-codes.md
new file mode 100644
index 0000000000000..6251b68b2315b
--- /dev/null
+++ b/docs/ko/docs/advanced/additional-status-codes.md
@@ -0,0 +1,41 @@
+# 추가 상태 코드 { #additional-status-codes }
+
+기본적으로 **FastAPI**는 응답을 `JSONResponse`를 사용하여 반환하며, *경로 처리*에서 반환한 내용을 해당 `JSONResponse` 안에 넣어 반환합니다.
+
+기본 상태 코드 또는 *경로 처리*에서 설정한 상태 코드를 사용합니다.
+
+## 추가 상태 코드 { #additional-status-codes_1 }
+
+기본 상태 코드와 별도로 추가 상태 코드를 반환하려면 `JSONResponse`와 같이 `Response`를 직접 반환하고 추가 상태 코드를 직접 설정할 수 있습니다.
+
+예를 들어 항목을 업데이트할 수 있는 *경로 처리*가 있고 성공 시 200 “OK”의 HTTP 상태 코드를 반환한다고 가정해 보겠습니다.
+
+하지만 새로운 항목을 허용하기를 원할 것입니다. 그리고 항목이 이전에 존재하지 않았다면 이를 생성하고 HTTP 상태 코드 201 "Created"를 반환합니다.
+
+이를 위해서는 `JSONResponse`를 가져와서 원하는 `status_code`를 설정하여 콘텐츠를 직접 반환합니다:
+
+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
+
+/// warning
+
+위의 예제처럼 `Response`를 직접 반환하면 바로 반환됩니다.
+
+모델 등과 함께 직렬화되지 않습니다.
+
+원하는 데이터가 있는지, 값이 유효한 JSON인지 확인합니다(`JSONResponse`를 사용하는 경우).
+
+///
+
+/// note | 기술 세부사항
+
+`from starlette.responses import JSONResponse`를 사용할 수도 있습니다.
+
+**FastAPI**는 개발자 여러분을 위한 편의성으로 `fastapi.responses`와 동일한 `starlette.responses`를 제공합니다. 그러나 사용 가능한 응답의 대부분은 Starlette에서 직접 제공됩니다. `status` 또한 마찬가지입니다.
+
+///
+
+## OpenAPI 및 API 문서 { #openapi-and-api-docs }
+
+추가 상태 코드와 응답을 직접 반환하는 경우, FastAPI는 반환할 내용을 미리 알 수 있는 방법이 없기 때문에 OpenAPI 스키마(API 문서)에 포함되지 않습니다.
+
+하지만 다음을 사용하여 코드에 이를 문서화할 수 있습니다: [추가 응답](additional-responses.md).
diff --git a/docs/ko/docs/advanced/advanced-dependencies.md b/docs/ko/docs/advanced/advanced-dependencies.md
new file mode 100644
index 0000000000000..2755986a21e4d
--- /dev/null
+++ b/docs/ko/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,164 @@
+# 고급 의존성 { #advanced-dependencies }
+
+## 매개변수화된 의존성 { #parameterized-dependencies }
+
+지금까지 본 모든 의존성은 고정된 함수 또는 클래스입니다.
+
+하지만 여러 개의 함수나 클래스를 선언하지 않고도 의존성에 매개변수를 설정해야 하는 경우가 있을 수 있습니다.
+
+예를 들어, `q` 쿼리 매개변수가 특정 고정된 내용을 포함하고 있는지 확인하는 의존성을 원한다고 가정해 봅시다.
+
+이때 해당 고정된 내용을 매개변수화할 수 있길 바랍니다.
+
+## "호출 가능한" 인스턴스 { #a-callable-instance }
+
+Python에는 클래스의 인스턴스를 "호출 가능"하게 만드는 방법이 있습니다.
+
+클래스 자체(이미 호출 가능함)가 아니라 해당 클래스의 인스턴스에 대해 호출 가능하게 하는 것입니다.
+
+이를 위해 `__call__` 메서드를 선언합니다:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}
+
+이 경우, **FastAPI**는 추가 매개변수와 하위 의존성을 확인하기 위해 `__call__`을 사용하게 되며,
+나중에 *경로 처리 함수*에서 매개변수에 값을 전달할 때 이를 호출하게 됩니다.
+
+## 인스턴스 매개변수화하기 { #parameterize-the-instance }
+
+이제 `__init__`을 사용하여 의존성을 "매개변수화"할 수 있는 인스턴스의 매개변수를 선언할 수 있습니다:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}
+
+이 경우, **FastAPI**는 `__init__`에 전혀 관여하지 않으며, 우리는 이 메서드를 코드에서 직접 사용하게 됩니다.
+
+## 인스턴스 생성하기 { #create-an-instance }
+
+다음과 같이 이 클래스의 인스턴스를 생성할 수 있습니다:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}
+
+이렇게 하면 `checker.fixed_content` 속성에 `"bar"`라는 값을 담아 의존성을 "매개변수화"할 수 있습니다.
+
+## 인스턴스를 의존성으로 사용하기 { #use-the-instance-as-a-dependency }
+
+그런 다음, 클래스 자체가 아닌 인스턴스 `checker`가 의존성이 되므로, `Depends(FixedContentQueryChecker)` 대신 `Depends(checker)`에서 이 `checker` 인스턴스를 사용할 수 있습니다.
+
+의존성을 해결할 때 **FastAPI**는 이 `checker`를 다음과 같이 호출합니다:
+
+```Python
+checker(q="somequery")
+```
+
+...그리고 이때 반환되는 값을 *경로 처리 함수*의 의존성 값으로, `fixed_content_included` 매개변수에 전달합니다:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}
+
+/// tip | 팁
+
+이 모든 과정이 복잡하게 느껴질 수 있습니다. 그리고 지금은 이 방법이 얼마나 유용한지 명확하지 않을 수도 있습니다.
+
+이 예시는 의도적으로 간단하게 만들었지만, 전체 구조가 어떻게 작동하는지 보여줍니다.
+
+보안 관련 장에서는 이와 같은 방식으로 구현된 유틸리티 함수들이 있습니다.
+
+이 모든 과정을 이해했다면, 이러한 보안용 유틸리티 도구들이 내부적으로 어떻게 작동하는지 이미 파악한 것입니다.
+
+///
+
+## `yield`, `HTTPException`, `except`, 백그라운드 태스크가 있는 의존성 { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+/// warning | 경고
+
+대부분의 경우 이러한 기술 세부사항이 필요하지 않을 것입니다.
+
+이 세부사항은 주로 0.121.0 이전의 FastAPI 애플리케이션이 있고 `yield`가 있는 의존성에서 문제가 발생하는 경우에 유용합니다.
+
+///
+
+`yield`가 있는 의존성은 여러 사용 사례를 수용하고 일부 문제를 해결하기 위해 시간이 지나며 발전해 왔습니다. 다음은 변경된 내용의 요약입니다.
+
+### `yield`와 `scope`가 있는 의존성 { #dependencies-with-yield-and-scope }
+
+0.121.0 버전에서 FastAPI는 `Depends(scope="function")` 지원을 추가했습니다.
+
+`Depends(scope="function")`를 사용하면, `yield` 이후의 종료 코드는 *경로 처리 함수*가 끝난 직후(클라이언트에 응답이 반환되기 전)에 실행됩니다.
+
+그리고 `Depends(scope="request")`(기본값)를 사용하면, `yield` 이후의 종료 코드는 응답이 전송된 후에 실행됩니다.
+
+자세한 내용은 [`yield`가 있는 의존성 - 조기 종료와 `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope) 문서를 참고하세요.
+
+### `yield`가 있는 의존성과 `StreamingResponse`, 기술 세부사항 { #dependencies-with-yield-and-streamingresponse-technical-details }
+
+FastAPI 0.118.0 이전에는 `yield`가 있는 의존성을 사용하면, *경로 처리 함수*가 반환된 뒤 응답을 보내기 직전에 `yield` 이후의 종료 코드가 실행되었습니다.
+
+의도는 응답이 네트워크를 통해 전달되기를 기다리면서 필요한 것보다 더 오래 리소스를 점유하지 않도록 하는 것이었습니다.
+
+이 변경은 `StreamingResponse`를 반환하는 경우에도 `yield`가 있는 의존성의 종료 코드가 이미 실행된다는 의미이기도 했습니다.
+
+예를 들어, `yield`가 있는 의존성에 데이터베이스 세션이 있다면, `StreamingResponse`는 데이터를 스트리밍하는 동안 해당 세션을 사용할 수 없게 됩니다. `yield` 이후의 종료 코드에서 세션이 이미 닫혔기 때문입니다.
+
+이 동작은 0.118.0에서 되돌려져, `yield` 이후의 종료 코드가 응답이 전송된 뒤 실행되도록 변경되었습니다.
+
+/// info | 정보
+
+아래에서 보시겠지만, 이는 0.106.0 버전 이전의 동작과 매우 비슷하지만, 여러 개선 사항과 코너 케이스에 대한 버그 수정이 포함되어 있습니다.
+
+///
+
+#### 종료 코드를 조기에 실행하는 사용 사례 { #use-cases-with-early-exit-code }
+
+특정 조건의 일부 사용 사례에서는 응답을 보내기 전에 `yield`가 있는 의존성의 종료 코드를 실행하던 예전 동작이 도움이 될 수 있습니다.
+
+예를 들어, `yield`가 있는 의존성에서 데이터베이스 세션을 사용해 사용자를 검증만 하고, *경로 처리 함수*에서는 그 데이터베이스 세션을 다시는 사용하지 않으며(의존성에서만 사용), **그리고** 응답을 전송하는 데 오랜 시간이 걸리는 경우를 생각해 봅시다. 예를 들어 데이터를 천천히 보내는 `StreamingResponse`인데, 어떤 이유로든 데이터베이스를 사용하지는 않는 경우입니다.
+
+이 경우 데이터베이스 세션은 응답 전송이 끝날 때까지 유지되지만, 사용하지 않는다면 굳이 유지할 필요가 없습니다.
+
+다음과 같이 보일 수 있습니다:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
+
+다음에서 `Session`을 자동으로 닫는 종료 코드는:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
+
+...응답이 느린 데이터 전송을 마친 뒤에 실행됩니다:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
+
+하지만 `generate_stream()`는 데이터베이스 세션을 사용하지 않으므로, 응답을 전송하는 동안 세션을 열린 채로 유지할 필요는 없습니다.
+
+SQLModel(또는 SQLAlchemy)을 사용하면서 이런 특정 사용 사례가 있다면, 더 이상 필요하지 않을 때 세션을 명시적으로 닫을 수 있습니다:
+
+{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}
+
+그러면 세션이 데이터베이스 연결을 해제하여, 다른 요청들이 이를 사용할 수 있게 됩니다.
+
+`yield`가 있는 의존성에서 조기 종료가 필요한 다른 사용 사례가 있다면, 여러분의 구체적인 사용 사례와 `yield`가 있는 의존성에 대한 조기 종료가 어떤 점에서 이득이 되는지를 포함해 [GitHub Discussions 질문](https://github.com/fastapi/fastapi/discussions/new?category=questions)을 생성해 주세요.
+
+`yield`가 있는 의존성에서 조기 종료에 대한 설득력 있는 사용 사례가 있다면, 조기 종료를 선택적으로 활성화할 수 있는 새로운 방법을 추가하는 것을 고려하겠습니다.
+
+### `yield`가 있는 의존성과 `except`, 기술 세부사항 { #dependencies-with-yield-and-except-technical-details }
+
+FastAPI 0.110.0 이전에는 `yield`가 있는 의존성을 사용한 다음 그 의존성에서 `except`로 예외를 잡고, 예외를 다시 발생시키지 않으면, 예외가 자동으로 어떤 예외 핸들러 또는 내부 서버 오류 핸들러로 raise/forward 되었습니다.
+
+이는 핸들러 없이 전달된 예외(내부 서버 오류)로 인해 처리되지 않은 메모리 사용이 발생하는 문제를 수정하고, 일반적인 Python 코드의 동작과 일관되게 하기 위해 0.110.0 버전에서 변경되었습니다.
+
+### 백그라운드 태스크와 `yield`가 있는 의존성, 기술 세부사항 { #background-tasks-and-dependencies-with-yield-technical-details }
+
+FastAPI 0.106.0 이전에는 `yield` 이후에 예외를 발생시키는 것이 불가능했습니다. `yield`가 있는 의존성의 종료 코드는 응답이 전송된 *후에* 실행되었기 때문에, [예외 핸들러](../tutorial/handling-errors.md#install-custom-exception-handlers)가 이미 실행된 뒤였습니다.
+
+이는 주로 백그라운드 태스크 안에서 의존성이 "yield"한 동일한 객체들을 사용할 수 있게 하기 위한 설계였습니다. 백그라운드 태스크가 끝난 뒤에 종료 코드가 실행되었기 때문입니다.
+
+이는 응답이 네트워크를 통해 전달되기를 기다리는 동안 리소스를 점유하지 않기 위한 의도로 FastAPI 0.106.0에서 변경되었습니다.
+
+/// tip | 팁
+
+추가로, 백그라운드 태스크는 보통 별도의 리소스(예: 자체 데이터베이스 연결)를 가지고 따로 처리되어야 하는 독립적인 로직 집합입니다.
+
+따라서 이 방식이 코드를 더 깔끔하게 만들어줄 가능성이 큽니다.
+
+///
+
+이 동작에 의존하던 경우라면, 이제는 백그라운드 태스크를 위한 리소스를 백그라운드 태스크 내부에서 생성하고, 내부적으로는 `yield`가 있는 의존성의 리소스에 의존하지 않는 데이터만 사용해야 합니다.
+
+예를 들어, 동일한 데이터베이스 세션을 사용하는 대신, 백그라운드 태스크 내부에서 새 데이터베이스 세션을 생성하고, 이 새 세션을 사용해 데이터베이스에서 객체를 가져오면 됩니다. 그리고 데이터베이스에서 가져온 객체를 백그라운드 태스크 함수의 매개변수로 전달하는 대신, 해당 객체의 ID를 전달한 다음 백그라운드 태스크 함수 내부에서 객체를 다시 가져오면 됩니다.
diff --git a/docs/ko/docs/advanced/advanced-python-types.md b/docs/ko/docs/advanced/advanced-python-types.md
new file mode 100644
index 0000000000000..0bd8aa543381b
--- /dev/null
+++ b/docs/ko/docs/advanced/advanced-python-types.md
@@ -0,0 +1,61 @@
+# 고급 Python 타입 { #advanced-python-types }
+
+Python 타입을 다룰 때 유용할 수 있는 몇 가지 추가 아이디어를 소개합니다.
+
+## `Union` 또는 `Optional` 사용 { #using-union-or-optional }
+
+어떤 이유로 코드에서 `|`를 사용할 수 없다면, 예를 들어 타입 어노테이션이 아니라 `response_model=` 같은 곳이라면, 파이프 문자(`|`) 대신 `typing`의 `Union`을 사용할 수 있습니다.
+
+예를 들어, 어떤 값이 `str` 또는 `None`이 될 수 있다고 선언할 수 있습니다:
+
+```python
+from typing import Union
+
+
+def say_hi(name: Union[str, None]):
+ print(f"Hi {name}!")
+```
+
+`typing`에는 `None`이 될 수 있음을 선언하는 축약형으로 `Optional`도 있습니다.
+
+아주 개인적인 관점에서의 팁입니다:
+
+- 🚨 `Optional[SomeType]` 사용은 피하세요
+- 대신 ✨ **`Union[SomeType, None]`를 사용하세요** ✨.
+
+둘은 동등하며 내부적으로도 같습니다. 하지만 단어 "optional"은 값이 선택 사항이라는 인상을 주는 반면, 실제 의미는 "값이 `None`이 될 수 있다"는 뜻입니다. 값이 선택 사항이 아니라 여전히 필수인 경우에도 그렇습니다.
+
+`Union[SomeType, None]`가 의미를 더 명확하게 드러낸다고 생각합니다.
+
+이는 단지 단어와 명칭의 문제입니다. 하지만 이런 단어가 여러분과 팀원이 코드를 어떻게 생각하는지에 영향을 줄 수 있습니다.
+
+예를 들어, 다음 함수를 보세요:
+
+```python
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+ print(f"Hey {name}!")
+```
+
+매개변수 `name`은 `Optional[str]`로 정의되어 있지만, 사실 선택적이지 않습니다. 이 매개변수 없이 함수를 호출할 수 없습니다:
+
+```Python
+say_hi() # 이런, 에러가 발생합니다! 😱
+```
+
+`name` 매개변수는 기본값이 없기 때문에 여전히 필수입니다(선택적이 아님). 대신, `name`에는 `None`을 전달할 수 있습니다:
+
+```Python
+say_hi(name=None) # 작동합니다. None은 유효합니다 🎉
+```
+
+좋은 소식은, 대부분의 경우 타입의 합집합을 정의할 때 그냥 `|`를 사용할 수 있다는 점입니다:
+
+```python
+def say_hi(name: str | None):
+ print(f"Hey {name}!")
+```
+
+그래서 보통은 `Optional`과 `Union` 같은 이름에 대해 걱정하지 않으셔도 됩니다. 😎
diff --git a/docs/ko/docs/advanced/async-tests.md b/docs/ko/docs/advanced/async-tests.md
new file mode 100644
index 0000000000000..b477c6c715e11
--- /dev/null
+++ b/docs/ko/docs/advanced/async-tests.md
@@ -0,0 +1,99 @@
+# 비동기 테스트 { #async-tests }
+
+제공된 `TestClient`를 사용하여 **FastAPI** 애플리케이션을 테스트하는 방법을 이미 살펴보았습니다. 지금까지는 `async` 함수를 사용하지 않고, 동기 테스트를 작성하는 방법만 보았습니다.
+
+테스트에서 비동기 함수를 사용할 수 있으면 유용할 수 있습니다. 예를 들어 데이터베이스를 비동기로 쿼리하는 경우를 생각해 보세요. FastAPI 애플리케이션에 요청을 보낸 다음, async 데이터베이스 라이브러리를 사용하면서 백엔드가 데이터베이스에 올바른 데이터를 성공적으로 기록했는지 검증하고 싶을 수 있습니다.
+
+어떻게 동작하게 만들 수 있는지 살펴보겠습니다.
+
+## pytest.mark.anyio { #pytest-mark-anyio }
+
+테스트에서 비동기 함수를 호출하려면, 테스트 함수도 비동기여야 합니다. AnyIO는 이를 위한 깔끔한 플러그인을 제공하며, 일부 테스트 함수를 비동기로 호출하도록 지정할 수 있습니다.
+
+## HTTPX { #httpx }
+
+**FastAPI** 애플리케이션이 `async def` 대신 일반 `def` 함수를 사용하더라도, 내부적으로는 여전히 `async` 애플리케이션입니다.
+
+`TestClient`는 표준 pytest를 사용하여, 일반 `def` 테스트 함수 안에서 비동기 FastAPI 애플리케이션을 호출하도록 내부에서 마법 같은 처리를 합니다. 하지만 비동기 함수 안에서 이를 사용하면 그 마법은 더 이상 동작하지 않습니다. 테스트를 비동기로 실행하면, 테스트 함수 안에서 `TestClient`를 더 이상 사용할 수 없습니다.
+
+`TestClient`는 [HTTPX](https://www.python-httpx.org)를 기반으로 하며, 다행히 HTTPX를 직접 사용해 API를 테스트할 수 있습니다.
+
+## 예시 { #example }
+
+간단한 예시로, [더 큰 애플리케이션](../tutorial/bigger-applications.md)과 [테스트](../tutorial/testing.md)에서 설명한 것과 비슷한 파일 구조를 살펴보겠습니다:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+`main.py` 파일은 다음과 같습니다:
+
+{* ../../docs_src/async_tests/app_a_py310/main.py *}
+
+`test_main.py` 파일에는 `main.py`에 대한 테스트가 있으며, 이제 다음과 같이 보일 수 있습니다:
+
+{* ../../docs_src/async_tests/app_a_py310/test_main.py *}
+
+## 실행하기 { #run-it }
+
+다음과 같이 평소처럼 테스트를 실행할 수 있습니다:
+
+
+
+하지만 프록시(포트 `9999`)를 사용해 "공식" URL인 `/api/v1/docs`에서 docs UI에 접근하면, 올바르게 동작합니다! 🎉
+
+[http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs)에서 확인할 수 있습니다:
+
+
+
+원하던 그대로입니다. ✔️
+
+이는 FastAPI가 이 `root_path`를 사용해, OpenAPI에서 기본 `server`를 `root_path`가 제공한 URL로 생성하기 때문입니다.
+
+## 추가 서버 { #additional-servers }
+
+/// warning | 경고
+
+이는 더 고급 사용 사례입니다. 건너뛰어도 괜찮습니다.
+
+///
+
+기본적으로 **FastAPI**는 OpenAPI 스키마에서 `root_path`의 URL로 `server`를 생성합니다.
+
+하지만 예를 들어 동일한 docs UI가 스테이징과 프로덕션 환경 모두와 상호작용하도록 하려면, 다른 대안 `servers`를 제공할 수도 있습니다.
+
+사용자 정의 `servers` 리스트를 전달했고 `root_path`(API가 프록시 뒤에 있기 때문)가 있다면, **FastAPI**는 리스트의 맨 앞에 이 `root_path`를 가진 "server"를 삽입합니다.
+
+예:
+
+{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}
+
+다음과 같은 OpenAPI 스키마를 생성합니다:
+
+```JSON hl_lines="5-7"
+{
+ "openapi": "3.1.0",
+ // 여기에 다른 내용이 더 있습니다
+ "servers": [
+ {
+ "url": "/api/v1"
+ },
+ {
+ "url": "https://stag.example.com",
+ "description": "Staging environment"
+ },
+ {
+ "url": "https://prod.example.com",
+ "description": "Production environment"
+ }
+ ],
+ "paths": {
+ // 여기에 다른 내용이 더 있습니다
+ }
+}
+```
+
+/// tip | 팁
+
+`root_path`에서 가져온 값인 `/api/v1`의 `url` 값을 가진, 자동 생성된 server에 주목하세요.
+
+///
+
+[http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs)의 docs UI에서는 다음처럼 보입니다:
+
+
+
+/// tip | 팁
+
+docs UI는 선택한 server와 상호작용합니다.
+
+///
+
+/// note | 기술 세부사항
+
+OpenAPI 사양에서 `servers` 속성은 선택 사항입니다.
+
+`servers` 파라미터를 지정하지 않고 `root_path`가 `/`와 같다면, 생성된 OpenAPI 스키마의 `servers` 속성은 기본적으로 완전히 생략되며, 이는 `url` 값이 `/`인 단일 server와 동등합니다.
+
+///
+
+### `root_path`에서 자동 server 비활성화하기 { #disable-automatic-server-from-root-path }
+
+**FastAPI**가 `root_path`를 사용한 자동 server를 포함하지 않게 하려면, `root_path_in_servers=False` 파라미터를 사용할 수 있습니다:
+
+{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}
+
+그러면 OpenAPI 스키마에 포함되지 않습니다.
+
+## 서브 애플리케이션 마운트하기 { #mounting-a-sub-application }
+
+프록시에서 `root_path`를 사용하면서도, [서브 애플리케이션 - 마운트](sub-applications.md)에 설명된 것처럼 서브 애플리케이션을 마운트해야 한다면, 기대하는 대로 일반적으로 수행할 수 있습니다.
+
+FastAPI가 내부적으로 `root_path`를 똑똑하게 사용하므로, 그냥 동작합니다. ✨
diff --git a/docs/ko/docs/advanced/custom-response.md b/docs/ko/docs/advanced/custom-response.md
new file mode 100644
index 0000000000000..e85ec3c743cd2
--- /dev/null
+++ b/docs/ko/docs/advanced/custom-response.md
@@ -0,0 +1,273 @@
+# 사용자 정의 응답 - HTML, Stream, 파일, 기타 { #custom-response-html-stream-file-others }
+
+기본적으로 **FastAPI**는 JSON 응답을 반환합니다.
+
+[응답을 직접 반환하기](response-directly.md)에서 본 것처럼 `Response`를 직접 반환하여 이를 재정의할 수 있습니다.
+
+그러나 `Response`를 직접 반환하면(또는 `JSONResponse`와 같은 하위 클래스를 반환하면) 데이터가 자동으로 변환되지 않으며(비록 `response_model`을 선언했다 하더라도), 문서도 자동으로 생성되지 않습니다(예를 들어, 생성된 OpenAPI의 일부로 HTTP 헤더 `Content-Type`에 특정 "미디어 타입"을 포함하는 것 등).
+
+하지만 *경로 처리 데코레이터*에서 `response_class` 매개변수를 사용하여 사용할 `Response`(예: 어떤 `Response` 하위 클래스든)를 선언할 수도 있습니다.
+
+*경로 처리 함수*에서 반환하는 내용은 해당 `Response` 안에 담깁니다.
+
+/// note | 참고
+
+미디어 타입이 없는 응답 클래스를 사용하는 경우, FastAPI는 응답에 내용이 없을 것으로 예상하므로 생성된 OpenAPI 문서에서 응답 형식을 문서화하지 않습니다.
+
+///
+
+## JSON 응답 { #json-responses }
+
+기본적으로 FastAPI는 JSON 응답을 반환합니다.
+
+[응답 모델](../tutorial/response-model.md)을 선언하면 FastAPI는 Pydantic을 사용해 데이터를 JSON으로 직렬화합니다.
+
+응답 모델을 선언하지 않으면 FastAPI는 [JSON 호환 가능 인코더](../tutorial/encoder.md)에서 설명한 `jsonable_encoder`를 사용해 데이터를 변환한 뒤 `JSONResponse`에 넣습니다.
+
+`JSONResponse`처럼 JSON 미디어 타입(`application/json`)을 가진 `response_class`를 선언하면, 여러분이 *경로 처리 데코레이터*에서 선언한 Pydantic의 `response_model`로 데이터가 자동 변환(및 필터링)됩니다. 하지만 데이터의 JSON 바이트 직렬화 자체는 Pydantic이 수행하지 않고, `jsonable_encoder`로 변환한 후 `JSONResponse` 클래스에 전달하며, 그 클래스가 Python 표준 JSON 라이브러리를 사용해 바이트로 직렬화합니다.
+
+### JSON 성능 { #json-performance }
+
+요약하면, 최대 성능이 필요하다면 [응답 모델](../tutorial/response-model.md)을 사용하고, *경로 처리 데코레이터*에 `response_class`를 선언하지 마세요.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py ln[15:17] hl[16] *}
+
+## HTML 응답 { #html-response }
+
+**FastAPI**에서 HTML 응답을 직접 반환하려면 `HTMLResponse`를 사용하세요.
+
+* `HTMLResponse`를 임포트합니다.
+* *경로 처리 데코레이터*의 `response_class` 매개변수로 `HTMLResponse`를 전달합니다.
+
+{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}
+
+/// info | 정보
+
+`response_class` 매개변수는 응답의 "미디어 타입"을 정의하는 데에도 사용됩니다.
+
+이 경우, HTTP 헤더 `Content-Type`은 `text/html`로 설정됩니다.
+
+그리고 이는 OpenAPI에 그대로 문서화됩니다.
+
+///
+
+### `Response` 반환하기 { #return-a-response }
+
+[응답을 직접 반환하기](response-directly.md)에서 본 것처럼, *경로 처리*에서 응답을 직접 반환하여 재정의할 수도 있습니다.
+
+위의 예제와 동일하게 `HTMLResponse`를 반환하는 코드는 다음과 같을 수 있습니다:
+
+{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}
+
+/// warning | 경고
+
+*경로 처리 함수*에서 직접 반환된 `Response`는 OpenAPI에 문서화되지 않습니다(예를 들어, `Content-Type`이 문서화되지 않음) 그리고 자동 대화형 문서에도 표시되지 않습니다.
+
+///
+
+/// info | 정보
+
+물론 실제 `Content-Type` 헤더, 상태 코드 등은 반환된 `Response` 객체에서 가져옵니다.
+
+///
+
+### OpenAPI에 문서화하고 `Response` 재정의하기 { #document-in-openapi-and-override-response }
+
+함수 내부에서 응답을 재정의하면서 동시에 OpenAPI에서 "미디어 타입"을 문서화하고 싶다면, `response_class` 매개변수를 사용하면서 `Response` 객체를 반환할 수 있습니다.
+
+이 경우 `response_class`는 OpenAPI *경로 처리*를 문서화하는 데만 사용되고, 실제로는 여러분이 반환한 `Response`가 그대로 사용됩니다.
+
+#### `HTMLResponse` 직접 반환하기 { #return-an-htmlresponse-directly }
+
+예를 들어, 다음과 같이 작성할 수 있습니다:
+
+{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}
+
+이 예제에서 `generate_html_response()` 함수는 HTML을 `str`로 반환하는 대신 이미 `Response`를 생성하고 반환합니다.
+
+`generate_html_response()`를 호출한 결과를 반환함으로써, 기본적인 **FastAPI** 동작을 재정의하는 `Response`를 이미 반환하고 있습니다.
+
+하지만 `response_class`에 `HTMLResponse`를 함께 전달했기 때문에, **FastAPI**는 이를 OpenAPI 및 대화형 문서에서 `text/html`의 HTML로 문서화하는 방법을 알 수 있습니다:
+
+
+
+## 사용 가능한 응답들 { #available-responses }
+
+다음은 사용할 수 있는 몇 가지 응답들입니다.
+
+`Response`를 사용하여 다른 어떤 것도 반환할 수 있으며, 직접 하위 클래스를 만들 수도 있습니다.
+
+/// note | 기술 세부사항
+
+`from starlette.responses import HTMLResponse`를 사용할 수도 있습니다.
+
+**FastAPI**는 개발자인 여러분의 편의를 위해 `starlette.responses`를 `fastapi.responses`로 동일하게 제공하지만, 대부분의 사용 가능한 응답은 Starlette에서 직접 가져옵니다.
+
+///
+
+### `Response` { #response }
+
+기본 `Response` 클래스이며, 다른 모든 응답 클래스가 이를 상속합니다.
+
+이 클래스를 직접 반환할 수 있습니다.
+
+다음 매개변수를 받을 수 있습니다:
+
+* `content` - `str` 또는 `bytes`.
+* `status_code` - HTTP 상태 코드를 나타내는 `int`.
+* `headers` - 문자열로 이루어진 `dict`.
+* `media_type` - 미디어 타입을 나타내는 `str` 예: `"text/html"`.
+
+FastAPI(정확히는 Starlette)가 자동으로 Content-Length 헤더를 포함시킵니다. 또한 `media_type`에 기반하여 Content-Type 헤더를 포함하며, 텍스트 타입의 경우 문자 집합을 추가합니다.
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+### `HTMLResponse` { #htmlresponse }
+
+텍스트 또는 바이트를 받아 HTML 응답을 반환합니다. 위에서 설명한 내용과 같습니다.
+
+### `PlainTextResponse` { #plaintextresponse }
+
+텍스트 또는 바이트를 받아 일반 텍스트 응답을 반환합니다.
+
+{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}
+
+### `JSONResponse` { #jsonresponse }
+
+데이터를 받아 `application/json`으로 인코딩된 응답을 반환합니다.
+
+이는 위에서 설명했듯이 **FastAPI**에서 기본적으로 사용되는 응답 형식입니다.
+
+/// note | 기술 세부사항
+
+하지만 응답 모델 또는 반환 타입을 선언한 경우, 해당 모델이 데이터를 JSON으로 직렬화하는 데 직접 사용되며, 올바른 JSON 미디어 타입의 응답이 `JSONResponse` 클래스를 사용하지 않고 바로 반환됩니다.
+
+이 방식이 최상의 성능을 얻는 이상적인 방법입니다.
+
+///
+
+### `RedirectResponse` { #redirectresponse }
+
+HTTP 리디렉션 응답을 반환합니다. 기본적으로 상태 코드는 307(임시 리디렉션)으로 설정됩니다.
+
+`RedirectResponse`를 직접 반환할 수 있습니다:
+
+{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}
+
+---
+
+또는 `response_class` 매개변수에서 사용할 수도 있습니다:
+
+
+{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}
+
+이 경우, *경로 처리* 함수에서 URL을 직접 반환할 수 있습니다.
+
+이 경우, 사용되는 `status_code`는 `RedirectResponse`의 기본값인 `307`입니다.
+
+---
+
+`status_code` 매개변수를 `response_class` 매개변수와 함께 사용할 수도 있습니다:
+
+{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}
+
+### `StreamingResponse` { #streamingresponse }
+
+비동기 제너레이터 또는 일반 제너레이터/이터레이터(`yield`가 있는 함수)를 받아 응답 본문을 스트리밍합니다.
+
+{* ../../docs_src/custom_response/tutorial007_py310.py hl[3,16] *}
+
+/// note | 기술 세부사항
+
+`async` 작업은 `await`에 도달했을 때만 취소될 수 있습니다. `await`가 없으면 제너레이터(`yield`가 있는 함수)는 제대로 취소될 수 없고, 취소가 요청된 후에도 계속 실행될 수 있습니다.
+
+이 작은 예제는 어떤 `await`도 필요하지 않으므로, 이벤트 루프가 취소를 처리할 기회를 주기 위해 `await anyio.sleep(0)`를 추가합니다.
+
+대규모 또는 무한 스트림에서는 더욱 중요합니다.
+
+///
+
+/// tip | 팁
+
+`StreamingResponse`를 직접 반환하는 대신, [데이터 스트리밍](./stream-data.md)에서의 스타일을 따르는 것이 더 편리하며 백그라운드에서 취소 처리를 해줍니다.
+
+JSON Lines를 스트리밍한다면, [JSON Lines 스트리밍](../tutorial/stream-json-lines.md) 튜토리얼을 확인하세요.
+
+///
+
+### `FileResponse` { #fileresponse }
+
+파일을 비동기로 스트리밍하여 응답합니다.
+
+다른 응답 유형과는 다른 인수를 사용하여 객체를 생성합니다:
+
+* `path` - 스트리밍할 파일의 경로.
+* `headers` - 딕셔너리 형식의 사용자 정의 헤더.
+* `media_type` - 미디어 타입을 나타내는 문자열. 설정되지 않은 경우 파일 이름이나 경로를 사용하여 추론합니다.
+* `filename` - 설정된 경우 응답의 `Content-Disposition`에 포함됩니다.
+
+파일 응답에는 적절한 `Content-Length`, `Last-Modified`, 및 `ETag` 헤더가 포함됩니다.
+
+{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}
+
+또한 `response_class` 매개변수를 사용할 수도 있습니다:
+
+{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}
+
+이 경우, 경로 처리 함수에서 파일 경로를 직접 반환할 수 있습니다.
+
+## 사용자 정의 응답 클래스 { #custom-response-class }
+
+`Response`를 상속받아 사용자 정의 응답 클래스를 생성하고 사용할 수 있습니다.
+
+예를 들어, [`orjson`](https://github.com/ijl/orjson)을 일부 설정과 함께 사용하고 싶다고 가정해봅시다.
+
+들여쓰기 및 포맷된 JSON을 반환하고 싶다면, orjson 옵션 `orjson.OPT_INDENT_2`를 사용할 수 있습니다.
+
+`CustomORJSONResponse`를 생성할 수 있습니다. 여기서 핵심은 `Response.render(content)` 메서드를 생성하여 내용을 `bytes`로 반환하는 것입니다:
+
+{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}
+
+이제 다음 대신:
+
+```json
+{"message": "Hello World"}
+```
+
+...이 응답은 이렇게 반환됩니다:
+
+```json
+{
+ "message": "Hello World"
+}
+```
+
+물론 JSON 포맷팅보다 더 유용하게 활용할 방법을 찾을 수 있을 것입니다. 😉
+
+### `orjson` 또는 응답 모델 { #orjson-or-response-model }
+
+성능이 목적이라면, `orjson` 응답을 사용하는 것보다 [응답 모델](../tutorial/response-model.md)을 사용하는 편이 더 나을 가능성이 큽니다.
+
+응답 모델을 사용하면 FastAPI는 중간 단계(예: `jsonable_encoder`로의 변환) 없이 Pydantic을 사용해 데이터를 JSON으로 직렬화합니다. 이런 중간 단계는 다른 경우에 발생합니다.
+
+그리고 내부적으로 Pydantic은 JSON 직렬화를 위해 `orjson`과 동일한 Rust 기반 메커니즘을 사용하므로, 응답 모델만으로도 이미 최상의 성능을 얻게 됩니다.
+
+## 기본 응답 클래스 { #default-response-class }
+
+**FastAPI** 클래스 인스턴스 또는 `APIRouter`를 생성할 때 기본으로 사용할 응답 클래스를 지정할 수 있습니다.
+
+이를 정의하는 매개변수는 `default_response_class`입니다.
+
+아래 예제에서 **FastAPI**는 모든 *경로 처리*에서 JSON 대신 기본적으로 `HTMLResponse`를 사용합니다.
+
+{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}
+
+/// tip | 팁
+
+여전히 이전처럼 *경로 처리*에서 `response_class`를 재정의할 수 있습니다.
+
+///
+
+## 추가 문서화 { #additional-documentation }
+
+OpenAPI에서 `responses`를 사용하여 미디어 타입 및 기타 세부 정보를 선언할 수도 있습니다: [OpenAPI에서 추가 응답](additional-responses.md).
diff --git a/docs/ko/docs/advanced/dataclasses.md b/docs/ko/docs/advanced/dataclasses.md
new file mode 100644
index 0000000000000..77e8d0464cbef
--- /dev/null
+++ b/docs/ko/docs/advanced/dataclasses.md
@@ -0,0 +1,95 @@
+# Dataclasses 사용하기 { #using-dataclasses }
+
+FastAPI는 **Pydantic** 위에 구축되어 있으며, 지금까지는 Pydantic 모델을 사용해 요청과 응답을 선언하는 방법을 보여드렸습니다.
+
+하지만 FastAPI는 [`dataclasses`](https://docs.python.org/3/library/dataclasses.html)도 같은 방식으로 사용하는 것을 지원합니다:
+
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
+
+이는 **Pydantic** 덕분에 여전히 지원되는데, Pydantic이 [`dataclasses`에 대한 내부 지원](https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel)을 제공하기 때문입니다.
+
+따라서 위 코드처럼 Pydantic을 명시적으로 사용하지 않더라도, FastAPI는 Pydantic을 사용해 표준 dataclasses를 Pydantic의 dataclasses 변형으로 변환합니다.
+
+그리고 물론 다음과 같은 기능도 동일하게 지원합니다:
+
+* 데이터 검증
+* 데이터 직렬화
+* 데이터 문서화 등
+
+이는 Pydantic 모델을 사용할 때와 같은 방식으로 동작합니다. 그리고 실제로도 내부적으로는 Pydantic을 사용해 같은 방식으로 구현됩니다.
+
+/// info
+
+dataclasses는 Pydantic 모델이 할 수 있는 모든 것을 할 수는 없다는 점을 기억하세요.
+
+그래서 여전히 Pydantic 모델을 사용해야 할 수도 있습니다.
+
+하지만 이미 여러 dataclasses를 가지고 있다면, 이것은 FastAPI로 웹 API를 구동하는 데 그것들을 활용할 수 있는 좋은 방법입니다. 🤓
+
+///
+
+## `response_model`에서 Dataclasses 사용하기 { #dataclasses-in-response-model }
+
+`response_model` 매개변수에서도 `dataclasses`를 사용할 수 있습니다:
+
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
+
+dataclass는 자동으로 Pydantic dataclass로 변환됩니다.
+
+이렇게 하면 해당 스키마가 API docs 사용자 인터페이스에 표시됩니다:
+
+
+
+## 중첩 데이터 구조에서 Dataclasses 사용하기 { #dataclasses-in-nested-data-structures }
+
+`dataclasses`를 다른 타입 애너테이션과 조합해 중첩 데이터 구조를 만들 수도 있습니다.
+
+일부 경우에는 Pydantic 버전의 `dataclasses`를 사용해야 할 수도 있습니다. 예를 들어 자동 생성된 API 문서에서 오류가 발생하는 경우입니다.
+
+그런 경우 표준 `dataclasses`를 드롭인 대체재인 `pydantic.dataclasses`로 간단히 바꾸면 됩니다:
+
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+
+1. 표준 `dataclasses`에서 `field`를 계속 임포트합니다.
+
+2. `pydantic.dataclasses`는 `dataclasses`의 드롭인 대체재입니다.
+
+3. `Author` dataclass에는 `Item` dataclasses의 리스트가 포함됩니다.
+
+4. `Author` dataclass가 `response_model` 매개변수로 사용됩니다.
+
+5. 요청 본문으로 dataclasses와 함께 다른 표준 타입 애너테이션을 사용할 수 있습니다.
+
+ 이 경우에는 `Item` dataclasses의 리스트입니다.
+
+6. 여기서는 dataclasses 리스트인 `items`를 포함하는 딕셔너리를 반환합니다.
+
+ FastAPI는 여전히 데이터를 JSON으로 직렬화할 수 있습니다.
+
+7. 여기서 `response_model`은 `Author` dataclasses 리스트에 대한 타입 애너테이션을 사용합니다.
+
+ 다시 말해, `dataclasses`를 표준 타입 애너테이션과 조합할 수 있습니다.
+
+8. 이 *경로 처리 함수*는 `async def` 대신 일반 `def`를 사용하고 있다는 점에 주목하세요.
+
+ 언제나처럼 FastAPI에서는 필요에 따라 `def`와 `async def`를 조합해 사용할 수 있습니다.
+
+ 어떤 것을 언제 사용해야 하는지 다시 확인하고 싶다면, [`async`와 `await`](../async.md#in-a-hurry) 문서의 _"급하신가요?"_ 섹션을 확인하세요.
+
+9. 이 *경로 처리 함수*는 dataclasses를(물론 반환할 수도 있지만) 반환하지 않고, 내부 데이터를 담은 딕셔너리들의 리스트를 반환합니다.
+
+ FastAPI는 `response_model` 매개변수(dataclasses 포함)를 사용해 응답을 변환합니다.
+
+`dataclasses`는 다른 타입 애너테이션과 매우 다양한 조합으로 결합해 복잡한 데이터 구조를 구성할 수 있습니다.
+
+더 구체적인 내용은 위 코드 내 애너테이션 팁을 확인하세요.
+
+## 더 알아보기 { #learn-more }
+
+`dataclasses`를 다른 Pydantic 모델과 조합하거나, 이를 상속하거나, 여러분의 모델에 포함하는 등의 작업도 할 수 있습니다.
+
+자세한 내용은 [dataclasses에 관한 Pydantic 문서](https://docs.pydantic.dev/latest/concepts/dataclasses/)를 참고하세요.
+
+## 버전 { #version }
+
+이 기능은 FastAPI `0.67.0` 버전부터 사용할 수 있습니다. 🔖
diff --git a/docs/ko/docs/advanced/events.md b/docs/ko/docs/advanced/events.md
new file mode 100644
index 0000000000000..708ad443ffc80
--- /dev/null
+++ b/docs/ko/docs/advanced/events.md
@@ -0,0 +1,165 @@
+# Lifespan 이벤트 { #lifespan-events }
+
+애플리케이션이 **시작**하기 전에 실행되어야 하는 로직(코드)을 정의할 수 있습니다. 이는 이 코드가 **한 번**만 실행되며, 애플리케이션이 **요청을 받기 시작하기 전**에 실행된다는 의미입니다.
+
+마찬가지로, 애플리케이션이 **종료**될 때 실행되어야 하는 로직(코드)을 정의할 수 있습니다. 이 경우, 이 코드는 **한 번**만 실행되며, **여러 요청을 처리한 후**에 실행됩니다.
+
+이 코드는 애플리케이션이 요청을 받기 **시작**하기 전에 실행되고, 요청 처리를 **끝낸 직후**에 실행되기 때문에 전체 애플리케이션의 **수명(lifespan)**을 다룹니다(잠시 후 "lifespan"이라는 단어가 중요해집니다 😉).
+
+이는 전체 앱에서 사용해야 하는 **자원**을 설정하고, 요청 간에 **공유되는** 자원을 설정하고, 그리고/또는 이후에 **정리**하는 데 매우 유용할 수 있습니다. 예를 들어, 데이터베이스 연결 풀 또는 공유 머신러닝 모델을 로드하는 경우입니다.
+
+## 사용 사례 { #use-case }
+
+먼저 **사용 사례** 예시로 시작한 다음, 이를 어떻게 해결할지 살펴보겠습니다.
+
+요청을 처리하는 데 사용하고 싶은 **머신러닝 모델**이 있다고 상상해 봅시다. 🤖
+
+동일한 모델이 요청 간에 공유되므로, 요청마다 모델이 하나씩 있거나 사용자마다 하나씩 있는 등의 방식이 아닙니다.
+
+모델을 로드하는 데 **상당한 시간이 걸린다고 상상해 봅시다**, 왜냐하면 모델이 **디스크에서 많은 데이터를 읽어야** 하기 때문입니다. 그래서 모든 요청마다 이를 수행하고 싶지는 않습니다.
+
+모듈/파일의 최상위에서 로드할 수도 있지만, 그러면 단순한 자동화된 테스트를 실행하는 경우에도 **모델을 로드**하게 되고, 테스트가 코드의 독립적인 부분을 실행하기 전에 모델이 로드될 때까지 기다려야 하므로 **느려집니다**.
+
+이것이 우리가 해결할 문제입니다. 요청을 처리하기 전에 모델을 로드하되, 코드가 로드되는 동안이 아니라 애플리케이션이 요청을 받기 시작하기 직전에만 로드하겠습니다.
+
+## Lifespan { #lifespan }
+
+`FastAPI` 앱의 `lifespan` 매개변수와 "컨텍스트 매니저"를 사용하여 *시작*과 *종료* 로직을 정의할 수 있습니다(컨텍스트 매니저가 무엇인지 잠시 후에 보여드리겠습니다).
+
+예제로 시작한 다음 자세히 살펴보겠습니다.
+
+`yield`를 사용해 비동기 함수 `lifespan()`을 다음과 같이 생성합니다:
+
+{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}
+
+여기서는 `yield` 이전에 (가짜) 모델 함수를 머신러닝 모델이 들어 있는 딕셔너리에 넣어 모델을 로드하는 비용이 큰 *시작* 작업을 시뮬레이션합니다. 이 코드는 애플리케이션이 **요청을 받기 시작하기 전**, *시작* 동안에 실행됩니다.
+
+그리고 `yield` 직후에는 모델을 언로드합니다. 이 코드는 애플리케이션이 **요청 처리를 마친 후**, *종료* 직전에 실행됩니다. 예를 들어 메모리나 GPU 같은 자원을 해제할 수 있습니다.
+
+/// tip | 팁
+
+`shutdown`은 애플리케이션을 **중지**할 때 발생합니다.
+
+새 버전을 시작해야 할 수도 있고, 그냥 실행하는 게 지겨워졌을 수도 있습니다. 🤷
+
+///
+
+### Lifespan 함수 { #lifespan-function }
+
+먼저 주목할 점은 `yield`를 사용하여 비동기 함수를 정의하고 있다는 것입니다. 이는 `yield`를 사용하는 의존성과 매우 유사합니다.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}
+
+함수의 첫 번째 부분, 즉 `yield` 이전의 코드는 애플리케이션이 시작되기 **전에** 실행됩니다.
+
+그리고 `yield` 이후의 부분은 애플리케이션이 종료된 **후에** 실행됩니다.
+
+### 비동기 컨텍스트 매니저 { #async-context-manager }
+
+확인해 보면, 함수는 `@asynccontextmanager`로 데코레이션되어 있습니다.
+
+이는 함수를 "**비동기 컨텍스트 매니저**"라고 불리는 것으로 변환합니다.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}
+
+파이썬에서 **컨텍스트 매니저**는 `with` 문에서 사용할 수 있는 것입니다. 예를 들어, `open()`은 컨텍스트 매니저로 사용할 수 있습니다:
+
+```Python
+with open("file.txt") as file:
+ file.read()
+```
+
+최근 버전의 파이썬에는 **비동기 컨텍스트 매니저**도 있습니다. 이를 `async with`와 함께 사용합니다:
+
+```Python
+async with lifespan(app):
+ await do_stuff()
+```
+
+위와 같은 컨텍스트 매니저 또는 비동기 컨텍스트 매니저를 만들면, `with` 블록에 들어가기 전에 `yield` 이전의 코드를 실행하고, `with` 블록을 벗어난 후에는 `yield` 이후의 코드를 실행합니다.
+
+위의 코드 예제에서는 직접 사용하지 않고, FastAPI에 전달하여 FastAPI가 이를 사용하도록 합니다.
+
+`FastAPI` 앱의 `lifespan` 매개변수는 **비동기 컨텍스트 매니저**를 받으므로, 새 `lifespan` 비동기 컨텍스트 매니저를 전달할 수 있습니다.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[22] *}
+
+## 대체 이벤트(사용 중단) { #alternative-events-deprecated }
+
+/// warning | 경고
+
+*시작*과 *종료*를 처리하는 권장 방법은 위에서 설명한 대로 `FastAPI` 앱의 `lifespan` 매개변수를 사용하는 것입니다. `lifespan` 매개변수를 제공하면 `startup`과 `shutdown` 이벤트 핸들러는 더 이상 호출되지 않습니다. `lifespan`만 쓰거나 이벤트만 쓰거나 둘 중 하나이지, 둘 다는 아닙니다.
+
+이 부분은 아마 건너뛰셔도 됩니다.
+
+///
+
+*시작*과 *종료* 동안 실행될 이 로직을 정의하는 대체 방법이 있습니다.
+
+애플리케이션이 시작되기 전에 또는 애플리케이션이 종료될 때 실행되어야 하는 이벤트 핸들러(함수)를 정의할 수 있습니다.
+
+이 함수들은 `async def` 또는 일반 `def`로 선언할 수 있습니다.
+
+### `startup` 이벤트 { #startup-event }
+
+애플리케이션이 시작되기 전에 실행되어야 하는 함수를 추가하려면, `"startup"` 이벤트로 선언합니다:
+
+{* ../../docs_src/events/tutorial001_py310.py hl[8] *}
+
+이 경우, `startup` 이벤트 핸들러 함수는 "database"(그냥 `dict`) 항목을 일부 값으로 초기화합니다.
+
+여러 개의 이벤트 핸들러 함수를 추가할 수 있습니다.
+
+그리고 모든 `startup` 이벤트 핸들러가 완료될 때까지 애플리케이션은 요청을 받기 시작하지 않습니다.
+
+### `shutdown` 이벤트 { #shutdown-event }
+
+애플리케이션이 종료될 때 실행되어야 하는 함수를 추가하려면, `"shutdown"` 이벤트로 선언합니다:
+
+{* ../../docs_src/events/tutorial002_py310.py hl[6] *}
+
+여기서 `shutdown` 이벤트 핸들러 함수는 텍스트 한 줄 `"Application shutdown"`을 `log.txt` 파일에 기록합니다.
+
+/// info | 정보
+
+`open()` 함수에서 `mode="a"`는 "append"(추가)를 의미하므로, 기존 내용을 덮어쓰지 않고 파일에 있던 내용 뒤에 줄이 추가됩니다.
+
+///
+
+/// tip | 팁
+
+이 경우에는 파일과 상호작용하는 표준 파이썬 `open()` 함수를 사용하고 있습니다.
+
+따라서 I/O(input/output)가 포함되어 있어 디스크에 기록되는 것을 "기다리는" 과정이 필요합니다.
+
+하지만 `open()`은 `async`와 `await`를 사용하지 않습니다.
+
+그래서 이벤트 핸들러 함수는 `async def` 대신 표준 `def`로 선언합니다.
+
+///
+
+### `startup`과 `shutdown`을 함께 { #startup-and-shutdown-together }
+
+*시작*과 *종료* 로직은 연결되어 있을 가능성이 높습니다. 무언가를 시작했다가 끝내거나, 자원을 획득했다가 해제하는 등의 작업이 필요할 수 있습니다.
+
+로직이나 변수를 함께 공유하지 않는 분리된 함수에서 이를 처리하면, 전역 변수에 값을 저장하거나 비슷한 트릭이 필요해져 더 어렵습니다.
+
+그 때문에, 이제는 위에서 설명한 대로 `lifespan`을 사용하는 것이 권장됩니다.
+
+## 기술적 세부사항 { #technical-details }
+
+호기심 많은 분들을 위한 기술적인 세부사항입니다. 🤓
+
+내부적으로 ASGI 기술 사양에서는 이것이 [Lifespan Protocol](https://asgi.readthedocs.io/en/latest/specs/lifespan.html)의 일부이며, `startup`과 `shutdown`이라는 이벤트를 정의합니다.
+
+/// info | 정보
+
+Starlette `lifespan` 핸들러에 대해서는 [Starlette의 Lifespan 문서](https://www.starlette.dev/lifespan/)에서 더 읽어볼 수 있습니다.
+
+또한 코드의 다른 영역에서 사용할 수 있는 lifespan 상태를 처리하는 방법도 포함되어 있습니다.
+
+///
+
+## 서브 애플리케이션 { #sub-applications }
+
+🚨 이 lifespan 이벤트(startup 및 shutdown)는 메인 애플리케이션에 대해서만 실행되며, [서브 애플리케이션 - Mounts](sub-applications.md)에는 실행되지 않음을 유의하세요.
diff --git a/docs/ko/docs/advanced/generate-clients.md b/docs/ko/docs/advanced/generate-clients.md
new file mode 100644
index 0000000000000..bf29e52e9ba42
--- /dev/null
+++ b/docs/ko/docs/advanced/generate-clients.md
@@ -0,0 +1,208 @@
+# SDK 생성하기 { #generating-sdks }
+
+**FastAPI**는 **OpenAPI** 사양을 기반으로 하므로, FastAPI의 API는 많은 도구가 이해할 수 있는 표준 형식으로 설명할 수 있습니다.
+
+덕분에 여러 언어용 클라이언트 라이브러리(**SDKs**), 최신 **문서**, 그리고 코드와 동기화된 **테스트** 또는 **자동화 워크플로**를 쉽게 생성할 수 있습니다.
+
+이 가이드에서는 FastAPI 백엔드용 **TypeScript SDK**를 생성하는 방법을 배웁니다.
+
+## 오픈 소스 SDK 생성기 { #open-source-sdk-generators }
+
+다양하게 활용할 수 있는 옵션으로 [OpenAPI Generator](https://openapi-generator.tech/)가 있으며, **다양한 프로그래밍 언어**를 지원하고 OpenAPI 사양으로부터 SDK를 생성할 수 있습니다.
+
+**TypeScript 클라이언트**의 경우 [Hey API](https://heyapi.dev/)는 TypeScript 생태계에 최적화된 경험을 제공하는 목적에 맞게 설계된 솔루션입니다.
+
+더 많은 SDK 생성기는 [OpenAPI.Tools](https://openapi.tools/#sdk)에서 확인할 수 있습니다.
+
+/// tip | 팁
+
+FastAPI는 **OpenAPI 3.1** 사양을 자동으로 생성하므로, 사용하는 도구는 이 버전을 지원해야 합니다.
+
+///
+
+## FastAPI 스폰서의 SDK 생성기 { #sdk-generators-from-fastapi-sponsors }
+
+이 섹션에서는 FastAPI를 후원하는 회사들이 제공하는 **벤처 투자 기반** 및 **기업 지원** 솔루션을 소개합니다. 이 제품들은 고품질로 생성된 SDK에 더해 **추가 기능**과 **통합**을 제공합니다.
+
+✨ [**FastAPI 후원하기**](../help-fastapi.md#sponsor-the-author) ✨를 통해, 이 회사들은 프레임워크와 그 **생태계**가 건강하고 **지속 가능**하게 유지되도록 돕습니다.
+
+또한 이들의 후원은 FastAPI **커뮤니티**(여러분)에 대한 강한 헌신을 보여주며, **좋은 서비스**를 제공하는 것뿐 아니라, 견고하고 활발한 프레임워크인 FastAPI를 지원하는 데에도 관심이 있음을 나타냅니다. 🙇
+
+예를 들어 다음을 사용해 볼 수 있습니다:
+
+* [Speakeasy](https://speakeasy.com/editor?utm_source=fastapi+repo&utm_medium=github+sponsorship)
+* [Stainless](https://www.stainless.com/?utm_source=fastapi&utm_medium=referral)
+* [liblab](https://developers.liblab.com/tutorials/sdk-for-fastapi?utm_source=fastapi)
+
+이 중 일부는 오픈 소스이거나 무료 티어를 제공하므로, 비용 부담 없이 사용해 볼 수 있습니다. 다른 상용 SDK 생성기도 있으며 온라인에서 찾을 수 있습니다. 🤓
+
+## TypeScript SDK 만들기 { #create-a-typescript-sdk }
+
+간단한 FastAPI 애플리케이션으로 시작해 보겠습니다:
+
+{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}
+
+*경로 처리*에서 요청 페이로드와 응답 페이로드에 사용하는 모델을 `Item`, `ResponseMessage` 모델로 정의하고 있다는 점에 주목하세요.
+
+### API 문서 { #api-docs }
+
+`/docs`로 이동하면, 요청으로 보낼 데이터와 응답으로 받을 데이터에 대한 **스키마(schemas)**가 있는 것을 볼 수 있습니다:
+
+
+
+이 스키마는 앱에서 모델로 선언되었기 때문에 볼 수 있습니다.
+
+그 정보는 앱의 **OpenAPI 스키마**에서 사용할 수 있고, 이후 API 문서에 표시됩니다.
+
+OpenAPI에 포함된 모델의 동일한 정보가 **클라이언트 코드 생성**에 사용될 수 있습니다.
+
+### Hey API { #hey-api }
+
+모델이 포함된 FastAPI 앱이 준비되면, Hey API를 사용해 TypeScript 클라이언트를 생성할 수 있습니다. 가장 빠른 방법은 npx를 사용하는 것입니다.
+
+```sh
+npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
+```
+
+이 명령은 `./src/client`에 TypeScript SDK를 생성합니다.
+
+[`@hey-api/openapi-ts` 설치 방법](https://heyapi.dev/openapi-ts/get-started)과 [생성된 결과물](https://heyapi.dev/openapi-ts/output)은 해당 웹사이트에서 확인할 수 있습니다.
+
+### SDK 사용하기 { #using-the-sdk }
+
+이제 클라이언트 코드를 import해서 사용할 수 있습니다. 아래처럼 사용할 수 있으며, 메서드에 대한 자동 완성이 제공되는 것을 확인할 수 있습니다:
+
+
+
+보낼 페이로드에 대해서도 자동 완성이 제공됩니다:
+
+
+
+/// tip | 팁
+
+`name`과 `price`에 대한 자동 완성은 FastAPI 애플리케이션에서 `Item` 모델에 정의된 내용입니다.
+
+///
+
+전송하는 데이터에 대해 인라인 오류도 표시됩니다:
+
+
+
+응답 객체도 자동 완성을 제공합니다:
+
+
+
+## 태그가 있는 FastAPI 앱 { #fastapi-app-with-tags }
+
+대부분의 경우 FastAPI 앱은 더 커지고, 서로 다른 *경로 처리* 그룹을 분리하기 위해 태그를 사용하게 될 가능성이 큽니다.
+
+예를 들어 **items** 섹션과 **users** 섹션이 있고, 이를 태그로 분리할 수 있습니다:
+
+{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}
+
+### 태그로 TypeScript 클라이언트 생성하기 { #generate-a-typescript-client-with-tags }
+
+태그를 사용하는 FastAPI 앱에 대해 클라이언트를 생성하면, 일반적으로 생성된 클라이언트 코드도 태그를 기준으로 분리됩니다.
+
+이렇게 하면 클라이언트 코드에서 항목들이 올바르게 정렬되고 그룹화됩니다:
+
+
+
+이 경우 다음이 있습니다:
+
+* `ItemsService`
+* `UsersService`
+
+### 클라이언트 메서드 이름 { #client-method-names }
+
+현재 `createItemItemsPost` 같은 생성된 메서드 이름은 그다지 깔끔하지 않습니다:
+
+```TypeScript
+ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
+```
+
+...이는 클라이언트 생성기가 각 *경로 처리*에 대해 OpenAPI 내부의 **operation ID**를 사용하기 때문입니다.
+
+OpenAPI는 모든 *경로 처리* 전체에서 operation ID가 각각 유일해야 한다고 요구합니다. 그래서 FastAPI는 operation ID가 유일하도록 **함수 이름**, **경로**, **HTTP method/operation**을 조합해 operation ID를 생성합니다.
+
+하지만 다음에서 이를 개선하는 방법을 보여드리겠습니다. 🤓
+
+## 커스텀 Operation ID와 더 나은 메서드 이름 { #custom-operation-ids-and-better-method-names }
+
+클라이언트에서 **더 단순한 메서드 이름**을 갖도록, operation ID가 **생성되는 방식**을 **수정**할 수 있습니다.
+
+이 경우 operation ID가 다른 방식으로도 **유일**하도록 보장해야 합니다.
+
+예를 들어 각 *경로 처리*이 태그를 갖도록 한 다음, **태그**와 *경로 처리* **이름**(함수 이름)을 기반으로 operation ID를 생성할 수 있습니다.
+
+### 유일 ID 생성 함수 커스터마이징 { #custom-generate-unique-id-function }
+
+FastAPI는 각 *경로 처리*에 대해 **유일 ID**를 사용하며, 이는 **operation ID** 및 요청/응답에 필요한 커스텀 모델 이름에도 사용됩니다.
+
+이 함수를 커스터마이징할 수 있습니다. 이 함수는 `APIRoute`를 받아 문자열을 반환합니다.
+
+예를 들어 아래에서는 첫 번째 태그(대부분 태그는 하나만 있을 것입니다)와 *경로 처리* 이름(함수 이름)을 사용합니다.
+
+그 다음 이 커스텀 함수를 `generate_unique_id_function` 매개변수로 **FastAPI**에 전달할 수 있습니다:
+
+{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}
+
+### 커스텀 Operation ID로 TypeScript 클라이언트 생성하기 { #generate-a-typescript-client-with-custom-operation-ids }
+
+이제 클라이언트를 다시 생성하면, 개선된 메서드 이름을 확인할 수 있습니다:
+
+
+
+보시다시피, 이제 메서드 이름은 태그 다음에 함수 이름이 오며, URL 경로와 HTTP operation의 정보는 포함하지 않습니다.
+
+### 클라이언트 생성기를 위한 OpenAPI 사양 전처리 { #preprocess-the-openapi-specification-for-the-client-generator }
+
+생성된 코드에는 여전히 일부 **중복 정보**가 있습니다.
+
+`ItemsService`(태그에서 가져옴)에 이미 **items**가 포함되어 있어 이 메서드가 items와 관련되어 있음을 알 수 있지만, 메서드 이름에도 태그 이름이 접두사로 붙어 있습니다. 😕
+
+OpenAPI 전반에서는 operation ID가 **유일**하다는 것을 보장하기 위해 이 방식을 유지하고 싶을 수 있습니다.
+
+하지만 생성된 클라이언트에서는, 클라이언트를 생성하기 직전에 OpenAPI operation ID를 **수정**해서 메서드 이름을 더 보기 좋고 **깔끔하게** 만들 수 있습니다.
+
+OpenAPI JSON을 `openapi.json` 파일로 다운로드한 뒤, 아래와 같은 스크립트로 **접두사 태그를 제거**할 수 있습니다:
+
+{* ../../docs_src/generate_clients/tutorial004_py310.py *}
+
+//// tab | Node.js
+
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
+```
+
+////
+
+이렇게 하면 operation ID가 `items-get_items` 같은 형태에서 `get_items`로 변경되어, 클라이언트 생성기가 더 단순한 메서드 이름을 생성할 수 있습니다.
+
+### 전처리된 OpenAPI로 TypeScript 클라이언트 생성하기 { #generate-a-typescript-client-with-the-preprocessed-openapi }
+
+이제 최종 결과가 `openapi.json` 파일에 있으므로, 입력 위치를 업데이트해야 합니다:
+
+```sh
+npx @hey-api/openapi-ts -i ./openapi.json -o src/client
+```
+
+새 클라이언트를 생성한 후에는 **깔끔한 메서드 이름**을 가지면서도, **자동 완성**, **인라인 오류** 등은 그대로 제공됩니다:
+
+
+
+## 장점 { #benefits }
+
+자동으로 생성된 클라이언트를 사용하면 다음에 대해 **자동 완성**을 받을 수 있습니다:
+
+* 메서드
+* 본문(body)의 요청 페이로드, 쿼리 파라미터 등
+* 응답 페이로드
+
+또한 모든 것에 대해 **인라인 오류**도 확인할 수 있습니다.
+
+그리고 백엔드 코드를 업데이트한 뒤 프론트엔드를 **재생성(regenerate)**하면, 새 *경로 처리*가 메서드로 추가되고 기존 것은 제거되며, 그 밖의 변경 사항도 생성된 코드에 반영됩니다. 🤓
+
+이는 무언가 변경되면 그 변경이 클라이언트 코드에도 자동으로 **반영**된다는 뜻입니다. 또한 클라이언트를 **빌드(build)**하면 사용된 데이터가 **불일치(mismatch)**할 경우 오류가 발생합니다.
+
+따라서 운영 환경에서 최종 사용자에게 오류가 노출된 뒤 문제를 추적하는 대신, 개발 사이클 초기에 **많은 오류를 매우 빨리 감지**할 수 있습니다. ✨
diff --git a/docs/ko/docs/advanced/index.md b/docs/ko/docs/advanced/index.md
new file mode 100644
index 0000000000000..feb91d5a6b0c8
--- /dev/null
+++ b/docs/ko/docs/advanced/index.md
@@ -0,0 +1,21 @@
+# 심화 사용자 안내서 { #advanced-user-guide }
+
+## 추가 기능 { #additional-features }
+
+메인 [자습서 - 사용자 안내서](../tutorial/index.md)는 여러분이 **FastAPI**의 모든 주요 기능을 둘러보시기에 충분할 것입니다.
+
+이어지는 장에서는 여러분이 다른 옵션, 구성 및 추가 기능을 보실 수 있습니다.
+
+/// tip | 팁
+
+다음 장들이 **반드시 "심화"**인 것은 아닙니다.
+
+그리고 여러분의 사용 사례에 대한 해결책이 그중 하나에 있을 수 있습니다.
+
+///
+
+## 자습서를 먼저 읽으십시오 { #read-the-tutorial-first }
+
+여러분은 메인 [자습서 - 사용자 안내서](../tutorial/index.md)의 지식으로 **FastAPI**의 대부분의 기능을 사용하실 수 있습니다.
+
+이어지는 장들은 여러분이 메인 자습서 - 사용자 안내서를 이미 읽으셨으며 주요 아이디어를 알고 계신다고 가정합니다.
diff --git a/docs/ko/docs/advanced/json-base64-bytes.md b/docs/ko/docs/advanced/json-base64-bytes.md
new file mode 100644
index 0000000000000..b5e55a41afbf0
--- /dev/null
+++ b/docs/ko/docs/advanced/json-base64-bytes.md
@@ -0,0 +1,63 @@
+# 바이트를 Base64로 포함하는 JSON { #json-with-bytes-as-base64 }
+
+애플리케이션에서 JSON 데이터를 주고받아야 하지만 그 안에 바이너리 데이터를 포함해야 한다면, base64로 인코딩해서 포함할 수 있습니다.
+
+## Base64와 파일 { #base64-vs-files }
+
+바이너리 데이터 업로드에는 [요청 파일](../tutorial/request-files.md)을, 바이너리 데이터 전송에는 [커스텀 응답 - FileResponse](./custom-response.md#fileresponse--fileresponse-)를 사용할 수 있는지 먼저 고려하세요. JSON으로 인코딩하는 대신 말입니다.
+
+JSON은 UTF-8로 인코딩된 문자열만 포함할 수 있으므로, 원시 바이트를 그대로 담을 수 없습니다.
+
+Base64는 바이너리 데이터를 문자열로 인코딩할 수 있지만, 이를 위해 원래의 바이너리 데이터보다 더 많은 문자 수를 사용해야 하므로 일반적인 파일 전송보다 비효율적일 수 있습니다.
+
+반드시 JSON 안에 바이너리 데이터를 포함해야 하고, 파일을 사용할 수 없을 때만 base64를 사용하세요.
+
+## Pydantic `bytes` { #pydantic-bytes }
+
+`bytes` 필드를 가진 Pydantic 모델을 선언하고, 모델 설정에서 `val_json_bytes`를 사용하도록 지정하면 입력 JSON 데이터를 base64로 “검증”하도록 할 수 있습니다. 이 검증 과정의 일부로 base64 문자열을 바이트로 디코딩합니다.
+
+{* ../../docs_src/json_base64_bytes/tutorial001_py310.py ln[1:9,29:35] hl[9] *}
+
+`/docs`를 확인하면 `data` 필드가 base64로 인코딩된 bytes를 기대한다고 표시됩니다:
+
+
+
diff --git a/docs/ko/docs/advanced/openapi-webhooks.md b/docs/ko/docs/advanced/openapi-webhooks.md
new file mode 100644
index 0000000000000..e40a7bb186d24
--- /dev/null
+++ b/docs/ko/docs/advanced/openapi-webhooks.md
@@ -0,0 +1,55 @@
+# OpenAPI Webhooks { #openapi-webhooks }
+
+앱이 어떤 데이터와 함께 (요청을 보내서) *사용자의* 앱을 호출할 수 있고, 보통 어떤 **이벤트**를 **알리기** 위해 그렇게 할 수 있다는 것을 API **사용자**에게 알려야 하는 경우가 있습니다.
+
+이는 사용자가 여러분의 API로 요청을 보내는 일반적인 과정 대신, **여러분의 API**(또는 앱)가 **사용자의 시스템**(사용자의 API, 사용자의 앱)으로 **요청을 보낼 수 있다**는 의미입니다.
+
+이를 보통 **webhook**이라고 합니다.
+
+## Webhooks 단계 { #webhooks-steps }
+
+일반적인 과정은, 여러분이 코드에서 보낼 메시지, 즉 **요청 본문(body)**이 무엇인지 **정의**하는 것입니다.
+
+또한 여러분의 앱이 어떤 **시점**에 그 요청(또는 이벤트)을 보낼지도 어떤 방식으로든 정의합니다.
+
+그리고 **사용자**는 (예: 어딘가의 웹 대시보드에서) 여러분의 앱이 그 요청을 보내야 할 **URL**을 어떤 방식으로든 정의합니다.
+
+webhook의 URL을 등록하는 방법과 실제로 그 요청을 보내는 코드에 대한 모든 **로직**은 여러분에게 달려 있습니다. **여러분의 코드**에서 원하는 방식으로 작성하면 됩니다.
+
+## **FastAPI**와 OpenAPI로 webhooks 문서화하기 { #documenting-webhooks-with-fastapi-and-openapi }
+
+**FastAPI**에서는 OpenAPI를 사용해, 이러한 webhook의 이름, 여러분의 앱이 보낼 수 있는 HTTP 작업 타입(예: `POST`, `PUT` 등), 그리고 여러분의 앱이 보낼 요청 **본문(body)**을 정의할 수 있습니다.
+
+이렇게 하면 사용자가 여러분의 **webhook** 요청을 받기 위해 **자신들의 API를 구현**하기가 훨씬 쉬워지고, 경우에 따라서는 자신의 API 코드 일부를 자동 생성할 수도 있습니다.
+
+/// info | 정보
+
+Webhooks는 OpenAPI 3.1.0 이상에서 사용할 수 있으며, FastAPI `0.99.0` 이상에서 지원됩니다.
+
+///
+
+## webhooks가 있는 앱 { #an-app-with-webhooks }
+
+**FastAPI** 애플리케이션을 만들면, *경로 처리*를 정의하는 것과 같은 방식으로(예: `@app.webhooks.post()`), *webhooks*를 정의하는 데 사용할 수 있는 `webhooks` 속성이 있습니다.
+
+{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}
+
+여러분이 정의한 webhook은 **OpenAPI** 스키마와 자동 **docs UI**에 포함됩니다.
+
+/// info | 정보
+
+`app.webhooks` 객체는 실제로 `APIRouter`일 뿐이며, 여러 파일로 앱을 구조화할 때 사용하는 것과 동일한 타입입니다.
+
+///
+
+webhook에서는 실제로(`/items/` 같은) *경로(path)*를 선언하지 않는다는 점에 유의하세요. 그곳에 전달하는 텍스트는 webhook의 **식별자**(이벤트 이름)일 뿐입니다. 예를 들어 `@app.webhooks.post("new-subscription")`에서 webhook 이름은 `new-subscription`입니다.
+
+이는 **사용자**가 webhook 요청을 받고 싶은 실제 **URL 경로**를 다른 방식(예: 웹 대시보드)으로 정의할 것이라고 기대하기 때문입니다.
+
+### 문서 확인하기 { #check-the-docs }
+
+이제 앱을 실행하고 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)로 이동하세요.
+
+문서에 일반적인 *경로 처리*가 보이고, 이제는 일부 **webhooks**도 함께 보일 것입니다:
+
+
diff --git a/docs/ko/docs/advanced/path-operation-advanced-configuration.md b/docs/ko/docs/advanced/path-operation-advanced-configuration.md
new file mode 100644
index 0000000000000..253a6f3021e2d
--- /dev/null
+++ b/docs/ko/docs/advanced/path-operation-advanced-configuration.md
@@ -0,0 +1,172 @@
+# 경로 처리 고급 구성 { #path-operation-advanced-configuration }
+
+## OpenAPI operationId { #openapi-operationid }
+
+/// warning | 경고
+
+OpenAPI “전문가”가 아니라면, 아마 이 내용은 필요하지 않을 것입니다.
+
+///
+
+매개변수 `operation_id`를 사용해 *경로 처리*에 사용할 OpenAPI `operationId`를 설정할 수 있습니다.
+
+각 작업마다 고유하도록 보장해야 합니다.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
+
+### *경로 처리 함수* 이름을 operationId로 사용하기 { #using-the-path-operation-function-name-as-the-operationid }
+
+API의 함수 이름을 `operationId`로 사용하고 싶다면, 모든 API를 순회하면서 `APIRoute.name`을 사용해 각 *경로 처리*의 `operation_id`를 덮어쓸 수 있습니다.
+
+모든 *경로 처리*를 추가한 뒤에 수행해야 합니다.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *}
+
+/// tip | 팁
+
+`app.openapi()`를 수동으로 호출한다면, 그 전에 `operationId`들을 업데이트해야 합니다.
+
+///
+
+/// warning | 경고
+
+이렇게 할 경우, 각 *경로 처리 함수*의 이름이 고유하도록 보장해야 합니다.
+
+서로 다른 모듈(파이썬 파일)에 있어도 마찬가지입니다.
+
+///
+
+## OpenAPI에서 제외하기 { #exclude-from-openapi }
+
+생성된 OpenAPI 스키마(따라서 자동 문서화 시스템)에서 특정 *경로 처리*를 제외하려면, `include_in_schema` 매개변수를 `False`로 설정하세요:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}
+
+## docstring에서 고급 설명 가져오기 { #advanced-description-from-docstring }
+
+OpenAPI에 사용할 *경로 처리 함수*의 docstring 줄 수를 제한할 수 있습니다.
+
+`\f`(이스케이프된 "form feed" 문자)를 추가하면 **FastAPI**는 이 지점에서 OpenAPI에 사용할 출력 내용을 잘라냅니다.
+
+문서에는 표시되지 않지만, Sphinx 같은 다른 도구는 나머지 부분을 사용할 수 있습니다.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}
+
+## 추가 응답 { #additional-responses }
+
+*경로 처리*에 대해 `response_model`과 `status_code`를 선언하는 방법을 이미 보셨을 것입니다.
+
+이는 *경로 처리*의 기본 응답에 대한 메타데이터를 정의합니다.
+
+모델, 상태 코드 등과 함께 추가 응답도 선언할 수 있습니다.
+
+이에 대한 문서의 전체 장이 있으니, [OpenAPI의 추가 응답](additional-responses.md)에서 읽어보세요.
+
+## OpenAPI Extra { #openapi-extra }
+
+애플리케이션에서 *경로 처리*를 선언하면, **FastAPI**는 OpenAPI 스키마에 포함될 해당 *경로 처리*의 관련 메타데이터를 자동으로 생성합니다.
+
+/// note | 기술 세부사항
+
+OpenAPI 명세에서는 이를 [Operation Object](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object)라고 부릅니다.
+
+///
+
+여기에는 *경로 처리*에 대한 모든 정보가 있으며, 자동 문서를 생성하는 데 사용됩니다.
+
+`tags`, `parameters`, `requestBody`, `responses` 등이 포함됩니다.
+
+이 *경로 처리* 전용 OpenAPI 스키마는 보통 **FastAPI**가 자동으로 생성하지만, 확장할 수도 있습니다.
+
+/// tip | 팁
+
+이는 저수준 확장 지점입니다.
+
+추가 응답만 선언하면 된다면, 더 편리한 방법은 [OpenAPI의 추가 응답](additional-responses.md)을 사용하는 것입니다.
+
+///
+
+`openapi_extra` 매개변수를 사용해 *경로 처리*의 OpenAPI 스키마를 확장할 수 있습니다.
+
+### OpenAPI 확장 { #openapi-extensions }
+
+예를 들어 `openapi_extra`는 [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions)를 선언하는 데 도움이 될 수 있습니다:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py310.py hl[6] *}
+
+자동 API 문서를 열면, 해당 특정 *경로 처리*의 하단에 확장이 표시됩니다.
+
+
+
+또한 API의 `/openapi.json`에서 결과 OpenAPI를 보면, 특정 *경로 처리*의 일부로 확장이 포함된 것도 확인할 수 있습니다:
+
+```JSON hl_lines="22"
+{
+ "openapi": "3.1.0",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0"
+ },
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ }
+ },
+ "x-aperture-labs-portal": "blue"
+ }
+ }
+ }
+}
+```
+
+### 사용자 정의 OpenAPI *경로 처리* 스키마 { #custom-openapi-path-operation-schema }
+
+`openapi_extra`의 딕셔너리는 *경로 처리*에 대해 자동으로 생성된 OpenAPI 스키마와 깊게 병합됩니다.
+
+따라서 자동 생성된 스키마에 추가 데이터를 더할 수 있습니다.
+
+예를 들어 Pydantic과 함께 FastAPI의 자동 기능을 사용하지 않고, 자체 코드로 요청을 읽고 검증하기로 결정할 수도 있지만, OpenAPI 스키마에는 여전히 그 요청을 정의하고 싶을 수 있습니다.
+
+그럴 때 `openapi_extra`를 사용할 수 있습니다:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py310.py hl[19:36, 39:40] *}
+
+이 예시에서는 어떤 Pydantic 모델도 선언하지 않았습니다. 사실 요청 바디는 JSON으로 파싱되지도 않고, `bytes`로 직접 읽습니다. 그리고 함수 `magic_data_reader()`가 어떤 방식으로든 이를 파싱하는 역할을 담당합니다.
+
+그럼에도 불구하고, 요청 바디에 대해 기대하는 스키마를 선언할 수 있습니다.
+
+### 사용자 정의 OpenAPI 콘텐츠 타입 { #custom-openapi-content-type }
+
+같은 트릭을 사용하면, Pydantic 모델을 이용해 JSON Schema를 정의하고 이를 *경로 처리*의 사용자 정의 OpenAPI 스키마 섹션에 포함시킬 수 있습니다.
+
+요청의 데이터 타입이 JSON이 아니더라도 이렇게 할 수 있습니다.
+
+예를 들어 이 애플리케이션에서는 Pydantic 모델에서 JSON Schema를 추출하는 FastAPI의 통합 기능도, JSON에 대한 자동 검증도 사용하지 않습니다. 실제로 요청 콘텐츠 타입을 JSON이 아니라 YAML로 선언합니다:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[15:20, 22] *}
+
+그럼에도 기본 통합 기능을 사용하지 않더라도, YAML로 받고자 하는 데이터에 대한 JSON Schema를 수동으로 생성하기 위해 Pydantic 모델을 여전히 사용합니다.
+
+그 다음 요청을 직접 사용하고, 바디를 `bytes`로 추출합니다. 이는 FastAPI가 요청 페이로드를 JSON으로 파싱하려고 시도조차 하지 않는다는 뜻입니다.
+
+그리고 코드에서 YAML 콘텐츠를 직접 파싱한 뒤, 다시 같은 Pydantic 모델을 사용해 YAML 콘텐츠를 검증합니다:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *}
+
+/// tip | 팁
+
+여기서는 같은 Pydantic 모델을 재사용합니다.
+
+하지만 마찬가지로, 다른 방식으로 검증할 수도 있습니다.
+
+///
diff --git a/docs/ko/docs/advanced/response-change-status-code.md b/docs/ko/docs/advanced/response-change-status-code.md
new file mode 100644
index 0000000000000..f30474917e86b
--- /dev/null
+++ b/docs/ko/docs/advanced/response-change-status-code.md
@@ -0,0 +1,31 @@
+# 응답 - 상태 코드 변경 { #response-change-status-code }
+
+기본 [응답 상태 코드 설정](../tutorial/response-status-code.md)이 가능하다는 걸 이미 알고 계실 겁니다.
+
+하지만 경우에 따라 기본 설정과 다른 상태 코드를 반환해야 할 때가 있습니다.
+
+## 사용 예 { #use-case }
+
+예를 들어 기본적으로 HTTP 상태 코드 "OK" `200`을 반환하고 싶다고 가정해 봅시다.
+
+하지만 데이터가 존재하지 않으면 이를 새로 생성하고, HTTP 상태 코드 "CREATED" `201`을 반환하고자 할 때가 있을 수 있습니다.
+
+하지만 여전히 `response_model`을 사용하여 반환하는 데이터를 필터링하고 변환할 수 있기를 원합니다.
+
+이런 경우에는 `Response` 파라미터를 사용할 수 있습니다.
+
+## `Response` 파라미터 사용하기 { #use-a-response-parameter }
+
+*경로 처리 함수*에 `Response` 타입의 파라미터를 선언할 수 있습니다. (쿠키와 헤더에 대해 선언하는 것과 유사하게)
+
+그리고 이 *임시* 응답 객체에서 `status_code`를 설정할 수 있습니다.
+
+{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}
+
+그리고 평소처럼 필요한 어떤 객체든 반환할 수 있습니다(`dict`, 데이터베이스 모델 등).
+
+`response_model`을 선언했다면 반환된 객체는 여전히 필터링되고 변환됩니다.
+
+**FastAPI**는 이 *임시* 응답 객체에서 상태 코드(쿠키와 헤더 포함)를 추출하여, `response_model`로 필터링된 반환 값을 포함하는 최종 응답에 넣습니다.
+
+또한, 의존성에서도 `Response` 파라미터를 선언하고 그 안에서 상태 코드를 설정할 수 있습니다. 단, 마지막으로 설정된 상태 코드가 우선 적용된다는 점을 유의하세요.
diff --git a/docs/ko/docs/advanced/response-cookies.md b/docs/ko/docs/advanced/response-cookies.md
new file mode 100644
index 0000000000000..b73d719699a53
--- /dev/null
+++ b/docs/ko/docs/advanced/response-cookies.md
@@ -0,0 +1,51 @@
+# 응답 쿠키 { #response-cookies }
+
+## `Response` 매개변수 사용하기 { #use-a-response-parameter }
+
+*경로 처리 함수*에서 `Response` 타입의 매개변수를 선언할 수 있습니다.
+
+그런 다음 해당 *임시* 응답 객체에서 쿠키를 설정할 수 있습니다.
+
+{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}
+
+그런 다음 일반적으로 하듯이 필요한 어떤 객체든 반환할 수 있습니다(`dict`, 데이터베이스 모델 등).
+
+그리고 `response_model`을 선언했다면 반환한 객체를 거르고 변환하는 데 여전히 사용됩니다.
+
+**FastAPI**는 그 *임시* 응답에서 쿠키(또한 헤더 및 상태 코드)를 추출하고, `response_model`로 필터링된 반환 값이 포함된 최종 응답에 이를 넣습니다.
+
+또한 의존관계에서 `Response` 매개변수를 선언하고, 해당 의존성에서 쿠키(및 헤더)를 설정할 수도 있습니다.
+
+## `Response`를 직접 반환하기 { #return-a-response-directly }
+
+코드에서 `Response`를 직접 반환할 때도 쿠키를 생성할 수 있습니다.
+
+이를 위해 [Response를 직접 반환하기](response-directly.md)에서 설명한 대로 응답을 생성할 수 있습니다.
+
+그런 다음 쿠키를 설정하고 반환하면 됩니다:
+
+{* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *}
+
+/// tip
+
+`Response` 매개변수를 사용하지 않고 응답을 직접 반환하는 경우, FastAPI는 이를 직접 반환한다는 점에 유의하세요.
+
+따라서 데이터가 올바른 유형인지 확인해야 합니다. 예: `JSONResponse`를 반환하는 경우, JSON과 호환되는지 확인하세요.
+
+또한 `response_model`로 필터링되어야 했던 데이터를 전송하지 않도록 하세요.
+
+///
+
+### 추가 정보 { #more-info }
+
+/// note | 기술 세부사항
+
+`from starlette.responses import Response` 또는 `from starlette.responses import JSONResponse`를 사용할 수도 있습니다.
+
+**FastAPI**는 개발자의 편의를 위해 `fastapi.responses`로 동일한 `starlette.responses`를 제공합니다. 하지만 사용 가능한 대부분의 응답은 Starlette에서 직접 제공됩니다.
+
+또한 `Response`는 헤더와 쿠키를 설정하는 데 자주 사용되므로, **FastAPI**는 이를 `fastapi.Response`로도 제공합니다.
+
+///
+
+사용 가능한 모든 매개변수와 옵션은 [Starlette의 문서](https://www.starlette.dev/responses/#set-cookie)에서 확인할 수 있습니다.
diff --git a/docs/ko/docs/advanced/response-directly.md b/docs/ko/docs/advanced/response-directly.md
new file mode 100644
index 0000000000000..301a259b2f1d0
--- /dev/null
+++ b/docs/ko/docs/advanced/response-directly.md
@@ -0,0 +1,83 @@
+# 응답을 직접 반환하기 { #return-a-response-directly }
+
+**FastAPI**에서 *경로 처리(path operation)*를 생성할 때, 일반적으로 `dict`, `list`, Pydantic 모델, 데이터베이스 모델 등의 데이터를 반환할 수 있습니다.
+
+[응답 모델](../tutorial/response-model.md)을 선언하면 FastAPI는 Pydantic을 사용해 데이터를 JSON으로 직렬화합니다.
+
+응답 모델을 선언하지 않으면, FastAPI는 [JSON 호환 가능 인코더](../tutorial/encoder.md)에 설명된 `jsonable_encoder`를 사용해 데이터를 변환하고 이를 `JSONResponse`에 넣습니다.
+
+또한 `JSONResponse`를 직접 생성해 반환할 수도 있습니다.
+
+/// tip | 팁
+
+일반적으로 `JSONResponse`를 직접 반환하는 것보다 [응답 모델](../tutorial/response-model.md)을 사용하는 편이 성능이 훨씬 좋습니다. 이렇게 하면 Pydantic이 Rust에서 데이터를 직렬화합니다.
+
+///
+
+## `Response` 반환하기 { #return-a-response }
+
+`Response` 또는 그 하위 클래스를 반환할 수 있습니다.
+
+/// info | 정보
+
+`JSONResponse` 자체도 `Response`의 하위 클래스입니다.
+
+///
+
+그리고 `Response`를 반환하면 **FastAPI**가 이를 그대로 전달합니다.
+
+Pydantic 모델로 데이터 변환을 수행하지 않으며, 내용을 다른 형식으로 변환하지 않습니다.
+
+이로 인해 많은 유연성을 얻을 수 있습니다. 어떤 데이터 유형이든 반환할 수 있고, 데이터 선언이나 유효성 검사를 재정의할 수 있습니다.
+
+또한 많은 책임도 따릅니다. 반환하는 데이터가 올바르고, 올바른 형식이며, 직렬화가 가능하도록 여러분이 직접 보장해야 합니다.
+
+## `Response`에서 `jsonable_encoder` 사용하기 { #using-the-jsonable-encoder-in-a-response }
+
+**FastAPI**는 반환하는 `Response`에 아무런 변경도 하지 않으므로, 그 내용이 준비되어 있는지 확인해야 합니다.
+
+예를 들어, Pydantic 모델을 먼저 `dict`로 변환하고 `datetime`, `UUID` 등의 모든 데이터 타입을 JSON 호환 타입으로 변환하지 않으면 Pydantic 모델을 `JSONResponse`에 넣을 수 없습니다.
+
+이러한 경우, 데이터를 응답에 전달하기 전에 `jsonable_encoder`를 사용하여 변환할 수 있습니다:
+
+{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}
+
+/// note | 기술 세부사항
+
+`from starlette.responses import JSONResponse`를 사용할 수도 있습니다.
+
+**FastAPI**는 개발자의 편의를 위해 `starlette.responses`를 `fastapi.responses`로 제공합니다. 하지만 대부분의 사용 가능한 응답은 Starlette에서 직접 제공합니다.
+
+///
+
+## 사용자 정의 `Response` 반환하기 { #returning-a-custom-response }
+
+위 예제는 필요한 모든 부분을 보여주지만, 아직은 그다지 유용하지 않습니다. `item`을 그냥 직접 반환했어도 **FastAPI**가 기본으로 이를 `JSONResponse`에 넣고 `dict`로 변환하는 등의 작업을 모두 수행해 주었을 것이기 때문입니다.
+
+이제, 이를 사용해 사용자 정의 응답을 반환하는 방법을 알아보겠습니다.
+
+예를 들어 [XML](https://en.wikipedia.org/wiki/XML) 응답을 반환하고 싶다고 가정해 보겠습니다.
+
+XML 내용을 문자열에 넣고, 이를 `Response`에 넣어 반환할 수 있습니다:
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+## 응답 모델 동작 방식 { #how-a-response-model-works }
+
+경로 처리에서 [응답 모델 - 반환 타입](../tutorial/response-model.md)을 선언하면 **FastAPI**는 Pydantic을 사용해 데이터를 JSON으로 직렬화합니다.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+이는 Rust 측에서 처리되므로, 일반적인 Python과 `JSONResponse` 클래스로 수행하는 것보다 성능이 훨씬 좋습니다.
+
+`response_model` 또는 반환 타입을 사용할 때 FastAPI는 `jsonable_encoder`로 데이터를 변환(이는 더 느립니다)하지도 않고, `JSONResponse` 클래스를 사용하지도 않습니다.
+
+대신 응답 모델(또는 반환 타입)을 사용해 Pydantic이 생성한 JSON 바이트를 가져와, JSON에 맞는 미디어 타입(`application/json`)을 가진 `Response`를 직접 반환합니다.
+
+## 참고 사항 { #notes }
+
+`Response`를 직접 반환할 때, 그 데이터는 자동으로 유효성 검사되거나, 변환(직렬화)되거나, 문서화되지 않습니다.
+
+그러나 [OpenAPI에서 추가 응답](additional-responses.md)에서 설명된 대로 문서화할 수 있습니다.
+
+이후 섹션에서 자동 데이터 변환, 문서화 등을 계속 사용하면서 이러한 사용자 정의 `Response`를 사용하는/선언하는 방법을 확인할 수 있습니다.
diff --git a/docs/ko/docs/advanced/response-headers.md b/docs/ko/docs/advanced/response-headers.md
new file mode 100644
index 0000000000000..e7157d8f48a0a
--- /dev/null
+++ b/docs/ko/docs/advanced/response-headers.md
@@ -0,0 +1,41 @@
+# 응답 헤더 { #response-headers }
+
+## `Response` 매개변수 사용하기 { #use-a-response-parameter }
+
+여러분은 *경로 처리 함수*에서 `Response` 타입의 매개변수를 선언할 수 있습니다 (쿠키와 같이 사용할 수 있습니다).
+
+그런 다음, 여러분은 해당 *임시* 응답 객체에서 헤더를 설정할 수 있습니다.
+
+{* ../../docs_src/response_headers/tutorial002_py310.py hl[1, 7:8] *}
+
+그 후, 일반적으로 사용하듯이 필요한 객체(`dict`, 데이터베이스 모델 등)를 반환할 수 있습니다.
+
+`response_model`을 선언한 경우, 반환한 객체를 필터링하고 변환하는 데 여전히 사용됩니다.
+
+**FastAPI**는 해당 *임시* 응답에서 헤더(쿠키와 상태 코드도 포함)를 추출하여, 여러분이 반환한 값을 포함하는 최종 응답에 `response_model`로 필터링된 값을 넣습니다.
+
+또한, 종속성에서 `Response` 매개변수를 선언하고 그 안에서 헤더(및 쿠키)를 설정할 수 있습니다.
+
+## `Response` 직접 반환하기 { #return-a-response-directly }
+
+`Response`를 직접 반환할 때에도 헤더를 추가할 수 있습니다.
+
+[응답을 직접 반환하기](response-directly.md)에 설명한 대로 응답을 생성하고, 헤더를 추가 매개변수로 전달하세요:
+
+{* ../../docs_src/response_headers/tutorial001_py310.py hl[10:12] *}
+
+/// note | 기술 세부사항
+
+`from starlette.responses import Response`나 `from starlette.responses import JSONResponse`를 사용할 수도 있습니다.
+
+**FastAPI**는 개발자인 여러분의 편의를 위해 `starlette.responses`와 동일한 것을 `fastapi.responses`로도 제공합니다. 하지만 사용 가능한 대부분의 응답은 Starlette에서 직접 제공합니다.
+
+그리고 `Response`는 헤더와 쿠키를 설정하는 데 자주 사용될 수 있으므로, **FastAPI**는 `fastapi.Response`로도 이를 제공합니다.
+
+///
+
+## 커스텀 헤더 { #custom-headers }
+
+커스텀 사설 헤더는 [`X-` 접두어를 사용하여](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) 추가할 수 있다는 점을 기억하세요.
+
+하지만, 여러분이 브라우저에서 클라이언트가 볼 수 있기를 원하는 커스텀 헤더가 있는 경우, CORS 설정에 이를 추가해야 합니다([CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md)에서 자세히 알아보세요). [Starlette의 CORS 문서](https://www.starlette.dev/middleware/#corsmiddleware)에 문서화된 `expose_headers` 매개변수를 사용하세요.
diff --git a/docs/ko/docs/advanced/security/http-basic-auth.md b/docs/ko/docs/advanced/security/http-basic-auth.md
new file mode 100644
index 0000000000000..273b8020504db
--- /dev/null
+++ b/docs/ko/docs/advanced/security/http-basic-auth.md
@@ -0,0 +1,107 @@
+# HTTP Basic Auth { #http-basic-auth }
+
+가장 단순한 경우에는 HTTP Basic Auth를 사용할 수 있습니다.
+
+HTTP Basic Auth에서는 애플리케이션이 사용자명과 비밀번호가 들어 있는 헤더를 기대합니다.
+
+이를 받지 못하면 HTTP 401 "Unauthorized" 오류를 반환합니다.
+
+그리고 값이 `Basic`이고 선택적으로 `realm` 파라미터를 포함하는 `WWW-Authenticate` 헤더를 반환합니다.
+
+이는 브라우저가 사용자명과 비밀번호를 입력하는 통합 프롬프트를 표시하도록 알려줍니다.
+
+그다음 사용자명과 비밀번호를 입력하면, 브라우저가 자동으로 해당 값을 헤더에 담아 전송합니다.
+
+## 간단한 HTTP Basic Auth { #simple-http-basic-auth }
+
+* `HTTPBasic`과 `HTTPBasicCredentials`를 임포트합니다.
+* `HTTPBasic`을 사용해 "`security` scheme"을 생성합니다.
+* *경로 처리*에서 dependency로 해당 `security`를 사용합니다.
+* `HTTPBasicCredentials` 타입의 객체를 반환합니다:
+ * 전송된 `username`과 `password`를 포함합니다.
+
+{* ../../docs_src/security/tutorial006_an_py310.py hl[4,8,12] *}
+
+처음으로 URL을 열어보면(또는 문서에서 "Execute" 버튼을 클릭하면) 브라우저가 사용자명과 비밀번호를 물어봅니다:
+
+
+
+## 사용자명 확인하기 { #check-the-username }
+
+더 완전한 예시입니다.
+
+dependency를 사용해 사용자명과 비밀번호가 올바른지 확인하세요.
+
+이를 위해 Python 표준 모듈 [`secrets`](https://docs.python.org/3/library/secrets.html)를 사용해 사용자명과 비밀번호를 확인합니다.
+
+`secrets.compare_digest()`는 `bytes` 또는 ASCII 문자(영어에서 사용하는 문자)만 포함한 `str`을 받아야 합니다. 즉, `Sebastián`의 `á` 같은 문자가 있으면 동작하지 않습니다.
+
+이를 처리하기 위해 먼저 `username`과 `password`를 UTF-8로 인코딩해서 `bytes`로 변환합니다.
+
+그런 다음 `secrets.compare_digest()`를 사용해 `credentials.username`이 `"stanleyjobson"`이고 `credentials.password`가 `"swordfish"`인지 확실히 확인할 수 있습니다.
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[1,12:24] *}
+
+이는 다음과 비슷합니다:
+
+```Python
+if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
+ # 어떤 오류를 반환
+ ...
+```
+
+하지만 `secrets.compare_digest()`를 사용하면 "timing attacks"라고 불리는 한 유형의 공격에 대해 안전해집니다.
+
+### 타이밍 공격 { #timing-attacks }
+
+그렇다면 "timing attack"이란 무엇일까요?
+
+공격자들이 사용자명과 비밀번호를 추측하려고 한다고 가정해봅시다.
+
+그리고 사용자명 `johndoe`, 비밀번호 `love123`으로 요청을 보냅니다.
+
+그러면 애플리케이션의 Python 코드는 대략 다음과 같을 것입니다:
+
+```Python
+if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+하지만 Python이 `johndoe`의 첫 글자 `j`를 `stanleyjobson`의 첫 글자 `s`와 비교하는 순간, 두 문자열이 같지 않다는 것을 이미 알게 되어 `False`를 반환합니다. 이는 “나머지 글자들을 비교하느라 계산을 더 낭비할 필요가 없다”고 판단하기 때문입니다. 그리고 애플리케이션은 "Incorrect username or password"라고 말합니다.
+
+그런데 공격자들이 사용자명을 `stanleyjobsox`, 비밀번호를 `love123`으로 다시 시도합니다.
+
+그러면 애플리케이션 코드는 다음과 비슷하게 동작합니다:
+
+```Python
+if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Python은 두 문자열이 같지 않다는 것을 알아차리기 전까지 `stanleyjobsox`와 `stanleyjobson` 양쪽의 `stanleyjobso` 전체를 비교해야 합니다. 그래서 "Incorrect username or password"라고 응답하기까지 추가로 몇 마이크로초가 더 걸릴 것입니다.
+
+#### 응답 시간은 공격자에게 도움이 됩니다 { #the-time-to-answer-helps-the-attackers }
+
+이 시점에서 서버가 "Incorrect username or password" 응답을 보내는 데 몇 마이크로초 더 걸렸다는 것을 알아채면, 공격자들은 _무언가_ 맞았다는 것(초기 몇 글자가 맞았다는 것)을 알게 됩니다.
+
+그리고 `johndoe`보다는 `stanleyjobsox`에 더 가까운 값을 시도해야 한다는 것을 알고 다시 시도할 수 있습니다.
+
+#### "전문적인" 공격 { #a-professional-attack }
+
+물론 공격자들은 이런 작업을 손으로 하지 않습니다. 보통 초당 수천~수백만 번 테스트할 수 있는 프로그램을 작성할 것이고, 한 번에 정답 글자 하나씩 추가로 얻어낼 수 있습니다.
+
+그렇게 하면 몇 분 또는 몇 시간 만에, 응답에 걸린 시간만을 이용해(우리 애플리케이션의 “도움”을 받아) 올바른 사용자명과 비밀번호를 추측할 수 있게 됩니다.
+
+#### `secrets.compare_digest()`로 해결하기 { #fix-it-with-secrets-compare-digest }
+
+하지만 우리 코드는 실제로 `secrets.compare_digest()`를 사용하고 있습니다.
+
+요약하면, `stanleyjobsox`와 `stanleyjobson`을 비교하는 데 걸리는 시간은 `johndoe`와 `stanleyjobson`을 비교하는 데 걸리는 시간과 같아집니다. 비밀번호도 마찬가지입니다.
+
+이렇게 애플리케이션 코드에서 `secrets.compare_digest()`를 사용하면, 이러한 범위의 보안 공격 전반에 대해 안전해집니다.
+
+### 오류 반환하기 { #return-the-error }
+
+자격 증명이 올바르지 않다고 판단되면, 상태 코드 401(자격 증명이 제공되지 않았을 때와 동일)을 사용하는 `HTTPException`을 반환하고 브라우저가 로그인 프롬프트를 다시 표시하도록 `WWW-Authenticate` 헤더를 추가하세요:
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[26:30] *}
diff --git a/docs/ko/docs/advanced/security/index.md b/docs/ko/docs/advanced/security/index.md
new file mode 100644
index 0000000000000..126e6524a3adb
--- /dev/null
+++ b/docs/ko/docs/advanced/security/index.md
@@ -0,0 +1,19 @@
+# 고급 보안 { #advanced-security }
+
+## 추가 기능 { #additional-features }
+
+[튜토리얼 - 사용자 가이드: 보안](../../tutorial/security/index.md)에서 다룬 내용 외에도, 보안을 처리하기 위한 몇 가지 추가 기능이 있습니다.
+
+/// tip | 팁
+
+다음 섹션들은 **반드시 "고급"이라고 할 수는 없습니다**.
+
+그리고 사용 사례에 따라, 그중 하나에 해결책이 있을 수도 있습니다.
+
+///
+
+## 먼저 튜토리얼 읽기 { #read-the-tutorial-first }
+
+다음 섹션은 주요 [튜토리얼 - 사용자 가이드: 보안](../../tutorial/security/index.md)을 이미 읽었다고 가정합니다.
+
+모두 동일한 개념을 기반으로 하지만, 몇 가지 추가 기능을 사용할 수 있게 해줍니다.
diff --git a/docs/ko/docs/advanced/security/oauth2-scopes.md b/docs/ko/docs/advanced/security/oauth2-scopes.md
new file mode 100644
index 0000000000000..5a785ff9fdcec
--- /dev/null
+++ b/docs/ko/docs/advanced/security/oauth2-scopes.md
@@ -0,0 +1,274 @@
+# OAuth2 스코프 { #oauth2-scopes }
+
+**FastAPI**에서 OAuth2 스코프를 직접 사용할 수 있으며, 자연스럽게 동작하도록 통합되어 있습니다.
+
+이를 통해 OAuth2 표준을 따르는 더 세밀한 권한 시스템을 OpenAPI 애플리케이션(및 API 문서)에 통합할 수 있습니다.
+
+스코프를 사용하는 OAuth2는 Facebook, Google, GitHub, Microsoft, X(Twitter) 등 많은 대형 인증 제공자가 사용하는 메커니즘입니다. 이들은 이를 통해 사용자와 애플리케이션에 특정 권한을 제공합니다.
+
+Facebook, Google, GitHub, Microsoft, X(Twitter)로 “로그인”할 때마다, 해당 애플리케이션은 스코프가 있는 OAuth2를 사용하고 있습니다.
+
+이 섹션에서는 **FastAPI** 애플리케이션에서 동일한 “스코프가 있는 OAuth2”로 인증(Authentication)과 인가(Authorization)를 관리하는 방법을 확인합니다.
+
+/// warning | 경고
+
+이 섹션은 다소 고급 내용입니다. 이제 막 시작했다면 건너뛰어도 됩니다.
+
+OAuth2 스코프가 반드시 필요한 것은 아니며, 인증과 인가는 원하는 방식으로 처리할 수 있습니다.
+
+하지만 스코프가 있는 OAuth2는 (OpenAPI와 함께) API 및 API 문서에 깔끔하게 통합될 수 있습니다.
+
+그럼에도 불구하고, 해당 스코프(또는 그 밖의 어떤 보안/인가 요구사항이든)는 코드에서 필요에 맞게 직접 강제해야 합니다.
+
+많은 경우 스코프가 있는 OAuth2는 과한 선택일 수 있습니다.
+
+하지만 필요하다고 알고 있거나 궁금하다면 계속 읽어보세요.
+
+///
+
+## OAuth2 스코프와 OpenAPI { #oauth2-scopes-and-openapi }
+
+OAuth2 사양은 “스코프(scopes)”를 공백으로 구분된 문자열 목록으로 정의합니다.
+
+각 문자열의 내용은 어떤 형식이든 될 수 있지만, 공백을 포함하면 안 됩니다.
+
+이 스코프들은 “권한”을 나타냅니다.
+
+OpenAPI(예: API 문서)에서는 “security schemes”를 정의할 수 있습니다.
+
+이 security scheme 중 하나가 OAuth2를 사용한다면, 스코프도 선언하고 사용할 수 있습니다.
+
+각 “스코프”는 (공백 없는) 문자열일 뿐입니다.
+
+보통 다음과 같이 특정 보안 권한을 선언하는 데 사용합니다:
+
+* `users:read` 또는 `users:write` 는 흔한 예시입니다.
+* `instagram_basic` 는 Facebook/Instagram에서 사용합니다.
+* `https://www.googleapis.com/auth/drive` 는 Google에서 사용합니다.
+
+/// info | 정보
+
+OAuth2에서 “스코프”는 필요한 특정 권한을 선언하는 문자열일 뿐입니다.
+
+`:` 같은 다른 문자가 있거나 URL이어도 상관없습니다.
+
+그런 세부사항은 구현에 따라 달라집니다.
+
+OAuth2 입장에서는 그저 문자열입니다.
+
+///
+
+## 전체 개요 { #global-view }
+
+먼저, 메인 **튜토리얼 - 사용자 가이드**의 [비밀번호(및 해싱)를 사용하는 OAuth2, JWT 토큰을 사용하는 Bearer](../../tutorial/security/oauth2-jwt.md) 예제에서 어떤 부분이 바뀌는지 빠르게 살펴보겠습니다. 이제 OAuth2 스코프를 사용합니다:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}
+
+이제 변경 사항을 단계별로 살펴보겠습니다.
+
+## OAuth2 보안 스킴 { #oauth2-security-scheme }
+
+첫 번째 변경 사항은 이제 사용 가능한 스코프 2개(`me`, `items`)로 OAuth2 보안 스킴을 선언한다는 점입니다.
+
+`scopes` 매개변수는 각 스코프를 키로 하고, 설명을 값으로 하는 `dict`를 받습니다:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *}
+
+이제 스코프를 선언했기 때문에, 로그인/인가할 때 API 문서에 스코프가 표시됩니다.
+
+그리고 접근을 허용할 스코프를 선택할 수 있게 됩니다: `me`와 `items`.
+
+이는 Facebook, Google, GitHub 등으로 로그인하면서 권한을 부여할 때 사용되는 것과 동일한 메커니즘입니다:
+
+
+
+## 스코프를 포함한 JWT 토큰 { #jwt-token-with-scopes }
+
+이제 토큰 *경로 처리*를 수정해, 요청된 스코프를 반환하도록 합니다.
+
+여전히 동일한 `OAuth2PasswordRequestForm`을 사용합니다. 여기에는 요청에서 받은 각 스코프를 담는 `scopes` 속성이 있으며, 타입은 `str`의 `list`입니다.
+
+그리고 JWT 토큰의 일부로 스코프를 반환합니다.
+
+/// danger | 위험
+
+단순화를 위해, 여기서는 요청으로 받은 스코프를 그대로 토큰에 추가하고 있습니다.
+
+하지만 실제 애플리케이션에서는 보안을 위해, 사용자가 실제로 가질 수 있는 스코프만(또는 미리 정의한 것만) 추가하도록 반드시 확인해야 합니다.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}
+
+## *경로 처리*와 의존성에서 스코프 선언하기 { #declare-scopes-in-path-operations-and-dependencies }
+
+이제 `/users/me/items/`에 대한 *경로 처리*가 스코프 `items`를 요구한다고 선언합니다.
+
+이를 위해 `fastapi`에서 `Security`를 import하여 사용합니다.
+
+`Security`는 (`Depends`처럼) 의존성을 선언하는 데 사용할 수 있지만, `Security`는 스코프(문자열) 목록을 받는 `scopes` 매개변수도 받습니다.
+
+이 경우, 의존성 함수 `get_current_active_user`를 `Security`에 전달합니다(`Depends`로 할 때와 같은 방식).
+
+하지만 스코프 `list`도 함께 전달합니다. 여기서는 스코프 하나만: `items`(더 많을 수도 있습니다).
+
+또한 의존성 함수 `get_current_active_user`는 `Depends`뿐 아니라 `Security`로도 하위 의존성을 선언할 수 있습니다. 자체 하위 의존성 함수(`get_current_user`)와 추가 스코프 요구사항을 선언합니다.
+
+이 경우에는 스코프 `me`를 요구합니다(여러 스코프를 요구할 수도 있습니다).
+
+/// note | 참고
+
+반드시 서로 다른 곳에 서로 다른 스코프를 추가해야 하는 것은 아닙니다.
+
+여기서는 **FastAPI**가 서로 다른 레벨에서 선언된 스코프를 어떻게 처리하는지 보여주기 위해 이렇게 합니다.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}
+
+/// info | 기술 세부사항
+
+`Security`는 실제로 `Depends`의 서브클래스이며, 나중에 보게 될 추가 매개변수 하나만 더 있습니다.
+
+하지만 `Depends` 대신 `Security`를 사용하면, **FastAPI**는 보안 스코프를 선언할 수 있음을 알고 내부적으로 이를 사용하며, OpenAPI로 API를 문서화할 수 있습니다.
+
+하지만 `fastapi`에서 `Query`, `Path`, `Depends`, `Security` 등을 import할 때, 이것들은 실제로 특수한 클래스를 반환하는 함수입니다.
+
+///
+
+## `SecurityScopes` 사용하기 { #use-securityscopes }
+
+이제 의존성 `get_current_user`를 업데이트합니다.
+
+이는 위의 의존성들이 사용하는 것입니다.
+
+여기에서 앞서 만든 동일한 OAuth2 스킴을 의존성으로 선언하여 사용합니다: `oauth2_scheme`.
+
+이 의존성 함수 자체에는 스코프 요구사항이 없기 때문에, `oauth2_scheme`와 함께 `Depends`를 사용할 수 있습니다. 보안 스코프를 지정할 필요가 없을 때는 `Security`를 쓸 필요가 없습니다.
+
+또한 `fastapi.security`에서 import한 `SecurityScopes` 타입의 특별한 매개변수를 선언합니다.
+
+이 `SecurityScopes` 클래스는 `Request`와 비슷합니다(`Request`는 요청 객체를 직접 얻기 위해 사용했습니다).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}
+
+## `scopes` 사용하기 { #use-the-scopes }
+
+매개변수 `security_scopes`의 타입은 `SecurityScopes`입니다.
+
+여기에는 `scopes` 속성이 있으며, 자기 자신과 이 함수를 하위 의존성으로 사용하는 모든 의존성이 요구하는 스코프 전체를 담은 `list`를 가집니다. 즉, 모든 “dependants”... 다소 헷갈릴 수 있는데, 아래에서 다시 설명합니다.
+
+`security_scopes` 객체(`SecurityScopes` 클래스)에는 또한 `scope_str` 속성이 있는데, 공백으로 구분된 단일 문자열로 스코프들을 담고 있습니다(이를 사용할 것입니다).
+
+나중에 여러 지점에서 재사용(`raise`)할 수 있는 `HTTPException`을 생성합니다.
+
+이 예외에는 필요한 스코프(있다면)를 공백으로 구분된 문자열(`scope_str`)로 포함합니다. 그리고 그 스코프 문자열을 `WWW-Authenticate` 헤더에 넣습니다(이는 사양의 일부입니다).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}
+
+## `username`과 데이터 형태 검증하기 { #verify-the-username-and-data-shape }
+
+`username`을 얻었는지 확인하고, 스코프를 추출합니다.
+
+그런 다음 Pydantic 모델로 데이터를 검증합니다(`ValidationError` 예외를 잡습니다). JWT 토큰을 읽거나 Pydantic으로 데이터를 검증하는 과정에서 오류가 나면, 앞에서 만든 `HTTPException`을 raise합니다.
+
+이를 위해 Pydantic 모델 `TokenData`에 새 속성 `scopes`를 추가합니다.
+
+Pydantic으로 데이터를 검증하면, 예를 들어 스코프가 정확히 `str`의 `list`이고 `username`이 `str`인지 등을 보장할 수 있습니다.
+
+예를 들어 `dict`나 다른 형태라면, 나중에 애플리케이션이 어느 시점에 깨지면서 보안 위험이 될 수 있습니다.
+
+또한 해당 username을 가진 사용자가 있는지 확인하고, 없다면 앞에서 만든 동일한 예외를 raise합니다.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}
+
+## `scopes` 검증하기 { #verify-the-scopes }
+
+이제 이 의존성과 모든 dependant( *경로 처리* 포함)가 요구하는 모든 스코프가, 받은 토큰의 스코프에 포함되어 있는지 확인합니다. 그렇지 않으면 `HTTPException`을 raise합니다.
+
+이를 위해, 모든 스코프를 `str`로 담고 있는 `security_scopes.scopes`를 사용합니다.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}
+
+## 의존성 트리와 스코프 { #dependency-tree-and-scopes }
+
+이 의존성 트리와 스코프를 다시 살펴보겠습니다.
+
+`get_current_active_user` 의존성은 `get_current_user`를 하위 의존성으로 가지므로, `get_current_active_user`에서 선언된 스코프 `"me"`는 `get_current_user`에 전달되는 `security_scopes.scopes`의 요구 스코프 목록에 포함됩니다.
+
+*경로 처리* 자체도 스코프 `"items"`를 선언하므로, 이것 또한 `get_current_user`에 전달되는 `security_scopes.scopes` 목록에 포함됩니다.
+
+의존성과 스코프의 계층 구조는 다음과 같습니다:
+
+* *경로 처리* `read_own_items`는:
+ * 의존성과 함께 요구 스코프 `["items"]`를 가집니다:
+ * `get_current_active_user`:
+ * 의존성 함수 `get_current_active_user`는:
+ * 의존성과 함께 요구 스코프 `["me"]`를 가집니다:
+ * `get_current_user`:
+ * 의존성 함수 `get_current_user`는:
+ * 자체적으로는 요구 스코프가 없습니다.
+ * `oauth2_scheme`를 사용하는 의존성이 있습니다.
+ * `SecurityScopes` 타입의 `security_scopes` 매개변수가 있습니다:
+ * 이 `security_scopes` 매개변수는 위에서 선언된 모든 스코프를 담은 `list`인 `scopes` 속성을 가지므로:
+ * *경로 처리* `read_own_items`의 경우 `security_scopes.scopes`에는 `["me", "items"]`가 들어갑니다.
+ * *경로 처리* `read_users_me`의 경우 `security_scopes.scopes`에는 `["me"]`가 들어갑니다. 이는 의존성 `get_current_active_user`에서 선언되기 때문입니다.
+ * *경로 처리* `read_system_status`의 경우 `security_scopes.scopes`에는 `[]`(없음)가 들어갑니다. `scopes`가 있는 `Security`를 선언하지 않았고, 그 의존성인 `get_current_user`도 `scopes`를 선언하지 않았기 때문입니다.
+
+/// tip | 팁
+
+여기서 중요한 “마법 같은” 점은 `get_current_user`가 각 *경로 처리*마다 검사해야 하는 `scopes` 목록이 달라진다는 것입니다.
+
+이는 특정 *경로 처리*에 대한 의존성 트리에서, 각 *경로 처리*와 각 의존성에 선언된 `scopes`에 따라 달라집니다.
+
+///
+
+## `SecurityScopes`에 대한 추가 설명 { #more-details-about-securityscopes }
+
+`SecurityScopes`는 어느 지점에서든, 그리고 여러 곳에서 사용할 수 있으며, “루트” 의존성에만 있어야 하는 것은 아닙니다.
+
+`SecurityScopes`는 **해당 특정** *경로 처리*와 **해당 특정** 의존성 트리에 대해, 현재 `Security` 의존성과 모든 dependant에 선언된 보안 스코프를 항상 갖고 있습니다.
+
+`SecurityScopes`에는 dependant가 선언한 모든 스코프가 포함되므로, 중앙의 의존성 함수에서 토큰이 필요한 스코프를 가지고 있는지 검증한 다음, 서로 다른 *경로 처리*에서 서로 다른 스코프 요구사항을 선언할 수 있습니다.
+
+이들은 각 *경로 처리*마다 독립적으로 검사됩니다.
+
+## 확인하기 { #check-it }
+
+API 문서를 열면, 인증하고 인가할 스코프를 지정할 수 있습니다.
+
+
+
+어떤 스코프도 선택하지 않으면 “인증”은 되지만, `/users/me/` 또는 `/users/me/items/`에 접근하려고 하면 권한이 충분하지 않다는 오류가 발생합니다. `/status/`에는 여전히 접근할 수 있습니다.
+
+그리고 스코프 `me`는 선택했지만 스코프 `items`는 선택하지 않았다면, `/users/me/`에는 접근할 수 있지만 `/users/me/items/`에는 접근할 수 없습니다.
+
+이는 사용자가 애플리케이션에 얼마나 많은 권한을 부여했는지에 따라, 제3자 애플리케이션이 사용자로부터 제공받은 토큰으로 이 *경로 처리*들 중 하나에 접근하려고 할 때 발생하는 상황과 같습니다.
+
+## 제3자 통합에 대해 { #about-third-party-integrations }
+
+이 예제에서는 OAuth2 “password” 플로우를 사용하고 있습니다.
+
+이는 보통 자체 프론트엔드가 있는 우리 애플리케이션에 로그인할 때 적합합니다.
+
+우리가 이를 통제하므로 `username`과 `password`를 받는 것을 신뢰할 수 있기 때문입니다.
+
+하지만 다른 사람들이 연결할 OAuth2 애플리케이션(즉, Facebook, Google, GitHub 등과 동등한 인증 제공자를 만들고 있다면)을 구축한다면, 다른 플로우 중 하나를 사용해야 합니다.
+
+가장 흔한 것은 implicit 플로우입니다.
+
+가장 안전한 것은 code 플로우이지만, 더 많은 단계가 필요해 구현이 더 복잡합니다. 복잡하기 때문에 많은 제공자는 implicit 플로우를 권장하게 됩니다.
+
+/// note | 참고
+
+인증 제공자마다 자신들의 브랜드의 일부로 만들기 위해, 각 플로우를 서로 다른 방식으로 이름 붙이는 경우가 흔합니다.
+
+하지만 결국, 동일한 OAuth2 표준을 구현하고 있는 것입니다.
+
+///
+
+**FastAPI**는 `fastapi.security.oauth2`에 이러한 모든 OAuth2 인증 플로우를 위한 유틸리티를 포함합니다.
+
+## 데코레이터 `dependencies`에서의 `Security` { #security-in-decorator-dependencies }
+
+[경로 처리 데코레이터의 의존성](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md)에서 설명한 것처럼 데코레이터의 `dependencies` 매개변수에 `Depends`의 `list`를 정의할 수 있는 것과 같은 방식으로, 거기에서 `scopes`와 함께 `Security`를 사용할 수도 있습니다.
diff --git a/docs/ko/docs/advanced/settings.md b/docs/ko/docs/advanced/settings.md
new file mode 100644
index 0000000000000..49a2b640e9ee4
--- /dev/null
+++ b/docs/ko/docs/advanced/settings.md
@@ -0,0 +1,302 @@
+# 설정과 환경 변수 { #settings-and-environment-variables }
+
+많은 경우 애플리케이션에는 외부 설정이나 구성(예: secret key, 데이터베이스 자격 증명, 이메일 서비스 자격 증명 등)이 필요할 수 있습니다.
+
+이러한 설정 대부분은 데이터베이스 URL처럼 변동 가능(변경될 수 있음)합니다. 그리고 많은 설정은 secret처럼 민감할 수 있습니다.
+
+이 때문에 보통 애플리케이션이 읽어들이는 환경 변수로 이를 제공하는 것이 일반적입니다.
+
+/// tip | 팁
+
+환경 변수를 이해하려면 [환경 변수](../environment-variables.md)를 읽어보세요.
+
+///
+
+## 타입과 검증 { #types-and-validation }
+
+이 환경 변수들은 Python 외부에 있으며 다른 프로그램 및 시스템의 나머지 부분(그리고 Linux, Windows, macOS 같은 서로 다른 운영체제와도)과 호환되어야 하므로, 텍스트 문자열만 다룰 수 있습니다.
+
+즉, Python에서 환경 변수로부터 읽어온 어떤 값이든 `str`이 되며, 다른 타입으로의 변환이나 검증은 코드에서 수행해야 합니다.
+
+## Pydantic `Settings` { #pydantic-settings }
+
+다행히 Pydantic은 환경 변수에서 오는 이러한 설정을 처리할 수 있는 훌륭한 유틸리티를 [Pydantic: Settings 관리](https://docs.pydantic.dev/latest/concepts/pydantic_settings/)로 제공합니다.
+
+### `pydantic-settings` 설치하기 { #install-pydantic-settings }
+
+먼저 [가상 환경](../virtual-environments.md)을 만들고 활성화한 다음, `pydantic-settings` 패키지를 설치하세요:
+
+
+
+그 다음, [http://127.0.0.1:8000/subapi/docs](http://127.0.0.1:8000/subapi/docs)에서 하위 애플리케이션의 문서를 여세요.
+
+하위 애플리케이션의 자동 API 문서를 보게 될 것이며, 하위 경로 접두사 `/subapi` 아래에 올바르게 포함된 하위 애플리케이션 자체의 _경로 처리_만 포함됩니다:
+
+
+
+두 사용자 인터페이스 중 어느 것과 상호작용을 시도하더라도 올바르게 동작할 것입니다. 브라우저가 각 특정 앱 또는 하위 앱과 통신할 수 있기 때문입니다.
+
+### 기술적 세부사항: `root_path` { #technical-details-root-path }
+
+위에서 설명한 대로 하위 애플리케이션을 마운트하면, FastAPI는 ASGI 명세의 메커니즘인 `root_path`를 사용해 하위 애플리케이션에 대한 마운트 경로를 전달하는 작업을 처리합니다.
+
+이렇게 하면 하위 애플리케이션은 문서 UI를 위해 해당 경로 접두사를 사용해야 한다는 것을 알게 됩니다.
+
+또한 하위 애플리케이션도 자체적으로 하위 앱을 마운트할 수 있으며, FastAPI가 이 모든 `root_path`를 자동으로 처리하기 때문에 모든 것이 올바르게 동작합니다.
+
+`root_path`와 이를 명시적으로 사용하는 방법에 대해서는 [프록시 뒤](behind-a-proxy.md) 섹션에서 더 알아볼 수 있습니다.
diff --git a/docs/ko/docs/advanced/templates.md b/docs/ko/docs/advanced/templates.md
new file mode 100644
index 0000000000000..9c33f37e918cd
--- /dev/null
+++ b/docs/ko/docs/advanced/templates.md
@@ -0,0 +1,126 @@
+# 템플릿 { #templates }
+
+**FastAPI**와 함께 원하는 어떤 템플릿 엔진도 사용할 수 있습니다.
+
+일반적인 선택은 Jinja2로, Flask와 다른 도구에서도 사용됩니다.
+
+설정을 쉽게 할 수 있는 유틸리티가 있으며, 이를 **FastAPI** 애플리케이션에서 직접 사용할 수 있습니다(Starlette 제공).
+
+## 의존성 설치 { #install-dependencies }
+
+[가상 환경](../virtual-environments.md)을 생성하고, 활성화한 후 `jinja2`를 설치해야 합니다:
+
+
+
+입력창에 메시지를 입력하고 전송할 수 있습니다:
+
+
+
+그리고 WebSockets가 포함된 **FastAPI** 애플리케이션이 응답을 돌려줄 것입니다:
+
+
+
+여러 메시지를 전송(그리고 수신)할 수 있습니다:
+
+
+
+그리고 모든 메시지는 동일한 WebSocket 연결을 사용합니다.
+
+## `Depends` 및 기타 사용하기 { #using-depends-and-others }
+
+WebSocket 엔드포인트에서 `fastapi`에서 다음을 가져와 사용할 수 있습니다:
+
+* `Depends`
+* `Security`
+* `Cookie`
+* `Header`
+* `Path`
+* `Query`
+
+이들은 다른 FastAPI 엔드포인트/*경로 처리*와 동일하게 동작합니다:
+
+{* ../../docs_src/websockets_/tutorial002_an_py310.py hl[68:69,82] *}
+
+/// info | 정보
+
+WebSocket이기 때문에 `HTTPException`을 발생시키는 것은 적절하지 않습니다. 대신 `WebSocketException`을 발생시킵니다.
+
+명세서에 정의된 [유효한 코드](https://tools.ietf.org/html/rfc6455#section-7.4.1)를 사용하여 종료 코드를 설정할 수 있습니다.
+
+///
+
+### 종속성을 가진 WebSockets 시도해보기 { #try-the-websockets-with-dependencies }
+
+애플리케이션을 실행합니다:
+
+
+
+## 연결 해제 및 다중 클라이언트 처리 { #handling-disconnections-and-multiple-clients }
+
+WebSocket 연결이 닫히면, `await websocket.receive_text()`가 `WebSocketDisconnect` 예외를 발생시킵니다. 그러면 이 예제처럼 이를 잡아 처리할 수 있습니다.
+
+{* ../../docs_src/websockets_/tutorial003_py310.py hl[79:81] *}
+
+테스트해보기:
+
+* 여러 브라우저 탭에서 앱을 엽니다.
+* 각 탭에서 메시지를 작성합니다.
+* 그런 다음 탭 중 하나를 닫아보세요.
+
+`WebSocketDisconnect` 예외가 발생하며, 다른 모든 클라이언트가 다음과 같은 메시지를 수신합니다:
+
+```
+Client #1596980209979 left the chat
+```
+
+/// tip | 팁
+
+위 앱은 여러 WebSocket 연결에 메시지를 처리하고 브로드캐스트하는 방법을 보여주는 최소한의 간단한 예제입니다.
+
+하지만 모든 것을 메모리의 단일 리스트로 처리하므로, 프로세스가 실행 중인 동안만 동작하며 단일 프로세스에서만 작동한다는 점을 기억하세요.
+
+FastAPI와 쉽게 통합할 수 있으면서 더 견고하고 Redis, PostgreSQL 등을 지원하는 도구가 필요하다면, [encode/broadcaster](https://github.com/encode/broadcaster)를 확인하세요.
+
+///
+
+## 추가 정보 { #more-info }
+
+다음 옵션에 대해 더 알아보려면 Starlette의 문서를 확인하세요:
+
+* [`WebSocket` 클래스](https://www.starlette.dev/websockets/).
+* [클래스 기반 WebSocket 처리](https://www.starlette.dev/endpoints/#websocketendpoint).
diff --git a/docs/ko/docs/advanced/wsgi.md b/docs/ko/docs/advanced/wsgi.md
new file mode 100644
index 0000000000000..921e426efd245
--- /dev/null
+++ b/docs/ko/docs/advanced/wsgi.md
@@ -0,0 +1,51 @@
+# WSGI 포함하기 - Flask, Django 등 { #including-wsgi-flask-django-others }
+
+[서브 애플리케이션 - 마운트](sub-applications.md), [프록시 뒤에서](behind-a-proxy.md)에서 본 것처럼 WSGI 애플리케이션을 마운트할 수 있습니다.
+
+이를 위해 `WSGIMiddleware`를 사용해 WSGI 애플리케이션(예: Flask, Django 등)을 감쌀 수 있습니다.
+
+## `WSGIMiddleware` 사용하기 { #using-wsgimiddleware }
+
+/// info | 정보
+
+이를 사용하려면 `a2wsgi`를 설치해야 합니다. 예: `pip install a2wsgi`
+
+///
+
+`a2wsgi`에서 `WSGIMiddleware`를 import 해야 합니다.
+
+그런 다음, WSGI(예: Flask) 애플리케이션을 미들웨어로 감쌉니다.
+
+그리고 해당 경로에 마운트합니다.
+
+{* ../../docs_src/wsgi/tutorial001_py310.py hl[1,3,23] *}
+
+/// note | 참고
+
+이전에 `fastapi.middleware.wsgi`의 `WSGIMiddleware` 사용을 권장했지만 이제는 더 이상 권장되지 않습니다.
+
+대신 `a2wsgi` 패키지 사용을 권장합니다. 사용 방법은 동일합니다.
+
+단, `a2wsgi` 패키지가 설치되어 있고 `a2wsgi`에서 `WSGIMiddleware`를 올바르게 import 하는지만 확인하세요.
+
+///
+
+## 확인하기 { #check-it }
+
+이제 `/v1/` 경로에 있는 모든 요청은 Flask 애플리케이션에서 처리됩니다.
+
+그리고 나머지는 **FastAPI**에 의해 처리됩니다.
+
+실행하고 [http://localhost:8000/v1/](http://localhost:8000/v1/)로 이동하면 Flask의 응답을 볼 수 있습니다:
+
+```txt
+Hello, World from Flask!
+```
+
+그리고 [http://localhost:8000/v2](http://localhost:8000/v2)로 이동하면 **FastAPI**의 응답을 볼 수 있습니다:
+
+```JSON
+{
+ "message": "Hello World"
+}
+```
diff --git a/docs/ko/docs/alternatives.md b/docs/ko/docs/alternatives.md
new file mode 100644
index 0000000000000..4f92f69d24ae5
--- /dev/null
+++ b/docs/ko/docs/alternatives.md
@@ -0,0 +1,485 @@
+# 대안, 영감, 비교 { #alternatives-inspiration-and-comparisons }
+
+**FastAPI**에 영감을 준 것들, 대안과의 비교, 그리고 그로부터 무엇을 배웠는지에 대한 내용입니다.
+
+## 소개 { #intro }
+
+다른 사람들의 이전 작업이 없었다면 **FastAPI**는 존재하지 않았을 것입니다.
+
+그 전에 만들어진 많은 도구들이 **FastAPI**의 탄생에 영감을 주었습니다.
+
+저는 여러 해 동안 새로운 framework를 만드는 것을 피하고 있었습니다. 먼저 **FastAPI**가 다루는 모든 기능을 여러 서로 다른 framework, plug-in, 도구를 사용해 해결해 보려고 했습니다.
+
+하지만 어느 시점에는, 이전 도구들의 가장 좋은 아이디어를 가져와 가능한 최선의 방식으로 조합하고, 이전에는 존재하지 않았던 언어 기능(Python 3.6+ type hints)을 활용해 이 모든 기능을 제공하는 무언가를 만드는 것 외에는 다른 선택지가 없었습니다.
+
+## 이전 도구들 { #previous-tools }
+
+### [Django](https://www.djangoproject.com/) { #django }
+
+가장 인기 있는 Python framework이며 널리 신뢰받고 있습니다. Instagram 같은 시스템을 만드는 데 사용됩니다.
+
+상대적으로 관계형 데이터베이스(예: MySQL 또는 PostgreSQL)와 강하게 결합되어 있어서, NoSQL 데이터베이스(예: Couchbase, MongoDB, Cassandra 등)를 주 저장 엔진으로 사용하는 것은 그리 쉽지 않습니다.
+
+백엔드에서 HTML을 생성하기 위해 만들어졌지, 현대적인 프런트엔드(예: React, Vue.js, Angular)나 다른 시스템(예: IoT 기기)에서 사용되는 API를 만들기 위해 설계된 것은 아닙니다.
+
+### [Django REST Framework](https://www.django-rest-framework.org/) { #django-rest-framework }
+
+Django REST framework는 Django를 기반으로 Web API를 구축하기 위한 유연한 toolkit으로 만들어졌고, Django의 API 기능을 개선하기 위한 목적이었습니다.
+
+Mozilla, Red Hat, Eventbrite를 포함해 많은 회사에서 사용합니다.
+
+**자동 API 문서화**의 초기 사례 중 하나였고, 이것이 특히 **FastAPI**를 "찾게 된" 첫 아이디어 중 하나였습니다.
+
+/// note | 참고
+
+Django REST Framework는 Tom Christie가 만들었습니다. **FastAPI**의 기반이 되는 Starlette와 Uvicorn을 만든 사람과 동일합니다.
+
+///
+
+/// check | **FastAPI**에 영감을 준 것
+
+자동 API 문서화 웹 사용자 인터페이스를 제공하기.
+
+///
+
+### [Flask](https://flask.palletsprojects.com) { #flask }
+
+Flask는 "microframework"로, Django에 기본으로 포함된 데이터베이스 통합이나 여러 기능들을 포함하지 않습니다.
+
+이 단순함과 유연성 덕분에 NoSQL 데이터베이스를 주 데이터 저장 시스템으로 사용하는 같은 작업이 가능합니다.
+
+매우 단순하기 때문에 비교적 직관적으로 배울 수 있지만, 문서가 어떤 지점에서는 다소 기술적으로 깊어지기도 합니다.
+
+또한 데이터베이스, 사용자 관리, 혹은 Django에 미리 구축되어 있는 다양한 기능들이 꼭 필요하지 않은 다른 애플리케이션에도 흔히 사용됩니다. 물론 이런 기능들 중 다수는 plug-in으로 추가할 수 있습니다.
+
+이런 구성요소의 분리와, 필요한 것만 정확히 덧붙여 확장할 수 있는 "microframework"라는 점은 제가 유지하고 싶었던 핵심 특성이었습니다.
+
+Flask의 단순함을 고려하면 API를 구축하는 데 잘 맞는 것처럼 보였습니다. 다음으로 찾고자 했던 것은 Flask용 "Django REST Framework"였습니다.
+
+/// check | **FastAPI**에 영감을 준 것
+
+micro-framework가 되기. 필요한 도구와 구성요소를 쉽게 조합할 수 있도록 하기.
+
+단순하고 사용하기 쉬운 routing 시스템을 갖기.
+
+///
+
+### [Requests](https://requests.readthedocs.io) { #requests }
+
+**FastAPI**는 실제로 **Requests**의 대안이 아닙니다. 둘의 범위는 매우 다릅니다.
+
+실제로 FastAPI 애플리케이션 *내부에서* Requests를 사용하는 경우도 흔합니다.
+
+그럼에도 FastAPI는 Requests로부터 꽤 많은 영감을 얻었습니다.
+
+**Requests**는 (클라이언트로서) API와 *상호작용*하기 위한 라이브러리이고, **FastAPI**는 (서버로서) API를 *구축*하기 위한 라이브러리입니다.
+
+대략 말하면 서로 반대편에 있으며, 서로를 보완합니다.
+
+Requests는 매우 단순하고 직관적인 설계를 가졌고, 합리적인 기본값을 바탕으로 사용하기가 아주 쉽습니다. 동시에 매우 강력하고 커스터마이징도 가능합니다.
+
+그래서 공식 웹사이트에서 말하듯이:
+
+> Requests is one of the most downloaded Python packages of all time
+
+사용 방법은 매우 간단합니다. 예를 들어 `GET` 요청을 하려면 다음처럼 작성합니다:
+
+```Python
+response = requests.get("http://example.com/some/url")
+```
+
+이에 대응하는 FastAPI의 API *경로 처리*는 다음과 같이 보일 수 있습니다:
+
+```Python hl_lines="1"
+@app.get("/some/url")
+def read_url():
+ return {"message": "Hello World"}
+```
+
+`requests.get(...)`와 `@app.get(...)`의 유사성을 확인해 보세요.
+
+/// check | **FastAPI**에 영감을 준 것
+
+* 단순하고 직관적인 API를 갖기.
+* HTTP method 이름(operations)을 직접, 직관적이고 명확한 방식으로 사용하기.
+* 합리적인 기본값을 제공하되, 강력한 커스터마이징을 가능하게 하기.
+
+///
+
+### [Swagger](https://swagger.io/) / [OpenAPI](https://github.com/OAI/OpenAPI-Specification/) { #swagger-openapi }
+
+제가 Django REST Framework에서 가장 원했던 주요 기능은 자동 API 문서화였습니다.
+
+그 후 JSON(또는 JSON의 확장인 YAML)을 사용해 API를 문서화하는 표준인 Swagger가 있다는 것을 알게 되었습니다.
+
+그리고 Swagger API를 위한 웹 사용자 인터페이스도 이미 만들어져 있었습니다. 그래서 API에 대한 Swagger 문서를 생성할 수 있다면, 이 웹 사용자 인터페이스를 자동으로 사용할 수 있게 됩니다.
+
+어느 시점에 Swagger는 Linux Foundation으로 넘어가 OpenAPI로 이름이 바뀌었습니다.
+
+그래서 2.0 버전을 이야기할 때는 "Swagger"라고 말하는 것이 일반적이고, 3+ 버전은 "OpenAPI"라고 말하는 것이 일반적입니다.
+
+/// check | **FastAPI**에 영감을 준 것
+
+커스텀 schema 대신, API 사양을 위한 열린 표준을 채택하고 사용하기.
+
+또한 표준 기반의 사용자 인터페이스 도구를 통합하기:
+
+* [Swagger UI](https://github.com/swagger-api/swagger-ui)
+* [ReDoc](https://github.com/Rebilly/ReDoc)
+
+이 두 가지는 꽤 대중적이고 안정적이기 때문에 선택되었습니다. 하지만 간단히 검색해보면 OpenAPI를 위한 대안 UI가 수십 가지나 있다는 것을 알 수 있습니다(**FastAPI**와 함께 사용할 수 있습니다).
+
+///
+
+### Flask REST framework들 { #flask-rest-frameworks }
+
+Flask REST framework는 여러 개가 있지만, 시간을 들여 조사해 본 결과, 상당수가 중단되었거나 방치되어 있었고, 해결되지 않은 여러 이슈 때문에 적합하지 않은 경우가 많았습니다.
+
+### [Marshmallow](https://marshmallow.readthedocs.io/en/stable/) { #marshmallow }
+
+API 시스템에 필요한 주요 기능 중 하나는 데이터 "직렬화"입니다. 이는 코드(Python)에서 데이터를 가져와 네트워크로 전송할 수 있는 형태로 변환하는 것을 의미합니다. 예를 들어 데이터베이스의 데이터를 담은 객체를 JSON 객체로 변환하거나, `datetime` 객체를 문자열로 변환하는 등의 작업입니다.
+
+API에 또 하나 크게 필요한 기능은 데이터 검증입니다. 특정 파라미터를 기준으로 데이터가 유효한지 확인하는 것입니다. 예를 들어 어떤 필드가 `int`인지, 임의의 문자열이 아닌지 확인하는 식입니다. 이는 특히 들어오는 데이터에 유용합니다.
+
+데이터 검증 시스템이 없다면, 모든 검사를 코드에서 수동으로 해야 합니다.
+
+이런 기능들을 제공하기 위해 Marshmallow가 만들어졌습니다. 훌륭한 라이브러리이며, 저도 이전에 많이 사용했습니다.
+
+하지만 Python type hints가 존재하기 전에 만들어졌습니다. 그래서 각 스키마를 정의하려면 Marshmallow가 제공하는 특정 유틸리티와 클래스를 사용해야 합니다.
+
+/// check | **FastAPI**에 영감을 준 것
+
+데이터 타입과 검증을 제공하는 "schema"를 코드로 정의하고, 이를 자동으로 활용하기.
+
+///
+
+### [Webargs](https://webargs.readthedocs.io/en/latest/) { #webargs }
+
+API에 필요한 또 다른 큰 기능은 들어오는 요청에서 데이터를 파싱하는 것입니다.
+
+Webargs는 Flask를 포함한 여러 framework 위에서 이를 제공하기 위해 만들어진 도구입니다.
+
+내부적으로 Marshmallow를 사용해 데이터 검증을 수행합니다. 그리고 같은 개발자들이 만들었습니다.
+
+아주 훌륭한 도구이며, 저도 **FastAPI**를 만들기 전에 많이 사용했습니다.
+
+/// info | 정보
+
+Webargs는 Marshmallow와 같은 개발자들이 만들었습니다.
+
+///
+
+/// check | **FastAPI**에 영감을 준 것
+
+들어오는 요청 데이터의 자동 검증을 갖기.
+
+///
+
+### [APISpec](https://apispec.readthedocs.io/en/stable/) { #apispec }
+
+Marshmallow와 Webargs는 plug-in 형태로 검증, parsing, serialization을 제공합니다.
+
+하지만 문서화는 여전히 부족했습니다. 그래서 APISpec이 만들어졌습니다.
+
+이는 여러 framework를 위한 plug-in이며(Starlette용 plug-in도 있습니다).
+
+작동 방식은, 각 route를 처리하는 함수의 docstring 안에 YAML 형식으로 schema 정의를 작성하고,
+
+그로부터 OpenAPI schema를 생성합니다.
+
+Flask, Starlette, Responder 등에서 이런 방식으로 동작합니다.
+
+하지만 다시, Python 문자열 내부(큰 YAML)에서 micro-syntax를 다루어야 한다는 문제가 있습니다.
+
+에디터가 이를 크게 도와주지 못합니다. 또한 파라미터나 Marshmallow schema를 수정해놓고 YAML docstring도 같이 수정하는 것을 잊어버리면, 생성된 schema는 오래된 상태가 됩니다.
+
+/// info | 정보
+
+APISpec은 Marshmallow와 같은 개발자들이 만들었습니다.
+
+///
+
+/// check | **FastAPI**에 영감을 준 것
+
+API를 위한 열린 표준인 OpenAPI를 지원하기.
+
+///
+
+### [Flask-apispec](https://flask-apispec.readthedocs.io/en/latest/) { #flask-apispec }
+
+Flask plug-in으로, Webargs, Marshmallow, APISpec을 묶어줍니다.
+
+Webargs와 Marshmallow의 정보를 사용해 APISpec으로 OpenAPI schema를 자동 생성합니다.
+
+훌륭한 도구인데도 과소평가되어 있습니다. 다른 많은 Flask plug-in보다 훨씬 더 유명해져야 합니다. 문서가 너무 간결하고 추상적이라서 그럴 수도 있습니다.
+
+이 도구는 Python docstring 내부에 YAML(또 다른 문법)을 작성해야 하는 문제를 해결했습니다.
+
+Flask + Flask-apispec + Marshmallow + Webargs 조합은 **FastAPI**를 만들기 전까지 제가 가장 좋아하던 백엔드 stack이었습니다.
+
+이를 사용하면서 여러 Flask full-stack generator가 만들어졌습니다. 이것들이 지금까지 저(그리고 여러 외부 팀)가 사용해 온 주요 stack입니다:
+
+* [https://github.com/tiangolo/full-stack](https://github.com/tiangolo/full-stack)
+* [https://github.com/tiangolo/full-stack-flask-couchbase](https://github.com/tiangolo/full-stack-flask-couchbase)
+* [https://github.com/tiangolo/full-stack-flask-couchdb](https://github.com/tiangolo/full-stack-flask-couchdb)
+
+그리고 이 동일한 full-stack generator들이 [**FastAPI** Project Generators](project-generation.md)의 기반이 되었습니다.
+
+/// info | 정보
+
+Flask-apispec은 Marshmallow와 같은 개발자들이 만들었습니다.
+
+///
+
+/// check | **FastAPI**에 영감을 준 것
+
+serialization과 validation을 정의하는 동일한 코드로부터 OpenAPI schema를 자동 생성하기.
+
+///
+
+### [NestJS](https://nestjs.com/) (그리고 [Angular](https://angular.io/)) { #nestjs-and-angular }
+
+이건 Python도 아닙니다. NestJS는 Angular에서 영감을 받은 JavaScript(TypeScript) NodeJS framework입니다.
+
+Flask-apispec으로 할 수 있는 것과 어느 정도 비슷한 것을 달성합니다.
+
+Angular 2에서 영감을 받은 의존성 주입 시스템이 통합되어 있습니다. 제가 아는 다른 의존성 주입 시스템들처럼 "injectable"을 사전에 등록해야 하므로, 장황함과 코드 반복이 늘어납니다.
+
+파라미터가 TypeScript 타입(Python type hints와 유사함)으로 설명되기 때문에 에디터 지원은 꽤 좋습니다.
+
+하지만 TypeScript 데이터는 JavaScript로 컴파일된 뒤에는 보존되지 않기 때문에, 타입에 의존해 검증, serialization, 문서화를 동시에 정의할 수 없습니다. 이 점과 일부 설계 결정 때문에, 검증/serialization/자동 schema 생성을 하려면 여러 곳에 decorator를 추가해야 하며, 결과적으로 매우 장황해집니다.
+
+중첩 모델을 잘 처리하지 못합니다. 즉, 요청의 JSON body가 내부 필드를 가진 JSON 객체이고 그 내부 필드들이 다시 중첩된 JSON 객체인 경우, 제대로 문서화하고 검증할 수 없습니다.
+
+/// check | **FastAPI**에 영감을 준 것
+
+Python 타입을 사용해 뛰어난 에디터 지원을 제공하기.
+
+강력한 의존성 주입 시스템을 갖추기. 코드 반복을 최소화하는 방법을 찾기.
+
+///
+
+### [Sanic](https://sanic.readthedocs.io/en/latest/) { #sanic }
+
+`asyncio` 기반의 매우 빠른 Python framework 중 초기 사례였습니다. Flask와 매우 유사하게 만들어졌습니다.
+
+/// note | 기술 세부사항
+
+[`uvloop`](https://github.com/MagicStack/uvloop)를 기본 Python `asyncio` 루프 대신 사용했습니다. 이것이 매우 빠르게 만든 요인입니다.
+
+이는 Uvicorn과 Starlette에 명확히 영감을 주었고, 현재 공개 benchmark에서는 이 둘이 Sanic보다 더 빠릅니다.
+
+///
+
+/// check | **FastAPI**에 영감을 준 것
+
+미친 성능을 낼 수 있는 방법을 찾기.
+
+그래서 **FastAPI**는 Starlette를 기반으로 합니다. Starlette는 사용 가능한 framework 중 가장 빠르기 때문입니다(서드파티 benchmark로 테스트됨).
+
+///
+
+### [Falcon](https://falconframework.org/) { #falcon }
+
+Falcon은 또 다른 고성능 Python framework로, 최소한으로 설계되었고 Hug 같은 다른 framework의 기반으로 동작하도록 만들어졌습니다.
+
+함수가 두 개의 파라미터(하나는 "request", 하나는 "response")를 받도록 설계되어 있습니다. 그런 다음 request에서 일부를 "읽고", response에 일부를 "작성"합니다. 이 설계 때문에, 표준 Python type hints를 함수 파라미터로 사용해 요청 파라미터와 body를 선언하는 것이 불가능합니다.
+
+따라서 데이터 검증, serialization, 문서화는 자동으로 되지 않고 코드로 해야 합니다. 또는 Hug처럼 Falcon 위에 framework를 얹어 구현해야 합니다. request 객체 하나와 response 객체 하나를 파라미터로 받는 Falcon의 설계에서 영감을 받은 다른 framework에서도 같은 구분이 나타납니다.
+
+/// check | **FastAPI**에 영감을 준 것
+
+훌륭한 성능을 얻는 방법을 찾기.
+
+Hug(= Falcon 기반)과 함께, 함수에서 `response` 파라미터를 선언하도록 **FastAPI**에 영감을 주었습니다.
+
+다만 FastAPI에서는 선택 사항이며, 주로 헤더, 쿠키, 그리고 대체 status code를 설정하는 데 사용됩니다.
+
+///
+
+### [Molten](https://moltenframework.com/) { #molten }
+
+**FastAPI**를 만들기 시작한 초기 단계에서 Molten을 알게 되었고, 꽤 비슷한 아이디어를 갖고 있었습니다:
+
+* Python type hints 기반
+* 이 타입으로부터 검증과 문서화 생성
+* 의존성 주입 시스템
+
+Pydantic 같은 서드파티 라이브러리를 사용해 데이터 검증/serialization/문서화를 하지 않고 자체 구현을 사용합니다. 그래서 이런 데이터 타입 정의를 쉽게 재사용하기는 어렵습니다.
+
+조금 더 장황한 설정이 필요합니다. 또한 WSGI(ASGI가 아니라) 기반이므로, Uvicorn, Starlette, Sanic 같은 도구가 제공하는 고성능을 활용하도록 설계되지 않았습니다.
+
+의존성 주입 시스템은 의존성을 사전에 등록해야 하고, 선언된 타입을 기반으로 의존성을 해결합니다. 따라서 특정 타입을 제공하는 "component"를 두 개 이상 선언할 수 없습니다.
+
+Route는 한 곳에서 선언하고, 다른 곳에 선언된 함수를 사용합니다(엔드포인트를 처리하는 함수 바로 위에 둘 수 있는 decorator를 사용하는 대신). 이는 Flask(및 Starlette)보다는 Django 방식에 가깝습니다. 코드에서 상대적으로 강하게 결합된 것들을 분리해 놓습니다.
+
+/// check | **FastAPI**에 영감을 준 것
+
+모델 속성의 "default" 값으로 데이터 타입에 대한 추가 검증을 정의하기. 이는 에디터 지원을 개선하며, 이전에는 Pydantic에 없었습니다.
+
+이것은 실제로 Pydantic의 일부를 업데이트하여 같은 검증 선언 스타일을 지원하도록 하는 데 영감을 주었습니다(이 기능은 이제 Pydantic에 이미 포함되어 있습니다).
+
+///
+
+### [Hug](https://github.com/hugapi/hug) { #hug }
+
+Hug는 Python type hints를 사용해 API 파라미터 타입을 선언하는 기능을 구현한 초기 framework 중 하나였습니다. 이는 다른 도구들도 같은 방식을 하도록 영감을 준 훌륭한 아이디어였습니다.
+
+표준 Python 타입 대신 커스텀 타입을 선언에 사용했지만, 여전히 큰 진전이었습니다.
+
+또한 전체 API를 JSON으로 선언하는 커스텀 schema를 생성한 초기 framework 중 하나였습니다.
+
+OpenAPI나 JSON Schema 같은 표준을 기반으로 하지 않았기 때문에 Swagger UI 같은 다른 도구와 통합하는 것은 직관적이지 않았습니다. 하지만 역시 매우 혁신적인 아이디어였습니다.
+
+흥미롭고 흔치 않은 기능이 하나 있습니다. 같은 framework로 API뿐 아니라 CLI도 만들 수 있습니다.
+
+동기식 Python 웹 framework의 이전 표준(WSGI) 기반이어서 Websockets와 다른 것들을 처리할 수는 없지만, 성능은 여전히 높습니다.
+
+/// info | 정보
+
+Hug는 Timothy Crosley가 만들었습니다. Python 파일에서 import를 자동으로 정렬하는 훌륭한 도구인 [`isort`](https://github.com/timothycrosley/isort)의 제작자이기도 합니다.
+
+///
+
+/// check | **FastAPI**에 영감을 준 아이디어들
+
+Hug는 APIStar의 일부에 영감을 주었고, 저는 APIStar와 함께 Hug를 가장 유망한 도구 중 하나로 보았습니다.
+
+Hug는 Python type hints로 파라미터를 선언하고, API를 정의하는 schema를 자동으로 생성하도록 **FastAPI**에 영감을 주었습니다.
+
+Hug는 헤더와 쿠키를 설정하기 위해 함수에 `response` 파라미터를 선언하도록 **FastAPI**에 영감을 주었습니다.
+
+///
+
+### [APIStar](https://github.com/encode/apistar) (<= 0.5) { #apistar-0-5 }
+
+**FastAPI**를 만들기로 결정하기 직전에 **APIStar** 서버를 발견했습니다. 찾고 있던 거의 모든 것을 갖추고 있었고 설계도 훌륭했습니다.
+
+NestJS와 Molten보다 앞서, Python type hints를 사용해 파라미터와 요청을 선언하는 framework 구현을 제가 처음 본 사례들 중 하나였습니다. Hug와 거의 같은 시기에 발견했습니다. 하지만 APIStar는 OpenAPI 표준을 사용했습니다.
+
+여러 위치에서 동일한 type hints를 기반으로 자동 데이터 검증, 데이터 serialization, OpenAPI schema 생성을 제공했습니다.
+
+Body schema 정의는 Pydantic처럼 동일한 Python type hints를 사용하지는 않았고 Marshmallow와 조금 더 비슷해서 에디터 지원은 그만큼 좋지 않았지만, 그래도 APIStar는 당시 사용할 수 있는 최선의 선택지였습니다.
+
+당시 최고의 성능 benchmark를 가졌습니다(Starlette에 의해서만 추월됨).
+
+처음에는 자동 API 문서화 웹 UI가 없었지만, Swagger UI를 추가할 수 있다는 것을 알고 있었습니다.
+
+의존성 주입 시스템도 있었습니다. 위에서 언급한 다른 도구들처럼 component의 사전 등록이 필요했지만, 여전히 훌륭한 기능이었습니다.
+
+보안 통합이 없어서 전체 프로젝트에서 사용해 볼 수는 없었습니다. 그래서 Flask-apispec 기반 full-stack generator로 갖추고 있던 모든 기능을 대체할 수 없었습니다. 그 기능을 추가하는 pull request를 만드는 것이 제 백로그에 있었습니다.
+
+하지만 이후 프로젝트의 초점이 바뀌었습니다.
+
+더 이상 API web framework가 아니게 되었는데, 제작자가 Starlette에 집중해야 했기 때문입니다.
+
+이제 APIStar는 web framework가 아니라 OpenAPI 사양을 검증하기 위한 도구 모음입니다.
+
+/// info | 정보
+
+APIStar는 Tom Christie가 만들었습니다. 다음을 만든 사람과 동일합니다:
+
+* Django REST Framework
+* Starlette(**FastAPI**의 기반)
+* Uvicorn(Starlette와 **FastAPI**에서 사용)
+
+///
+
+/// check | **FastAPI**에 영감을 준 것
+
+존재하게 만들기.
+
+동일한 Python 타입으로 여러 가지(데이터 검증, serialization, 문서화)를 선언하면서 동시에 뛰어난 에디터 지원을 제공한다는 아이디어는 제가 매우 훌륭하다고 생각했습니다.
+
+그리고 오랫동안 비슷한 framework를 찾아 여러 대안을 테스트한 끝에, APIStar가 그때 이용 가능한 최선의 선택지였습니다.
+
+그 후 APIStar 서버가 더는 존재하지 않게 되고 Starlette가 만들어졌는데, 이는 그런 시스템을 위한 더 새롭고 더 나은 기반이었습니다. 이것이 **FastAPI**를 만들게 된 최종 영감이었습니다.
+
+저는 **FastAPI**를 APIStar의 "정신적 후계자"로 생각합니다. 동시에, 이 모든 이전 도구들에서 배운 것들을 바탕으로 기능, typing 시스템, 그리고 다른 부분들을 개선하고 확장했습니다.
+
+///
+
+## **FastAPI**가 사용하는 것 { #used-by-fastapi }
+
+### [Pydantic](https://docs.pydantic.dev/) { #pydantic }
+
+Pydantic은 Python type hints를 기반으로 데이터 검증, serialization, 문서화(JSON Schema 사용)를 정의하는 라이브러리입니다.
+
+그 덕분에 매우 직관적입니다.
+
+Marshmallow와 비교할 수 있습니다. 다만 benchmark에서 Marshmallow보다 빠릅니다. 그리고 동일한 Python type hints를 기반으로 하므로 에디터 지원도 훌륭합니다.
+
+/// check | **FastAPI**가 이를 사용하는 목적
+
+모든 데이터 검증, 데이터 serialization, 자동 모델 문서화(JSON Schema 기반)를 처리하기.
+
+그 다음 **FastAPI**는 그 JSON Schema 데이터를 가져와 OpenAPI에 포함시키며, 그 외에도 여러 작업을 수행합니다.
+
+///
+
+### [Starlette](https://www.starlette.dev/) { #starlette }
+
+Starlette는 경량 ASGI framework/toolkit으로, 고성능 asyncio 서비스를 만들기에 이상적입니다.
+
+매우 단순하고 직관적입니다. 쉽게 확장할 수 있도록 설계되었고, 모듈식 component를 갖습니다.
+
+다음이 포함됩니다:
+
+* 정말 인상적인 성능.
+* WebSocket 지원.
+* 프로세스 내 백그라운드 작업.
+* 시작 및 종료 이벤트.
+* HTTPX 기반의 테스트 클라이언트.
+* CORS, GZip, Static Files, Streaming responses.
+* 세션 및 쿠키 지원.
+* 100% 테스트 커버리지.
+* 100% 타입 주석이 달린 코드베이스.
+* 소수의 필수 의존성.
+
+Starlette는 현재 테스트된 Python framework 중 가장 빠릅니다. 단, framework가 아니라 서버인 Uvicorn이 더 빠릅니다.
+
+Starlette는 웹 microframework의 기본 기능을 모두 제공합니다.
+
+하지만 자동 데이터 검증, serialization, 문서화는 제공하지 않습니다.
+
+그것이 **FastAPI**가 위에 추가하는 핵심 중 하나이며, 모두 Python type hints(Pydantic 사용)를 기반으로 합니다. 여기에 더해 의존성 주입 시스템, 보안 유틸리티, OpenAPI schema 생성 등도 포함됩니다.
+
+/// note | 기술 세부사항
+
+ASGI는 Django 코어 팀 멤버들이 개발 중인 새로운 "표준"입니다. 아직 "Python 표준"(PEP)은 아니지만, 그 방향으로 진행 중입니다.
+
+그럼에도 이미 여러 도구에서 "표준"으로 사용되고 있습니다. 이는 상호운용성을 크게 개선합니다. 예를 들어 Uvicorn을 다른 ASGI 서버(예: Daphne 또는 Hypercorn)로 교체할 수도 있고, `python-socketio` 같은 ASGI 호환 도구를 추가할 수도 있습니다.
+
+///
+
+/// check | **FastAPI**가 이를 사용하는 목적
+
+핵심 웹 부분을 모두 처리하기. 그 위에 기능을 추가하기.
+
+`FastAPI` 클래스 자체는 `Starlette` 클래스를 직접 상속합니다.
+
+따라서 Starlette로 할 수 있는 모든 것은 기본적으로 **FastAPI**로도 직접 할 수 있습니다. 즉, **FastAPI**는 사실상 Starlette에 강력한 기능을 더한 것입니다.
+
+///
+
+### [Uvicorn](https://www.uvicorn.dev/) { #uvicorn }
+
+Uvicorn은 uvloop과 httptools로 구축된 초고속 ASGI 서버입니다.
+
+web framework가 아니라 서버입니다. 예를 들어 경로 기반 routing을 위한 도구는 제공하지 않습니다. 그런 것은 Starlette(또는 **FastAPI**) 같은 framework가 위에서 제공합니다.
+
+Starlette와 **FastAPI**에서 권장하는 서버입니다.
+
+/// check | **FastAPI**가 이를 권장하는 방식
+
+**FastAPI** 애플리케이션을 실행하기 위한 주요 웹 서버.
+
+또한 `--workers` 커맨드라인 옵션을 사용하면 비동기 멀티프로세스 서버로 실행할 수도 있습니다.
+
+자세한 내용은 [배포](deployment/index.md) 섹션을 확인하세요.
+
+///
+
+## 벤치마크와 속도 { #benchmarks-and-speed }
+
+Uvicorn, Starlette, FastAPI 사이의 차이를 이해하고 비교하려면 [벤치마크](benchmarks.md) 섹션을 확인하세요.
diff --git a/docs/ko/docs/async.md b/docs/ko/docs/async.md
index 47dbaa1b01885..485111fac965f 100644
--- a/docs/ko/docs/async.md
+++ b/docs/ko/docs/async.md
@@ -1,18 +1,18 @@
-# 동시성과 async / await
+# 동시성과 async / await { #concurrency-and-async-await }
-*경로 작동 함수*에서의 `async def` 문법에 대한 세부사항과 비동기 코드, 동시성 및 병렬성에 대한 배경
+*경로 처리 함수*에서의 `async def` 문법에 대한 세부사항과 비동기 코드, 동시성 및 병렬성에 대한 배경
-## 바쁘신 경우
+## 바쁘신가요? { #in-a-hurry }
-요약
+TL;DR:
-다음과 같이 `await`를 사용해 호출하는 제3의 라이브러리를 사용하는 경우:
+다음과 같이 `await`를 사용해 호출하라고 안내하는 제3자 라이브러리를 사용하는 경우:
```Python
results = await some_library()
```
-다음처럼 *경로 작동 함수*를 `async def`를 사용해 선언하십시오:
+다음처럼 *경로 처리 함수*를 `async def`를 사용해 선언하십시오:
```Python hl_lines="2"
@app.get('/')
@@ -21,12 +21,15 @@ async def read_results():
return results
```
-!!! note "참고"
- `async def`로 생성된 함수 내부에서만 `await`를 사용할 수 있습니다.
+/// note | 참고
+
+`async def`로 생성된 함수 내부에서만 `await`를 사용할 수 있습니다.
+
+///
---
-데이터베이스, API, 파일시스템 등과 의사소통하는 제3의 라이브러리를 사용하고, 그것이 `await`를 지원하지 않는 경우(현재 거의 모든 데이터베이스 라이브러리가 그러합니다), *경로 작동 함수*를 일반적인 `def`를 사용해 선언하십시오:
+데이터베이스, API, 파일시스템 등과 의사소통하는 제3자 라이브러리를 사용하고, 그것이 `await` 사용을 지원하지 않는 경우(현재 대부분의 데이터베이스 라이브러리가 그러합니다), *경로 처리 함수*를 일반적인 `def`를 사용해 선언하십시오:
```Python hl_lines="2"
@app.get('/')
@@ -37,23 +40,23 @@ def results():
---
-만약 당신의 응용프로그램이 (어째서인지) 다른 무엇과 의사소통하고 그것이 응답하기를 기다릴 필요가 없다면 `async def`를 사용하십시오.
+만약 여러분의 애플리케이션이 (어째서인지) 다른 어떤 것과도 통신하고 그 응답을 기다릴 필요가 없다면, 내부에서 `await`를 사용할 필요가 없더라도 `async def`를 사용하세요.
---
-모르겠다면, 그냥 `def`를 사용하십시오.
+잘 모르겠다면, 일반적인 `def`를 사용하세요.
---
-**참고**: *경로 작동 함수*에서 필요한만큼 `def`와 `async def`를 혼용할 수 있고, 가장 알맞은 것을 선택해서 정의할 수 있습니다. FastAPI가 자체적으로 알맞은 작업을 수행할 것입니다.
+**참고**: *경로 처리 함수*에서 필요한 만큼 `def`와 `async def`를 혼용할 수 있으며, 각각에 대해 가장 알맞은 옵션을 선택해 정의하면 됩니다. FastAPI가 올바르게 처리합니다.
-어찌되었든, 상기 어떠한 경우라도, FastAPI는 여전히 비동기적으로 작동하고 매우 빠릅니다.
+어쨌든 위의 어떤 경우에서도 FastAPI는 여전히 비동기적으로 동작하며 매우 빠릅니다.
-그러나 상기 작업을 수행함으로써 어느 정도의 성능 최적화가 가능합니다.
+하지만 위의 단계를 따르면, 몇 가지 성능 최적화를 할 수 있습니다.
-## 기술적 세부사항
+## 기술적 세부사항 { #technical-details }
-최신 파이썬 버전은 `async`와 `await` 문법과 함께 **“코루틴”**이라고 하는 것을 사용하는 **“비동기 코드”**를 지원합니다.
+최신 파이썬 버전은 **“코루틴”**이라고 하는 것을 사용하는 **“비동기 코드”**를 **`async` 및 `await`** 문법과 함께 지원합니다.
아래 섹션들에서 해당 문장을 부분별로 살펴보겠습니다:
@@ -61,251 +64,283 @@ def results():
* **`async`와 `await`**
* **코루틴**
-## 비동기 코드
+## 비동기 코드 { #asynchronous-code }
-비동기 코드란 언어 💬 가 코드의 어느 한 부분에서, 컴퓨터 / 프로그램🤖에게 *다른 무언가*가 어딘가에서 끝날 때까지 기다려야한다고 말하는 방식입니다. *다른 무언가*가 “느린-파일" 📝 이라고 불린다고 가정해봅시다.
+비동기 코드는 언어 💬 가 코드의 어느 한 부분에서 컴퓨터/프로그램 🤖 에게, 어느 시점에는 어딘가에서 *다른 무언가*가 끝날 때까지 기다려야 한다고 말할 수 있는 방법이 있다는 의미입니다. 그 *다른 무언가*를 "slow-file" 📝 이라고 해보겠습니다.
-따라서 “느린-파일” 📝이 끝날때까지 컴퓨터는 다른 작업을 수행할 수 있습니다.
+따라서 그 시간 동안 컴퓨터는 "slow-file" 📝 이 끝나는 동안 다른 작업을 하러 갈 수 있습니다.
-그 다음 컴퓨터 / 프로그램 🤖 은 다시 기다리고 있기 때문에 기회가 있을 때마다 다시 돌아오거나, 혹은 당시에 수행해야하는 작업들이 완료될 때마다 다시 돌아옵니다. 그리고 그것 🤖 은 기다리고 있던 작업 중 어느 것이 이미 완료되었는지, 그것 🤖 이 해야하는 모든 작업을 수행하면서 확인합니다.
+그 다음 컴퓨터/프로그램 🤖 은 다시 기다리는 중이기 때문에 기회가 있을 때마다 돌아오거나, 혹은 그 시점에 해야 할 작업을 모두 끝낼 때마다 돌아옵니다. 그리고 기다리던 작업 중 이미 끝난 것이 있는지 확인하면서, 해야 했던 작업을 수행합니다.
-다음으로, 그것 🤖 은 완료할 첫번째 작업에 착수하고(우리의 "느린-파일" 📝 이라고 가정합시다) 그에 대해 수행해야하는 작업을 계속합니다.
+다음으로, 완료된 첫 번째 작업(우리의 "slow-file" 📝 이라고 해보겠습니다)을 가져와서, 그에 대해 해야 했던 작업을 계속합니다.
-"다른 무언가를 기다리는 것"은 일반적으로 비교적 "느린" (프로세서와 RAM 메모리 속도에 비해) I/O 작업을 의미합니다. 예를 들면 다음의 것들을 기다리는 것입니다:
+이 "다른 무언가를 기다리는 것"은 일반적으로 프로세서와 RAM 메모리 속도에 비해 상대적으로 "느린" I/O 작업을 의미합니다. 예를 들어 다음을 기다리는 것입니다:
-* 네트워크를 통해 클라이언트로부터 전송되는 데이터
-* 네트워크를 통해 클라이언트가 수신할, 당신의 프로그램으로부터 전송되는 데이터
-* 시스템이 읽고 프로그램에 전달할 디스크 내의 파일 내용
-* 당신의 프로그램이 시스템에 전달하는, 디스크에 작성될 내용
+* 네트워크를 통해 클라이언트가 데이터를 보내는 것
+* 네트워크를 통해 클라이언트가 여러분의 프로그램이 보낸 데이터를 받는 것
+* 시스템이 디스크의 파일 내용을 읽어서 프로그램에 전달하는 것
+* 프로그램이 시스템에 전달한 내용을 디스크에 쓰는 것
* 원격 API 작업
-* 완료될 데이터베이스 작업
-* 결과를 반환하는 데이터베이스 쿼리
-* 기타
+* 데이터베이스 작업이 완료되는 것
+* 데이터베이스 쿼리가 결과를 반환하는 것
+* 기타 등등
-수행 시간의 대부분이 I/O 작업을 기다리는데에 소요되기 때문에, "I/O에 묶인" 작업이라고 불립니다.
+실행 시간의 대부분이 I/O 작업을 기다리는 데 소비되기 때문에, 이를 "I/O bound" 작업이라고 부릅니다.
-이것은 "비동기"라고 불리는데 컴퓨터 / 프로그램이 작업 결과를 가지고 일을 수행할 수 있도록, 느린 작업에 "동기화"되어 아무것도 하지 않으면서 작업이 완료될 정확한 시점만을 기다릴 필요가 없기 때문입니다.
+이것은 컴퓨터/프로그램이 느린 작업과 "동기화"되어, 아무것도 하지 않은 채 그 작업이 끝나는 정확한 시점만 기다렸다가 결과를 가져와 일을 계속할 필요가 없기 때문에 "비동기"라고 불립니다.
-이 대신에, "비동기" 시스템에서는, 작업은 일단 완료되면, 컴퓨터 / 프로그램이 수행하고 있는 일을 완료하고 이후 다시 돌아와서 그것의 결과를 받아 이를 사용해 작업을 지속할 때까지 잠시 (몇 마이크로초) 대기할 수 있습니다.
+대신 "비동기" 시스템에서는, 작업이 끝나면 컴퓨터/프로그램이 하러 갔던 일을 마칠 때까지 잠시(몇 마이크로초) 줄에서 기다렸다가, 다시 돌아와 결과를 받아 이를 사용해 작업을 계속할 수 있습니다.
-"동기"("비동기"의 반대)는 컴퓨터 / 프로그램이 상이한 작업들간 전환을 하기 전에 그것이 대기를 동반하게 될지라도 모든 순서를 따르기 때문에 "순차"라는 용어로도 흔히 불립니다.
+"동기"(“비동기”의 반대)는 보통 "순차"라는 용어로도 불리는데, 컴퓨터/프로그램이 다른 작업으로 전환하기 전에 모든 단계를 순서대로 따르기 때문이며, 그 단계들에 기다림이 포함되어 있더라도 마찬가지입니다.
-### 동시성과 버거
+### 동시성과 햄버거 { #concurrency-and-burgers }
-위에서 설명한 **비동기** 코드에 대한 개념은 종종 **"동시성"**이라고도 불립니다. 이것은 **"병렬성"**과는 다릅니다.
+위에서 설명한 **비동기** 코드에 대한 개념은 때때로 **"동시성"**이라고도 불립니다. 이는 **"병렬성"**과는 다릅니다.
-**동시성**과 **병렬성**은 모두 "동시에 일어나는 서로 다른 일들"과 관련이 있습니다.
+**동시성**과 **병렬성**은 모두 "대략 같은 시간에 일어나는 서로 다른 일들"과 관련이 있습니다.
하지만 *동시성*과 *병렬성*의 세부적인 개념에는 꽤 차이가 있습니다.
-차이를 확인하기 위해, 다음의 버거에 대한 이야기를 상상해보십시오:
+차이를 보기 위해, 다음의 햄버거 이야기를 상상해보세요:
+
+### 동시 햄버거 { #concurrent-burgers }
+
+여러분은 짝사랑 상대와 패스트푸드를 먹으러 갔고, 점원이 여러분 앞 사람들의 주문을 받는 동안 줄을 서서 기다립니다. 😍
+
+
+
+이제 여러분 차례가 되어, 여러분과 짝사랑 상대를 위해 매우 고급스러운 햄버거 2개를 주문합니다. 🍔🍔
+
+
+
+점원은 주방의 요리사에게 무언가를 말해, (지금은 앞선 손님들의 주문을 준비하고 있더라도) 여러분의 햄버거를 준비해야 한다는 것을 알게 합니다.
+
+
+
+여러분이 돈을 냅니다. 💸
+
+점원은 여러분 차례 번호를 줍니다.
+
+
-### 동시 버거
+기다리는 동안, 여러분은 짝사랑 상대와 함께 자리를 고르고 앉아 오랫동안 대화를 나눕니다(여러분의 햄버거는 매우 고급스럽기 때문에 준비하는 데 시간이 좀 걸립니다).
-당신은 짝사랑 상대 😍 와 패스트푸드 🍔 를 먹으러 갔습니다. 당신은 점원 💁 이 당신 앞에 있는 사람들의 주문을 받을 동안 줄을 서서 기다리고 있습니다.
+짝사랑 상대와 테이블에 앉아 햄버거를 기다리는 동안, 그 사람이 얼마나 멋지고 귀엽고 똑똑한지 감탄하며 시간을 보낼 수 있습니다 ✨😍✨.
-이제 당신의 순서가 되어서, 당신은 당신과 짝사랑 상대 😍 를 위한 두 개의 고급스러운 버거 🍔 를 주문합니다.
+
-당신이 돈을 냅니다 💸.
+기다리며 대화하는 동안, 때때로 여러분은 카운터에 표시되는 번호를 확인해 여러분 차례인지 봅니다.
-점원 💁 은 주방 👨🍳 에 요리를 하라고 전달하고, 따라서 그들은 당신의 버거 🍔 를 준비해야한다는 사실을 알게됩니다(그들이 지금은 당신 앞 고객들의 주문을 준비하고 있을지라도 말입니다).
+그러다 어느 순간 마침내 여러분 차례가 됩니다. 여러분은 카운터에 가서 햄버거를 받고, 테이블로 돌아옵니다.
-점원 💁 은 당신의 순서가 적힌 번호표를 줍니다.
+
-기다리는 동안, 당신은 짝사랑 상대 😍 와 함께 테이블을 고르고, 자리에 앉아 오랫동안 (당신이 주문한 버거는 꽤나 고급스럽기 때문에 준비하는데 시간이 조금 걸립니다 ✨🍔✨) 대화를 나눕니다.
+여러분과 짝사랑 상대는 햄버거를 먹으며 좋은 시간을 보냅니다. ✨
-짝사랑 상대 😍 와 테이블에 앉아서 버거 🍔 를 기다리는 동안, 그 사람 😍 이 얼마나 멋지고, 사랑스럽고, 똑똑한지 감탄하며 시간을 보냅니다 ✨😍✨.
+
-짝사랑 상대 😍 와 기다리면서 얘기하는 동안, 때때로, 당신은 당신의 차례가 되었는지 보기 위해 카운터의 번호를 확인합니다.
+/// info | 정보
-그러다 어느 순간, 당신의 차례가 됩니다. 카운터에 가서, 버거 🍔 를 받고, 테이블로 다시 돌아옵니다.
+아름다운 일러스트: [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨
-당신과 짝사랑 상대 😍 는 버거 🍔 를 먹으며 좋은 시간을 보냅니다 ✨.
+///
---
-당신이 이 이야기에서 컴퓨터 / 프로그램 🤖 이라고 상상해보십시오.
+이 이야기에서 여러분이 컴퓨터/프로그램 🤖 이라고 상상해보세요.
-줄을 서서 기다리는 동안, 당신은 아무것도 하지 않고 😴 당신의 차례를 기다리며, 어떠한 "생산적인" 일도 하지 않습니다. 하지만 점원 💁 이 (음식을 준비하지는 않고) 주문을 받기만 하기 때문에 줄이 빨리 줄어들어서 괜찮습니다.
+줄을 서 있는 동안, 여러분은 그냥 쉬고 😴, 차례를 기다리며, 그다지 "생산적인" 일을 하지 않습니다. 하지만 점원은 주문만 받지(음식을 준비하진 않기) 때문에 줄이 빠르게 줄어들어 괜찮습니다.
-그다음, 당신이 차례가 오면, 당신은 실제로 "생산적인" 일 🤓 을 합니다. 당신은 메뉴를 보고, 무엇을 먹을지 결정하고, 짝사랑 상대 😍 의 선택을 묻고, 돈을 내고 💸 , 맞는 카드를 냈는지 확인하고, 비용이 제대로 지불되었는지 확인하고, 주문이 제대로 들어갔는지 확인을 하는 작업 등등을 수행합니다.
+그 다음 여러분 차례가 되면, 여러분은 실제로 "생산적인" 일을 합니다. 메뉴를 처리하고, 무엇을 먹을지 결정하고, 짝사랑 상대의 선택을 확인하고, 결제하고, 올바른 현금이나 카드를 냈는지 확인하고, 정확히 청구되었는지 확인하고, 주문에 올바른 항목들이 들어갔는지 확인하는 등등을 합니다.
-하지만 이후에는, 버거 🍔 를 아직 받지 못했음에도, 버거가 준비될 때까지 기다려야 🕙 하기 때문에 점원 💁 과의 작업은 "일시정지" ⏸ 상태입니다.
+하지만 그 다음에는, 아직 햄버거를 받지 못했더라도, 햄버거가 준비될 때까지 기다려야 🕙 하므로 점원과의 작업은 "일시정지" ⏸ 상태입니다.
-하지만 번호표를 받고 카운터에서 나와 테이블에 앉으면, 당신은 짝사랑 상대 😍 와 그 "작업" ⏯ 🤓 에 번갈아가며 🔀 집중합니다. 그러면 당신은 다시 짝사랑 상대 😍 에게 작업을 거는 매우 "생산적인" 일 🤓 을 합니다.
+하지만 번호를 들고 카운터에서 벗어나 테이블에 앉으면, 여러분은 짝사랑 상대에게 관심을 전환 🔀 하고, 그에 대한 "작업" ⏯ 🤓 을 할 수 있습니다. 그러면 여러분은 다시 짝사랑 상대에게 작업을 거는 매우 "생산적인" 일을 하게 됩니다 😍.
-점원 💁 이 카운터 화면에 당신의 번호를 표시함으로써 "버거 🍔 가 준비되었습니다"라고 해도, 당신은 즉시 뛰쳐나가지는 않을 것입니다. 당신은 당신의 번호를 갖고있고, 다른 사람들은 그들의 번호를 갖고있기 때문에, 아무도 당신의 버거 🍔 를 훔쳐가지 않는다는 사실을 알기 때문입니다.
+그 다음 점원 💁 이 카운터 화면에 여러분 번호를 띄워 "햄버거를 만들었어요"라고 말하지만, 표시된 번호가 여러분 차례로 바뀌었다고 해서 즉시 미친 듯이 뛰어가지는 않습니다. 여러분은 여러분 번호를 갖고 있고, 다른 사람들은 그들의 번호를 갖고 있으니, 아무도 여러분 햄버거를 훔쳐갈 수 없다는 것을 알기 때문입니다.
-그래서 당신은 짝사랑 상대 😍 가 이야기를 끝낼 때까지 기다린 후 (현재 작업 완료 ⏯ / 진행 중인 작업 처리 🤓 ), 정중하게 미소짓고 버거를 가지러 가겠다고 말합니다 ⏸.
+그래서 여러분은 짝사랑 상대가 이야기를 끝낼 때까지 기다린 다음(현재 작업 ⏯ / 처리 중인 작업 🤓 을 끝내고), 부드럽게 미소 지으며 햄버거를 가지러 가겠다고 말합니다 ⏸.
-그다음 당신은 카운터에 가서 🔀 , 초기 작업을 이제 완료하고 ⏯ , 버거 🍔 를 받고, 감사하다고 말하고 테이블로 가져옵니다. 이로써 카운터와의 상호작용 단계 / 작업이 종료됩니다 ⏹.
+그 다음 여러분은 카운터로 가서 🔀, 이제 끝난 초기 작업 ⏯ 으로 돌아와 햄버거를 받고, 감사 인사를 하고, 테이블로 가져옵니다. 이로써 카운터와 상호작용하는 그 단계/작업이 끝납니다 ⏹. 그리고 이는 새로운 작업인 "햄버거 먹기" 🔀 ⏯ 를 만들지만, 이전 작업인 "햄버거 받기"는 끝났습니다 ⏹.
-이전 작업인 "버거 받기"가 종료되면 ⏹ "버거 먹기"라는 새로운 작업이 생성됩니다 🔀 ⏯.
+### 병렬 햄버거 { #parallel-burgers }
-### 병렬 버거
+이제 이것이 "동시 햄버거"가 아니라 "병렬 햄버거"라고 상상해봅시다.
-이제 "동시 버거"가 아닌 "병렬 버거"를 상상해보십시오.
+여러분은 짝사랑 상대와 함께 병렬 패스트푸드를 먹으러 갑니다.
-당신은 짝사랑 상대 😍 와 함께 병렬 패스트푸드 🍔 를 먹으러 갔습니다.
+여러분은 여러 명(예: 8명)의 점원이 동시에 요리사이기도 하여 여러분 앞 사람들의 주문을 받는 동안 줄을 서 있습니다.
-당신은 여러명(8명이라고 가정합니다)의 점원이 당신 앞 사람들의 주문을 받으며 동시에 요리 👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳 도 하는 동안 줄을 서서 기다립니다.
+여러분 앞의 모든 사람들은, 8명의 점원 각각이 다음 주문을 받기 전에 바로 햄버거를 준비하러 가기 때문에, 카운터를 떠나지 않고 햄버거가 준비될 때까지 기다립니다.
-당신 앞 모든 사람들이 버거가 준비될 때까지 카운터에서 떠나지 않고 기다립니다 🕙 . 왜냐하면 8명의 직원들이 다음 주문을 받기 전에 버거를 준비하러 가기 때문입니다.
+
-마침내 당신의 차례가 왔고, 당신은 당신과 짝사랑 상대 😍 를 위한 두 개의 고급스러운 버거 🍔 를 주문합니다.
+마침내 여러분 차례가 되어, 여러분과 짝사랑 상대를 위해 매우 고급스러운 햄버거 2개를 주문합니다.
-당신이 비용을 지불합니다 💸 .
+여러분이 돈을 냅니다 💸.
-점원이 주방에 갑니다 👨🍳 .
+
-당신은 번호표가 없기 때문에 누구도 당신의 버거 🍔 를 대신 가져갈 수 없도록 카운터에 서서 기다립니다 🕙 .
+점원은 주방으로 갑니다.
-당신과 짝사랑 상대 😍 는 다른 사람이 새치기해서 버거를 가져가지 못하게 하느라 바쁘기 때문에 🕙 , 짝사랑 상대에게 주의를 기울일 수 없습니다 😞 .
+여러분은 번호표가 없으므로, 다른 사람이 여러분보다 먼저 햄버거를 가져가지 못하도록 카운터 앞에 서서 기다립니다 🕙.
-이것은 "동기" 작업이고, 당신은 점원/요리사 👨🍳 와 "동기화" 되었습니다. 당신은 기다리고 🕙 , 점원/요리사 👨🍳 가 버거 🍔 준비를 완료한 후 당신에게 주거나, 누군가가 그것을 가져가는 그 순간에 그 곳에 있어야합니다.
+
-카운터 앞에서 오랫동안 기다린 후에 🕙 , 점원/요리사 👨🍳 가 당신의 버거 🍔 를 가지고 돌아옵니다.
+여러분과 짝사랑 상대는 햄버거가 나오면 다른 사람이 끼어들어 가져가지 못하게 하느라 바쁘기 때문에, 짝사랑 상대에게 집중할 수 없습니다. 😞
-당신은 버거를 받고 짝사랑 상대와 함께 테이블로 돌아옵니다.
+이것은 "동기" 작업이며, 여러분은 점원/요리사 👨🍳 와 "동기화"되어 있습니다. 점원/요리사 👨🍳 가 햄버거를 완성해 여러분에게 주는 정확한 순간에 그 자리에 있어야 하므로, 여러분은 기다려야 🕙 하고, 그렇지 않으면 다른 사람이 가져갈 수도 있습니다.
-단지 먹기만 하다가, 다 먹었습니다 🍔 ⏹.
+
-카운터 앞에서 기다리면서 🕙 너무 많은 시간을 허비했기 때문에 대화를 하거나 작업을 걸 시간이 거의 없었습니다 😞 .
+그러다 점원/요리사 👨🍳 가 카운터 앞에서 오랫동안 기다린 🕙 끝에 마침내 햄버거를 가지고 돌아옵니다.
----
+
+
+여러분은 햄버거를 받아 짝사랑 상대와 테이블로 갑니다.
+
+그냥 먹고, 끝입니다. ⏹
-이 병렬 버거 시나리오에서, 당신은 기다리고 🕙 , 오랜 시간동안 "카운터에서 기다리는" 🕙 데에 주의를 기울이는 ⏯ 두 개의 프로세서(당신과 짝사랑 상대😍)를 가진 컴퓨터 / 프로그램 🤖 입니다.
+
-패스트푸드점에는 8개의 프로세서(점원/요리사) 👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳 가 있습니다. 동시 버거는 단 두 개(한 명의 직원과 한 명의 요리사) 💁 👨🍳 만을 가지고 있었습니다.
+대부분의 시간을 카운터 앞에서 기다리는 데 🕙 썼기 때문에, 대화하거나 작업을 걸 시간은 많지 않았습니다. 😞
-하지만 여전히, 병렬 버거 예시가 최선은 아닙니다 😞 .
+/// info | 정보
+
+아름다운 일러스트: [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨
+
+///
---
-이 예시는 버거🍔 이야기와 결이 같습니다.
+이 병렬 햄버거 시나리오에서, 여러분은 두 개의 프로세서(여러분과 짝사랑 상대)를 가진 컴퓨터/프로그램 🤖 이며, 둘 다 기다리고 🕙 오랫동안 "카운터에서 기다리기" 🕙 에 주의를 ⏯ 기울입니다.
-더 "현실적인" 예시로, 은행을 상상해보십시오.
+패스트푸드점에는 8개의 프로세서(점원/요리사)가 있습니다. 동시 햄버거 가게는 2개(점원 1명, 요리사 1명)만 있었을 것입니다.
-최근까지, 대다수의 은행에는 다수의 은행원들 👨💼👨💼👨💼👨💼 과 긴 줄 🕙🕙🕙🕙🕙🕙🕙🕙 이 있습니다.
+하지만 여전히 최종 경험은 그다지 좋지 않습니다. 😞
-모든 은행원들은 한 명 한 명의 고객들을 차례로 상대합니다 👨💼⏯ .
+---
-그리고 당신은 오랫동안 줄에서 기다려야하고 🕙 , 그렇지 않으면 당신의 차례를 잃게 됩니다.
+이것이 햄버거의 병렬 버전에 해당하는 이야기입니다. 🍔
-아마 당신은 은행 🏦 심부름에 짝사랑 상대 😍 를 데려가고 싶지는 않을 것입니다.
+좀 더 "현실적인" 예시로, 은행을 상상해보세요.
-### 버거 예시의 결론
+최근까지 대부분의 은행에는 여러 은행원 👨💼👨💼👨💼👨💼 과 긴 줄 🕙🕙🕙🕙🕙🕙🕙🕙 이 있었습니다.
-"짝사랑 상대와의 패스트푸드점 버거" 시나리오에서, 오랜 기다림 🕙 이 있기 때문에 동시 시스템 ⏸🔀⏯ 을 사용하는 것이 더 합리적입니다.
+모든 은행원이 한 고객씩 순서대로 모든 일을 처리합니다 👨💼⏯.
-대다수의 웹 응용프로그램의 경우가 그러합니다.
+그리고 여러분은 오랫동안 줄에서 기다려야 🕙 하며, 그렇지 않으면 차례를 잃습니다.
-매우 많은 수의 유저가 있지만, 서버는 그들의 요청을 전송하기 위해 그닥-좋지-않은 연결을 기다려야 합니다 🕙 .
+아마 은행 🏦 업무를 보러 갈 때 짝사랑 상대 😍 를 데려가고 싶지는 않을 것입니다.
-그리고 응답이 돌아올 때까지 다시 기다려야 합니다 🕙 .
+### 햄버거 예시의 결론 { #burger-conclusion }
-이 "기다림" 🕙 은 마이크로초 단위이지만, 모두 더해지면, 결국에는 매우 긴 대기시간이 됩니다.
+"짝사랑 상대와의 패스트푸드점 햄버거" 시나리오에서는 기다림 🕙 이 많기 때문에, 동시 시스템 ⏸🔀⏯ 을 사용하는 것이 훨씬 더 합리적입니다.
-따라서 웹 API를 위해 비동기 ⏸🔀⏯ 코드를 사용하는 것이 합리적입니다.
+대부분의 웹 애플리케이션이 그렇습니다.
-대부분의 존재하는 유명한 파이썬 프레임워크 (Flask와 Django 등)은 새로운 비동기 기능들이 파이썬에 존재하기 전에 만들어졌습니다. 그래서, 그들의 배포 방식은 병렬 실행과 새로운 기능만큼 강력하지는 않은 예전 버전의 비동기 실행을 지원합니다.
+매우 많은 사용자들이 있고, 서버는 그들의 좋지 않은 연결을 통해 요청이 전송되기를 기다립니다 🕙.
-비동기 웹 파이썬(ASGI)에 대한 주요 명세가 웹소켓을 지원하기 위해 Django에서 개발 되었음에도 그렇습니다.
+그리고 응답이 돌아오기를 다시 기다립니다 🕙.
-이러한 종류의 비동기성은 (NodeJS는 병렬적이지 않음에도) NodeJS가 사랑받는 이유이고, 프로그래밍 언어로서의 Go의 강점입니다.
+이 "기다림" 🕙 은 마이크로초 단위로 측정되지만, 모두 합치면 결국 꽤 많은 대기 시간이 됩니다.
-그리고 **FastAPI**를 사용함으로써 동일한 성능을 낼 수 있습니다.
+그래서 웹 API에는 비동기 ⏸🔀⏯ 코드를 사용하는 것이 매우 합리적입니다.
-또한 병렬성과 비동기성을 동시에 사용할 수 있기 때문에, 대부분의 테스트가 완료된 NodeJS 프레임워크보다 더 높은 성능을 얻고 C에 더 가까운 컴파일 언어인 Go와 동등한 성능을 얻을 수 있습니다(모두 Starlette 덕분입니다).
+이러한 종류의 비동기성은 NodeJS가 인기 있는 이유(비록 NodeJS가 병렬은 아니지만)이자, 프로그래밍 언어로서 Go의 강점입니다.
-### 동시성이 병렬성보다 더 나은가?
+그리고 이것이 **FastAPI**로 얻는 것과 같은 수준의 성능입니다.
-그렇지 않습니다! 그것이 이야기의 교훈은 아닙니다.
+또한 병렬성과 비동기성을 동시에 사용할 수 있으므로, 대부분의 테스트된 NodeJS 프레임워크보다 더 높은 성능을 얻고, C에 더 가까운 컴파일 언어인 Go와 동등한 성능을 얻을 수 있습니다 [(모두 Starlette 덕분입니다)](https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=query&l=zijmkf-1).
-동시성은 병렬성과 다릅니다. 그리고 그것은 많은 대기를 필요로하는 **특정한** 시나리오에서는 더 낫습니다. 이로 인해, 웹 응용프로그램 개발에서 동시성이 병렬성보다 일반적으로 훨씬 낫습니다. 하지만 모든 경우에 그런 것은 아닙니다.
+### 동시성이 병렬성보다 더 나은가요? { #is-concurrency-better-than-parallelism }
-따라서, 균형을 맞추기 위해, 다음의 짧은 이야기를 상상해보십시오:
+아니요! 그게 이 이야기의 교훈은 아닙니다.
-> 당신은 크고, 더러운 집을 청소해야합니다.
+동시성은 병렬성과 다릅니다. 그리고 많은 기다림이 포함되는 **특정한** 시나리오에서는 더 낫습니다. 그 때문에 웹 애플리케이션 개발에서는 일반적으로 병렬성보다 훨씬 더 낫습니다. 하지만 모든 것에 해당하진 않습니다.
+
+그래서 균형을 맞추기 위해, 다음의 짧은 이야기를 상상해보세요:
+
+> 여러분은 크고 더러운 집을 청소해야 합니다.
*네, 이게 전부입니다*.
---
-어디에도 대기 🕙 는 없고, 집안 곳곳에서 해야하는 많은 작업들만 있습니다.
+어디에도 기다림 🕙 은 없고, 집의 여러 장소에서 해야 할 일이 많을 뿐입니다.
-버거 예시처럼 처음에는 거실, 그 다음은 부엌과 같은 식으로 순서를 정할 수도 있으나, 무엇도 기다리지 🕙 않고 계속해서 청소 작업만 수행하기 때문에, 순서는 아무런 영향을 미치지 않습니다.
+햄버거 예시처럼 거실부터, 그 다음은 부엌처럼 순서를 정할 수도 있지만, 어떤 것도 기다리지 🕙 않고 계속 청소만 하기 때문에, 순서는 아무런 영향을 주지 않습니다.
-순서가 있든 없든 동일한 시간이 소요될 것이고(동시성) 동일한 양의 작업을 하게 될 것입니다.
+순서가 있든 없든(동시성) 끝내는 데 걸리는 시간은 같고, 같은 양의 일을 하게 됩니다.
-하지만 이 경우에서, 8명의 전(前)-점원/요리사이면서-현(現)-청소부 👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳 를 고용할 수 있고, 그들 각자(그리고 당신)가 집의 한 부분씩 맡아 청소를 한다면, 당신은 **병렬적**으로 작업을 수행할 수 있고, 조금의 도움이 있다면, 훨씬 더 빨리 끝낼 수 있습니다.
+하지만 이 경우, 전(前) 점원/요리사이자 현(現) 청소부가 된 8명을 데려올 수 있고, 각자(그리고 여러분)가 집의 구역을 하나씩 맡아 청소한다면, 추가 도움과 함께 모든 일을 **병렬**로 수행하여 훨씬 더 빨리 끝낼 수 있습니다.
-이 시나리오에서, (당신을 포함한) 각각의 청소부들은 프로세서가 될 것이고, 각자의 역할을 수행합니다.
+이 시나리오에서 (여러분을 포함한) 각 청소부는 프로세서가 되어, 맡은 일을 수행합니다.
-실행 시간의 대부분이 대기가 아닌 실제 작업에 소요되고, 컴퓨터에서 작업은 CPU에서 이루어지므로, 이러한 문제를 "CPU에 묶였"다고 합니다.
+그리고 실행 시간의 대부분이 기다림이 아니라 실제 작업에 쓰이고, 컴퓨터에서 작업은 CPU가 수행하므로, 이런 문제를 "CPU bound"라고 부릅니다.
---
-CPU에 묶인 연산에 관한 흔한 예시는 복잡한 수학 처리를 필요로 하는 경우입니다.
+CPU bound 작업의 흔한 예시는 복잡한 수학 처리가 필요한 것들입니다.
예를 들어:
-* **오디오** 또는 **이미지** 처리.
-* **컴퓨터 비전**: 하나의 이미지는 수백개의 픽셀로 구성되어있고, 각 픽셀은 3개의 값 / 색을 갖고 있으며, 일반적으로 해당 픽셀들에 대해 동시에 무언가를 계산해야하는 처리.
-* **머신러닝**: 일반적으로 많은 "행렬"과 "벡터" 곱셈이 필요합니다. 거대한 스프레드 시트에 수들이 있고 그 수들을 동시에 곱해야 한다고 생각해보십시오.
-* **딥러닝**: 머신러닝의 하위영역으로, 동일한 예시가 적용됩니다. 단지 이 경우에는 하나의 스프레드 시트에 곱해야할 수들이 있는 것이 아니라, 거대한 세트의 스프레드 시트들이 있고, 많은 경우에, 이 모델들을 만들고 사용하기 위해 특수한 프로세서를 사용합니다.
+* **오디오** 또는 **이미지** 처리
+* **컴퓨터 비전**: 이미지는 수백만 개의 픽셀로 구성되며, 각 픽셀은 3개의 값/색을 갖습니다. 보통 그 픽셀들에 대해 동시에 무언가를 계산해야 합니다.
+* **머신러닝**: 보통 많은 "matrix"와 "vector" 곱셈이 필요합니다. 숫자가 있는 거대한 스프레드시트를 생각하고, 그 모든 수를 동시에 곱한다고 생각해보세요.
+* **딥러닝**: 머신러닝의 하위 분야이므로 동일하게 적용됩니다. 다만 곱해야 할 숫자가 있는 스프레드시트가 하나가 아니라, 아주 큰 집합이며, 많은 경우 그 모델을 만들고/또는 사용하기 위해 특별한 프로세서를 사용합니다.
-### 동시성 + 병렬성: 웹 + 머신러닝
+### 동시성 + 병렬성: 웹 + 머신러닝 { #concurrency-parallelism-web-machine-learning }
-**FastAPI**를 사용하면 웹 개발에서는 매우 흔한 동시성의 이점을 (NodeJS의 주된 매력만큼) 얻을 수 있습니다.
+**FastAPI**를 사용하면 웹 개발에서 매우 흔한 동시성의 이점을( NodeJS의 주요 매력과 같은) 얻을 수 있습니다.
-뿐만 아니라 머신러닝 시스템과 같이 **CPU에 묶인** 작업을 위해 병렬성과 멀티프로세싱(다수의 프로세스를 병렬적으로 동작시키는 것)을 이용하는 것도 가능합니다.
+또한 머신러닝 시스템처럼 **CPU bound** 워크로드에 대해 병렬성과 멀티프로세싱(여러 프로세스를 병렬로 실행)을 활용할 수도 있습니다.
-파이썬이 **데이터 사이언스**, 머신러닝과 특히 딥러닝에 의 주된 언어라는 간단한 사실에 더해서, 이것은 FastAPI를 데이터 사이언스 / 머신러닝 웹 API와 응용프로그램에 (다른 것들보다) 좋은 선택지가 되게 합니다.
+이것은 파이썬이 **데이터 사이언스**, 머신러닝, 특히 딥러닝의 주요 언어라는 단순한 사실과 더해져, FastAPI를 데이터 사이언스/머신러닝 웹 API 및 애플리케이션(그 외에도 많은 것들)에 매우 잘 맞는 선택으로 만들어 줍니다.
-배포시 병렬을 어떻게 가능하게 하는지 알고싶다면, [배포](/ko/deployment){.internal-link target=_blank}문서를 참고하십시오.
+프로덕션에서 이 병렬성을 어떻게 달성하는지 보려면 [배포](deployment/index.md) 섹션을 참고하세요.
-## `async`와 `await`
+## `async`와 `await` { #async-and-await }
-최신 파이썬 버전에는 비동기 코드를 정의하는 매우 직관적인 방법이 있습니다. 이는 이것을 평범한 "순차적" 코드로 보이게 하고, 적절한 순간에 당신을 위해 "대기"합니다.
+최신 파이썬 버전에는 비동기 코드를 정의하는 매우 직관적인 방법이 있습니다. 이 방법은 이를 평범한 "순차" 코드처럼 보이게 하고, 적절한 순간에 여러분을 위해 "기다림"을 수행합니다.
-연산이 결과를 전달하기 전에 대기를 해야하고 새로운 파이썬 기능들을 지원한다면, 이렇게 코드를 작성할 수 있습니다:
+결과를 주기 전에 기다림이 필요한 작업이 있고, 이러한 새로운 파이썬 기능을 지원한다면, 다음과 같이 작성할 수 있습니다:
```Python
burgers = await get_burgers(2)
```
-여기서 핵심은 `await`입니다. 이것은 파이썬에게 `burgers` 결과를 저장하기 이전에 `get_burgers(2)`의 작업이 완료되기를 🕙 기다리라고 ⏸ 말합니다. 이로 인해, 파이썬은 그동안 (다른 요청을 받는 것과 같은) 다른 작업을 수행해도 된다는 것을 🔀 ⏯ 알게될 것입니다.
+여기서 핵심은 `await`입니다. 이는 파이썬에게 `get_burgers(2)`가 그 일을 끝낼 때까지 🕙 기다리도록 ⏸ 말하고, 그 결과를 `burgers`에 저장하기 전에 완료되기를 기다리라고 합니다. 이를 통해 파이썬은 그동안(예: 다른 요청을 받는 것처럼) 다른 일을 하러 갈 수 있다는 것 🔀 ⏯ 을 알게 됩니다.
-`await`가 동작하기 위해, 이것은 비동기를 지원하는 함수 내부에 있어야 합니다. 이를 위해서 함수를 `async def`를 사용해 정의하기만 하면 됩니다:
+`await`가 동작하려면, 이 비동기성을 지원하는 함수 내부에 있어야 합니다. 그러려면 `async def`로 선언하기만 하면 됩니다:
```Python hl_lines="1"
async def get_burgers(number: int):
- # Do some asynchronous stuff to create the burgers
+ # 햄버거를 만들기 위한 비동기 처리를 수행
return burgers
```
-...`def`를 사용하는 대신:
+...`def` 대신:
```Python hl_lines="2"
-# This is not asynchronous
+# 비동기가 아닙니다
def get_sequential_burgers(number: int):
- # Do some sequential stuff to create the burgers
+ # 햄버거를 만들기 위한 순차 처리를 수행
return burgers
```
-`async def`를 사용하면, 파이썬은 해당 함수 내에서 `await` 표현에 주의해야한다는 사실과, 해당 함수의 실행을 "일시정지"⏸하고 다시 돌아오기 전까지 다른 작업을 수행🔀할 수 있다는 것을 알게됩니다.
+`async def`를 사용하면, 파이썬은 그 함수 내부에서 `await` 표현식에 주의해야 하며, 그 함수의 실행을 "일시정지" ⏸ 하고 다시 돌아오기 전에 다른 일을 하러 갈 수 있다는 것 🔀 을 알게 됩니다.
-`async def`f 함수를 호출하고자 할 때, "대기"해야합니다. 따라서, 아래는 동작하지 않습니다.
+`async def` 함수를 호출하고자 할 때는, 그 함수를 "await" 해야 합니다. 따라서 아래는 동작하지 않습니다:
```Python
-# This won't work, because get_burgers was defined with: async def
+# 동작하지 않습니다. get_burgers는 async def로 정의되었습니다
burgers = get_burgers(2)
```
---
-따라서, `await`f를 사용해서 호출할 수 있는 라이브러리를 사용한다면, 다음과 같이 `async def`를 사용하는 *경로 작동 함수*를 생성해야 합니다:
+따라서, `await`로 호출할 수 있다고 말하는 라이브러리를 사용한다면, 다음과 같이 그것을 사용하는 *경로 처리 함수*를 `async def`로 만들어야 합니다:
```Python hl_lines="2-3"
@app.get('/burgers')
@@ -314,91 +349,96 @@ async def read_burgers():
return burgers
```
-### 더 세부적인 기술적 사항
+### 더 세부적인 기술적 사항 { #more-technical-details }
+
+`await`는 `async def`로 정의된 함수 내부에서만 사용할 수 있다는 것을 눈치채셨을 것입니다.
+
+하지만 동시에, `async def`로 정의된 함수는 "await" 되어야 합니다. 따라서 `async def`를 가진 함수는 `async def`로 정의된 함수 내부에서만 호출될 수 있습니다.
+
+그렇다면, 닭이 먼저냐 달걀이 먼저냐처럼, 첫 번째 `async` 함수는 어떻게 호출할 수 있을까요?
-`await`가 `async def`를 사용하는 함수 내부에서만 사용이 가능하다는 것을 눈치채셨을 것입니다.
+**FastAPI**로 작업한다면 걱정할 필요가 없습니다. 그 "첫" 함수는 여러분의 *경로 처리 함수*가 될 것이고, FastAPI는 올바르게 처리하는 방법을 알고 있기 때문입니다.
-하지만 동시에, `async def`로 정의된 함수들은 "대기"되어야만 합니다. 따라서, `async def`를 사용한 함수들은 역시 `async def`를 사용한 함수 내부에서만 호출될 수 있습니다.
+하지만 FastAPI 없이 `async` / `await`를 사용하고 싶다면, 그것도 가능합니다.
-그렇다면 닭이 먼저냐, 달걀이 먼저냐, 첫 `async` 함수를 어떻게 호출할 수 있겠습니까?
+### 여러분만의 async 코드 작성하기 { #write-your-own-async-code }
-**FastAPI**를 사용해 작업한다면 이것을 걱정하지 않아도 됩니다. 왜냐하면 그 "첫" 함수는 당신의 *경로 작동 함수*가 될 것이고, FastAPI는 어떻게 올바르게 처리할지 알고있기 때문입니다.
+Starlette(그리고 **FastAPI**)는 [AnyIO](https://anyio.readthedocs.io/en/stable/)를 기반으로 하고 있으며, 파이썬 표준 라이브러리 [asyncio](https://docs.python.org/3/library/asyncio-task.html)와 [Trio](https://trio.readthedocs.io/en/stable/) 모두와 호환됩니다.
-하지만 FastAPI를 사용하지 않고 `async` / `await`를 사용하고 싶다면, 이 역시 가능합니다.
+특히, 코드에서 더 고급 패턴이 필요한 고급 동시성 사용 사례에서는 직접 [AnyIO](https://anyio.readthedocs.io/en/stable/)를 사용할 수 있습니다.
-### 당신만의 비동기 코드 작성하기
+그리고 FastAPI를 사용하지 않더라도, 높은 호환성을 확보하고 그 이점(예: *structured concurrency*)을 얻기 위해 [AnyIO](https://anyio.readthedocs.io/en/stable/)로 여러분만의 async 애플리케이션을 작성할 수도 있습니다.
-Starlette(그리고 FastAPI)는 AnyIO를 기반으로 하고있고, 따라서 파이썬 표준 라이브러리인 asyncio 및 Trio와 호환됩니다.
+저는 AnyIO 위에 얇은 레이어로 또 다른 라이브러리를 만들었는데, 타입 어노테이션을 조금 개선하고 더 나은 **자동완성**, **인라인 오류** 등을 얻기 위한 것입니다. 또한 **이해**하고 **여러분만의 async 코드**를 작성하도록 돕는 친절한 소개와 튜토리얼도 제공합니다: [Asyncer](https://asyncer.tiangolo.com/). 특히 **async 코드와 일반**(blocking/동기) 코드를 **결합**해야 한다면 아주 유용합니다.
-특히, 코드에서 고급 패턴이 필요한 고급 동시성을 사용하는 경우 직접적으로 AnyIO를 사용할 수 있습니다.
+### 비동기 코드의 다른 형태 { #other-forms-of-asynchronous-code }
-FastAPI를 사용하지 않더라도, 높은 호환성 및 AnyIO의 이점(예: *구조화된 동시성*)을 취하기 위해 AnyIO를 사용해 비동기 응용프로그램을 작성할 수 있습니다.
+`async`와 `await`를 사용하는 이 스타일은 언어에서 비교적 최근에 추가되었습니다.
-### 비동기 코드의 다른 형태
+하지만 비동기 코드를 다루는 일을 훨씬 더 쉽게 만들어 줍니다.
-파이썬에서 `async`와 `await`를 사용하게 된 것은 비교적 최근의 일입니다.
+거의 동일한 문법이 최근 브라우저와 NodeJS의 최신 JavaScript에도 포함되었습니다.
-하지만 이로 인해 비동기 코드 작업이 훨씬 간단해졌습니다.
+하지만 그 이전에는 비동기 코드를 처리하는 것이 훨씬 더 복잡하고 어려웠습니다.
-같은 (또는 거의 유사한) 문법은 최신 버전의 자바스크립트(브라우저와 NodeJS)에도 추가되었습니다.
+이전 버전의 파이썬에서는 스레드 또는 [Gevent](https://www.gevent.org/)를 사용할 수 있었을 것입니다. 하지만 코드를 이해하고, 디버깅하고, 이에 대해 생각하는 것이 훨씬 더 복잡합니다.
-하지만 그 이전에, 비동기 코드를 처리하는 것은 꽤 복잡하고 어려운 일이었습니다.
+이전 버전의 NodeJS/브라우저 JavaScript에서는 "callback"을 사용했을 것입니다. 이는 "callback hell"로 이어집니다.
-파이썬의 예전 버전이라면, 스레드 또는 Gevent를 사용할 수 있을 것입니다. 하지만 코드를 이해하고, 디버깅하고, 이에 대해 생각하는게 훨씬 복잡합니다.
+## 코루틴 { #coroutines }
-예전 버전의 NodeJS / 브라우저 자바스크립트라면, "콜백 함수"를 사용했을 것입니다. 그리고 이로 인해 콜백 지옥에 빠지게 될 수 있습니다.
+**코루틴**은 `async def` 함수가 반환하는 것에 대한 매우 고급스러운 용어일 뿐입니다. 파이썬은 그것이 함수와 비슷한 무언가로서 시작할 수 있고, 어느 시점에 끝나지만, 내부에 `await`가 있을 때마다 내부적으로도 일시정지 ⏸ 될 수 있다는 것을 알고 있습니다.
-## 코루틴
+하지만 `async` 및 `await`와 함께 비동기 코드를 사용하는 이 모든 기능은 종종 "코루틴"을 사용한다고 요약됩니다. 이는 Go의 주요 핵심 기능인 "Goroutines"에 비견됩니다.
-**코루틴**은 `async def` 함수가 반환하는 것을 칭하는 매우 고급스러운 용어일 뿐입니다. 파이썬은 그것이 시작되고 어느 시점에서 완료되지만 내부에 `await`가 있을 때마다 내부적으로 일시정지⏸될 수도 있는 함수와 유사한 것이라는 사실을 알고있습니다.
+## 결론 { #conclusion }
-그러나 `async` 및 `await`와 함께 비동기 코드를 사용하는 이 모든 기능들은 "코루틴"으로 간단히 요약됩니다. 이것은 Go의 주된 핵심 기능인 "고루틴"에 견줄 수 있습니다.
+위의 같은 문장을 다시 봅시다:
-## 결론
+> 최신 파이썬 버전은 **“코루틴”**이라고 하는 것을 사용하는 **“비동기 코드”**를 **`async` 및 `await`** 문법과 함께 지원합니다.
-상기 문장을 다시 한 번 봅시다:
+이제 더 이해가 될 것입니다. ✨
-> 최신 파이썬 버전은 **`async` 및 `await`** 문법과 함께 **“코루틴”**이라고 하는 것을 사용하는 **“비동기 코드”**를 지원합니다.
+이 모든 것이 FastAPI(Starlette을 통해)를 구동하고, 인상적인 성능을 내게 하는 원동력입니다.
-이제 이 말을 조금 더 이해할 수 있을 것입니다. ✨
+## 매우 세부적인 기술적 사항 { #very-technical-details }
-이것이 (Starlette을 통해) FastAPI를 강하게 하면서 그것이 인상적인 성능을 낼 수 있게 합니다.
+/// warning | 경고
-## 매우 세부적인 기술적 사항
+이 부분은 아마 건너뛰어도 됩니다.
-!!! warning "경고"
- 이 부분은 넘어가도 됩니다.
+이것들은 **FastAPI**가 내부적으로 어떻게 동작하는지에 대한 매우 세부적인 기술사항입니다.
- 이것들은 **FastAPI**가 내부적으로 어떻게 동작하는지에 대한 매우 세부적인 기술사항입니다.
+(코루틴, 스레드, 블로킹 등) 같은 기술 지식이 꽤 있고 FastAPI가 `async def`와 일반 `def`를 어떻게 처리하는지 궁금하다면, 계속 읽어보세요.
- 만약 기술적 지식(코루틴, 스레드, 블록킹 등)이 있고 FastAPI가 어떻게 `async def` vs `def`를 다루는지 궁금하다면, 계속하십시오.
+///
-### 경로 작동 함수
+### 경로 처리 함수 { #path-operation-functions }
-경로 작동 함수를 `async def` 대신 일반적인 `def`로 선언하는 경우, (서버를 차단하는 것처럼) 그것을 직접 호출하는 대신 대기중인 외부 스레드풀에서 실행됩니다.
+*경로 처리 함수*를 `async def` 대신 일반적인 `def`로 선언하면, (서버를 블로킹할 수 있으므로 직접 호출하는 대신) 외부 스레드풀에서 실행되고 그 결과를 await 합니다.
-만약 상기에 묘사된대로 동작하지 않는 비동기 프로그램을 사용해왔고 약간의 성능 향상 (약 100 나노초)을 위해 `def`를 사용해서 계산만을 위한 사소한 *경로 작동 함수*를 정의해왔다면, **FastAPI**는 이와는 반대라는 것에 주의하십시오. 이러한 경우에, *경로 작동 함수*가 블로킹 I/O를 수행하는 코드를 사용하지 않는 한 `async def`를 사용하는 편이 더 낫습니다.
+위에서 설명한 방식으로 동작하지 않는 다른 async 프레임워크를 사용해본 적이 있고, 아주 작은 성능 향상(약 100 나노초)을 위해 계산만 하는 사소한 *경로 처리 함수*를 일반 `def`로 정의하곤 했다면, **FastAPI**에서는 그 효과가 정반대가 될 수 있다는 점에 유의하세요. 이런 경우에는 *경로 처리 함수*에서 블로킹 I/O 를 수행하는 코드를 사용하지 않는 한 `async def`를 사용하는 편이 더 낫습니다.
-하지만 두 경우 모두, FastAPI가 당신이 전에 사용하던 프레임워크보다 [더 빠를](/#performance){.internal-link target=_blank} (최소한 비견될) 확률이 높습니다.
+그럼에도 두 경우 모두, **FastAPI**는 이전에 사용하던 프레임워크보다 [여전히 더 빠를](index.md#performance) 가능성이 높습니다(또는 최소한 비슷합니다).
-### 의존성
+### 의존성 { #dependencies }
-의존성에도 동일하게 적용됩니다. 의존성이 `async def`가 아닌 표준 `def` 함수라면, 외부 스레드풀에서 실행됩니다.
+[의존성](tutorial/dependencies/index.md)에도 동일하게 적용됩니다. 의존성이 `async def` 대신 표준 `def` 함수라면, 외부 스레드풀에서 실행됩니다.
-### 하위-의존성
+### 하위 의존성 { #sub-dependencies }
-함수 정의시 매개변수로 서로를 필요로하는 다수의 의존성과 하위-의존성을 가질 수 있고, 그 중 일부는 `async def`로, 다른 일부는 일반적인 `def`로 생성되었을 수 있습니다. 이것은 여전히 잘 동작하고, 일반적인 `def`로 생성된 것들은 "대기"되는 대신에 (스레드풀로부터) 외부 스레드에서 호출됩니다.
+서로를 필요로 하는 여러 의존성과 [하위 의존성](tutorial/dependencies/sub-dependencies.md)을 함수 정의의 매개변수로 가질 수 있으며, 그중 일부는 `async def`로, 다른 일부는 일반 `def`로 생성되었을 수 있습니다. 그래도 정상 동작하며, 일반 `def`로 생성된 것들은 "await"되는 대신 (스레드풀에서) 외부 스레드에서 호출됩니다.
-### 다른 유틸리티 함수
+### 다른 유틸리티 함수 { #other-utility-functions }
-직접 호출되는 다른 모든 유틸리티 함수는 일반적인 `def`나 `async def`로 생성될 수 있고 FastAPI는 이를 호출하는 방식에 영향을 미치지 않습니다.
+직접 호출하는 다른 모든 유틸리티 함수는 일반 `def`나 `async def`로 생성될 수 있으며, FastAPI는 호출 방식에 영향을 주지 않습니다.
-이것은 FastAPI가 당신을 위해 호출하는 함수와는 반대입니다: *경로 작동 함수*와 의존성
+이는 FastAPI가 여러분을 위해 호출하는 함수(즉, *경로 처리 함수*와 의존성)와 대비됩니다.
-만약 당신의 유틸리티 함수가 `def`를 사용한 일반적인 함수라면, 스레드풀에서가 아니라 직접 호출(당신이 코드에 작성한 대로)될 것이고, `async def`로 생성된 함수라면 코드에서 호출할 때 그 함수를 `await` 해야 합니다.
+유틸리티 함수가 `def`로 만든 일반 함수라면, 스레드풀이 아니라 직접(코드에 작성한 대로) 호출됩니다. 그리고 `async def`로 생성된 함수라면, 코드에서 호출할 때 그 함수를 `await` 해야 합니다.
---
-다시 말하지만, 이것은 당신이 이것에 대해 찾고있던 경우에 한해 유용할 매우 세부적인 기술사항입니다.
+다시 말하지만, 이것들은 아마도 이를 찾고 있었던 경우에 유용한 매우 세부적인 기술사항입니다.
-그렇지 않은 경우, 상기의 가이드라인만으로도 충분할 것입니다: [바쁘신 경우](#in-a-hurry).
+그렇지 않다면, 위 섹션의 가이드라인이면 충분합니다: 바쁘신가요?.
diff --git a/docs/ko/docs/benchmarks.md b/docs/ko/docs/benchmarks.md
new file mode 100644
index 0000000000000..43c25e865fc9a
--- /dev/null
+++ b/docs/ko/docs/benchmarks.md
@@ -0,0 +1,34 @@
+# 벤치마크 { #benchmarks }
+
+독립적인 TechEmpower 벤치마크에 따르면 **FastAPI** 애플리케이션이 Uvicorn을 사용하여 [사용 가능한 가장 빠른 Python 프레임워크 중 하나](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7)로 실행되며, Starlette와 Uvicorn 자체(내부적으로 FastAPI가 사용하는 도구)보다 조금 아래에 위치합니다.
+
+그러나 벤치마크와 비교를 확인할 때 다음 사항을 염두에 두어야 합니다.
+
+## 벤치마크와 속도 { #benchmarks-and-speed }
+
+벤치마크를 확인할 때, 일반적으로 여러 가지 유형의 도구가 동등한 것으로 비교되는 것을 볼 수 있습니다.
+
+특히, Uvicorn, Starlette, FastAPI가 함께 비교되는 경우가 많습니다(다른 여러 도구와 함께).
+
+도구가 해결하는 문제가 단순할수록 성능이 더 좋아집니다. 그리고 대부분의 벤치마크는 도구가 제공하는 추가 기능을 테스트하지 않습니다.
+
+계층 구조는 다음과 같습니다:
+
+* **Uvicorn**: ASGI 서버
+ * **Starlette**: (Uvicorn 사용) 웹 마이크로 프레임워크
+ * **FastAPI**: (Starlette 사용) 데이터 검증 등 API를 구축하기 위한 여러 추가 기능이 포함된 API 마이크로 프레임워크
+
+* **Uvicorn**:
+ * 서버 자체 외에는 많은 추가 코드가 없기 때문에 최고의 성능을 발휘합니다.
+ * 직접 Uvicorn으로 응용 프로그램을 작성하지는 않을 것입니다. 즉, 사용자의 코드에는 적어도 Starlette(또는 **FastAPI**)에서 제공하는 모든 코드가 포함되어야 합니다. 그렇게 하면 최종 응용 프로그램은 프레임워크를 사용하고 앱 코드와 버그를 최소화하는 것과 동일한 오버헤드를 갖게 됩니다.
+ * Uvicorn을 비교할 때는 Daphne, Hypercorn, uWSGI 등의 응용 프로그램 서버와 비교하세요.
+* **Starlette**:
+ * Uvicorn 다음으로 좋은 성능을 발휘합니다. 사실 Starlette는 Uvicorn을 사용하여 실행됩니다. 따라서 더 많은 코드를 실행해야 하기 때문에 Uvicorn보다 "느려질" 수밖에 없습니다.
+ * 하지만 경로 기반 라우팅 등 간단한 웹 응용 프로그램을 구축할 수 있는 도구를 제공합니다.
+ * Starlette를 비교할 때는 Sanic, Flask, Django 등의 웹 프레임워크(또는 마이크로 프레임워크)와 비교하세요.
+* **FastAPI**:
+ * Starlette가 Uvicorn을 사용하므로 Uvicorn보다 빨라질 수 없는 것과 마찬가지로, **FastAPI**는 Starlette를 사용하므로 더 빠를 수 없습니다.
+ * FastAPI는 Starlette에 추가적으로 더 많은 기능을 제공합니다. API를 구축할 때 거의 항상 필요한 데이터 검증 및 직렬화와 같은 기능들이 포함되어 있습니다. 그리고 이를 사용하면 문서 자동화 기능도 제공됩니다(문서 자동화는 응용 프로그램 실행 시 오버헤드를 추가하지 않고 시작 시 생성됩니다).
+ * FastAPI를 사용하지 않고 직접 Starlette(또는 다른 도구, 예: Sanic, Flask, Responder 등)를 사용했다면 데이터 검증 및 직렬화를 직접 구현해야 합니다. 따라서 최종 응용 프로그램은 FastAPI를 사용한 것과 동일한 오버헤드를 가지게 될 것입니다. 많은 경우 데이터 검증 및 직렬화가 응용 프로그램에서 작성된 코드 중 가장 많은 부분을 차지합니다.
+ * 따라서 FastAPI를 사용함으로써 개발 시간, 버그, 코드 라인을 줄일 수 있으며, FastAPI를 사용하지 않았을 때와 동일한 성능(또는 더 나은 성능)을 얻을 수 있을 것입니다(코드에서 모두 구현해야 하기 때문에).
+ * FastAPI를 비교할 때는 Flask-apispec, NestJS, Molten 등 데이터 검증, 직렬화 및 문서화를 제공하는 웹 애플리케이션 프레임워크(또는 도구 집합)와 비교하세요. 통합된 자동 데이터 검증, 직렬화 및 문서화를 제공하는 프레임워크입니다.
diff --git a/docs/ko/docs/deployment/cloud.md b/docs/ko/docs/deployment/cloud.md
index f2b965a9113b8..9d9dc93a3d77d 100644
--- a/docs/ko/docs/deployment/cloud.md
+++ b/docs/ko/docs/deployment/cloud.md
@@ -1,17 +1,24 @@
-# FastAPI를 클라우드 제공업체에서 배포하기
+# 클라우드 제공업체에서 FastAPI 배포하기 { #deploy-fastapi-on-cloud-providers }
사실상 거의 **모든 클라우드 제공업체**를 사용하여 여러분의 FastAPI 애플리케이션을 배포할 수 있습니다.
대부분의 경우, 주요 클라우드 제공업체에서는 FastAPI를 배포할 수 있도록 가이드를 제공합니다.
-## 클라우드 제공업체 - 후원자들
+## FastAPI Cloud { #fastapi-cloud }
-몇몇 클라우드 제공업체들은 [**FastAPI를 후원하며**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, 이를 통해 FastAPI와 FastAPI **생태계**가 지속적이고 건전한 **발전**을 할 수 있습니다.
+**[FastAPI Cloud](https://fastapicloud.com)**는 **FastAPI**를 만든 동일한 작성자와 팀이 구축했습니다.
-이는 FastAPI와 **커뮤니티** (여러분)에 대한 진정한 헌신을 보여줍니다. 그들은 여러분에게 **좋은 서비스**를 제공할 뿐 만이 아니라 여러분이 **훌륭하고 건강한 프레임워크인** FastAPI 를 사용하길 원하기 때문입니다. 🙇
+최소한의 노력으로 API를 **구축**, **배포**, **접근**하는 과정을 간소화합니다.
-아래와 같은 서비스를 사용해보고 각 서비스의 가이드를 따를 수도 있습니다:
+FastAPI로 앱을 빌드할 때의 동일한 **개발자 경험**을 클라우드에 **배포**하는 데에도 제공합니다. 🎉
-* Platform.sh
-* Porter
-* Deta
+FastAPI Cloud는 *FastAPI and friends* 오픈 소스 프로젝트의 주요 후원자이자 자금 제공자입니다. ✨
+
+## 클라우드 제공업체 - 후원자들 { #cloud-providers-sponsors }
+
+다른 몇몇 클라우드 제공업체들도 ✨ [**FastAPI를 후원합니다**](../help-fastapi.md#sponsor-the-author) ✨. 🙇
+
+가이드를 따라 하고 서비스를 사용해보기 위해 이들도 고려해볼 수 있습니다:
+
+* [Render](https://docs.render.com/deploy-fastapi?utm_source=deploydoc&utm_medium=referral&utm_campaign=fastapi)
+* [Railway](https://docs.railway.com/guides/fastapi?utm_medium=integration&utm_source=docs&utm_campaign=fastapi)
diff --git a/docs/ko/docs/deployment/concepts.md b/docs/ko/docs/deployment/concepts.md
new file mode 100644
index 0000000000000..a5c5e53e0d914
--- /dev/null
+++ b/docs/ko/docs/deployment/concepts.md
@@ -0,0 +1,321 @@
+# 배포 개념 { #deployments-concepts }
+
+**FastAPI** 애플리케이션(사실 어떤 종류의 웹 API든)을 배포할 때는, 여러분이 신경 써야 할 여러 개념이 있습니다. 그리고 이 개념들을 활용하면 **애플리케이션을 배포하기 위한 가장 적절한 방법**을 찾을 수 있습니다.
+
+중요한 개념 몇 가지는 다음과 같습니다:
+
+* 보안 - HTTPS
+* 시작 시 실행
+* 재시작
+* 복제(실행 중인 프로세스 수)
+* 메모리
+* 시작 전 사전 단계
+
+이것들이 **배포**에 어떤 영향을 주는지 살펴보겠습니다.
+
+결국 최종 목표는 **API 클라이언트에 서비스를 제공**할 때 **보안**을 보장하고, **중단을 피하며**, **컴퓨팅 리소스**(예: 원격 서버/가상 머신)를 가능한 한 효율적으로 사용하는 것입니다. 🚀
+
+여기서 이 **개념들**을 조금 더 설명하겠습니다. 그러면 서로 매우 다른 환경, 심지어 아직 존재하지 않는 **미래**의 환경에서도 API를 어떻게 배포할지 결정하는 데 필요한 **직관**을 얻을 수 있을 것입니다.
+
+이 개념들을 고려하면, 여러분은 **자신의 API**를 배포하기 위한 최선의 방법을 **평가하고 설계**할 수 있습니다.
+
+다음 장들에서는 FastAPI 애플리케이션을 배포하기 위한 더 **구체적인 레시피**를 제공하겠습니다.
+
+하지만 지금은, 이 중요한 **개념적 아이디어**들을 확인해 봅시다. 이 개념들은 다른 어떤 종류의 웹 API에도 동일하게 적용됩니다. 💡
+
+## 보안 - HTTPS { #security-https }
+
+[이전 HTTPS 장](https.md)에서 HTTPS가 API에 암호화를 제공하는 방식에 대해 배웠습니다.
+
+또한 HTTPS는 일반적으로 애플리케이션 서버 바깥의 **외부** 컴포넌트인 **TLS Termination Proxy**가 제공한다는 것도 확인했습니다.
+
+그리고 **HTTPS 인증서 갱신**을 담당하는 무언가가 필요합니다. 같은 컴포넌트가 그 역할을 할 수도 있고, 다른 무언가가 담당할 수도 있습니다.
+
+### HTTPS를 위한 도구 예시 { #example-tools-for-https }
+
+TLS Termination Proxy로 사용할 수 있는 도구는 예를 들어 다음과 같습니다:
+
+* Traefik
+ * 인증서 갱신을 자동으로 처리 ✨
+* Caddy
+ * 인증서 갱신을 자동으로 처리 ✨
+* Nginx
+ * 인증서 갱신을 위해 Certbot 같은 외부 컴포넌트 사용
+* HAProxy
+ * 인증서 갱신을 위해 Certbot 같은 외부 컴포넌트 사용
+* Nginx 같은 Ingress Controller를 사용하는 Kubernetes
+ * 인증서 갱신을 위해 cert-manager 같은 외부 컴포넌트 사용
+* 클라우드 제공자가 서비스 일부로 내부적으로 처리(아래를 읽어보세요 👇)
+
+또 다른 선택지는 HTTPS 설정을 포함해 더 많은 일을 대신해주는 **클라우드 서비스**를 사용하는 것입니다. 제약이 있거나 비용이 더 들 수도 있습니다. 하지만 그 경우에는 TLS Termination Proxy를 직접 설정할 필요가 없습니다.
+
+다음 장에서 구체적인 예시를 보여드리겠습니다.
+
+---
+
+다음으로 고려할 개념들은 실제로 여러분의 API를 실행하는 프로그램(예: Uvicorn)과 관련된 내용입니다.
+
+## 프로그램과 프로세스 { #program-and-process }
+
+실행 중인 "**프로세스**"에 대해 많이 이야기하게 될 텐데, 이 말이 무엇을 의미하는지, 그리고 "**프로그램**"이라는 단어와 무엇이 다른지 명확히 해두는 것이 유용합니다.
+
+### 프로그램이란 { #what-is-a-program }
+
+**프로그램**이라는 단어는 보통 여러 가지를 가리키는 데 사용됩니다:
+
+* 여러분이 작성하는 **코드**, 즉 **Python 파일**들
+* 운영체제에서 **실행**할 수 있는 **파일**, 예: `python`, `python.exe`, `uvicorn`
+* 운영체제에서 **실행 중**인 특정 프로그램으로, CPU를 사용하고 메모리에 내용을 저장합니다. 이것을 **프로세스**라고도 합니다.
+
+### 프로세스란 { #what-is-a-process }
+
+**프로세스**라는 단어는 보통 더 구체적으로, 운영체제에서 실행 중인 것(위 마지막 항목처럼)만을 가리키는 데 사용됩니다:
+
+* 운영체제에서 **실행 중**인 특정 프로그램
+ * 파일이나 코드를 의미하는 것이 아니라, 운영체제가 **실제로 실행**하고 관리하는 대상을 **구체적으로** 의미합니다.
+* 어떤 프로그램이든 어떤 코드든, **실행**될 때만 무언가를 **할 수 있습니다**. 즉, **프로세스가 실행 중**일 때입니다.
+* 프로세스는 여러분이, 혹은 운영체제가 **종료**(또는 “kill”)할 수 있습니다. 그러면 실행이 멈추고, 더 이상 **아무것도 할 수 없습니다**.
+* 컴퓨터에서 실행 중인 각 애플리케이션 뒤에는 프로세스가 있습니다. 실행 중인 프로그램, 각 창 등도 마찬가지입니다. 그리고 컴퓨터가 켜져 있는 동안 보통 많은 프로세스가 **동시에** 실행됩니다.
+* **같은 프로그램**의 **여러 프로세스**가 동시에 실행될 수도 있습니다.
+
+운영체제의 “작업 관리자(task manager)”나 “시스템 모니터(system monitor)”(또는 비슷한 도구)를 확인해 보면, 이런 프로세스가 많이 실행 중인 것을 볼 수 있습니다.
+
+또 예를 들어, 같은 브라우저 프로그램(Firefox, Chrome, Edge 등)을 실행하는 프로세스가 여러 개 있는 것도 보일 가능성이 큽니다. 보통 탭마다 하나의 프로세스를 실행하고, 그 외에도 추가 프로세스 몇 개가 더 있습니다.
+
+
+
+---
+
+이제 **프로세스**와 **프로그램**의 차이를 알았으니, 배포에 대한 이야기를 계속해 보겠습니다.
+
+## 시작 시 실행 { #running-on-startup }
+
+대부분의 경우 웹 API를 만들면, 클라이언트가 언제나 접근할 수 있도록 **항상 실행**되고 중단되지 않기를 원합니다. 물론 특정 상황에서만 실행하고 싶은 특별한 이유가 있을 수는 있지만, 대부분은 지속적으로 실행되며 **사용 가능**한 상태이기를 원합니다.
+
+### 원격 서버에서 { #in-a-remote-server }
+
+원격 서버(클라우드 서버, 가상 머신 등)를 설정할 때, 가장 단순한 방법은 로컬 개발 때처럼 수동으로 `fastapi run`(Uvicorn을 사용합니다)이나 비슷한 명령을 실행하는 것입니다.
+
+이 방식은 동작하고, **개발 중에는** 유용합니다.
+
+하지만 서버에 대한 연결이 끊기면, 실행 중인 **프로세스**도 아마 종료될 것입니다.
+
+또 서버가 재시작되면(예: 업데이트 이후, 혹은 클라우드 제공자의 마이그레이션 이후) 여러분은 아마 **알아차리지 못할** 겁니다. 그 결과, 프로세스를 수동으로 다시 시작해야 한다는 사실도 모르게 됩니다. 그러면 API는 그냥 죽은 상태로 남습니다. 😱
+
+### 시작 시 자동 실행 { #run-automatically-on-startup }
+
+일반적으로 서버 프로그램(예: Uvicorn)은 서버가 시작될 때 자동으로 시작되고, **사람의 개입** 없이도 FastAPI 앱을 실행하는 프로세스가 항상 실행 중이도록(예: FastAPI 앱을 실행하는 Uvicorn) 구성하고 싶을 것입니다.
+
+### 별도의 프로그램 { #separate-program }
+
+이를 위해 보통 애플리케이션이 시작 시 실행되도록 보장하는 **별도의 프로그램**을 둡니다. 그리고 많은 경우, 데이터베이스 같은 다른 컴포넌트나 애플리케이션도 함께 실행되도록 보장합니다.
+
+### 시작 시 실행을 위한 도구 예시 { #example-tools-to-run-at-startup }
+
+이 역할을 할 수 있는 도구 예시는 다음과 같습니다:
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Swarm Mode의 Docker
+* Systemd
+* Supervisor
+* 클라우드 제공자가 서비스 일부로 내부적으로 처리
+* 기타...
+
+다음 장에서 더 구체적인 예시를 제공하겠습니다.
+
+## 재시작 { #restarts }
+
+애플리케이션이 시작 시 실행되도록 보장하는 것과 비슷하게, 장애가 발생했을 때 **재시작**되도록 보장하고 싶을 것입니다.
+
+### 우리는 실수합니다 { #we-make-mistakes }
+
+사람은 언제나 **실수**합니다. 소프트웨어에는 거의 *항상* 여기저기에 숨은 **버그**가 있습니다. 🐛
+
+그리고 개발자는 버그를 발견하고 새로운 기능을 구현하면서 코드를 계속 개선합니다(새로운 버그도 추가할 수 있겠죠 😅).
+
+### 작은 오류는 자동으로 처리됨 { #small-errors-automatically-handled }
+
+FastAPI로 웹 API를 만들 때 코드에 오류가 있으면, FastAPI는 보통 그 오류를 발생시킨 단일 요청 안에만 문제를 가둡니다. 🛡
+
+클라이언트는 해당 요청에 대해 **500 Internal Server Error**를 받지만, 애플리케이션은 완전히 크래시하지 않고 다음 요청부터는 계속 동작합니다.
+
+### 더 큰 오류 - 크래시 { #bigger-errors-crashes }
+
+그럼에도 불구하고, 우리가 작성한 코드가 **전체 애플리케이션을 크래시**시켜 Uvicorn과 Python 자체가 종료되는 경우가 있을 수 있습니다. 💥
+
+그래도 한 군데 오류 때문에 애플리케이션이 죽은 채로 남아 있기를 바라지는 않을 것입니다. 망가진 경로 처리를 제외한 나머지 *경로 처리*라도 **계속 실행**되기를 원할 가능성이 큽니다.
+
+### 크래시 후 재시작 { #restart-after-crash }
+
+하지만 실행 중인 **프로세스**가 크래시하는 정말 심각한 오류의 경우에는, 적어도 몇 번은 프로세스를 **재시작**하도록 담당하는 외부 컴포넌트가 필요합니다...
+
+/// tip | 팁
+
+...다만 애플리케이션 전체가 **즉시 계속 크래시**한다면, 무한히 재시작하는 것은 아마 의미가 없을 것입니다. 그런 경우에는 개발 중에, 또는 최소한 배포 직후에 알아차릴 가능성이 큽니다.
+
+그러니 여기서는, 특정한 경우에만 전체가 크래시할 수 있고 **미래**에도 그럴 수 있으며, 그래도 재시작하는 것이 의미 있는 주요 사례에 집중해 봅시다.
+
+///
+
+애플리케이션을 재시작하는 역할은 **외부 컴포넌트**가 맡는 편이 보통 좋습니다. 그 시점에는 Uvicorn과 Python을 포함한 애플리케이션이 이미 크래시했기 때문에, 같은 앱의 같은 코드 안에서 이를 해결할 방법이 없기 때문입니다.
+
+### 자동 재시작을 위한 도구 예시 { #example-tools-to-restart-automatically }
+
+대부분의 경우 **시작 시 실행**에 사용한 도구가 자동 **재시작**도 함께 처리합니다.
+
+예를 들어 다음이 가능합니다:
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Swarm Mode의 Docker
+* Systemd
+* Supervisor
+* 클라우드 제공자가 서비스 일부로 내부적으로 처리
+* 기타...
+
+## 복제 - 프로세스와 메모리 { #replication-processes-and-memory }
+
+FastAPI 애플리케이션은 Uvicorn을 실행하는 `fastapi` 명령 같은 서버 프로그램을 사용하면, **하나의 프로세스**로 실행하더라도 여러 클라이언트를 동시에 처리할 수 있습니다.
+
+하지만 많은 경우, 여러 워커 프로세스를 동시에 실행하고 싶을 것입니다.
+
+### 여러 프로세스 - 워커 { #multiple-processes-workers }
+
+단일 프로세스가 처리할 수 있는 것보다 클라이언트가 더 많고(예: 가상 머신이 그리 크지 않을 때), 서버 CPU에 **여러 코어**가 있다면, 같은 애플리케이션을 실행하는 **여러 프로세스**를 동시에 띄우고 요청을 분산시킬 수 있습니다.
+
+같은 API 프로그램을 **여러 프로세스**로 실행할 때, 이 프로세스들을 보통 **workers**라고 부릅니다.
+
+### 워커 프로세스와 포트 { #worker-processes-and-ports }
+
+[HTTPS에 대한 문서](https.md)에서, 서버에서 하나의 포트와 IP 주소 조합에는 하나의 프로세스만 리스닝할 수 있다는 것을 기억하시나요?
+
+이것은 여전히 사실입니다.
+
+따라서 **여러 프로세스**를 동시에 실행하려면, 먼저 **포트에서 리스닝하는 단일 프로세스**가 있어야 하고, 그 프로세스가 어떤 방식으로든 각 워커 프로세스로 통신을 전달해야 합니다.
+
+### 프로세스당 메모리 { #memory-per-process }
+
+이제 프로그램이 메모리에 무언가를 로드한다고 해봅시다. 예를 들어 머신러닝 모델을 변수에 올리거나 큰 파일 내용을 변수에 올리는 경우입니다. 이런 것들은 서버의 **메모리(RAM)**를 어느 정도 사용합니다.
+
+그리고 여러 프로세스는 보통 **메모리를 공유하지 않습니다**. 즉, 각 실행 중인 프로세스는 자체 변수와 메모리를 갖습니다. 코드에서 메모리를 많이 사용한다면, **각 프로세스**가 그만큼의 메모리를 사용하게 됩니다.
+
+### 서버 메모리 { #server-memory }
+
+예를 들어 코드가 크기 **1 GB**의 머신러닝 모델을 로드한다고 해봅시다. API를 프로세스 하나로 실행하면 RAM을 최소 1GB 사용합니다. 그리고 **4개 프로세스**(워커 4개)를 시작하면 각각 1GB RAM을 사용합니다. 즉 총 **4 GB RAM**을 사용합니다.
+
+그런데 원격 서버나 가상 머신의 RAM이 3GB뿐이라면, 4GB를 넘게 로드하려고 할 때 문제가 생깁니다. 🚨
+
+### 여러 프로세스 - 예시 { #multiple-processes-an-example }
+
+이 예시에서는 **Manager Process**가 두 개의 **Worker Processes**를 시작하고 제어합니다.
+
+이 Manager Process는 아마 IP의 **포트**에서 리스닝하는 역할을 합니다. 그리고 모든 통신을 워커 프로세스로 전달합니다.
+
+워커 프로세스들이 실제로 애플리케이션을 실행하며, **요청**을 받아 **응답**을 반환하는 주요 연산을 수행하고, RAM에 변수로 로드한 모든 내용을 담습니다.
+
++ +**FastAPI**는 다른 사람들이 이전에 해온 작업이 없었다면 존재하지 않았을 것입니다. + +그 전에 만들어진 많은 도구들이 이것의 탄생에 영감을 주었습니다. + +저는 여러 해 동안 새로운 프레임워크를 만드는 것을 피하고 있었습니다. 처음에는 **FastAPI**가 다루는 모든 기능을 여러 다른 프레임워크, 플러그인, 도구들을 사용해 해결하려고 했습니다. + +하지만 어느 시점에는, 이전 도구들의 최고의 아이디어를 가져와 가능한 한 최선의 방식으로 조합하고, 이전에는 존재하지 않았던 언어 기능(Python 3.6+ type hints)을 사용해 이 모든 기능을 제공하는 무언가를 만드는 것 외에는 다른 선택지가 없었습니다. + ++ +## 조사 { #investigation } + +이전의 모든 대안을 사용해 보면서, 각 도구로부터 배울 기회를 얻었고, 아이디어를 가져와 제가 일해온 개발 팀들과 저 자신에게 가장 적합하다고 찾은 방식으로 조합할 수 있었습니다. + +예를 들어, 이상적으로는 표준 Python 타입 힌트에 기반해야 한다는 점이 분명했습니다. + +또한, 가장 좋은 접근법은 이미 존재하는 표준을 사용하는 것이었습니다. + +그래서 **FastAPI**의 코딩을 시작하기도 전에, OpenAPI, JSON Schema, OAuth2 등과 같은 명세를 몇 달 동안 공부했습니다. 이들의 관계, 겹치는 부분, 차이점을 이해하기 위해서였습니다. + +## 디자인 { #design } + +그 다음에는 (FastAPI를 사용하는 개발자로서) 사용자로서 갖고 싶었던 개발자 "API"를 디자인하는 데 시간을 썼습니다. + +가장 인기 있는 Python 편집기들: PyCharm, VS Code, Jedi 기반 편집기에서 여러 아이디어를 테스트했습니다. + +약 80%의 사용자를 포함하는 최근 [Python Developer Survey](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools)에 따르면 그렇습니다. + +즉, **FastAPI**는 Python 개발자의 80%가 사용하는 편집기들로 특별히 테스트되었습니다. 그리고 대부분의 다른 편집기도 유사하게 동작하는 경향이 있으므로, 그 모든 이점은 사실상 모든 편집기에서 동작해야 합니다. + +그렇게 해서 코드 중복을 가능한 한 많이 줄이고, 어디서나 자동 완성, 타입 및 에러 검사 등을 제공하는 최선의 방법을 찾을 수 있었습니다. + +모든 개발자에게 최고의 개발 경험을 제공하는 방식으로 말입니다. + +## 필요조건 { #requirements } + +여러 대안을 테스트한 후, 장점 때문에 [**Pydantic**](https://docs.pydantic.dev/)을 사용하기로 결정했습니다. + +그 후, JSON Schema를 완전히 준수하도록 하고, 제약 조건 선언을 정의하는 다양한 방식을 지원하며, 여러 편집기에서의 테스트를 바탕으로 편집기 지원(타입 검사, 자동 완성)을 개선하기 위해 기여했습니다. + +개발 과정에서, 또 다른 핵심 필요조건인 [**Starlette**](https://www.starlette.dev/)에도 기여했습니다. + +## 개발 { #development } + +**FastAPI** 자체를 만들기 시작했을 때쯤에는, 대부분의 조각들이 이미 갖춰져 있었고, 디자인은 정의되어 있었며, 필요조건과 도구는 준비되어 있었고, 표준과 명세에 대한 지식도 명확하고 최신 상태였습니다. + +## 미래 { #future } + +이 시점에는, **FastAPI**가 그 아이디어와 함께 많은 사람들에게 유용하다는 것이 이미 분명합니다. + +많은 사용 사례에 더 잘 맞기 때문에 이전 대안들보다 선택되고 있습니다. + +많은 개발자와 팀이 이미 자신의 프로젝트를 위해 **FastAPI**에 의존하고 있습니다(저와 제 팀도 포함해서요). + +하지만 여전히, 앞으로 나올 개선 사항과 기능들이 많이 있습니다. + +**FastAPI**의 미래는 밝습니다. + +그리고 [여러분의 도움](help-fastapi.md)은 큰 힘이 됩니다. diff --git a/docs/ko/docs/how-to/authentication-error-status-code.md b/docs/ko/docs/how-to/authentication-error-status-code.md new file mode 100644 index 0000000000000..c82ed0de22249 --- /dev/null +++ b/docs/ko/docs/how-to/authentication-error-status-code.md @@ -0,0 +1,17 @@ +# 이전 403 인증 오류 상태 코드 사용하기 { #use-old-403-authentication-error-status-codes } + +FastAPI 버전 `0.122.0` 이전에는, 통합 보안 유틸리티가 인증 실패 후 클라이언트에 오류를 반환할 때 HTTP 상태 코드 `403 Forbidden`을 사용했습니다. + +FastAPI 버전 `0.122.0`부터는 더 적절한 HTTP 상태 코드 `401 Unauthorized`를 사용하며, HTTP 명세인 [RFC 7235](https://datatracker.ietf.org/doc/html/rfc7235#section-3.1), [RFC 9110](https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized)를 따라 응답에 합리적인 `WWW-Authenticate` 헤더를 반환합니다. + +하지만 어떤 이유로든 클라이언트가 이전 동작에 의존하고 있다면, 보안 클래스에서 `make_not_authenticated_error` 메서드를 오버라이드하여 이전 동작으로 되돌릴 수 있습니다. + +예를 들어, 기본값인 `401 Unauthorized` 오류 대신 `403 Forbidden` 오류를 반환하는 `HTTPBearer`의 서브클래스를 만들 수 있습니다: + +{* ../../docs_src/authentication_error_status_code/tutorial001_an_py310.py hl[9:13] *} + +/// tip | 팁 + +함수는 예외를 `return`하는 것이지 `raise`하지 않는다는 점에 유의하세요. 예외를 발생시키는(`raise`) 작업은 내부 코드의 나머지 부분에서 수행됩니다. + +/// diff --git a/docs/ko/docs/how-to/conditional-openapi.md b/docs/ko/docs/how-to/conditional-openapi.md new file mode 100644 index 0000000000000..b1617b1e83049 --- /dev/null +++ b/docs/ko/docs/how-to/conditional-openapi.md @@ -0,0 +1,56 @@ +# 조건부 OpenAPI { #conditional-openapi } + +필요한 경우, 설정 및 환경 변수를 사용하여 환경에 따라 OpenAPI를 조건부로 구성하고 완전히 비활성화할 수도 있습니다. + +## 보안, API 및 docs에 대해서 { #about-security-apis-and-docs } + +프로덕션에서, 문서화된 사용자 인터페이스(UI)를 숨기는 것이 API를 보호하는 방법이 되어서는 안 됩니다. + +이는 API에 추가적인 보안을 제공하지 않으며, *경로 처리*는 여전히 동일한 위치에서 사용 할 수 있습니다. + +코드에 보안 결함이 있다면, 그 결함은 여전히 존재할 것입니다. + +문서를 숨기는 것은 API와 상호작용하는 방법을 이해하기 어렵게 만들며, 프로덕션에서 디버깅을 더 어렵게 만들 수 있습니다. 이는 단순히 [은폐를 통한 보안](https://en.wikipedia.org/wiki/Security_through_obscurity)의 한 형태로 간주될 수 있습니다. + +API를 보호하고 싶다면, 예를 들어 다음과 같은 더 나은 방법들이 있습니다: + +* 요청 본문과 응답에 대해 잘 정의된 Pydantic 모델이 있는지 확인하세요. +* 종속성을 사용하여 필요한 권한과 역할을 구성하세요. +* 평문 비밀번호를 절대 저장하지 말고, 비밀번호 해시만 저장하세요. +* pwdlib와 JWT 토큰 등과 같은 잘 알려진 암호화 도구들을 구현하고 사용하세요. +* 필요한 곳에 OAuth2 범위를 사용하여 더 세분화된 권한 제어를 추가하세요. +* ...등등. + +그럼에도 불구하고, 특정 환경(예: 프로덕션)에서 또는 환경 변수의 설정에 따라 API docs를 비활성화해야 하는 매우 특정한 사용 사례가 있을 수 있습니다. + +## 설정 및 환경변수의 조건부 OpenAPI { #conditional-openapi-from-settings-and-env-vars } + +동일한 Pydantic 설정을 사용하여 생성된 OpenAPI 및 docs UI를 쉽게 구성할 수 있습니다. + +예를 들어: + +{* ../../docs_src/conditional_openapi/tutorial001_py310.py hl[6,11] *} + +여기서 `openapi_url` 설정을 기본값인 `"/openapi.json"`으로 선언합니다. + +그런 뒤, 우리는 `FastAPI` 앱을 만들 때 그것을 사용합니다. + +그런 다음 환경 변수 `OPENAPI_URL`을 빈 문자열로 설정하여 OpenAPI(UI docs 포함)를 비활성화할 수도 있습니다. 예를 들어: + +
+
+그러나 `syntaxHighlight`를 `False`로 설정하여 구문 강조 기능을 비활성화할 수 있습니다:
+
+{* ../../docs_src/configure_swagger_ui/tutorial001_py310.py hl[3] *}
+
+...그럼 Swagger UI에서 더 이상 구문 강조 기능이 표시되지 않습니다:
+
+
+
+## 테마 변경 { #change-the-theme }
+
+동일한 방식으로 `"syntaxHighlight.theme"` 키를 사용하여 구문 강조 테마를 설정할 수 있습니다 (중간에 점이 포함된 것을 참고하십시오).
+
+{* ../../docs_src/configure_swagger_ui/tutorial002_py310.py hl[3] *}
+
+이 설정은 구문 강조 색상 테마를 변경합니다:
+
+
+
+## 기본 Swagger UI 매개변수 변경 { #change-default-swagger-ui-parameters }
+
+FastAPI는 대부분의 사용 사례에 적합한 몇 가지 기본 구성 매개변수를 포함하고 있습니다.
+
+기본 구성에는 다음이 포함됩니다:
+
+{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}
+
+`swagger_ui_parameters` 인수에 다른 값을 설정하여 이러한 기본값 중 어느 것이든 재정의할 수 있습니다.
+
+예를 들어, `deepLinking`을 비활성화하려면 `swagger_ui_parameters`에 다음 설정을 전달할 수 있습니다:
+
+{* ../../docs_src/configure_swagger_ui/tutorial003_py310.py hl[3] *}
+
+## 기타 Swagger UI 매개변수 { #other-swagger-ui-parameters }
+
+사용할 수 있는 다른 모든 구성 옵션을 확인하려면, 공식 [Swagger UI 매개변수 문서](https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/)를 참조하십시오.
+
+## JavaScript 전용 설정 { #javascript-only-settings }
+
+Swagger UI는 **JavaScript 전용** 객체(예: JavaScript 함수)로 다른 구성을 허용하기도 합니다.
+
+FastAPI는 이러한 JavaScript 전용 `presets` 설정을 포함하고 있습니다:
+
+```JavaScript
+presets: [
+ SwaggerUIBundle.presets.apis,
+ SwaggerUIBundle.SwaggerUIStandalonePreset
+]
+```
+
+이들은 문자열이 아닌 **JavaScript** 객체이므로 Python 코드에서 직접 전달할 수 없습니다.
+
+이와 같은 JavaScript 전용 구성을 사용해야 하는 경우, 위의 방법 중 하나를 사용할 수 있습니다. Swagger UI *경로 처리*를 모두 재정의하고 필요한 JavaScript를 수동으로 작성하세요.
diff --git a/docs/ko/docs/how-to/custom-docs-ui-assets.md b/docs/ko/docs/how-to/custom-docs-ui-assets.md
new file mode 100644
index 0000000000000..265eaca047429
--- /dev/null
+++ b/docs/ko/docs/how-to/custom-docs-ui-assets.md
@@ -0,0 +1,185 @@
+# 커스텀 Docs UI 정적 에셋(자체 호스팅) { #custom-docs-ui-static-assets-self-hosting }
+
+API 문서는 **Swagger UI**와 **ReDoc**을 사용하며, 각각 JavaScript와 CSS 파일이 필요합니다.
+
+기본적으로 이러한 파일은 CDN에서 제공됩니다.
+
+하지만 이를 커스터마이징할 수 있으며, 특정 CDN을 지정하거나 파일을 직접 제공할 수도 있습니다.
+
+## JavaScript와 CSS용 커스텀 CDN { #custom-cdn-for-javascript-and-css }
+
+예를 들어 다른 CDN을 사용하고 싶다고 해봅시다. 예를 들면 `https://unpkg.com/`을 사용하려는 경우입니다.
+
+이는 예를 들어 특정 국가에서 일부 URL을 제한하는 경우에 유용할 수 있습니다.
+
+### 자동 문서 비활성화하기 { #disable-the-automatic-docs }
+
+첫 번째 단계는 자동 문서를 비활성화하는 것입니다. 기본적으로 자동 문서는 기본 CDN을 사용하기 때문입니다.
+
+비활성화하려면 `FastAPI` 앱을 생성할 때 해당 URL을 `None`으로 설정하세요:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[8] *}
+
+### 커스텀 문서 포함하기 { #include-the-custom-docs }
+
+이제 커스텀 문서를 위한 *경로 처리*를 만들 수 있습니다.
+
+FastAPI 내부 함수를 재사용해 문서용 HTML 페이지를 생성하고, 필요한 인자를 전달할 수 있습니다:
+
+* `openapi_url`: 문서 HTML 페이지가 API의 OpenAPI 스키마를 가져올 수 있는 URL입니다. 여기서는 `app.openapi_url` 속성을 사용할 수 있습니다.
+* `title`: API의 제목입니다.
+* `oauth2_redirect_url`: 기본값을 사용하려면 여기서 `app.swagger_ui_oauth2_redirect_url`을 사용할 수 있습니다.
+* `swagger_js_url`: Swagger UI 문서의 HTML이 **JavaScript** 파일을 가져올 수 있는 URL입니다. 커스텀 CDN URL입니다.
+* `swagger_css_url`: Swagger UI 문서의 HTML이 **CSS** 파일을 가져올 수 있는 URL입니다. 커스텀 CDN URL입니다.
+
+ReDoc도 마찬가지입니다...
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[2:6,11:19,22:24,27:33] *}
+
+/// tip | 팁
+
+`swagger_ui_redirect`에 대한 *경로 처리*는 OAuth2를 사용할 때 도움이 되는 헬퍼입니다.
+
+API를 OAuth2 provider와 통합하면 인증을 수행한 뒤 획득한 자격 증명으로 API 문서로 다시 돌아올 수 있습니다. 그리고 실제 OAuth2 인증을 사용해 API와 상호작용할 수 있습니다.
+
+Swagger UI가 이 과정을 백그라운드에서 처리해 주지만, 이를 위해 이 "redirect" 헬퍼가 필요합니다.
+
+///
+
+### 테스트용 *경로 처리* 만들기 { #create-a-path-operation-to-test-it }
+
+이제 모든 것이 제대로 동작하는지 테스트할 수 있도록 *경로 처리*를 하나 만드세요:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[36:38] *}
+
+### 테스트하기 { #test-it }
+
+이제 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)에서 문서에 접속한 뒤 페이지를 새로고침하면, 새 CDN에서 에셋을 불러오는 것을 확인할 수 있습니다.
+
+## 문서용 JavaScript와 CSS 자체 호스팅하기 { #self-hosting-javascript-and-css-for-docs }
+
+JavaScript와 CSS를 자체 호스팅하는 것은 예를 들어, 오프라인 상태이거나 외부 인터넷에 접근할 수 없는 환경, 또는 로컬 네트워크에서도 앱이 계속 동작해야 할 때 유용할 수 있습니다.
+
+여기서는 동일한 FastAPI 앱에서 해당 파일을 직접 제공하고, 문서가 이를 사용하도록 설정하는 방법을 살펴봅니다.
+
+### 프로젝트 파일 구조 { #project-file-structure }
+
+프로젝트 파일 구조가 다음과 같다고 해봅시다:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+```
+
+이제 해당 정적 파일을 저장할 디렉터리를 만드세요.
+
+새 파일 구조는 다음과 같을 수 있습니다:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static/
+```
+
+### 파일 다운로드하기 { #download-the-files }
+
+문서에 필요한 정적 파일을 다운로드해서 `static/` 디렉터리에 넣으세요.
+
+각 링크를 우클릭한 뒤 "링크를 다른 이름으로 저장..."과 비슷한 옵션을 선택하면 될 것입니다.
+
+**Swagger UI**는 다음 파일을 사용합니다:
+
+* [`swagger-ui-bundle.js`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js)
+* [`swagger-ui.css`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css)
+
+**ReDoc**은 다음 파일을 사용합니다:
+
+* [`redoc.standalone.js`](https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js)
+
+이후 파일 구조는 다음과 같을 수 있습니다:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static
+ ├── redoc.standalone.js
+ ├── swagger-ui-bundle.js
+ └── swagger-ui.css
+```
+
+### 정적 파일 제공하기 { #serve-the-static-files }
+
+* `StaticFiles`를 import합니다.
+* 특정 경로에 `StaticFiles()` 인스턴스를 "마운트(mount)"합니다.
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[7,11] *}
+
+### 정적 파일 테스트하기 { #test-the-static-files }
+
+애플리케이션을 시작하고 [http://127.0.0.1:8000/static/redoc.standalone.js](http://127.0.0.1:8000/static/redoc.standalone.js)로 이동하세요.
+
+**ReDoc**용 매우 긴 JavaScript 파일이 보일 것입니다.
+
+예를 들어 다음과 같이 시작할 수 있습니다:
+
+```JavaScript
+/*! For license information please see redoc.standalone.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")):
+...
+```
+
+이는 앱에서 정적 파일을 제공할 수 있고, 문서용 정적 파일을 올바른 위치에 배치했다는 것을 확인해 줍니다.
+
+이제 문서가 이 정적 파일을 사용하도록 앱을 설정할 수 있습니다.
+
+### 정적 파일을 위한 자동 문서 비활성화하기 { #disable-the-automatic-docs-for-static-files }
+
+커스텀 CDN을 사용할 때와 마찬가지로, 첫 단계는 자동 문서를 비활성화하는 것입니다. 자동 문서는 기본적으로 CDN을 사용합니다.
+
+비활성화하려면 `FastAPI` 앱을 생성할 때 해당 URL을 `None`으로 설정하세요:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[9] *}
+
+### 정적 파일을 위한 커스텀 문서 포함하기 { #include-the-custom-docs-for-static-files }
+
+그리고 커스텀 CDN을 사용할 때와 동일한 방식으로, 이제 커스텀 문서를 위한 *경로 처리*를 만들 수 있습니다.
+
+다시 한 번, FastAPI 내부 함수를 재사용해 문서용 HTML 페이지를 생성하고, 필요한 인자를 전달할 수 있습니다:
+
+* `openapi_url`: 문서 HTML 페이지가 API의 OpenAPI 스키마를 가져올 수 있는 URL입니다. 여기서는 `app.openapi_url` 속성을 사용할 수 있습니다.
+* `title`: API의 제목입니다.
+* `oauth2_redirect_url`: 기본값을 사용하려면 여기서 `app.swagger_ui_oauth2_redirect_url`을 사용할 수 있습니다.
+* `swagger_js_url`: Swagger UI 문서의 HTML이 **JavaScript** 파일을 가져올 수 있는 URL입니다. **이제는 여러분의 앱이 직접 제공하는 파일입니다**.
+* `swagger_css_url`: Swagger UI 문서의 HTML이 **CSS** 파일을 가져올 수 있는 URL입니다. **이제는 여러분의 앱이 직접 제공하는 파일입니다**.
+
+ReDoc도 마찬가지입니다...
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[2:6,14:22,25:27,30:36] *}
+
+/// tip | 팁
+
+`swagger_ui_redirect`에 대한 *경로 처리*는 OAuth2를 사용할 때 도움이 되는 헬퍼입니다.
+
+API를 OAuth2 provider와 통합하면 인증을 수행한 뒤 획득한 자격 증명으로 API 문서로 다시 돌아올 수 있습니다. 그리고 실제 OAuth2 인증을 사용해 API와 상호작용할 수 있습니다.
+
+Swagger UI가 이 과정을 백그라운드에서 처리해 주지만, 이를 위해 이 "redirect" 헬퍼가 필요합니다.
+
+///
+
+### 정적 파일 테스트용 *경로 처리* 만들기 { #create-a-path-operation-to-test-static-files }
+
+이제 모든 것이 제대로 동작하는지 테스트할 수 있도록 *경로 처리*를 하나 만드세요:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[39:41] *}
+
+### 정적 파일 UI 테스트하기 { #test-static-files-ui }
+
+이제 WiFi 연결을 끊고 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)에서 문서에 접속한 뒤 페이지를 새로고침해 보세요.
+
+인터넷이 없어도 API 문서를 보고, API와 상호작용할 수 있을 것입니다.
diff --git a/docs/ko/docs/how-to/custom-request-and-route.md b/docs/ko/docs/how-to/custom-request-and-route.md
new file mode 100644
index 0000000000000..99138a737002b
--- /dev/null
+++ b/docs/ko/docs/how-to/custom-request-and-route.md
@@ -0,0 +1,109 @@
+# 커스텀 Request 및 APIRoute 클래스 { #custom-request-and-apiroute-class }
+
+일부 경우에는 `Request`와 `APIRoute` 클래스에서 사용되는 로직을 오버라이드하고 싶을 수 있습니다.
+
+특히, 이는 middleware에 있는 로직의 좋은 대안이 될 수 있습니다.
+
+예를 들어, 애플리케이션에서 처리되기 전에 요청 바디를 읽거나 조작하고 싶을 때가 그렇습니다.
+
+/// danger | 위험
+
+이 기능은 "고급" 기능입니다.
+
+**FastAPI**를 이제 막 시작했다면 이 섹션은 건너뛰는 것이 좋습니다.
+
+///
+
+## 사용 사례 { #use-cases }
+
+사용 사례에는 다음이 포함됩니다:
+
+* JSON이 아닌 요청 바디를 JSON으로 변환하기(예: [`msgpack`](https://msgpack.org/index.html)).
+* gzip으로 압축된 요청 바디 압축 해제하기.
+* 모든 요청 바디를 자동으로 로깅하기.
+
+## 커스텀 요청 바디 인코딩 처리하기 { #handling-custom-request-body-encodings }
+
+커스텀 `Request` 서브클래스를 사용해 gzip 요청의 압축을 해제하는 방법을 살펴보겠습니다.
+
+그리고 그 커스텀 요청 클래스를 사용하기 위한 `APIRoute` 서브클래스도 함께 보겠습니다.
+
+### 커스텀 `GzipRequest` 클래스 만들기 { #create-a-custom-gziprequest-class }
+
+/// tip | 팁
+
+이 예시는 동작 방식 시연을 위한 장난감 예제입니다. Gzip 지원이 필요하다면 제공되는 [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware)를 사용할 수 있습니다.
+
+///
+
+먼저, `GzipRequest` 클래스를 만듭니다. 이 클래스는 `Request.body()` 메서드를 덮어써서, 적절한 헤더가 있는 경우 바디를 압축 해제합니다.
+
+헤더에 `gzip`이 없으면 바디를 압축 해제하려고 시도하지 않습니다.
+
+이렇게 하면 동일한 route 클래스가 gzip으로 압축된 요청과 압축되지 않은 요청을 모두 처리할 수 있습니다.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[9:16] *}
+
+### 커스텀 `GzipRoute` 클래스 만들기 { #create-a-custom-gziproute-class }
+
+다음으로, `GzipRequest`를 활용하는 `fastapi.routing.APIRoute`의 커스텀 서브클래스를 만듭니다.
+
+이번에는 `APIRoute.get_route_handler()` 메서드를 오버라이드합니다.
+
+이 메서드는 함수를 반환합니다. 그리고 그 함수가 요청을 받아 응답을 반환합니다.
+
+여기서는 원본 요청으로부터 `GzipRequest`를 만들기 위해 이를 사용합니다.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[19:27] *}
+
+/// note | 기술 세부사항
+
+`Request`에는 `request.scope` 속성이 있는데, 이는 요청과 관련된 메타데이터를 담고 있는 Python `dict`입니다.
+
+`Request`에는 또한 `request.receive`가 있는데, 이는 요청의 바디를 "받기(receive)" 위한 함수입니다.
+
+`scope` `dict`와 `receive` 함수는 모두 ASGI 명세의 일부입니다.
+
+그리고 이 두 가지, `scope`와 `receive`가 새로운 `Request` 인스턴스를 만드는 데 필요한 것들입니다.
+
+`Request`에 대해 더 알아보려면 [Starlette의 Requests 문서](https://www.starlette.dev/requests/)를 확인하세요.
+
+///
+
+`GzipRequest.get_route_handler`가 반환하는 함수가 다르게 하는 유일한 것은 `Request`를 `GzipRequest`로 변환하는 것입니다.
+
+이렇게 하면, 우리의 `GzipRequest`가 *경로 처리*로 전달하기 전에(필요하다면) 데이터의 압축 해제를 담당하게 됩니다.
+
+그 이후의 모든 처리 로직은 동일합니다.
+
+하지만 `GzipRequest.body`에서 변경을 했기 때문에, 필요할 때 **FastAPI**가 로드하는 시점에 요청 바디는 자동으로 압축 해제됩니다.
+
+## 예외 핸들러에서 요청 바디 접근하기 { #accessing-the-request-body-in-an-exception-handler }
+
+/// tip | 팁
+
+같은 문제를 해결하려면 `RequestValidationError`에 대한 커스텀 핸들러에서 `body`를 사용하는 편이 아마 훨씬 더 쉽습니다([오류 처리하기](../tutorial/handling-errors.md#use-the-requestvalidationerror-body)).
+
+하지만 이 예시도 여전히 유효하며, 내부 컴포넌트와 상호작용하는 방법을 보여줍니다.
+
+///
+
+같은 접근 방식을 사용해 예외 핸들러에서 요청 바디에 접근할 수도 있습니다.
+
+필요한 것은 `try`/`except` 블록 안에서 요청을 처리하는 것뿐입니다:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[14,16] *}
+
+예외가 발생하더라도 `Request` 인스턴스는 여전히 스코프 안에 남아 있으므로, 오류를 처리할 때 요청 바디를 읽고 활용할 수 있습니다:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[17:19] *}
+
+## 라우터에서의 커스텀 `APIRoute` 클래스 { #custom-apiroute-class-in-a-router }
+
+`APIRouter`의 `route_class` 파라미터를 설정할 수도 있습니다:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[26] *}
+
+이 예시에서는 `router` 아래의 *경로 처리*들이 커스텀 `TimedRoute` 클래스를 사용하며, 응답을 생성하는 데 걸린 시간을 담은 추가 `X-Response-Time` 헤더가 응답에 포함됩니다:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[13:20] *}
diff --git a/docs/ko/docs/how-to/extending-openapi.md b/docs/ko/docs/how-to/extending-openapi.md
new file mode 100644
index 0000000000000..992243dbe5c08
--- /dev/null
+++ b/docs/ko/docs/how-to/extending-openapi.md
@@ -0,0 +1,80 @@
+# OpenAPI 확장하기 { #extending-openapi }
+
+생성된 OpenAPI 스키마를 수정해야 하는 경우가 있습니다.
+
+이 섹션에서 그 방법을 살펴보겠습니다.
+
+## 일반적인 과정 { #the-normal-process }
+
+일반적인(기본) 과정은 다음과 같습니다.
+
+`FastAPI` 애플리케이션(인스턴스)에는 OpenAPI 스키마를 반환해야 하는 `.openapi()` 메서드가 있습니다.
+
+애플리케이션 객체를 생성하는 과정에서 `/openapi.json`(또는 `openapi_url`에 설정한 경로)용 *경로 처리*가 등록됩니다.
+
+이 경로 처리는 애플리케이션의 `.openapi()` 메서드 결과를 JSON 응답으로 반환할 뿐입니다.
+
+기본적으로 `.openapi()` 메서드는 프로퍼티 `.openapi_schema`에 내용이 있는지 확인하고, 있으면 그 내용을 반환합니다.
+
+없으면 `fastapi.openapi.utils.get_openapi`에 있는 유틸리티 함수를 사용해 생성합니다.
+
+그리고 `get_openapi()` 함수는 다음을 파라미터로 받습니다:
+
+* `title`: 문서에 표시되는 OpenAPI 제목.
+* `version`: API 버전. 예: `2.5.0`.
+* `openapi_version`: 사용되는 OpenAPI 스펙 버전. 기본값은 최신인 `3.1.0`.
+* `summary`: API에 대한 짧은 요약.
+* `description`: API 설명. markdown을 포함할 수 있으며 문서에 표시됩니다.
+* `routes`: 라우트 목록. 각각 등록된 *경로 처리*입니다. `app.routes`에서 가져옵니다.
+
+/// info | 정보
+
+`summary` 파라미터는 OpenAPI 3.1.0 이상에서 사용할 수 있으며, FastAPI 0.99.0 이상에서 지원됩니다.
+
+///
+
+## 기본값 덮어쓰기 { #overriding-the-defaults }
+
+위 정보를 바탕으로, 동일한 유틸리티 함수를 사용해 OpenAPI 스키마를 생성하고 필요한 각 부분을 덮어쓸 수 있습니다.
+
+예를 들어, [커스텀 로고를 포함하기 위한 ReDoc의 OpenAPI 확장](https://github.com/Rebilly/ReDoc/blob/master/docs/redoc-vendor-extensions.md#x-logo)을 추가해 보겠습니다.
+
+### 일반적인 **FastAPI** { #normal-fastapi }
+
+먼저, 평소처럼 **FastAPI** 애플리케이션을 모두 작성합니다:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[1,4,7:9] *}
+
+### OpenAPI 스키마 생성하기 { #generate-the-openapi-schema }
+
+그다음 `custom_openapi()` 함수 안에서, 동일한 유틸리티 함수를 사용해 OpenAPI 스키마를 생성합니다:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[2,15:21] *}
+
+### OpenAPI 스키마 수정하기 { #modify-the-openapi-schema }
+
+이제 OpenAPI 스키마의 `info` "object"에 커스텀 `x-logo`를 추가하여 ReDoc 확장을 더할 수 있습니다:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[22:24] *}
+
+### OpenAPI 스키마 캐시하기 { #cache-the-openapi-schema }
+
+생성한 스키마를 저장하기 위한 "cache"로 `.openapi_schema` 프로퍼티를 사용할 수 있습니다.
+
+이렇게 하면 사용자가 API 문서를 열 때마다 애플리케이션이 스키마를 매번 생성하지 않아도 됩니다.
+
+스키마는 한 번만 생성되고, 이후 요청에서는 같은 캐시된 스키마가 사용됩니다.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[13:14,25:26] *}
+
+### 메서드 오버라이드하기 { #override-the-method }
+
+이제 `.openapi()` 메서드를 새 함수로 교체할 수 있습니다.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[29] *}
+
+### 확인하기 { #check-it }
+
+[http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc)로 이동하면 커스텀 로고(이 예시에서는 **FastAPI** 로고)를 사용하는 것을 확인할 수 있습니다:
+
+
diff --git a/docs/ko/docs/how-to/general.md b/docs/ko/docs/how-to/general.md
new file mode 100644
index 0000000000000..28f9535bc7cc6
--- /dev/null
+++ b/docs/ko/docs/how-to/general.md
@@ -0,0 +1,43 @@
+# 일반 - 사용 방법 - 레시피 { #general-how-to-recipes }
+
+일반적이거나 자주 나오는 질문에 대해, 문서의 다른 위치로 안내하는 몇 가지 포인터를 소개합니다.
+
+## 데이터 필터링 - 보안 { #filter-data-security }
+
+반환하면 안 되는 데이터를 과도하게 반환하지 않도록 하려면, [튜토리얼 - 응답 모델 - 반환 타입](../tutorial/response-model.md) 문서를 읽어보세요.
+
+## 응답 성능 최적화 - 응답 모델 - 반환 타입 { #optimize-response-performance-response-model-return-type }
+
+JSON 데이터를 반환할 때 성능을 최적화하려면 반환 타입 또는 응답 모델을 사용하세요. 그러면 Pydantic이 Python을 거치지 않고 Rust 측에서 JSON 직렬화를 처리합니다. 자세한 내용은 [튜토리얼 - 응답 모델 - 반환 타입](../tutorial/response-model.md) 문서를 참고하세요.
+
+## 문서화 태그 - OpenAPI { #documentation-tags-openapi }
+
+*경로 처리*에 태그를 추가하고, 문서 UI에서 이를 그룹화하려면 [튜토리얼 - 경로 처리 구성 - 태그](../tutorial/path-operation-configuration.md#tags) 문서를 읽어보세요.
+
+## 문서화 요약 및 설명 - OpenAPI { #documentation-summary-and-description-openapi }
+
+*경로 처리*에 요약과 설명을 추가하고, 문서 UI에 표시하려면 [튜토리얼 - 경로 처리 구성 - 요약 및 설명](../tutorial/path-operation-configuration.md#summary-and-description) 문서를 읽어보세요.
+
+## 문서화 응답 설명 - OpenAPI { #documentation-response-description-openapi }
+
+문서 UI에 표시되는 응답의 설명을 정의하려면 [튜토리얼 - 경로 처리 구성 - 응답 설명](../tutorial/path-operation-configuration.md#response-description) 문서를 읽어보세요.
+
+## 문서화 *경로 처리* 지원 중단하기 - OpenAPI { #documentation-deprecate-a-path-operation-openapi }
+
+*경로 처리*를 지원 중단(deprecate)으로 표시하고, 문서 UI에 보여주려면 [튜토리얼 - 경로 처리 구성 - 지원 중단](../tutorial/path-operation-configuration.md#deprecate-a-path-operation) 문서를 읽어보세요.
+
+## 어떤 데이터든 JSON 호환으로 변환하기 { #convert-any-data-to-json-compatible }
+
+어떤 데이터든 JSON 호환 형식으로 변환하려면 [튜토리얼 - JSON 호환 인코더](../tutorial/encoder.md) 문서를 읽어보세요.
+
+## OpenAPI 메타데이터 - 문서 { #openapi-metadata-docs }
+
+라이선스, 버전, 연락처 등의 정보를 포함해 OpenAPI 스키마에 메타데이터를 추가하려면 [튜토리얼 - 메타데이터와 문서 URL](../tutorial/metadata.md) 문서를 읽어보세요.
+
+## OpenAPI 사용자 정의 URL { #openapi-custom-url }
+
+OpenAPI URL을 커스터마이즈(또는 제거)하려면 [튜토리얼 - 메타데이터와 문서 URL](../tutorial/metadata.md#openapi-url) 문서를 읽어보세요.
+
+## OpenAPI 문서 URL { #openapi-docs-urls }
+
+자동으로 생성되는 문서 사용자 인터페이스에서 사용하는 URL을 업데이트하려면 [튜토리얼 - 메타데이터와 문서 URL](../tutorial/metadata.md#docs-urls) 문서를 읽어보세요.
diff --git a/docs/ko/docs/how-to/graphql.md b/docs/ko/docs/how-to/graphql.md
new file mode 100644
index 0000000000000..c4353d57d3ae9
--- /dev/null
+++ b/docs/ko/docs/how-to/graphql.md
@@ -0,0 +1,60 @@
+# GraphQL { #graphql }
+
+**FastAPI**는 **ASGI** 표준을 기반으로 하므로, ASGI와도 호환되는 어떤 **GraphQL** 라이브러리든 매우 쉽게 통합할 수 있습니다.
+
+같은 애플리케이션에서 일반 FastAPI **경로 처리**와 GraphQL을 함께 조합할 수 있습니다.
+
+/// tip | 팁
+
+**GraphQL**은 몇 가지 매우 특정한 사용 사례를 해결합니다.
+
+일반적인 **web API**와 비교했을 때 **장점**과 **단점**이 있습니다.
+
+여러분의 사용 사례에서 **이점**이 **단점**을 상쇄하는지 꼭 평가해 보세요. 🤓
+
+///
+
+## GraphQL 라이브러리 { #graphql-libraries }
+
+다음은 **ASGI** 지원이 있는 **GraphQL** 라이브러리들입니다. **FastAPI**와 함께 사용할 수 있습니다:
+
+* [Strawberry](https://strawberry.rocks/) 🍓
+ * [FastAPI용 문서](https://strawberry.rocks/docs/integrations/fastapi) 제공
+* [Ariadne](https://ariadnegraphql.org/)
+ * [FastAPI용 문서](https://ariadnegraphql.org/docs/fastapi-integration) 제공
+* [Tartiflette](https://tartiflette.io/)
+ * ASGI 통합을 제공하기 위해 [Tartiflette ASGI](https://tartiflette.github.io/tartiflette-asgi/) 사용
+* [Graphene](https://graphene-python.org/)
+ * [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3) 사용
+
+## Strawberry로 GraphQL 사용하기 { #graphql-with-strawberry }
+
+**GraphQL**로 작업해야 하거나 작업하고 싶다면, [**Strawberry**](https://strawberry.rocks/)를 **권장**합니다. **FastAPI**의 설계와 가장 가깝고, 모든 것이 **type annotations**에 기반해 있기 때문입니다.
+
+사용 사례에 따라 다른 라이브러리를 선호할 수도 있지만, 제게 묻는다면 아마 **Strawberry**를 먼저 시도해 보라고 제안할 것입니다.
+
+다음은 Strawberry를 FastAPI와 통합하는 방법에 대한 간단한 미리보기입니다:
+
+{* ../../docs_src/graphql_/tutorial001_py310.py hl[3,22,25] *}
+
+[Strawberry 문서](https://strawberry.rocks/)에서 Strawberry에 대해 더 알아볼 수 있습니다.
+
+또한 [FastAPI에서 Strawberry 사용](https://strawberry.rocks/docs/integrations/fastapi)에 대한 문서도 확인해 보세요.
+
+## Starlette의 예전 `GraphQLApp` { #older-graphqlapp-from-starlette }
+
+이전 버전의 Starlette에는 [Graphene](https://graphene-python.org/)과 통합하기 위한 `GraphQLApp` 클래스가 포함되어 있었습니다.
+
+이것은 Starlette에서 deprecated 되었지만, 이를 사용하던 코드가 있다면 같은 사용 사례를 다루고 **거의 동일한 인터페이스**를 가진 [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3)로 쉽게 **마이그레이션**할 수 있습니다.
+
+/// tip | 팁
+
+GraphQL이 필요하다면, 커스텀 클래스와 타입 대신 type annotations에 기반한 [Strawberry](https://strawberry.rocks/)를 여전히 확인해 보시길 권장합니다.
+
+///
+
+## 더 알아보기 { #learn-more }
+
+[공식 GraphQL 문서](https://graphql.org/)에서 **GraphQL**에 대해 더 알아볼 수 있습니다.
+
+또한 위에서 설명한 각 라이브러리에 대해서도 해당 링크에서 더 자세히 읽어볼 수 있습니다.
diff --git a/docs/ko/docs/how-to/index.md b/docs/ko/docs/how-to/index.md
new file mode 100644
index 0000000000000..f80f9f3586693
--- /dev/null
+++ b/docs/ko/docs/how-to/index.md
@@ -0,0 +1,13 @@
+# How To - 레시피 { #how-to-recipes }
+
+여기에서는 **여러 주제**에 대한 다양한 레시피(“how to” 가이드)를 볼 수 있습니다.
+
+대부분의 아이디어는 어느 정도 **서로 독립적**이며, 대부분의 경우 **여러분의 프로젝트**에 직접 적용되는 경우에만 학습하면 됩니다.
+
+프로젝트에 흥미롭고 유용해 보이는 것이 있다면 확인해 보세요. 그렇지 않다면 아마 건너뛰어도 됩니다.
+
+/// tip | 팁
+
+**FastAPI를 구조적으로 학습**하고 싶다면(권장), 대신 [튜토리얼 - 사용자 가이드](../tutorial/index.md)를 장별로 읽어보세요.
+
+///
diff --git a/docs/ko/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/ko/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
new file mode 100644
index 0000000000000..d47f0bc415017
--- /dev/null
+++ b/docs/ko/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -0,0 +1,135 @@
+# Pydantic v1에서 Pydantic v2로 마이그레이션하기 { #migrate-from-pydantic-v1-to-pydantic-v2 }
+
+오래된 FastAPI 앱이 있다면 Pydantic 버전 1을 사용하고 있을 수 있습니다.
+
+FastAPI 0.100.0 버전은 Pydantic v1 또는 v2 중 하나를 지원했습니다. 설치되어 있는 쪽을 사용했습니다.
+
+FastAPI 0.119.0 버전에서는 v2로의 마이그레이션을 쉽게 하기 위해, Pydantic v2 내부에서 Pydantic v1을(`pydantic.v1`로) 부분적으로 지원하기 시작했습니다.
+
+FastAPI 0.126.0 버전에서는 Pydantic v1 지원을 중단했지만, `pydantic.v1`은 잠시 동안 계속 지원했습니다.
+
+/// warning | 경고
+
+Pydantic 팀은 최신 Python 버전에서 Pydantic v1 지원을 중단했으며, 시작 버전은 **Python 3.14**입니다.
+
+여기에는 `pydantic.v1`도 포함되며, Python 3.14 이상에서는 더 이상 지원되지 않습니다.
+
+Python의 최신 기능을 사용하려면 Pydantic v2를 사용하고 있는지 확인해야 합니다.
+
+///
+
+Pydantic v1을 사용하는 오래된 FastAPI 앱이 있다면, 여기서는 이를 Pydantic v2로 마이그레이션하는 방법과 점진적 마이그레이션을 돕는 **FastAPI 0.119.0의 기능**을 소개하겠습니다.
+
+## 공식 가이드 { #official-guide }
+
+Pydantic에는 v1에서 v2로의 공식 [마이그레이션 가이드](https://docs.pydantic.dev/latest/migration/)가 있습니다.
+
+여기에는 무엇이 바뀌었는지, 검증이 이제 어떻게 더 정확하고 엄격해졌는지, 가능한 주의사항 등도 포함되어 있습니다.
+
+변경된 내용을 더 잘 이해하기 위해 읽어보면 좋습니다.
+
+## 테스트 { #tests }
+
+앱에 대한 [테스트](../tutorial/testing.md)가 있는지 확인하고, 지속적 통합(CI)에서 테스트를 실행하세요.
+
+이렇게 하면 업그레이드를 진행하면서도 모든 것이 기대한 대로 계속 동작하는지 확인할 수 있습니다.
+
+## `bump-pydantic` { #bump-pydantic }
+
+많은 경우, 커스터마이징 없이 일반적인 Pydantic 모델을 사용하고 있다면 Pydantic v1에서 Pydantic v2로의 마이그레이션 과정 대부분을 자동화할 수 있습니다.
+
+같은 Pydantic 팀이 제공하는 [`bump-pydantic`](https://github.com/pydantic/bump-pydantic)를 사용할 수 있습니다.
+
+이 도구는 변경해야 하는 코드의 대부분을 자동으로 바꾸는 데 도움을 줍니다.
+
+그 다음 테스트를 실행해서 모든 것이 동작하는지 확인하면 됩니다. 잘 된다면 끝입니다. 😎
+
+## v2 안의 Pydantic v1 { #pydantic-v1-in-v2 }
+
+Pydantic v2는 Pydantic v1의 모든 것을 서브모듈 `pydantic.v1`로 포함합니다. 하지만 이는 Python 3.13보다 높은 버전에서는 더 이상 지원되지 않습니다.
+
+즉, Pydantic v2의 최신 버전을 설치한 뒤, 이 서브모듈에서 예전 Pydantic v1 구성 요소를 import하여 예전 Pydantic v1을 설치한 것처럼 사용할 수 있습니다.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}
+
+### v2 안의 Pydantic v1에 대한 FastAPI 지원 { #fastapi-support-for-pydantic-v1-in-v2 }
+
+FastAPI 0.119.0부터는 v2로의 마이그레이션을 쉽게 하기 위해, Pydantic v2 내부의 Pydantic v1에 대해서도 부분적인 지원이 있습니다.
+
+따라서 Pydantic을 최신 v2로 업그레이드하고, import를 `pydantic.v1` 서브모듈을 사용하도록 바꾸면, 많은 경우 그대로 동작합니다.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py hl[2,5,15] *}
+
+/// warning | 경고
+
+Pydantic 팀이 Python 3.14부터 최신 Python 버전에서 Pydantic v1을 더 이상 지원하지 않으므로, `pydantic.v1`을 사용하는 것 역시 Python 3.14 이상에서는 지원되지 않는다는 점을 염두에 두세요.
+
+///
+
+### 같은 앱에서 Pydantic v1과 v2 함께 사용하기 { #pydantic-v1-and-v2-on-the-same-app }
+
+Pydantic에서는 Pydantic v2 모델의 필드를 Pydantic v1 모델로 정의하거나 그 반대로 하는 것을 **지원하지 않습니다**.
+
+```mermaid
+graph TB
+ subgraph "❌ Not Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+...하지만 같은 앱에서 Pydantic v1과 v2를 사용하되, 모델을 분리해서 둘 수는 있습니다.
+
+```mermaid
+graph TB
+ subgraph "✅ Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+어떤 경우에는 FastAPI 앱의 같은 **경로 처리**에서 Pydantic v1과 v2 모델을 함께 사용하는 것도 가능합니다:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}
+
+위 예제에서 입력 모델은 Pydantic v1 모델이고, 출력 모델(`response_model=ItemV2`로 정의됨)은 Pydantic v2 모델입니다.
+
+### Pydantic v1 파라미터 { #pydantic-v1-parameters }
+
+Pydantic v1 모델과 함께 `Body`, `Query`, `Form` 등 파라미터용 FastAPI 전용 도구 일부를 사용해야 한다면, Pydantic v2로의 마이그레이션을 마칠 때까지 `fastapi.temp_pydantic_v1_params`에서 import할 수 있습니다:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py hl[4,18] *}
+
+### 단계적으로 마이그레이션하기 { #migrate-in-steps }
+
+/// tip | 팁
+
+먼저 `bump-pydantic`로 시도해 보세요. 테스트가 통과하고 잘 동작한다면, 한 번의 명령으로 끝입니다. ✨
+
+///
+
+`bump-pydantic`가 여러분의 사용 사례에 맞지 않는다면, 같은 앱에서 Pydantic v1과 v2 모델을 모두 지원하는 기능을 이용해 Pydantic v2로 점진적으로 마이그레이션할 수 있습니다.
+
+먼저 Pydantic을 최신 v2로 업그레이드하고, 모든 모델의 import를 `pydantic.v1`을 사용하도록 바꿀 수 있습니다.
+
+그 다음 Pydantic v1에서 v2로 모델을 그룹 단위로, 점진적인 단계로 마이그레이션을 시작하면 됩니다. 🚶
diff --git a/docs/ko/docs/how-to/separate-openapi-schemas.md b/docs/ko/docs/how-to/separate-openapi-schemas.md
new file mode 100644
index 0000000000000..2dd76a3b4cee1
--- /dev/null
+++ b/docs/ko/docs/how-to/separate-openapi-schemas.md
@@ -0,0 +1,102 @@
+# 입력과 출력에 대해 OpenAPI 스키마를 분리할지 여부 { #separate-openapi-schemas-for-input-and-output-or-not }
+
+**Pydantic v2**가 릴리스된 이후, 생성되는 OpenAPI는 이전보다 조금 더 정확하고 **올바르게** 만들어집니다. 😎
+
+실제로 어떤 경우에는, 같은 Pydantic 모델에 대해 OpenAPI 안에 **두 개의 JSON Schema**가 생기기도 합니다. **기본값(default value)**이 있는지 여부에 따라, 입력용과 출력용으로 나뉩니다.
+
+이것이 어떻게 동작하는지, 그리고 필요하다면 어떻게 변경할 수 있는지 살펴보겠습니다.
+
+## 입력과 출력을 위한 Pydantic 모델 { #pydantic-models-for-input-and-output }
+
+예를 들어, 다음처럼 기본값이 있는 Pydantic 모델이 있다고 해보겠습니다:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *}
+
+### 입력용 모델 { #model-for-input }
+
+이 모델을 다음처럼 입력으로 사용하면:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *}
+
+...`description` 필드는 **필수가 아닙니다**. `None`이라는 기본값이 있기 때문입니다.
+
+### 문서에서의 입력 모델 { #input-model-in-docs }
+
+문서에서 `description` 필드에 **빨간 별표**가 없고, 필수로 표시되지 않는 것을 확인할 수 있습니다:
+
+
+
+
+
+
+FastAPI 프레임워크, 고성능, 간편한 학습, 빠른 코드 작성, 준비된 프로덕션
--- -**문서**: https://fastapi.tiangolo.com +**문서**: [https://fastapi.tiangolo.com/ko](https://fastapi.tiangolo.com/ko) -**소스 코드**: https://github.com/tiangolo/fastapi +**소스 코드**: [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi) --- -FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python3.6+의 API를 빌드하기 위한 웹 프레임워크입니다. +FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python의 API를 빌드하기 위한 웹 프레임워크입니다. 주요 특징으로: * **빠름**: (Starlette과 Pydantic 덕분에) **NodeJS** 및 **Go**와 대등할 정도로 매우 높은 성능. [사용 가능한 가장 빠른 파이썬 프레임워크 중 하나](#performance). - * **빠른 코드 작성**: 약 200%에서 300%까지 기능 개발 속도 증가. * * **적은 버그**: 사람(개발자)에 의한 에러 약 40% 감소. * -* **직관적**: 훌륭한 편집기 지원. 모든 곳에서 자동완성. 적은 디버깅 시간. +* **직관적**: 훌륭한 편집기 지원. 자동완성이 모든 곳에서 동작. 적은 디버깅 시간. * **쉬움**: 쉽게 사용하고 배우도록 설계. 적은 문서 읽기 시간. * **짧음**: 코드 중복 최소화. 각 매개변수 선언의 여러 기능. 적은 버그. * **견고함**: 준비된 프로덕션 용 코드를 얻으십시오. 자동 대화형 문서와 함께. -* **표준 기반**: API에 대한 (완전히 호환되는) 개방형 표준 기반: OpenAPI (이전에 Swagger로 알려졌던) 및 JSON 스키마. +* **표준 기반**: API에 대한 (완전히 호환되는) 개방형 표준 기반: [OpenAPI](https://github.com/OAI/OpenAPI-Specification) (이전에 Swagger로 알려졌던) 및 [JSON Schema](https://json-schema.org/). * 내부 개발팀의 프로덕션 애플리케이션을 빌드한 테스트에 근거한 측정 -## 골드 스폰서 +## 스폰서 { #sponsors } -{% if sponsors %} +### 키스톤 스폰서 { #keystone-sponsor } + +{% for sponsor in sponsors.keystone -%} +
-FastAPI는 거인들의 어깨 위에 서 있습니다:
+## **Typer**, CLI를 위한 FastAPI { #typer-the-fastapi-of-clis }
-* 웹 부분을 위한 Starlette.
-* 데이터 부분을 위한 Pydantic.
+async def 사용하기...uvicorn main:app --reload 명령에 관하여...fastapi dev 명령에 관하여...email_validator - 이메일 유효성 검사.
+* [`email-validator`](https://github.com/JoshData/python-email-validator) - 이메일 유효성 검사.
Starlette이 사용하는:
-* HTTPX - `TestClient`를 사용하려면 필요.
-* jinja2 - 기본 템플릿 설정을 사용하려면 필요.
-* python-multipart - `request.form()`과 함께 "parsing"의 지원을 원하면 필요.
-* itsdangerous - `SessionMiddleware` 지원을 위해 필요.
-* pyyaml - Starlette의 `SchemaGenerator` 지원을 위해 필요 (FastAPI와 쓸때는 필요 없을 것입니다).
-* graphene - `GraphQLApp` 지원을 위해 필요.
-* ujson - `UJSONResponse`를 사용하려면 필요.
+* [`httpx`](https://www.python-httpx.org) - `TestClient`를 사용하려면 필요.
+* [`jinja2`](https://jinja.palletsprojects.com) - 기본 템플릿 설정을 사용하려면 필요.
+* [`python-multipart`](https://github.com/Kludex/python-multipart) - `request.form()`과 함께 form "파싱" 지원을 원하면 필요.
+
+FastAPI가 사용하는:
+
+* [`uvicorn`](https://www.uvicorn.dev) - 애플리케이션을 로드하고 제공하는 서버를 위한 것입니다. 여기에는 고성능 서빙에 필요한 일부 의존성(예: `uvloop`)이 포함된 `uvicorn[standard]`가 포함됩니다.
+* `fastapi-cli[standard]` - `fastapi` 명령을 제공하기 위한 것입니다.
+ * 여기에는 [FastAPI Cloud](https://fastapicloud.com)에 FastAPI 애플리케이션을 배포할 수 있게 해주는 `fastapi-cloud-cli`가 포함됩니다.
+
+### `standard` 의존성 없이 { #without-standard-dependencies }
+
+`standard` 선택적 의존성을 포함하고 싶지 않다면, `pip install "fastapi[standard]"` 대신 `pip install fastapi`로 설치할 수 있습니다.
+
+### `fastapi-cloud-cli` 없이 { #without-fastapi-cloud-cli }
+
+표준 의존성과 함께 FastAPI를 설치하되 `fastapi-cloud-cli` 없이 설치하고 싶다면, `pip install "fastapi[standard-no-fastapi-cloud-cli]"`로 설치할 수 있습니다.
+
+### 추가 선택적 의존성 { #additional-optional-dependencies }
+
+추가로 설치하고 싶을 수 있는 의존성도 있습니다.
+
+추가 선택적 Pydantic 의존성:
-FastAPI / Starlette이 사용하는:
+* [`pydantic-settings`](https://docs.pydantic.dev/latest/usage/pydantic_settings/) - 설정 관리를 위한 것입니다.
+* [`pydantic-extra-types`](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/) - Pydantic에서 사용할 추가 타입을 위한 것입니다.
-* uvicorn - 애플리케이션을 로드하고 제공하는 서버.
-* orjson - `ORJSONResponse`을 사용하려면 필요.
+추가 선택적 FastAPI 의존성:
-`pip install fastapi[all]`를 통해 이 모두를 설치 할 수 있습니다.
+* [`orjson`](https://github.com/ijl/orjson) - `ORJSONResponse`를 사용하려면 필요.
+* [`ujson`](https://github.com/esnme/ultrajson) - `UJSONResponse`를 사용하려면 필요.
-## 라이센스
+## 라이센스 { #license }
이 프로젝트는 MIT 라이센스 조약에 따라 라이센스가 부여됩니다.
diff --git a/docs/ko/docs/learn/index.md b/docs/ko/docs/learn/index.md
new file mode 100644
index 0000000000000..0b4d14ff47cd3
--- /dev/null
+++ b/docs/ko/docs/learn/index.md
@@ -0,0 +1,5 @@
+# 배우기 { #learn }
+
+여기 **FastAPI**를 배우기 위한 입문 섹션과 자습서가 있습니다.
+
+여러분은 이것을 FastAPI를 배우기 위한 **책**, **강의**, **공식**이자 권장되는 방법으로 생각할 수 있습니다. 😎
diff --git a/docs/ko/docs/project-generation.md b/docs/ko/docs/project-generation.md
new file mode 100644
index 0000000000000..774b03a190e05
--- /dev/null
+++ b/docs/ko/docs/project-generation.md
@@ -0,0 +1,28 @@
+# Full Stack FastAPI 템플릿 { #full-stack-fastapi-template }
+
+템플릿은 일반적으로 특정 설정과 함께 제공되지만, 유연하고 커스터마이징이 가능하게 디자인 되었습니다. 이 특성들은 여러분이 프로젝트의 요구사항에 맞춰 수정, 적용을 할 수 있게 해주고, 템플릿이 완벽한 시작점이 되게 해줍니다. 🏁
+
+많은 초기 설정, 보안, 데이터베이스 및 일부 API 엔드포인트가 이미 준비되어 있으므로, 여러분은 이 템플릿을 시작하는 데 사용할 수 있습니다.
+
+GitHub 저장소: [Full Stack FastAPI 템플릿](https://github.com/tiangolo/full-stack-fastapi-template)
+
+## Full Stack FastAPI 템플릿 - 기술 스택과 기능들 { #full-stack-fastapi-template-technology-stack-and-features }
+
+- ⚡ Python 백엔드 API를 위한 [**FastAPI**](https://fastapi.tiangolo.com/ko).
+ - 🧰 Python SQL 데이터베이스 상호작용을 위한 [SQLModel](https://sqlmodel.tiangolo.com) (ORM).
+ - 🔍 FastAPI에 의해 사용되는, 데이터 검증과 설정 관리를 위한 [Pydantic](https://docs.pydantic.dev).
+ - 💾 SQL 데이터베이스로서의 [PostgreSQL](https://www.postgresql.org).
+- 🚀 프론트엔드를 위한 [React](https://react.dev).
+ - 💃 TypeScript, hooks, Vite 및 기타 현대적인 프론트엔드 스택을 사용.
+ - 🎨 프론트엔드 컴포넌트를 위한 [Tailwind CSS](https://tailwindcss.com) 및 [shadcn/ui](https://ui.shadcn.com).
+ - 🤖 자동으로 생성된 프론트엔드 클라이언트.
+ - 🧪 End-to-End 테스트를 위한 [Playwright](https://playwright.dev).
+ - 🦇 다크 모드 지원.
+- 🐋 개발 환경과 프로덕션(운영)을 위한 [Docker Compose](https://www.docker.com).
+- 🔒 기본으로 지원되는 안전한 비밀번호 해싱.
+- 🔑 JWT (JSON Web Token) 인증.
+- 📫 이메일 기반 비밀번호 복구.
+- ✅ [Pytest](https://pytest.org)를 이용한 테스트.
+- 📞 리버스 프록시 / 로드 밸런서로서의 [Traefik](https://traefik.io).
+- 🚢 Docker Compose를 이용한 배포 지침: 자동 HTTPS 인증서를 처리하기 위한 프론트엔드 Traefik 프록시 설정 방법을 포함.
+- 🏭 GitHub Actions를 기반으로 CI (지속적인 통합) 및 CD (지속적인 배포).
diff --git a/docs/ko/docs/python-types.md b/docs/ko/docs/python-types.md
new file mode 100644
index 0000000000000..12890f2832bb3
--- /dev/null
+++ b/docs/ko/docs/python-types.md
@@ -0,0 +1,350 @@
+# 파이썬 타입 소개 { #python-types-intro }
+
+파이썬은 선택적으로 "타입 힌트(type hints)"(“type annotations”라고도 함)를 지원합니다.
+
+이러한 **"타입 힌트"** 또는 애너테이션은 변수의 타입을 선언할 수 있게 해주는 특수한 구문입니다.
+
+변수의 타입을 선언하면 에디터와 도구가 더 나은 지원을 제공할 수 있습니다.
+
+이 문서는 파이썬 타입 힌트에 대한 **빠른 자습서 / 내용 환기**입니다. **FastAPI**와 함께 사용하기 위해 필요한 최소한만 다룹니다... 실제로는 아주 조금만 있으면 됩니다.
+
+**FastAPI**는 모두 이러한 타입 힌트에 기반을 두고 있으며, 이는 많은 장점과 이점을 제공합니다.
+
+하지만 **FastAPI**를 전혀 사용하지 않더라도, 타입 힌트를 조금만 배워도 도움이 됩니다.
+
+/// note | 참고
+
+파이썬에 능숙하고 타입 힌트에 대해 이미 모두 알고 있다면, 다음 장으로 건너뛰세요.
+
+///
+
+## 동기 부여 { #motivation }
+
+간단한 예제로 시작해봅시다:
+
+{* ../../docs_src/python_types/tutorial001_py310.py *}
+
+이 프로그램을 호출하면 다음이 출력됩니다:
+
+```
+John Doe
+```
+
+이 함수는 다음을 수행합니다:
+
+* `first_name`과 `last_name`를 받습니다.
+* `title()`로 각각의 첫 글자를 대문자로 변환합니다.
+* 가운데에 공백을 두고 연결합니다.
+
+{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}
+
+### 수정하기 { #edit-it }
+
+매우 간단한 프로그램입니다.
+
+하지만 이제, 이것을 처음부터 작성한다고 상상해봅시다.
+
+어느 시점엔 함수를 정의하기 시작했고, 매개변수도 준비해두었을 겁니다...
+
+그런데 "첫 글자를 대문자로 변환하는 그 메서드"를 호출해야 합니다.
+
+`upper`였나요? `uppercase`였나요? `first_uppercase`? `capitalize`?
+
+그 다음, 개발자들의 오랜 친구인 에디터 자동완성을 시도합니다.
+
+함수의 첫 번째 매개변수인 `first_name`을 입력하고, 점(`.`)을 찍은 다음, 완성을 트리거하기 위해 `Ctrl+Space`를 누릅니다.
+
+하지만, 슬프게도 쓸만한 게 아무것도 없습니다:
+
+
+
+### 타입 추가하기 { #add-types }
+
+이전 버전에서 한 줄만 수정해봅시다.
+
+함수의 매개변수인 정확히 이 부분을:
+
+```Python
+ first_name, last_name
+```
+
+에서:
+
+```Python
+ first_name: str, last_name: str
+```
+
+로 바꾸겠습니다.
+
+이게 다입니다.
+
+이것들이 "타입 힌트"입니다:
+
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
+
+이것은 다음처럼 기본값을 선언하는 것과는 다릅니다:
+
+```Python
+ first_name="john", last_name="doe"
+```
+
+다른 것입니다.
+
+등호(`=`)가 아니라 콜론(`:`)을 사용합니다.
+
+그리고 보통 타입 힌트를 추가해도, 타입 힌트 없이 일어나는 일과 비교해 특별히 달라지는 것은 없습니다.
+
+하지만 이제, 타입 힌트를 포함해 그 함수를 다시 만드는 중이라고 상상해봅시다.
+
+같은 지점에서 `Ctrl+Space`로 자동완성을 트리거하면 다음이 보입니다:
+
+
+
+그러면 스크롤하며 옵션을 보다가, "기억나는" 것을 찾을 수 있습니다:
+
+
+
+## 더 큰 동기부여 { #more-motivation }
+
+이 함수를 확인해보세요. 이미 타입 힌트가 있습니다:
+
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
+
+에디터가 변수의 타입을 알고 있기 때문에, 자동완성만 되는 게 아니라 오류 검사도 할 수 있습니다:
+
+
+
+이제 고쳐야 한다는 것을 알고, `age`를 `str(age)`로 문자열로 바꿉니다:
+
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
+
+## 타입 선언 { #declaring-types }
+
+방금 타입 힌트를 선언하는 주요 위치를 보았습니다. 함수 매개변수입니다.
+
+이것은 **FastAPI**와 함께 사용할 때도 주요 위치입니다.
+
+### Simple 타입 { #simple-types }
+
+`str`뿐 아니라 모든 파이썬 표준 타입을 선언할 수 있습니다.
+
+예를 들어 다음을 사용할 수 있습니다:
+
+* `int`
+* `float`
+* `bool`
+* `bytes`
+
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
+
+### `typing` 모듈 { #typing-module }
+
+몇 가지 추가적인 사용 사례에서는 표준 라이브러리의 `typing` 모듈에서 무언가를 import해야 할 수 있습니다. 예를 들어 어떤 값이 "아무 타입"일 수 있다고 선언하려면, `typing`의 `Any`를 사용할 수 있습니다:
+
+```python
+from typing import Any
+
+
+def some_function(data: Any):
+ print(data)
+```
+
+### Generic(제네릭) 타입 { #generic-types }
+
+일부 타입은 대괄호 안에 "타입 매개변수"를 받아 내부 타입을 정의할 수 있습니다. 예를 들어 "문자열의 리스트"는 `list[str]`로 선언합니다.
+
+이렇게 타입 매개변수를 받을 수 있는 타입을 **Generic types** 또는 **Generics**라고 부릅니다.
+
+대괄호와 내부 타입을 사용해 동일한 내장 타입들을 제네릭으로 사용할 수 있습니다:
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
+
+#### List { #list }
+
+예를 들어, `str`의 `list`인 변수를 정의해봅시다.
+
+같은 콜론(`:`) 문법으로 변수를 선언합니다.
+
+타입으로 `list`를 넣습니다.
+
+`list`는 내부 타입을 포함하는 타입이므로, 그 타입들을 대괄호 안에 넣습니다:
+
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
+
+/// info | 정보
+
+대괄호 안의 내부 타입은 "type parameters"라고 부릅니다.
+
+이 경우 `str`이 `list`에 전달된 타입 매개변수입니다.
+
+///
+
+이는 "변수 `items`는 `list`이고, 이 `list`의 각 아이템은 `str`이다"라는 뜻입니다.
+
+이렇게 하면, 에디터는 리스트의 아이템을 처리하는 동안에도 지원을 제공할 수 있습니다:
+
+
+
+타입이 없으면, 이는 거의 불가능합니다.
+
+변수 `item`이 리스트 `items`의 요소 중 하나라는 점에 주목하세요.
+
+그리고 에디터는 여전히 이것이 `str`임을 알고, 그에 대한 지원을 제공합니다.
+
+#### Tuple과 Set { #tuple-and-set }
+
+`tuple`과 `set`도 동일하게 선언할 수 있습니다:
+
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
+
+이는 다음을 의미합니다:
+
+* 변수 `items_t`는 3개의 아이템을 가진 `tuple`이며, `int`, 또 다른 `int`, 그리고 `str`입니다.
+* 변수 `items_s`는 `set`이며, 각 아이템의 타입은 `bytes`입니다.
+
+#### Dict { #dict }
+
+`dict`를 정의하려면, 쉼표로 구분된 2개의 타입 매개변수를 전달합니다.
+
+첫 번째 타입 매개변수는 `dict`의 키를 위한 것입니다.
+
+두 번째 타입 매개변수는 `dict`의 값을 위한 것입니다:
+
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
+
+이는 다음을 의미합니다:
+
+* 변수 `prices`는 `dict`입니다:
+ * 이 `dict`의 키는 `str` 타입입니다(예: 각 아이템의 이름).
+ * 이 `dict`의 값은 `float` 타입입니다(예: 각 아이템의 가격).
+
+#### Union { #union }
+
+변수가 **여러 타입 중 어떤 것이든** 될 수 있다고 선언할 수 있습니다. 예를 들어 `int` 또는 `str`입니다.
+
+이를 정의하려면 두 타입을 세로 막대(`|`)로 구분해 사용합니다.
+
+이는 두 타입 집합의 합집합(union) 안의 어느 것이든 될 수 있다는 뜻이므로 "유니온"이라고 부릅니다.
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
+```
+
+이는 `item`이 `int` 또는 `str`일 수 있다는 뜻입니다.
+
+#### `None`일 수도 있음 { #possibly-none }
+
+값이 `str` 같은 타입일 수도 있지만, `None`일 수도 있다고 선언할 수 있습니다.
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
+
+////
+
+그냥 `str` 대신 `str | None`을 사용하면, 값이 항상 `str`이라고 가정하고 있지만 실제로는 `None`일 수도 있는 상황에서 에디터가 오류를 감지하도록 도와줍니다.
+
+### 타입으로서의 클래스 { #classes-as-types }
+
+변수의 타입으로 클래스를 선언할 수도 있습니다.
+
+이름을 가진 `Person` 클래스가 있다고 해봅시다:
+
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
+
+그러면 `Person` 타입의 변수를 선언할 수 있습니다:
+
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
+
+그리고 다시, 에디터의 모든 지원을 받을 수 있습니다:
+
+
+
+이는 "`one_person`은 `Person` 클래스의 **인스턴스**"라는 뜻입니다.
+
+"`one_person`은 `Person`이라는 **클래스**다"라는 뜻이 아닙니다.
+
+## Pydantic 모델 { #pydantic-models }
+
+[Pydantic](https://docs.pydantic.dev/)은 데이터 검증을 수행하는 파이썬 라이브러리입니다.
+
+속성을 가진 클래스 형태로 데이터의 "모양(shape)"을 선언합니다.
+
+그리고 각 속성은 타입을 가집니다.
+
+그 다음 그 클래스의 인스턴스를 몇 가지 값으로 생성하면, 값들을 검증하고, (그런 경우라면) 적절한 타입으로 변환한 뒤, 모든 데이터를 가진 객체를 제공합니다.
+
+그리고 그 결과 객체에 대해 에디터의 모든 지원을 받을 수 있습니다.
+
+Pydantic 공식 문서의 예시:
+
+{* ../../docs_src/python_types/tutorial011_py310.py *}
+
+/// info | 정보
+
+Pydantic에 대해 더 알아보려면 [문서를 확인하세요](https://docs.pydantic.dev/).
+
+///
+
+**FastAPI**는 모두 Pydantic에 기반을 두고 있습니다.
+
+이 모든 것은 [자습서 - 사용자 안내서](tutorial/index.md)에서 실제로 많이 보게 될 것입니다.
+
+## 메타데이터 애너테이션이 있는 타입 힌트 { #type-hints-with-metadata-annotations }
+
+파이썬에는 `Annotated`를 사용해 이러한 타입 힌트에 **추가 메타데이터**를 넣을 수 있는 기능도 있습니다.
+
+`Annotated`는 `typing`에서 import할 수 있습니다.
+
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
+
+파이썬 자체는 이 `Annotated`로 아무것도 하지 않습니다. 그리고 에디터와 다른 도구들에게는 타입이 여전히 `str`입니다.
+
+하지만 `Annotated`의 이 공간을 사용해, 애플리케이션이 어떻게 동작하길 원하는지에 대한 추가 메타데이터를 **FastAPI**에 제공할 수 있습니다.
+
+기억해야 할 중요한 점은 `Annotated`에 전달하는 **첫 번째 *타입 매개변수***가 **실제 타입**이라는 것입니다. 나머지는 다른 도구를 위한 메타데이터일 뿐입니다.
+
+지금은 `Annotated`가 존재하며, 표준 파이썬이라는 것만 알면 됩니다. 😎
+
+나중에 이것이 얼마나 **강력**할 수 있는지 보게 될 것입니다.
+
+/// tip | 팁
+
+이것이 **표준 파이썬**이라는 사실은, 에디터에서 가능한 **최고의 개발자 경험**을 계속 얻을 수 있다는 뜻이기도 합니다. 사용하는 도구로 코드를 분석하고 리팩터링하는 등에서도요. ✨
+
+또한 코드가 많은 다른 파이썬 도구 및 라이브러리와 매우 호환된다는 뜻이기도 합니다. 🚀
+
+///
+
+## **FastAPI**에서의 타입 힌트 { #type-hints-in-fastapi }
+
+**FastAPI**는 이러한 타입 힌트를 활용해 여러 가지를 합니다.
+
+**FastAPI**에서는 타입 힌트로 매개변수를 선언하면 다음을 얻습니다:
+
+* **에디터 도움**.
+* **타입 확인**.
+
+...그리고 **FastAPI**는 같은 선언을 다음에도 사용합니다:
+
+* **요구사항 정의**: 요청 경로 매개변수, 쿼리 매개변수, 헤더, 바디, 의존성 등에서.
+* **데이터 변환**: 요청에서 필요한 타입으로.
+* **데이터 검증**: 각 요청에서:
+ * 데이터가 유효하지 않을 때 클라이언트에 반환되는 **자동 오류**를 생성합니다.
+* OpenAPI를 사용해 API를 **문서화**:
+ * 자동 상호작용 문서 UI에서 사용됩니다.
+
+이 모든 것이 다소 추상적으로 들릴 수도 있습니다. 걱정하지 마세요. [자습서 - 사용자 안내서](tutorial/index.md)에서 실제로 확인하게 될 것입니다.
+
+가장 중요한 점은 표준 파이썬 타입을 한 곳에서 사용함으로써(더 많은 클래스, 데코레이터 등을 추가하는 대신) **FastAPI**가 여러분을 위해 많은 일을 해준다는 사실입니다.
+
+/// info | 정보
+
+자습서를 모두 끝내고 타입에 대해 더 알아보기 위해 다시 돌아왔다면, 좋은 자료로 [`mypy`의 "cheat sheet"](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html)가 있습니다.
+
+///
diff --git a/docs/ko/docs/resources/index.md b/docs/ko/docs/resources/index.md
new file mode 100644
index 0000000000000..f8ec8ddddef05
--- /dev/null
+++ b/docs/ko/docs/resources/index.md
@@ -0,0 +1,3 @@
+# 리소스 { #resources }
+
+추가 리소스, 외부 링크, 그리고 더 많은 자료. ✈️
diff --git a/docs/ko/docs/translation-banner.md b/docs/ko/docs/translation-banner.md
new file mode 100644
index 0000000000000..7bcd907d56891
--- /dev/null
+++ b/docs/ko/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 AI와 사람이 함께한 번역
+
+이 번역은 사람의 안내를 받아 AI가 만들었습니다. 🤝
+
+원문의 의미를 오해하거나 부자연스러워 보이는 등 오류가 있을 수 있습니다. 🤖
+
+[AI LLM을 더 잘 안내하는 데 도움을 주세요](https://fastapi.tiangolo.com/ko/contributing/#translations).
+
+[영문 버전](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/ko/docs/tutorial/background-tasks.md b/docs/ko/docs/tutorial/background-tasks.md
new file mode 100644
index 0000000000000..1f042829c0538
--- /dev/null
+++ b/docs/ko/docs/tutorial/background-tasks.md
@@ -0,0 +1,86 @@
+# 백그라운드 작업 { #background-tasks }
+
+FastAPI에서는 응답을 반환한 *후에* 실행할 백그라운드 작업을 정의할 수 있습니다.
+
+백그라운드 작업은 요청 후에 발생해야 하지만, 클라이언트가 응답을 받기 전에 작업이 완료될 때까지 기다릴 필요가 없는 작업에 유용합니다.
+
+예를 들면 다음과 같습니다.
+
+* 작업을 수행한 후 전송되는 이메일 알림:
+ * 이메일 서버에 연결하고 이메일을 전송하는 것은 (몇 초 정도) "느린" 경향이 있으므로, 응답은 즉시 반환하고 이메일 알림은 백그라운드에서 전송할 수 있습니다.
+* 데이터 처리:
+ * 예를 들어 처리에 오랜 시간이 걸리는 프로세스를 거쳐야 하는 파일을 받았다면, "Accepted"(HTTP 202) 응답을 반환하고 백그라운드에서 파일을 처리할 수 있습니다.
+
+## `BackgroundTasks` 사용 { #using-backgroundtasks }
+
+먼저 `BackgroundTasks`를 임포트하고, `BackgroundTasks` 타입 선언으로 *경로 처리 함수*에 매개변수를 정의합니다:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
+
+**FastAPI**가 `BackgroundTasks` 타입의 객체를 생성하고 해당 매개변수로 전달합니다.
+
+## 작업 함수 생성 { #create-a-task-function }
+
+백그라운드 작업으로 실행할 함수를 생성합니다.
+
+이는 매개변수를 받을 수 있는 표준 함수일 뿐입니다.
+
+`async def` 함수일 수도, 일반 `def` 함수일 수도 있으며, **FastAPI**가 이를 올바르게 처리하는 방법을 알고 있습니다.
+
+이 경우 작업 함수는 파일에 쓰기를 수행합니다(이메일 전송을 시뮬레이션).
+
+그리고 쓰기 작업은 `async`와 `await`를 사용하지 않으므로, 일반 `def`로 함수를 정의합니다:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
+
+## 백그라운드 작업 추가 { #add-the-background-task }
+
+*경로 처리 함수* 내부에서 `.add_task()` 메서드로 작업 함수를 *백그라운드 작업* 객체에 전달합니다:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
+
+`.add_task()`는 다음 인자를 받습니다:
+
+* 백그라운드에서 실행될 작업 함수(`write_notification`).
+* 작업 함수에 순서대로 전달되어야 하는 인자 시퀀스(`email`).
+* 작업 함수에 전달되어야 하는 키워드 인자(`message="some notification"`).
+
+## 의존성 주입 { #dependency-injection }
+
+`BackgroundTasks`는 의존성 주입 시스템에서도 동작하며, *경로 처리 함수*, 의존성(dependable), 하위 의존성 등 여러 수준에서 `BackgroundTasks` 타입의 매개변수를 선언할 수 있습니다.
+
+**FastAPI**는 각 경우에 무엇을 해야 하는지와 동일한 객체를 어떻게 재사용해야 하는지를 알고 있으므로, 모든 백그라운드 작업이 함께 병합되어 이후 백그라운드에서 실행됩니다:
+
+
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
+
+
+이 예제에서는 응답이 전송된 *후에* 메시지가 `log.txt` 파일에 작성됩니다.
+
+요청에 쿼리가 있었다면, 백그라운드 작업으로 로그에 작성됩니다.
+
+그 다음 *경로 처리 함수*에서 생성된 또 다른 백그라운드 작업이 `email` 경로 매개변수를 사용해 메시지를 작성합니다.
+
+## 기술적 세부사항 { #technical-details }
+
+`BackgroundTasks` 클래스는 [`starlette.background`](https://www.starlette.dev/background/)에서 직접 가져옵니다.
+
+FastAPI에 직접 임포트/포함되어 있으므로 `fastapi`에서 임포트할 수 있고, 실수로 `starlette.background`에서 대안인 `BackgroundTask`(끝에 `s`가 없음)를 임포트하는 것을 피할 수 있습니다.
+
+`BackgroundTask`가 아닌 `BackgroundTasks`만 사용하면, 이를 *경로 처리 함수*의 매개변수로 사용할 수 있고 나머지는 **FastAPI**가 `Request` 객체를 직접 사용할 때처럼 대신 처리해 줍니다.
+
+FastAPI에서 `BackgroundTask`만 단독으로 사용하는 것도 가능하지만, 코드에서 객체를 생성하고 이를 포함하는 Starlette `Response`를 반환해야 합니다.
+
+더 자세한 내용은 [Starlette의 Background Tasks 공식 문서](https://www.starlette.dev/background/)에서 확인할 수 있습니다.
+
+## 주의사항 { #caveat }
+
+무거운 백그라운드 계산을 수행해야 하고, 반드시 동일한 프로세스에서 실행할 필요가 없다면(예: 메모리, 변수 등을 공유할 필요가 없음) [Celery](https://docs.celeryq.dev) 같은 더 큰 도구를 사용하는 것이 도움이 될 수 있습니다.
+
+이들은 RabbitMQ나 Redis 같은 메시지/작업 큐 관리자 등 더 복잡한 설정을 필요로 하는 경향이 있지만, 여러 프로세스에서, 특히 여러 서버에서 백그라운드 작업을 실행할 수 있습니다.
+
+하지만 동일한 **FastAPI** 앱의 변수와 객체에 접근해야 하거나, 작은 백그라운드 작업(예: 이메일 알림 전송)을 수행해야 한다면, `BackgroundTasks`를 간단히 사용하면 됩니다.
+
+## 요약 { #recap }
+
+*경로 처리 함수*와 의존성에서 매개변수로 `BackgroundTasks`를 임포트해 사용하여 백그라운드 작업을 추가합니다.
diff --git a/docs/ko/docs/tutorial/bigger-applications.md b/docs/ko/docs/tutorial/bigger-applications.md
new file mode 100644
index 0000000000000..5b93dbb20bac7
--- /dev/null
+++ b/docs/ko/docs/tutorial/bigger-applications.md
@@ -0,0 +1,535 @@
+# 더 큰 애플리케이션 - 여러 파일 { #bigger-applications-multiple-files }
+
+애플리케이션이나 웹 API를 만들 때, 모든 것을 하나의 파일에 담을 수 있는 경우는 드뭅니다.
+
+**FastAPI**는 모든 유연성을 유지하면서도 애플리케이션을 구조화할 수 있게 해주는 편리한 도구를 제공합니다.
+
+/// info | 정보
+
+Flask를 사용해 보셨다면, 이는 Flask의 Blueprints에 해당하는 개념입니다.
+
+///
+
+## 예시 파일 구조 { #an-example-file-structure }
+
+다음과 같은 파일 구조가 있다고 해봅시다:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ ├── dependencies.py
+│ └── routers
+│ │ ├── __init__.py
+│ │ ├── items.py
+│ │ └── users.py
+│ └── internal
+│ ├── __init__.py
+│ └── admin.py
+```
+
+/// tip | 팁
+
+`__init__.py` 파일이 여러 개 있습니다: 각 디렉터리 또는 하위 디렉터리에 하나씩 있습니다.
+
+이 파일들이 한 파일의 코드를 다른 파일로 import할 수 있게 해줍니다.
+
+예를 들어 `app/main.py`에는 다음과 같은 줄이 있을 수 있습니다:
+
+```
+from app.routers import items
+```
+
+///
+
+* `app` 디렉터리에는 모든 것이 들어 있습니다. 그리고 비어 있는 파일 `app/__init__.py`가 있어 "Python package"(“Python modules”의 모음)인 `app`이 됩니다.
+* `app/main.py` 파일이 있습니다. Python package(`__init__.py` 파일이 있는 디렉터리) 안에 있으므로, 이 package의 "module"입니다: `app.main`.
+* `app/dependencies.py` 파일도 있습니다. `app/main.py`와 마찬가지로 "module"입니다: `app.dependencies`.
+* `app/routers/` 하위 디렉터리가 있고, 여기에 또 `__init__.py` 파일이 있으므로 "Python subpackage"입니다: `app.routers`.
+* `app/routers/items.py` 파일은 `app/routers/` package 안에 있으므로, submodule입니다: `app.routers.items`.
+* `app/routers/users.py`도 동일하게 또 다른 submodule입니다: `app.routers.users`.
+* `app/internal/` 하위 디렉터리도 있고 여기에 `__init__.py`가 있으므로 또 다른 "Python subpackage"입니다: `app.internal`.
+* 그리고 `app/internal/admin.py` 파일은 또 다른 submodule입니다: `app.internal.admin`.
+
+
+
+## 같은 router를 다른 `prefix`로 여러 번 포함하기 { #include-the-same-router-multiple-times-with-different-prefix }
+
+`.include_router()`를 사용해 *같은* router를 서로 다른 prefix로 여러 번 포함할 수도 있습니다.
+
+예를 들어 `/api/v1`과 `/api/latest`처럼 서로 다른 prefix로 동일한 API를 노출할 때 유용할 수 있습니다.
+
+이는 고급 사용 방식이라 실제로 필요하지 않을 수도 있지만, 필요할 때를 위해 제공됩니다.
+
+## `APIRouter`에 다른 `APIRouter` 포함하기 { #include-an-apirouter-in-another }
+
+`APIRouter`를 `FastAPI` 애플리케이션에 포함할 수 있는 것과 같은 방식으로, 다음을 사용해 `APIRouter`를 다른 `APIRouter`에 포함할 수 있습니다:
+
+```Python
+router.include_router(other_router)
+```
+
+`FastAPI` 앱에 `router`를 포함하기 전에 수행해야 하며, 그래야 `other_router`의 *path operations*도 함께 포함됩니다.
diff --git a/docs/ko/docs/tutorial/body-fields.md b/docs/ko/docs/tutorial/body-fields.md
new file mode 100644
index 0000000000000..0774dc4413ee0
--- /dev/null
+++ b/docs/ko/docs/tutorial/body-fields.md
@@ -0,0 +1,60 @@
+# 본문 - 필드 { #body-fields }
+
+`Query`, `Path`와 `Body`를 사용해 *경로 처리 함수* 매개변수 내에서 추가적인 검증이나 메타데이터를 선언한 것처럼 Pydantic의 `Field`를 사용하여 모델 내에서 검증과 메타데이터를 선언할 수 있습니다.
+
+## `Field` 임포트 { #import-field }
+
+먼저 이를 임포트해야 합니다:
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}
+
+/// warning | 경고
+
+`Field`는 다른 것들처럼 (`Query`, `Path`, `Body` 등) `fastapi`에서가 아닌 `pydantic`에서 바로 임포트 되는 점에 주의하세요.
+
+///
+
+## 모델 어트리뷰트 선언 { #declare-model-attributes }
+
+그 다음 모델 어트리뷰트와 함께 `Field`를 사용할 수 있습니다:
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}
+
+`Field`는 `Query`, `Path`와 `Body`와 같은 방식으로 동작하며, 모두 같은 매개변수들 등을 가집니다.
+
+/// note | 기술 세부사항
+
+실제로 `Query`, `Path`등, 여러분이 앞으로 볼 다른 것들은 공통 클래스인 `Param` 클래스의 서브클래스 객체를 만드는데, 그 자체로 Pydantic의 `FieldInfo` 클래스의 서브클래스입니다.
+
+그리고 Pydantic의 `Field` 또한 `FieldInfo`의 인스턴스를 반환합니다.
+
+`Body` 또한 `FieldInfo`의 서브클래스 객체를 직접적으로 반환합니다. 그리고 `Body` 클래스의 서브클래스인 것들도 여러분이 나중에 보게될 것입니다.
+
+ `Query`, `Path`와 그 외 것들을 `fastapi`에서 임포트할 때, 이는 실제로 특별한 클래스를 반환하는 함수인 것을 기억해 주세요.
+
+///
+
+/// tip | 팁
+
+주목할 점은 타입, 기본 값 및 `Field`로 이루어진 각 모델 어트리뷰트가 `Path`, `Query`와 `Body`대신 `Field`를 사용하는 *경로 처리 함수*의 매개변수와 같은 구조를 가진다는 점 입니다.
+
+///
+
+## 별도 정보 추가 { #add-extra-information }
+
+`Field`, `Query`, `Body`, 그 외 안에 별도 정보를 선언할 수 있습니다. 이는 생성된 JSON 스키마에 포함됩니다.
+
+여러분이 예제를 선언할 때 나중에 이 공식 문서에서 별도 정보를 추가하는 방법을 배울 것입니다.
+
+/// warning | 경고
+
+별도 키가 전달된 `Field` 또한 여러분의 애플리케이션의 OpenAPI 스키마에 나타날 것입니다.
+이런 키가 OpenAPI 명세서의 일부가 아닐 수도 있으므로, [OpenAPI validator](https://validator.swagger.io/) 같은 몇몇 OpenAPI 도구들은 여러분이 생성한 스키마와 호환되지 않을 수 있습니다.
+
+///
+
+## 요약 { #recap }
+
+모델 어트리뷰트를 위한 추가 검증과 메타데이터 선언하기 위해 Pydantic의 `Field` 를 사용할 수 있습니다.
+
+또한 추가적인 JSON 스키마 메타데이터를 전달하기 위한 별도의 키워드 인자를 사용할 수 있습니다.
diff --git a/docs/ko/docs/tutorial/body-multiple-params.md b/docs/ko/docs/tutorial/body-multiple-params.md
new file mode 100644
index 0000000000000..3db614d72b4ae
--- /dev/null
+++ b/docs/ko/docs/tutorial/body-multiple-params.md
@@ -0,0 +1,169 @@
+# 본문 - 다중 매개변수 { #body-multiple-parameters }
+
+이제 `Path`와 `Query`를 어떻게 사용하는지 확인했으니, 요청 본문 선언에 대한 더 고급 사용법을 살펴보겠습니다.
+
+## `Path`, `Query` 및 본문 매개변수 혼합 { #mix-path-query-and-body-parameters }
+
+먼저, 물론 `Path`, `Query` 및 요청 본문 매개변수 선언을 자유롭게 혼합해서 사용할 수 있고, **FastAPI**는 어떤 동작을 할지 압니다.
+
+또한 기본 값을 `None`으로 설정해 본문 매개변수를 선택사항으로 선언할 수 있습니다:
+
+{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
+
+/// note | 참고
+
+이 경우에는 본문에서 가져올 `item`이 선택사항이라는 점을 유의하세요. 기본값이 `None`이기 때문입니다.
+
+///
+
+## 다중 본문 매개변수 { #multiple-body-parameters }
+
+이전 예제에서, *경로 처리*는 아래처럼 `Item`의 속성을 가진 JSON 본문을 예상합니다:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+
+하지만, 다중 본문 매개변수 역시 선언할 수 있습니다. 예. `item`과 `user`:
+
+{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}
+
+
+이 경우에, **FastAPI**는 이 함수에 본문 매개변수가 1개보다 많다는 것을 알아챌 것입니다(두 매개변수가 Pydantic 모델입니다).
+
+그래서, 본문에서 매개변수 이름을 키(필드 이름)로 사용하고, 다음과 같은 본문을 예상합니다:
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ }
+}
+```
+
+/// note | 참고
+
+`item`이 이전과 같은 방식으로 선언되었더라도, 이제는 본문에서 `item` 키 안에 있을 것으로 예상된다는 점을 유의하세요.
+
+///
+
+**FastAPI**는 요청에서 자동으로 변환을 수행하여, 매개변수 `item`이 해당하는 내용을 받고 `user`도 마찬가지로 받도록 합니다.
+
+복합 데이터의 검증을 수행하고, OpenAPI 스키마 및 자동 문서에도 그에 맞게 문서화합니다.
+
+## 본문 내의 단일 값 { #singular-values-in-body }
+
+쿼리 및 경로 매개변수에 대한 추가 데이터를 정의하는 `Query`와 `Path`가 있는 것과 같은 방식으로, **FastAPI**는 동등한 `Body`를 제공합니다.
+
+예를 들어 이전 모델을 확장해서, `item`과 `user` 외에도 같은 본문에 `importance`라는 다른 키를 두고 싶을 수 있습니다.
+
+단일 값이므로 그대로 선언하면, **FastAPI**는 이를 쿼리 매개변수라고 가정할 것입니다.
+
+하지만 `Body`를 사용하여 다른 본문 키로 처리하도록 **FastAPI**에 지시할 수 있습니다:
+
+{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
+
+
+이 경우에는 **FastAPI**가 다음과 같은 본문을 예상할 것입니다:
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ },
+ "importance": 5
+}
+```
+
+다시 말해, 데이터 타입을 변환하고, 검증하고, 문서화하는 등의 작업을 수행합니다.
+
+## 다중 본문 매개변수와 쿼리 { #multiple-body-params-and-query }
+
+물론, 필요할 때마다 어떤 본문 매개변수에 추가로 쿼리 매개변수도 선언할 수 있습니다.
+
+기본적으로 단일 값은 쿼리 매개변수로 해석되므로, 명시적으로 `Query`를 추가할 필요 없이 이렇게 하면 됩니다:
+
+```Python
+q: str | None = None
+```
+
+예를 들어:
+
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
+
+
+/// info | 정보
+
+`Body` 또한 `Query`, `Path` 그리고 이후에 볼 다른 것들과 마찬가지로 동일한 추가 검증과 메타데이터 매개변수를 모두 갖고 있습니다.
+
+///
+
+## 단일 본문 매개변수 삽입하기 { #embed-a-single-body-parameter }
+
+Pydantic 모델 `Item`에서 가져온 단일 `item` 본문 매개변수만 있다고 하겠습니다.
+
+기본적으로 **FastAPI**는 그 본문을 직접 예상합니다.
+
+하지만 추가 본문 매개변수를 선언할 때처럼, `item` 키를 가지고 그 안에 모델 내용이 들어 있는 JSON을 예상하게 하려면, `Body`의 특별한 매개변수 `embed`를 사용할 수 있습니다:
+
+```Python
+item: Item = Body(embed=True)
+```
+
+다음과 같이요:
+
+{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}
+
+
+이 경우 **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
+}
+```
+
+## 정리 { #recap }
+
+요청은 본문을 하나만 가질 수 있지만, *경로 처리 함수*에 다중 본문 매개변수를 추가할 수 있습니다.
+
+하지만 **FastAPI**는 이를 처리하고, 함수에 올바른 데이터를 제공하며, *경로 처리*에서 올바른 스키마를 검증하고 문서화합니다.
+
+또한 단일 값을 본문의 일부로 받도록 선언할 수 있습니다.
+
+그리고 단 하나의 매개변수만 선언되어 있더라도, **FastAPI**에 본문을 키 안에 삽입하도록 지시할 수 있습니다.
diff --git a/docs/ko/docs/tutorial/body-nested-models.md b/docs/ko/docs/tutorial/body-nested-models.md
new file mode 100644
index 0000000000000..bbb95cf00b3fa
--- /dev/null
+++ b/docs/ko/docs/tutorial/body-nested-models.md
@@ -0,0 +1,221 @@
+# 본문 - 중첩 모델 { #body-nested-models }
+
+**FastAPI**를 사용하면 (Pydantic 덕분에) 임의로 깊게 중첩된 모델을 정의, 검증, 문서화하고 사용할 수 있습니다.
+
+## 리스트 필드 { #list-fields }
+
+어트리뷰트를 서브타입으로 정의할 수 있습니다. 예를 들어 파이썬 `list`는:
+
+{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}
+
+이는 `tags`를 리스트로 만들지만, 리스트 요소의 타입을 선언하지는 않습니다.
+
+## 타입 매개변수가 있는 리스트 필드 { #list-fields-with-type-parameter }
+
+하지만 파이썬에는 내부 타입, 즉 "타입 매개변수"를 사용해 리스트를 선언하는 특정한 방법이 있습니다:
+
+### 타입 매개변수로 `list` 선언 { #declare-a-list-with-a-type-parameter }
+
+`list`, `dict`, `tuple`처럼 타입 매개변수(내부 타입)를 갖는 타입을 선언하려면,
+대괄호 `[` 및 `]`를 사용해 내부 타입(들)을 "타입 매개변수"로 전달하세요.
+
+```Python
+my_list: list[str]
+```
+
+이 모든 것은 타입 선언을 위한 표준 파이썬 문법입니다.
+
+내부 타입을 갖는 모델 어트리뷰트에 대해 동일한 표준 문법을 사용하세요.
+
+마찬가지로 예제에서 `tags`를 구체적으로 "문자열의 리스트"로 만들 수 있습니다:
+
+{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}
+
+## 집합 타입 { #set-types }
+
+그런데 생각해보니 태그는 반복되면 안 되고, 아마 고유한 문자열이어야 할 것입니다.
+
+그리고 파이썬에는 고유한 항목들의 집합을 위한 특별한 데이터 타입 `set`이 있습니다.
+
+그렇다면 `tags`를 문자열의 집합으로 선언할 수 있습니다:
+
+{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}
+
+이렇게 하면 중복 데이터가 있는 요청을 받더라도 고유한 항목들의 집합으로 변환됩니다.
+
+그리고 해당 데이터를 출력할 때마다, 소스에 중복이 있더라도 고유한 항목들의 집합으로 출력됩니다.
+
+또한 그에 따라 주석이 생기고 문서화됩니다.
+
+## 중첩 모델 { #nested-models }
+
+Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다.
+
+그런데 그 타입 자체가 또 다른 Pydantic 모델일 수 있습니다.
+
+따라서 특정한 어트리뷰트 이름, 타입, 검증을 사용하여 깊게 중첩된 JSON "객체"를 선언할 수 있습니다.
+
+모든 것이 임의의 깊이로 중첩됩니다.
+
+### 서브모델 정의 { #define-a-submodel }
+
+예를 들어, `Image` 모델을 정의할 수 있습니다:
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}
+
+### 서브모델을 타입으로 사용 { #use-the-submodel-as-a-type }
+
+그리고 이를 어트리뷰트의 타입으로 사용할 수 있습니다:
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}
+
+이는 **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**로 그 선언만 해도 얻는 것은:
+
+* 중첩 모델도 편집기 지원(자동완성 등)
+* 데이터 변환
+* 데이터 검증
+* 자동 문서화
+
+## 특별한 타입과 검증 { #special-types-and-validation }
+
+`str`, `int`, `float` 등과 같은 일반적인 단일 타입과는 별개로, `str`을 상속하는 더 복잡한 단일 타입을 사용할 수 있습니다.
+
+사용할 수 있는 모든 옵션을 보려면 [Pydantic의 Type Overview](https://docs.pydantic.dev/latest/concepts/types/)를 확인하세요. 다음 장에서 몇 가지 예제를 볼 수 있습니다.
+
+예를 들어 `Image` 모델에는 `url` 필드가 있으므로, 이를 `str` 대신 Pydantic의 `HttpUrl` 인스턴스로 선언할 수 있습니다:
+
+{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}
+
+이 문자열은 유효한 URL인지 검사되며, JSON Schema / OpenAPI에도 그에 맞게 문서화됩니다.
+
+## 서브모델 리스트를 갖는 어트리뷰트 { #attributes-with-lists-of-submodels }
+
+`list`, `set` 등의 서브타입으로 Pydantic 모델을 사용할 수도 있습니다:
+
+{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}
+
+아래와 같은 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` 키가 이제 이미지 객체 리스트를 갖는지 주목하세요.
+
+///
+
+## 깊게 중첩된 모델 { #deeply-nested-models }
+
+임의로 깊게 중첩된 모델을 정의할 수 있습니다:
+
+{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}
+
+/// info | 정보
+
+`Offer`가 `Item`의 리스트를 가지고, 그 `Item`이 다시 선택 사항인 `Image` 리스트를 갖는지 주목하세요
+
+///
+
+## 순수 리스트의 본문 { #bodies-of-pure-lists }
+
+예상되는 JSON 본문의 최상위 값이 JSON `array`(파이썬 `list`)라면, Pydantic 모델에서와 마찬가지로 함수의 매개변수에서 타입을 선언할 수 있습니다:
+
+```Python
+images: list[Image]
+```
+
+이를 아래처럼:
+
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
+
+## 어디서나 편집기 지원 { #editor-support-everywhere }
+
+그리고 어디서나 편집기 지원을 받을 수 있습니다.
+
+리스트 내부 항목의 경우에도:
+
+
+
+Pydantic 모델 대신 `dict`로 직접 작업한다면 이런 종류의 편집기 지원을 받을 수 없습니다.
+
+하지만 그 부분에 대해서도 걱정할 필요는 없습니다. 들어오는 dict는 자동으로 변환되고, 출력도 자동으로 JSON으로 변환됩니다.
+
+## 임의의 `dict` 본문 { #bodies-of-arbitrary-dicts }
+
+또한 키는 어떤 타입이고 값은 다른 타입인 `dict`로 본문을 선언할 수 있습니다.
+
+이렇게 하면 (Pydantic 모델을 사용하는 경우처럼) 유효한 필드/어트리뷰트 이름이 무엇인지 미리 알 필요가 없습니다.
+
+아직 모르는 키를 받으려는 경우에 유용합니다.
+
+---
+
+또 다른 유용한 경우는 다른 타입(예: `int`)의 키를 갖고 싶을 때입니다.
+
+여기서 그 경우를 볼 것입니다.
+
+이 경우, `int` 키와 `float` 값을 가진 한 어떤 `dict`든 받아들입니다:
+
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
+
+/// tip | 팁
+
+JSON은 키로 `str`만 지원한다는 것을 염두에 두세요.
+
+하지만 Pydantic은 자동 데이터 변환 기능이 있습니다.
+
+즉, API 클라이언트는 키로 문자열만 보낼 수 있더라도, 해당 문자열이 순수한 정수를 포함하기만 하면 Pydantic이 이를 변환하고 검증합니다.
+
+그리고 `weights`로 받는 `dict`는 실제로 `int` 키와 `float` 값을 갖게 됩니다.
+
+///
+
+## 요약 { #recap }
+
+**FastAPI**를 사용하면 Pydantic 모델이 제공하는 최대 유연성을 확보하면서 코드를 간단하고 짧고 우아하게 유지할 수 있습니다.
+
+하지만 아래의 모든 이점도 있습니다:
+
+* 편집기 지원(어디서나 자동완성!)
+* 데이터 변환(일명 파싱/직렬화)
+* 데이터 검증
+* 스키마 문서화
+* 자동 문서
diff --git a/docs/ko/docs/tutorial/body-updates.md b/docs/ko/docs/tutorial/body-updates.md
new file mode 100644
index 0000000000000..f9ea061a6e044
--- /dev/null
+++ b/docs/ko/docs/tutorial/body-updates.md
@@ -0,0 +1,100 @@
+# Body - 업데이트 { #body-updates }
+
+## `PUT`으로 교체 업데이트하기 { #update-replacing-with-put }
+
+항목을 업데이트하려면 [HTTP `PUT`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) 작업을 사용할 수 있습니다.
+
+`jsonable_encoder`를 사용해 입력 데이터를 JSON으로 저장할 수 있는 데이터로 변환할 수 있습니다(예: NoSQL 데이터베이스 사용 시). 예를 들어 `datetime`을 `str`로 변환하는 경우입니다.
+
+{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}
+
+`PUT`은 기존 데이터를 **대체**해야 하는 데이터를 받는 데 사용합니다.
+
+### 대체 시 주의사항 { #warning-about-replacing }
+
+즉, `PUT`으로 항목 `bar`를 업데이트하면서 다음과 같은 body를 보낸다면:
+
+```Python
+{
+ "name": "Barz",
+ "price": 3,
+ "description": None,
+}
+```
+
+이미 저장된 속성 `"tax": 20.2`가 포함되어 있지 않기 때문에, 입력 모델은 `"tax": 10.5`라는 기본값을 사용하게 됩니다.
+
+그리고 데이터는 그 “새로운” `tax` 값 `10.5`로 저장됩니다.
+
+## `PATCH`로 부분 업데이트하기 { #partial-updates-with-patch }
+
+[HTTP `PATCH`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) 작업을 사용해 데이터를 *부분적으로* 업데이트할 수도 있습니다.
+
+이는 업데이트하려는 데이터만 보내고, 나머지는 그대로 두는 것을 의미합니다.
+
+/// note | 참고
+
+`PATCH`는 `PUT`보다 덜 일반적으로 사용되고 덜 알려져 있습니다.
+
+그리고 많은 팀이 부분 업데이트에도 `PUT`만 사용합니다.
+
+여러분은 원하는 방식으로 **자유롭게** 사용할 수 있으며, **FastAPI**는 어떤 제한도 강제하지 않습니다.
+
+다만 이 가이드는 의도된 사용 방식이 대략 어떻게 되는지를 보여줍니다.
+
+///
+
+### Pydantic의 `exclude_unset` 파라미터 사용하기 { #using-pydantics-exclude-unset-parameter }
+
+부분 업데이트를 받으려면 Pydantic 모델의 `.model_dump()`에서 `exclude_unset` 파라미터를 사용하는 것이 매우 유용합니다.
+
+예: `item.model_dump(exclude_unset=True)`.
+
+이는 `item` 모델을 만들 때 실제로 설정된 데이터만 포함하는 `dict`를 생성하고, 기본값은 제외합니다.
+
+그 다음 이를 사용해 (요청에서 전송되어) 설정된 데이터만 포함하고 기본값은 생략한 `dict`를 만들 수 있습니다:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}
+
+### Pydantic의 `update` 파라미터 사용하기 { #using-pydantics-update-parameter }
+
+이제 `.model_copy()`를 사용해 기존 모델의 복사본을 만들고, 업데이트할 데이터가 들어있는 `dict`를 `update` 파라미터로 전달할 수 있습니다.
+
+예: `stored_item_model.model_copy(update=update_data)`:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}
+
+### 부분 업데이트 요약 { #partial-updates-recap }
+
+정리하면, 부분 업데이트를 적용하려면 다음을 수행합니다:
+
+* (선택 사항) `PUT` 대신 `PATCH`를 사용합니다.
+* 저장된 데이터를 조회합니다.
+* 그 데이터를 Pydantic 모델에 넣습니다.
+* 입력 모델에서 기본값이 제외된 `dict`를 생성합니다(`exclude_unset` 사용).
+ * 이렇게 하면 모델의 기본값으로 이미 저장된 값을 덮어쓰지 않고, 사용자가 실제로 설정한 값만 업데이트할 수 있습니다.
+* 저장된 모델의 복사본을 만들고, 받은 부분 업데이트로 해당 속성들을 갱신합니다(`update` 파라미터 사용).
+* 복사한 모델을 DB에 저장할 수 있는 형태로 변환합니다(예: `jsonable_encoder` 사용).
+ * 이는 모델의 `.model_dump()` 메서드를 다시 사용하는 것과 비슷하지만, JSON으로 변환 가능한 데이터 타입으로 값이 확실히 변환되도록 보장합니다(예: `datetime` → `str`).
+* 데이터를 DB에 저장합니다.
+* 업데이트된 모델을 반환합니다.
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *}
+
+/// tip | 팁
+
+동일한 기법을 HTTP `PUT` 작업에서도 실제로 사용할 수 있습니다.
+
+하지만 여기의 예시는 이런 사용 사례를 위해 만들어진 `PATCH`를 사용합니다.
+
+///
+
+/// note | 참고
+
+입력 모델은 여전히 검증된다는 점에 유의하세요.
+
+따라서 모든 속성을 생략할 수 있는 부분 업데이트를 받으려면, 모든 속성이 optional로 표시된(기본값을 가지거나 `None`을 기본값으로 가지는) 모델이 필요합니다.
+
+**업데이트**를 위한 “모든 값이 optional인” 모델과, **생성**을 위한 “필수 값이 있는” 모델을 구분하려면 [추가 모델](extra-models.md)에 설명된 아이디어를 사용할 수 있습니다.
+
+///
diff --git a/docs/ko/docs/tutorial/body.md b/docs/ko/docs/tutorial/body.md
new file mode 100644
index 0000000000000..d124b4bef03d2
--- /dev/null
+++ b/docs/ko/docs/tutorial/body.md
@@ -0,0 +1,166 @@
+# 요청 본문 { #request-body }
+
+클라이언트(브라우저라고 해봅시다)로부터 여러분의 API로 데이터를 보내야 할 때, **요청 본문**으로 보냅니다.
+
+**요청** 본문은 클라이언트에서 API로 보내지는 데이터입니다. **응답** 본문은 API가 클라이언트로 보내는 데이터입니다.
+
+여러분의 API는 대부분의 경우 **응답** 본문을 보내야 합니다. 하지만 클라이언트는 항상 **요청 본문**을 보낼 필요는 없고, 때로는 (쿼리 매개변수와 함께) 어떤 경로만 요청하고 본문은 보내지 않을 수도 있습니다.
+
+**요청** 본문을 선언하기 위해서 모든 강력함과 이점을 갖춘 [Pydantic](https://docs.pydantic.dev/) 모델을 사용합니다.
+
+/// info | 정보
+
+데이터를 보내기 위해, (좀 더 보편적인) `POST`, `PUT`, `DELETE` 혹은 `PATCH` 중에 하나를 사용하는 것이 좋습니다.
+
+`GET` 요청에 본문을 담아 보내는 것은 명세서에 정의되지 않은 행동입니다. 그럼에도 불구하고, 이 방식은 아주 복잡한/극한의 사용 상황에서만 FastAPI에 의해 지원됩니다.
+
+`GET` 요청에 본문을 담는 것은 권장되지 않기에, Swagger UI같은 대화형 문서에서는 `GET` 사용시 담기는 본문에 대한 문서를 표시하지 않으며, 중간에 있는 프록시는 이를 지원하지 않을 수도 있습니다.
+
+///
+
+## Pydantic의 `BaseModel` 임포트 { #import-pydantics-basemodel }
+
+먼저 `pydantic`에서 `BaseModel`를 임포트해야 합니다:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[2] *}
+
+## 여러분의 데이터 모델 만들기 { #create-your-data-model }
+
+`BaseModel`를 상속받은 클래스로 여러분의 데이터 모델을 선언합니다.
+
+모든 어트리뷰트에 대해 표준 파이썬 타입을 사용합니다:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}
+
+
+쿼리 매개변수를 선언할 때와 같이, 모델 어트리뷰트가 기본 값을 가지고 있어도 이는 필수가 아닙니다. 그외에는 필수입니다. 그저 `None`을 사용하여 선택적으로 만들 수 있습니다.
+
+예를 들면, 위의 이 모델은 JSON "`object`" (혹은 파이썬 `dict`)을 다음과 같이 선언합니다:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "An optional description",
+ "price": 45.2,
+ "tax": 3.5
+}
+```
+
+...`description`과 `tax`는 (기본 값이 `None`으로 되어 있어) 선택적이기 때문에, 이 JSON "`object`"는 다음과 같은 상황에서도 유효합니다:
+
+```JSON
+{
+ "name": "Foo",
+ "price": 45.2
+}
+```
+
+## 매개변수로서 선언하기 { #declare-it-as-a-parameter }
+
+여러분의 *경로 처리*에 추가하기 위해, 경로 매개변수 그리고 쿼리 매개변수에서 선언했던 것과 같은 방식으로 선언하면 됩니다.
+
+{* ../../docs_src/body/tutorial001_py310.py hl[16] *}
+
+...그리고 만들어낸 모델인 `Item`으로 타입을 선언합니다.
+
+## 결과 { #results }
+
+위에서의 단순한 파이썬 타입 선언으로, **FastAPI**는 다음과 같이 동작합니다:
+
+* 요청의 본문을 JSON으로 읽어 들입니다.
+* (필요하다면) 대응되는 타입으로 변환합니다.
+* 데이터를 검증합니다.
+ * 만약 데이터가 유효하지 않다면, 정확히 어떤 것이 그리고 어디에서 데이터가 잘 못 되었는지 지시하는 친절하고 명료한 에러를 반환할 것입니다.
+* 매개변수 `item`에 포함된 수신 데이터를 제공합니다.
+ * 함수 내에서 매개변수를 `Item` 타입으로 선언했기 때문에, 모든 어트리뷰트와 그에 대한 타입에 대한 편집기 지원(완성 등)을 또한 받을 수 있습니다.
+* 여러분의 모델을 위한 [JSON Schema](https://json-schema.org) 정의를 생성합니다. 여러분의 프로젝트에 적합하다면 여러분이 사용하고 싶은 곳 어디에서나 사용할 수 있습니다.
+* 이러한 스키마는, 생성된 OpenAPI 스키마 일부가 될 것이며, 자동 문서화 UIs에 사용됩니다.
+
+## 자동 문서화 { #automatic-docs }
+
+모델의 JSON 스키마는 생성된 OpenAPI 스키마에 포함되며 대화형 API 문서에 표시됩니다:
+
+
+
+이를 필요로 하는 각각의 *경로 처리* 내부의 API 문서에도 사용됩니다:
+
+
+
+## 편집기 지원 { #editor-support }
+
+편집기에서, 함수 내에서 타입 힌트와 완성을 어디서나 (만약 Pydantic model 대신에 `dict`을 받을 경우 나타나지 않을 수 있습니다) 받을 수 있습니다:
+
+
+
+잘못된 타입 연산에 대한 에러 확인도 받을 수 있습니다:
+
+
+
+단순한 우연이 아닙니다. 프레임워크 전체가 이러한 디자인을 중심으로 설계되었습니다.
+
+그 어떤 구현 전에, 모든 편집기에서 작동할 수 있도록 보장하기 위해 설계 단계에서 혹독하게 테스트되었습니다.
+
+이를 지원하기 위해 Pydantic 자체에서 몇몇 변경점이 있었습니다.
+
+이전 스크린샷은 [Visual Studio Code](https://code.visualstudio.com)로 찍은 것입니다.
+
+하지만 똑같은 편집기 지원을 [PyCharm](https://www.jetbrains.com/pycharm/)와 대부분의 다른 파이썬 편집기에서도 받을 수 있습니다:
+
+
+
+/// tip | 팁
+
+만약 [PyCharm](https://www.jetbrains.com/pycharm/)를 편집기로 사용한다면, [Pydantic PyCharm Plugin](https://github.com/koxudaxi/pydantic-pycharm-plugin/)을 사용할 수 있습니다.
+
+다음 사항을 포함해 Pydantic 모델에 대한 편집기 지원을 향상시킵니다:
+
+* auto-completion
+* type checks
+* refactoring
+* searching
+* inspections
+
+///
+
+## 모델 사용하기 { #use-the-model }
+
+함수 안에서 모델 객체의 모든 어트리뷰트에 직접 접근 가능합니다:
+
+{* ../../docs_src/body/tutorial002_py310.py *}
+
+## 요청 본문 + 경로 매개변수 { #request-body-path-parameters }
+
+경로 매개변수와 요청 본문을 동시에 선언할 수 있습니다.
+
+**FastAPI**는 경로 매개변수와 일치하는 함수 매개변수가 **경로에서 가져와야 한다**는 것을 인지하며, Pydantic 모델로 선언된 그 함수 매개변수는 **요청 본문에서 가져와야 한다**는 것을 인지할 것입니다.
+
+{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}
+
+
+## 요청 본문 + 경로 + 쿼리 매개변수 { #request-body-path-query-parameters }
+
+**본문**, **경로** 그리고 **쿼리** 매개변수 모두 동시에 선언할 수도 있습니다.
+
+**FastAPI**는 각각을 인지하고 데이터를 올바른 위치에 가져올 것입니다.
+
+{* ../../docs_src/body/tutorial004_py310.py hl[16] *}
+
+함수 매개변수는 다음을 따라서 인지하게 됩니다:
+
+* 만약 매개변수가 **경로**에도 선언되어 있다면, 이는 경로 매개변수로 사용될 것입니다.
+* 만약 매개변수가 (`int`, `float`, `str`, `bool` 등과 같은) **유일한 타입**으로 되어있으면, **쿼리** 매개변수로 해석될 것입니다.
+* 만약 매개변수가 **Pydantic 모델** 타입으로 선언되어 있으면, 요청 **본문**으로 해석될 것입니다.
+
+/// note | 참고
+
+FastAPI는 `q`의 값이 필요없음을 기본 값 `= None` 때문에 알게 됩니다.
+
+`str | None`은 FastAPI가 값이 필수인지 아닌지를 판단하기 위해 사용하지 않습니다. 기본 값이 `= None`이므로 필수가 아님을 알게 됩니다.
+
+하지만 타입 어노테이션을 추가하면 편집기가 더 나은 지원을 제공하고 오류를 감지할 수 있습니다.
+
+///
+
+## Pydantic없이 { #without-pydantic }
+
+만약 Pydantic 모델을 사용하고 싶지 않다면, **Body** 매개변수를 사용할 수도 있습니다. [Body - Multiple Parameters: Singular values in body](body-multiple-params.md#singular-values-in-body) 문서를 확인하세요.
diff --git a/docs/ko/docs/tutorial/cookie-param-models.md b/docs/ko/docs/tutorial/cookie-param-models.md
new file mode 100644
index 0000000000000..70b76e09cefab
--- /dev/null
+++ b/docs/ko/docs/tutorial/cookie-param-models.md
@@ -0,0 +1,76 @@
+# 쿠키 매개변수 모델 { #cookie-parameter-models }
+
+관련있는 **쿠키**들의 그룹이 있는 경우, **Pydantic 모델**을 생성하여 선언할 수 있습니다. 🍪
+
+이를 통해 **여러 위치**에서 **모델을 재사용** 할 수 있고 모든 매개변수에 대한 유효성 검사 및 메타데이터를 한 번에 선언할 수도 있습니다. 😎
+
+/// note | 참고
+
+이 기능은 FastAPI 버전 `0.115.0` 이후부터 지원됩니다. 🤓
+
+///
+
+/// tip | 팁
+
+동일한 기술이 `Query`, `Cookie`, 그리고 `Header`에 적용됩니다. 😎
+
+///
+
+## Pydantic 모델을 사용한 쿠키 { #cookies-with-a-pydantic-model }
+
+**Pydantic 모델**에 필요한 **쿠키** 매개변수를 선언한 다음, 해당 매개변수를 `Cookie`로 선언합니다:
+
+{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}
+
+**FastAPI**는 요청에서 받은 **쿠키**에서 **각 필드**에 대한 데이터를 **추출**하고 정의한 Pydantic 모델을 줍니다.
+
+## 문서 확인하기 { #check-the-docs }
+
+문서 UI `/docs`에서 정의한 쿠키를 볼 수 있습니다:
+
+
+
+
+---
+
+Pycharm을 사용하는 경우 다음을 수행할 수 있습니다
+
+* "Run" 메뉴를 엽니다.
+* "Debug..." 옵션을 선택합니다.
+* 그러면 상황에 맞는 메뉴가 나타납니다.
+* 디버그할 파일을 선택합니다(이 경우 `main.py`).
+
+그런 다음 **FastAPI** 코드로 서버를 시작하고 중단점 등에서 중지합니다.
+
+다음과 같이 표시됩니다.
+
+
diff --git a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md
index bbf3a82838c70..83749f7b0afa4 100644
--- a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md
+++ b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -1,40 +1,30 @@
-# 의존성으로서의 클래스
+# 의존성으로서의 클래스 { #classes-as-dependencies }
-**의존성 주입** 시스템에 대해 자세히 살펴보기 전에 이전 예제를 업그레이드 해보겠습니다.
+**의존성 주입** 시스템에 대해 더 깊이 살펴보기 전에, 이전 예제를 업그레이드해 보겠습니다.
-## 이전 예제의 `딕셔너리`
+## 이전 예제의 `dict` { #a-dict-from-the-previous-example }
-이전 예제에서, 우리는 의존성(의존 가능한) 함수에서 `딕셔너리`객체를 반환하고 있었습니다:
+이전 예제에서는 의존성("dependable")에서 `dict`를 반환하고 있었습니다:
-=== "파이썬 3.6 이상"
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *}
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+하지만 그러면 *경로 처리 함수*의 매개변수 `commons`에서 `dict`를 받게 됩니다.
-=== "파이썬 3.10 이상"
+그리고 에디터는 `dict`의 키와 값 타입을 알 수 없기 때문에 `dict`에 대해서는 (완성 기능 같은) 많은 지원을 제공할 수 없다는 것을 알고 있습니다.
- ```Python hl_lines="7"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+더 나은 방법이 있습니다...
-우리는 *경로 작동 함수*의 매개변수 `commons`에서 `딕셔너리` 객체를 얻습니다.
+## 의존성이 되기 위한 조건 { #what-makes-a-dependency }
-그리고 우리는 에디터들이 `딕셔너리` 객체의 키나 밸류의 자료형을 알 수 없기 때문에 자동 완성과 같은 기능을 제공해 줄 수 없다는 것을 알고 있습니다.
+지금까지는 함수로 선언된 의존성을 봤습니다.
-더 나은 방법이 있을 것 같습니다...
+하지만 그것만이 의존성을 선언하는 유일한 방법은 아닙니다(아마도 더 일반적이긴 하겠지만요).
-## 의존성으로 사용 가능한 것
+핵심 요소는 의존성이 "호출 가능(callable)"해야 한다는 것입니다.
-지금까지 함수로 선언된 의존성을 봐왔습니다.
+파이썬에서 "**호출 가능(callable)**"이란 파이썬이 함수처럼 "호출"할 수 있는 모든 것입니다.
-아마도 더 일반적이기는 하겠지만 의존성을 선언하는 유일한 방법은 아닙니다.
-
-핵심 요소는 의존성이 "호출 가능"해야 한다는 것입니다
-
-파이썬에서의 "**호출 가능**"은 파이썬이 함수처럼 "호출"할 수 있는 모든 것입니다.
-
-따라서, 만약 당신이 `something`(함수가 아닐 수도 있음) 객체를 가지고 있고,
+따라서 `something`(함수가 _아닐_ 수도 있습니다)이라는 객체가 있고, 다음처럼 "호출"(실행)할 수 있다면:
```Python
something()
@@ -46,11 +36,11 @@ something()
something(some_argument, some_keyword_argument="foo")
```
-상기와 같은 방식으로 "호출(실행)" 할 수 있다면 "호출 가능"이 됩니다.
+그것은 "호출 가능(callable)"입니다.
-## 의존성으로서의 클래스
+## 의존성으로서의 클래스 { #classes-as-dependencies_1 }
-파이썬 클래스의 인스턴스를 생성하기 위해 사용하는 것과 동일한 문법을 사용한다는 걸 알 수 있습니다.
+파이썬 클래스의 인스턴스를 만들 때도 같은 문법을 사용한다는 것을 알 수 있을 겁니다.
예를 들어:
@@ -63,182 +53,236 @@ class Cat:
fluffy = Cat(name="Mr Fluffy")
```
-이 경우에 `fluffy`는 클래스 `Cat`의 인스턴스입니다. 그리고 우리는 `fluffy`를 만들기 위해서 `Cat`을 "호출"했습니다.
-
-따라서, 파이썬 클래스는 **호출 가능**합니다.
+이 경우 `fluffy`는 클래스 `Cat`의 인스턴스입니다.
-그래서 **FastAPI**에서는 파이썬 클래스를 의존성으로 사용할 수 있습니다.
+그리고 `fluffy`를 만들기 위해 `Cat`을 "호출"하고 있습니다.
-FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래스 또는 다른 모든 것)과 정의된 매개변수들입니다.
+따라서 파이썬 클래스도 **호출 가능(callable)**합니다.
-"호출 가능"한 것을 의존성으로서 **FastAPI**에 전달하면, 그 "호출 가능"한 것의 매개변수들을 분석한 후 이를 *경로 동작 함수*를 위한 매개변수와 동일한 방식으로 처리합니다. 하위-의존성 또한 같은 방식으로 처리합니다.
+그러면 **FastAPI**에서는 파이썬 클래스를 의존성으로 사용할 수 있습니다.
-매개변수가 없는 "호출 가능"한 것 역시 매개변수가 없는 *경로 동작 함수*와 동일한 방식으로 적용됩니다.
+FastAPI가 실제로 확인하는 것은 그것이 "호출 가능(callable)"(함수, 클래스, 또는 다른 무엇이든)한지와 정의된 매개변수들입니다.
-그래서, 우리는 위 예제에서의 `common_paramenters` 의존성을 클래스 `CommonQueryParams`로 바꿀 수 있습니다.
+**FastAPI**에서 "호출 가능(callable)"한 것을 의존성으로 넘기면, 그 "호출 가능(callable)"한 것의 매개변수들을 분석하고 *경로 처리 함수*의 매개변수와 동일한 방식으로 처리합니다. 하위 의존성도 포함해서요.
-=== "파이썬 3.6 이상"
+이것은 매개변수가 전혀 없는 callable에도 적용됩니다. 매개변수가 없는 *경로 처리 함수*에 적용되는 것과 동일합니다.
- ```Python hl_lines="11-15"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+그러면 위의 의존성("dependable") `common_parameters`를 클래스 `CommonQueryParams`로 바꿀 수 있습니다:
-=== "파이썬 3.10 이상"
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *}
- ```Python hl_lines="9-13"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+클래스의 인스턴스를 만들 때 사용하는 `__init__` 메서드에 주목하세요:
-클래스의 인스턴스를 생성하는 데 사용되는 `__init__` 메서드에 주목하기 바랍니다:
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *}
-=== "파이썬 3.6 이상"
+...이전의 `common_parameters`와 동일한 매개변수를 가지고 있습니다:
- ```Python hl_lines="12"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *}
-=== "파이썬 3.10 이상"
+이 매개변수들이 **FastAPI**가 의존성을 "해결"하는 데 사용할 것들입니다.
- ```Python hl_lines="10"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+두 경우 모두 다음을 갖게 됩니다:
-...이전 `common_parameters`와 동일한 매개변수를 가집니다:
+* `str`인 선택적 쿼리 매개변수 `q`.
+* 기본값이 `0`인 `int` 쿼리 매개변수 `skip`.
+* 기본값이 `100`인 `int` 쿼리 매개변수 `limit`.
-=== "파이썬 3.6 이상"
+두 경우 모두 데이터는 변환되고, 검증되며, OpenAPI 스키마에 문서화되는 등 여러 처리가 적용됩니다.
- ```Python hl_lines="9"
- {!> ../../../docs_src/dependencies/tutorial001.py!}
- ```
+## 사용하기 { #use-it }
-=== "파이썬 3.10 이상"
+이제 이 클래스를 사용해 의존성을 선언할 수 있습니다.
- ```Python hl_lines="6"
- {!> ../../../docs_src/dependencies/tutorial001_py310.py!}
- ```
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *}
-이 매개변수들은 **FastAPI**가 의존성을 "해결"하기 위해 사용할 것입니다
+**FastAPI**는 `CommonQueryParams` 클래스를 호출합니다. 그러면 해당 클래스의 "인스턴스"가 생성되고, 그 인스턴스가 함수의 매개변수 `commons`로 전달됩니다.
-함수와 클래스 두 가지 방식 모두, 아래 요소를 갖습니다:
+## 타입 어노테이션 vs `Depends` { #type-annotation-vs-depends }
-* `문자열`이면서 선택사항인 쿼리 매개변수 `q`.
-* 기본값이 `0`이면서 `정수형`인 쿼리 매개변수 `skip`
-* 기본값이 `100`이면서 `정수형`인 쿼리 매개변수 `limit`
+위 코드에서 `CommonQueryParams`를 두 번 작성하는 방식에 주목하세요:
-두 가지 방식 모두, 데이터는 변환, 검증되고 OpenAPI 스키마에 문서화됩니다.
+//// tab | Python 3.10+
-## 사용해봅시다!
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
-이제 아래의 클래스를 이용해서 의존성을 정의할 수 있습니다.
+////
-=== "파이썬 3.6 이상"
+//// tab | Python 3.10+ Annotated 미사용
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial002.py!}
- ```
+/// tip | 팁
-=== "파이썬 3.10 이상"
+가능하다면 `Annotated` 버전을 사용하는 것을 권장합니다.
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial002_py310.py!}
- ```
+///
-**FastAPI**는 `CommonQueryParams` 클래스를 호출합니다. 이것은 해당 클래스의 "인스턴스"를 생성하고 그 인스턴스는 함수의 매개변수 `commons`로 전달됩니다.
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
-## 타입 힌팅 vs `Depends`
+////
-위 코드에서 `CommonQueryParams`를 두 번 작성한 방식에 주목하십시오:
+마지막 `CommonQueryParams`는, 다음에서:
```Python
-commons: CommonQueryParams = Depends(CommonQueryParams)
+... Depends(CommonQueryParams)
```
-마지막 `CommonQueryParams` 변수를 보면:
+...**FastAPI**가 실제로 무엇이 의존성인지 알기 위해 사용하는 것입니다.
+
+FastAPI는 여기에서 선언된 매개변수들을 추출하고, 실제로 이것을 호출합니다.
+
+---
+
+이 경우 첫 번째 `CommonQueryParams`는 다음에서:
+
+//// tab | Python 3.10+
```Python
-... = Depends(CommonQueryParams)
+commons: Annotated[CommonQueryParams, ...
```
-... **FastAPI**가 실제로 어떤 것이 의존성인지 알기 위해서 사용하는 방법입니다.
-FastAPI는 선언된 매개변수들을 추출할 것이고 실제로 이 변수들을 호출할 것입니다.
+////
----
+//// tab | Python 3.10+ Annotated 미사용
+
+/// tip | 팁
+
+가능하다면 `Annotated` 버전을 사용하는 것을 권장합니다.
-이 경우에, 첫번째 `CommonQueryParams` 변수를 보면:
+///
```Python
commons: CommonQueryParams ...
```
-... **FastAPI**는 `CommonQueryParams` 변수에 어떠한 특별한 의미도 부여하지 않습니다. FastAPI는 이 변수를 데이터 변환, 검증 등에 활용하지 않습니다. (활용하려면 `= Depends(CommonQueryParams)`를 사용해야 합니다.)
+////
+
+...**FastAPI**에 특별한 의미가 없습니다. FastAPI는 이를 데이터 변환, 검증 등에 사용하지 않습니다(그런 용도로는 `Depends(CommonQueryParams)`를 사용하고 있기 때문입니다).
+
+실제로는 이렇게만 작성해도 됩니다:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[Any, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ Annotated 미사용
+
+/// tip | 팁
+
+가능하다면 `Annotated` 버전을 사용하는 것을 권장합니다.
-사실 아래와 같이 작성해도 무관합니다:
+///
```Python
commons = Depends(CommonQueryParams)
```
-..전체적인 코드는 아래와 같습니다:
+////
-=== "파이썬 3.6 이상"
+...다음과 같이요:
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial003.py!}
- ```
+{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *}
-=== "파이썬 3.10 이상"
+하지만 타입을 선언하는 것을 권장합니다. 그러면 에디터가 매개변수 `commons`에 무엇이 전달되는지 알 수 있고, 코드 완성, 타입 체크 등에서 도움을 받을 수 있습니다:
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial003_py310.py!}
- ```
+
-그러나 자료형을 선언하면 에디터가 매개변수 `commons`로 전달될 것이 무엇인지 알게 되고, 이를 통해 코드 완성, 자료형 확인 등에 도움이 될 수 있으므로 권장됩니다.
+## 단축 { #shortcut }
-
+하지만 `CommonQueryParams`를 두 번 작성하는 코드 반복이 있다는 것을 볼 수 있습니다:
-## 코드 단축
+//// tab | Python 3.10+
-그러나 여기 `CommonQueryParams`를 두 번이나 작성하는, 코드 반복이 있다는 것을 알 수 있습니다:
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ Annotated 미사용
+
+/// tip | 팁
+
+가능하다면 `Annotated` 버전을 사용하는 것을 권장합니다.
+
+///
```Python
commons: CommonQueryParams = Depends(CommonQueryParams)
```
-**FastAPI**는 *특히* 의존성이 **FastAPI**가 클래스 자체의 인스턴스를 생성하기 위해 "호출"하는 클래스인 경우, 조금 더 쉬운 방법을 제공합니다.
+////
-이러한 특정한 경우에는 아래처럼 사용할 수 있습니다:
+**FastAPI**는 이런 경우를 위한 단축 방법을 제공합니다. 이때 의존성은 *특히* **FastAPI**가 "호출"해서 클래스 자체의 인스턴스를 만들도록 하는 클래스입니다.
-이렇게 쓰는 것 대신:
+이 특정한 경우에는 다음과 같이 할 수 있습니다:
+
+다음처럼 작성하는 대신:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ Annotated 미사용
+
+/// tip | 팁
+
+가능하다면 `Annotated` 버전을 사용하는 것을 권장합니다.
+
+///
```Python
commons: CommonQueryParams = Depends(CommonQueryParams)
```
-...이렇게 쓸 수 있습니다.:
+////
+
+...이렇게 작성합니다:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
+
+////
+
+//// tab | Python 3.10+ Annotated 미사용
+
+/// tip | 팁
+
+가능하다면 `Annotated` 버전을 사용하는 것을 권장합니다.
+
+///
```Python
commons: CommonQueryParams = Depends()
```
-의존성을 매개변수의 타입으로 선언하는 경우 `Depends(CommonQueryParams)`처럼 클래스 이름 전체를 *다시* 작성하는 대신, 매개변수를 넣지 않은 `Depends()`의 형태로 사용할 수 있습니다.
+////
-아래에 같은 예제가 있습니다:
+의존성을 매개변수의 타입으로 선언하고, `Depends(CommonQueryParams)` 안에 클래스 전체를 *다시* 작성하는 대신 매개변수 없이 `Depends()`를 사용합니다.
-=== "파이썬 3.6 이상"
+그러면 같은 예제는 다음처럼 보일 겁니다:
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
- ```
+{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *}
-=== "파이썬 3.10 이상"
+...그리고 **FastAPI**는 무엇을 해야 하는지 알게 됩니다.
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
+/// tip | 팁
-...이렇게 코드를 단축하여도 **FastAPI**는 무엇을 해야하는지 알고 있습니다.
+도움이 되기보다 더 헷갈린다면, 무시하세요. 이건 *필수*가 아닙니다.
-!!! tip "팁"
- 만약 이것이 도움이 되기보다 더 헷갈리게 만든다면, 잊어버리십시오. 이것이 반드시 필요한 것은 아닙니다.
+그저 단축 방법일 뿐입니다. **FastAPI**는 코드 반복을 최소화하도록 도와주는 것을 중요하게 생각하기 때문입니다.
- 이것은 단지 손쉬운 방법일 뿐입니다. 왜냐하면 **FastAPI**는 코드 반복을 최소화할 수 있는 방법을 고민하기 때문입니다.
+///
diff --git a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
new file mode 100644
index 0000000000000..880a47157f750
--- /dev/null
+++ b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -0,0 +1,69 @@
+# 경로 처리 데코레이터에서의 의존성 { #dependencies-in-path-operation-decorators }
+
+몇몇 경우에는, *경로 처리 함수* 안에서 의존성의 반환 값이 필요하지 않습니다.
+
+또는 의존성이 값을 반환하지 않습니다.
+
+그러나 여전히 실행/해결될 필요가 있습니다.
+
+그런 경우에, `Depends`를 사용하여 *경로 처리 함수*의 매개변수로 선언하는 대신 *경로 처리 데코레이터*에 `dependencies`의 `list`를 추가할 수 있습니다.
+
+## *경로 처리 데코레이터*에 `dependencies` 추가하기 { #add-dependencies-to-the-path-operation-decorator }
+
+*경로 처리 데코레이터*는 선택적인 인자 `dependencies`를 받습니다.
+
+`Depends()`로 된 `list`이어야 합니다:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
+
+이러한 의존성들은 기존 의존성들과 같은 방식으로 실행/해결됩니다. 그러나 값은 (무엇이든 반환한다면) *경로 처리 함수*에 제공되지 않습니다.
+
+/// tip | 팁
+
+일부 편집기에서는 사용되지 않는 함수 매개변수를 검사하고 오류로 표시합니다.
+
+*경로 처리 데코레이터*에서 이러한 `dependencies`를 사용하면 편집기/도구 오류를 피하면서도 실행되도록 할 수 있습니다.
+
+또한 코드에서 사용되지 않는 매개변수를 보고 불필요하다고 생각할 수 있는 새로운 개발자의 혼란을 방지하는데 도움이 될 수 있습니다.
+
+///
+
+/// info | 정보
+
+이 예시에서 `X-Key`와 `X-Token`이라는 커스텀 헤더를 만들어 사용했습니다.
+
+그러나 실제로 보안을 구현할 때는 통합된 [보안 유틸리티 (다음 챕터)](../security/index.md)를 사용하는 것이 더 많은 이점을 얻을 수 있습니다.
+
+///
+
+## 의존성 오류와 값 반환하기 { #dependencies-errors-and-return-values }
+
+평소에 사용하던대로 같은 의존성 *함수*를 사용할 수 있습니다.
+
+### 의존성 요구사항 { #dependency-requirements }
+
+(헤더같은) 요청 요구사항이나 하위-의존성을 선언할 수 있습니다:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
+
+### 오류 발생시키기 { #raise-exceptions }
+
+다음 의존성은 기존 의존성과 동일하게 예외를 `raise`할 수 있습니다:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
+
+### 값 반환하기 { #return-values }
+
+값을 반환하거나, 그러지 않을 수 있으며 값은 사용되지 않습니다.
+
+그래서 이미 다른 곳에서 사용된 (값을 반환하는) 일반적인 의존성을 재사용할 수 있고, 비록 값은 사용되지 않지만 의존성은 실행될 것입니다:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
+
+## *경로 처리* 모음에 대한 의존성 { #dependencies-for-a-group-of-path-operations }
+
+나중에 여러 파일을 가지고 있을 수 있는 더 큰 애플리케이션을 구조화하는 법([더 큰 애플리케이션 - 여러 파일들](../../tutorial/bigger-applications.md))을 읽을 때, *경로 처리* 모음에 대한 단일 `dependencies` 매개변수를 선언하는 법에 대해서 배우게 될 것입니다.
+
+## 전역 의존성 { #global-dependencies }
+
+다음으로 각 *경로 처리*에 적용되도록 `FastAPI` 애플리케이션 전체에 의존성을 추가하는 법을 볼 것입니다.
diff --git a/docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md
new file mode 100644
index 0000000000000..56f690f593906
--- /dev/null
+++ b/docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -0,0 +1,289 @@
+# `yield`를 사용하는 의존성 { #dependencies-with-yield }
+
+FastAPI는 작업 완료 후 추가 단계를 수행하는 의존성을 지원합니다.
+
+이를 구현하려면 `return` 대신 `yield`를 사용하고, 추가로 실행할 단계 (코드)를 그 뒤에 작성하세요.
+
+/// tip
+
+각 의존성마다 `yield`는 한 번만 사용해야 합니다.
+
+///
+
+/// note | 기술 세부사항
+
+다음과 함께 사용할 수 있는 모든 함수:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) 또는
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+는 **FastAPI**의 의존성으로 사용할 수 있습니다.
+
+사실, FastAPI는 내부적으로 이 두 데코레이터를 사용합니다.
+
+///
+
+## `yield`를 사용하는 데이터베이스 의존성 { #a-database-dependency-with-yield }
+
+예를 들어, 이 기능을 사용하면 데이터베이스 세션을 생성하고 작업이 끝난 후에 세션을 종료할 수 있습니다.
+
+응답을 생성하기 전에는 `yield`문을 포함하여 그 이전의 코드만이 실행됩니다:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
+
+yield된 값은 *경로 처리* 및 다른 의존성들에 주입되는 값 입니다:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
+
+`yield`문 다음의 코드는 응답을 생성한 후 실행됩니다:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
+
+/// tip
+
+`async` 함수와 일반 함수 모두 사용할 수 있습니다.
+
+**FastAPI**는 일반 의존성과 마찬가지로 각각의 함수를 올바르게 처리할 것입니다.
+
+///
+
+## `yield`와 `try`를 사용하는 의존성 { #a-dependency-with-yield-and-try }
+
+`yield`를 사용하는 의존성에서 `try` 블록을 사용한다면, 의존성을 사용하는 도중 발생한 모든 예외를 받을 수 있습니다.
+
+예를 들어, 다른 의존성이나 *경로 처리*의 중간에 데이터베이스 트랜잭션 "롤백"이 발생하거나 다른 오류가 발생한다면, 해당 예외를 의존성에서 받을 수 있습니다.
+
+따라서, 의존성 내에서 `except SomeException`을 사용하여 특정 예외를 처리할 수 있습니다.
+
+마찬가지로, `finally`를 사용하여 예외 발생 여부와 관계 없이 종료 단계까 실행되도록 할 수 있습니다.
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
+
+## `yield`를 사용하는 하위 의존성 { #sub-dependencies-with-yield }
+
+모든 크기와 형태의 하위 의존성과 하위 의존성의 "트리"도 가질 수 있으며, 이들 모두가 `yield`를 사용할 수 있습니다.
+
+**FastAPI**는 `yield`를 사용하는 각 의존성의 "종료 코드"가 올바른 순서로 실행되도록 보장합니다.
+
+예를 들어, `dependency_c`는 `dependency_b`에 의존할 수 있고, `dependency_b`는 `dependency_a`에 의존할 수 있습니다.
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
+
+이들 모두는 `yield`를 사용할 수 있습니다.
+
+이 경우 `dependency_c`는 종료 코드를 실행하기 위해, `dependency_b`의 값 (여기서는 `dep_b`로 명명)이 여전히 사용 가능해야 합니다.
+
+그리고, `dependency_b`는 종료 코드를 위해 `dependency_a`의 값 (여기서는 `dep_a`로 명명) 이 사용 가능해야 합니다.
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
+
+같은 방식으로, `yield`를 사용하는 의존성과 `return`을 사용하는 의존성을 함께 사용할 수 있으며, 이들 중 일부가 다른 것들에 의존할 수 있습니다.
+
+그리고 `yield`를 사용하는 다른 여러 의존성을 필요로 하는 단일 의존성을 가질 수도 있습니다.
+
+원하는 의존성을 원하는 대로 조합할 수 있습니다.
+
+**FastAPI**는 모든 것이 올바른 순서로 실행되도록 보장합니다.
+
+/// note | 기술 세부사항
+
+파이썬의 [Context Managers](https://docs.python.org/3/library/contextlib.html) 덕분에 이 기능이 작동합니다.
+
+**FastAPI**는 이를 내부적으로 사용하여 이를 달성합니다.
+
+///
+
+## `yield`와 `HTTPException`를 사용하는 의존성 { #dependencies-with-yield-and-httpexception }
+
+`yield`를 사용하는 의존성에서 `try` 블록을 사용해 코드를 실행하고, 그 다음 `finally` 뒤에 종료 코드를 실행할 수 있다는 것을 보았습니다.
+
+또한 `except`를 사용해 발생한 예외를 잡고 그에 대해 무언가를 할 수도 있습니다.
+
+예를 들어, `HTTPException` 같은 다른 예외를 발생시킬 수 있습니다.
+
+/// tip
+
+이는 다소 고급 기술이며, 대부분의 경우 실제로는 필요하지 않을 것입니다. 예를 들어, *경로 처리 함수* 등 나머지 애플리케이션 코드 내부에서 예외 (`HTTPException` 포함)를 발생시킬 수 있기 때문입니다.
+
+하지만 필요한 경우 사용할 수 있습니다. 🤓
+
+///
+
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
+
+예외를 잡고 그에 기반해 사용자 정의 응답을 생성하려면, [사용자 정의 예외 처리기](../handling-errors.md#install-custom-exception-handlers)를 생성하세요.
+
+## `yield`와 `except`를 사용하는 의존성 { #dependencies-with-yield-and-except }
+
+`yield`를 사용하는 의존성에서 `except`를 사용하여 예외를 포착하고 예외를 다시 발생시키지 않거나 (또는 새 예외를 발생시키지 않으면), FastAPI는 일반적인 Python에서와 마찬가지로 예외가 있었다는 것을 알아차릴 수 없습니다:
+
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
+
+이 경우, `HTTPException`이나 유사한 예외를 발생시키지 않기 때문에 클라이언트는 마땅히 *HTTP 500 Internal Server Error* 응답을 보게 되지만, 서버에는 어떤 오류였는지에 대한 **로그**나 다른 표시가 **전혀 남지 않게 됩니다**. 😱
+
+### `yield`와 `except`를 사용하는 의존성에서 항상 `raise` 하기 { #always-raise-in-dependencies-with-yield-and-except }
+
+`yield`가 있는 의존성에서 예외를 잡았을 때, 다른 `HTTPException`이나 유사한 예외를 발생시키는 것이 아니라면, **원래 예외를 다시 발생시켜야 합니다**.
+
+`raise`를 사용하여 동일한 예외를 다시 발생시킬 수 있습니다:
+
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
+
+이제 클라이언트는 동일한 *HTTP 500 Internal Server Error* 응답을 받게 되지만, 서버 로그에는 사용자 정의 `InternalError`가 기록됩니다. 😎
+
+## `yield`를 사용하는 의존성의 실행 순서 { #execution-of-dependencies-with-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,operation: Can raise exceptions, including HTTPException
+ client ->> dep: Start request
+ Note over dep: Run code up to yield
+ opt raise Exception
+ dep -->> handler: Raise Exception
+ handler -->> client: HTTP error response
+ end
+ dep ->> operation: Run dependency, e.g. DB session
+ opt raise
+ operation -->> dep: Raise Exception (e.g. HTTPException)
+ opt handle
+ dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception
+ end
+ handler -->> client: HTTP error response
+ 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 -->> tasks: Handle exceptions in the background task code
+ end
+```
+
+/// info
+
+클라이언트에는 **하나의 응답**만 전송됩니다. 이는 오류 응답 중 하나일 수도 있고, *경로 처리*에서 생성된 응답일 수도 있습니다.
+
+이러한 응답 중 하나가 전송된 후에는 다른 응답을 보낼 수 없습니다.
+
+///
+
+/// tip
+
+*경로 처리 함수*의 코드에서 어떤 예외를 발생시키면 `HTTPException`을 포함해 `yield`를 사용하는 의존성으로 전달됩니다. 대부분의 경우 해당 예외(또는 새 예외)를 `yield`를 사용하는 의존성에서 다시 발생시켜, 제대로 처리되도록 해야 합니다.
+
+///
+
+## 조기 종료와 `scope` { #early-exit-and-scope }
+
+일반적으로 `yield`를 사용하는 의존성의 종료 코드는 클라이언트로 **응답이 전송된 후에** 실행됩니다.
+
+하지만 *경로 처리 함수*에서 반환한 뒤에는 더 이상 해당 의존성이 필요 없다는 것을 알고 있다면, `Depends(scope="function")`을 사용하여 FastAPI에 *경로 처리 함수*가 반환된 후, 하지만 **응답이 전송되기 전에** 의존성을 종료(닫기)해야 한다고 알려줄 수 있습니다.
+
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
+
+`Depends()`는 다음이 될 수 있는 `scope` 매개변수를 받습니다:
+
+* `"function"`: 요청을 처리하는 *경로 처리 함수* 전에 의존성을 시작하고, *경로 처리 함수*가 끝난 후, 하지만 응답이 클라이언트로 전송되기 **전에** 의존성을 종료합니다. 즉, 의존성 함수는 *경로 처리 **함수***를 **둘러싸며** 실행됩니다.
+* `"request"`: 요청을 처리하는 *경로 처리 함수* 전에 의존성을 시작하고(`"function"`을 사용할 때와 유사), 응답이 클라이언트로 전송된 **후에** 종료합니다. 즉, 의존성 함수는 **요청**과 응답 사이클을 **둘러싸며** 실행됩니다.
+
+지정하지 않고 의존성이 `yield`를 사용한다면, 기본 `scope`는 `"request"`입니다.
+
+### 하위 의존성을 위한 `scope` { #scope-for-sub-dependencies }
+
+`scope="request"`(기본값)로 의존성을 선언하면, 모든 하위 의존성도 `scope`가 `"request"`여야 합니다.
+
+하지만 `scope`가 `"function"`인 의존성은 `scope`가 `"function"`인 의존성과 `"request"`인 의존성을 모두 의존성으로 가질 수 있습니다.
+
+이는 어떤 의존성이든, 종료 코드에서 하위 의존성을 계속 사용해야 할 수도 있으므로, 하위 의존성보다 먼저 종료 코드를 실행할 수 있어야 하기 때문입니다.
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant dep_req as Dep scope="request"
+participant dep_func as Dep scope="function"
+participant operation as Path Operation
+
+ client ->> dep_req: Start request
+ Note over dep_req: Run code up to yield
+ dep_req ->> dep_func: Pass dependency
+ Note over dep_func: Run code up to yield
+ dep_func ->> operation: Run path operation with dependency
+ operation ->> dep_func: Return from path operation
+ Note over dep_func: Run code after yield
+ Note over dep_func: ✅ Dependency closed
+ dep_func ->> client: Send response to client
+ Note over client: Response sent
+ Note over dep_req: Run code after yield
+ Note over dep_req: ✅ Dependency closed
+```
+
+## `yield`, `HTTPException`, `except` 및 백그라운드 작업을 사용하는 의존성 { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+`yield`를 사용하는 의존성은 시간이 지나면서 서로 다른 사용 사례를 다루고 일부 문제를 수정하기 위해 발전해 왔습니다.
+
+FastAPI의 여러 버전에서 무엇이 바뀌었는지 보고 싶다면, 고급 가이드의 [고급 의존성 - `yield`, `HTTPException`, `except` 및 백그라운드 작업을 사용하는 의존성](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks)에서 더 자세히 읽을 수 있습니다.
+## 컨텍스트 관리자 { #context-managers }
+
+### "컨텍스트 관리자"란 { #what-are-context-managers }
+
+"컨텍스트 관리자"는 Python에서 `with` 문에서 사용할 수 있는 모든 객체를 의미합니다.
+
+예를 들어, [with를 사용해 파일을 읽을 수 있습니다](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files):
+
+```Python
+with open("./somefile.txt") as f:
+ contents = f.read()
+ print(contents)
+```
+
+내부적으로 `open("./somefile.txt")` 는 "컨텍스트 관리자(Context Manager)"라고 불리는 객체를 생성합니다.
+
+`with` 블록이 끝나면, 예외가 발생했더라도 파일을 닫도록 보장합니다.
+
+`yield`가 있는 의존성을 생성하면 **FastAPI**는 내부적으로 이를 위한 컨텍스트 매니저를 생성하고 다른 관련 도구들과 결합합니다.
+
+### `yield`를 사용하는 의존성에서 컨텍스트 관리자 사용하기 { #using-context-managers-in-dependencies-with-yield }
+
+/// warning
+
+이것은 어느 정도 "고급" 개념입니다.
+
+**FastAPI**를 처음 시작하는 경우 지금은 이 부분을 건너뛰어도 좋습니다.
+
+///
+
+Python에서는 [두 가지 메서드: `__enter__()`와 `__exit__()`가 있는 클래스를 생성하여](https://docs.python.org/3/reference/datamodel.html#context-managers) 컨텍스트 관리자를 만들 수 있습니다.
+
+**FastAPI**의 `yield`가 있는 의존성 내에서
+`with` 또는 `async with`문을 사용하여 이들을 활용할 수 있습니다:
+
+{* ../../docs_src/dependencies/tutorial010_py310.py hl[1:9,13] *}
+
+/// tip
+
+컨텍스트 관리자를 생성하는 또 다른 방법은 다음과 같습니다:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) 또는
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+이들은 단일 `yield`가 있는 함수를 꾸미는 데 사용합니다.
+
+이것이 **FastAPI**가 `yield`가 있는 의존성을 위해 내부적으로 사용하는 방식입니다.
+
+하지만 FastAPI 의존성에는 이러한 데코레이터를 사용할 필요가 없습니다(그리고 사용해서도 안됩니다).
+
+FastAPI가 내부적으로 이를 처리해 줄 것입니다.
+
+///
diff --git a/docs/ko/docs/tutorial/dependencies/global-dependencies.md b/docs/ko/docs/tutorial/dependencies/global-dependencies.md
new file mode 100644
index 0000000000000..6d4c43eb6c5fc
--- /dev/null
+++ b/docs/ko/docs/tutorial/dependencies/global-dependencies.md
@@ -0,0 +1,15 @@
+# 전역 의존성 { #global-dependencies }
+
+몇몇 유형의 애플리케이션에서는 애플리케이션 전체에 의존성을 추가하고 싶을 수 있습니다.
+
+[*경로 처리 데코레이터*에 `dependencies` 추가하기](dependencies-in-path-operation-decorators.md)와 유사한 방법으로 `FastAPI` 애플리케이션에 그것들을 추가할 수 있습니다.
+
+그런 경우에, 애플리케이션의 모든 *경로 처리*에 적용될 것입니다:
+
+{* ../../docs_src/dependencies/tutorial012_an_py310.py hl[17] *}
+
+그리고 [*경로 처리 데코레이터*에 `dependencies` 추가하기](dependencies-in-path-operation-decorators.md) 섹션의 모든 아이디어는 여전히 적용되지만, 이 경우에는 애플리케이션의 모든 *경로 처리*에 적용됩니다.
+
+## *경로 처리* 그룹에 대한 의존성 { #dependencies-for-groups-of-path-operations }
+
+나중에 여러 파일을 포함할 수도 있는 더 큰 애플리케이션을 구조화하는 법([더 큰 애플리케이션 - 여러 파일들](../../tutorial/bigger-applications.md))을 읽을 때, *경로 처리* 그룹에 대한 단일 `dependencies` 매개변수를 선언하는 법을 배우게 될 것입니다.
diff --git a/docs/ko/docs/tutorial/dependencies/index.md b/docs/ko/docs/tutorial/dependencies/index.md
new file mode 100644
index 0000000000000..4b540b779e7e7
--- /dev/null
+++ b/docs/ko/docs/tutorial/dependencies/index.md
@@ -0,0 +1,250 @@
+# 의존성 { #dependencies }
+
+**FastAPI**는 아주 강력하지만 직관적인 **의존성 주입** 시스템을 가지고 있습니다.
+
+이는 사용하기 아주 쉽게 설계했으며, 어느 개발자나 다른 컴포넌트와 **FastAPI**를 쉽게 통합할 수 있도록 만들었습니다.
+
+## "의존성 주입"은 무엇입니까? { #what-is-dependency-injection }
+
+**"의존성 주입"**은 프로그래밍에서 여러분의 코드(이 경우, *경로 처리 함수*)가 작동하고 사용하는 데 필요로 하는 것, 즉 "의존성"을 선언할 수 있는 방법을 의미합니다.
+
+그 후에, 시스템(이 경우 **FastAPI**)은 여러분의 코드가 요구하는 의존성을 제공하기 위해 필요한 모든 작업을 처리합니다.(의존성을 "주입"합니다)
+
+이는 여러분이 다음과 같은 사항을 필요로 할 때 매우 유용합니다:
+
+* 공용된 로직을 가졌을 경우 (같은 코드 로직이 계속 반복되는 경우).
+* 데이터베이스 연결을 공유하는 경우.
+* 보안, 인증, 역할 요구 사항 등을 강제하는 경우.
+* 그리고 많은 다른 사항...
+
+이 모든 사항을 할 때 코드 반복을 최소화합니다.
+
+## 첫번째 단계 { #first-steps }
+
+아주 간단한 예제를 봅시다. 너무 간단할 것이기에 지금 당장은 유용하지 않을 수 있습니다.
+
+하지만 이를 통해 **의존성 주입** 시스템이 어떻게 작동하는지에 중점을 둘 것입니다.
+
+### 의존성 혹은 "디펜더블" 만들기 { #create-a-dependency-or-dependable }
+
+의존성에 집중해 봅시다.
+
+*경로 처리 함수*가 가질 수 있는 모든 매개변수를 갖는 단순한 함수입니다:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}
+
+이게 다입니다.
+
+**단 두 줄입니다**.
+
+그리고, 이 함수는 여러분의 모든 *경로 처리 함수*가 가지고 있는 것과 같은 형태와 구조를 가지고 있습니다.
+
+여러분은 이를 "데코레이터"가 없는 (`@app.get("/some-path")`가 없는) *경로 처리 함수*라고 생각할 수 있습니다.
+
+그리고 여러분이 원하는 무엇이든 반환할 수 있습니다.
+
+이 경우, 이 의존성은 다음과 같은 경우를 기대합니다:
+
+* 선택적인 쿼리 매개변수 `q`, `str`을 자료형으로 가집니다.
+* 선택적인 쿼리 매개변수 `skip`, `int`를 자료형으로 가지며 기본 값은 `0`입니다.
+* 선택적인 쿼리 매개변수 `limit`, `int`를 자료형으로 가지며 기본 값은 `100`입니다.
+
+그 후 위의 값을 포함한 `dict` 자료형으로 반환할 뿐입니다.
+
+/// info | 정보
+
+FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 사용하기 권장합니다) 추가했습니다.
+
+옛날 버전을 가지고 있는 경우, `Annotated`를 사용하려 하면 에러를 맞이하게 될 것입니다.
+
+`Annotated`를 사용하기 전에 최소 0.95.1로 [FastAPI 버전 업그레이드](../../deployment/versions.md#upgrading-the-fastapi-versions)를 확실하게 하세요.
+
+///
+
+### `Depends` 불러오기 { #import-depends }
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}
+
+### "의존자"에 의존성 명시하기 { #declare-the-dependency-in-the-dependant }
+
+*경로 처리 함수*의 매개변수로 `Body`, `Query` 등을 사용하는 방식과 같이 새로운 매개변수로 `Depends`를 사용합니다:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}
+
+비록 `Depends`를 함수의 매개변수에서 `Body`, `Query` 등을 사용하는 것과 같은 방식으로 사용하지만, `Depends`는 약간 다르게 작동합니다.
+
+`Depends`에 단일 매개변수만 전달했습니다.
+
+이 매개변수는 함수같은 것이어야 합니다.
+
+여러분은 직접 **호출하지 않았습니다** (끝에 괄호를 치지 않았습니다), 단지 `Depends()`에 매개변수로 넘겨 줬을 뿐입니다.
+
+그리고 그 함수는 *경로 처리 함수*가 작동하는 것과 같은 방식으로 매개변수를 받습니다.
+
+/// tip | 팁
+
+여러분은 다음 장에서 함수를 제외하고서, "다른 것들"이 어떻게 의존성으로 사용되는지 알게 될 것입니다.
+
+///
+
+새로운 요청이 도착할 때마다, **FastAPI**는 다음을 처리합니다:
+
+* 올바른 매개변수를 가진 의존성("디펜더블") 함수를 호출합니다.
+* 함수에서 결과를 받아옵니다.
+* *경로 처리 함수*에 있는 매개변수에 그 결과를 할당합니다
+
+```mermaid
+graph TB
+
+common_parameters(["common_parameters"])
+read_items["/items/"]
+read_users["/users/"]
+
+common_parameters --> read_items
+common_parameters --> read_users
+```
+
+이렇게 하면 공용 코드를 한번만 적어도 되며, **FastAPI**는 *경로 처리*을 위해 이에 대한 호출을 처리합니다.
+
+/// check | 확인
+
+특별한 클래스를 만들지 않아도 되며, 이러한 것 혹은 비슷한 종류를 **FastAPI**에 "등록"하기 위해 어떤 곳에 넘겨주지 않아도 됩니다.
+
+단순히 `Depends`에 넘겨주기만 하면 되며, **FastAPI**는 나머지를 어찌할지 알고 있습니다.
+
+///
+
+## `Annotated`인 의존성 공유하기 { #share-annotated-dependencies }
+
+위의 예제에서 몇몇 작은 **코드 중복**이 있다는 것을 보았을 겁니다.
+
+`common_parameters()`의존을 사용해야 한다면, 타입 명시와 `Depends()`와 함께 전체 매개변수를 적어야 합니다:
+
+```Python
+commons: Annotated[dict, Depends(common_parameters)]
+```
+
+하지만 `Annotated`를 사용하고 있기에, `Annotated` 값을 변수에 저장하고 여러 장소에서 사용할 수 있습니다:
+
+{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}
+
+/// tip | 팁
+
+이는 그저 표준 파이썬이고 "type alias"라고 부르며 사실 **FastAPI**에 국한되는 것은 아닙니다.
+
+하지만, `Annotated`를 포함하여, **FastAPI**가 파이썬 표준을 기반으로 하고 있기에, 이를 여러분의 코드 트릭으로 사용할 수 있습니다. 😎
+
+///
+
+이 의존성은 계속해서 예상한대로 작동할 것이며, **제일 좋은 부분**은 **타입 정보가 보존된다는 것입니다**. 즉 여러분의 편집기가 **자동 완성**, **인라인 에러** 등을 계속해서 제공할 수 있다는 것입니다. `mypy`같은 다른 도구도 마찬가지입니다.
+
+이는 특히 **많은 *경로 처리***에서 **같은 의존성**을 계속해서 사용하는 **거대 코드 기반**안에서 사용하면 유용할 것입니다.
+
+## `async`하게, 혹은 `async`하지 않게 { #to-async-or-not-to-async }
+
+의존성이 (*경로 처리 함수*에서 처럼 똑같이) **FastAPI**에 의해 호출될 수 있으며, 함수를 정의할 때 동일한 규칙이 적용됩니다.
+
+`async def`을 사용하거나 혹은 일반적인 `def`를 사용할 수 있습니다.
+
+그리고 일반적인 `def` *경로 처리 함수* 안에 `async def`로 의존성을 선언할 수 있으며, `async def` *경로 처리 함수* 안에 `def`로 의존성을 선언하는 등의 방법이 있습니다.
+
+아무 문제 없습니다. **FastAPI**는 무엇을 할지 알고 있습니다.
+
+/// note | 참고
+
+잘 모르시겠다면, [Async: *"In a hurry?"*](../../async.md#in-a-hurry) 문서에서 `async`와 `await`에 대해 확인할 수 있습니다.
+
+///
+
+## OpenAPI와 통합 { #integrated-with-openapi }
+
+모든 요청 선언, 검증과 의존성(및 하위 의존성)에 대한 요구 사항은 동일한 OpenAPI 스키마에 통합됩니다.
+
+따라서 대화형 문서에 이러한 의존성에 대한 모든 정보 역시 포함하고 있습니다:
+
+
+
+## 간단한 사용법 { #simple-usage }
+
+이를 보면, *경로 처리 함수*는 *경로*와 *작동*이 매칭되면 언제든지 사용되도록 정의되었으며, **FastAPI**는 올바른 매개변수를 가진 함수를 호출하고 해당 요청에서 데이터를 추출합니다.
+
+사실, 모든 (혹은 대부분의) 웹 프레임워크는 이와 같은 방식으로 작동합니다.
+
+여러분은 이러한 함수들을 절대 직접 호출하지 않습니다. 프레임워크(이 경우 **FastAPI**)에 의해 호출됩니다.
+
+의존성 주입 시스템과 함께라면 **FastAPI**에게 여러분의 *경로 처리 함수*가 실행되기 전에 실행되어야 하는 무언가에 여러분의 *경로 처리 함수* 또한 "의존"하고 있음을 알릴 수 있으며, **FastAPI**는 이를 실행하고 결과를 "주입"할 것입니다.
+
+"의존성 주입"이라는 동일한 아이디어에 대한 다른 일반적인 용어는 다음과 같습니다:
+
+* 리소스
+* 제공자
+* 서비스
+* 인젝터블
+* 컴포넌트
+
+## **FastAPI** 플러그인 { #fastapi-plug-ins }
+
+통합과 "플러그인"은 **의존성 주입** 시스템을 사용하여 구축할 수 있습니다. 하지만 실제로 **"플러그인"을 만들 필요는 없습니다**, 왜냐하면 의존성을 사용함으로써 여러분의 *경로 처리 함수*에 통합과 상호 작용을 무한대로 선언할 수 있기 때문입니다.
+
+그리고 "말 그대로", 그저 필요로 하는 파이썬 패키지를 임포트하고 단 몇 줄의 코드로 여러분의 API 함수와 통합함으로써, 의존성을 아주 간단하고 직관적인 방법으로 만들 수 있습니다.
+
+관계형 및 NoSQL 데이터베이스, 보안 등, 이에 대한 예시를 다음 장에서 볼 수 있습니다.
+
+## **FastAPI** 호환성 { #fastapi-compatibility }
+
+의존성 주입 시스템의 단순함은 **FastAPI**를 다음과 같은 요소들과 호환할 수 있게 합니다:
+
+* 모든 관계형 데이터베이스
+* NoSQL 데이터베이스
+* 외부 패키지
+* 외부 API
+* 인증 및 권한 부여 시스템
+* API 사용 모니터링 시스템
+* 응답 데이터 주입 시스템
+* 기타 등등.
+
+## 간편하고 강력하다 { #simple-and-powerful }
+
+계층적인 의존성 주입 시스템은 정의하고 사용하기 쉽지만, 여전히 매우 강력합니다.
+
+여러분은 스스로를 의존하는 의존성을 정의할 수 있습니다.
+
+끝에는, 계층적인 나무로 된 의존성이 만들어지며, 그리고 **의존성 주입** 시스템은 (하위 의존성도 마찬가지로) 이러한 의존성들을 처리하고 각 단계마다 결과를 제공합니다(주입합니다).
+
+예를 들면, 여러분이 4개의 API 엔드포인트(*경로 처리*)를 가지고 있다고 해봅시다:
+
+* `/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**와의 통합 { #integrated-with-openapi_1 }
+
+이 모든 의존성은 각각의 요구사항을 선언하는 동시에, *경로 처리*에 매개변수, 검증 등을 추가합니다.
+
+**FastAPI**는 이 모든 것을 OpenAPI 스키마에 추가할 것이며, 이를 통해 대화형 문서 시스템에 나타날 것입니다.
diff --git a/docs/ko/docs/tutorial/dependencies/sub-dependencies.md b/docs/ko/docs/tutorial/dependencies/sub-dependencies.md
new file mode 100644
index 0000000000000..52c847b70254c
--- /dev/null
+++ b/docs/ko/docs/tutorial/dependencies/sub-dependencies.md
@@ -0,0 +1,105 @@
+# 하위 의존성 { #sub-dependencies }
+
+**하위 의존성**을 가지는 의존성을 만들 수 있습니다.
+
+필요한 만큼 **깊게** 중첩할 수도 있습니다.
+
+이것을 해결하는 일은 **FastAPI**가 알아서 처리합니다.
+
+## 첫 번째 의존성 "dependable" { #first-dependency-dependable }
+
+다음과 같이 첫 번째 의존성("dependable")을 만들 수 있습니다:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}
+
+이 의존성은 선택적 쿼리 파라미터 `q`를 `str`로 선언하고, 그대로 반환합니다.
+
+매우 단순한 예시(그다지 유용하진 않음)이지만, 하위 의존성이 어떻게 동작하는지에 집중하는 데 도움이 됩니다.
+
+## 두 번째 의존성 "dependable"과 "dependant" { #second-dependency-dependable-and-dependant }
+
+그다음, 또 다른 의존성 함수("dependable")를 만들 수 있는데, 이 함수는 동시에 자기 자신의 의존성도 선언합니다(그래서 "dependant"이기도 합니다):
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}
+
+선언된 파라미터를 살펴보겠습니다:
+
+* 이 함수 자체가 의존성("dependable")이지만, 다른 의존성도 하나 선언합니다(즉, 다른 무언가에 "의존"합니다).
+ * `query_extractor`에 의존하며, 그 반환값을 파라미터 `q`에 할당합니다.
+* 또한 선택적 `last_query` 쿠키를 `str`로 선언합니다.
+ * 사용자가 쿼리 `q`를 제공하지 않았다면, 이전에 쿠키에 저장해 둔 마지막 쿼리를 사용합니다.
+
+## 의존성 사용하기 { #use-the-dependency }
+
+그다음 다음과 같이 의존성을 사용할 수 있습니다:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}
+
+/// info | 정보
+
+*경로 처리 함수*에서는 `query_or_cookie_extractor`라는 의존성 하나만 선언하고 있다는 점에 주목하세요.
+
+하지만 **FastAPI**는 `query_or_cookie_extractor`를 호출하는 동안 그 결과를 전달하기 위해, 먼저 `query_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
+```
+
+## 같은 의존성을 여러 번 사용하기 { #using-the-same-dependency-multiple-times }
+
+같은 *경로 처리*에 대해 의존성 중 하나가 여러 번 선언되는 경우(예: 여러 의존성이 공통 하위 의존성을 갖는 경우), **FastAPI**는 그 하위 의존성을 요청당 한 번만 호출해야 한다는 것을 알고 있습니다.
+
+그리고 같은 요청에 대해 동일한 의존성을 여러 번 호출하는 대신, 반환값을 "캐시"에 저장하고, 그 요청에서 해당 값이 필요한 모든 "dependants"에 전달합니다.
+
+고급 시나리오로, 같은 요청에서 "cached" 값을 쓰는 대신 매 단계마다(아마도 여러 번) 의존성이 호출되어야 한다는 것을 알고 있다면, `Depends`를 사용할 때 `use_cache=False` 파라미터를 설정할 수 있습니다:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+//// tab | Python 3.10+ 비 Annotated
+
+/// tip | 팁
+
+가능하다면 `Annotated` 버전을 사용하는 것을 권장합니다.
+
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+## 정리 { #recap }
+
+여기서 사용한 그럴듯한 용어들을 제외하면, **Dependency Injection** 시스템은 꽤 단순합니다.
+
+*경로 처리 함수*와 같은 형태의 함수들일 뿐입니다.
+
+하지만 여전히 매우 강력하며, 임의로 깊게 중첩된 의존성 "그래프"(트리)를 선언할 수 있습니다.
+
+/// tip | 팁
+
+이 단순한 예시만 보면 그다지 유용해 보이지 않을 수도 있습니다.
+
+하지만 **보안**에 관한 챕터에서 이것이 얼마나 유용한지 보게 될 것입니다.
+
+또한 얼마나 많은 코드를 아껴주는지도 보게 될 것입니다.
+
+///
diff --git a/docs/ko/docs/tutorial/encoder.md b/docs/ko/docs/tutorial/encoder.md
index 8b5fdb8b7ea16..9ed7a13cd8a76 100644
--- a/docs/ko/docs/tutorial/encoder.md
+++ b/docs/ko/docs/tutorial/encoder.md
@@ -1,34 +1,35 @@
-# JSON 호환 가능 인코더
+# JSON 호환 가능 인코더 { #json-compatible-encoder }
-데이터 유형(예: Pydantic 모델)을 JSON과 호환된 형태로 반환해야 하는 경우가 있습니다. (예: `dict`, `list` 등)
+데이터 유형(예: Pydantic 모델)을 JSON과 호환되는 형태(예: `dict`, `list` 등)로 변환해야 하는 경우가 있습니다.
-예를 들면, 데이터베이스에 저장해야하는 경우입니다.
+예를 들면, 데이터베이스에 저장해야 하는 경우입니다.
-이를 위해, **FastAPI** 에서는 `jsonable_encoder()` 함수를 제공합니다.
+이를 위해, **FastAPI**에서는 `jsonable_encoder()` 함수를 제공합니다.
-## `jsonable_encoder` 사용
+## `jsonable_encoder` 사용 { #using-the-jsonable-encoder }
JSON 호환 가능 데이터만 수신하는 `fake_db` 데이터베이스가 존재한다고 가정하겠습니다.
-예를 들면, `datetime` 객체는 JSON과 호환되는 데이터가 아니므로 이 데이터는 받아들여지지 않습니다.
+예를 들면, `datetime` 객체는 JSON과 호환되지 않으므로 이 데이터베이스는 이를 받지 않습니다.
-따라서 `datetime` 객체는 ISO format 데이터를 포함하는 `str`로 변환되어야 합니다.
+따라서 `datetime` 객체는 [ISO 형식](https://en.wikipedia.org/wiki/ISO_8601)의 데이터를 포함하는 `str`로 변환되어야 합니다.
-같은 방식으로 이 데이터베이스는 Pydantic 모델(속성이 있는 객체)을 받지 않고, `dict` 만을 받습니다.
+같은 방식으로 이 데이터베이스는 Pydantic 모델(속성이 있는 객체)을 받지 않고, `dict`만을 받습니다.
-이를 위해 `jsonable_encoder` 를 사용할 수 있습니다.
+이를 위해 `jsonable_encoder`를 사용할 수 있습니다.
-Pydantic 모델과 같은 객체를 받고 JSON 호환 가능한 버전으로 반환합니다:
+Pydantic 모델 같은 객체를 받고 JSON 호환 가능한 버전을 반환합니다:
-```Python hl_lines="5 22"
-{!../../../docs_src/encoder/tutorial001.py!}
-```
+{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *}
-이 예시는 Pydantic 모델을 `dict`로, `datetime` 형식을 `str`로 변환합니다.
+이 예시에서는 Pydantic 모델을 `dict`로, `datetime`을 `str`로 변환합니다.
-이렇게 호출한 결과는 파이썬 표준인 `json.dumps()`로 인코딩 할 수 있습니다.
+이렇게 호출한 결과는 파이썬 표준인 [`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps)로 인코딩할 수 있습니다.
-길이가 긴 문자열 형태의 JSON 형식(문자열)의 데이터가 들어있는 상황에서는 `str`로 반환하지 않습니다. JSON과 모두 호환되는 값과 하위 값이 있는 Python 표준 데이터 구조 (예: `dict`)를 반환합니다.
+JSON 형식(문자열)의 데이터가 들어있는 큰 `str`을 반환하지 않습니다. JSON과 모두 호환되는 값과 하위 값이 있는 파이썬 표준 데이터 구조(예: `dict`)를 반환합니다.
-!!! note "참고"
- 실제로 `jsonable_encoder`는 **FastAPI** 에서 내부적으로 데이터를 변환하는 데 사용하지만, 다른 많은 곳에서도 이는 유용합니다.
+/// note | 참고
+
+`jsonable_encoder`는 실제로 **FastAPI**에서 내부적으로 데이터를 변환하는 데 사용하지만, 다른 많은 시나리오에서도 유용합니다.
+
+///
diff --git a/docs/ko/docs/tutorial/extra-data-types.md b/docs/ko/docs/tutorial/extra-data-types.md
new file mode 100644
index 0000000000000..da62a399273a0
--- /dev/null
+++ b/docs/ko/docs/tutorial/extra-data-types.md
@@ -0,0 +1,62 @@
+# 추가 데이터 자료형 { #extra-data-types }
+
+지금까지 일반적인 데이터 자료형을 사용했습니다. 예를 들면 다음과 같습니다:
+
+* `int`
+* `float`
+* `str`
+* `bool`
+
+하지만 더 복잡한 데이터 자료형 또한 사용할 수 있습니다.
+
+그리고 지금까지와 같은 기능들을 여전히 사용할 수 있습니다.
+
+* 훌륭한 편집기 지원.
+* 들어오는 요청의 데이터 변환.
+* 응답 데이터의 데이터 변환.
+* 데이터 검증.
+* 자동 어노테이션과 문서화.
+
+## 다른 데이터 자료형 { #other-data-types }
+
+아래의 추가적인 데이터 자료형을 사용할 수 있습니다:
+
+* `UUID`:
+ * 표준 "범용 고유 식별자"로, 많은 데이터베이스와 시스템에서 ID로 사용됩니다.
+ * 요청과 응답에서 `str`로 표현됩니다.
+* `datetime.datetime`:
+ * 파이썬의 `datetime.datetime`.
+ * 요청과 응답에서 `2008-09-15T15:53:00+05:00`와 같은 ISO 8601 형식의 `str`로 표현됩니다.
+* `datetime.date`:
+ * 파이썬의 `datetime.date`.
+ * 요청과 응답에서 `2008-09-15`와 같은 ISO 8601 형식의 `str`로 표현됩니다.
+* `datetime.time`:
+ * 파이썬의 `datetime.time`.
+ * 요청과 응답에서 `14:23:55.003`와 같은 ISO 8601 형식의 `str`로 표현됩니다.
+* `datetime.timedelta`:
+ * 파이썬의 `datetime.timedelta`.
+ * 요청과 응답에서 전체 초(seconds)의 `float`로 표현됩니다.
+ * Pydantic은 "ISO 8601 time diff encoding"으로 표현하는 것 또한 허용합니다. [더 많은 정보는 문서를 확인하세요](https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers).
+* `frozenset`:
+ * 요청과 응답에서 `set`와 동일하게 취급됩니다:
+ * 요청 시, 리스트를 읽어 중복을 제거하고 `set`로 변환합니다.
+ * 응답 시, `set`는 `list`로 변환됩니다.
+ * 생성된 스키마는 (JSON 스키마의 `uniqueItems`를 이용해) `set`의 값이 고유함을 명시합니다.
+* `bytes`:
+ * 표준 파이썬의 `bytes`.
+ * 요청과 응답에서 `str`로 취급됩니다.
+ * 생성된 스키마는 이것이 `binary` "형식"의 `str`임을 명시합니다.
+* `Decimal`:
+ * 표준 파이썬의 `Decimal`.
+ * 요청과 응답에서 `float`와 동일하게 다뤄집니다.
+* 여기에서 모든 유효한 Pydantic 데이터 자료형을 확인할 수 있습니다: [Pydantic 데이터 자료형](https://docs.pydantic.dev/latest/usage/types/types/).
+
+## 예시 { #example }
+
+위의 몇몇 자료형을 매개변수로 사용하는 *경로 처리* 예시입니다.
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *}
+
+함수 안의 매개변수가 그들만의 데이터 자료형을 가지고 있으며, 예를 들어, 다음과 같이 날짜를 조작할 수 있음을 참고하십시오:
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *}
diff --git a/docs/ko/docs/tutorial/extra-models.md b/docs/ko/docs/tutorial/extra-models.md
new file mode 100644
index 0000000000000..157549f92fc48
--- /dev/null
+++ b/docs/ko/docs/tutorial/extra-models.md
@@ -0,0 +1,211 @@
+# 추가 모델 { #extra-models }
+
+지난 예제에 이어서, 연관된 모델을 여러 개 갖는 것은 흔한 일입니다.
+
+특히 사용자 모델의 경우에 그러한데, 왜냐하면:
+
+* **입력 모델**은 비밀번호를 가질 수 있어야 합니다.
+* **출력 모델**은 비밀번호를 가지면 안 됩니다.
+* **데이터베이스 모델**은 아마도 해시 처리된 비밀번호를 가질 필요가 있을 것입니다.
+
+/// danger
+
+절대 사용자의 비밀번호를 평문으로 저장하지 마세요. 항상 이후에 검증 가능한 "안전한 해시(secure hash)"로 저장하세요.
+
+만약 이게 무엇인지 모르겠다면, [보안 장](security/simple-oauth2.md#password-hashing)에서 "password hash"가 무엇인지 배울 수 있습니다.
+
+///
+
+## 다중 모델 { #multiple-models }
+
+아래는 비밀번호 필드와 해당 필드가 사용되는 위치를 포함하여, 각 모델들이 어떤 형태를 가질 수 있는지 전반적인 예시입니다:
+
+{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}
+
+### `**user_in.model_dump()` 에 대하여 { #about-user-in-model-dump }
+
+#### Pydantic의 `.model_dump()` { #pydantics-model-dump }
+
+`user_in`은 Pydantic 모델 클래스인 `UserIn`입니다.
+
+Pydantic 모델은 모델 데이터를 포함한 `dict`를 반환하는 `.model_dump()` 메서드를 제공합니다.
+
+따라서, 다음과 같이 Pydantic 객체 `user_in`을 생성할 수 있습니다:
+
+```Python
+user_in = UserIn(username="john", password="secret", email="john.doe@example.com")
+```
+
+그 다음, 다음과 같이 호출합니다:
+
+```Python
+user_dict = user_in.model_dump()
+```
+
+이제 변수 `user_dict`에 데이터가 포함된 `dict`를 가지게 됩니다(이는 Pydantic 모델 객체가 아닌 `dict`입니다).
+
+그리고 다음과 같이 호출하면:
+
+```Python
+print(user_dict)
+```
+
+Python의 `dict`가 다음과 같이 출력됩니다:
+
+```Python
+{
+ 'username': 'john',
+ 'password': 'secret',
+ 'email': 'john.doe@example.com',
+ 'full_name': None,
+}
+```
+
+#### `dict` 언패킹 { #unpacking-a-dict }
+
+`user_dict`와 같은 `dict`를 함수(또는 클래스)에 `**user_dict`로 전달하면, Python은 이를 "언팩(unpack)"합니다. 이 과정에서 `user_dict`의 키와 값을 각각 키-값 인자로 직접 전달합니다.
+
+따라서, 위에서 생성한 `user_dict`를 사용하여 다음과 같이 작성하면:
+
+```Python
+UserInDB(**user_dict)
+```
+
+다음과 같은 결과를 생성합니다:
+
+```Python
+UserInDB(
+ username="john",
+ password="secret",
+ email="john.doe@example.com",
+ 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 모델 생성 { #a-pydantic-model-from-the-contents-of-another }
+
+위의 예제에서 `user_in.model_dump()`로부터 `user_dict`를 생성한 것처럼, 아래 코드는:
+
+```Python
+user_dict = user_in.model_dump()
+UserInDB(**user_dict)
+```
+
+다음과 동일합니다:
+
+```Python
+UserInDB(**user_in.model_dump())
+```
+
+...왜냐하면 `user_in.model_dump()`는 `dict`이며, 이를 `**`로 Python이 "언팩(unpack)"하도록 하여 `UserInDB`에 전달하기 때문입니다.
+
+따라서, 다른 Pydantic 모델의 데이터를 사용하여 새로운 Pydantic 모델을 생성할 수 있습니다.
+
+#### `dict` 언패킹과 추가 키워드 { #unpacking-a-dict-and-extra-keywords }
+
+그리고 다음과 같이 추가 키워드 인자 `hashed_password=hashed_password`를 추가하면:
+
+```Python
+UserInDB(**user_in.model_dump(), 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
+
+추가적으로 제공된 함수 `fake_password_hasher`와 `fake_save_user`는 데이터 흐름을 시연하기 위한 예제일 뿐이며, 실제 보안을 제공하지 않습니다.
+
+///
+
+## 중복 줄이기 { #reduce-duplication }
+
+코드 중복을 줄이는 것은 **FastAPI**의 핵심 아이디어 중 하나입니다.
+
+코드 중복은 버그, 보안 문제, 코드 비동기화 문제(한 곳은 업데이트되었지만 다른 곳은 업데이트되지 않는 문제) 등의 가능성을 증가시킵니다.
+
+그리고 이 모델들은 많은 데이터를 공유하면서 속성 이름과 타입을 중복하고 있습니다.
+
+더 나은 방법이 있습니다.
+
+`UserBase` 모델을 선언하여 다른 모델들의 기본(base)으로 사용할 수 있습니다. 그런 다음 이 모델을 상속받아 속성과 타입 선언(유형 선언, 검증 등)을 상속하는 서브클래스를 만들 수 있습니다.
+
+모든 데이터 변환, 검증, 문서화 등은 정상적으로 작동할 것입니다.
+
+이렇게 하면 각 모델 간의 차이점만 선언할 수 있습니다(평문 `password`, `hashed_password`, 그리고 비밀번호가 없는 경우):
+
+{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}
+
+## `Union` 또는 `anyOf` { #union-or-anyof }
+
+두 가지 이상의 타입을 포함하는 `Union`으로 응답을 선언할 수 있습니다. 이는 응답이 그 중 하나의 타입일 수 있음을 의미합니다.
+
+OpenAPI에서는 이를 `anyOf`로 정의합니다.
+
+이를 위해 표준 Python 타입 힌트인 [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union)을 사용할 수 있습니다:
+
+/// note
+
+[`Union`](https://docs.pydantic.dev/latest/concepts/types/#unions)을 정의할 때는 더 구체적인 타입을 먼저 포함하고, 덜 구체적인 타입을 그 뒤에 나열해야 합니다. 아래 예제에서는 `Union[PlaneItem, CarItem]`에서 더 구체적인 `PlaneItem`이 `CarItem`보다 앞에 위치합니다.
+
+///
+
+{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}
+
+### Python 3.10에서 `Union` { #union-in-python-3-10 }
+
+위의 예제에서는 `response_model` 인자 값으로 `Union[PlaneItem, CarItem]`을 전달합니다.
+
+이 경우, 이를 **타입 어노테이션(type annotation)**이 아닌 **인자 값(argument value)**으로 전달하고 있기 때문에 Python 3.10에서도 `Union`을 사용해야 합니다.
+
+만약 타입 어노테이션에 사용한다면, 다음과 같이 수직 막대(|)를 사용할 수 있습니다:
+
+```Python
+some_variable: PlaneItem | CarItem
+```
+
+하지만 이를 `response_model=PlaneItem | CarItem`과 같이 할당하면 에러가 발생합니다. 이는 Python이 이를 타입 어노테이션으로 해석하지 않고, `PlaneItem`과 `CarItem` 사이의 **잘못된 연산(invalid operation)**을 시도하기 때문입니다.
+
+## 모델 리스트 { #list-of-models }
+
+마찬가지로, 객체 리스트 형태의 응답을 선언할 수도 있습니다.
+
+이를 위해 표준 Python의 `list`를 사용하세요:
+
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
+
+## 임의의 `dict` 응답 { #response-with-arbitrary-dict }
+
+Pydantic 모델을 사용하지 않고, 키와 값의 타입만 선언하여 평범한 임의의 `dict`로 응답을 선언할 수도 있습니다.
+
+이는 Pydantic 모델에 필요한 유효한 필드/속성 이름을 사전에 알 수 없는 경우에 유용합니다.
+
+이 경우, `dict`를 사용할 수 있습니다:
+
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
+
+## 요약 { #recap }
+
+여러 Pydantic 모델을 사용하고, 각 경우에 맞게 자유롭게 상속하세요.
+
+엔터티가 서로 다른 "상태"를 가져야 하는 경우, 엔터티당 단일 데이터 모델을 사용할 필요는 없습니다. 예를 들어, 사용자 "엔터티"가 `password`, `password_hash`, 그리고 비밀번호가 없는 상태를 포함할 수 있는 경우처럼 말입니다.
diff --git a/docs/ko/docs/tutorial/first-steps.md b/docs/ko/docs/tutorial/first-steps.md
index a669cb2ba7e79..cc3d6c6182559 100644
--- a/docs/ko/docs/tutorial/first-steps.md
+++ b/docs/ko/docs/tutorial/first-steps.md
@@ -1,47 +1,64 @@
-# 첫걸음
+# 첫걸음 { #first-steps }
-가장 단순한 FastAPI 파일은 다음과 같이 보일 겁니다:
+가장 단순한 FastAPI 파일은 다음과 같이 보일 것입니다:
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
-위를 `main.py`에 복사합니다.
+위 코드를 `main.py`에 복사합니다.
라이브 서버를 실행합니다:
get 동작 사용
+* get 작동 사용
+
+/// info | `@decorator` 정보
-!!! info "`@decorator` 정보"
- 이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다.
+이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다.
- 함수 맨 위에 놓습니다. 마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한거 같습니다).
+마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한 것 같습니다) 함수 맨 위에 놓습니다.
- "데코레이터" 아래 있는 함수를 받고 그걸 이용해 무언가 합니다.
+"데코레이터"는 아래 있는 함수를 받아 그것으로 무언가를 합니다.
- 우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`에 해당하는 `get` **동작**하라고 알려줍니다.
+우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`의 `get` **작동**에 해당한다고 알려줍니다.
- 이것이 "**경로 동작 데코레이터**"입니다.
+이것이 "**경로 처리 데코레이터**"입니다.
-다른 동작도 쓸 수 있습니다:
+///
+
+다른 작동도 사용할 수 있습니다:
* `@app.post()`
* `@app.put()`
* `@app.delete()`
-이국적인 것들도 있습니다:
+흔히 사용되지 않는 것들도 있습니다:
* `@app.options()`
* `@app.head()`
* `@app.patch()`
* `@app.trace()`
-!!! tip "팁"
- 각 동작(HTTP 메소드)을 원하는 대로 사용해도 됩니다.
+/// tip | 팁
+
+각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다.
- **FastAPI**는 특정 의미를 강제하지 않습니다.
+**FastAPI**는 특정 의미를 강제하지 않습니다.
- 여기서 정보는 지침서일뿐 요구사항이 아닙니다.
+여기서 정보는 지침서일뿐 강제사항이 아닙니다.
- 예를 들어 GraphQL을 사용할때 일반적으로 `POST` 동작만 사용하여 모든 행동을 수행합니다.
+예를 들어 GraphQL을 사용하는 경우, 일반적으로 `POST` 작동만 사용하여 모든 행동을 수행합니다.
-### 4 단계: **경로 동작 함수** 정의
+///
-다음은 우리의 "**경로 동작 함수**"입니다:
+### 4 단계: **경로 처리 함수** 정의 { #step-4-define-the-path-operation-function }
+
+다음은 우리의 "**경로 처리 함수**"입니다:
* **경로**: 는 `/`입니다.
-* **동작**: 은 `get`입니다.
+* **작동**: 은 `get`입니다.
* **함수**: 는 "데코레이터" 아래에 있는 함수입니다 (`@app.get("/")` 아래).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
이것은 파이썬 함수입니다.
-`GET` 동작을 사용하여 URL "`/`"에 대한 요청을 받을 때마다 **FastAPI**에 의해 호출됩니다.
+URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **FastAPI**에 의해 호출됩니다.
-위의 경우 `async` 함수입니다.
+위의 예시에서 이 함수는 `async`(비동기) 함수입니다.
---
-`async def` 대신 일반 함수로 정의할 수 있습니다:
+`async def`을 이용하는 대신 일반 함수로 정의할 수 있습니다:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
-!!! note 참고
- 차이점을 모르겠다면 [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}을 확인하세요.
+/// note | 참고
-### 5 단계: 콘텐츠 반환
+차이점을 모르겠다면 [Async: *"바쁘신 경우"*](../async.md#in-a-hurry)를 확인하세요.
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+///
+
+### 5 단계: 콘텐츠 반환 { #step-5-return-the-content }
+
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
`dict`, `list`, 단일값을 가진 `str`, `int` 등을 반환할 수 있습니다.
Pydantic 모델을 반환할 수도 있습니다(나중에 더 자세히 살펴봅니다).
-JSON으로 자동 변환되는 객체들과 모델들이 많이 있습니다(ORM 등을 포함해서요). 가장 마음에 드는 것을 사용하세요, 이미 지원되고 있을 겁니다.
+JSON으로 자동 변환되는 객체들과 모델들(ORM 등을 포함해서)이 많이 있습니다. 가장 마음에 드는 것을 사용하십시오, 이미 지원되고 있을 것입니다.
+
+### 6 단계: 배포하기 { #step-6-deploy-it }
+
+한 번의 명령으로 **[FastAPI Cloud](https://fastapicloud.com)**에 앱을 배포합니다: `fastapi deploy`. 🎉
+
+#### FastAPI Cloud 소개 { #about-fastapi-cloud }
+
+**[FastAPI Cloud](https://fastapicloud.com)**는 **FastAPI** 뒤에 있는 동일한 작성자와 팀이 만들었습니다.
+
+최소한의 노력으로 API를 **빌드**, **배포**, **접근**하는 과정을 간소화합니다.
+
+FastAPI로 앱을 빌드할 때의 동일한 **개발자 경험**을 클라우드에 **배포**할 때도 제공합니다. 🎉
+
+FastAPI Cloud는 *FastAPI와 친구들* 오픈 소스 프로젝트의 주요 스폰서이자 자금 제공자입니다. ✨
+
+#### 다른 클라우드 제공업체에 배포하기 { #deploy-to-other-cloud-providers }
+
+FastAPI는 오픈 소스이며 표준을 기반으로 합니다. 선택한 어떤 클라우드 제공업체에도 FastAPI 앱을 배포할 수 있습니다.
+
+클라우드 제공업체의 가이드를 따라 FastAPI 앱을 배포하세요. 🤓
-## 요약
+## 요약 { #recap }
* `FastAPI` 임포트.
* `app` 인스턴스 생성.
-* (`@app.get("/")`처럼) **경로 동작 데코레이터** 작성.
-* (위에 있는 `def root(): ...`처럼) **경로 동작 함수** 작성.
-* (`uvicorn main:app --reload`처럼) 개발 서버 실행.
+* (`@app.get("/")`처럼) **경로 처리 데코레이터** 작성.
+* (위에 있는 `def root(): ...`처럼) **경로 처리 함수** 작성.
+* `fastapi dev` 명령으로 개발 서버 실행.
+* 선택적으로 `fastapi deploy`로 앱 배포.
diff --git a/docs/ko/docs/tutorial/handling-errors.md b/docs/ko/docs/tutorial/handling-errors.md
new file mode 100644
index 0000000000000..efee108ef1ebf
--- /dev/null
+++ b/docs/ko/docs/tutorial/handling-errors.md
@@ -0,0 +1,244 @@
+# 오류 처리 { #handling-errors }
+
+API를 사용하는 클라이언트에 오류를 알려야 하는 상황은 많이 있습니다.
+
+이 클라이언트는 프론트엔드가 있는 브라우저일 수도 있고, 다른 사람이 작성한 코드일 수도 있고, IoT 장치일 수도 있습니다.
+
+클라이언트에 다음과 같은 내용을 알려야 할 수도 있습니다:
+
+* 클라이언트가 해당 작업을 수행할 충분한 권한이 없습니다.
+* 클라이언트가 해당 리소스에 접근할 수 없습니다.
+* 클라이언트가 접근하려고 한 항목이 존재하지 않습니다.
+* 등등.
+
+이런 경우 보통 **400**번대(400에서 499) 범위의 **HTTP 상태 코드**를 반환합니다.
+
+이는 200번대 HTTP 상태 코드(200에서 299)와 비슷합니다. "200" 상태 코드는 어떤 형태로든 요청이 "성공"했음을 의미합니다.
+
+400번대 상태 코드는 클라이언트 측에서 오류가 발생했음을 의미합니다.
+
+**"404 Not Found"** 오류(그리고 농담들)도 다들 기억하시죠?
+
+## `HTTPException` 사용하기 { #use-httpexception }
+
+클라이언트에 오류가 포함된 HTTP 응답을 반환하려면 `HTTPException`을 사용합니다.
+
+### `HTTPException` 가져오기 { #import-httpexception }
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
+
+### 코드에서 `HTTPException` 발생시키기 { #raise-an-httpexception-in-your-code }
+
+`HTTPException`은 API와 관련된 추가 데이터를 가진 일반적인 Python 예외입니다.
+
+Python 예외이므로 `return` 하는 것이 아니라 `raise` 합니다.
+
+이는 또한, *경로 처리 함수* 내부에서 호출하는 유틸리티 함수 안에서 `HTTPException`을 `raise`하면, *경로 처리 함수*의 나머지 코드는 실행되지 않고 즉시 해당 요청이 종료되며 `HTTPException`의 HTTP 오류가 클라이언트로 전송된다는 뜻입니다.
+
+값을 반환하는 것보다 예외를 발생시키는 것의 이점은 의존성과 보안에 대한 섹션에서 더 분명해집니다.
+
+이 예시에서는, 클라이언트가 존재하지 않는 ID로 항목을 요청하면 상태 코드 `404`로 예외를 발생시킵니다:
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
+
+### 결과 응답 { #the-resulting-response }
+
+클라이언트가 `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`을 발생시킬 때 `detail` 파라미터로 `str`만 전달할 수 있는 것이 아니라, JSON으로 변환할 수 있는 어떤 값이든 전달할 수 있습니다.
+
+`dict`, `list` 등을 전달할 수 있습니다.
+
+이들은 **FastAPI**가 자동으로 처리해 JSON으로 변환합니다.
+
+///
+
+## 커스텀 헤더 추가하기 { #add-custom-headers }
+
+HTTP 오류에 커스텀 헤더를 추가할 수 있으면 유용한 상황이 있습니다. 예를 들어 특정 보안 유형에서 그렇습니다.
+
+아마 코드에서 직접 사용할 일은 거의 없을 것입니다.
+
+하지만 고급 시나리오에서 필요하다면 커스텀 헤더를 추가할 수 있습니다:
+
+{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
+
+## 커스텀 예외 핸들러 설치하기 { #install-custom-exception-handlers }
+
+[Starlette의 동일한 예외 유틸리티](https://www.starlette.dev/exceptions/)를 사용해 커스텀 예외 핸들러를 추가할 수 있습니다.
+
+여러분(또는 사용하는 라이브러리)이 `raise`할 수 있는 커스텀 예외 `UnicornException`이 있다고 가정해 봅시다.
+
+그리고 이 예외를 FastAPI에서 전역적으로 처리하고 싶다고 해봅시다.
+
+`@app.exception_handler()`로 커스텀 예외 핸들러를 추가할 수 있습니다:
+
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
+
+여기서 `/unicorns/yolo`를 요청하면, *경로 처리*가 `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**는 개발자의 편의를 위해 `starlette.responses`를 `fastapi.responses`로도 동일하게 제공합니다. 하지만 사용 가능한 대부분의 응답은 Starlette에서 직접 옵니다. `Request`도 마찬가지입니다.
+
+///
+
+## 기본 예외 핸들러 오버라이드하기 { #override-the-default-exception-handlers }
+
+**FastAPI**에는 몇 가지 기본 예외 핸들러가 있습니다.
+
+이 핸들러들은 `HTTPException`을 `raise`했을 때, 그리고 요청에 유효하지 않은 데이터가 있을 때 기본 JSON 응답을 반환하는 역할을 합니다.
+
+이 예외 핸들러들을 여러분의 것으로 오버라이드할 수 있습니다.
+
+### 요청 검증 예외 오버라이드하기 { #override-request-validation-exceptions }
+
+요청에 유효하지 않은 데이터가 포함되면, **FastAPI**는 내부적으로 `RequestValidationError`를 `raise`합니다.
+
+그리고 이에 대한 기본 예외 핸들러도 포함되어 있습니다.
+
+이를 오버라이드하려면 `RequestValidationError`를 가져오고, `@app.exception_handler(RequestValidationError)`로 예외 핸들러를 데코레이트해 사용하세요.
+
+예외 핸들러는 `Request`와 예외를 받습니다.
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
+
+이제 `/items/foo`로 이동하면, 다음과 같은 기본 JSON 오류 대신:
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ]
+}
+```
+
+다음과 같은 텍스트 버전을 받게 됩니다:
+
+```
+Validation errors:
+Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer
+```
+
+### `HTTPException` 오류 핸들러 오버라이드하기 { #override-the-httpexception-error-handler }
+
+같은 방식으로 `HTTPException` 핸들러도 오버라이드할 수 있습니다.
+
+예를 들어, 이런 오류들에 대해 JSON 대신 일반 텍스트 응답을 반환하고 싶을 수 있습니다:
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
+
+/// note | 기술 세부사항
+
+`from starlette.responses import PlainTextResponse`를 사용할 수도 있습니다.
+
+**FastAPI**는 개발자의 편의를 위해 `starlette.responses`를 `fastapi.responses`로도 동일하게 제공합니다. 하지만 사용 가능한 대부분의 응답은 Starlette에서 직접 옵니다.
+
+///
+
+/// warning | 경고
+
+`RequestValidationError`에는 검증 오류가 발생한 파일 이름과 줄 정보가 포함되어 있어, 원한다면 관련 정보와 함께 로그에 표시할 수 있다는 점을 유념하세요.
+
+하지만 이는 단순히 문자열로 변환해 그 정보를 그대로 반환하면 시스템에 대한 일부 정보를 누설할 수 있다는 뜻이기도 합니다. 그래서 여기의 코드는 각 오류를 독립적으로 추출해 보여줍니다.
+
+///
+
+### `RequestValidationError`의 body 사용하기 { #use-the-requestvalidationerror-body }
+
+`RequestValidationError`에는 유효하지 않은 데이터와 함께 받은 `body`가 포함됩니다.
+
+앱을 개발하는 동안 body를 로그로 남기고 디버그하거나, 사용자에게 반환하는 등으로 사용할 수 있습니다.
+
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
+
+이제 다음처럼 유효하지 않은 item을 보내보세요:
+
+```JSON
+{
+ "title": "towel",
+ "size": "XL"
+}
+```
+
+받은 body를 포함해 데이터가 유효하지 않다고 알려주는 응답을 받게 됩니다:
+
+```JSON hl_lines="12-15"
+{
+ "detail": [
+ {
+ "loc": [
+ "body",
+ "size"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ],
+ "body": {
+ "title": "towel",
+ "size": "XL"
+ }
+}
+```
+
+#### FastAPI의 `HTTPException` vs Starlette의 `HTTPException` { #fastapis-httpexception-vs-starlettes-httpexception }
+
+**FastAPI**에는 자체 `HTTPException`이 있습니다.
+
+그리고 **FastAPI**의 `HTTPException` 오류 클래스는 Starlette의 `HTTPException` 오류 클래스를 상속합니다.
+
+유일한 차이는 **FastAPI**의 `HTTPException`은 `detail` 필드에 JSON으로 변환 가능한 어떤 데이터든 받을 수 있는 반면, Starlette의 `HTTPException`은 문자열만 받을 수 있다는 점입니다.
+
+따라서 코드에서는 평소처럼 **FastAPI**의 `HTTPException`을 계속 `raise`하면 됩니다.
+
+하지만 예외 핸들러를 등록할 때는 Starlette의 `HTTPException`에 대해 등록해야 합니다.
+
+이렇게 하면 Starlette 내부 코드의 어떤 부분, 또는 Starlette 확장/플러그인이 Starlette `HTTPException`을 `raise`하더라도, 여러분의 핸들러가 이를 잡아서 처리할 수 있습니다.
+
+이 예시에서는 동일한 코드에서 두 `HTTPException`을 모두 사용할 수 있도록, Starlette의 예외를 `StarletteHTTPException`으로 이름을 바꿉니다:
+
+```Python
+from starlette.exceptions import HTTPException as StarletteHTTPException
+```
+
+### **FastAPI**의 예외 핸들러 재사용하기 { #reuse-fastapis-exception-handlers }
+
+예외를 사용하면서 **FastAPI**의 동일한 기본 예외 핸들러도 함께 사용하고 싶다면, `fastapi.exception_handlers`에서 기본 예외 핸들러를 가져와 재사용할 수 있습니다:
+
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
+
+이 예시에서는 매우 표현력 있는 메시지로 오류를 출력만 하고 있지만, 요지는 이해하셨을 겁니다. 예외를 사용한 뒤 기본 예외 핸들러를 그대로 재사용할 수 있습니다.
diff --git a/docs/ko/docs/tutorial/header-param-models.md b/docs/ko/docs/tutorial/header-param-models.md
new file mode 100644
index 0000000000000..70f02550674e7
--- /dev/null
+++ b/docs/ko/docs/tutorial/header-param-models.md
@@ -0,0 +1,72 @@
+# 헤더 매개변수 모델 { #header-parameter-models }
+
+관련 있는 **헤더 매개변수** 그룹이 있는 경우, **Pydantic 모델**을 생성하여 선언할 수 있습니다.
+
+이를 통해 **여러 위치**에서 **모델을 재사용할** 수 있고 모든 매개변수에 대한 유효성 검사 및 메타데이터를 한 번에 선언할 수도 있습니다. 😎
+
+/// note | 참고
+
+이 기능은 FastAPI 버전 `0.115.0` 이후부터 지원됩니다. 🤓
+
+///
+
+## Pydantic 모델을 사용한 헤더 매개변수 { #header-parameters-with-a-pydantic-model }
+
+**Pydantic 모델**에 필요한 **헤더 매개변수**를 선언한 다음, 해당 매개변수를 `Header`로 선언합니다:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI**는 요청에서 받은 **헤더**에서 **각 필드**에 대한 데이터를 **추출**하고 정의한 Pydantic 모델을 줍니다.
+
+## 문서 확인하기 { #check-the-docs }
+
+문서 UI `/docs`에서 필요한 헤더를 볼 수 있습니다:
+
+
+contact 필드| 매개변수 | 타입 | 설명 |
|---|---|---|
name | str | 연락처 인물/조직의 식별명입니다. |
url | str | 연락처 정보가 담긴 URL입니다. URL 형식이어야 합니다. |
email | str | 연락처 인물/조직의 이메일 주소입니다. 이메일 주소 형식이어야 합니다. |
license_info 필드| 매개변수 | 타입 | 설명 |
|---|---|---|
name | str | 필수 (license_info가 설정된 경우). API에 사용된 라이선스 이름입니다. |
identifier | str | API에 대한 [SPDX](https://spdx.org/licenses/) 라이선스 표현입니다. identifier 필드는 url 필드와 상호 배타적입니다. OpenAPI 3.1.0, FastAPI 0.99.0부터 사용 가능. |
url | str | API에 사용된 라이선스의 URL입니다. URL 형식이어야 합니다. |
+
+## 라이선스 식별자 { #license-identifier }
+
+OpenAPI 3.1.0 및 FastAPI 0.99.0부터 `license_info`에 `url` 대신 `identifier`를 설정할 수도 있습니다.
+
+예:
+
+{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}
+
+## 태그에 대한 메타데이터 { #metadata-for-tags }
+
+`openapi_tags` 매개변수를 사용하여 경로 처리를 그룹화하는 데 사용되는 여러 태그에 추가 메타데이터를 추가할 수도 있습니다.
+
+리스트는 각 태그에 대해 하나의 딕셔너리를 포함합니다.
+
+각 딕셔너리에는 다음이 포함될 수 있습니다:
+
+* `name` (**필수**): *경로 처리* 및 `APIRouter`의 `tags` 매개변수에서 사용하는 태그 이름과 동일한 `str`입니다.
+* `description`: 태그에 대한 간단한 설명을 담은 `str`입니다. 마크다운을 포함할 수 있으며 문서 UI에 표시됩니다.
+* `externalDocs`: 외부 문서를 설명하는 `dict`이며:
+ * `description`: 외부 문서에 대한 간단한 설명을 담은 `str`입니다.
+ * `url` (**필수**): 외부 문서의 URL을 담은 `str`입니다.
+
+### 태그에 대한 메타데이터 생성 { #create-metadata-for-tags }
+
+`users` 및 `items`에 대한 태그 예시로 시도해 보겠습니다.
+
+태그에 대한 메타데이터를 생성하고 이를 `openapi_tags` 매개변수로 전달하세요:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}
+
+설명 안에 마크다운을 사용할 수 있다는 점에 유의하세요. 예를 들어 "login"은 굵게(**login**) 표시되고, "fancy"는 기울임꼴(_fancy_)로 표시됩니다.
+
+/// tip | 팁
+
+사용 중인 모든 태그에 메타데이터를 추가할 필요는 없습니다.
+
+///
+
+### 태그 사용 { #use-your-tags }
+
+`tags` 매개변수를 *경로 처리* (및 `APIRouter`)와 함께 사용하여 이를 서로 다른 태그에 할당하세요:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}
+
+/// info | 정보
+
+태그에 대한 자세한 내용은 [경로 처리 구성](path-operation-configuration.md#tags)에서 읽어보세요.
+
+///
+
+### 문서 확인 { #check-the-docs }
+
+이제 문서를 확인하면 모든 추가 메타데이터가 표시됩니다:
+
+
+
+### 태그 순서 { #order-of-tags }
+
+각 태그 메타데이터 딕셔너리의 순서는 문서 UI에 표시되는 순서도 정의합니다.
+
+예를 들어, 알파벳 순서상 `users`는 `items` 뒤에 오지만, 우리는 해당 메타데이터를 리스트의 첫 번째 딕셔너리로 추가했기 때문에 먼저 표시됩니다.
+
+## OpenAPI URL { #openapi-url }
+
+기본적으로 OpenAPI 스키마는 `/openapi.json`에서 제공됩니다.
+
+하지만 `openapi_url` 매개변수로 이를 설정할 수 있습니다.
+
+예를 들어, 이를 `/api/v1/openapi.json`에서 제공하도록 설정하려면:
+
+{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}
+
+OpenAPI 스키마를 완전히 비활성화하려면 `openapi_url=None`으로 설정할 수 있으며, 이를 사용하여 문서화 사용자 인터페이스도 비활성화됩니다.
+
+## 문서화 URL { #docs-urls }
+
+포함된 두 가지 문서화 사용자 인터페이스를 설정할 수 있습니다:
+
+* **Swagger UI**: `/docs`에서 제공됩니다.
+ * `docs_url` 매개변수로 URL을 설정할 수 있습니다.
+ * `docs_url=None`으로 설정하여 비활성화할 수 있습니다.
+* **ReDoc**: `/redoc`에서 제공됩니다.
+ * `redoc_url` 매개변수로 URL을 설정할 수 있습니다.
+ * `redoc_url=None`으로 설정하여 비활성화할 수 있습니다.
+
+예를 들어, Swagger UI를 `/documentation`에서 제공하고 ReDoc을 비활성화하려면:
+
+{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}
diff --git a/docs/ko/docs/tutorial/middleware.md b/docs/ko/docs/tutorial/middleware.md
new file mode 100644
index 0000000000000..b459f6434e931
--- /dev/null
+++ b/docs/ko/docs/tutorial/middleware.md
@@ -0,0 +1,95 @@
+# 미들웨어 { #middleware }
+
+미들웨어를 **FastAPI** 애플리케이션에 추가할 수 있습니다.
+
+"미들웨어"는 특정 *경로 처리*에 의해 처리되기 전, 모든 **요청**에 대해서 동작하는 함수입니다. 또한 모든 **응답**이 반환되기 전에도 동일하게 동작합니다.
+
+* 미들웨어는 애플리케이션으로 오는 각 **요청**을 가져옵니다.
+* 그런 다음 해당 **요청**에 대해 무언가를 하거나 필요한 코드를 실행할 수 있습니다.
+* 그런 다음 **요청**을 나머지 애플리케이션(어떤 *경로 처리*가)을 통해 처리되도록 전달합니다.
+* 그런 다음 애플리케이션(어떤 *경로 처리*가)이 생성한 **응답**을 가져옵니다.
+* 그런 다음 해당 **응답**에 대해 무언가를 하거나 필요한 코드를 실행할 수 있습니다.
+* 그런 다음 **응답**을 반환합니다.
+
+/// note | 기술 세부사항
+
+`yield`를 사용하는 의존성이 있다면, exit 코드는 미들웨어 *후에* 실행됩니다.
+
+백그라운드 작업(뒤에서 보게 될 [백그라운드 작업](background-tasks.md) 섹션에서 다룹니다)이 있다면, 모든 미들웨어 *후에* 실행됩니다.
+
+///
+
+## 미들웨어 만들기 { #create-a-middleware }
+
+미들웨어를 만들기 위해 함수 상단에 데코레이터 `@app.middleware("http")`를 사용합니다.
+
+미들웨어 함수는 다음을 받습니다:
+
+* `request`.
+* `request`를 매개변수로 받는 `call_next` 함수.
+ * 이 함수는 `request`를 해당하는 *경로 처리*로 전달합니다.
+ * 그런 다음 해당 *경로 처리*가 생성한 `response`를 반환합니다.
+* 그런 다음 반환하기 전에 `response`를 추가로 수정할 수 있습니다.
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}
+
+/// tip | 팁
+
+사용자 정의 독점 헤더는 [`X-` 접두사를 사용](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers)하여 추가할 수 있다는 점을 기억하세요.
+
+하지만 브라우저에서 클라이언트가 볼 수 있게 하려는 사용자 정의 헤더가 있다면, [CORS (Cross-Origin Resource Sharing)](cors.md) 설정에 [Starlette의 CORS 문서](https://www.starlette.dev/middleware/#corsmiddleware)에 문서화된 `expose_headers` 매개변수를 사용해 추가해야 합니다.
+
+///
+
+/// note | 기술 세부사항
+
+`from starlette.requests import Request`를 사용할 수도 있습니다.
+
+**FastAPI**는 개발자인 여러분의 편의를 위해 이를 제공합니다. 하지만 이는 Starlette에서 직접 가져온 것입니다.
+
+///
+
+### `response`의 전과 후 { #before-and-after-the-response }
+
+어떤 *경로 처리*가 받기 전에, `request`와 함께 실행될 코드를 추가할 수 있습니다.
+
+또한 `response`가 생성된 후, 반환하기 전에 코드를 추가할 수도 있습니다.
+
+예를 들어, 요청을 처리하고 응답을 생성하는 데 걸린 시간을 초 단위로 담는 사용자 정의 헤더 `X-Process-Time`을 추가할 수 있습니다:
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}
+
+/// tip | 팁
+
+여기서는 이러한 사용 사례에서 더 정확할 수 있기 때문에 `time.time()` 대신 [`time.perf_counter()`](https://docs.python.org/3/library/time.html#time.perf_counter)를 사용합니다. 🤓
+
+///
+
+## 여러 미들웨어 실행 순서 { #multiple-middleware-execution-order }
+
+`@app.middleware()` 데코레이터 또는 `app.add_middleware()` 메서드를 사용해 여러 미들웨어를 추가하면, 새로 추가된 각 미들웨어가 애플리케이션을 감싸 스택을 형성합니다. 마지막에 추가된 미들웨어가 *가장 바깥쪽*이고, 처음에 추가된 미들웨어가 *가장 안쪽*입니다.
+
+요청 경로에서는 *가장 바깥쪽* 미들웨어가 먼저 실행됩니다.
+
+응답 경로에서는 마지막에 실행됩니다.
+
+예를 들어:
+
+```Python
+app.add_middleware(MiddlewareA)
+app.add_middleware(MiddlewareB)
+```
+
+이 경우 실행 순서는 다음과 같습니다:
+
+* **요청**: MiddlewareB → MiddlewareA → route
+
+* **응답**: route → MiddlewareA → MiddlewareB
+
+이러한 스태킹 동작은 미들웨어가 예측 가능하고 제어 가능한 순서로 실행되도록 보장합니다.
+
+## 다른 미들웨어 { #other-middlewares }
+
+다른 미들웨어에 대한 더 많은 정보는 나중에 [숙련된 사용자 안내서: 향상된 미들웨어](../advanced/middleware.md)에서 확인할 수 있습니다.
+
+다음 섹션에서 미들웨어로 CORS를 처리하는 방법을 보게 될 것입니다.
diff --git a/docs/ko/docs/tutorial/path-operation-configuration.md b/docs/ko/docs/tutorial/path-operation-configuration.md
new file mode 100644
index 0000000000000..ebdf6f918fdc2
--- /dev/null
+++ b/docs/ko/docs/tutorial/path-operation-configuration.md
@@ -0,0 +1,107 @@
+# 경로 처리 설정 { #path-operation-configuration }
+
+*경로 처리 데코레이터*를 설정하기 위해 전달할 수 있는 몇 가지 매개변수가 있습니다.
+
+/// warning | 경고
+
+아래 매개변수들은 *경로 처리 함수*가 아닌 *경로 처리 데코레이터*에 직접 전달된다는 사실을 기억하세요.
+
+///
+
+## 응답 상태 코드 { #response-status-code }
+
+*경로 처리*의 응답에 사용될 (HTTP) `status_code`를 정의할 수 있습니다.
+
+`404`와 같은 `int`형 코드를 직접 전달할 수 있습니다.
+
+하지만 각 숫자 코드가 무엇을 의미하는지 기억하지 못한다면, `status`에 있는 단축 상수들을 사용할 수 있습니다:
+
+{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *}
+
+해당 상태 코드는 응답에 사용되며, OpenAPI 스키마에 추가됩니다.
+
+/// note | 기술 세부사항
+
+다음과 같이 임포트하셔도 좋습니다. `from starlette import status`.
+
+**FastAPI**는 개발자 여러분의 편의를 위해 `starlette.status`와 동일한 `fastapi.status`를 제공합니다. 하지만 이는 Starlette에서 직접 온 것입니다.
+
+///
+
+## 태그 { #tags }
+
+(보통 단일 `str`인) `str`로 구성된 `list`와 함께 매개변수 `tags`를 전달하여, *경로 처리*에 태그를 추가할 수 있습니다:
+
+{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *}
+
+전달된 태그들은 OpenAPI의 스키마에 추가되며, 자동 문서 인터페이스에서 사용됩니다:
+
+
+
+### Enum을 사용한 태그 { #tags-with-enums }
+
+큰 애플리케이션이 있다면, **여러 태그**가 쌓이게 될 수 있고, 관련된 *경로 처리*에 항상 **같은 태그**를 사용하는지 확인하고 싶을 것입니다.
+
+이런 경우에는 태그를 `Enum`에 저장하는 것이 합리적일 수 있습니다.
+
+**FastAPI**는 일반 문자열과 동일한 방식으로 이를 지원합니다:
+
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
+
+## 요약과 설명 { #summary-and-description }
+
+`summary`와 `description`을 추가할 수 있습니다:
+
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *}
+
+## 독스트링으로 만든 설명 { #description-from-docstring }
+
+설명은 보통 길어지고 여러 줄에 걸쳐있기 때문에, *경로 처리* 설명을 함수 독스트링에 선언할 수 있으며, **FastAPI**는 그곳에서 이를 읽습니다.
+
+독스트링에는 [Markdown](https://en.wikipedia.org/wiki/Markdown)을 작성할 수 있으며, (독스트링의 들여쓰기를 고려하여) 올바르게 해석되고 표시됩니다.
+
+{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}
+
+이는 대화형 문서에서 사용됩니다:
+
+
+
+## 응답 설명 { #response-description }
+
+`response_description` 매개변수로 응답에 관한 설명을 명시할 수 있습니다:
+
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
+
+/// info | 정보
+
+`response_description`은 구체적으로 응답을 지칭하며, `description`은 일반적인 *경로 처리*를 지칭합니다.
+
+///
+
+/// check | 확인
+
+OpenAPI는 각 *경로 처리*가 응답에 관한 설명을 요구할 것을 명시합니다.
+
+따라서, 응답에 관한 설명을 제공하지 않으면, **FastAPI**가 "Successful response" 중 하나를 자동으로 생성합니다.
+
+///
+
+
+
+## *경로 처리* 지원중단하기 { #deprecate-a-path-operation }
+
+*경로 처리*를 제거하지 않고 지원중단으로 표시해야 한다면, `deprecated` 매개변수를 전달하면 됩니다:
+
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
+
+대화형 문서에서 지원중단으로 명확하게 표시됩니다:
+
+
+
+지원중단된 *경로 처리*와 지원중단되지 않은 *경로 처리*가 어떻게 보이는지 확인해 보세요:
+
+
+
+## 정리 { #recap }
+
+*경로 처리 데코레이터*에 매개변수(들)를 전달하여 *경로 처리*를 설정하고 메타데이터를 쉽게 추가할 수 있습니다.
diff --git a/docs/ko/docs/tutorial/path-params-numeric-validations.md b/docs/ko/docs/tutorial/path-params-numeric-validations.md
index cadf543fc69fe..2ff56c46e7be3 100644
--- a/docs/ko/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/ko/docs/tutorial/path-params-numeric-validations.md
@@ -1,122 +1,154 @@
-# 경로 매개변수와 숫자 검증
+# 경로 매개변수와 숫자 검증 { #path-parameters-and-numeric-validations }
`Query`를 사용하여 쿼리 매개변수에 더 많은 검증과 메타데이터를 선언하는 방법과 동일하게 `Path`를 사용하여 경로 매개변수에 검증과 메타데이터를 같은 타입으로 선언할 수 있습니다.
-## 경로 임포트
+## `Path` 임포트 { #import-path }
-먼저 `fastapi`에서 `Path`를 임포트합니다:
+먼저 `fastapi`에서 `Path`를 임포트하고, `Annotated`도 임포트합니다:
-```Python hl_lines="3"
-{!../../../docs_src/path_params_numeric_validations/tutorial001.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
-## 메타데이터 선언
+/// info | 정보
+
+FastAPI는 0.95.0 버전에서 `Annotated` 지원을 추가했고(그리고 이를 권장하기 시작했습니다).
+
+더 오래된 버전이 있다면 `Annotated`를 사용하려고 할 때 오류가 발생합니다.
+
+`Annotated`를 사용하기 전에 최소 0.95.1까지 [FastAPI 버전 업그레이드](../deployment/versions.md#upgrading-the-fastapi-versions)를 꼭 하세요.
+
+///
+
+## 메타데이터 선언 { #declare-metadata }
`Query`에 동일한 매개변수를 선언할 수 있습니다.
-예를 들어, `title` 메타데이터 값을 경로 매개변수 `item_id`에 선언하려면 다음과 같이 입력할 수 있습니다:
+예를 들어, 경로 매개변수 `item_id`에 `title` 메타데이터 값을 선언하려면 다음과 같이 입력할 수 있습니다:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *}
-```Python hl_lines="10"
-{!../../../docs_src/path_params_numeric_validations/tutorial001.py!}
-```
+/// note | 참고
-!!! note "참고"
- 경로 매개변수는 경로의 일부여야 하므로 언제나 필수적입니다.
+경로 매개변수는 경로의 일부여야 하므로 언제나 필수입니다. `None`으로 선언하거나 기본값을 지정하더라도 아무 영향이 없으며, 항상 필수입니다.
- 즉, `...`로 선언해서 필수임을 나타내는게 좋습니다.
+///
- 그럼에도 `None`으로 선언하거나 기본값을 지정할지라도 아무 영향을 끼치지 않으며 언제나 필수입니다.
+## 필요한 대로 매개변수 정렬하기 { #order-the-parameters-as-you-need }
-## 필요한 경우 매개변수 정렬하기
+/// tip | 팁
+
+`Annotated`를 사용한다면 이것은 아마 그렇게 중요하지 않거나 필요하지 않을 수 있습니다.
+
+///
`str` 형인 쿼리 매개변수 `q`를 필수로 선언하고 싶다고 해봅시다.
-해당 매개변수에 대해 아무런 선언을 할 필요가 없으므로 `Query`를 정말로 써야할 필요는 없습니다.
+해당 매개변수에 대해 아무런 선언을 할 필요가 없으므로 `Query`를 정말로 써야 할 필요는 없습니다.
+
+하지만 `item_id` 경로 매개변수는 여전히 `Path`를 사용해야 합니다. 그리고 어떤 이유로 `Annotated`를 사용하고 싶지 않다고 해봅시다.
+
+파이썬은 "기본값"이 있는 값을 "기본값"이 없는 값 앞에 두면 불평합니다.
+
+하지만 순서를 재정렬해서 기본값이 없는 값(쿼리 매개변수 `q`)을 앞에 둘 수 있습니다.
+
+**FastAPI**에서는 중요하지 않습니다. 이름, 타입 그리고 기본값 선언(`Query`, `Path` 등)로 매개변수를 감지하며 순서는 신경 쓰지 않습니다.
-하지만 `item_id` 경로 매개변수는 여전히 `Path`를 사용해야 합니다.
+따라서 함수를 다음과 같이 선언할 수 있습니다:
-파이썬은 "기본값"이 없는 값 앞에 "기본값"이 있는 값을 입력하면 불평합니다.
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
-그러나 매개변수들을 재정렬함으로써 기본값(쿼리 매개변수 `q`)이 없는 값을 처음 부분에 위치 할 수 있습니다.
+하지만 `Annotated`를 사용하면 이 문제가 없다는 점을 기억하세요. `Query()`나 `Path()`에 함수 매개변수 기본값을 사용하지 않기 때문에, 순서는 중요하지 않습니다.
-**FastAPI**에서는 중요하지 않습니다. 이름, 타입 그리고 선언구(`Query`, `Path` 등)로 매개변수를 감지하며 순서는 신경 쓰지 않습니다.
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
-따라서 함수를 다음과 같이 선언 할 수 있습니다:
+## 필요한 대로 매개변수 정렬하기, 트릭 { #order-the-parameters-as-you-need-tricks }
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial002.py!}
-```
+/// tip | 팁
-## 필요한 경우 매개변수 정렬하기, 트릭
+`Annotated`를 사용한다면 이것은 아마 그렇게 중요하지 않거나 필요하지 않을 수 있습니다.
-`Query`나 아무런 기본값으로도 `q` 경로 매개변수를 선언하고 싶지 않지만 `Path`를 사용하여 경로 매개변수를 `item_id` 다른 순서로 선언하고 싶다면, 파이썬은 이를 위한 작고 특별한 문법이 있습니다.
+///
-`*`를 함수의 첫 번째 매개변수로 전달하세요.
+유용할 수 있는 **작은 트릭**이 하나 있지만, 자주 필요하진 않을 겁니다.
-파이썬은 `*`으로 아무런 행동도 하지 않지만, 따르는 매개변수들은 kwargs로도 알려진 키워드 인자(키-값 쌍)여야 함을 인지합니다. 기본값을 가지고 있지 않더라도 그렇습니다.
+만약 다음을 원한다면:
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
-```
+* `Query`나 어떤 기본값 없이 쿼리 매개변수 `q`를 선언하기
+* `Path`를 사용해서 경로 매개변수 `item_id`를 선언하기
+* 이들을 다른 순서로 두기
+* `Annotated`를 사용하지 않기
-## 숫자 검증: 크거나 같음
+...이를 위해 파이썬에는 작은 특별한 문법이 있습니다.
-`Query`와 `Path`(나중에 볼 다른 것들도)를 사용하여 문자열 뿐만 아니라 숫자의 제약을 선언할 수 있습니다.
+함수의 첫 번째 매개변수로 `*`를 전달하세요.
-여기서 `ge=1`인 경우, `item_id`는 `1`보다 "크거나(`g`reater) 같은(`e`qual)" 정수형 숫자여야 합니다.
+파이썬은 `*`으로 아무것도 하지 않지만, 뒤따르는 모든 매개변수는 키워드 인자(키-값 쌍)로 호출되어야 함을 알게 됩니다. 이는 kwargs로도 알려져 있습니다. 기본값이 없더라도 마찬가지입니다.
-```Python hl_lines="8"
-{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
-## 숫자 검증: 크거나 같음 및 작거나 같음
+### `Annotated`를 쓰면 더 좋습니다 { #better-with-annotated }
+
+`Annotated`를 사용하면 함수 매개변수 기본값을 사용하지 않기 때문에 이 문제가 발생하지 않으며, 아마 `*`도 사용할 필요가 없다는 점을 기억하세요.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
+
+## 숫자 검증: 크거나 같음 { #number-validations-greater-than-or-equal }
+
+`Query`와 `Path`(그리고 나중에 볼 다른 것들)를 사용하여 숫자 제약을 선언할 수 있습니다.
+
+여기서 `ge=1`인 경우, `item_id`는 `1`보다 "`g`reater than or `e`qual"(크거나 같은) 정수형 숫자여야 합니다.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
+
+## 숫자 검증: 크거나 및 작거나 같음 { #number-validations-greater-than-and-less-than-or-equal }
동일하게 적용됩니다:
-* `gt`: 크거나(`g`reater `t`han)
-* `le`: 작거나 같은(`l`ess than or `e`qual)
+* `gt`: `g`reater `t`han
+* `le`: `l`ess than or `e`qual
-```Python hl_lines="9"
-{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
-## 숫자 검증: 부동소수, 크거나 및 작거나
+## 숫자 검증: 부동소수, 크거나 및 작거나 { #number-validations-floats-greater-than-and-less-than }
숫자 검증은 `float` 값에도 동작합니다.
-여기에서 ge뿐만 아니라 gt를 선언 할 수있는 것이 중요해집니다. 예를 들어 필요한 경우, 값이 `1`보다 작더라도 반드시 `0`보다 커야합니다.
+여기에서 gt를, ge뿐만 아니라 선언할 수 있다는 점이 중요해집니다. 예를 들어 값이 `1`보다 작더라도, 반드시 `0`보다 커야 한다고 요구할 수 있습니다.
즉, `0.5`는 유효한 값입니다. 그러나 `0.0` 또는 `0`은 그렇지 않습니다.
-lt 역시 마찬가지입니다.
+lt 역시 마찬가지입니다.
-```Python hl_lines="11"
-{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
-## 요약
+## 요약 { #recap }
-`Query`, `Path`(아직 보지 못한 다른 것들도)를 사용하면 [쿼리 매개변수와 문자열 검증](query-params-str-validations.md){.internal-link target=_blank}에서와 마찬가지로 메타데이터와 문자열 검증을 선언할 수 있습니다.
+`Query`, `Path`(아직 보지 못한 다른 것들도)를 사용하면 [쿼리 매개변수와 문자열 검증](query-params-str-validations.md)에서와 마찬가지로 메타데이터와 문자열 검증을 선언할 수 있습니다.
그리고 숫자 검증 또한 선언할 수 있습니다:
-* `gt`: 크거나(`g`reater `t`han)
-* `ge`: 크거나 같은(`g`reater than or `e`qual)
-* `lt`: 작거나(`l`ess `t`han)
-* `le`: 작거나 같은(`l`ess than or `e`qual)
+* `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` 클래스의 서브클래스입니다.
+
+이들 모두는 여러분이 본 추가 검증과 메타데이터에 대한 동일한 매개변수를 공유합니다.
+
+///
-!!! info "정보"
- `Query`, `Path`, 그리고 나중에게 보게될 것들은 (여러분이 사용할 필요가 없는) 공통 `Param` 클래스의 서브 클래스입니다.
+/// note | 기술 세부사항
- 그리고 이들 모두는 여태까지 본 추가 검증과 메타데이터의 동일한 모든 매개변수를 공유합니다.
+`fastapi`에서 `Query`, `Path` 등을 임포트할 때, 이것들은 실제로 함수입니다.
-!!! note "기술 세부사항"
- `fastapi`에서 `Query`, `Path` 등을 임포트 할 때, 이것들은 실제로 함수입니다.
+호출되면 동일한 이름의 클래스의 인스턴스를 반환합니다.
- 호출되면 동일한 이름의 클래스의 인스턴스를 반환합니다.
+즉, 함수인 `Query`를 임포트한 겁니다. 그리고 호출하면 `Query`라는 이름을 가진 클래스의 인스턴스를 반환합니다.
- 즉, 함수인 `Query`를 임포트한 겁니다. 그리고 호출하면 `Query`라는 이름을 가진 클래스의 인스턴스를 반환합니다.
+이 함수들이 있는 이유는(클래스를 직접 사용하는 대신) 편집기에서 타입에 대한 오류를 표시하지 않도록 하기 위해서입니다.
- 편집기에서 타입에 대한 오류를 표시하지 않도록 하기 위해 (클래스를 직접 사용하는 대신) 이러한 함수들이 있습니다.
+이렇게 하면 오류를 무시하기 위한 사용자 설정을 추가하지 않고도 일반 편집기와 코딩 도구를 사용할 수 있습니다.
- 이렇게 하면 오류를 무시하기 위한 사용자 설정을 추가하지 않고도 일반 편집기와 코딩 도구를 사용할 수 있습니다.
+///
diff --git a/docs/ko/docs/tutorial/path-params.md b/docs/ko/docs/tutorial/path-params.md
index 5cf397e7ae0e2..c6ea6b7c1655a 100644
--- a/docs/ko/docs/tutorial/path-params.md
+++ b/docs/ko/docs/tutorial/path-params.md
@@ -1,190 +1,196 @@
-# 경로 매개변수
+# 경로 매개변수 { #path-parameters }
-파이썬 포맷 문자열이 사용하는 동일한 문법으로 "매개변수" 또는 "변수"를 경로에 선언할 수 있습니다:
+파이썬의 포맷 문자열 리터럴에서 사용되는 문법을 이용하여 경로 "매개변수" 또는 "변수"를 선언할 수 있습니다:
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
경로 매개변수 `item_id`의 값은 함수의 `item_id` 인자로 전달됩니다.
-그래서 이 예제를 실행하고 http://127.0.0.1:8000/items/foo로 이동하면, 다음 응답을 볼 수 있습니다:
+그래서 이 예제를 실행하고 [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo)로 이동하면, 다음 응답을 볼 수 있습니다:
```JSON
{"item_id":"foo"}
```
-## 타입이 있는 매개변수
+## 타입이 있는 경로 매개변수 { #path-parameters-with-types }
파이썬 표준 타입 어노테이션을 사용하여 함수에 있는 경로 매개변수의 타입을 선언할 수 있습니다:
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
+{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}
+
+위의 예시에서, `item_id`는 `int`로 선언되었습니다.
+
+/// check | 확인
-지금과 같은 경우, `item_id`는 `int`로 선언 되었습니다.
+이 기능은 함수 내에서 오류 검사, 자동완성 등의 편집기 기능을 활용할 수 있게 해줍니다.
-!!! check "확인"
- 이 기능은 함수 내에서 오류 검사, 자동완성 등을 편집기를 지원합니다
+///
-## 데이터 변환
+## 데이터 변환 { #data-conversion }
-이 예제를 실행하고 http://127.0.0.1:8000/items/3을 열면, 다음 응답을 볼 수 있습니다:
+이 예제를 실행하고 [http://127.0.0.1:8000/items/3](http://127.0.0.1:8000/items/3)을 열면, 다음 응답을 볼 수 있습니다:
```JSON
{"item_id":3}
```
-!!! check "확인"
- 함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다.
+/// check | 확인
- 즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 "파싱"합니다.
+함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다.
-## 데이터 검증
+즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 "파싱"합니다.
-하지만 브라우저에서 http://127.0.0.1:8000/items/foo로 이동하면, 멋진 HTTP 오류를 볼 수 있습니다:
+///
+
+## 데이터 검증 { #data-validation }
+
+하지만 브라우저에서 [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo)로 이동하면, 다음과 같은 HTTP 오류를 볼 수 있습니다:
```JSON
{
- "detail": [
- {
- "loc": [
- "path",
- "item_id"
- ],
- "msg": "value is not a valid integer",
- "type": "type_error.integer"
- }
- ]
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo"
+ }
+ ]
}
```
-경로 매개변수 `item_id`는 `int`가 아닌 `"foo"` 값이기 때문입니다.
+경로 매개변수 `item_id`가 `int`가 아닌 `"foo"` 값을 가졌기 때문입니다.
+
+`int` 대신 `float`을 제공하면(예: [http://127.0.0.1:8000/items/4.2](http://127.0.0.1:8000/items/4.2)) 동일한 오류가 나타납니다.
-`int` 대신 `float`을 전달하면 동일한 오류가 나타납니다: http://127.0.0.1:8000/items/4.2
+/// check | 확인
-!!! check "확인"
- 즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다.
+즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다.
- 오류는 검증을 통과하지 못한 지점도 정확하게 명시합니다.
+또한 오류에는 검증을 통과하지 못한 지점이 정확히 명시됩니다.
- 이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다.
+이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다.
-## 문서화
+///
-그리고 브라우저에서 http://127.0.0.1:8000/docs를 열면, 다음과 같이 자동 대화식 API 문서를 볼 수 있습니다:
+## 문서화 { #documentation }
+
+그리고 브라우저에서 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)를 열면, 다음과 같이 자동 대화식 API 문서를 볼 수 있습니다:
-!!! check "확인"
- 다시 한번, 그저 파이썬 타입 선언을 하기만 하면 **FastAPI**는 자동 대화식 API 문서(Swagger UI 통합)를 제공합니다.
+/// check | 확인
+
+다시 한 번, 동일한 파이썬 타입 선언만으로 **FastAPI**는 자동 대화형 문서(Swagger UI 통합)를 제공합니다.
+
+경로 매개변수가 정수형으로 선언된 것을 확인할 수 있습니다.
- 경로 매개변수는 정수형으로 선언됐음을 주목하세요.
+///
-## 표준 기반의 이점, 대체 문서화
+## 표준 기반의 이점, 대체 문서 { #standards-based-benefits-alternative-documentation }
-그리고 생성된 스키마는 OpenAPI 표준에서 나온 것이기 때문에 호환되는 도구가 많이 있습니다.
+그리고 생성된 스키마는 [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md) 표준에서 나온 것이기 때문에 호환되는 도구가 많이 있습니다.
-이 덕분에 **FastAPI**는 http://127.0.0.1:8000/redoc로 접속할 수 있는 (ReDoc을 사용하는) 대체 API 문서를 제공합니다:
+이 덕분에 **FastAPI** 자체에서 [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc)로 접속할 수 있는 (ReDoc을 사용하는) 대체 API 문서를 제공합니다:
-이와 마찬가지로 호환되는 도구가 많이 있습니다. 다양한 언어에 대한 코드 생성 도구를 포함합니다.
+이와 마찬가지로 다양한 언어에 대한 코드 생성 도구를 포함하여 여러 호환되는 도구가 있습니다.
-## Pydantic
+## Pydantic { #pydantic }
-모든 데이터 검증은 Pydantic에 의해 내부적으로 수행되므로 이로 인한 모든 이점을 얻을 수 있습니다. 여러분은 관리를 잘 받고 있음을 느낄 수 있습니다.
+모든 데이터 검증은 [Pydantic](https://docs.pydantic.dev/)에 의해 내부적으로 수행되므로 이로 인한 이점을 모두 얻을 수 있습니다. 여러분은 관리를 잘 받고 있음을 느낄 수 있습니다.
-`str`, `float`, `bool`과 다른 복잡한 데이터 타입 선언을 할 수 있습니다.
+`str`, `float`, `bool`, 그리고 다른 여러 복잡한 데이터 타입 선언을 할 수 있습니다.
-이 중 몇 가지는 자습서의 다음 장에서 살펴봅니다.
+이 중 몇 가지는 자습서의 다음 장에 설명되어 있습니다.
-## 순서 문제
+## 순서 문제 { #order-matters }
-*경로 동작*을 만들때 고정 경로를 갖고 있는 상황들을 맞닦뜨릴 수 있습니다.
+*경로 처리*를 만들 때 고정 경로를 갖고 있는 상황들을 맞닥뜨릴 수 있습니다.
`/users/me`처럼, 현재 사용자의 데이터를 가져온다고 합시다.
사용자 ID를 이용해 특정 사용자의 정보를 가져오는 경로 `/users/{user_id}`도 있습니다.
-*경로 동작*은 순차적으로 평가되기 때문에 `/users/{user_id}` 이전에 `/users/me`를 먼저 선언해야 합니다:
+*경로 처리*는 순차적으로 평가되기 때문에 `/users/me`에 대한 경로가 `/users/{user_id}` 이전에 먼저 선언되었는지 확인해야 합니다:
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
-```
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
+
+그렇지 않으면 `/users/{user_id}`에 대한 경로가 `/users/me`에도 매칭되어, 매개변수 `user_id`에 `"me"` 값이 들어왔다고 "생각하게" 됩니다.
+
+마찬가지로, 경로 처리를 재정의할 수는 없습니다:
-그렇지 않으면 `/users/{user_id}`는 매개변수 `user_id`의 값을 `"me"`라고 "생각하여" `/users/me`도 연결합니다.
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
-## 사전정의 값
+경로가 먼저 매칭되기 때문에 첫 번째 것이 항상 사용됩니다.
-만약 *경로 매개변수*를 받는 *경로 동작*이 있지만, 유효하고 미리 정의할 수 있는 *경로 매개변수* 값을 원한다면 파이썬 표준 `Enum`을 사용할 수 있습니다.
+## 사전정의 값 { #predefined-values }
-### `Enum` 클래스 생성
+만약 *경로 매개변수*를 받는 *경로 처리*가 있지만, 가능한 유효한 *경로 매개변수* 값들을 미리 정의하고 싶다면 파이썬 표준 `Enum`을 사용할 수 있습니다.
+
+### `Enum` 클래스 생성 { #create-an-enum-class }
`Enum`을 임포트하고 `str`과 `Enum`을 상속하는 서브 클래스를 만듭니다.
-`str`을 상속함으로써 API 문서는 값이 `string` 형이어야 하는 것을 알게 되고 제대로 렌더링 할 수 있게 됩니다.
+`str`을 상속함으로써 API 문서는 값이 `string` 형이어야 하는 것을 알게 되고 이는 문서에 제대로 표시됩니다.
-고정값으로 사용할 수 있는 유효한 클래스 어트리뷰트를 만듭니다:
+가능한 값들에 해당하는 고정된 값의 클래스 어트리뷰트들을 만듭니다:
-```Python hl_lines="1 6-9"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
-!!! info "정보"
- 열거형(또는 enums)은 파이썬 버전 3.4 이후로 사용가능합니다.
+/// tip | 팁
-!!! tip "팁"
- 혹시 헷갈린다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 기계 학습 모델들의 이름입니다.
+혹시 궁금하다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 머신 러닝 모델들의 이름입니다.
-### *경로 매개변수* 선언
+///
-생성한 열거형 클래스(`ModelName`)를 사용하는 타입 어노테이션으로 *경로 매개변수*를 만듭니다:
+### *경로 매개변수* 선언 { #declare-a-path-parameter }
-```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+생성한 열거형 클래스(`ModelName`)를 사용하는 타입 어노테이션으로 *경로 매개변수를* 만듭니다:
-### 문서 확인
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
-*경로 매개변수*에 사용할 수 있는 값은 미리 정의되어 있으므로 대화형 문서에서 멋지게 표시됩니다:
+### 문서 확인 { #check-the-docs }
+
+*경로 매개변수*에 사용할 수 있는 값은 미리 정의되어 있으므로 대화형 문서에서 잘 표시됩니다:
-### 파이썬 *열거형*으로 작업하기
+### 파이썬 *열거형*으로 작업하기 { #working-with-python-enumerations }
*경로 매개변수*의 값은 *열거형 멤버*가 됩니다.
-#### *열거형 멤버* 비교
+#### *열거형 멤버* 비교 { #compare-enumeration-members }
-열거체 `ModelName`의 *열거형 멤버*를 비교할 수 있습니다:
+생성한 열거형 `ModelName`의 *열거형 멤버*와 비교할 수 있습니다:
-```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}
-#### *열거형 값* 가져오기
+#### *열거형 값* 가져오기 { #get-the-enumeration-value }
-`model_name.value` 또는 일반적으로 `your_enum_member.value`를 이용하여 실제값(지금의 경우 `str`)을 가져올 수 있습니다:
+`model_name.value` 또는 일반적으로 `your_enum_member.value`를 이용하여 실제 값(위 예시의 경우 `str`)을 가져올 수 있습니다:
-```Python hl_lines="20"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}
-!!! tip "팁"
- `ModelName.lenet.value`로도 값 `"lenet"`에 접근할 수 있습니다.
+/// tip | 팁
-#### *열거형 멤버* 반환
+`ModelName.lenet.value`로도 값 `"lenet"`에 접근할 수 있습니다.
-*경로 동작*에서 중첩 JSON 본문(예: `dict`) 역시 *열거형 멤버*를 반환할 수 있습니다.
+///
+
+#### *열거형 멤버* 반환 { #return-enumeration-members }
+
+*경로 처리*에서 *enum 멤버*를 반환할 수 있습니다. 이는 JSON 본문(예: `dict`) 내에 중첩된 형태로도 가능합니다.
클라이언트에 반환하기 전에 해당 값(이 경우 문자열)으로 변환됩니다:
-```Python hl_lines="18 21 23"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}
-클라이언트는 아래의 JSON 응답을 얻습니다:
+클라이언트는 아래와 같은 JSON 응답을 얻게 됩니다:
```JSON
{
@@ -193,52 +199,53 @@
}
```
-## 경로를 포함하는 경로 매개변수
+## 경로를 포함하는 경로 매개변수 { #path-parameters-containing-paths }
-`/files/{file_path}`가 있는 *경로 동작*이 있다고 해봅시다.
+경로 `/files/{file_path}`를 가진 *경로 처리*가 있다고 해봅시다.
-그런데 여러분은 `home/johndoe/myfile.txt`처럼 *path*에 들어있는 `file_path` 자체가 필요합니다.
+하지만 `file_path` 자체가 `home/johndoe/myfile.txt`와 같은 *경로*를 포함해야 합니다.
-따라서 해당 파일의 URL은 다음처럼 됩니다: `/files/home/johndoe/myfile.txt`.
+이때 해당 파일의 URL은 다음처럼 됩니다: `/files/home/johndoe/myfile.txt`.
-### OpenAPI 지원
+### OpenAPI 지원 { #openapi-support }
테스트와 정의가 어려운 시나리오로 이어질 수 있으므로 OpenAPI는 *경로*를 포함하는 *경로 매개변수*를 내부에 선언하는 방법을 지원하지 않습니다.
-그럼에도 Starlette의 내부 도구중 하나를 사용하여 **FastAPI**에서는 할 수 있습니다.
+그럼에도 Starlette의 내부 도구 중 하나를 사용하여 **FastAPI**에서는 이가 가능합니다.
-매개변수에 경로가 포함되어야 한다는 문서를 추가하지 않아도 문서는 계속 작동합니다.
+또한 문서가 여전히 동작하긴 하지만, 매개변수에 경로가 포함되어야 한다는 내용을 추가로 문서화하지는 않습니다.
-### 경로 변환기
+### 경로 변환기 { #path-convertor }
-Starlette에서 직접 옵션을 사용하면 다음과 같은 URL을 사용하여 *path*를 포함하는 *경로 매개변수*를 선언 할 수 있습니다:
+Starlette의 옵션을 직접 이용하여 다음과 같은 URL을 사용함으로써 *경로*를 포함하는 *경로 매개변수*를 선언할 수 있습니다:
```
/files/{file_path:path}
```
-이러한 경우 매개변수의 이름은 `file_path`이고 마지막 부분 `:path`는 매개변수가 *경로*와 일치해야함을 알려줍니다.
+이러한 경우 매개변수의 이름은 `file_path`이며, 마지막 부분 `:path`는 매개변수가 어떤 *경로*와도 매칭되어야 함을 의미합니다.
-그러므로 다음과 같이 사용할 수 있습니다:
+따라서 다음과 같이 사용할 수 있습니다:
-```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
-```
+{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}
+
+/// tip | 팁
+
+매개변수가 선행 슬래시(`/`)가 있는 `/home/johndoe/myfile.txt`를 포함해야 할 수도 있습니다.
-!!! tip "팁"
- 매개변수가 `/home/johndoe/myfile.txt`를 갖고 있어 슬래시로 시작(`/`)해야 할 수 있습니다.
+그 경우 URL은: `/files//home/johndoe/myfile.txt`이며 `files`와 `home` 사이에 이중 슬래시(`//`)가 생깁니다.
- 이 경우 URL은: `/files//home/johndoe/myfile.txt`이며 `files`과 `home` 사이에 이중 슬래시(`//`)가 생깁니다.
+///
-## 요약
+## 요약 { #recap }
-**FastAPI**과 함께라면 짧고 직관적인 표준 파이썬 타입 선언을 사용하여 다음을 얻을 수 있습니다:
+**FastAPI**를 이용하면 짧고 직관적인 표준 파이썬 타입 선언을 사용하여 다음을 얻을 수 있습니다:
* 편집기 지원: 오류 검사, 자동완성 등
-* 데이터 "파싱"
+* 데이터 "파싱"
* 데이터 검증
* API 주석(Annotation)과 자동 문서
-위 사항들을 그저 한번에 선언하면 됩니다.
+그리고 한 번만 선언하면 됩니다.
-이는 (원래 성능과는 별개로) 대체 프레임워크와 비교했을 때 **FastAPI**의 주요 가시적 장점일 것입니다.
+이는 대체 프레임워크와 비교했을 때 (엄청나게 빠른 성능 외에도) **FastAPI**의 주요한 장점일 것입니다.
diff --git a/docs/ko/docs/tutorial/query-param-models.md b/docs/ko/docs/tutorial/query-param-models.md
new file mode 100644
index 0000000000000..d354c56c3dbec
--- /dev/null
+++ b/docs/ko/docs/tutorial/query-param-models.md
@@ -0,0 +1,68 @@
+# 쿼리 매개변수 모델 { #query-parameter-models }
+
+연관된 **쿼리 매개변수** 그룹이 있다면 이를 선언하기 위해 **Pydantic 모델**을 생성할 수 있습니다.
+
+이렇게 하면 **여러 곳**에서 **모델을 재사용**할 수 있을 뿐만 아니라, 매개변수에 대한 검증 및 메타데이터도 한 번에 선언할 수 있습니다. 😎
+
+/// note | 참고
+
+이 기능은 FastAPI 버전 `0.115.0`부터 지원됩니다. 🤓
+
+///
+
+## Pydantic 모델과 쿼리 매개변수 { #query-parameters-with-a-pydantic-model }
+
+필요한 **쿼리 매개변수**를 **Pydantic 모델** 안에 선언한 다음, 매개변수를 `Query`로 선언합니다:
+
+{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}
+
+**FastAPI**는 요청의 **쿼리 매개변수**에서 **각 필드**의 데이터를 **추출**해 정의한 Pydantic 모델을 제공합니다.
+
+## 문서 확인하기 { #check-the-docs }
+
+`/docs`의 문서 UI에서 쿼리 매개변수를 확인할 수 있습니다:
+
+
+
+
+### 쿼리 매개변수 리스트 / 기본값이 있는 다중값 { #query-parameter-list-multiple-values-with-defaults }
+
+제공된 값이 없으면 기본 `list` 값을 정의할 수도 있습니다:
+
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
+
+다음으로 이동하면:
+
+```
+http://localhost:8000/items/
+```
+
+`q`의 기본값은 `["foo", "bar"]`가 되고, 응답은 다음이 됩니다:
+
+```JSON
+{
+ "q": [
+ "foo",
+ "bar"
+ ]
+}
+```
+
+#### `list`만 사용하기 { #using-just-list }
+
+`list[str]` 대신 `list`를 직접 사용할 수도 있습니다:
+
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
+
+/// note | 참고
+
+이 경우 FastAPI는 리스트의 내용을 검사하지 않음을 명심하세요.
+
+예를 들어, `list[int]`는 리스트 내용이 정수인지 검사(및 문서화)합니다. 하지만 `list` 단독일 경우는 아닙니다.
+
+///
+
+## 더 많은 메타데이터 선언 { #declare-more-metadata }
+
+매개변수에 대한 정보를 추가할 수 있습니다.
+
+해당 정보는 생성된 OpenAPI에 포함되고 문서 사용자 인터페이스 및 외부 도구에서 사용됩니다.
+
+/// note | 참고
+
+도구에 따라 OpenAPI 지원 수준이 다를 수 있음을 명심하세요.
+
+일부는 아직 선언된 추가 정보를 모두 표시하지 않을 수 있지만, 대부분의 경우 누락된 기능은 이미 개발 계획이 있습니다.
+
+///
+
+`title`을 추가할 수 있습니다:
+
+{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *}
+
+그리고 `description`도 추가할 수 있습니다:
+
+{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *}
+
+## 별칭 매개변수 { #alias-parameters }
+
+매개변수가 `item-query`이길 원한다고 가정해 봅시다.
+
+마치 다음과 같습니다:
+
+```
+http://127.0.0.1:8000/items/?item-query=foobaritems
+```
+
+그러나 `item-query`는 유효한 파이썬 변수 이름이 아닙니다.
+
+가장 가까운 것은 `item_query`일 겁니다.
+
+하지만 정확히 `item-query`이길 원합니다...
+
+이럴 경우 `alias`를 선언할 수 있으며, 해당 별칭은 매개변수 값을 찾는 데 사용됩니다:
+
+{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *}
+
+## 매개변수 사용 중단하기 { #deprecating-parameters }
+
+이제는 더 이상 이 매개변수를 마음에 들어하지 않는다고 가정해 봅시다.
+
+이 매개변수를 사용하는 클라이언트가 있기 때문에 한동안은 남겨둬야 하지만, 문서에서 사용 중단됨으로 명확하게 보여주고 싶습니다.
+
+그렇다면 `deprecated=True` 매개변수를 `Query`로 전달합니다:
+
+{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *}
+
+문서가 아래와 같이 보일겁니다:
+
+
+
+## OpenAPI에서 매개변수 제외 { #exclude-parameters-from-openapi }
+
+생성된 OpenAPI 스키마(따라서 자동 문서화 시스템)에서 쿼리 매개변수를 제외하려면 `Query`의 `include_in_schema` 매개변수를 `False`로 설정하세요:
+
+{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *}
+
+## 커스텀 검증 { #custom-validation }
+
+위에 나온 매개변수들로는 할 수 없는 **커스텀 검증**이 필요한 경우가 있을 수 있습니다.
+
+그런 경우에는 일반적인 검증(예: 값이 `str`인지 검증한 뒤) 이후에 적용되는 **커스텀 검증 함수**를 사용할 수 있습니다.
+
+`Annotated` 안에서 [Pydantic의 `AfterValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-after-validator)를 사용하면 이를 구현할 수 있습니다.
+
+/// tip | 팁
+
+Pydantic에는 [BeforeValidator](https://docs.pydantic.dev/latest/concepts/validators/#field-before-validator)와 같은 다른 것들도 있습니다. 🤓
+
+///
+
+예를 들어, 이 커스텀 validator는 ISBN 도서 번호의 경우 아이템 ID가 `isbn-`으로 시작하고, IMDB 영화 URL ID의 경우 `imdb-`로 시작하는지 확인합니다:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
+
+/// info | 정보
+
+이는 Pydantic 2 이상 버전에서 사용할 수 있습니다. 😎
+
+///
+
+/// tip | 팁
+
+데이터베이스나 다른 API 같은 **외부 구성요소**와 통신이 필요한 어떤 종류의 검증이든 해야 한다면, 대신 **FastAPI Dependencies**를 사용해야 합니다. 이에 대해서는 나중에 배우게 됩니다.
+
+이 커스텀 validator는 요청에서 제공된 **같은 데이터만**으로 확인할 수 있는 것들을 위한 것입니다.
+
+///
+
+### 코드 이해하기 { #understand-that-code }
+
+중요한 부분은 **`Annotated` 안에서 함수와 함께 `AfterValidator`를 사용한다는 것**뿐입니다. 이 부분은 건너뛰셔도 됩니다. 🤸
+
+---
+
+하지만 이 특정 코드 예제가 궁금하고 계속 보고 싶다면, 추가 세부사항은 다음과 같습니다.
+
+#### `value.startswith()`를 사용한 문자열 { #string-with-value-startswith }
+
+알고 계셨나요? `value.startswith()`를 사용하는 문자열은 튜플을 받을 수 있으며, 튜플에 있는 각 값을 확인합니다:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *}
+
+#### 임의의 항목 { #a-random-item }
+
+`data.items()`를 사용하면 각 딕셔너리 항목의 키와 값을 담은 튜플로 구성된 이터러블 객체를 얻습니다.
+
+이 이터러블 객체를 `list(data.items())`로 적절한 `list`로 변환합니다.
+
+그 다음 `random.choice()`로 리스트에서 **무작위 값**을 얻어 `(id, name)` 형태의 튜플을 얻습니다. 예를 들어 `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")` 같은 값이 될 것입니다.
+
+그 다음 이 튜플의 **두 값을** 변수 `id`와 `name`에 **할당**합니다.
+
+따라서 사용자가 아이템 ID를 제공하지 않더라도, 무작위 추천을 받게 됩니다.
+
+...이 모든 것을 **단 하나의 간단한 줄**로 합니다. 🤯 Python 정말 좋지 않나요? 🐍
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *}
+
+## 요약 { #recap }
+
+매개변수에 검증과 메타데이터를 추가 선언할 수 있습니다.
+
+제네릭 검증과 메타데이터:
+
+* `alias`
+* `title`
+* `description`
+* `deprecated`
+
+문자열에 특화된 검증:
+
+* `min_length`
+* `max_length`
+* `pattern`
+
+`AfterValidator`를 사용하는 커스텀 검증.
+
+예제에서 `str` 값의 검증을 어떻게 추가하는지 살펴보았습니다.
+
+숫자와 같은 다른 타입에 대한 검증을 어떻게 선언하는지 확인하려면 다음 장을 확인하기 바랍니다.
diff --git a/docs/ko/docs/tutorial/query-params.md b/docs/ko/docs/tutorial/query-params.md
index bb631e6ffc310..4dffc90570ddb 100644
--- a/docs/ko/docs/tutorial/query-params.md
+++ b/docs/ko/docs/tutorial/query-params.md
@@ -1,14 +1,12 @@
-# 쿼리 매개변수
+# 쿼리 매개변수 { #query-parameters }
-경로 매개변수의 일부가 아닌 다른 함수 매개변수를 선언할 때, "쿼리" 매개변수로 자동 해석합니다.
+경로 매개변수의 일부가 아닌 다른 함수 매개변수를 선언하면 "쿼리" 매개변수로 자동 해석합니다.
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial001.py!}
-```
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
쿼리는 URL에서 `?` 후에 나오고 `&`으로 구분되는 키-값 쌍의 집합입니다.
-예를 들어, URL에서:
+예를 들어, 아래 URL에서:
```
http://127.0.0.1:8000/items/?skip=0&limit=10
@@ -21,28 +19,28 @@ http://127.0.0.1:8000/items/?skip=0&limit=10
URL의 일부이므로 "자연스럽게" 문자열입니다.
-하지만 파이썬 타입과 함께 선언할 경우(위 예에서 `int`), 해당 타입으로 변환되고 이에 대해 검증합니다.
+하지만 파이썬 타입과 함께 선언할 경우(위 예에서 `int`), 해당 타입으로 변환 및 검증됩니다.
경로 매개변수에 적용된 동일한 프로세스가 쿼리 매개변수에도 적용됩니다:
* (당연히) 편집기 지원
-* 데이터 "파싱"
+* 데이터 "파싱"
* 데이터 검증
* 자동 문서화
-## 기본값
+## 기본값 { #defaults }
쿼리 매개변수는 경로에서 고정된 부분이 아니기 때문에 선택적일 수 있고 기본값을 가질 수 있습니다.
위 예에서 `skip=0`과 `limit=10`은 기본값을 갖고 있습니다.
-그러므로 URL로 이동하면:
+그러므로 URL로 이동하는 것은:
```
http://127.0.0.1:8000/items/
```
-아래로 이동한 것과 같습니다:
+아래로 이동하는 것과 같습니다:
```
http://127.0.0.1:8000/items/?skip=0&limit=10
@@ -59,31 +57,25 @@ http://127.0.0.1:8000/items/?skip=20
* `skip=20`: URL에서 지정했기 때문입니다
* `limit=10`: 기본값이기 때문입니다
-## 선택적 매개변수
+## 선택적 매개변수 { #optional-parameters }
같은 방법으로 기본값을 `None`으로 설정하여 선택적 매개변수를 선언할 수 있습니다:
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial002.py!}
-```
+{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *}
이 경우 함수 매개변수 `q`는 선택적이며 기본값으로 `None` 값이 됩니다.
-!!! check "확인"
- **FastAPI**는 `item_id`가 경로 매개변수이고 `q`는 경로 매개변수가 아닌 쿼리 매개변수라는 것을 알 정도로 충분히 똑똑합니다.
+/// check
-!!! note "참고"
- FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다.
+또한 **FastAPI**는 `item_id`가 경로 매개변수이고 `q`는 경로 매개변수가 아니라서 쿼리 매개변수라는 것을 알 정도로 충분히 똑똑하다는 점도 확인하세요.
- `Union[str, None]`에 있는 `Union`은 FastAPI(FastAPI는 `str` 부분만 사용합니다)가 사용하는게 아니지만, `Union[str, None]`은 편집기에게 코드에서 오류를 찾아낼 수 있게 도와줍니다.
+///
-## 쿼리 매개변수 형변환
+## 쿼리 매개변수 형변환 { #query-parameter-type-conversion }
`bool` 형으로 선언할 수도 있고, 아래처럼 변환됩니다:
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial003.py!}
-```
+{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *}
이 경우, 아래로 이동하면:
@@ -115,10 +107,10 @@ http://127.0.0.1:8000/items/foo?short=on
http://127.0.0.1:8000/items/foo?short=yes
```
-또는 다른 어떤 변형(대문자, 첫글자만 대문자 등)이더라도 함수는 매개변수 `bool`형을 가진 `short`의 값이 `True`임을 압니다. 그렇지 않은 경우 `False`입니다.
+또는 다른 어떤 변형(대문자, 첫글자만 대문자 등)이더라도 함수는 `bool` 값이 `True`인 매개변수 `short`를 보게 됩니다. 그렇지 않은 경우 `False`입니다.
-## 여러 경로/쿼리 매개변수
+## 여러 경로/쿼리 매개변수 { #multiple-path-and-query-parameters }
여러 경로 매개변수와 쿼리 매개변수를 동시에 선언할 수 있으며 **FastAPI**는 어느 것이 무엇인지 알고 있습니다.
@@ -126,25 +118,21 @@ http://127.0.0.1:8000/items/foo?short=yes
매개변수들은 이름으로 감지됩니다:
-```Python hl_lines="8 10"
-{!../../../docs_src/query_params/tutorial004.py!}
-```
+{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *}
-## 필수 쿼리 매개변수
+## 필수 쿼리 매개변수 { #required-query-parameters }
경로가 아닌 매개변수에 대한 기본값을 선언할 때(지금은 쿼리 매개변수만 보았습니다), 해당 매개변수는 필수적(Required)이지 않았습니다.
특정값을 추가하지 않고 선택적으로 만들기 위해선 기본값을 `None`으로 설정하면 됩니다.
-그러나 쿼리 매개변수를 필수로 만들려면 기본값을 선언할 수 없습니다:
+그러나 쿼리 매개변수를 필수로 만들려면 단순히 기본값을 선언하지 않으면 됩니다:
-```Python hl_lines="6-7"
-{!../../../docs_src/query_params/tutorial005.py!}
-```
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
여기 쿼리 매개변수 `needy`는 `str`형인 필수 쿼리 매개변수입니다.
-브라우저에서 URL을 아래처럼 연다면:
+브라우저에서 아래와 같은 URL을 연다면:
```
http://127.0.0.1:8000/items/foo-item
@@ -154,16 +142,17 @@ http://127.0.0.1:8000/items/foo-item
```JSON
{
- "detail": [
- {
- "loc": [
- "query",
- "needy"
- ],
- "msg": "field required",
- "type": "value_error.missing"
- }
- ]
+ "detail": [
+ {
+ "type": "missing",
+ "loc": [
+ "query",
+ "needy"
+ ],
+ "msg": "Field required",
+ "input": null
+ }
+ ]
}
```
@@ -184,15 +173,16 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
그리고 물론, 일부 매개변수는 필수로, 다른 일부는 기본값을, 또 다른 일부는 선택적으로 선언할 수 있습니다:
-```Python hl_lines="10"
-{!../../../docs_src/query_params/tutorial006.py!}
-```
+{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *}
-이 경우 3가지 쿼리 매개변수가 있습니다:
+위 예시에서는 3가지 쿼리 매개변수가 있습니다:
* `needy`, 필수적인 `str`.
* `skip`, 기본값이 `0`인 `int`.
* `limit`, 선택적인 `int`.
-!!! tip "팁"
- [경로 매개변수](path-params.md#predefined-values){.internal-link target=_blank}와 마찬가지로 `Enum`을 사용할 수 있습니다.
+/// tip
+
+[경로 매개변수](path-params.md#predefined-values)와 마찬가지로 `Enum`을 사용할 수 있습니다.
+
+///
diff --git a/docs/ko/docs/tutorial/request-files.md b/docs/ko/docs/tutorial/request-files.md
index decefe981fef7..49522ac252531 100644
--- a/docs/ko/docs/tutorial/request-files.md
+++ b/docs/ko/docs/tutorial/request-files.md
@@ -1,70 +1,78 @@
-# 파일 요청
+# 파일 요청 { #request-files }
`File`을 사용하여 클라이언트가 업로드할 파일들을 정의할 수 있습니다.
-!!! info "정보"
- 업로드된 파일을 전달받기 위해 먼저 `python-multipart`를 설치해야합니다.
+/// info | 정보
- 예시) `pip install python-multipart`.
+업로드된 파일을 전달받기 위해 먼저 [`python-multipart`](https://github.com/Kludex/python-multipart)를 설치해야합니다.
- 업로드된 파일들은 "폼 데이터"의 형태로 전송되기 때문에 이 작업이 필요합니다.
+[가상 환경](../virtual-environments.md)을 생성하고, 활성화한 다음, 예를 들어 다음과 같이 설치하세요:
-## `File` 임포트
+```console
+$ pip install python-multipart
+```
+
+업로드된 파일들은 "폼 데이터"의 형태로 전송되기 때문에 이 작업이 필요합니다.
+
+///
+
+## `File` 임포트 { #import-file }
`fastapi` 에서 `File` 과 `UploadFile` 을 임포트 합니다:
-```Python hl_lines="1"
-{!../../../docs_src/request_files/tutorial001.py!}
-```
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
-## `File` 매개변수 정의
+## `File` 매개변수 정의 { #define-file-parameters }
`Body` 및 `Form` 과 동일한 방식으로 파일의 매개변수를 생성합니다:
-```Python hl_lines="7"
-{!../../../docs_src/request_files/tutorial001.py!}
-```
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
+
+/// info | 정보
-!!! info "정보"
- `File` 은 `Form` 으로부터 직접 상속된 클래스입니다.
+`File` 은 `Form` 으로부터 직접 상속된 클래스입니다.
- 하지만 `fastapi`로부터 `Query`, `Path`, `File` 등을 임포트 할 때, 이것들은 특별한 클래스들을 반환하는 함수라는 것을 기억하기 바랍니다.
+하지만 `fastapi`로부터 `Query`, `Path`, `File` 등을 임포트 할 때, 이것들은 특별한 클래스들을 반환하는 함수라는 것을 기억하기 바랍니다.
-!!! tip "팁"
- File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본문(JSON) 매개변수로 해석되는 것을 방지하기 위해 `File` 을 사용해야합니다.
+///
+
+/// tip | 팁
+
+File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본문(JSON) 매개변수로 해석되는 것을 방지하기 위해 `File` 을 사용해야합니다.
+
+///
파일들은 "폼 데이터"의 형태로 업로드 됩니다.
-*경로 작동 함수*의 매개변수를 `bytes` 로 선언하는 경우 **FastAPI**는 파일을 읽고 `bytes` 형태의 내용을 전달합니다.
+*경로 처리 함수*의 매개변수를 `bytes` 로 선언하는 경우 **FastAPI**는 파일을 읽고 `bytes` 형태의 내용을 전달합니다.
이것은 전체 내용이 메모리에 저장된다는 것을 의미한다는 걸 염두하기 바랍니다. 이는 작은 크기의 파일들에 적합합니다.
어떤 경우에는 `UploadFile` 을 사용하는 것이 더 유리합니다.
-## `File` 매개변수와 `UploadFile`
+## `UploadFile`을 사용하는 `File` 매개변수 { #file-parameters-with-uploadfile }
`File` 매개변수를 `UploadFile` 타입으로 정의합니다:
-```Python hl_lines="12"
-{!../../../docs_src/request_files/tutorial001.py!}
-```
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
`UploadFile` 을 사용하는 것은 `bytes` 과 비교해 다음과 같은 장점이 있습니다:
+* 매개변수의 기본값에서 `File()`을 사용할 필요가 없습니다.
* "스풀 파일"을 사용합니다.
* 최대 크기 제한까지만 메모리에 저장되며, 이를 초과하는 경우 디스크에 저장됩니다.
* 따라서 이미지, 동영상, 큰 이진코드와 같은 대용량 파일들을 많은 메모리를 소모하지 않고 처리하기에 적합합니다.
* 업로드 된 파일의 메타데이터를 얻을 수 있습니다.
-* file-like `async` 인터페이스를 갖고 있습니다.
-* file-like object를 필요로하는 다른 라이브러리에 직접적으로 전달할 수 있는 파이썬 `SpooledTemporaryFile` 객체를 반환합니다.
+* [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) `async` 인터페이스를 갖고 있습니다.
+* file-like object를 필요로하는 다른 라이브러리에 직접적으로 전달할 수 있는 파이썬 [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) 객체를 반환합니다.
-### `UploadFile`
+### `UploadFile` { #uploadfile }
`UploadFile` 은 다음과 같은 어트리뷰트가 있습니다:
* `filename` : 문자열(`str`)로 된 업로드된 파일의 파일명입니다 (예: `myimage.jpg`).
* `content_type` : 문자열(`str`)로 된 파일 형식(MIME type / media type)입니다 (예: `image/jpeg`).
-* `file` : `SpooledTemporaryFile` (파일류 객체)입니다. 이것은 "파일류" 객체를 필요로하는 다른 라이브러리에 직접적으로 전달할 수 있는 실질적인 파이썬 파일입니다.
+* `file` : [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) (a [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) object)입니다. 이것은 "file-like" 객체를 필요로하는 다른 함수나 라이브러리에 직접적으로 전달할 수 있는 실질적인 파이썬 파일 객체입니다.
`UploadFile` 에는 다음의 `async` 메소드들이 있습니다. 이들은 내부적인 `SpooledTemporaryFile` 을 사용하여 해당하는 파일 메소드를 호출합니다.
@@ -77,43 +85,67 @@
상기 모든 메소드들이 `async` 메소드이기 때문에 “await”을 사용하여야 합니다.
-예를들어, `async` *경로 작동 함수*의 내부에서 다음과 같은 방식으로 내용을 가져올 수 있습니다:
+예를들어, `async` *경로 처리 함수*의 내부에서 다음과 같은 방식으로 내용을 가져올 수 있습니다:
```Python
contents = await myfile.read()
```
-만약 일반적인 `def` *경로 작동 함수*의 내부라면, 다음과 같이 `UploadFile.file` 에 직접 접근할 수 있습니다:
+만약 일반적인 `def` *경로 처리 함수*의 내부라면, 다음과 같이 `UploadFile.file` 에 직접 접근할 수 있습니다:
```Python
contents = myfile.file.read()
```
-!!! note "`async` 기술적 세부사항"
- `async` 메소드들을 사용할 때 **FastAPI**는 스레드풀에서 파일 메소드들을 실행하고 그들을 기다립니다.
+/// note | `async` 기술 세부사항
+
+`async` 메소드들을 사용할 때 **FastAPI**는 스레드풀에서 파일 메소드들을 실행하고 그들을 기다립니다.
+
+///
+
+/// note | Starlette 기술 세부사항
-!!! note "Starlette 기술적 세부사항"
- **FastAPI**의 `UploadFile` 은 **Starlette**의 `UploadFile` 을 직접적으로 상속받지만, **Pydantic** 및 FastAPI의 다른 부분들과의 호환성을 위해 필요한 부분들이 추가되었습니다.
+**FastAPI**의 `UploadFile` 은 **Starlette**의 `UploadFile` 을 직접적으로 상속받지만, **Pydantic** 및 FastAPI의 다른 부분들과의 호환성을 위해 필요한 부분들이 추가되었습니다.
-## "폼 데이터"란
+///
+
+## "폼 데이터"란 { #what-is-form-data }
HTML의 폼들(``)이 서버에 데이터를 전송하는 방식은 대개 데이터에 JSON과는 다른 "특별한" 인코딩을 사용합니다.
**FastAPI**는 JSON 대신 올바른 위치에서 데이터를 읽을 수 있도록 합니다.
-!!! note "기술적 세부사항"
- 폼의 데이터는 파일이 포함되지 않은 경우 일반적으로 "미디어 유형" `application/x-www-form-urlencoded` 을 사용해 인코딩 됩니다.
+/// note | 기술 세부사항
+
+폼의 데이터는 파일이 포함되지 않은 경우 일반적으로 "미디어 유형" `application/x-www-form-urlencoded` 을 사용해 인코딩 됩니다.
+
+하지만 파일이 포함된 경우, `multipart/form-data`로 인코딩됩니다. `File`을 사용하였다면, **FastAPI**는 본문의 적합한 부분에서 파일을 가져와야 한다는 것을 인지합니다.
+
+인코딩과 폼 필드에 대해 더 알고싶다면, [MDN 웹 문서의 `POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)를 참고하기 바랍니다.
+
+///
+
+/// warning | 경고
+
+다수의 `File` 과 `Form` 매개변수를 한 *경로 처리*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다.
- 하지만 파일이 포함된 경우, `multipart/form-data`로 인코딩됩니다. `File`을 사용하였다면, **FastAPI**는 본문의 적합한 부분에서 파일을 가져와야 한다는 것을 인지합니다.
+이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다.
- 인코딩과 폼 필드에 대해 더 알고싶다면, POST에 관한MDN웹 문서 를 참고하기 바랍니다,.
+///
-!!! warning "주의"
- 다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다.
+## 선택적 파일 업로드 { #optional-file-upload }
- 이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다.
+표준 타입 애너테이션을 사용하고 기본값을 `None`으로 설정하여 파일을 선택적으로 만들 수 있습니다:
-## 다중 파일 업로드
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## 추가 메타데이터를 포함한 `UploadFile` { #uploadfile-with-additional-metadata }
+
+추가 메타데이터를 설정하기 위해 예를 들어 `UploadFile`과 함께 `File()`을 사용할 수도 있습니다:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
+
+## 다중 파일 업로드 { #multiple-file-uploads }
여러 파일을 동시에 업로드 할 수 있습니다.
@@ -121,24 +153,24 @@ HTML의 폼들(``)이 서버에 데이터를 전송하는 방식은
이 기능을 사용하기 위해 , `bytes` 의 `List` 또는 `UploadFile` 를 선언하기 바랍니다:
-```Python hl_lines="10 15"
-{!../../../docs_src/request_files/tutorial002.py!}
-```
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
선언한대로, `bytes` 의 `list` 또는 `UploadFile` 들을 전송받을 것입니다.
-!!! note "참고"
- 2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, #4276과 #3641을 참고하세요.
+/// note | 기술 세부사항
+
+`from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다.
+
+**FastAPI**는 개발자의 편의를 위해 `fastapi.responses` 와 동일한 `starlette.responses` 도 제공합니다. 하지만 대부분의 응답들은 Starlette로부터 직접 제공됩니다.
- 그럼에도, **FastAPI**는 표준 Open API를 사용해 이미 호환이 가능합니다.
+///
- 따라서 Swagger UI 또는 기타 그 외의 OpenAPI를 지원하는 툴이 다중 파일 업로드를 지원하는 경우, 이들은 **FastAPI**와 호환됩니다.
+### 추가 메타데이터를 포함한 다중 파일 업로드 { #multiple-file-uploads-with-additional-metadata }
-!!! note "기술적 세부사항"
- `from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다.
+이전과 같은 방식으로 `UploadFile`에 대해서도 `File()`을 사용해 추가 매개변수를 설정할 수 있습니다:
- **FastAPI**는 개발자의 편의를 위해 `fastapi.responses` 와 동일한 `starlette.responses` 도 제공합니다. 하지만 대부분의 응답들은 Starlette로부터 직접 제공됩니다.
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
-## 요약
+## 요약 { #recap }
-폼 데이터로써 입력 매개변수로 업로드할 파일을 선언할 경우 `File` 을 사용하기 바랍니다.
+`File`, `bytes`, `UploadFile`을 사용하여 폼 데이터로 전송되는 요청에서 업로드할 파일을 선언하세요.
diff --git a/docs/ko/docs/tutorial/request-form-models.md b/docs/ko/docs/tutorial/request-form-models.md
new file mode 100644
index 0000000000000..4a5c3e1a75383
--- /dev/null
+++ b/docs/ko/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# 폼 모델 { #form-models }
+
+FastAPI에서 **Pydantic 모델**을 이용하여 **폼 필드**를 선언할 수 있습니다.
+
+/// info | 정보
+
+폼을 사용하려면, 먼저 [`python-multipart`](https://github.com/Kludex/python-multipart)를 설치하세요.
+
+[가상 환경](../virtual-environments.md)을 생성하고 활성화한 다음, 예를 들어 아래와 같이 설치하세요:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | 참고
+
+이 기능은 FastAPI 버전 `0.113.0` 이후부터 지원됩니다. 🤓
+
+///
+
+## 폼을 위한 Pydantic 모델 { #pydantic-models-for-forms }
+
+**폼 필드**로 받고 싶은 필드를 **Pydantic 모델**로 선언한 다음, 매개변수를 `Form`으로 선언하면 됩니다:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
+
+**FastAPI**는 요청에서 받은 **폼 데이터**에서 **각 필드**에 대한 데이터를 **추출**하고 정의한 Pydantic 모델을 줍니다.
+
+## 문서 확인하기 { #check-the-docs }
+
+문서 UI `/docs`에서 확인할 수 있습니다:
+
+
+
+
+그리고 두 모델 모두 대화형 API 문서에 사용됩니다:
+
+
+
+## 기타 반환 타입 어노테이션 { #other-return-type-annotations }
+
+유효한 Pydantic 필드가 아닌 것을 반환하면서도, 도구(에디터, mypy 등)가 제공하는 지원을 받기 위해 함수에 어노테이션을 달아두는 경우가 있을 수 있습니다.
+
+### 응답을 직접 반환하기 { #return-a-response-directly }
+
+가장 흔한 경우는 [고급 문서에서 나중에 설명하는 대로 Response를 직접 반환하는 것](../advanced/response-directly.md)입니다.
+
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
+
+이 간단한 경우는 반환 타입 어노테이션이 `Response` 클래스(또는 그 서브클래스)이기 때문에 FastAPI에서 자동으로 처리됩니다.
+
+그리고 `RedirectResponse`와 `JSONResponse`는 모두 `Response`의 서브클래스이므로, 타입 어노테이션이 올바르기 때문에 도구들도 만족합니다.
+
+### Response 서브클래스 어노테이션 { #annotate-a-response-subclass }
+
+타입 어노테이션에 `Response`의 서브클래스를 사용할 수도 있습니다:
+
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
+
+이는 `RedirectResponse`가 `Response`의 서브클래스이기 때문에 동작하며, FastAPI가 이 간단한 경우를 자동으로 처리합니다.
+
+### 유효하지 않은 반환 타입 어노테이션 { #invalid-return-type-annotations }
+
+하지만 유효한 Pydantic 타입이 아닌 다른 임의의 객체(예: 데이터베이스 객체)를 반환하고, 함수에서 그렇게 어노테이션하면, FastAPI는 그 타입 어노테이션으로부터 Pydantic 응답 모델을 만들려고 시도하다가 실패합니다.
+
+또한, 유효한 Pydantic 타입이 아닌 타입이 하나 이상 포함된 여러 타입 간의 union이 있는 경우에도 동일합니다. 예를 들어, 아래는 실패합니다 💥:
+
+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
+
+...이는 타입 어노테이션이 Pydantic 타입이 아니고, 단일 `Response` 클래스/서브클래스도 아니며, `Response`와 `dict` 간 union(둘 중 아무거나)이기 때문에 실패합니다.
+
+### 응답 모델 비활성화 { #disable-response-model }
+
+위 예제에서 이어서, FastAPI가 수행하는 기본 데이터 검증, 문서화, 필터링 등을 원하지 않을 수 있습니다.
+
+하지만 에디터나 타입 체커(예: mypy) 같은 도구 지원을 받기 위해 함수에 반환 타입 어노테이션은 유지하고 싶을 수도 있습니다.
+
+이 경우 `response_model=None`으로 설정하여 응답 모델 생성을 비활성화할 수 있습니다:
+
+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}
+
+그러면 FastAPI는 응답 모델 생성을 건너뛰며, FastAPI 애플리케이션에 영향을 주지 않고 필요한 반환 타입 어노테이션을 어떤 것이든 사용할 수 있습니다. 🤓
+
+## 응답 모델 인코딩 매개변수 { #response-model-encoding-parameters }
+
+응답 모델은 아래와 같이 기본값을 가질 수 있습니다:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}
+
+* `description: Union[str, None] = None` (또는 Python 3.10에서 `str | None = None`)은 기본값으로 `None`을 갖습니다.
+* `tax: float = 10.5`는 기본값으로 `10.5`를 갖습니다.
+* `tags: List[str] = []`는 기본값으로 빈 리스트 `[]`를 갖습니다.
+
+하지만 실제로 저장되지 않았을 경우 결과에서 이를 생략하고 싶을 수 있습니다.
+
+예를 들어, NoSQL 데이터베이스에 많은 선택적 속성이 있는 모델이 있지만, 기본값으로 가득 찬 매우 긴 JSON 응답을 보내고 싶지 않습니다.
+
+### `response_model_exclude_unset` 매개변수 사용 { #use-the-response-model-exclude-unset-parameter }
+
+*경로 처리 데코레이터* 매개변수 `response_model_exclude_unset=True`로 설정할 수 있습니다:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}
+
+그러면 이러한 기본값은 응답에 포함되지 않고, 실제로 설정된 값만 포함됩니다.
+
+따라서 ID가 `foo`인 항목에 대해 해당 *경로 처리*로 요청을 보내면, (기본값을 제외한) 응답은 다음과 같습니다:
+
+```JSON
+{
+ "name": "Foo",
+ "price": 50.2
+}
+```
+
+/// info | 정보
+
+다음도 사용할 수 있습니다:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+`exclude_defaults` 및 `exclude_none`에 대해 [Pydantic 문서](https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict)에 설명된 대로 사용할 수 있습니다.
+
+///
+
+#### 기본값이 있는 필드에 값이 있는 데이터 { #data-with-values-for-fields-with-defaults }
+
+하지만 ID가 `bar`인 항목처럼, 기본값이 있는 모델의 필드에 값이 있다면:
+
+```Python hl_lines="3 5"
+{
+ "name": "Bar",
+ "description": "The bartenders",
+ "price": 62,
+ "tax": 20.2
+}
+```
+
+응답에 포함됩니다.
+
+#### 기본값과 동일한 값을 갖는 데이터 { #data-with-the-same-values-as-the-defaults }
+
+데이터가 ID가 `baz`인 항목처럼 기본값과 동일한 값을 갖는다면:
+
+```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`뿐만 아니라 어떤 것이든 될 수 있습니다.
+
+리스트(`[]`), `float`인 `10.5` 등이 될 수 있습니다.
+
+///
+
+### `response_model_include` 및 `response_model_exclude` { #response-model-include-and-response-model-exclude }
+
+*경로 처리 데코레이터* 매개변수 `response_model_include` 및 `response_model_exclude`를 사용할 수도 있습니다.
+
+이들은 포함(나머지 생략)하거나 제외(나머지 포함)할 어트리뷰트 이름을 담은 `str`의 `set`을 받습니다.
+
+Pydantic 모델이 하나만 있고 출력에서 일부 데이터를 제거하려는 경우, 빠른 지름길로 사용할 수 있습니다.
+
+/// tip | 팁
+
+하지만 이러한 매개변수 대신, 위에서 설명한 것처럼 여러 클래스를 사용하는 것을 여전히 권장합니다.
+
+이는 일부 어트리뷰트를 생략하기 위해 `response_model_include` 또는 `response_model_exclude`를 사용하더라도, 앱의 OpenAPI(및 문서)에 생성되는 JSON Schema가 여전히 전체 모델에 대한 스키마이기 때문입니다.
+
+비슷하게 동작하는 `response_model_by_alias`에도 동일하게 적용됩니다.
+
+///
+
+{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}
+
+/// tip | 팁
+
+문법 `{"name", "description"}`은 두 값을 갖는 `set`을 만듭니다.
+
+이는 `set(["name", "description"])`과 동일합니다.
+
+///
+
+#### `set` 대신 `list` 사용하기 { #using-lists-instead-of-sets }
+
+`set`을 쓰는 것을 잊고 `list`나 `tuple`을 대신 사용하더라도, FastAPI는 이를 `set`으로 변환하므로 올바르게 동작합니다:
+
+{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}
+
+## 요약 { #recap }
+
+응답 모델을 정의하고 특히 개인정보가 필터링되도록 보장하려면 *경로 처리 데코레이터*의 매개변수 `response_model`을 사용하세요.
+
+명시적으로 설정된 값만 반환하려면 `response_model_exclude_unset`을 사용하세요.
diff --git a/docs/ko/docs/tutorial/response-status-code.md b/docs/ko/docs/tutorial/response-status-code.md
index f92c057be4fd9..68db66e3388d7 100644
--- a/docs/ko/docs/tutorial/response-status-code.md
+++ b/docs/ko/docs/tutorial/response-status-code.md
@@ -1,89 +1,101 @@
-# 응답 상태 코드
+# 응답 상태 코드 { #response-status-code }
-응답 모델과 같은 방법으로, 어떤 *경로 작동*이든 `status_code` 매개변수를 사용하여 응답에 대한 HTTP 상태 코드를 선언할 수 있습니다.
+응답 모델을 지정하는 것과 같은 방법으로, 어떤 *경로 처리*에서든 `status_code` 매개변수를 사용하여 응답에 사용할 HTTP 상태 코드를 선언할 수도 있습니다:
* `@app.get()`
* `@app.post()`
* `@app.put()`
* `@app.delete()`
-* 기타
+* 등
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
-!!! note "참고"
- `status_code` 는 "데코레이터" 메소드(`get`, `post` 등)의 매개변수입니다. 모든 매개변수들과 본문처럼 *경로 작동 함수*가 아닙니다.
+/// note | 참고
+
+`status_code` 는 "데코레이터" 메소드(`get`, `post` 등)의 매개변수입니다. 모든 매개변수들과 본문처럼 *경로 처리 함수*가 아닙니다.
+
+///
`status_code` 매개변수는 HTTP 상태 코드를 숫자로 입력받습니다.
-!!! info "정보"
- `status_code` 는 파이썬의 `http.HTTPStatus` 와 같은 `IntEnum` 을 입력받을 수도 있습니다.
+/// info | 정보
+
+`status_code` 는 파이썬의 [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus) 와 같은 `IntEnum` 을 입력받을 수도 있습니다.
+
+///
`status_code` 매개변수는:
* 응답에서 해당 상태 코드를 반환합니다.
-* 상태 코드를 OpenAPI 스키마(및 사용자 인터페이스)에 문서화 합니다.
+* 상태 코드를 OpenAPI 스키마(따라서, 사용자 인터페이스에도)에 문서화합니다:
+
+
+
+/// note | 참고
-
+일부 응답 코드(다음 섹션 참고)는 응답에 본문이 없다는 것을 나타냅니다.
-!!! note "참고"
- 어떤 응답 코드들은 해당 응답에 본문이 없다는 것을 의미하기도 합니다 (다음 항목 참고).
+FastAPI는 이를 알고 있으며, 응답 본문이 없다고 명시하는 OpenAPI 문서를 생성합니다.
- 이에 따라 FastAPI는 응답 본문이 없음을 명시하는 OpenAPI를 생성합니다.
+///
-## HTTP 상태 코드에 대하여
+## HTTP 상태 코드에 대하여 { #about-http-status-codes }
-!!! note "참고"
- 만약 HTTP 상태 코드에 대하여 이미 알고있다면, 다음 항목으로 넘어가십시오.
+/// note | 참고
-HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다.
+만약 HTTP 상태 코드가 무엇인지 이미 알고 있다면, 다음 섹션으로 넘어가세요.
-이 상태 코드들은 각자를 식별할 수 있도록 지정된 이름이 있으나, 중요한 것은 숫자 코드입니다.
+///
+
+HTTP에서는 응답의 일부로 3자리 숫자 상태 코드를 보냅니다.
+
+이 상태 코드들은 이를 식별할 수 있도록 이름이 연결되어 있지만, 중요한 부분은 숫자입니다.
요약하자면:
-* `**1xx**` 상태 코드는 "정보"용입니다. 이들은 직접적으로는 잘 사용되지는 않습니다. 이 상태 코드를 갖는 응답들은 본문을 가질 수 없습니다.
-* `**2xx**` 상태 코드는 "성공적인" 응답을 위해 사용됩니다. 가장 많이 사용되는 유형입니다.
- * `200` 은 디폴트 상태 코드로, 모든 것이 "성공적임"을 의미합니다.
- * 다른 예로는 `201` "생성됨"이 있습니다. 일반적으로 데이터베이스에 새로운 레코드를 생성한 후 사용합니다.
- * 단, `204` "내용 없음"은 특별한 경우입니다. 이것은 클라이언트에게 반환할 내용이 없는 경우 사용합니다. 따라서 응답은 본문을 가질 수 없습니다.
-* `**3xx**` 상태 코드는 "리다이렉션"용입니다. 본문을 가질 수 없는 `304` "수정되지 않음"을 제외하고, 이 상태 코드를 갖는 응답에는 본문이 있을 수도, 없을 수도 있습니다.
-* `**4xx**` 상태 코드는 "클라이언트 오류" 응답을 위해 사용됩니다. 이것은 아마 가장 많이 사용하게 될 두번째 유형입니다.
- * 일례로 `404` 는 "찾을 수 없음" 응답을 위해 사용합니다.
- * 일반적인 클라이언트 오류의 경우 `400` 을 사용할 수 있습니다.
-* `**5xx**` 상태 코드는 서버 오류에 사용됩니다. 이것들을 직접 사용할 일은 거의 없습니다. 응용 프로그램 코드나 서버의 일부에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다.
+* `100 - 199` 는 "정보"용입니다. 직접 사용할 일은 거의 없습니다. 이 상태 코드를 갖는 응답은 본문을 가질 수 없습니다.
+* **`200 - 299`** 는 "성공적인" 응답을 위한 것입니다. 가장 많이 사용하게 될 유형입니다.
+ * `200` 은 기본 상태 코드로, 모든 것이 "OK"임을 의미합니다.
+ * 다른 예로는 `201` "생성됨"이 있습니다. 일반적으로 데이터베이스에 새 레코드를 생성한 후 사용합니다.
+ * 특별한 경우로 `204` "내용 없음"이 있습니다. 이 응답은 클라이언트에게 반환할 내용이 없을 때 사용되며, 따라서 응답은 본문을 가지면 안 됩니다.
+* **`300 - 399`** 는 "리다이렉션"용입니다. 이 상태 코드를 갖는 응답은 본문이 있을 수도 없을 수도 있으며, 본문이 없어야 하는 `304` "수정되지 않음"을 제외합니다.
+* **`400 - 499`** 는 "클라이언트 오류" 응답을 위한 것입니다. 아마 두 번째로 가장 많이 사용하게 될 유형입니다.
+ * 예를 들어 `404` 는 "찾을 수 없음" 응답을 위해 사용합니다.
+ * 클라이언트의 일반적인 오류에는 `400` 을 그냥 사용할 수 있습니다.
+* `500 - 599` 는 서버 오류에 사용됩니다. 직접 사용할 일은 거의 없습니다. 애플리케이션 코드의 일부나 서버에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다.
+
+/// tip | 팁
-!!! tip "팁"
- 각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 MDN HTTP 상태 코드에 관한 문서 를 확인하십시오.
+각 상태 코드와 어떤 코드가 어떤 용도인지 더 알고 싶다면 [MDN의 HTTP 상태 코드에 관한 문서](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)를 확인하세요.
-## 이름을 기억하는 쉬운 방법
+///
-상기 예시 참고:
+## 이름을 기억하는 쉬운 방법 { #shortcut-to-remember-the-names }
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+이전 예시를 다시 확인해보겠습니다:
-`201` 은 "생성됨"를 의미하는 상태 코드입니다.
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
-하지만 모든 상태 코드들이 무엇을 의미하는지 외울 필요는 없습니다.
+`201` 은 "생성됨"을 위한 상태 코드입니다.
+
+하지만 각각의 코드가 무엇을 의미하는지 외울 필요는 없습니다.
`fastapi.status` 의 편의 변수를 사용할 수 있습니다.
-```Python hl_lines="1 6"
-{!../../../docs_src/response_status_code/tutorial002.py!}
-```
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
+
+이것들은 단지 편의를 위한 것으로, 동일한 숫자를 갖고 있지만, 이를 통해 편집기의 자동완성 기능으로 찾을 수 있습니다:
+
+
-이것은 단순히 작업을 편리하게 하기 위한 것으로, HTTP 상태 코드와 동일한 번호를 갖고있지만, 이를 사용하면 편집기의 자동완성 기능을 사용할 수 있습니다:
+/// note | 기술 세부사항
-
+`from starlette import status` 역시 사용할 수 있습니다.
-!!! note "기술적 세부사항"
- `from starlette import status` 역시 사용할 수 있습니다.
+**FastAPI**는 개발자인 여러분의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다.
- **FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다.
+///
-## 기본값 변경
+## 기본값 변경 { #changing-the-default }
-추후 여기서 선언하는 기본 상태 코드가 아닌 다른 상태 코드를 반환하는 방법을 [숙련된 사용자 지침서](https://fastapi.tiangolo.com/ko/advanced/response-change-status-code/){.internal-link target=_blank}에서 확인할 수 있습니다.
+나중에 [고급 사용자 지침서](../advanced/response-change-status-code.md)에서, 여기서 선언하는 기본값과 다른 상태 코드를 반환하는 방법을 확인할 수 있습니다.
diff --git a/docs/ko/docs/tutorial/schema-extra-example.md b/docs/ko/docs/tutorial/schema-extra-example.md
new file mode 100644
index 0000000000000..ffa97375dfe81
--- /dev/null
+++ b/docs/ko/docs/tutorial/schema-extra-example.md
@@ -0,0 +1,202 @@
+# 요청 예제 데이터 선언 { #declare-request-example-data }
+
+여러분의 앱이 받을 수 있는 데이터 예제를 선언할 수 있습니다.
+
+여기 이를 위한 몇 가지 방식이 있습니다.
+
+## Pydantic 모델 속 추가 JSON 스키마 데이터 { #extra-json-schema-data-in-pydantic-models }
+
+생성된 JSON 스키마에 추가될 Pydantic 모델을 위한 `examples`을 선언할 수 있습니다.
+
+{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}
+
+추가 정보는 있는 그대로 해당 모델의 **JSON 스키마** 결과에 추가되고, API 문서에서 사용합니다.
+
+[Pydantic 문서: Configuration](https://docs.pydantic.dev/latest/api/config/)에 설명된 것처럼 `dict`를 받는 `model_config` 어트리뷰트를 사용할 수 있습니다.
+
+`"json_schema_extra"`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다.
+
+/// tip | 팁
+
+JSON 스키마를 확장하고 여러분의 별도의 자체 데이터를 추가하기 위해 같은 기술을 사용할 수 있습니다.
+
+예를 들면, 프론트엔드 사용자 인터페이스에 메타데이터를 추가하는 등에 사용할 수 있습니다.
+
+///
+
+/// info | 정보
+
+(FastAPI 0.99.0부터 쓰이기 시작한) OpenAPI 3.1.0은 **JSON 스키마** 표준의 일부인 `examples`에 대한 지원을 추가했습니다.
+
+그 전에는, 하나의 예제만 가능한 `example` 키워드만 지원했습니다. 이는 아직 OpenAPI 3.1.0에서 지원하지만, 지원이 종료될 것이며 JSON 스키마 표준에 포함되지 않습니다. 그렇기에 `example`을 `examples`으로 이전하는 것을 추천합니다. 🤓
+
+이 페이지 끝에서 더 많은 내용을 읽을 수 있습니다.
+
+///
+
+## `Field` 추가 인자 { #field-additional-arguments }
+
+Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 선언할 수 있습니다:
+
+{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}
+
+## JSON Schema에서의 `examples` - OpenAPI { #examples-in-json-schema-openapi }
+
+다음 중 하나를 사용할 때:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+**OpenAPI** 안의 **JSON 스키마**에 추가될 부가적인 정보를 포함한 `examples` 모음을 선언할 수도 있습니다.
+
+### `examples`를 포함한 `Body` { #body-with-examples }
+
+여기, `Body()`에 예상되는 예제 데이터 하나를 포함한 `examples`를 넘겼습니다:
+
+{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *}
+
+### 문서 UI 예시 { #example-in-the-docs-ui }
+
+위의 어느 방법과 함께라면 `/docs`에서 다음과 같이 보일 것입니다:
+
+
+
+### 다중 `examples`를 포함한 `Body` { #body-with-multiple-examples }
+
+물론 여러 `examples`를 넘길 수 있습니다:
+
+{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *}
+
+이와 같이 하면 예제들은 그 본문 데이터의 내부 **JSON 스키마**의 일부가 될 것입니다.
+
+그럼에도 불구하고, 지금 이 문서를 작성하는 시간에, 문서 UI를 보여주는 역할을 맡은 Swagger UI는 **JSON 스키마** 속 데이터를 위한 여러 예제의 표현을 지원하지 않습니다. 하지만 해결 방안을 밑에서 읽어보세요.
+
+### OpenAPI-특화 `examples` { #openapi-specific-examples }
+
+**JSON 스키마**가 `examples`를 지원하기 전부터 OpenAPI는 `examples`이라 불리는 다른 필드를 지원해 왔습니다.
+
+이 **OpenAPI-특화** `examples`는 OpenAPI 명세서의 다른 구역으로 들어갑니다. 각 JSON 스키마 내부가 아니라 **각 *경로 처리* 세부 정보**에 포함됩니다.
+
+그리고 Swagger UI는 이 특정한 `examples` 필드를 한동안 지원했습니다. 그래서, 이를 다른 **문서 UI에 있는 예제**를 **표시**하기 위해 사용할 수 있습니다.
+
+이 OpenAPI-특화 필드인 `examples`의 형태는 (`list` 대신에) **다중 예제**가 포함된 `dict`이며, 각각의 별도 정보 또한 **OpenAPI**에 추가될 것입니다.
+
+이는 OpenAPI에 포함된 각 JSON 스키마 안으로 포함되지 않으며, *경로 처리*에 직접적으로 포함됩니다.
+
+### `openapi_examples` 매개변수 사용하기 { #using-the-openapi-examples-parameter }
+
+다음에 대해 FastAPI에서 매개변수 `openapi_examples`로 OpenAPI-특화 `examples`를 선언할 수 있습니다:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+`dict`의 키는 각 예제를 식별하고, 각 값은 또 다른 `dict`입니다.
+
+`examples` 안의 각 특정 예제 `dict`에는 다음이 포함될 수 있습니다:
+
+* `summary`: 예제에 대한 짧은 설명문.
+* `description`: 마크다운 텍스트를 포함할 수 있는 긴 설명문.
+* `value`: 실제로 보여지는 예시, 예를 들면 `dict`.
+* `externalValue`: `value`의 대안이며 예제를 가리키는 URL. 비록 `value`처럼 많은 도구를 지원하지 못할 수 있습니다.
+
+이를 다음과 같이 사용할 수 있습니다:
+
+{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *}
+
+### 문서 UI에서의 OpenAPI 예시 { #openapi-examples-in-the-docs-ui }
+
+`Body()`에 `openapi_examples`가 추가되면 `/docs`는 다음과 같이 보일 것입니다:
+
+
+
+## 기술적 세부 사항 { #technical-details }
+
+/// tip | 팁
+
+이미 **FastAPI**의 **0.99.0 혹은 그 이상** 버전을 사용하고 있다면, 이 세부 사항을 **스킵**해도 상관 없을 것입니다.
+
+세부 사항은 OpenAPI 3.1.0이 사용가능하기 전, 예전 버전과 더 관련있습니다.
+
+간략한 OpenAPI와 JSON 스키마 **역사 강의**로 생각할 수 있습니다. 🤓
+
+///
+
+/// warning | 경고
+
+표준 **JSON 스키마**와 **OpenAPI**에 대한 아주 기술적인 세부사항입니다.
+
+만약 위의 생각이 작동한다면, 그것으로 충분하며 이 세부 사항은 필요없을 것이니, 마음 편하게 스킵하셔도 됩니다.
+
+///
+
+OpenAPI 3.1.0 전에 OpenAPI는 오래된 **JSON 스키마**의 수정된 버전을 사용했습니다.
+
+JSON 스키마는 `examples`를 가지고 있지 않았고, 따라서 OpenAPI는 그들만의 `example` 필드를 수정된 버전에 추가했습니다.
+
+OpenAPI는 또한 `example`과 `examples` 필드를 명세서의 다른 부분에 추가했습니다:
+
+* [`Parameter Object` (명세서에 있는)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object)는 FastAPI의 다음 기능에서 쓰였습니다:
+ * `Path()`
+ * `Query()`
+ * `Header()`
+ * `Cookie()`
+* [`Request Body Object`, `Media Type Object` (명세서에 있는)의 `content` 필드에 있는](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object)는 FastAPI의 다음 기능에서 쓰였습니다:
+ * `Body()`
+ * `File()`
+ * `Form()`
+
+/// info | 정보
+
+이 예전 OpenAPI-특화 `examples` 매개변수는 이제 FastAPI `0.103.0`부터 `openapi_examples`입니다.
+
+///
+
+### JSON 스키마의 `examples` 필드 { #json-schemas-examples-field }
+
+하지만, 후에 JSON 스키마는 [`examples`](https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.9.5) 필드를 명세서의 새 버전에 추가했습니다.
+
+그리고 새로운 OpenAPI 3.1.0은 이 새로운 `examples` 필드가 포함된 최신 버전 (JSON 스키마 2020-12)을 기반으로 했습니다.
+
+그리고 이제 이 새로운 `examples` 필드는 이제 지원 중단된, 예전의 단일 (그리고 커스텀) `example` 필드보다 우선됩니다.
+
+JSON 스키마의 새로운 `examples` 필드는 예제의 **단순한 `list`**일 뿐이며, (위에서 상술한 것처럼) OpenAPI의 다른 곳에 존재하는 추가 메타데이터가 있는 dict가 아닙니다.
+
+/// info | 정보
+
+더 쉽고 새로운 JSON 스키마와의 통합과 함께 OpenAPI 3.1.0가 배포되었지만, 잠시동안 자동 문서 생성을 제공하는 도구인 Swagger UI는 OpenAPI 3.1.0을 지원하지 않았습니다 (5.0.0 버전부터 지원합니다 🎉).
+
+이로인해, FastAPI 0.99.0 이전 버전은 아직 OpenAPI 3.1.0 보다 낮은 버전을 사용했습니다.
+
+///
+
+### Pydantic과 FastAPI `examples` { #pydantic-and-fastapi-examples }
+
+Pydantic 모델 안에 `examples`를 추가할 때, `schema_extra` 또는 `Field(examples=["something"])`를 사용하면 그 예제는 해당 Pydantic 모델의 **JSON 스키마**에 추가됩니다.
+
+그리고 Pydantic 모델의 **JSON 스키마**는 API의 **OpenAPI**에 포함되고, 그 후 문서 UI 속에서 사용됩니다.
+
+FastAPI 0.99.0 이전 버전에서 (0.99.0 이상 버전은 새로운 OpenAPI 3.1.0을 사용합니다), 다른 유틸리티(`Query()`, `Body()` 등)와 함께 `example` 또는 `examples`를 사용했을 때, 그러한 예제는 그 데이터를 설명하는 JSON 스키마에 추가되지 않고 (OpenAPI 자체의 JSON 스키마에도 포함되지 않습니다), OpenAPI의 *경로 처리* 선언에 직접적으로 추가됩니다 (JSON 스키마를 사용하는 OpenAPI 부분 밖에서).
+
+하지만 이제 FastAPI 0.99.0 및 이후 버전에서는 JSON 스키마 2020-12를 사용하는 OpenAPI 3.1.0과 Swagger UI 5.0.0 및 이후 버전을 사용하기 때문에, 모든 것이 더 일관성을 띄고 예제도 JSON 스키마에 포함됩니다.
+
+### Swagger UI와 OpenAPI-특화 `examples` { #swagger-ui-and-openapi-specific-examples }
+
+Swagger UI는 다중 JSON 스키마 예제를 지원하지 않았기 때문에(2023-08-26 기준), 사용자는 문서에 여러 예제를 표시할 방법이 없었습니다.
+
+이를 해결하기 위해, FastAPI `0.103.0`은 새로운 매개변수인 `openapi_examples`로 동일한 예전 **OpenAPI-특화** `examples` 필드를 선언하는 **지원**을 추가했습니다. 🤓
+
+### 요약 { #summary }
+
+저는 역사를 그다지 좋아하는 편이 아니라고 말하고는 했지만... "기술 역사" 강의를 하는 지금의 저를 보세요. 😅
+
+요약하자면 **FastAPI 0.99.0 혹은 그 이상의 버전**으로 업그레이드하면, 많은 것들이 훨씬 더 **단순하고, 일관적이며 직관적**이 되며, 여러분은 이 모든 역사적 세부 사항을 알 필요가 없습니다. 😎
diff --git a/docs/ko/docs/tutorial/security/first-steps.md b/docs/ko/docs/tutorial/security/first-steps.md
new file mode 100644
index 0000000000000..8b7563ec3e9eb
--- /dev/null
+++ b/docs/ko/docs/tutorial/security/first-steps.md
@@ -0,0 +1,203 @@
+# 보안 - 첫 단계 { #security-first-steps }
+
+어떤 도메인에 **backend** API가 있다고 가정해 보겠습니다.
+
+그리고 다른 도메인에 **frontend**가 있거나, 같은 도메인의 다른 경로에 있거나(또는 모바일 애플리케이션에 있을 수도 있습니다).
+
+그리고 frontend가 **username**과 **password**를 사용해 backend에 인증할 수 있는 방법이 필요하다고 해봅시다.
+
+**FastAPI**와 함께 **OAuth2**를 사용해서 이를 구현할 수 있습니다.
+
+하지만 필요한 작은 정보 조각들을 찾기 위해 길고 긴 전체 스펙을 읽느라 시간을 쓰지 않도록 하겠습니다.
+
+보안을 처리하기 위해 **FastAPI**가 제공하는 도구들을 사용해 봅시다.
+
+## 어떻게 보이는지 { #how-it-looks }
+
+먼저 코드를 그냥 사용해서 어떻게 동작하는지 보고, 그다음에 무슨 일이 일어나는지 이해하러 다시 돌아오겠습니다.
+
+## `main.py` 만들기 { #create-main-py }
+
+예제를 파일 `main.py`에 복사하세요:
+
+{* ../../docs_src/security/tutorial001_an_py310.py *}
+
+## 실행하기 { #run-it }
+
+/// info | 정보
+
+[`python-multipart`](https://github.com/Kludex/python-multipart) 패키지는 `pip install "fastapi[standard]"` 명령을 실행하면 **FastAPI**와 함께 자동으로 설치됩니다.
+
+하지만 `pip install fastapi` 명령을 사용하면 `python-multipart` 패키지가 기본으로 포함되지 않습니다.
+
+수동으로 설치하려면, [가상 환경](../../virtual-environments.md)을 만들고 활성화한 다음, 아래로 설치하세요:
+
+```console
+$ pip install python-multipart
+```
+
+이는 **OAuth2**가 `username`과 `password`를 보내기 위해 "form data"를 사용하기 때문입니다.
+
+///
+
+다음으로 예제를 실행하세요:
+
+
+
+/// check | Authorize 버튼!
+
+반짝이는 새 "Authorize" 버튼이 이미 있습니다.
+
+그리고 *경로 처리*에는 오른쪽 상단에 클릭할 수 있는 작은 자물쇠가 있습니다.
+
+///
+
+그리고 이를 클릭하면 `username`과 `password`(그리고 다른 선택적 필드들)를 입력할 수 있는 작은 인증 폼이 나타납니다:
+
+
+
+/// note | 참고
+
+폼에 무엇을 입력하든 아직은 동작하지 않습니다. 하지만 곧 여기까지 구현할 것입니다.
+
+///
+
+물론 이것은 최종 사용자를 위한 frontend는 아니지만, 모든 API를 대화형으로 문서화하는 훌륭한 자동 도구입니다.
+
+frontend 팀(그게 본인일 수도 있습니다)이 사용할 수 있습니다.
+
+서드파티 애플리케이션과 시스템에서도 사용할 수 있습니다.
+
+그리고 동일한 애플리케이션을 디버그하고, 확인하고, 테스트하기 위해 본인이 사용할 수도 있습니다.
+
+## `password` 플로우 { #the-password-flow }
+
+이제 조금 돌아가서 이것들이 무엇인지 이해해 봅시다.
+
+`password` "flow"는 보안과 인증을 처리하기 위해 OAuth2에서 정의한 여러 방식("flows") 중 하나입니다.
+
+OAuth2는 backend 또는 API가 사용자를 인증하는 서버와 독립적일 수 있도록 설계되었습니다.
+
+하지만 이 경우에는 같은 **FastAPI** 애플리케이션이 API와 인증을 모두 처리합니다.
+
+따라서, 단순화된 관점에서 다시 정리해보면:
+
+* 사용자가 frontend에서 `username`과 `password`를 입력하고 `Enter`를 누릅니다.
+* frontend(사용자의 브라우저에서 실행됨)는 해당 `username`과 `password`를 우리 API의 특정 URL로 보냅니다(`tokenUrl="token"`로 선언됨).
+* API는 `username`과 `password`를 확인하고 "token"으로 응답합니다(아직 아무것도 구현하지 않았습니다).
+ * "token"은 나중에 이 사용자를 검증하는 데 사용할 수 있는 어떤 내용이 담긴 문자열일 뿐입니다.
+ * 보통 token은 일정 시간이 지나면 만료되도록 설정합니다.
+ * 그래서 사용자는 나중에 어느 시점엔 다시 로그인해야 합니다.
+ * 그리고 token이 도난당하더라도 위험이 더 낮습니다. 대부분의 경우 영구적으로 항상 동작하는 키와는 다릅니다.
+* frontend는 그 token을 임시로 어딘가에 저장합니다.
+* 사용자가 frontend에서 클릭해서 frontend 웹 앱의 다른 섹션으로 이동합니다.
+* frontend는 API에서 더 많은 데이터를 가져와야 합니다.
+ * 하지만 그 특정 endpoint에는 인증이 필요합니다.
+ * 그래서 우리 API에 인증하기 위해 `Authorization` 헤더를, 값은 `Bearer `에 token을 더한 형태로 보냅니다.
+ * token에 `foobar`가 들어 있다면 `Authorization` 헤더의 내용은 `Bearer foobar`가 됩니다.
+
+## **FastAPI**의 `OAuth2PasswordBearer` { #fastapis-oauth2passwordbearer }
+
+**FastAPI**는 이런 보안 기능을 구현하기 위해, 서로 다른 추상화 수준에서 여러 도구를 제공합니다.
+
+이 예제에서는 **OAuth2**의 **Password** 플로우와 **Bearer** token을 사용합니다. 이를 위해 `OAuth2PasswordBearer` 클래스를 사용합니다.
+
+/// info | 정보
+
+"bearer" token만이 유일한 선택지는 아닙니다.
+
+하지만 이 사용 사례에는 가장 적합한 선택입니다.
+
+또한 OAuth2 전문가로서 왜 다른 옵션이 더 적합한지 정확히 아는 경우가 아니라면, 대부분의 사용 사례에도 가장 적합할 가능성이 큽니다.
+
+그런 경우를 위해서도 **FastAPI**는 이를 구성할 수 있는 도구를 제공합니다.
+
+///
+
+`OAuth2PasswordBearer` 클래스의 인스턴스를 만들 때 `tokenUrl` 파라미터를 전달합니다. 이 파라미터에는 클라이언트(사용자의 브라우저에서 실행되는 frontend)가 token을 받기 위해 `username`과 `password`를 보낼 URL이 들어 있습니다.
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
+
+/// tip | 팁
+
+여기서 `tokenUrl="token"`은 아직 만들지 않은 상대 URL `token`을 가리킵니다. 상대 URL이므로 `./token`과 동일합니다.
+
+상대 URL을 사용하므로, 예를 들어 API가 `https://example.com/`에 있다면 `https://example.com/token`을 가리킵니다. 하지만 API가 `https://example.com/api/v1/`에 있다면 `https://example.com/api/v1/token`을 가리킵니다.
+
+상대 URL을 사용하는 것은 [프록시 뒤에서](../../advanced/behind-a-proxy.md) 같은 고급 사용 사례에서도 애플리케이션이 계속 동작하도록 보장하는 데 중요합니다.
+
+///
+
+이 파라미터는 그 endpoint / *경로 처리*를 만들지는 않지만, URL `/token`이 클라이언트가 token을 얻기 위해 사용해야 할 URL이라고 선언합니다. 이 정보는 OpenAPI에 사용되고, 이어서 대화형 API 문서 시스템에서도 사용됩니다.
+
+곧 실제 경로 처리를 만들 것입니다.
+
+/// info | 정보
+
+엄격한 "Pythonista"라면 `token_url` 대신 `tokenUrl` 같은 파라미터 이름 스타일이 마음에 들지 않을 수도 있습니다.
+
+이는 OpenAPI 스펙에서 사용하는 이름과 동일하게 맞춘 것이기 때문입니다. 그래서 이런 보안 스킴에 대해 더 조사해야 할 때, 그대로 복사해서 붙여 넣어 더 많은 정보를 찾을 수 있습니다.
+
+///
+
+`oauth2_scheme` 변수는 `OAuth2PasswordBearer`의 인스턴스이지만, "callable"이기도 합니다.
+
+다음처럼 호출될 수 있습니다:
+
+```Python
+oauth2_scheme(some, parameters)
+```
+
+따라서 `Depends`와 함께 사용할 수 있습니다.
+
+### 사용하기 { #use-it }
+
+이제 `Depends`로 `oauth2_scheme`를 의존성에 전달할 수 있습니다.
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+이 의존성은 `str`을 제공하고, 그 값은 *경로 처리 함수*의 파라미터 `token`에 할당됩니다.
+
+**FastAPI**는 이 의존성을 사용해 OpenAPI 스키마(및 자동 API 문서)에 "security scheme"를 정의할 수 있다는 것을 알게 됩니다.
+
+/// info | 기술 세부사항
+
+**FastAPI**는 (의존성에 선언된) `OAuth2PasswordBearer` 클래스를 사용해 OpenAPI에서 보안 스킴을 정의할 수 있다는 것을 알고 있습니다. 이는 `OAuth2PasswordBearer`가 `fastapi.security.oauth2.OAuth2`를 상속하고, 이것이 다시 `fastapi.security.base.SecurityBase`를 상속하기 때문입니다.
+
+OpenAPI(및 자동 API 문서)와 통합되는 모든 보안 유틸리티는 `SecurityBase`를 상속하며, 그래서 **FastAPI**가 이를 OpenAPI에 어떻게 통합할지 알 수 있습니다.
+
+///
+
+## 무엇을 하는지 { #what-it-does }
+
+요청에서 `Authorization` 헤더를 찾아, 값이 `Bearer `에 어떤 token이 붙은 형태인지 확인한 뒤, 그 token을 `str`로 반환합니다.
+
+`Authorization` 헤더가 없거나, 값에 `Bearer ` token이 없다면, 곧바로 401 상태 코드 오류(`UNAUTHORIZED`)로 응답합니다.
+
+오류를 반환하기 위해 token이 존재하는지 직접 확인할 필요조차 없습니다. 함수가 실행되었다면 그 token에는 `str`이 들어 있다고 확신할 수 있습니다.
+
+대화형 문서에서 이미 시도해 볼 수 있습니다:
+
+
+
+아직 token의 유효성을 검증하진 않지만, 이것만으로도 시작은 된 셈입니다.
+
+## 요약 { #recap }
+
+즉, 추가로 3~4줄만으로도 이미 원시적인 형태의 보안을 갖추게 됩니다.
diff --git a/docs/ko/docs/tutorial/security/get-current-user.md b/docs/ko/docs/tutorial/security/get-current-user.md
new file mode 100644
index 0000000000000..eab599e2753bb
--- /dev/null
+++ b/docs/ko/docs/tutorial/security/get-current-user.md
@@ -0,0 +1,105 @@
+# 현재 사용자 가져오기 { #get-current-user }
+
+이전 장에서 (의존성 주입 시스템을 기반으로 한) 보안 시스템은 *경로 처리 함수*에 `str`로 `token`을 제공했습니다:
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+하지만 이는 여전히 그다지 유용하지 않습니다.
+
+현재 사용자를 제공하도록 해봅시다.
+
+## 사용자 모델 생성하기 { #create-a-user-model }
+
+먼저 Pydantic 사용자 모델을 만들어 봅시다.
+
+Pydantic을 사용해 본문을 선언하는 것과 같은 방식으로, 다른 곳에서도 어디서든 사용할 수 있습니다:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *}
+
+## `get_current_user` 의존성 생성하기 { #create-a-get-current-user-dependency }
+
+의존성 `get_current_user`를 만들어 봅시다.
+
+의존성이 하위 의존성을 가질 수 있다는 것을 기억하시나요?
+
+`get_current_user`는 이전에 생성한 것과 동일한 `oauth2_scheme`에 대한 의존성을 갖게 됩니다.
+
+이전에 *경로 처리*에서 직접 수행했던 것과 동일하게, 새 의존성 `get_current_user`는 하위 의존성 `oauth2_scheme`로부터 `str`로 `token`을 받게 됩니다:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *}
+
+## 사용자 가져오기 { #get-the-user }
+
+`get_current_user`는 우리가 만든 (가짜) 유틸리티 함수를 사용합니다. 이 함수는 `str`로 토큰을 받아 Pydantic `User` 모델을 반환합니다:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *}
+
+## 현재 사용자 주입하기 { #inject-the-current-user }
+
+이제 *경로 처리*에서 `get_current_user`와 함께 같은 `Depends`를 사용할 수 있습니다:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *}
+
+`current_user`의 타입을 Pydantic 모델 `User`로 선언한다는 점에 주목하세요.
+
+이는 함수 내부에서 자동 완성과 타입 체크에 도움을 줍니다.
+
+/// tip | 팁
+
+요청 본문도 Pydantic 모델로 선언된다는 것을 기억하실지도 모릅니다.
+
+여기서 **FastAPI**는 `Depends`를 사용하고 있기 때문에 혼동하지 않습니다.
+
+///
+
+/// check | 확인
+
+이 의존성 시스템이 설계된 방식은 모두 `User` 모델을 반환하는 서로 다른 의존성(서로 다른 "dependables")을 가질 수 있도록 합니다.
+
+해당 타입의 데이터를 반환할 수 있는 의존성이 하나만 있어야 하는 것으로 제한되지 않습니다.
+
+///
+
+## 다른 모델 { #other-models }
+
+이제 *경로 처리 함수*에서 현재 사용자를 직접 가져올 수 있으며, `Depends`를 사용해 **의존성 주입** 수준에서 보안 메커니즘을 처리할 수 있습니다.
+
+그리고 보안 요구 사항을 위해 어떤 모델이나 데이터든 사용할 수 있습니다(이 경우 Pydantic 모델 `User`).
+
+하지만 특정 데이터 모델, 클래스 또는 타입만 사용해야 하는 것은 아닙니다.
+
+모델에 `id`와 `email`이 있고 `username`은 없게 하고 싶으신가요? 물론입니다. 같은 도구를 사용할 수 있습니다.
+
+`str`만 갖고 싶으신가요? 아니면 `dict`만요? 또는 데이터베이스 클래스 모델 인스턴스를 직접 쓰고 싶으신가요? 모두 같은 방식으로 동작합니다.
+
+애플리케이션에 로그인하는 사용자는 없고, 액세스 토큰만 가진 로봇, 봇 또는 다른 시스템만 있나요? 이것도 마찬가지로 모두 동일하게 동작합니다.
+
+애플리케이션에 필요한 어떤 종류의 모델, 어떤 종류의 클래스, 어떤 종류의 데이터베이스든 사용하세요. **FastAPI**는 의존성 주입 시스템으로 이를 지원합니다.
+
+## 코드 크기 { #code-size }
+
+이 예시는 장황해 보일 수 있습니다. 동일한 파일에서 보안, 데이터 모델, 유틸리티 함수 및 *경로 처리*를 섞어서 사용하고 있다는 점을 기억하세요.
+
+하지만 여기 핵심이 있습니다.
+
+보안과 의존성 주입 관련 코드는 한 번만 작성합니다.
+
+그리고 원하는 만큼 복잡하게 만들 수 있습니다. 그럼에도 여전히 한 번만, 한 곳에만 작성하면 됩니다. 유연성을 모두 유지하면서요.
+
+하지만 같은 보안 시스템을 사용해 수천 개의 엔드포인트(*경로 처리*)를 가질 수 있습니다.
+
+그리고 그들 모두(또는 원하는 일부)는 이러한 의존성 또는 여러분이 생성한 다른 의존성을 재사용하는 이점을 얻을 수 있습니다.
+
+그리고 이 수천 개의 *경로 처리*는 3줄 정도로도 만들 수 있습니다:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *}
+
+## 요약 { #recap }
+
+이제 *경로 처리 함수*에서 현재 사용자를 직접 가져올 수 있습니다.
+
+우리는 이미 절반은 왔습니다.
+
+사용자/클라이언트가 실제로 `username`과 `password`를 보내도록 하는 *경로 처리*만 추가하면 됩니다.
+
+다음에 이어집니다.
diff --git a/docs/ko/docs/tutorial/security/index.md b/docs/ko/docs/tutorial/security/index.md
new file mode 100644
index 0000000000000..2320b06571a2f
--- /dev/null
+++ b/docs/ko/docs/tutorial/security/index.md
@@ -0,0 +1,106 @@
+# 보안 { #security }
+
+보안, 인증(authentication), 인가(authorization)를 처리하는 방법은 매우 다양합니다.
+
+그리고 보통 복잡하고 "어려운" 주제이기도 합니다.
+
+많은 프레임워크와 시스템에서 보안과 인증만 처리하는 데도 큰 노력과 코드가 필요합니다(많은 경우 작성된 전체 코드의 50% 이상이 될 수도 있습니다).
+
+**FastAPI**는 모든 보안 명세를 전부 공부하고 배울 필요 없이, 표준적인 방식으로 쉽고 빠르게 **보안(Security)** 을 다룰 수 있도록 여러 도구를 제공합니다.
+
+하지만 먼저, 몇 가지 작은 개념을 확인해 보겠습니다.
+
+## 급하신가요? { #in-a-hurry }
+
+이 용어들에 관심이 없고 사용자명과 비밀번호 기반 인증을 사용한 보안을 *지금 당장* 추가하기만 하면 된다면, 다음 장들로 넘어가세요.
+
+## OAuth2 { #oauth2 }
+
+OAuth2는 인증과 인가를 처리하는 여러 방법을 정의하는 명세입니다.
+
+상당히 방대한 명세이며 여러 복잡한 사용 사례를 다룹니다.
+
+"제3자"를 사용해 인증하는 방법도 포함합니다.
+
+바로 `"Facebook, Google, X (Twitter), GitHub로 로그인"` 같은 시스템들이 내부적으로 사용하는 방식입니다.
+
+### OAuth 1 { #oauth-1 }
+
+OAuth 1도 있었는데, 이는 OAuth2와 매우 다르고 통신을 암호화하는 방법까지 직접 명세에 포함했기 때문에 더 복잡했습니다.
+
+요즘에는 그다지 인기 있거나 사용되지는 않습니다.
+
+OAuth2는 통신을 어떻게 암호화할지는 명세하지 않고, 애플리케이션이 HTTPS로 제공될 것을 기대합니다.
+
+/// tip | 팁
+
+**배포**에 대한 섹션에서 Traefik과 Let's Encrypt를 사용해 무료로 HTTPS를 설정하는 방법을 볼 수 있습니다.
+
+///
+
+## OpenID Connect { #openid-connect }
+
+OpenID Connect는 **OAuth2**를 기반으로 한 또 다른 명세입니다.
+
+OAuth2에서 비교적 모호한 부분을 일부 구체화하여 상호 운용성을 높이려는 확장입니다.
+
+예를 들어, Google 로그인은 OpenID Connect를 사용합니다(내부적으로는 OAuth2를 사용).
+
+하지만 Facebook 로그인은 OpenID Connect를 지원하지 않습니다. 자체적인 변형의 OAuth2를 사용합니다.
+
+### OpenID("OpenID Connect"가 아님) { #openid-not-openid-connect }
+
+"OpenID"라는 명세도 있었습니다. 이는 **OpenID Connect**와 같은 문제를 해결하려고 했지만, OAuth2를 기반으로 하지 않았습니다.
+
+따라서 완전히 별도의 추가 시스템이었습니다.
+
+요즘에는 그다지 인기 있거나 사용되지는 않습니다.
+
+## OpenAPI { #openapi }
+
+OpenAPI(이전에는 Swagger로 알려짐)는 API를 구축하기 위한 공개 명세입니다(현재 Linux Foundation의 일부).
+
+**FastAPI**는 **OpenAPI**를 기반으로 합니다.
+
+이 덕분에 여러 자동 대화형 문서 인터페이스, 코드 생성 등과 같은 기능을 사용할 수 있습니다.
+
+OpenAPI에는 여러 보안 "scheme"을 정의하는 방법이 있습니다.
+
+이를 사용하면 이러한 대화형 문서 시스템을 포함해, 표준 기반 도구들을 모두 활용할 수 있습니다.
+
+OpenAPI는 다음 보안 scheme들을 정의합니다:
+
+* `apiKey`: 다음에서 전달될 수 있는 애플리케이션 전용 키:
+ * 쿼리 파라미터
+ * 헤더
+ * 쿠키
+* `http`: 표준 HTTP 인증 시스템, 예:
+ * `bearer`: `Authorization` 헤더에 `Bearer ` + 토큰 값을 넣는 방식. OAuth2에서 유래했습니다.
+ * HTTP Basic 인증
+ * HTTP Digest 등
+* `oauth2`: 보안을 처리하는 모든 OAuth2 방식(이를 "flow"라고 부릅니다).
+ * 이 flow들 중 여러 개는 OAuth 2.0 인증 제공자(예: Google, Facebook, X (Twitter), GitHub 등)를 구축하는 데 적합합니다:
+ * `implicit`
+ * `clientCredentials`
+ * `authorizationCode`
+ * 하지만 같은 애플리케이션에서 직접 인증을 처리하는 데 완벽하게 사용할 수 있는 특정 "flow"도 하나 있습니다:
+ * `password`: 다음 장들에서 이에 대한 예시를 다룹니다.
+* `openIdConnect`: OAuth2 인증 데이터를 자동으로 탐색(discover)하는 방법을 정의합니다.
+ * 이 자동 탐색은 OpenID Connect 명세에서 정의됩니다.
+
+
+/// tip | 팁
+
+Google, Facebook, X (Twitter), GitHub 등 다른 인증/인가 제공자를 통합하는 것도 가능하며 비교적 쉽습니다.
+
+가장 복잡한 문제는 그런 인증/인가 제공자 자체를 구축하는 것이지만, **FastAPI**는 어려운 작업을 대신 처리해 주면서 이를 쉽게 할 수 있는 도구를 제공합니다.
+
+///
+
+## **FastAPI** 유틸리티 { #fastapi-utilities }
+
+FastAPI는 `fastapi.security` 모듈에서 각 보안 scheme에 대한 여러 도구를 제공하며, 이러한 보안 메커니즘을 더 쉽게 사용할 수 있게 해줍니다.
+
+다음 장들에서는 **FastAPI**가 제공하는 도구를 사용해 API에 보안을 추가하는 방법을 보게 될 것입니다.
+
+또한 대화형 문서 시스템에 어떻게 자동으로 통합되는지도 확인하게 됩니다.
diff --git a/docs/ko/docs/tutorial/security/oauth2-jwt.md b/docs/ko/docs/tutorial/security/oauth2-jwt.md
new file mode 100644
index 0000000000000..3c3b93e3a6b74
--- /dev/null
+++ b/docs/ko/docs/tutorial/security/oauth2-jwt.md
@@ -0,0 +1,277 @@
+# 패스워드(해싱 포함)를 사용하는 OAuth2, JWT 토큰을 사용하는 Bearer { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
+
+모든 보안 흐름을 구성했으므로, 이제 JWT 토큰과 안전한 패스워드 해싱을 사용해 애플리케이션을 실제로 안전하게 만들겠습니다.
+
+이 코드는 실제로 애플리케이션에서 사용할 수 있으며, 패스워드 해시를 데이터베이스에 저장하는 등의 작업에 활용할 수 있습니다.
+
+이전 장에서 멈춘 지점부터 시작해 내용을 확장해 나가겠습니다.
+
+## JWT 알아보기 { #about-jwt }
+
+JWT는 "JSON Web Tokens"를 의미합니다.
+
+JSON 객체를 공백이 없는 길고 밀집된 문자열로 부호화하는 표준입니다. 다음과 같은 형태입니다:
+
+```
+eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
+```
+
+암호화된 것이 아니므로, 누구나 내용에서 정보를 복원할 수 있습니다.
+
+하지만 서명되어 있습니다. 따라서 자신이 발급한 토큰을 받았을 때, 실제로 자신이 발급한 것이 맞는지 검증할 수 있습니다.
+
+예를 들어 만료 기간이 1주일인 토큰을 생성할 수 있습니다. 그리고 사용자가 다음 날 토큰을 가지고 돌아오면, 그 사용자가 시스템에 여전히 로그인되어 있다는 것을 알 수 있습니다.
+
+1주일 뒤에는 토큰이 만료되고 사용자는 인가되지 않으므로 새 토큰을 받기 위해 다시 로그인해야 합니다. 그리고 사용자(또는 제3자)가 만료 시간을 바꾸기 위해 토큰을 수정하려고 하면, 서명이 일치하지 않기 때문에 이를 알아챌 수 있습니다.
+
+JWT 토큰을 직접 다뤄보고 동작 방식을 확인해보고 싶다면 [https://jwt.io](https://jwt.io/)를 확인하십시오.
+
+## `PyJWT` 설치 { #install-pyjwt }
+
+Python에서 JWT 토큰을 생성하고 검증하려면 `PyJWT`를 설치해야 합니다.
+
+[가상환경](../../virtual-environments.md)을 만들고 활성화한 다음 `pyjwt`를 설치하십시오:
+
+
+
+이전과 같은 방법으로 애플리케이션을 인가하십시오.
+
+다음 인증 정보를 사용하십시오:
+
+Username: `johndoe`
+Password: `secret`
+
+/// check | 확인
+
+코드 어디에도 평문 패스워드 "`secret`"은 없고, 해시된 버전만 있다는 점에 유의하십시오.
+
+///
+
+
+
+엔드포인트 `/users/me/`를 호출하면 다음과 같은 응답을 받게 됩니다:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false
+}
+```
+
+
+
+개발자 도구를 열어보면 전송된 데이터에는 토큰만 포함되어 있고, 패스워드는 사용자를 인증하고 해당 액세스 토큰을 얻기 위한 첫 번째 요청에서만 전송되며 이후에는 전송되지 않는 것을 확인할 수 있습니다:
+
+
+
+/// note | 참고
+
+`Bearer `로 시작하는 값을 가진 `Authorization` 헤더에 주목하십시오.
+
+///
+
+## `scopes`의 고급 사용법 { #advanced-usage-with-scopes }
+
+OAuth2에는 "scopes"라는 개념이 있습니다.
+
+이를 사용해 JWT 토큰에 특정 권한 집합을 추가할 수 있습니다.
+
+그런 다음 이 토큰을 사용자에게 직접 제공하거나 제3자에게 제공하여, 특정 제한사항 하에서 API와 상호작용하도록 할 수 있습니다.
+
+어떻게 사용하는지, 그리고 **FastAPI**에 어떻게 통합되는지는 이후 **심화 사용자 안내서**에서 배울 수 있습니다.
+
+## 요약 { #recap }
+
+지금까지 살펴본 내용을 바탕으로, OAuth2와 JWT 같은 표준을 사용해 안전한 **FastAPI** 애플리케이션을 설정할 수 있습니다.
+
+거의 모든 프레임워크에서 보안 처리는 꽤 빠르게 복잡한 주제가 됩니다.
+
+이를 크게 단순화하는 많은 패키지들은 데이터 모델, 데이터베이스, 사용 가능한 기능들에 대해 많은 타협을 해야 합니다. 그리고 지나치게 단순화하는 일부 패키지들은 실제로 내부에 보안 결함이 있기도 합니다.
+
+---
+
+**FastAPI**는 어떤 데이터베이스, 데이터 모델, 도구에도 타협하지 않습니다.
+
+프로젝트에 가장 잘 맞는 것들을 선택할 수 있는 모든 유연성을 제공합니다.
+
+그리고 **FastAPI**는 외부 패키지를 통합하기 위해 복잡한 메커니즘을 요구하지 않기 때문에 `pwdlib`와 `PyJWT` 같은 잘 관리되고 널리 사용되는 패키지들을 바로 사용할 수 있습니다.
+
+하지만 유연성, 견고성, 보안성을 해치지 않으면서 과정을 가능한 한 단순화할 수 있도록 도구들을 제공합니다.
+
+또한 OAuth2 같은 안전한 표준 프로토콜을 비교적 간단한 방식으로 사용하고 구현할 수 있습니다.
+
+더 세분화된 권한 시스템을 위해 OAuth2 "scopes"를 사용하는 방법은, 같은 표준을 따르는 방식으로 **심화 사용자 안내서**에서 더 자세히 배울 수 있습니다. 스코프를 사용하는 OAuth2는 Facebook, Google, GitHub, Microsoft, X (Twitter) 등 많은 대형 인증 제공업체들이 제3자 애플리케이션이 사용자 대신 그들의 API와 상호작용할 수 있도록 인가하는 데 사용하는 메커니즘입니다.
diff --git a/docs/ko/docs/tutorial/security/simple-oauth2.md b/docs/ko/docs/tutorial/security/simple-oauth2.md
new file mode 100644
index 0000000000000..48361de83d05e
--- /dev/null
+++ b/docs/ko/docs/tutorial/security/simple-oauth2.md
@@ -0,0 +1,289 @@
+# 패스워드와 Bearer를 이용한 간단한 OAuth2 { #simple-oauth2-with-password-and-bearer }
+
+이제 이전 장에서 빌드하고 누락된 부분을 추가하여 완전한 보안 흐름을 갖도록 하겠습니다.
+
+## `username`와 `password` 얻기 { #get-the-username-and-password }
+
+**FastAPI** 보안 유틸리티를 사용하여 `username` 및 `password`를 가져올 것입니다.
+
+OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할 때 클라이언트/유저가 `username` 및 `password` 필드를 폼 데이터로 보내야 함을 지정합니다.
+
+그리고 사양에는 필드의 이름을 그렇게 지정해야 한다고 나와 있습니다. 따라서 `user-name` 또는 `email`은 작동하지 않습니다.
+
+하지만 걱정하지 않아도 됩니다. 프런트엔드에서 최종 사용자에게 원하는 대로 표시할 수 있습니다.
+
+그리고 데이터베이스 모델은 원하는 다른 이름을 사용할 수 있습니다.
+
+그러나 로그인 *경로 처리*의 경우 사양과 호환되도록 이러한 이름을 사용해야 합니다(예를 들어 통합 API 문서 시스템을 사용할 수 있어야 합니다).
+
+사양에는 또한 `username`과 `password`가 폼 데이터로 전송되어야 한다고 명시되어 있습니다(따라서 여기에는 JSON이 없습니다).
+
+### `scope` { #scope }
+
+사양에는 클라이언트가 다른 폼 필드 "`scope`"를 보낼 수 있다고 나와 있습니다.
+
+폼 필드 이름은 `scope`(단수형)이지만 실제로는 공백으로 구분된 "범위"가 있는 긴 문자열입니다.
+
+각 "범위"는 공백이 없는 문자열입니다.
+
+일반적으로 특정 보안 권한을 선언하는 데 사용됩니다. 다음을 봅시다:
+
+* `users:read` 또는 `users:write`는 일반적인 예시입니다.
+* `instagram_basic`은 페이스북/인스타그램에서 사용합니다.
+* `https://www.googleapis.com/auth/drive`는 Google에서 사용합니다.
+
+/// info | 정보
+
+OAuth2에서 "범위"는 필요한 특정 권한을 선언하는 문자열입니다.
+
+`:`과 같은 다른 문자가 있는지 또는 URL인지는 중요하지 않습니다.
+
+이러한 세부 사항은 구현에 따라 다릅니다.
+
+OAuth2의 경우 문자열일 뿐입니다.
+
+///
+
+## `username`과 `password`를 가져오는 코드 { #code-to-get-the-username-and-password }
+
+이제 **FastAPI**에서 제공하는 유틸리티를 사용하여 이를 처리해 보겠습니다.
+
+### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform }
+
+먼저 `OAuth2PasswordRequestForm`을 가져와 `/token`에 대한 *경로 처리*에서 `Depends`의 의존성으로 사용합니다.
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}
+
+`OAuth2PasswordRequestForm`은 다음을 사용하여 폼 본문을 선언하는 클래스 의존성입니다:
+
+* `username`.
+* `password`.
+* `scope`는 선택적인 필드로 공백으로 구분된 문자열로 구성된 큰 문자열입니다.
+* `grant_type`(선택적으로 사용).
+
+/// tip | 팁
+
+OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 필드를 *요구*하지만 `OAuth2PasswordRequestForm`은 이를 강요하지 않습니다.
+
+사용해야 한다면 `OAuth2PasswordRequestForm` 대신 `OAuth2PasswordRequestFormStrict`를 사용하면 됩니다.
+
+///
+
+* `client_id`(선택적으로 사용) (예제에서는 필요하지 않습니다).
+* `client_secret`(선택적으로 사용) (예제에서는 필요하지 않습니다).
+
+/// info | 정보
+
+`OAuth2PasswordRequestForm`은 `OAuth2PasswordBearer`와 같이 **FastAPI**에 대한 특수 클래스가 아닙니다.
+
+`OAuth2PasswordBearer`는 **FastAPI**가 보안 체계임을 알도록 합니다. 그래서 OpenAPI에 그렇게 추가됩니다.
+
+그러나 `OAuth2PasswordRequestForm`은 직접 작성하거나 `Form` 매개변수를 직접 선언할 수 있는 클래스 의존성일 뿐입니다.
+
+그러나 일반적인 사용 사례이므로 더 쉽게 하기 위해 **FastAPI**에서 직접 제공합니다.
+
+///
+
+### 폼 데이터 사용하기 { #use-the-form-data }
+
+/// tip | 팁
+
+종속성 클래스 `OAuth2PasswordRequestForm`의 인스턴스에는 공백으로 구분된 긴 문자열이 있는 `scope` 속성이 없고 대신 전송된 각 범위에 대한 실제 문자열 목록이 있는 `scopes` 속성이 있습니다.
+
+이 예제에서는 `scopes`를 사용하지 않지만 필요한 경우, 기능이 있습니다.
+
+///
+
+이제 폼 필드의 `username`을 사용하여 (가짜) 데이터베이스에서 유저 데이터를 가져옵니다.
+
+해당 사용자가 없으면 "잘못된 사용자 이름 또는 패스워드"라는 오류가 반환됩니다.
+
+오류의 경우 `HTTPException` 예외를 사용합니다:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}
+
+### 패스워드 확인하기 { #check-the-password }
+
+이 시점에서 데이터베이스의 사용자 데이터 형식을 확인했지만 암호를 확인하지 않았습니다.
+
+먼저 데이터를 Pydantic `UserInDB` 모델에 넣겠습니다.
+
+일반 텍스트 암호를 저장하면 안 되니 (가짜) 암호 해싱 시스템을 사용합니다.
+
+두 패스워드가 일치하지 않으면 동일한 오류가 반환됩니다.
+
+#### 패스워드 해싱 { #password-hashing }
+
+"해싱"은 일부 콘텐츠(이 경우 패스워드)를 횡설수설하는 것처럼 보이는 일련의 바이트(문자열)로 변환하는 것을 의미합니다.
+
+정확히 동일한 콘텐츠(정확히 동일한 패스워드)를 전달할 때마다 정확히 동일한 횡설수설이 발생합니다.
+
+그러나 횡설수설에서 암호로 다시 변환할 수는 없습니다.
+
+##### 패스워드 해싱을 사용해야 하는 이유 { #why-use-password-hashing }
+
+데이터베이스가 유출된 경우 해커는 사용자의 일반 텍스트 암호가 아니라 해시만 갖게 됩니다.
+
+따라서 해커는 다른 시스템에서 동일한 암호를 사용하려고 시도할 수 없습니다(많은 사용자가 모든 곳에서 동일한 암호를 사용하므로 이는 위험할 수 있습니다).
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}
+
+#### `**user_dict`에 대해 { #about-user-dict }
+
+`UserInDB(**user_dict)`는 다음을 의미한다:
+
+*`user_dict`의 키와 값을 다음과 같은 키-값 인수로 직접 전달합니다:*
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ disabled = user_dict["disabled"],
+ hashed_password = user_dict["hashed_password"],
+)
+```
+
+/// info | 정보
+
+`**user_dict`에 대한 자세한 설명은 [**추가 모델** 문서](../extra-models.md#about-user-in-dict)를 다시 확인해보세요.
+
+///
+
+## 토큰 반환하기 { #return-the-token }
+
+`token` 엔드포인트의 응답은 JSON 객체여야 합니다.
+
+`token_type`이 있어야 합니다. 여기서는 "Bearer" 토큰을 사용하므로 토큰 유형은 "`bearer`"여야 합니다.
+
+그리고 액세스 토큰을 포함하는 문자열과 함께 `access_token`이 있어야 합니다.
+
+이 간단한 예제에서는 완전히 안전하지 않고, 동일한 `username`을 토큰으로 반환합니다.
+
+/// tip | 팁
+
+다음 장에서는 패스워드 해싱 및 JWT 토큰을 사용하여 실제 보안 구현을 볼 수 있습니다.
+
+하지만 지금은 필요한 세부 정보에 집중하겠습니다.
+
+///
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}
+
+/// tip | 팁
+
+사양에 따라 이 예제와 동일하게 `access_token` 및 `token_type`이 포함된 JSON을 반환해야 합니다.
+
+이는 코드에서 직접 수행해야 하며 해당 JSON 키를 사용해야 합니다.
+
+사양을 준수하기 위해 스스로 올바르게 수행하기 위해 거의 유일하게 기억해야 하는 것입니다.
+
+나머지는 **FastAPI**가 처리합니다.
+
+///
+
+## 의존성 업데이트하기 { #update-the-dependencies }
+
+이제 의존성을 업데이트를 할 겁니다.
+
+이 사용자가 활성화되어 있는 *경우에만* `current_user`를 가져올 겁니다.
+
+따라서 `get_current_user`를 의존성으로 사용하는 추가 의존성 `get_current_active_user`를 만듭니다.
+
+이러한 의존성 모두, 사용자가 존재하지 않거나 비활성인 경우 HTTP 오류를 반환합니다.
+
+따라서 엔드포인트에서는 사용자가 존재하고 올바르게 인증되었으며 활성 상태인 경우에만 사용자를 얻습니다:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}
+
+/// info | 정보
+
+여기서 반환하는 값이 `Bearer`인 추가 헤더 `WWW-Authenticate`도 사양의 일부입니다.
+
+모든 HTTP(오류) 상태 코드 401 "UNAUTHORIZED"는 `WWW-Authenticate` 헤더도 반환해야 합니다.
+
+베어러 토큰의 경우(지금의 경우) 해당 헤더의 값은 `Bearer`여야 합니다.
+
+실제로 추가 헤더를 건너뛸 수 있으며 여전히 작동합니다.
+
+그러나 여기에서는 사양을 준수하도록 제공됩니다.
+
+또한 이를 예상하고 (현재 또는 미래에) 사용하는 도구가 있을 수 있으며, 현재 또는 미래에 자신 혹은 자신의 유저들에게 유용할 것입니다.
+
+그것이 표준의 이점입니다 ...
+
+///
+
+## 확인하기 { #see-it-in-action }
+
+대화형 문서 열기: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).
+
+### 인증하기 { #authenticate }
+
+"Authorize" 버튼을 눌러봅시다.
+
+자격 증명을 사용합니다.
+
+유저명: `johndoe`
+
+패스워드: `secret`
+
+
+
+시스템에서 인증하면 다음과 같이 표시됩니다:
+
+
+
+### 자신의 유저 데이터 가져오기 { #get-your-own-user-data }
+
+이제 `/users/me` 경로에 `GET` 작업을 진행합시다.
+
+다음과 같은 사용자 데이터를 얻을 수 있습니다:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false,
+ "hashed_password": "fakehashedsecret"
+}
+```
+
+
+
+잠금 아이콘을 클릭하고 로그아웃한 다음 동일한 작업을 다시 시도하면 다음과 같은 HTTP 401 오류가 발생합니다.
+
+```JSON
+{
+ "detail": "Not authenticated"
+}
+```
+
+### 비활성된 유저 { #inactive-user }
+
+이제 비활성된 사용자로 시도하고, 인증해봅시다:
+
+유저명: `alice`
+
+패스워드: `secret2`
+
+그리고 `/users/me` 경로와 함께 `GET` 작업을 사용해 봅시다.
+
+다음과 같은 "Inactive user" 오류가 발생합니다:
+
+```JSON
+{
+ "detail": "Inactive user"
+}
+```
+
+## 요약 { #recap }
+
+이제 API에 대한 `username` 및 `password`를 기반으로 완전한 보안 시스템을 구현할 수 있는 도구가 있습니다.
+
+이러한 도구를 사용하여 보안 시스템을 모든 데이터베이스 및 모든 사용자 또는 데이터 모델과 호환되도록 만들 수 있습니다.
+
+유일한 오점은 아직 실제로 "안전"하지 않다는 것입니다.
+
+다음 장에서는 안전한 패스워드 해싱 라이브러리와 JWT 토큰을 사용하는 방법을 살펴보겠습니다.
diff --git a/docs/ko/docs/tutorial/server-sent-events.md b/docs/ko/docs/tutorial/server-sent-events.md
new file mode 100644
index 0000000000000..a8ae1180faae9
--- /dev/null
+++ b/docs/ko/docs/tutorial/server-sent-events.md
@@ -0,0 +1,120 @@
+# 서버 전송 이벤트(SSE) { #server-sent-events-sse }
+
+브라우저 클라이언트로 데이터를 스트리밍하려면 **Server-Sent Events**(SSE)를 사용할 수 있습니다.
+
+이는 [JSON Lines 스트리밍](stream-json-lines.md)과 비슷하지만, 브라우저가 기본적으로 [`EventSource` API](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)를 통해 지원하는 `text/event-stream` 형식을 사용합니다.
+
+/// info | 정보
+
+FastAPI 0.135.0에 추가되었습니다.
+
+///
+
+## Server-Sent Events란 { #what-are-server-sent-events }
+
+SSE는 서버에서 클라이언트로 HTTP를 통해 데이터를 스트리밍하기 위한 표준입니다.
+
+각 이벤트는 `data`, `event`, `id`, `retry`와 같은 "필드"를 가진 작은 텍스트 블록이며, 빈 줄로 구분됩니다.
+
+다음과 같습니다:
+
+```
+data: {"name": "Portal Gun", "price": 999.99}
+
+data: {"name": "Plumbus", "price": 32.99}
+
+```
+
+SSE는 AI 채팅 스트리밍, 실시간 알림, 로그와 관측성, 그리고 서버가 클라이언트로 업데이트를 푸시하는 여러 경우에 흔히 사용됩니다.
+
+/// tip | 팁
+
+비디오나 오디오처럼 바이너리 데이터를 스트리밍하려면 고급 가이드: [데이터 스트리밍](../advanced/stream-data.md)을 확인하세요.
+
+///
+
+## FastAPI로 SSE 스트리밍 { #stream-sse-with-fastapi }
+
+FastAPI에서 SSE를 스트리밍하려면, 경로 처리 함수에서 `yield`를 사용하고 `response_class=EventSourceResponse`를 설정하세요.
+
+`EventSourceResponse`는 `fastapi.sse`에서 임포트합니다:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[4,22] *}
+
+각 `yield`된 항목은 JSON으로 인코딩되어 SSE 이벤트의 `data:` 필드로 전송됩니다.
+
+반환 타입을 `AsyncIterable[Item]`으로 선언하면 FastAPI가 이를 사용해 데이터를 Pydantic으로 **검증**, **문서화**, **직렬화**합니다.
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[10:12,23] *}
+
+/// tip | 팁
+
+Pydantic이 **Rust** 쪽에서 직렬화하므로, 반환 타입을 선언하지 않았을 때보다 훨씬 더 높은 **성능**을 얻을 수 있습니다.
+
+///
+
+### 비 async *경로 처리 함수* { #non-async-path-operation-functions }
+
+`async`가 없는 일반 `def` 함수도 사용할 수 있으며, 동일하게 `yield`를 사용할 수 있습니다.
+
+FastAPI가 이벤트 루프를 막지 않도록 올바르게 실행을 보장합니다.
+
+이 경우 함수가 async가 아니므로 적절한 반환 타입은 `Iterable[Item]`입니다:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[28:31] hl[29] *}
+
+### 반환 타입 없음 { #no-return-type }
+
+반환 타입을 생략할 수도 있습니다. FastAPI는 [`jsonable_encoder`](./encoder.md)를 사용해 데이터를 변환하고 전송합니다.
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[34:37] hl[35] *}
+
+## `ServerSentEvent` { #serversentevent }
+
+`event`, `id`, `retry`, `comment` 같은 SSE 필드를 설정해야 한다면, 일반 데이터 대신 `ServerSentEvent` 객체를 `yield`할 수 있습니다.
+
+`ServerSentEvent`는 `fastapi.sse`에서 임포트합니다:
+
+{* ../../docs_src/server_sent_events/tutorial002_py310.py hl[4,26] *}
+
+`data` 필드는 항상 JSON으로 인코딩됩니다. Pydantic 모델을 포함해 JSON으로 직렬화할 수 있는 값을 모두 전달할 수 있습니다.
+
+## 원시 데이터 { #raw-data }
+
+JSON 인코딩 없이 데이터를 보내야 한다면, `data` 대신 `raw_data`를 사용하세요.
+
+미리 포맷된 텍스트, 로그 라인, 또는 `[DONE]`과 같은 특수한 "센티널" 값을 보낼 때 유용합니다.
+
+{* ../../docs_src/server_sent_events/tutorial003_py310.py hl[17] *}
+
+/// note | 참고
+
+`data`와 `raw_data`는 상호 배타적입니다. 각 `ServerSentEvent`에는 이 둘 중 하나만 설정할 수 있습니다.
+
+///
+
+## `Last-Event-ID`로 재개하기 { #resuming-with-last-event-id }
+
+브라우저가 연결이 끊긴 후 재연결할 때, 마지막으로 받은 `id`를 `Last-Event-ID` 헤더에 담아 보냅니다.
+
+헤더 파라미터로 이를 읽어와 클라이언트가 중단한 지점부터 스트림을 재개할 수 있습니다:
+
+{* ../../docs_src/server_sent_events/tutorial004_py310.py hl[25,27,31] *}
+
+## POST로 SSE 사용하기 { #sse-with-post }
+
+SSE는 `GET`뿐만 아니라 **모든 HTTP 메서드**와 함께 동작합니다.
+
+이는 `POST`로 SSE를 스트리밍하는 [MCP](https://modelcontextprotocol.io) 같은 프로토콜에 유용합니다:
+
+{* ../../docs_src/server_sent_events/tutorial005_py310.py hl[14] *}
+
+## 기술 세부사항 { #technical-details }
+
+FastAPI는 일부 SSE 모범 사례를 기본으로 구현합니다.
+
+- 메시지가 없을 때는 15초마다 **"keep alive" `ping` 주석**을 보내 일부 프록시가 연결을 종료하지 않도록 합니다. [HTML 사양: Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes)에서 권장합니다.
+- 스트림이 **캐시되지 않도록** `Cache-Control: no-cache` 헤더를 설정합니다.
+- Nginx 같은 일부 프록시에서 **버퍼링을 방지**하기 위해 특수 헤더 `X-Accel-Buffering: no`를 설정합니다.
+
+여러분이 따로 할 일은 없습니다. 기본값으로 동작합니다. 🤓
diff --git a/docs/ko/docs/tutorial/sql-databases.md b/docs/ko/docs/tutorial/sql-databases.md
new file mode 100644
index 0000000000000..b046d14b530a8
--- /dev/null
+++ b/docs/ko/docs/tutorial/sql-databases.md
@@ -0,0 +1,357 @@
+# SQL (관계형) 데이터베이스 { #sql-relational-databases }
+
+**FastAPI**에서 SQL(관계형) 데이터베이스 사용은 필수가 아닙니다. 하지만 여러분이 원하는 **어떤 데이터베이스든** 사용할 수 있습니다.
+
+여기서는 [SQLModel](https://sqlmodel.tiangolo.com/)을 사용하는 예제를 살펴보겠습니다.
+
+**SQLModel**은 [SQLAlchemy](https://www.sqlalchemy.org/)와 Pydantic을 기반으로 구축되었습니다. **SQL 데이터베이스**를 사용해야 하는 FastAPI 애플리케이션에 완벽히 어울리도록 **FastAPI**와 같은 제작자가 만든 도구입니다.
+
+/// tip | 팁
+
+다른 SQL 또는 NoSQL 데이터베이스 라이브러리를 사용할 수도 있습니다 (일부는 "ORMs"이라고도 불립니다), FastAPI는 특정 라이브러리의 사용을 강요하지 않습니다. 😎
+
+///
+
+SQLModel은 SQLAlchemy를 기반으로 하므로, SQLAlchemy에서 **지원하는 모든 데이터베이스**를 손쉽게 사용할 수 있습니다(이것들은 SQLModel에서도 지원됩니다). 예를 들면:
+
+* PostgreSQL
+* MySQL
+* SQLite
+* Oracle
+* Microsoft SQL Server 등.
+
+이 예제에서는 **SQLite**를 사용합니다. SQLite는 단일 파일을 사용하고 Python에서 통합 지원하기 때문입니다. 따라서 이 예제를 그대로 복사하여 실행할 수 있습니다.
+
+나중에 프로덕션 애플리케이션에서는 **PostgreSQL**과 같은 데이터베이스 서버를 사용하는 것이 좋습니다.
+
+/// tip | 팁
+
+프론트엔드와 더 많은 도구를 포함하여 **FastAPI**와 **PostgreSQL**을 포함한 공식 프로젝트 생성기가 있습니다: [https://github.com/fastapi/full-stack-fastapi-template](https://github.com/fastapi/full-stack-fastapi-template)
+
+///
+
+이 튜토리얼은 매우 간단하고 짧습니다. 데이터베이스 기본 개념, SQL, 또는 더 고급 기능에 대해 배우고 싶다면, [SQLModel 문서](https://sqlmodel.tiangolo.com/)를 참고하세요.
+
+## `SQLModel` 설치하기 { #install-sqlmodel }
+
+먼저, [가상 환경](../virtual-environments.md)을 생성하고 활성화한 다음, `sqlmodel`을 설치하세요:
+
+
+
+- FastAPI to szybki, prosty w nauce i gotowy do użycia w produkcji framework -
- - ---- - -**Dokumentacja**: https://fastapi.tiangolo.com - -**Kod żródłowy**: https://github.com/tiangolo/fastapi - ---- - -FastAPI to nowoczesny, wydajny framework webowy do budowania API z użyciem Pythona 3.6+ bazujący na standardowym typowaniu Pythona. - -Kluczowe cechy: - -* **Wydajność**: FastAPI jest bardzo wydajny, na równi z **NodeJS** oraz **Go** (dzięki Starlette i Pydantic). [Jeden z najszybszych dostępnych frameworków Pythonowych](#wydajnosc). -* **Szybkość kodowania**: Przyśpiesza szybkość pisania nowych funkcjonalności o około 200% do 300%. * -* **Mniejsza ilość błędów**: Zmniejsza ilość ludzkich (dewelopera) błędy o około 40%. * -* **Intuicyjność**: Wspaniałe wsparcie dla edytorów kodu. Dostępne wszędzie automatyczne uzupełnianie kodu. Krótszy czas debugowania. -* **Łatwość**: Zaprojektowany by być prosty i łatwy do nauczenia. Mniej czasu spędzonego na czytanie dokumentacji. -* **Kompaktowość**: Minimalizacja powtarzającego się kodu. Wiele funkcjonalności dla każdej deklaracji parametru. Mniej błędów. -* **Solidność**: Kod gotowy dla środowiska produkcyjnego. Wraz z automatyczną interaktywną dokumentacją. -* **Bazujący na standardach**: Oparty na (i w pełni kompatybilny z) otwartych standardach API: OpenAPI (wcześniej znane jako Swagger) oraz JSON Schema. - -* oszacowania bazowane na testach wykonanych przez wewnętrzny zespół deweloperów, budujących aplikacie używane na środowisku produkcyjnym. - -## Sponsorzy - - - -{% if sponsors %} -{% for sponsor in sponsors.gold -%} -async def...uvicorn main:app --reload...email_validator - dla walidacji adresów email.
-
-Używane przez Starlette:
-
-* httpx - Wymagane jeżeli chcesz korzystać z `TestClient`.
-* aiofiles - Wymagane jeżeli chcesz korzystać z `FileResponse` albo `StaticFiles`.
-* jinja2 - Wymagane jeżeli chcesz używać domyślnej konfiguracji szablonów.
-* python-multipart - Wymagane jeżelich chcesz wsparcie "parsowania" formularzy, używając `request.form()`.
-* itsdangerous - Wymagany dla wsparcia `SessionMiddleware`.
-* pyyaml - Wymagane dla wsparcia `SchemaGenerator` z Starlette (z FastAPI prawdopodobnie tego nie potrzebujesz).
-* graphene - Wymagane dla wsparcia `GraphQLApp`.
-* ujson - Wymagane jeżeli chcesz korzystać z `UJSONResponse`.
-
-Używane przez FastAPI / Starlette:
-
-* uvicorn - jako serwer, który ładuje i obsługuje Twoją aplikację.
-* orjson - Wymagane jeżeli chcesz używać `ORJSONResponse`.
-
-Możesz zainstalować wszystkie te aplikacje przy pomocy `pip install fastapi[all]`.
-
-## Licencja
-
-Ten projekt jest na licencji MIT.
diff --git a/docs/pl/docs/tutorial/first-steps.md b/docs/pl/docs/tutorial/first-steps.md
deleted file mode 100644
index 9406d703d59cb..0000000000000
--- a/docs/pl/docs/tutorial/first-steps.md
+++ /dev/null
@@ -1,334 +0,0 @@
-# Pierwsze kroki
-
-Najprostszy plik FastAPI może wyglądać tak:
-
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
-
-Skopiuj to do pliku `main.py`.
-
-Uruchom serwer:
-
-get
-
-!!! info "`@decorator` Info"
- Składnia `@something` jest w Pythonie nazywana "dekoratorem".
-
- Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa).
-
- "Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi.
-
- W naszym przypadku dekorator mówi **FastAPI**, że poniższa funkcja odpowiada **ścieżce** `/` z **operacją** `get`.
-
- Jest to "**dekorator operacji na ścieżce**".
-
-Możesz również użyć innej operacji:
-
-* `@app.post()`
-* `@app.put()`
-* `@app.delete()`
-
-Oraz tych bardziej egzotycznych:
-
-* `@app.options()`
-* `@app.head()`
-* `@app.patch()`
-* `@app.trace()`
-
-!!! tip
- Możesz dowolnie używać każdej operacji (metody HTTP).
-
- **FastAPI** nie narzuca żadnego konkretnego znaczenia.
-
- Informacje tutaj są przedstawione jako wskazówka, a nie wymóg.
-
- Na przykład, używając GraphQL, normalnie wykonujesz wszystkie akcje używając tylko operacji `POST`.
-
-### Krok 4: zdefiniuj **funkcję obsługującą ścieżkę**
-
-To jest nasza "**funkcja obsługująca ścieżkę**":
-
-* **ścieżka**: to `/`.
-* **operacja**: to `get`.
-* **funkcja**: to funkcja poniżej "dekoratora" (poniżej `@app.get("/")`).
-
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
-
-Jest to funkcja Python.
-
-Zostanie ona wywołana przez **FastAPI** za każdym razem, gdy otrzyma żądanie do adresu URL "`/`" przy użyciu operacji `GET`.
-
-W tym przypadku jest to funkcja "asynchroniczna".
-
----
-
-Możesz również zdefiniować to jako normalną funkcję zamiast `async def`:
-
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
-
-!!! note
- Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](/async/#in-a-hurry){.internal-link target=_blank}.
-
-### Krok 5: zwróć zawartość
-
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
-
-Możesz zwrócić `dict`, `list`, pojedynczą wartość jako `str`, `int`, itp.
-
-Możesz również zwrócić modele Pydantic (więcej o tym później).
-
-Istnieje wiele innych obiektów i modeli, które zostaną automatycznie skonwertowane do formatu JSON (w tym ORM itp.). Spróbuj użyć swoich ulubionych, jest bardzo prawdopodobne, że są już obsługiwane.
-
-## Podsumowanie
-
-* Zaimportuj `FastAPI`.
-* Stwórz instancję `app`.
-* Dodaj **dekorator operacji na ścieżce** (taki jak `@app.get("/")`).
-* Napisz **funkcję obsługującą ścieżkę** (taką jak `def root(): ...` powyżej).
-* Uruchom serwer deweloperski (`uvicorn main:app --reload`).
diff --git a/docs/pl/docs/tutorial/index.md b/docs/pl/docs/tutorial/index.md
deleted file mode 100644
index f8c5c602273f1..0000000000000
--- a/docs/pl/docs/tutorial/index.md
+++ /dev/null
@@ -1,80 +0,0 @@
-# Samouczek
-
-Ten samouczek pokaże Ci, krok po kroku, jak używać większości funkcji **FastAPI**.
-
-Każda część korzysta z poprzednich, ale jest jednocześnie osobnym tematem. Możesz przejść bezpośrednio do każdego rozdziału, jeśli szukasz rozwiązania konkretnego problemu.
-
-Samouczek jest tak zbudowany, żeby służył jako punkt odniesienia w przyszłości.
-
-Możesz wracać i sprawdzać dokładnie to czego potrzebujesz.
-
-## Wykonywanie kodu
-
-Wszystkie fragmenty kodu mogą być skopiowane bezpośrednio i użyte (są poprawnymi i przetestowanymi plikami).
-
-Żeby wykonać każdy przykład skopiuj kod to pliku `main.py` i uruchom `uvicorn` za pomocą:
-
-lt
+* XWT
+* PSGI
+
+### O abbr fornece uma frase completa e uma explicação { #the-abbr-gives-a-full-phrase-and-an-explanation }
+
+* MDN
+* I/O.
+
+////
+
+//// tab | Informação
+
+Os atributos "title" dos elementos "abbr" são traduzidos seguindo algumas instruções específicas.
+
+As traduções podem adicionar seus próprios elementos "abbr" que o LLM não deve remover. Por exemplo, para explicar palavras em inglês.
+
+Veja a seção `### HTML abbr elements` no prompt geral em `scripts/translate.py`.
+
+////
+
+## Elementos HTML "dfn" { #html-dfn-elements }
+
+* cluster
+* Deep Learning
+
+## Títulos { #headings }
+
+//// tab | Teste
+
+### Desenvolver uma webapp - um tutorial { #develop-a-webapp-a-tutorial }
+
+Olá.
+
+### Anotações de tipo e -anotações { #type-hints-and-annotations }
+
+Olá novamente.
+
+### Super- e subclasses { #super-and-subclasses }
+
+Olá novamente.
+
+////
+
+//// tab | Informação
+
+A única regra rígida para títulos é que o LLM deixe a parte do hash dentro de chaves inalterada, o que garante que os links não quebrem.
+
+Veja a seção `### Headings` no prompt geral em `scripts/translate.py`.
+
+Para algumas instruções específicas do idioma, veja, por exemplo, a seção `### Headings` em `docs/de/llm-prompt.md`.
+
+////
+
+## Termos usados na documentação { #terms-used-in-the-docs }
+
+//// tab | Teste
+
+* você
+* seu
+
+* por exemplo
+* etc.
+
+* `foo` como um `int`
+* `bar` como uma `str`
+* `baz` como uma `list`
+
+* o Tutorial - Guia do Usuário
+* o Guia do Usuário Avançado
+* a documentação do SQLModel
+* a documentação da API
+* a documentação automática
+
+* Ciência de Dados
+* Deep Learning
+* Aprendizado de Máquina
+* Injeção de Dependências
+* autenticação HTTP Basic
+* HTTP Digest
+* formato ISO
+* o padrão JSON Schema
+* o JSON schema
+* a definição do schema
+* Fluxo de Senha
+* Mobile
+
+* descontinuado
+* projetado
+* inválido
+* dinamicamente
+* padrão
+* padrão predefinido
+* sensível a maiúsculas e minúsculas
+* não sensível a maiúsculas e minúsculas
+
+* servir a aplicação
+* servir a página
+
+* o app
+* a aplicação
+
+* a requisição
+* a resposta
+* a resposta de erro
+
+* a operação de rota
+* o decorador de operação de rota
+* a função de operação de rota
+
+* o corpo
+* o corpo da requisição
+* o corpo da resposta
+* o corpo JSON
+* o corpo do formulário
+* o corpo do arquivo
+* o corpo da função
+
+* o parâmetro
+* o parâmetro de corpo
+* o parâmetro de path
+* o parâmetro de query
+* o parâmetro de cookie
+* o parâmetro de header
+* o parâmetro de formulário
+* o parâmetro da função
+
+* o evento
+* o evento de inicialização
+* a inicialização do servidor
+* o evento de encerramento
+* o evento de lifespan
+
+* o manipulador
+* o manipulador de eventos
+* o manipulador de exceções
+* tratar
+
+* o modelo
+* o modelo Pydantic
+* o modelo de dados
+* o modelo de banco de dados
+* o modelo de formulário
+* o objeto de modelo
+
+* a classe
+* a classe base
+* a classe pai
+* a subclasse
+* a classe filha
+* a classe irmã
+* o método de classe
+
+* o cabeçalho
+* os cabeçalhos
+* o cabeçalho de autorização
+* o cabeçalho `Authorization`
+* o cabeçalho encaminhado
+
+* o sistema de injeção de dependências
+* a dependência
+* o dependable
+* o dependant
+
+* limitado por I/O
+* limitado por CPU
+* concorrência
+* paralelismo
+* multiprocessamento
+
+* a env var
+* a variável de ambiente
+* o `PATH`
+* a variável `PATH`
+
+* a autenticação
+* o provedor de autenticação
+* a autorização
+* o formulário de autorização
+* o provedor de autorização
+* o usuário se autentica
+* o sistema autentica o usuário
+
+* a CLI
+* a interface de linha de comando
+
+* o servidor
+* o cliente
+
+* o provedor de nuvem
+* o serviço de nuvem
+
+* o desenvolvimento
+* as etapas de desenvolvimento
+
+* o dict
+* o dicionário
+* a enumeração
+* o enum
+* o membro do enum
+
+* o codificador
+* o decodificador
+* codificar
+* decodificar
+
+* a exceção
+* lançar
+
+* a expressão
+* a instrução
+
+* o frontend
+* o backend
+
+* a discussão do GitHub
+* a issue do GitHub
+
+* o desempenho
+* a otimização de desempenho
+
+* o tipo de retorno
+* o valor de retorno
+
+* a segurança
+* o esquema de segurança
+
+* a tarefa
+* a tarefa em segundo plano
+* a função da tarefa
+
+* o template
+* o mecanismo de template
+
+* a anotação de tipo
+* a anotação de tipo
+
+* o worker de servidor
+* o worker do Uvicorn
+* o Worker do Gunicorn
+* o processo worker
+* a classe de worker
+* a carga de trabalho
+
+* a implantação
+* implantar
+
+* o SDK
+* o kit de desenvolvimento de software
+
+* o `APIRouter`
+* o `requirements.txt`
+* o Bearer Token
+* a alteração com quebra de compatibilidade
+* o bug
+* o botão
+* o chamável
+* o código
+* o commit
+* o gerenciador de contexto
+* a corrotina
+* a sessão do banco de dados
+* o disco
+* o domínio
+* o mecanismo
+* o X falso
+* o método HTTP GET
+* o item
+* a biblioteca
+* o lifespan
+* o bloqueio
+* o middleware
+* a aplicação mobile
+* o módulo
+* a montagem
+* a rede
+* a origem
+* a sobrescrita
+* a carga útil
+* o processador
+* a propriedade
+* o proxy
+* o pull request
+* a consulta
+* a RAM
+* a máquina remota
+* o código de status
+* a string
+* a tag
+* o framework web
+* o curinga
+* retornar
+* validar
+
+////
+
+//// tab | Informação
+
+Esta é uma lista não completa e não normativa de termos (principalmente) técnicos vistos na documentação. Pode ser útil para o designer do prompt descobrir para quais termos o LLM precisa de uma ajudinha. Por exemplo, quando ele continua revertendo uma boa tradução para uma tradução subótima. Ou quando tem problemas para conjugar/declinar um termo no seu idioma.
+
+Veja, por exemplo, a seção `### List of English terms and their preferred German translations` em `docs/de/llm-prompt.md`.
+
+////
diff --git a/docs/pt/docs/about/index.md b/docs/pt/docs/about/index.md
new file mode 100644
index 0000000000000..39e160741beae
--- /dev/null
+++ b/docs/pt/docs/about/index.md
@@ -0,0 +1,3 @@
+# Sobre { #about }
+
+Sobre o FastAPI, seu design, inspiração e mais. 🤓
diff --git a/docs/pt/docs/advanced/additional-responses.md b/docs/pt/docs/advanced/additional-responses.md
new file mode 100644
index 0000000000000..1df4b98519799
--- /dev/null
+++ b/docs/pt/docs/advanced/additional-responses.md
@@ -0,0 +1,247 @@
+# Retornos Adicionais no OpenAPI { #additional-responses-in-openapi }
+
+/// warning | Atenção
+
+Este é um tema bem avançado.
+
+Se você está começando com o **FastAPI**, provavelmente você não precisa disso.
+
+///
+
+Você pode declarar retornos adicionais, com códigos de status adicionais, media types, descrições, etc.
+
+Essas respostas adicionais serão incluídas no esquema do OpenAPI, e também aparecerão na documentação da API.
+
+Porém para as respostas adicionais, você deve garantir que está retornando um `Response` como por exemplo o `JSONResponse` diretamente, junto com o código de status e o conteúdo.
+
+## Retorno Adicional com `model` { #additional-response-with-model }
+
+Você pode fornecer o parâmetro `responses` aos seus *decoradores de caminho*.
+
+Este parâmetro recebe um `dict`, as chaves são os códigos de status para cada retorno, como por exemplo `200`, e os valores são um outro `dict` com a informação de cada um deles.
+
+Cada um desses `dict` de retorno pode ter uma chave `model`, contendo um modelo do Pydantic, assim como o `response_model`.
+
+O **FastAPI** pegará este modelo, gerará o esquema JSON dele e incluirá no local correto do OpenAPI.
+
+Por exemplo, para declarar um outro retorno com o status code `404` e um modelo do Pydantic chamado `Message`, você pode escrever:
+
+{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}
+
+/// note | Nota
+
+Lembre-se que você deve retornar o `JSONResponse` diretamente.
+
+///
+
+/// info | Informação
+
+A chave `model` não é parte do OpenAPI.
+
+O **FastAPI** pegará o modelo do Pydantic, gerará o `JSON Schema`, e adicionará no local correto.
+
+O local correto é:
+
+* Na chave `content`, que tem como valor um outro objeto JSON (`dict`) que contém:
+ * Uma chave com o media type, como por exemplo `application/json`, que contém como valor um outro objeto JSON, contendo::
+ * Uma chave `schema`, que contém como valor o JSON Schema do modelo, sendo este o local correto.
+ * O **FastAPI** adiciona aqui a referência dos esquemas JSON globais que estão localizados em outro lugar, ao invés de incluí-lo diretamente. Deste modo, outras aplicações e clientes podem utilizar estes esquemas JSON diretamente, fornecer melhores ferramentas de geração de código, etc.
+
+///
+
+O retorno gerado no OpenAPI para esta *operação de rota* será:
+
+```JSON hl_lines="3-12"
+{
+ "responses": {
+ "404": {
+ "description": "Additional Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Message"
+ }
+ }
+ }
+ },
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+Os esquemas são referenciados em outro local dentro do esquema OpenAPI:
+
+```JSON hl_lines="4-16"
+{
+ "components": {
+ "schemas": {
+ "Message": {
+ "title": "Message",
+ "required": [
+ "message"
+ ],
+ "type": "object",
+ "properties": {
+ "message": {
+ "title": "Message",
+ "type": "string"
+ }
+ }
+ },
+ "Item": {
+ "title": "Item",
+ "required": [
+ "id",
+ "value"
+ ],
+ "type": "object",
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
+ },
+ "value": {
+ "title": "Value",
+ "type": "string"
+ }
+ }
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": [
+ "loc",
+ "msg",
+ "type"
+ ],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string"
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string"
+ }
+ }
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+## Media types adicionais para o retorno principal { #additional-media-types-for-the-main-response }
+
+Você pode utilizar o mesmo parâmetro `responses` para adicionar diferentes media types para o mesmo retorno principal.
+
+Por exemplo, você pode adicionar um media type adicional de `image/png`, declarando que a sua *operação de rota* pode retornar um objeto JSON (com o media type `application/json`) ou uma imagem PNG:
+
+{* ../../docs_src/additional_responses/tutorial002_py310.py hl[17:22,26] *}
+
+/// note | Nota
+
+Note que você deve retornar a imagem utilizando um `FileResponse` diretamente.
+
+///
+
+/// info | Informação
+
+A menos que você especifique um media type diferente explicitamente em seu parâmetro `responses`, o FastAPI assumirá que o retorno possui o mesmo media type contido na classe principal de retorno (padrão `application/json`).
+
+Porém se você especificou uma classe de retorno com o valor `None` como media type, o FastAPI utilizará `application/json` para qualquer retorno adicional que possui um modelo associado.
+
+///
+
+## Combinando informações { #combining-information }
+
+Você também pode combinar informações de diferentes lugares, incluindo os parâmetros `response_model`, `status_code`, e `responses`.
+
+Você pode declarar um `response_model`, utilizando o código de status padrão `200` (ou um customizado caso você precise), e depois adicionar informações adicionais para esse mesmo retorno em `responses`, diretamente no esquema OpenAPI.
+
+O **FastAPI** manterá as informações adicionais do `responses`, e combinará com o esquema JSON do seu modelo.
+
+Por exemplo, você pode declarar um retorno com o código de status `404` que utiliza um modelo do Pydantic e tem uma `description` customizada.
+
+E um retorno com o código de status `200` que utiliza o seu `response_model`, porém inclui um `example` customizado:
+
+{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}
+
+Isso será combinado e incluído em seu OpenAPI, e disponibilizado na documentação da sua API:
+
+
+
+## Combinar retornos predefinidos e personalizados { #combine-predefined-responses-and-custom-ones }
+
+Você pode querer possuir alguns retornos predefinidos que são aplicados para diversas *operações de rota*, porém você deseja combinar com retornos personalizados que são necessários para cada *operação de rota*.
+
+Para estes casos, você pode utilizar a técnica do Python de "desempacotamento" de um `dict` utilizando `**dict_to_unpack`:
+
+```Python
+old_dict = {
+ "old key": "old value",
+ "second old key": "second old value",
+}
+new_dict = {**old_dict, "new key": "new value"}
+```
+
+Aqui, o `new_dict` terá todos os pares de chave-valor do `old_dict` mais o novo par de chave-valor:
+
+```Python
+{
+ "old key": "old value",
+ "second old key": "second old value",
+ "new key": "new value",
+}
+```
+
+Você pode utilizar essa técnica para reutilizar alguns retornos predefinidos nas suas *operações de rota* e combiná-las com personalizações adicionais.
+
+Por exemplo:
+
+{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}
+
+## Mais informações sobre retornos OpenAPI { #more-information-about-openapi-responses }
+
+Para verificar exatamente o que você pode incluir nos retornos, você pode conferir estas seções na especificação do OpenAPI:
+
+* [Objeto de Retornos do OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responses-object), inclui o `Response Object`.
+* [Objeto de Retorno do OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#response-object), você pode incluir qualquer coisa dele diretamente em cada retorno dentro do seu parâmetro `responses`. Incluindo `description`, `headers`, `content` (dentro dele que você declara diferentes media types e esquemas JSON), e `links`.
diff --git a/docs/pt/docs/advanced/additional-status-codes.md b/docs/pt/docs/advanced/additional-status-codes.md
new file mode 100644
index 0000000000000..af1cefaf2b6ba
--- /dev/null
+++ b/docs/pt/docs/advanced/additional-status-codes.md
@@ -0,0 +1,41 @@
+# Códigos de status adicionais { #additional-status-codes }
+
+Por padrão, o **FastAPI** retornará as respostas utilizando o `JSONResponse`, adicionando o conteúdo do retorno da sua *operação de rota* dentro do `JSONResponse`.
+
+Ele usará o código de status padrão ou o que você definir na sua *operação de rota*.
+
+## Códigos de status adicionais { #additional-status-codes_1 }
+
+Caso você queira retornar códigos de status adicionais além do código principal, você pode fazer isso retornando um `Response` diretamente, como por exemplo um `JSONResponse`, e definir os códigos de status adicionais diretamente.
+
+Por exemplo, vamos dizer que você deseja ter uma *operação de rota* que permita atualizar itens, e retornar um código de status HTTP 200 "OK" quando for bem sucedido.
+
+Mas você também deseja aceitar novos itens. E quando os itens não existiam, ele os cria, e retorna o código de status HTTP 201 "Created".
+
+Para conseguir isso, importe `JSONResponse` e retorne o seu conteúdo diretamente, definindo o `status_code` que você deseja:
+
+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
+
+/// warning | Atenção
+
+Quando você retorna um `Response` diretamente, como no exemplo acima, ele será retornado diretamente.
+
+Ele não será serializado com um modelo, etc.
+
+Garanta que ele tenha toda informação que você deseja, e que os valores sejam um JSON válido (caso você esteja usando `JSONResponse`).
+
+///
+
+/// note | Detalhes Técnicos
+
+Você também pode utilizar `from starlette.responses import JSONResponse`.
+
+O **FastAPI** disponibiliza o `starlette.responses` como `fastapi.responses` apenas por conveniência para você, o programador. Porém a maioria dos retornos disponíveis vem diretamente do Starlette. O mesmo com `status`.
+
+///
+
+## OpenAPI e documentação da API { #openapi-and-api-docs }
+
+Se você retorna códigos de status adicionais e retornos diretamente, eles não serão incluídos no esquema do OpenAPI (a documentação da API), porque o FastAPI não tem como saber de antemão o que será retornado.
+
+Mas você pode documentar isso no seu código, utilizando: [Retornos Adicionais](additional-responses.md).
diff --git a/docs/pt/docs/advanced/advanced-dependencies.md b/docs/pt/docs/advanced/advanced-dependencies.md
new file mode 100644
index 0000000000000..dbcf99390466a
--- /dev/null
+++ b/docs/pt/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,163 @@
+# Dependências avançadas { #advanced-dependencies }
+
+## Dependências parametrizadas { #parameterized-dependencies }
+
+Todas as dependências que vimos até agora são funções ou classes fixas.
+
+Mas podem ocorrer casos onde você deseja ser capaz de definir parâmetros na dependência, sem ter a necessidade de declarar diversas funções ou classes.
+
+Vamos imaginar que queremos ter uma dependência que verifica se o parâmetro de consulta `q` possui um valor fixo.
+
+Porém nós queremos poder parametrizar o conteúdo fixo.
+
+## Uma instância "chamável" { #a-callable-instance }
+
+Em Python existe uma maneira de fazer com que uma instância de uma classe seja um "chamável".
+
+Não propriamente a classe (que já é um chamável), mas a instância desta classe.
+
+Para fazer isso, nós declaramos o método `__call__`:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}
+
+Neste caso, o `__call__` é o que o **FastAPI** utilizará para verificar parâmetros adicionais e sub dependências, e isso é o que será chamado para passar o valor ao parâmetro na sua *função de operação de rota* posteriormente.
+
+## Parametrizar a instância { #parameterize-the-instance }
+
+E agora, nós podemos utilizar o `__init__` para declarar os parâmetros da instância que podemos utilizar para "parametrizar" a dependência:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}
+
+Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós vamos utilizar diretamente em nosso código.
+
+## Crie uma instância { #create-an-instance }
+
+Nós poderíamos criar uma instância desta classe com:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}
+
+E deste modo nós podemos "parametrizar" a nossa dependência, que agora possui `"bar"` dentro dele, como o atributo `checker.fixed_content`.
+
+## Utilize a instância como dependência { #use-the-instance-as-a-dependency }
+
+Então, nós podemos utilizar este `checker` em um `Depends(checker)`, no lugar de `Depends(FixedContentQueryChecker)`, porque a dependência é a instância, `checker`, e não a própria classe.
+
+E quando a dependência for resolvida, o **FastAPI** chamará este `checker` como:
+
+```Python
+checker(q="somequery")
+```
+
+...e passar o que quer que isso retorne como valor da dependência em nossa *função de operação de rota* como o parâmetro `fixed_content_included`:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}
+
+/// tip | Dica
+
+Tudo isso parece não ser natural. E pode não estar muito claro ou aparentar ser útil ainda.
+
+Estes exemplos são intencionalmente simples, porém mostram como tudo funciona.
+
+Nos capítulos sobre segurança, existem funções utilitárias que são implementadas desta maneira.
+
+Se você entendeu tudo isso, você já sabe como essas funções utilitárias para segurança funcionam por debaixo dos panos.
+
+///
+
+## Dependências com `yield`, `HTTPException`, `except` e Tarefas em Segundo Plano { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+/// warning | Atenção
+
+Muito provavelmente você não precisa desses detalhes técnicos.
+
+Esses detalhes são úteis principalmente se você tinha uma aplicação FastAPI anterior à versão 0.121.0 e está enfrentando problemas com dependências com `yield`.
+
+///
+
+Dependências com `yield` evoluíram ao longo do tempo para contemplar diferentes casos de uso e corrigir alguns problemas, aqui está um resumo do que mudou.
+
+### Dependências com `yield` e `scope` { #dependencies-with-yield-and-scope }
+
+Na versão 0.121.0, o FastAPI adicionou suporte a `Depends(scope="function")` para dependências com `yield`.
+
+Usando `Depends(scope="function")`, o código de saída após o `yield` é executado logo depois que a *função de operação de rota* termina, antes de a response ser enviada de volta ao cliente.
+
+E ao usar `Depends(scope="request")` (o padrão), o código de saída após o `yield` é executado depois que a response é enviada.
+
+Você pode ler mais na documentação em [Dependências com `yield` - Saída antecipada e `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope).
+
+### Dependências com `yield` e `StreamingResponse`, Detalhes Técnicos { #dependencies-with-yield-and-streamingresponse-technical-details }
+
+Antes do FastAPI 0.118.0, se você usasse uma dependência com `yield`, o código de saída (após o `yield`) rodaria depois que a *função de operação de rota* retornasse, mas logo antes de enviar a resposta.
+
+A intenção era evitar manter recursos por mais tempo que o necessário, esperando a resposta percorrer a rede.
+
+Essa mudança também significava que, se você retornasse um `StreamingResponse`, o código de saída da dependência com `yield` já teria sido executado.
+
+Por exemplo, se você tivesse uma sessão de banco de dados em uma dependência com `yield`, o `StreamingResponse` não conseguiria usar essa sessão enquanto transmite dados, porque a sessão já teria sido fechada no código de saída após o `yield`.
+
+Esse comportamento foi revertido na versão 0.118.0, para que o código de saída após o `yield` seja executado depois que a resposta for enviada.
+
+/// info | Informação
+
+Como você verá abaixo, isso é muito semelhante ao comportamento antes da versão 0.106.0, mas com várias melhorias e correções de bugs para casos extremos.
+
+///
+
+#### Casos de uso com código de saída antecipado { #use-cases-with-early-exit-code }
+
+Há alguns casos de uso, com condições específicas, que poderiam se beneficiar do comportamento antigo de executar o código de saída das dependências com `yield` antes de enviar a resposta.
+
+Por exemplo, imagine que você tem código que usa uma sessão de banco de dados em uma dependência com `yield` apenas para verificar um usuário, mas a sessão de banco de dados nunca é usada novamente na *função de operação de rota*, somente na dependência, e a resposta demora a ser enviada, como um `StreamingResponse` que envia dados lentamente, mas por algum motivo não usa o banco de dados.
+
+Nesse caso, a sessão de banco de dados seria mantida até que a resposta termine de ser enviada, mas se você não a usa, então não seria necessário mantê-la.
+
+Veja como poderia ser:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
+
+O código de saída, o fechamento automático da `Session` em:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
+
+...seria executado depois que a resposta terminar de enviar os dados lentos:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
+
+Mas como `generate_stream()` não usa a sessão do banco de dados, não é realmente necessário manter a sessão aberta enquanto envia a resposta.
+
+Se você tiver esse caso específico usando SQLModel (ou SQLAlchemy), você poderia fechar explicitamente a sessão depois que não precisar mais dela:
+
+{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}
+
+Dessa forma a sessão liberaria a conexão com o banco de dados, para que outras requisições pudessem usá-la.
+
+Se você tiver um caso diferente que precise sair antecipadamente de uma dependência com `yield`, por favor crie uma [Pergunta no GitHub Discussions](https://github.com/fastapi/fastapi/discussions/new?category=questions) com o seu caso específico e por que você se beneficiaria de ter o fechamento antecipado para dependências com `yield`.
+
+Se houver casos de uso convincentes para fechamento antecipado em dependências com `yield`, considerarei adicionar uma nova forma de optar por esse fechamento antecipado.
+
+### Dependências com `yield` e `except`, Detalhes Técnicos { #dependencies-with-yield-and-except-technical-details }
+
+Antes do FastAPI 0.110.0, se você usasse uma dependência com `yield`, e então capturasse uma exceção com `except` nessa dependência, e você não relançasse a exceção, a exceção seria automaticamente levantada/encaminhada para quaisquer tratadores de exceção ou para o tratador de erro interno do servidor.
+
+Isso foi alterado na versão 0.110.0 para corrigir consumo de memória não tratado decorrente de exceções encaminhadas sem um tratador (erros internos do servidor), e para torná-lo consistente com o comportamento do código Python regular.
+
+### Tarefas em Segundo Plano e Dependências com `yield`, Detalhes Técnicos { #background-tasks-and-dependencies-with-yield-technical-details }
+
+Antes do FastAPI 0.106.0, lançar exceções após o `yield` não era possível, o código de saída em dependências com `yield` era executado depois que a resposta era enviada, então [Tratadores de Exceções](../tutorial/handling-errors.md#install-custom-exception-handlers) já teriam sido executados.
+
+Isso foi projetado assim principalmente para permitir o uso dos mesmos objetos "yielded" por dependências dentro de tarefas em segundo plano, porque o código de saída seria executado depois que as tarefas em segundo plano fossem concluídas.
+
+Isso foi alterado no FastAPI 0.106.0 com a intenção de não manter recursos enquanto se espera a response percorrer a rede.
+
+/// tip | Dica
+
+Além disso, uma tarefa em segundo plano normalmente é um conjunto de lógica independente que deve ser tratado separadamente, com seus próprios recursos (por exemplo, sua própria conexão de banco de dados).
+
+Assim, desta forma você provavelmente terá um código mais limpo.
+
+///
+
+Se você costumava depender desse comportamento, agora você deve criar os recursos para tarefas em segundo plano dentro da própria tarefa em segundo plano, e usar internamente apenas dados que não dependam dos recursos de dependências com `yield`.
+
+Por exemplo, em vez de usar a mesma sessão de banco de dados, você criaria uma nova sessão de banco de dados dentro da tarefa em segundo plano, e obteria os objetos do banco de dados usando essa nova sessão. E então, em vez de passar o objeto do banco de dados como parâmetro para a função da tarefa em segundo plano, você passaria o ID desse objeto e então obteria o objeto novamente dentro da função da tarefa em segundo plano.
diff --git a/docs/pt/docs/advanced/advanced-python-types.md b/docs/pt/docs/advanced/advanced-python-types.md
new file mode 100644
index 0000000000000..f92a20bd46d95
--- /dev/null
+++ b/docs/pt/docs/advanced/advanced-python-types.md
@@ -0,0 +1,61 @@
+# Tipos Avançados de Python { #advanced-python-types }
+
+Aqui estão algumas ideias adicionais que podem ser úteis ao trabalhar com tipos em Python.
+
+## Usando `Union` ou `Optional` { #using-union-or-optional }
+
+Se, por algum motivo, seu código não puder usar `|`, por exemplo, se não for em uma anotação de tipo, mas em algo como `response_model=`, em vez de usar a barra vertical (`|`) você pode usar `Union` do `typing`.
+
+Por exemplo, você poderia declarar que algo pode ser `str` ou `None`:
+
+```python
+from typing import Union
+
+
+def say_hi(name: Union[str, None]):
+ print(f"Hi {name}!")
+```
+
+O `typing` também tem um atalho para declarar que algo pode ser `None`, com `Optional`.
+
+Aqui vai uma dica do meu ponto de vista bem subjetivo:
+
+* 🚨 Evite usar `Optional[SomeType]`
+* Em vez disso ✨ use **`Union[SomeType, None]`** ✨.
+
+Ambos são equivalentes e, por baixo, são a mesma coisa, mas eu recomendaria `Union` em vez de `Optional` porque a palavra "opcional" sugere que o valor é opcional; na verdade, significa "pode ser `None`", mesmo quando não é opcional e continua sendo obrigatório.
+
+Acho que `Union[SomeType, None]` é mais explícito quanto ao significado.
+
+É apenas uma questão de palavras e nomes. Mas essas palavras podem influenciar como você e sua equipe pensam sobre o código.
+
+Como exemplo, veja esta função:
+
+```python
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+ print(f"Hey {name}!")
+```
+
+O parâmetro `name` é definido como `Optional[str]`, mas não é opcional; não é possível chamar a função sem o parâmetro:
+
+```Python
+say_hi() # Ah, não, isso gera um erro! 😱
+```
+
+O parâmetro `name` continua obrigatório (não é opcional) porque não tem valor padrão. Ainda assim, `name` aceita `None` como valor:
+
+```Python
+say_hi(name=None) # Isso funciona, None é válido 🎉
+```
+
+A boa notícia é que, na maioria dos casos, você poderá simplesmente usar `|` para definir uniões de tipos:
+
+```python
+def say_hi(name: str | None):
+ print(f"Hey {name}!")
+```
+
+Então, normalmente você não precisa se preocupar com nomes como `Optional` e `Union`. 😎
diff --git a/docs/pt/docs/advanced/async-tests.md b/docs/pt/docs/advanced/async-tests.md
new file mode 100644
index 0000000000000..9dfadc32a1133
--- /dev/null
+++ b/docs/pt/docs/advanced/async-tests.md
@@ -0,0 +1,99 @@
+# Testes Assíncronos { #async-tests }
+
+Você já viu como testar as suas aplicações **FastAPI** utilizando o `TestClient` que é fornecido. Até agora, você viu apenas como escrever testes síncronos, sem utilizar funções `async`.
+
+Ser capaz de utilizar funções assíncronas em seus testes pode ser útil, por exemplo, quando você está realizando uma consulta em seu banco de dados de maneira assíncrona. Imagine que você deseja testar realizando requisições para a sua aplicação FastAPI e depois verificar que a sua aplicação inseriu corretamente as informações no banco de dados, ao utilizar uma biblioteca assíncrona para banco de dados.
+
+Vamos ver como nós podemos fazer isso funcionar.
+
+## pytest.mark.anyio { #pytest-mark-anyio }
+
+Se quisermos chamar funções assíncronas em nossos testes, as nossas funções de teste precisam ser assíncronas. O AnyIO oferece um plugin bem legal para isso, que nos permite especificar que algumas das nossas funções de teste precisam ser chamadas de forma assíncrona.
+
+## HTTPX { #httpx }
+
+Mesmo que a sua aplicação **FastAPI** utilize funções normais com `def` no lugar de `async def`, ela ainda é uma aplicação `async` por baixo dos panos.
+
+O `TestClient` faz algumas mágicas para invocar a aplicação FastAPI assíncrona em suas funções `def` normais, utilizando o pytest padrão. Porém a mágica não acontece mais quando nós estamos utilizando dentro de funções assíncronas. Ao executar os nossos testes de forma assíncrona, nós não podemos mais utilizar o `TestClient` dentro das nossas funções de teste.
+
+O `TestClient` é baseado no [HTTPX](https://www.python-httpx.org), e felizmente nós podemos utilizá-lo diretamente para testar a API.
+
+## Exemplo { #example }
+
+Para um exemplos simples, vamos considerar uma estrutura de arquivos semelhante ao descrito em [Aplicações Maiores](../tutorial/bigger-applications.md) e [Testes](../tutorial/testing.md):
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+O arquivo `main.py` teria:
+
+{* ../../docs_src/async_tests/app_a_py310/main.py *}
+
+O arquivo `test_main.py` teria os testes para para o arquivo `main.py`, ele poderia ficar assim:
+
+{* ../../docs_src/async_tests/app_a_py310/test_main.py *}
+
+## Executá-lo { #run-it }
+
+Você pode executar os seus testes normalmente via:
+
+
+
+Mas se acessarmos a interface de documentação no URL "oficial" usando o proxy com a porta `9999`, em `/api/v1/docs`, ela funciona corretamente! 🎉
+
+Você pode verificar em [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs):
+
+
+
+Exatamente como queríamos. ✔️
+
+Isso porque o FastAPI usa esse `root_path` para criar o `server` padrão no OpenAPI com o URL fornecido pelo `root_path`.
+
+## Servidores adicionais { #additional-servers }
+
+/// warning | Atenção
+
+Este é um caso de uso mais avançado. Sinta-se à vontade para pular.
+
+///
+
+Por padrão, o **FastAPI** criará um `server` no OpenAPI schema com o URL para o `root_path`.
+
+Mas você também pode fornecer outros `servers` alternativos, por exemplo, se quiser que a mesma interface de documentação interaja com ambientes de staging e produção.
+
+Se você passar uma lista personalizada de `servers` e houver um `root_path` (porque sua API está atrás de um proxy), o **FastAPI** inserirá um "server" com esse `root_path` no início da lista.
+
+Por exemplo:
+
+{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}
+
+Gerará um OpenAPI schema como:
+
+```JSON hl_lines="5-7"
+{
+ "openapi": "3.1.0",
+ // Mais coisas aqui
+ "servers": [
+ {
+ "url": "/api/v1"
+ },
+ {
+ "url": "https://stag.example.com",
+ "description": "Staging environment"
+ },
+ {
+ "url": "https://prod.example.com",
+ "description": "Production environment"
+ }
+ ],
+ "paths": {
+ // Mais coisas aqui
+ }
+}
+```
+
+/// tip | Dica
+
+Perceba o servidor gerado automaticamente com um valor `url` de `/api/v1`, retirado do `root_path`.
+
+///
+
+Na interface de documentação em [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs) parecerá:
+
+
+
+/// tip | Dica
+
+A interface de documentação interagirá com o servidor que você selecionar.
+
+///
+
+/// note | Detalhes Técnicos
+
+A propriedade `servers` na especificação OpenAPI é opcional.
+
+Se você não especificar o parâmetro `servers` e `root_path` for igual a `/`, a propriedade `servers` no OpenAPI gerado será totalmente omitida por padrão, o que equivale a um único servidor com valor de `url` igual a `/`.
+
+///
+
+### Desabilitar servidor automático de `root_path` { #disable-automatic-server-from-root-path }
+
+Se você não quiser que o **FastAPI** inclua um servidor automático usando o `root_path`, você pode usar o parâmetro `root_path_in_servers=False`:
+
+{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}
+
+e então ele não será incluído no OpenAPI schema.
+
+## Montando uma sub-aplicação { #mounting-a-sub-application }
+
+Se você precisar montar uma sub-aplicação (como descrito em [Sub-aplicações - Montagens](sub-applications.md)) enquanto também usa um proxy com `root_path`, você pode fazer isso normalmente, como esperaria.
+
+O FastAPI usará internamente o `root_path` de forma inteligente, então tudo funcionará. ✨
diff --git a/docs/pt/docs/advanced/custom-response.md b/docs/pt/docs/advanced/custom-response.md
new file mode 100644
index 0000000000000..a360bd3c9b8bb
--- /dev/null
+++ b/docs/pt/docs/advanced/custom-response.md
@@ -0,0 +1,272 @@
+# Resposta Personalizada - HTML, Stream, File e outras { #custom-response-html-stream-file-others }
+
+Por padrão, o **FastAPI** retornará respostas JSON.
+
+Você pode sobrescrever isso retornando uma `Response` diretamente, como visto em [Retornando uma Resposta Diretamente](response-directly.md).
+
+Mas se você retornar uma `Response` diretamente (ou qualquer subclasse, como `JSONResponse`), os dados não serão convertidos automaticamente (mesmo que você declare um `response_model`), e a documentação não será gerada automaticamente (por exemplo, incluindo o "media type" específico, no cabeçalho HTTP `Content-Type` como parte do OpenAPI gerado).
+
+Mas você também pode declarar a `Response` que deseja utilizar (e.g. qualquer subclasse de `Response`), no *decorador de operação de rota* usando o parâmetro `response_class`.
+
+O conteúdo que você retorna da sua *função de operação de rota* será colocado dentro dessa `Response`.
+
+/// note | Nota
+
+Se você utilizar uma classe de resposta sem media type, o FastAPI esperará que sua resposta não tenha conteúdo, então ele não irá documentar o formato da resposta na documentação OpenAPI gerada.
+
+///
+
+## Respostas JSON { #json-responses }
+
+Por padrão, o FastAPI retorna respostas JSON.
+
+Se você declarar um [Modelo de Resposta](../tutorial/response-model.md), o FastAPI irá usá-lo para serializar os dados para JSON, usando Pydantic.
+
+Se você não declarar um modelo de resposta, o FastAPI usará o `jsonable_encoder` explicado em [Codificador Compatível com JSON](../tutorial/encoder.md) e o colocará em uma `JSONResponse`.
+
+Se você declarar uma `response_class` com um media type JSON (`application/json`), como no caso de `JSONResponse`, os dados que você retorna serão automaticamente convertidos (e filtrados) com qualquer `response_model` do Pydantic que você declarou no *decorador de operação de rota*. Mas os dados não serão serializados para bytes JSON com Pydantic; em vez disso, serão convertidos com o `jsonable_encoder` e então passados para a classe `JSONResponse`, que fará a serialização para bytes usando a biblioteca padrão de JSON do Python.
+
+### Performance com JSON { #json-performance }
+
+Resumindo, se você quer o máximo de performance, use um [Modelo de Resposta](../tutorial/response-model.md) e não declare uma `response_class` no *decorador de operação de rota*.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py ln[15:17] hl[16] *}
+
+## Resposta HTML { #html-response }
+
+Para retornar uma resposta com HTML diretamente do **FastAPI**, utilize `HTMLResponse`.
+
+* Importe `HTMLResponse`.
+* Passe `HTMLResponse` como o parâmetro de `response_class` do seu *decorador de operação de rota*.
+
+{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}
+
+/// info | Informação
+
+O parâmetro `response_class` também será usado para definir o "media type" da resposta.
+
+Neste caso, o cabeçalho HTTP `Content-Type` será definido como `text/html`.
+
+E será documentado como tal no OpenAPI.
+
+///
+
+### Retornando uma `Response` { #return-a-response }
+
+Como visto em [Retornando uma Resposta Diretamente](response-directly.md), você também pode sobrescrever a resposta diretamente na sua *operação de rota*, ao retornar ela.
+
+O mesmo exemplo de antes, retornando uma `HTMLResponse`, poderia parecer com:
+
+{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}
+
+/// warning | Atenção
+
+Uma `Response` retornada diretamente em sua *função de operação de rota* não será documentada no OpenAPI (por exemplo, o `Content-Type` não será documentado) e não será visível na documentação interativa automática.
+
+///
+
+/// info | Informação
+
+Obviamente, o cabeçalho `Content-Type`, o código de status, etc, virão do objeto `Response` que você retornou.
+
+///
+
+### Documentar no OpenAPI e sobrescrever `Response` { #document-in-openapi-and-override-response }
+
+Se você deseja sobrescrever a resposta dentro de uma função, mas ao mesmo tempo documentar o "media type" no OpenAPI, você pode utilizar o parâmetro `response_class` E retornar um objeto `Response`.
+
+A `response_class` será usada apenas para documentar o OpenAPI da *operação de rota*, mas sua `Response` será usada como foi definida.
+
+#### Retornando uma `HTMLResponse` diretamente { #return-an-htmlresponse-directly }
+
+Por exemplo, poderia ser algo como:
+
+{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}
+
+Neste exemplo, a função `generate_html_response()` já cria e retorna uma `Response` em vez de retornar o HTML em uma `str`.
+
+Ao retornar o resultado chamando `generate_html_response()`, você já está retornando uma `Response` que irá sobrescrever o comportamento padrão do **FastAPI**.
+
+Mas como você passou `HTMLResponse` em `response_class` também, o **FastAPI** saberá como documentar isso no OpenAPI e na documentação interativa como um HTML com `text/html`:
+
+
+
+## Respostas disponíveis { #available-responses }
+
+Aqui estão algumas das respostas disponíveis.
+
+Lembre-se que você pode utilizar `Response` para retornar qualquer outra coisa, ou até mesmo criar uma subclasse personalizada.
+
+/// note | Detalhes Técnicos
+
+Você também pode utilizar `from starlette.responses import HTMLResponse`.
+
+O **FastAPI** provê a mesma `starlette.responses` como `fastapi.responses` apenas como uma facilidade para você, desenvolvedor. Mas a maioria das respostas disponíveis vêm diretamente do Starlette.
+
+///
+
+### `Response` { #response }
+
+A classe principal de respostas, todas as outras respostas herdam dela.
+
+Você pode retorná-la diretamente.
+
+Ela aceita os seguintes parâmetros:
+
+* `content` - Uma `str` ou `bytes`.
+* `status_code` - Um código de status HTTP do tipo `int`.
+* `headers` - Um `dict` de strings.
+* `media_type` - Uma `str` informando o media type. E.g. `"text/html"`.
+
+O FastAPI (Starlette, na verdade) irá incluir o cabeçalho Content-Length automaticamente. Ele também irá incluir o cabeçalho Content-Type, baseado no `media_type` e acrescentando uma codificação para tipos textuais.
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+### `HTMLResponse` { #htmlresponse }
+
+Usa algum texto ou sequência de bytes e retorna uma resposta HTML. Como você leu acima.
+
+### `PlainTextResponse` { #plaintextresponse }
+
+Usa algum texto ou sequência de bytes para retornar uma resposta de texto não formatado.
+
+{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}
+
+### `JSONResponse` { #jsonresponse }
+
+Pega alguns dados e retorna uma resposta com codificação `application/json`.
+
+É a resposta padrão utilizada no **FastAPI**, como você leu acima.
+
+/// note | Detalhes Técnicos
+
+Mas se você declarar um modelo de resposta ou tipo de retorno, isso será usado diretamente para serializar os dados para JSON, e uma resposta com o media type correto para JSON será retornada diretamente, sem usar a classe `JSONResponse`.
+
+Esta é a forma ideal para obter a melhor performance.
+
+///
+
+### `RedirectResponse` { #redirectresponse }
+
+Retorna um redirecionamento HTTP. Utiliza o código de status 307 (Redirecionamento Temporário) por padrão.
+
+Você pode retornar uma `RedirectResponse` diretamente:
+
+{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}
+
+---
+
+Ou você pode utilizá-la no parâmetro `response_class`:
+
+{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}
+
+Se você fizer isso, então você pode retornar a URL diretamente da sua *função de operação de rota*.
+
+Neste caso, o `status_code` utilizado será o padrão de `RedirectResponse`, que é `307`.
+
+---
+
+Você também pode utilizar o parâmetro `status_code` combinado com o parâmetro `response_class`:
+
+{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}
+
+### `StreamingResponse` { #streamingresponse }
+
+Recebe um gerador assíncrono ou um gerador/iterador comum (uma função com `yield`) e transmite (stream) o corpo da resposta.
+
+{* ../../docs_src/custom_response/tutorial007_py310.py hl[3,16] *}
+
+/// note | Detalhes Técnicos
+
+Uma tarefa `async` só pode ser cancelada quando alcança um `await`. Se não houver `await`, o gerador (função com `yield`) não pode ser cancelado adequadamente e pode continuar executando mesmo após o cancelamento ser solicitado.
+
+Como este pequeno exemplo não precisa de nenhuma instrução `await`, adicionamos um `await anyio.sleep(0)` para dar ao event loop a chance de lidar com o cancelamento.
+
+Isso seria ainda mais importante com streams grandes ou infinitos.
+
+///
+
+/// tip | Dica
+
+Em vez de retornar uma `StreamingResponse` diretamente, você deveria provavelmente seguir o estilo em [Transmitir Dados](./stream-data.md), é muito mais conveniente e lida com cancelamento nos bastidores para você.
+
+Se você estiver transmitindo JSON Lines, siga o tutorial [Transmitir JSON Lines](../tutorial/stream-json-lines.md).
+
+///
+
+### `FileResponse` { #fileresponse }
+
+Envia um arquivo de forma assíncrona e contínua (stream).
+
+Recebe um conjunto de argumentos do construtor diferente dos outros tipos de resposta:
+
+* `path` - O caminho do arquivo que será transmitido.
+* `headers` - Quaisquer cabeçalhos personalizados a serem incluídos, como um dicionário.
+* `media_type` - Uma string com o media type. Se não for definida, o nome do arquivo ou path será usado para inferir um media type.
+* `filename` - Se definido, será incluído no cabeçalho `Content-Disposition`.
+
+Respostas de arquivos incluirão os cabeçalhos apropriados `Content-Length`, `Last-Modified` e `ETag`.
+
+{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}
+
+Você também pode usar o parâmetro `response_class`:
+
+{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}
+
+Nesse caso, você pode retornar o path do arquivo diretamente da sua *função de operação de rota*.
+
+## Classe de resposta personalizada { #custom-response-class }
+
+Você pode criar sua própria classe de resposta personalizada, herdando de `Response` e usando-a.
+
+Por exemplo, vamos supor que você queira usar [`orjson`](https://github.com/ijl/orjson) com algumas configurações.
+
+Vamos supor que você queira retornar um JSON indentado e formatado, então você quer utilizar a opção `orjson.OPT_INDENT_2` do orjson.
+
+Você poderia criar uma `CustomORJSONResponse`. A principal coisa que você tem que fazer é criar um método `Response.render(content)` que retorne o conteúdo como `bytes`:
+
+{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}
+
+Agora em vez de retornar:
+
+```json
+{"message": "Hello World"}
+```
+
+...essa resposta retornará:
+
+```json
+{
+ "message": "Hello World"
+}
+```
+
+Obviamente, você provavelmente vai encontrar maneiras muito melhores de se aproveitar disso do que a formatação de JSON. 😉
+
+### `orjson` ou Modelo de Resposta { #orjson-or-response-model }
+
+Se o que você procura é performance, provavelmente é melhor usar um [Modelo de Resposta](../tutorial/response-model.md) do que uma resposta com `orjson`.
+
+Com um modelo de resposta, o FastAPI usará o Pydantic para serializar os dados para JSON, sem passos intermediários, como convertê-los com `jsonable_encoder`, o que aconteceria em qualquer outro caso.
+
+E, por baixo dos panos, o Pydantic usa os mesmos mecanismos em Rust que o `orjson` para serializar para JSON, então você já terá a melhor performance com um modelo de resposta.
+
+## Classe de resposta padrão { #default-response-class }
+
+Quando você criar uma instância da classe **FastAPI** ou um `APIRouter` você pode especificar qual classe de resposta utilizar por padrão.
+
+O parâmetro que define isso é o `default_response_class`.
+
+No exemplo abaixo, o **FastAPI** utilizará `HTMLResponse` por padrão, em todas as *operações de rota*, em vez de JSON.
+
+{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}
+
+/// tip | Dica
+
+Você ainda pode substituir `response_class` em *operações de rota* como antes.
+
+///
+
+## Documentação adicional { #additional-documentation }
+
+Você também pode declarar o media type e muitos outros detalhes no OpenAPI utilizando `responses`: [Respostas Adicionais no OpenAPI](additional-responses.md).
diff --git a/docs/pt/docs/advanced/dataclasses.md b/docs/pt/docs/advanced/dataclasses.md
new file mode 100644
index 0000000000000..9a1f212d64873
--- /dev/null
+++ b/docs/pt/docs/advanced/dataclasses.md
@@ -0,0 +1,95 @@
+# Usando Dataclasses { #using-dataclasses }
+
+FastAPI é construído em cima do **Pydantic**, e eu tenho mostrado como usar modelos Pydantic para declarar requisições e respostas.
+
+Mas o FastAPI também suporta o uso de [`dataclasses`](https://docs.python.org/3/library/dataclasses.html) da mesma forma:
+
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
+
+Isso ainda é suportado graças ao **Pydantic**, pois ele tem [suporte interno para `dataclasses`](https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel).
+
+Então, mesmo com o código acima que não usa Pydantic explicitamente, o FastAPI está usando Pydantic para converter essas dataclasses padrão para a versão do Pydantic.
+
+E claro, ele suporta o mesmo:
+
+* validação de dados
+* serialização de dados
+* documentação de dados, etc.
+
+Isso funciona da mesma forma que com os modelos Pydantic. E na verdade é alcançado da mesma maneira por baixo dos panos, usando Pydantic.
+
+/// info | Informação
+
+Lembre-se de que dataclasses não podem fazer tudo o que os modelos Pydantic podem fazer.
+
+Então, você ainda pode precisar usar modelos Pydantic.
+
+Mas se você tem um monte de dataclasses por aí, este é um truque legal para usá-las para alimentar uma API web usando FastAPI. 🤓
+
+///
+
+## Dataclasses em `response_model` { #dataclasses-in-response-model }
+
+Você também pode usar `dataclasses` no parâmetro `response_model`:
+
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
+
+A dataclass será automaticamente convertida para uma dataclass Pydantic.
+
+Dessa forma, seu esquema aparecerá na interface de documentação da API:
+
+
+
+## Dataclasses em Estruturas de Dados Aninhadas { #dataclasses-in-nested-data-structures }
+
+Você também pode combinar `dataclasses` com outras anotações de tipo para criar estruturas de dados aninhadas.
+
+Em alguns casos, você ainda pode ter que usar a versão do Pydantic das `dataclasses`. Por exemplo, se você tiver erros com a documentação da API gerada automaticamente.
+
+Nesse caso, você pode simplesmente trocar as `dataclasses` padrão por `pydantic.dataclasses`, que é um substituto direto:
+
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+
+1. Ainda importamos `field` das `dataclasses` padrão.
+
+2. `pydantic.dataclasses` é um substituto direto para `dataclasses`.
+
+3. A dataclass `Author` inclui uma lista de dataclasses `Item`.
+
+4. A dataclass `Author` é usada como o parâmetro `response_model`.
+
+5. Você pode usar outras anotações de tipo padrão com dataclasses como o corpo da requisição.
+
+ Neste caso, é uma lista de dataclasses `Item`.
+
+6. Aqui estamos retornando um dicionário que contém `items`, que é uma lista de dataclasses.
+
+ O FastAPI ainda é capaz de serializar os dados para JSON.
+
+7. Aqui o `response_model` está usando uma anotação de tipo de uma lista de dataclasses `Author`.
+
+ Novamente, você pode combinar `dataclasses` com anotações de tipo padrão.
+
+8. Note que esta *função de operação de rota* usa `def` regular em vez de `async def`.
+
+ Como sempre, no FastAPI você pode combinar `def` e `async def` conforme necessário.
+
+ Se você precisar de uma atualização sobre quando usar qual, confira a seção _"Com pressa?"_ na documentação sobre [`async` e `await`](../async.md#in-a-hurry).
+
+9. Esta *função de operação de rota* não está retornando dataclasses (embora pudesse), mas uma lista de dicionários com dados internos.
+
+ O FastAPI usará o parâmetro `response_model` (que inclui dataclasses) para converter a resposta.
+
+Você pode combinar `dataclasses` com outras anotações de tipo em muitas combinações diferentes para formar estruturas de dados complexas.
+
+Confira as dicas de anotação no código acima para ver mais detalhes específicos.
+
+## Saiba Mais { #learn-more }
+
+Você também pode combinar `dataclasses` com outros modelos Pydantic, herdar deles, incluí-los em seus próprios modelos, etc.
+
+Para saber mais, confira a [documentação do Pydantic sobre dataclasses](https://docs.pydantic.dev/latest/concepts/dataclasses/).
+
+## Versão { #version }
+
+Isso está disponível desde a versão `0.67.0` do FastAPI. 🔖
diff --git a/docs/pt/docs/advanced/events.md b/docs/pt/docs/advanced/events.md
index 7f6cb6f5d498e..7f15d833e6170 100644
--- a/docs/pt/docs/advanced/events.md
+++ b/docs/pt/docs/advanced/events.md
@@ -1,70 +1,66 @@
-# Eventos de vida útil
+# Eventos de lifespan { #lifespan-events }
-Você pode definir a lógica (código) que poderia ser executada antes da aplicação **inicializar**. Isso significa que esse código será executado **uma vez**, **antes** da aplicação **começar a receber requisições**.
+Você pode definir a lógica (código) que deve ser executada antes da aplicação **inicializar**. Isso significa que esse código será executado **uma vez**, **antes** de a aplicação **começar a receber requisições**.
-Do mesmo modo, você pode definir a lógica (código) que será executada quando a aplicação estiver sendo **encerrada**. Nesse caso, este código será executado **uma vez**, **depois** de ter possivelmente tratado **várias requisições**.
+Da mesma forma, você pode definir a lógica (código) que deve ser executada quando a aplicação estiver **encerrando**. Nesse caso, esse código será executado **uma vez**, **depois** de possivelmente ter tratado **várias requisições**.
-Por conta desse código ser executado antes da aplicação **começar** a receber requisições, e logo após **terminar** de lidar com as requisições, ele cobre toda a **vida útil** (_lifespan_) da aplicação (o termo "vida útil" será importante em um segundo 😉).
+Como esse código é executado antes de a aplicação **começar** a receber requisições e logo depois que ela **termina** de lidar com as requisições, ele cobre todo o **lifespan** da aplicação (a palavra "lifespan" será importante em um segundo 😉).
-Pode ser muito útil para configurar **recursos** que você precisa usar por toda aplicação, e que são **compartilhados** entre as requisições, e/ou que você precisa **limpar** depois. Por exemplo, o pool de uma conexão com o banco de dados ou carregamento de um modelo compartilhado de aprendizado de máquina (_machine learning_).
+Isso pode ser muito útil para configurar **recursos** que você precisa usar por toda a aplicação, e que são **compartilhados** entre as requisições e/ou que você precisa **limpar** depois. Por exemplo, um pool de conexões com o banco de dados ou o carregamento de um modelo de Aprendizado de Máquina compartilhado.
-## Caso de uso
+## Caso de uso { #use-case }
-Vamos iniciar com um exemplo de **caso de uso** e então ver como resolvê-lo com isso.
+Vamos começar com um exemplo de **caso de uso** e então ver como resolvê-lo com isso.
-Vamos imaginar que você tem alguns **modelos de _machine learning_** que deseja usar para lidar com as requisições. 🤖
+Vamos imaginar que você tem alguns **modelos de Aprendizado de Máquina** que deseja usar para lidar com as requisições. 🤖
-Os mesmos modelos são compartilhados entre as requisições, então não é um modelo por requisição, ou um por usuário ou algo parecido.
+Os mesmos modelos são compartilhados entre as requisições, então não é um modelo por requisição, ou um por usuário, ou algo parecido.
-Vamos imaginar que o carregamento do modelo pode **demorar bastante tempo**, porque ele tem que ler muitos **dados do disco**. Então você não quer fazer isso a cada requisição.
+Vamos imaginar que o carregamento do modelo pode **demorar bastante tempo**, porque ele precisa ler muitos **dados do disco**. Então você não quer fazer isso a cada requisição.
-Você poderia carregá-lo no nível mais alto do módulo/arquivo, mas isso também poderia significaria **carregar o modelo** mesmo se você estiver executando um simples teste automatizado, então esse teste poderia ser **lento** porque teria que esperar o carregamento do modelo antes de ser capaz de executar uma parte independente do código.
+Você poderia carregá-lo no nível mais alto do módulo/arquivo, mas isso também significaria **carregar o modelo** mesmo se você estivesse executando um teste automatizado simples; então esse teste poderia ser **lento** porque teria que esperar o carregamento do modelo antes de conseguir executar uma parte independente do código.
+É isso que vamos resolver: vamos carregar o modelo antes de as requisições serem tratadas, mas apenas um pouco antes de a aplicação começar a receber requisições, não enquanto o código estiver sendo carregado.
-Isso é que nós iremos resolver, vamos carregar o modelo antes das requisições serem manuseadas, mas apenas um pouco antes da aplicação começar a receber requisições, não enquanto o código estiver sendo carregado.
+## Lifespan { #lifespan }
-## Vida útil (_Lifespan_)
+Você pode definir essa lógica de *inicialização* e *encerramento* usando o parâmetro `lifespan` da aplicação `FastAPI`, e um "gerenciador de contexto" (vou mostrar o que é isso em um segundo).
-Você pode definir essa lógica de *inicialização* e *encerramento* usando os parâmetros de `lifespan` da aplicação `FastAPI`, e um "gerenciador de contexto" (te mostrarei o que é isso a seguir).
+Vamos começar com um exemplo e depois ver em detalhes.
-Vamos iniciar com um exemplo e ver isso detalhadamente.
+Nós criamos uma função assíncrona `lifespan()` com `yield` assim:
-Nós criamos uma função assíncrona chamada `lifespan()` com `yield` como este:
+{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}
-```Python hl_lines="16 19"
-{!../../../docs_src/events/tutorial003.py!}
-```
+Aqui estamos simulando a operação de *inicialização* custosa de carregar o modelo, colocando a (falsa) função do modelo no dicionário com modelos de Aprendizado de Máquina antes do `yield`. Esse código será executado **antes** de a aplicação **começar a receber requisições**, durante a *inicialização*.
-Aqui nós estamos simulando a *inicialização* custosa do carregamento do modelo colocando a (falsa) função de modelo no dicionário com modelos de _machine learning_ antes do `yield`. Este código será executado **antes** da aplicação **começar a receber requisições**, durante a *inicialização*.
+E então, logo após o `yield`, descarregamos o modelo. Esse código será executado **depois** de a aplicação **terminar de lidar com as requisições**, pouco antes do *encerramento*. Isso poderia, por exemplo, liberar recursos como memória ou uma GPU.
-E então, logo após o `yield`, descarregaremos o modelo. Esse código será executado **após** a aplicação **terminar de lidar com as requisições**, pouco antes do *encerramento*. Isso poderia, por exemplo, liberar recursos como memória ou GPU.
+/// tip | Dica
-!!! tip "Dica"
- O `shutdown` aconteceria quando você estivesse **encerrando** a aplicação.
+O `shutdown` aconteceria quando você estivesse **encerrando** a aplicação.
- Talvez você precise inicializar uma nova versão, ou apenas cansou de executá-la. 🤷
+Talvez você precise iniciar uma nova versão, ou apenas cansou de executá-la. 🤷
-### Função _lifespan_
+///
-A primeira coisa a notar, é que estamos definindo uma função assíncrona com `yield`. Isso é muito semelhante à Dependências com `yield`.
+### Função lifespan { #lifespan-function }
-```Python hl_lines="14-19"
-{!../../../docs_src/events/tutorial003.py!}
-```
+A primeira coisa a notar é que estamos definindo uma função assíncrona com `yield`. Isso é muito semelhante a Dependências com `yield`.
-A primeira parte da função, antes do `yield`, será executada **antes** da aplicação inicializar.
+{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}
-E a parte posterior do `yield` irá executar **após** a aplicação ser encerrada.
+A primeira parte da função, antes do `yield`, será executada **antes** de a aplicação iniciar.
-### Gerenciador de Contexto Assíncrono
+E a parte posterior ao `yield` será executada **depois** de a aplicação ter terminado.
+
+### Gerenciador de contexto assíncrono { #async-context-manager }
Se você verificar, a função está decorada com um `@asynccontextmanager`.
-Que converte a função em algo chamado de "**Gerenciador de Contexto Assíncrono**".
+Isso converte a função em algo chamado "**gerenciador de contexto assíncrono**".
-```Python hl_lines="1 13"
-{!../../../docs_src/events/tutorial003.py!}
-```
+{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}
Um **gerenciador de contexto** em Python é algo que você pode usar em uma declaração `with`, por exemplo, `open()` pode ser usado como um gerenciador de contexto:
@@ -73,91 +69,97 @@ with open("file.txt") as file:
file.read()
```
-Nas versões mais recentes de Python, há também um **gerenciador de contexto assíncrono**. Você o usaria com `async with`:
+Em versões mais recentes do Python, há também um **gerenciador de contexto assíncrono**. Você o usaria com `async with`:
```Python
async with lifespan(app):
await do_stuff()
```
-Quando você cria um gerenciador de contexto ou um gerenciador de contexto assíncrono como mencionado acima, o que ele faz é que, antes de entrar no bloco `with`, ele irá executar o código anterior ao `yield`, e depois de sair do bloco `with`, ele irá executar o código depois do `yield`.
+Quando você cria um gerenciador de contexto ou um gerenciador de contexto assíncrono como acima, o que ele faz é: antes de entrar no bloco `with`, ele executa o código antes do `yield`, e após sair do bloco `with`, ele executa o código depois do `yield`.
-No nosso exemplo de código acima, nós não usamos ele diretamente, mas nós passamos para o FastAPI para ele usá-lo.
+No nosso exemplo de código acima, não o usamos diretamente, mas passamos para o FastAPI para que ele o use.
-O parâmetro `lifespan` da aplicação `FastAPI` usa um **Gerenciador de Contexto Assíncrono**, então nós podemos passar nosso novo gerenciador de contexto assíncrono do `lifespan` para ele.
+O parâmetro `lifespan` da aplicação `FastAPI` aceita um **gerenciador de contexto assíncrono**, então podemos passar para ele nosso novo gerenciador de contexto assíncrono `lifespan`.
-```Python hl_lines="22"
-{!../../../docs_src/events/tutorial003.py!}
-```
+{* ../../docs_src/events/tutorial003_py310.py hl[22] *}
+
+## Eventos alternativos (descontinuados) { #alternative-events-deprecated }
-## Eventos alternativos (deprecados)
+/// warning | Atenção
-!!! warning "Aviso"
- A maneira recomendada para lidar com a *inicialização* e o *encerramento* é usando o parâmetro `lifespan` da aplicação `FastAPI` como descrito acima.
+A forma recomendada de lidar com a *inicialização* e o *encerramento* é usando o parâmetro `lifespan` da aplicação `FastAPI`, como descrito acima. Se você fornecer um parâmetro `lifespan`, os manipuladores de eventos `startup` e `shutdown` não serão mais chamados. É tudo `lifespan` ou tudo por eventos, não ambos.
- Você provavelmente pode pular essa parte.
+Você provavelmente pode pular esta parte.
-Existe uma forma alternativa para definir a execução dessa lógica durante *inicialização* e durante *encerramento*.
+///
-Você pode definir manipuladores de eventos (funções) que precisam ser executadas antes da aplicação inicializar, ou quando a aplicação estiver encerrando.
+Existe uma forma alternativa de definir essa lógica para ser executada durante a *inicialização* e durante o *encerramento*.
+
+Você pode definir manipuladores de eventos (funções) que precisam ser executados antes de a aplicação iniciar ou quando a aplicação estiver encerrando.
Essas funções podem ser declaradas com `async def` ou `def` normal.
-### Evento `startup`
+### Evento `startup` { #startup-event }
-Para adicionar uma função que deve rodar antes da aplicação iniciar, declare-a com o evento `"startup"`:
+Para adicionar uma função que deve rodar antes de a aplicação iniciar, declare-a com o evento `"startup"`:
-```Python hl_lines="8"
-{!../../../docs_src/events/tutorial001.py!}
-```
+{* ../../docs_src/events/tutorial001_py310.py hl[8] *}
-Nesse caso, a função de manipulação de evento `startup` irá inicializar os itens do "banco de dados" (só um `dict`) com alguns valores.
+Nesse caso, a função de manipulador do evento `startup` inicializará os itens do "banco de dados" (apenas um `dict`) com alguns valores.
-Você pode adicionar mais que uma função de manipulação de evento.
+Você pode adicionar mais de uma função de manipulador de eventos.
-E sua aplicação não irá começar a receber requisições até que todos os manipuladores de eventos de `startup` sejam concluídos.
+E sua aplicação não começará a receber requisições até que todos os manipuladores de eventos `startup` sejam concluídos.
-### Evento `shutdown`
+### Evento `shutdown` { #shutdown-event }
-Para adicionar uma função que deve ser executada quando a aplicação estiver encerrando, declare ela com o evento `"shutdown"`:
+Para adicionar uma função que deve ser executada quando a aplicação estiver encerrando, declare-a com o evento `"shutdown"`:
-```Python hl_lines="6"
-{!../../../docs_src/events/tutorial002.py!}
-```
+{* ../../docs_src/events/tutorial002_py310.py hl[6] *}
+
+Aqui, a função de manipulador do evento `shutdown` escreverá uma linha de texto `"Application shutdown"` no arquivo `log.txt`.
+
+/// info | Informação
+
+Na função `open()`, o `mode="a"` significa "acrescentar", então a linha será adicionada depois do que já estiver naquele arquivo, sem sobrescrever o conteúdo anterior.
+
+///
+
+/// tip | Dica
+
+Perceba que, nesse caso, estamos usando a função padrão do Python `open()` que interage com um arquivo.
-Aqui, a função de manipulação de evento `shutdown` irá escrever uma linha de texto `"Application shutdown"` no arquivo `log.txt`.
+Então, isso envolve I/O (input/output), que requer "esperar" que as coisas sejam escritas em disco.
-!!! info "Informação"
- Na função `open()`, o `mode="a"` significa "acrescentar", então, a linha irá ser adicionada depois de qualquer coisa que esteja naquele arquivo, sem sobrescrever o conteúdo anterior.
+Mas `open()` não usa `async` e `await`.
-!!! tip "Dica"
- Perceba que nesse caso nós estamos usando a função padrão do Python `open()` que interage com um arquivo.
+Assim, declaramos a função de manipulador de evento com `def` padrão em vez de `async def`.
- Então, isso envolve I/O (input/output), que exige "esperar" que coisas sejam escritas em disco.
+///
- Mas `open()` não usa `async` e `await`.
+### `startup` e `shutdown` juntos { #startup-and-shutdown-together }
- Então, nós declaramos uma função de manipulação de evento com o padrão `def` ao invés de `async def`.
+Há uma grande chance de que a lógica para sua *inicialização* e *encerramento* esteja conectada, você pode querer iniciar alguma coisa e então finalizá-la, adquirir um recurso e então liberá-lo, etc.
-### `startup` e `shutdown` juntos
+Fazer isso em funções separadas que não compartilham lógica ou variáveis entre si é mais difícil, pois você precisaria armazenar valores em variáveis globais ou truques semelhantes.
-Há uma grande chance que a lógica para sua *inicialização* e *encerramento* esteja conectada, você pode querer iniciar alguma coisa e então finalizá-la, adquirir um recurso e então liberá-lo, etc.
+Por causa disso, agora é recomendado usar o `lifespan`, como explicado acima.
-Fazendo isso em funções separadas que não compartilham lógica ou variáveis entre elas é mais difícil já que você precisa armazenar os valores em variáveis globais ou truques parecidos.
+## Detalhes técnicos { #technical-details }
-Por causa disso, agora é recomendado em vez disso usar o `lifespan` como explicado acima.
+Apenas um detalhe técnico para nerds curiosos. 🤓
-## Detalhes técnicos
+Por baixo, na especificação técnica do ASGI, isso é parte do [Protocolo Lifespan](https://asgi.readthedocs.io/en/latest/specs/lifespan.html), e define eventos chamados `startup` e `shutdown`.
-Só um detalhe técnico para nerds curiosos. 🤓
+/// info | Informação
-Por baixo, na especificação técnica ASGI, essa é a parte do Protocolo Lifespan, e define eventos chamados `startup` e `shutdown`.
+Você pode ler mais sobre os manipuladores de `lifespan` do Starlette na [Documentação do Lifespan do Starlette](https://www.starlette.dev/lifespan/).
-!!! info "Informação"
- Você pode ler mais sobre o manipulador `lifespan` do Starlette na Documentação do Lifespan Starlette.
+Incluindo como lidar com estado do lifespan que pode ser usado em outras áreas do seu código.
- Incluindo como manipular estado do lifespan que pode ser usado em outras áreas do seu código.
+///
-## Sub Aplicações
+## Sub Aplicações { #sub-applications }
-🚨 Tenha em mente que esses eventos de lifespan (de inicialização e desligamento) irão somente ser executados para a aplicação principal, não para [Sub Aplicações - Montagem](./sub-applications.md){.internal-link target=_blank}.
+🚨 Tenha em mente que esses eventos de lifespan (inicialização e encerramento) serão executados apenas para a aplicação principal, não para [Sub Aplicações - Montagem](sub-applications.md).
diff --git a/docs/pt/docs/advanced/generate-clients.md b/docs/pt/docs/advanced/generate-clients.md
new file mode 100644
index 0000000000000..0d31a69af8395
--- /dev/null
+++ b/docs/pt/docs/advanced/generate-clients.md
@@ -0,0 +1,208 @@
+# Gerando SDKs { #generating-sdks }
+
+Como o **FastAPI** é baseado na especificação **OpenAPI**, suas APIs podem ser descritas em um formato padrão que muitas ferramentas entendem.
+
+Isso facilita gerar **documentação** atualizada, bibliotecas clientes (**SDKs**) em várias linguagens e **testes** ou **fluxos de trabalho de automação** que permanecem em sincronia com o seu código.
+
+Neste guia, você aprenderá como gerar um **SDK em TypeScript** para o seu backend FastAPI.
+
+## Geradores de SDK de código aberto { #open-source-sdk-generators }
+
+Uma opção versátil é o [OpenAPI Generator](https://openapi-generator.tech/), que suporta **muitas linguagens de programação** e pode gerar SDKs a partir da sua especificação OpenAPI.
+
+Para **clientes TypeScript**, o [Hey API](https://heyapi.dev/) é uma solução feita sob medida, oferecendo uma experiência otimizada para o ecossistema TypeScript.
+
+Você pode descobrir mais geradores de SDK em [OpenAPI.Tools](https://openapi.tools/#sdk).
+
+/// tip | Dica
+
+O FastAPI gera automaticamente especificações **OpenAPI 3.1**, então qualquer ferramenta que você usar deve suportar essa versão.
+
+///
+
+## Geradores de SDK dos patrocinadores do FastAPI { #sdk-generators-from-fastapi-sponsors }
+
+Esta seção destaca soluções **financiadas por investimento** e **com suporte de empresas** que patrocinam o FastAPI. Esses produtos fornecem **funcionalidades adicionais** e **integrações** além de SDKs gerados com alta qualidade.
+
+Ao ✨ [**patrocinar o FastAPI**](../help-fastapi.md#sponsor-the-author) ✨, essas empresas ajudam a garantir que o framework e seu **ecossistema** continuem saudáveis e **sustentáveis**.
+
+O patrocínio também demonstra um forte compromisso com a **comunidade** FastAPI (você), mostrando que elas se importam não apenas em oferecer um **ótimo serviço**, mas também em apoiar um **framework robusto e próspero**, o FastAPI. 🙇
+
+Por exemplo, você pode querer experimentar:
+
+* [Speakeasy](https://speakeasy.com/editor?utm_source=fastapi+repo&utm_medium=github+sponsorship)
+* [Stainless](https://www.stainless.com/?utm_source=fastapi&utm_medium=referral)
+* [liblab](https://developers.liblab.com/tutorials/sdk-for-fastapi?utm_source=fastapi)
+
+Algumas dessas soluções também podem ser open source ou oferecer planos gratuitos, para que você possa testá-las sem compromisso financeiro. Outros geradores comerciais de SDK estão disponíveis e podem ser encontrados online. 🤓
+
+## Crie um SDK em TypeScript { #create-a-typescript-sdk }
+
+Vamos começar com uma aplicação FastAPI simples:
+
+{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}
+
+Note que as *operações de rota* definem os modelos que usam para o corpo da requisição e o corpo da resposta, usando os modelos `Item` e `ResponseMessage`.
+
+### Documentação da API { #api-docs }
+
+Se você for para `/docs`, verá que ela tem os **schemas** para os dados a serem enviados nas requisições e recebidos nas respostas:
+
+
+
+Você pode ver esses schemas porque eles foram declarados com os modelos no app.
+
+Essas informações estão disponíveis no **schema OpenAPI** do app e são mostradas na documentação da API.
+
+E essas mesmas informações dos modelos que estão incluídas no OpenAPI são o que pode ser usado para **gerar o código do cliente**.
+
+### Hey API { #hey-api }
+
+Depois que tivermos uma aplicação FastAPI com os modelos, podemos usar o Hey API para gerar um cliente TypeScript. A forma mais rápida é via npx.
+
+```sh
+npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
+```
+
+Isso gerará um SDK TypeScript em `./src/client`.
+
+Você pode aprender como [instalar `@hey-api/openapi-ts`](https://heyapi.dev/openapi-ts/get-started) e ler sobre o [resultado gerado](https://heyapi.dev/openapi-ts/output) no site deles.
+
+### Usando o SDK { #using-the-sdk }
+
+Agora você pode importar e usar o código do cliente. Poderia ser assim, observe que você obtém preenchimento automático para os métodos:
+
+
+
+Você também obterá preenchimento automático para o corpo a ser enviado:
+
+
+
+/// tip | Dica
+
+Observe o preenchimento automático para `name` e `price`, que foi definido na aplicação FastAPI, no modelo `Item`.
+
+///
+
+Você terá erros em linha para os dados que você envia:
+
+
+
+O objeto de resposta também terá preenchimento automático:
+
+
+
+## Aplicação FastAPI com Tags { #fastapi-app-with-tags }
+
+Em muitos casos, sua aplicação FastAPI será maior, e você provavelmente usará tags para separar diferentes grupos de *operações de rota*.
+
+Por exemplo, você poderia ter uma seção para **items** e outra seção para **users**, e elas poderiam ser separadas por tags:
+
+{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}
+
+### Gere um cliente TypeScript com Tags { #generate-a-typescript-client-with-tags }
+
+Se você gerar um cliente para uma aplicação FastAPI usando tags, normalmente também separará o código do cliente com base nas tags.
+
+Dessa forma, você poderá ter as coisas ordenadas e agrupadas corretamente para o código do cliente:
+
+
+
+Nesse caso você tem:
+
+* `ItemsService`
+* `UsersService`
+
+### Nomes dos métodos do cliente { #client-method-names }
+
+Agora os nomes dos métodos gerados como `createItemItemsPost` não parecem muito “limpos”:
+
+```TypeScript
+ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
+```
+
+...isso ocorre porque o gerador de clientes usa o **ID de operação** interno do OpenAPI para cada *operação de rota*.
+
+O OpenAPI exige que cada ID de operação seja único em todas as *operações de rota*, então o FastAPI usa o **nome da função**, o **path** e o **método/operação HTTP** para gerar esse ID de operação, porque dessa forma ele pode garantir que os IDs de operação sejam únicos.
+
+Mas eu vou te mostrar como melhorar isso a seguir. 🤓
+
+## IDs de operação personalizados e nomes de métodos melhores { #custom-operation-ids-and-better-method-names }
+
+Você pode **modificar** a maneira como esses IDs de operação são **gerados** para torná-los mais simples e ter **nomes de método mais simples** nos clientes.
+
+Neste caso, você terá que garantir que cada ID de operação seja **único** de alguma outra maneira.
+
+Por exemplo, você poderia garantir que cada *operação de rota* tenha uma tag, e então gerar o ID de operação com base na **tag** e no **nome** da *operação de rota* (o nome da função).
+
+### Função personalizada para gerar IDs exclusivos { #custom-generate-unique-id-function }
+
+O FastAPI usa um **ID exclusivo** para cada *operação de rota*, ele é usado para o **ID de operação** e também para os nomes de quaisquer modelos personalizados necessários, para requisições ou respostas.
+
+Você pode personalizar essa função. Ela recebe uma `APIRoute` e retorna uma string.
+
+Por exemplo, aqui está usando a primeira tag (Você provavelmente terá apenas uma tag) e o nome da *operação de rota* (o nome da função).
+
+Você pode então passar essa função personalizada para o **FastAPI** como o parâmetro `generate_unique_id_function`:
+
+{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}
+
+### Gere um cliente TypeScript com IDs de operação personalizados { #generate-a-typescript-client-with-custom-operation-ids }
+
+Agora, se você gerar o cliente novamente, verá que ele tem os nomes dos métodos melhorados:
+
+
+
+Como você pode ver, os nomes dos métodos agora têm a tag e, em seguida, o nome da função. Agora eles não incluem informações do path da URL e da operação HTTP.
+
+### Pré-processar a especificação OpenAPI para o gerador de clientes { #preprocess-the-openapi-specification-for-the-client-generator }
+
+O código gerado ainda tem algumas **informações duplicadas**.
+
+Nós já sabemos que esse método está relacionado aos **items** porque essa palavra está no `ItemsService` (retirada da tag), mas ainda temos o nome da tag prefixado no nome do método também. 😕
+
+Provavelmente ainda queremos mantê-lo para o OpenAPI em geral, pois isso garantirá que os IDs de operação sejam **únicos**.
+
+Mas para o cliente gerado, poderíamos **modificar** os IDs de operação do OpenAPI logo antes de gerar os clientes, apenas para tornar esses nomes de método mais agradáveis e **limpos**.
+
+Poderíamos baixar o JSON do OpenAPI para um arquivo `openapi.json` e então poderíamos **remover essa tag prefixada** com um script como este:
+
+{* ../../docs_src/generate_clients/tutorial004_py310.py *}
+
+//// tab | Node.js
+
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
+```
+
+////
+
+Com isso, os IDs de operação seriam renomeados de coisas como `items-get_items` para apenas `get_items`, dessa forma o gerador de clientes pode gerar nomes de métodos mais simples.
+
+### Gere um cliente TypeScript com o OpenAPI pré-processado { #generate-a-typescript-client-with-the-preprocessed-openapi }
+
+Como o resultado final está agora em um arquivo `openapi.json`, você precisa atualizar o local de entrada:
+
+```sh
+npx @hey-api/openapi-ts -i ./openapi.json -o src/client
+```
+
+Depois de gerar o novo cliente, você terá agora **nomes de métodos “limpos”**, com todo o **preenchimento automático**, **erros em linha**, etc:
+
+
+
+## Benefícios { #benefits }
+
+Ao usar os clientes gerados automaticamente, você terá **preenchimento automático** para:
+
+* Métodos.
+* Corpos de requisições, parâmetros de query, etc.
+* Corpos de respostas.
+
+Você também terá **erros em linha** para tudo.
+
+E sempre que você atualizar o código do backend e **regenerar** o frontend, ele terá quaisquer novas *operações de rota* disponíveis como métodos, as antigas removidas, e qualquer outra alteração será refletida no código gerado. 🤓
+
+Isso também significa que, se algo mudou, será **refletido** no código do cliente automaticamente. E se você **construir** o cliente, ele falhará caso haja qualquer **incompatibilidade** nos dados usados.
+
+Assim, você **detectará muitos erros** muito cedo no ciclo de desenvolvimento, em vez de ter que esperar que os erros apareçam para seus usuários finais em produção e então tentar depurar onde está o problema. ✨
diff --git a/docs/pt/docs/advanced/index.md b/docs/pt/docs/advanced/index.md
index 7e276f732ab65..bbb8b0b50b067 100644
--- a/docs/pt/docs/advanced/index.md
+++ b/docs/pt/docs/advanced/index.md
@@ -1,24 +1,21 @@
-# Guia de Usuário Avançado
+# Guia de Usuário Avançado { #advanced-user-guide }
-## Recursos Adicionais
+## Recursos Adicionais { #additional-features }
-O [Tutorial - Guia de Usuário](../tutorial/){.internal-link target=_blank} deve ser o suficiente para dar a você um tour por todos os principais recursos do **FastAPI**.
+O [Tutorial - Guia de Usuário](../tutorial/index.md) principal deve ser o suficiente para dar a você um tour por todos os principais recursos do **FastAPI**.
-Na próxima seção você verá outras opções, configurações, e recursos adicionais.
+Nas próximas seções você verá outras opções, configurações, e recursos adicionais.
-!!! tip "Dica"
- As próximas seções **não são necessáriamente "avançadas"**
+/// tip | Dica
- E é possível que para seu caso de uso, a solução esteja em uma delas.
+As próximas seções **não são necessariamente "avançadas"**.
-## Leia o Tutorial primeiro
+E é possível que para seu caso de uso, a solução esteja em uma delas.
-Você ainda pode usar a maior parte dos recursos no **FastAPI** com o conhecimento do [Tutorial - Guia de Usuário](../tutorial/){.internal-link target=_blank}.
+///
-E as próximas seções assumem que você já leu ele, e que você conhece suas ideias principais.
-
-## Curso TestDriven.io
+## Leia o Tutorial primeiro { #read-the-tutorial-first }
-Se você gostaria de fazer um curso avançado-iniciante para complementar essa seção da documentação, você pode querer conferir: Test-Driven Development com FastAPI e Docker por **TestDriven.io**.
+Você ainda pode usar a maior parte dos recursos no **FastAPI** com o conhecimento do [Tutorial - Guia de Usuário](../tutorial/index.md) principal.
-Eles estão atualmente doando 10% de todos os lucros para o desenvolvimento do **FastAPI**. 🎉 😄
+E as próximas seções assumem que você já leu ele, e que você conhece suas ideias principais.
diff --git a/docs/pt/docs/advanced/json-base64-bytes.md b/docs/pt/docs/advanced/json-base64-bytes.md
new file mode 100644
index 0000000000000..cc956da4f03b9
--- /dev/null
+++ b/docs/pt/docs/advanced/json-base64-bytes.md
@@ -0,0 +1,63 @@
+# JSON com bytes em Base64 { #json-with-bytes-as-base64 }
+
+Se sua aplicação precisa receber e enviar dados JSON, mas você precisa incluir dados binários nele, você pode codificá-los em base64.
+
+## Base64 vs Arquivos { #base64-vs-files }
+
+Primeiro, considere se você pode usar [Arquivos na request](../tutorial/request-files.md) para fazer upload de dados binários e [Response personalizada - FileResponse](./custom-response.md#fileresponse--fileresponse-) para enviar dados binários, em vez de codificá-los em JSON.
+
+JSON só pode conter strings codificadas em UTF-8, portanto não pode conter bytes puros.
+
+Base64 pode codificar dados binários em strings, mas, para isso, precisa usar mais caracteres do que os dados binários originais; assim, normalmente é menos eficiente do que arquivos comuns.
+
+Use base64 apenas se realmente precisar incluir dados binários em JSON e não puder usar arquivos para isso.
+
+## Pydantic `bytes` { #pydantic-bytes }
+
+Você pode declarar um modelo Pydantic com campos `bytes` e então usar `val_json_bytes` na configuração do modelo para indicar que deve usar base64 para *validar* os dados JSON de entrada; como parte dessa validação, ele decodificará a string base64 em bytes.
+
+{* ../../docs_src/json_base64_bytes/tutorial001_py310.py ln[1:9,29:35] hl[9] *}
+
+Se você verificar a `/docs`, verá que o campo `data` espera bytes codificados em base64:
+
+
+
diff --git a/docs/pt/docs/advanced/openapi-webhooks.md b/docs/pt/docs/advanced/openapi-webhooks.md
new file mode 100644
index 0000000000000..0c675089ca3f0
--- /dev/null
+++ b/docs/pt/docs/advanced/openapi-webhooks.md
@@ -0,0 +1,55 @@
+# Webhooks OpenAPI { #openapi-webhooks }
+
+Existem situações onde você deseja informar os **usuários** da sua API que a sua aplicação pode chamar a aplicação *deles* (enviando uma requisição) com alguns dados, normalmente para **notificar** algum tipo de **evento**.
+
+Isso significa que no lugar do processo normal de seus usuários enviarem requisições para a sua API, é a **sua API** (ou sua aplicação) que poderia **enviar requisições para o sistema deles** (para a API deles, a aplicação deles).
+
+Isso normalmente é chamado de **webhook**.
+
+## Etapas dos webhooks { #webhooks-steps }
+
+Normalmente, o processo é que **você define** em seu código qual é a mensagem que você irá mandar, o **corpo da sua requisição**.
+
+Você também define de alguma maneira em quais **momentos** a sua aplicação mandará essas requisições ou eventos.
+
+E os **seus usuários** definem de alguma forma (em algum painel por exemplo) a **URL** que a sua aplicação deve enviar essas requisições.
+
+Toda a **lógica** sobre como cadastrar as URLs para os webhooks e o código para enviar de fato as requisições cabe a você definir. Você escreve da maneira que você desejar no **seu próprio código**.
+
+## Documentando webhooks com o **FastAPI** e OpenAPI { #documenting-webhooks-with-fastapi-and-openapi }
+
+Com o **FastAPI**, utilizando o OpenAPI, você pode definir os nomes destes webhooks, os tipos das operações HTTP que a sua aplicação pode enviar (e.g. `POST`, `PUT`, etc.) e os **corpos** da requisição que a sua aplicação enviaria.
+
+Isto pode facilitar bastante para os seus usuários **implementarem as APIs deles** para receber as requisições dos seus **webhooks**, eles podem inclusive ser capazes de gerar parte do código da API deles.
+
+/// info | Informação
+
+Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do FastAPI a partir da versão `0.99.0`.
+
+///
+
+## Uma aplicação com webhooks { #an-app-with-webhooks }
+
+Quando você cria uma aplicação com o **FastAPI**, existe um atributo chamado `webhooks`, que você utilizar para defini-los da mesma maneira que você definiria as suas **operações de rotas**, utilizando por exemplo `@app.webhooks.post()`.
+
+{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}
+
+Os webhooks que você define aparecerão no esquema do **OpenAPI** e na **página de documentação** gerada automaticamente.
+
+/// info | Informação
+
+O objeto `app.webhooks` é na verdade apenas um `APIRouter`, o mesmo tipo que você utilizaria ao estruturar a sua aplicação com diversos arquivos.
+
+///
+
+Note que utilizando webhooks você não está de fato declarando um *path* (como `/items/`), o texto que informa é apenas um **identificador** do webhook (o nome do evento), por exemplo em `@app.webhooks.post("new-subscription")`, o nome do webhook é `new-subscription`.
+
+Isto porque espera-se que os **seus usuários** definam o verdadeiro **URL path** onde eles desejam receber a requisição do webhook de algum outra maneira. (e.g. um painel).
+
+### Confira a documentação { #check-the-docs }
+
+Agora você pode iniciar a sua aplicação e ir até [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).
+
+Você verá que a sua documentação possui as *operações de rota* normais e agora também possui alguns **webhooks**:
+
+
diff --git a/docs/pt/docs/advanced/path-operation-advanced-configuration.md b/docs/pt/docs/advanced/path-operation-advanced-configuration.md
new file mode 100644
index 0000000000000..b9862876cad1a
--- /dev/null
+++ b/docs/pt/docs/advanced/path-operation-advanced-configuration.md
@@ -0,0 +1,172 @@
+# Configuração Avançada da Operação de Rota { #path-operation-advanced-configuration }
+
+## operationId do OpenAPI { #openapi-operationid }
+
+/// warning | Atenção
+
+Se você não é um "especialista" no OpenAPI, você provavelmente não precisa disso.
+
+///
+
+Você pode definir o `operationId` do OpenAPI que será utilizado na sua *operação de rota* com o parâmetro `operation_id`.
+
+Você deveria ter certeza que ele é único para cada operação.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
+
+### Utilizando o nome da *função de operação de rota* como o operationId { #using-the-path-operation-function-name-as-the-operationid }
+
+Se você quiser utilizar o nome das funções da sua API como `operationId`s, você pode iterar sobre todos esses nomes e sobrescrever o `operation_id` em cada *operação de rota* utilizando o `APIRoute.name` dela.
+
+Você deveria fazer isso depois de adicionar todas as suas *operações de rota*.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *}
+
+/// tip | Dica
+
+Se você chamar `app.openapi()` manualmente, você deveria atualizar os `operationId`s antes dessa chamada.
+
+///
+
+/// warning | Atenção
+
+Se você fizer isso, você tem que ter certeza de que cada uma das suas *funções de operação de rota* tem um nome único.
+
+Mesmo que elas estejam em módulos (arquivos Python) diferentes.
+
+///
+
+## Excluir do OpenAPI { #exclude-from-openapi }
+
+Para excluir uma *operação de rota* do esquema OpenAPI gerado (e por consequência, dos sistemas de documentação automáticos), utilize o parâmetro `include_in_schema` e defina ele como `False`:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}
+
+## Descrição avançada a partir de docstring { #advanced-description-from-docstring }
+
+Você pode limitar as linhas utilizadas a partir da docstring de uma *função de operação de rota* para o OpenAPI.
+
+Adicionar um `\f` (um caractere de escape para "form feed") faz com que o **FastAPI** trunque a saída usada para o OpenAPI até esse ponto.
+
+Ele não será mostrado na documentação, mas outras ferramentas (como o Sphinx) serão capazes de utilizar o resto.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}
+
+## Respostas Adicionais { #additional-responses }
+
+Você provavelmente já viu como declarar o `response_model` e `status_code` para uma *operação de rota*.
+
+Isso define os metadados sobre a resposta principal da *operação de rota*.
+
+Você também pode declarar respostas adicionais, com seus modelos, códigos de status, etc.
+
+Existe um capítulo inteiro da nossa documentação sobre isso, você pode ler em [Respostas Adicionais no OpenAPI](additional-responses.md).
+
+## Extras do OpenAPI { #openapi-extra }
+
+Quando você declara uma *operação de rota* na sua aplicação, o **FastAPI** irá gerar os metadados relevantes da *operação de rota* automaticamente para serem incluídos no esquema do OpenAPI.
+
+/// note | Detalhes Técnicos
+
+Na especificação do OpenAPI, isso é chamado de um [Objeto de Operação](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object).
+
+///
+
+Ele possui toda a informação sobre a *operação de rota* e é usado para gerar a documentação automaticamente.
+
+Ele inclui os atributos `tags`, `parameters`, `requestBody`, `responses`, etc.
+
+Esse esquema específico para uma *operação de rota* normalmente é gerado automaticamente pelo **FastAPI**, mas você também pode estender ele.
+
+/// tip | Dica
+
+Esse é um ponto de extensão de baixo nível.
+
+Caso você só precise declarar respostas adicionais, uma forma conveniente de fazer isso é com [Respostas Adicionais no OpenAPI](additional-responses.md).
+
+///
+
+Você pode estender o esquema do OpenAPI para uma *operação de rota* utilizando o parâmetro `openapi_extra`.
+
+### Extensões do OpenAPI { #openapi-extensions }
+
+Esse parâmetro `openapi_extra` pode ser útil, por exemplo, para declarar [Extensões do OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py310.py hl[6] *}
+
+Se você abrir os documentos criados automaticamente para a API, sua extensão aparecerá no final da *operação de rota* específica.
+
+
+
+E se você olhar o esquema OpenAPI resultante (na rota `/openapi.json` da sua API), você verá que a sua extensão também faz parte da *operação de rota* específica:
+
+```JSON hl_lines="22"
+{
+ "openapi": "3.1.0",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0"
+ },
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ }
+ },
+ "x-aperture-labs-portal": "blue"
+ }
+ }
+ }
+}
+```
+
+### Esquema de *operação de rota* do OpenAPI personalizado { #custom-openapi-path-operation-schema }
+
+O dicionário em `openapi_extra` vai ser mesclado profundamente com o esquema OpenAPI gerado automaticamente para a *operação de rota*.
+
+Então, você pode adicionar dados extras ao esquema gerado automaticamente.
+
+Por exemplo, você poderia decidir ler e validar a requisição com seu próprio código, sem usar as funcionalidades automáticas do FastAPI com o Pydantic, mas ainda assim querer definir a requisição no esquema OpenAPI.
+
+Você pode fazer isso com `openapi_extra`:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py310.py hl[19:36, 39:40] *}
+
+Nesse exemplo, nós não declaramos nenhum modelo do Pydantic. Na verdade, o corpo da requisição não está nem mesmo analisado como JSON, ele é lido diretamente como `bytes`, e a função `magic_data_reader()` seria a responsável por analisá-lo de alguma forma.
+
+De toda forma, nós podemos declarar o esquema esperado para o corpo da requisição.
+
+### Tipo de conteúdo do OpenAPI personalizado { #custom-openapi-content-type }
+
+Utilizando esse mesmo truque, você pode usar um modelo Pydantic para definir o JSON Schema que é então incluído na seção do esquema personalizado do OpenAPI na *operação de rota*.
+
+E você pode fazer isso até mesmo quando o tipo de dados na requisição não é JSON.
+
+Por exemplo, nesta aplicação nós não usamos a funcionalidade integrada ao FastAPI de extrair o JSON Schema dos modelos Pydantic nem a validação automática para JSON. Na verdade, estamos declarando o tipo de conteúdo da requisição como YAML, em vez de JSON:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[15:20, 22] *}
+
+Entretanto, mesmo que não utilizemos a funcionalidade integrada por padrão, ainda estamos usando um modelo Pydantic para gerar um JSON Schema manualmente para os dados que queremos receber em YAML.
+
+Então utilizamos a requisição diretamente e extraímos o corpo como `bytes`. Isso significa que o FastAPI não vai sequer tentar analisar o payload da requisição como JSON.
+
+E então no nosso código, nós analisamos o conteúdo YAML diretamente e, em seguida, estamos usando novamente o mesmo modelo Pydantic para validar o conteúdo YAML:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *}
+
+/// tip | Dica
+
+Aqui reutilizamos o mesmo modelo do Pydantic.
+
+Mas da mesma forma, nós poderíamos ter validado de alguma outra forma.
+
+///
diff --git a/docs/pt/docs/advanced/response-change-status-code.md b/docs/pt/docs/advanced/response-change-status-code.md
new file mode 100644
index 0000000000000..44ca6062a54a2
--- /dev/null
+++ b/docs/pt/docs/advanced/response-change-status-code.md
@@ -0,0 +1,31 @@
+# Retorno - Altere o Código de Status { #response-change-status-code }
+
+Você provavelmente leu anteriormente que você pode definir um [Código de Status do Retorno](../tutorial/response-status-code.md) padrão.
+
+Porém em alguns casos você precisa retornar um código de status diferente do padrão.
+
+## Caso de uso { #use-case }
+
+Por exemplo, imagine que você deseja retornar um código de status HTTP de "OK" `200` por padrão.
+
+Mas se o dado não existir, você quer criá-lo e retornar um código de status HTTP de "CREATED" `201`.
+
+Mas você ainda quer ser capaz de filtrar e converter o dado que você retornará com um `response_model`.
+
+Para estes casos, você pode utilizar um parâmetro `Response`.
+
+## Use um parâmetro `Response` { #use-a-response-parameter }
+
+Você pode declarar um parâmetro do tipo `Response` em sua *função de operação de rota* (assim como você pode fazer para cookies e headers).
+
+E então você pode definir o `status_code` neste objeto de retorno *temporal*.
+
+{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}
+
+E então você pode retornar qualquer objeto que você precise, como você faria normalmente (um `dict`, um modelo de banco de dados, etc.).
+
+E se você declarar um `response_model`, ele ainda será utilizado para filtrar e converter o objeto que você retornou.
+
+O **FastAPI** utilizará este retorno *temporal* para extrair o código de status (e também cookies e headers), e irá colocá-los no retorno final que contém o valor que você retornou, filtrado por qualquer `response_model`.
+
+Você também pode declarar o parâmetro `Response` nas dependências, e definir o código de status nelas. Mas lembre-se que o último que for definido é o que prevalecerá.
diff --git a/docs/pt/docs/advanced/response-cookies.md b/docs/pt/docs/advanced/response-cookies.md
new file mode 100644
index 0000000000000..691bd1b9c5c57
--- /dev/null
+++ b/docs/pt/docs/advanced/response-cookies.md
@@ -0,0 +1,51 @@
+# Cookies de Resposta { #response-cookies }
+
+## Use um parâmetro `Response` { #use-a-response-parameter }
+
+Você pode declarar um parâmetro do tipo `Response` na sua *função de operação de rota*.
+
+E então você pode definir cookies nesse objeto de resposta *temporário*.
+
+{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}
+
+Em seguida, você pode retornar qualquer objeto que precise, como normalmente faria (um `dict`, um modelo de banco de dados, etc).
+
+E se você declarou um `response_model`, ele ainda será usado para filtrar e converter o objeto que você retornou.
+
+**FastAPI** usará essa resposta *temporária* para extrair os cookies (também os cabeçalhos e código de status) e os colocará na resposta final que contém o valor que você retornou, filtrado por qualquer `response_model`.
+
+Você também pode declarar o parâmetro `Response` em dependências e definir cookies (e cabeçalhos) nelas.
+
+## Retorne uma `Response` diretamente { #return-a-response-directly }
+
+Você também pode criar cookies ao retornar uma `Response` diretamente no seu código.
+
+Para fazer isso, você pode criar uma resposta como descrito em [Retorne uma Resposta Diretamente](response-directly.md).
+
+Então, defina os cookies nela e a retorne:
+
+{* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *}
+
+/// tip | Dica
+
+Lembre-se de que se você retornar uma resposta diretamente em vez de usar o parâmetro `Response`, FastAPI a retornará diretamente.
+
+Portanto, você terá que garantir que seus dados sejam do tipo correto. E.g. será compatível com JSON se você estiver retornando um `JSONResponse`.
+
+E também que você não esteja enviando nenhum dado que deveria ter sido filtrado por um `response_model`.
+
+///
+
+### Mais informações { #more-info }
+
+/// note | Detalhes Técnicos
+
+Você também poderia usar `from starlette.responses import Response` ou `from starlette.responses import JSONResponse`.
+
+**FastAPI** fornece as mesmas `starlette.responses` em `fastapi.responses` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vem diretamente do Starlette.
+
+E como o `Response` pode ser usado frequentemente para definir cabeçalhos e cookies, o **FastAPI** também o fornece em `fastapi.Response`.
+
+///
+
+Para ver todos os parâmetros e opções disponíveis, verifique a [documentação no Starlette](https://www.starlette.dev/responses/#set-cookie).
diff --git a/docs/pt/docs/advanced/response-directly.md b/docs/pt/docs/advanced/response-directly.md
new file mode 100644
index 0000000000000..9024897c1ad42
--- /dev/null
+++ b/docs/pt/docs/advanced/response-directly.md
@@ -0,0 +1,83 @@
+# Retornando uma Resposta Diretamente { #return-a-response-directly }
+
+Quando você cria uma *operação de rota* no **FastAPI**, normalmente você pode retornar qualquer dado: um `dict`, uma `list`, um modelo do Pydantic, um modelo do banco de dados, etc.
+
+Se você declarar um [Modelo de resposta](../tutorial/response-model.md), o FastAPI irá usá-lo para serializar os dados para JSON, usando o Pydantic.
+
+Se você não declarar um modelo de resposta, o FastAPI usará o `jsonable_encoder` explicado em [Codificador Compatível com JSON](../tutorial/encoder.md) e o colocará em uma `JSONResponse`.
+
+Você também pode criar uma `JSONResponse` diretamente e retorná-la.
+
+/// tip | Dica
+
+Normalmente você terá um desempenho muito melhor usando um [Modelo de resposta](../tutorial/response-model.md) do que retornando uma `JSONResponse` diretamente, pois assim ele serializa os dados usando o Pydantic, em Rust.
+
+///
+
+## Retornando uma `Response` { #return-a-response }
+
+Você pode retornar uma `Response` ou qualquer subclasse dela.
+
+/// info | Informação
+
+A própria `JSONResponse` é uma subclasse de `Response`.
+
+///
+
+E quando você retorna uma `Response`, o **FastAPI** vai repassá-la diretamente.
+
+Ele não fará conversões de dados com modelos do Pydantic, não converterá o conteúdo para nenhum tipo, etc.
+
+Isso te dá bastante flexibilidade. Você pode retornar qualquer tipo de dado, sobrescrever qualquer declaração e validação nos dados, etc.
+
+Isso também te dá muita responsabilidade. Você precisa garantir que os dados retornados estão corretos, no formato correto, que podem ser serializados, etc.
+
+## Utilizando o `jsonable_encoder` em uma `Response` { #using-the-jsonable-encoder-in-a-response }
+
+Como o **FastAPI** não realiza nenhuma mudança na `Response` que você retorna, você precisa garantir que o conteúdo dela está pronto para uso.
+
+Por exemplo, você não pode colocar um modelo do Pydantic em uma `JSONResponse` sem antes convertê-lo em um `dict` com todos os tipos de dados (como `datetime`, `UUID`, etc) convertidos para tipos compatíveis com JSON.
+
+Para esses casos, você pode usar o `jsonable_encoder` para converter seus dados antes de repassá-los para a resposta:
+
+{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}
+
+/// note | Detalhes Técnicos
+
+Você também pode utilizar `from starlette.responses import JSONResponse`.
+
+**FastAPI** utiliza a mesma `starlette.responses` como `fastapi.responses` apenas como uma conveniência para você, desenvolvedor. Mas maior parte das respostas disponíveis vem diretamente do Starlette.
+
+///
+
+## Retornando uma `Response` personalizada { #returning-a-custom-response }
+
+O exemplo acima mostra todas as partes que você precisa, mas ainda não é muito útil, já que você poderia ter retornado o `item` diretamente, e o **FastAPI** colocaria em uma `JSONResponse` para você, convertendo em um `dict`, etc. Tudo isso por padrão.
+
+Agora, vamos ver como você pode usar isso para retornar uma resposta personalizada.
+
+Vamos dizer que você quer retornar uma resposta [XML](https://en.wikipedia.org/wiki/XML).
+
+Você pode colocar o seu conteúdo XML em uma string, colocar em uma `Response`, e retorná-lo:
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+## Como funciona um Modelo de resposta { #how-a-response-model-works }
+
+Quando você declara um [Modelo de resposta - Tipo de retorno](../tutorial/response-model.md) em uma operação de rota, o **FastAPI** irá usá-lo para serializar os dados para JSON, usando o Pydantic.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+Como isso acontece no lado do Rust, o desempenho será muito melhor do que se fosse feito com Python comum e a classe `JSONResponse`.
+
+Ao usar um `response_model` ou tipo de retorno, o FastAPI não usará o `jsonable_encoder` para converter os dados (o que seria mais lento) nem a classe `JSONResponse`.
+
+Em vez disso, ele pega os bytes JSON gerados com o Pydantic usando o modelo de resposta (ou tipo de retorno) e retorna uma `Response` com o media type correto para JSON diretamente (`application/json`).
+
+## Notas { #notes }
+
+Quando você retorna uma `Response` diretamente os dados não são validados, convertidos (serializados) ou documentados automaticamente.
+
+Mas você ainda pode documentar como descrito em [Respostas adicionais no OpenAPI](additional-responses.md).
+
+Você pode ver nas próximas seções como usar/declarar essas `Responses` customizadas enquanto mantém a conversão e documentação automática dos dados.
diff --git a/docs/pt/docs/advanced/response-headers.md b/docs/pt/docs/advanced/response-headers.md
new file mode 100644
index 0000000000000..7235b5eb8cabf
--- /dev/null
+++ b/docs/pt/docs/advanced/response-headers.md
@@ -0,0 +1,41 @@
+# Cabeçalhos de resposta { #response-headers }
+
+## Use um parâmetro `Response` { #use-a-response-parameter }
+
+Você pode declarar um parâmetro do tipo `Response` na sua *função de operação de rota* (assim como você pode fazer para cookies).
+
+Então você pode definir os cabeçalhos nesse objeto de resposta *temporário*.
+
+{* ../../docs_src/response_headers/tutorial002_py310.py hl[1, 7:8] *}
+
+Em seguida você pode retornar qualquer objeto que precisar, da maneira que faria normalmente (um `dict`, um modelo de banco de dados, etc.).
+
+Se você declarou um `response_model`, ele ainda será utilizado para filtrar e converter o objeto que você retornou.
+
+**FastAPI** usará essa resposta *temporária* para extrair os cabeçalhos (cookies e código de status também) e os colocará na resposta final que contém o valor que você retornou, filtrado por qualquer `response_model`.
+
+Você também pode declarar o parâmetro `Response` em dependências e definir cabeçalhos (e cookies) nelas.
+
+## Retorne uma `Response` diretamente { #return-a-response-directly }
+
+Você também pode adicionar cabeçalhos quando retornar uma `Response` diretamente.
+
+Crie uma resposta conforme descrito em [Retornar uma resposta diretamente](response-directly.md) e passe os cabeçalhos como um parâmetro adicional:
+
+{* ../../docs_src/response_headers/tutorial001_py310.py hl[10:12] *}
+
+/// note | Detalhes Técnicos
+
+Você também pode usar `from starlette.responses import Response` ou `from starlette.responses import JSONResponse`.
+
+**FastAPI** fornece as mesmas `starlette.responses` como `fastapi.responses` apenas como uma conveniência para você, desenvolvedor. Mas a maioria das respostas disponíveis vem diretamente do Starlette.
+
+E como a `Response` pode ser usada frequentemente para definir cabeçalhos e cookies, **FastAPI** também a fornece em `fastapi.Response`.
+
+///
+
+## Cabeçalhos personalizados { #custom-headers }
+
+Tenha em mente que cabeçalhos personalizados proprietários podem ser adicionados [usando o prefixo `X-`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers).
+
+Porém, se você tiver cabeçalhos personalizados que deseja que um cliente no navegador possa ver, você precisa adicioná-los às suas configurações de CORS (saiba mais em [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md)), usando o parâmetro `expose_headers` descrito na [documentação de CORS do Starlette](https://www.starlette.dev/middleware/#corsmiddleware).
diff --git a/docs/pt/docs/advanced/security/http-basic-auth.md b/docs/pt/docs/advanced/security/http-basic-auth.md
new file mode 100644
index 0000000000000..303d8480e1c2e
--- /dev/null
+++ b/docs/pt/docs/advanced/security/http-basic-auth.md
@@ -0,0 +1,107 @@
+# HTTP Basic Auth { #http-basic-auth }
+
+Para os casos mais simples, você pode utilizar o HTTP Basic Auth.
+
+No HTTP Basic Auth, a aplicação espera um cabeçalho que contém um usuário e uma senha.
+
+Caso ela não receba, ela retorna um erro HTTP 401 "Unauthorized".
+
+E retorna um cabeçalho `WWW-Authenticate` com o valor `Basic`, e um parâmetro opcional `realm`.
+
+Isso sinaliza ao navegador para mostrar o prompt integrado para um usuário e senha.
+
+Então, quando você digitar o usuário e senha, o navegador os envia automaticamente no cabeçalho.
+
+## HTTP Basic Auth Simples { #simple-http-basic-auth }
+
+* Importe `HTTPBasic` e `HTTPBasicCredentials`.
+* Crie um "esquema `security`" utilizando `HTTPBasic`.
+* Utilize o `security` com uma dependência em sua *operação de rota*.
+* Isso retorna um objeto do tipo `HTTPBasicCredentials`:
+ * Isto contém o `username` e o `password` enviado.
+
+{* ../../docs_src/security/tutorial006_an_py310.py hl[4,8,12] *}
+
+Quando você tentar abrir a URL pela primeira vez (ou clicar no botão "Executar" na documentação) o navegador vai pedir pelo seu usuário e senha:
+
+
+
+## Verifique o usuário { #check-the-username }
+
+Aqui está um exemplo mais completo.
+
+Utilize uma dependência para verificar se o usuário e a senha estão corretos.
+
+Para isso, utilize o módulo padrão do Python [`secrets`](https://docs.python.org/3/library/secrets.html) para verificar o usuário e senha.
+
+O `secrets.compare_digest()` necessita receber `bytes` ou `str` que possuem apenas caracteres ASCII (os em inglês). Isso significa que não funcionaria com caracteres como o `á`, como em `Sebastián`.
+
+Para lidar com isso, primeiramente nós convertemos o `username` e o `password` para `bytes`, codificando-os com UTF-8.
+
+Então nós podemos utilizar o `secrets.compare_digest()` para garantir que o `credentials.username` é `"stanleyjobson"`, e que o `credentials.password` é `"swordfish"`.
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[1,12:24] *}
+
+Isso seria parecido com:
+
+```Python
+if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
+ # Return some error
+ ...
+```
+
+Porém, ao utilizar o `secrets.compare_digest()`, isso estará seguro contra um tipo de ataque chamado "timing attacks".
+
+### Ataques de Temporização { #timing-attacks }
+
+Mas o que é um "timing attack"?
+
+Vamos imaginar que alguns invasores estão tentando adivinhar o usuário e a senha.
+
+E eles enviam uma requisição com um usuário `johndoe` e uma senha `love123`.
+
+Então o código Python em sua aplicação seria equivalente a algo como:
+
+```Python
+if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Mas no exato momento que o Python compara o primeiro `j` em `johndoe` contra o primeiro `s` em `stanleyjobson`, ele retornará `False`, porque ele já sabe que aquelas duas strings não são a mesma, pensando que "não existe a necessidade de desperdiçar mais poder computacional comparando o resto das letras". E a sua aplicação dirá "Usuário ou senha incorretos".
+
+Então os invasores vão tentar com o usuário `stanleyjobsox` e a senha `love123`.
+
+E a sua aplicação faz algo como:
+
+```Python
+if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+O Python terá que comparar todo o `stanleyjobso` tanto em `stanleyjobsox` como em `stanleyjobson` antes de perceber que as strings não são a mesma. Então isso levará alguns microssegundos a mais para retornar "Usuário ou senha incorretos".
+
+#### O tempo para responder ajuda os invasores { #the-time-to-answer-helps-the-attackers }
+
+Neste ponto, ao perceber que o servidor demorou alguns microssegundos a mais para enviar o retorno "Usuário ou senha incorretos", os invasores irão saber que eles acertaram _alguma coisa_, algumas das letras iniciais estavam certas.
+
+E eles podem tentar de novo sabendo que provavelmente é algo mais parecido com `stanleyjobsox` do que com `johndoe`.
+
+#### Um ataque "profissional" { #a-professional-attack }
+
+Claro, os invasores não tentariam tudo isso de forma manual, eles escreveriam um programa para fazer isso, possivelmente com milhares ou milhões de testes por segundo. E obteriam apenas uma letra a mais por vez.
+
+Mas fazendo isso, em alguns minutos ou horas os invasores teriam adivinhado o usuário e senha corretos, com a "ajuda" da nossa aplicação, apenas usando o tempo levado para responder.
+
+#### Corrija com o `secrets.compare_digest()` { #fix-it-with-secrets-compare-digest }
+
+Mas em nosso código já estamos utilizando o `secrets.compare_digest()`.
+
+Resumindo, levará o mesmo tempo para comparar `stanleyjobsox` com `stanleyjobson` do que comparar `johndoe` com `stanleyjobson`. E o mesmo para a senha.
+
+Deste modo, ao utilizar `secrets.compare_digest()` no código de sua aplicação, ela estará a salvo contra toda essa gama de ataques de segurança.
+
+### Retorne o erro { #return-the-error }
+
+Após detectar que as credenciais estão incorretas, retorne um `HTTPException` com o status 401 (o mesmo retornado quando nenhuma credencial foi informada) e adicione o cabeçalho `WWW-Authenticate` para fazer com que o navegador mostre o prompt de login novamente:
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[26:30] *}
diff --git a/docs/pt/docs/advanced/security/index.md b/docs/pt/docs/advanced/security/index.md
new file mode 100644
index 0000000000000..b5ced914a79c0
--- /dev/null
+++ b/docs/pt/docs/advanced/security/index.md
@@ -0,0 +1,19 @@
+# Segurança Avançada { #advanced-security }
+
+## Funcionalidades Adicionais { #additional-features }
+
+Existem algumas funcionalidades adicionais para lidar com segurança além das cobertas em [Tutorial - Guia de Usuário: Segurança](../../tutorial/security/index.md).
+
+/// tip | Dica
+
+As próximas seções **não são necessariamente "avançadas"**.
+
+E é possível que para o seu caso de uso, a solução está em uma delas.
+
+///
+
+## Leia o Tutorial primeiro { #read-the-tutorial-first }
+
+As próximas seções pressupõem que você já leu o principal [Tutorial - Guia de Usuário: Segurança](../../tutorial/security/index.md).
+
+Todas elas são baseadas nos mesmos conceitos, mas permitem algumas funcionalidades extras.
diff --git a/docs/pt/docs/advanced/security/oauth2-scopes.md b/docs/pt/docs/advanced/security/oauth2-scopes.md
new file mode 100644
index 0000000000000..7ea61ad60e3c4
--- /dev/null
+++ b/docs/pt/docs/advanced/security/oauth2-scopes.md
@@ -0,0 +1,274 @@
+# Escopos OAuth2 { #oauth2-scopes }
+
+Você pode utilizar escopos do OAuth2 diretamente com o **FastAPI**, eles são integrados para funcionar perfeitamente.
+
+Isso permitiria que você tivesse um sistema de permissionamento mais refinado, seguindo o padrão do OAuth2 integrado na sua aplicação OpenAPI (e as documentações da API).
+
+OAuth2 com escopos é o mecanismo utilizado por muitos provedores de autenticação, como o Facebook, Google, GitHub, Microsoft, X (Twitter), etc. Eles utilizam isso para prover permissões específicas para os usuários e aplicações.
+
+Toda vez que você "se autentica com" Facebook, Google, GitHub, Microsoft, X (Twitter), aquela aplicação está utilizando o OAuth2 com escopos.
+
+Nesta seção, você verá como gerenciar a autenticação e autorização com os mesmos escopos do OAuth2 em sua aplicação **FastAPI**.
+
+/// warning | Atenção
+
+Isso é uma seção mais ou menos avançada. Se você está apenas começando, você pode pular.
+
+Você não necessariamente precisa de escopos do OAuth2, e você pode lidar com autenticação e autorização da maneira que você achar melhor.
+
+Mas o OAuth2 com escopos pode ser integrado de maneira fácil em sua API (com OpenAPI) e a sua documentação de API.
+
+No entanto, você ainda aplica estes escopos, ou qualquer outro requisito de segurança/autorização, conforme necessário, em seu código.
+
+Em muitos casos, OAuth2 com escopos pode ser um exagero.
+
+Mas se você sabe que precisa, ou está curioso, continue lendo.
+
+///
+
+## Escopos OAuth2 e OpenAPI { #oauth2-scopes-and-openapi }
+
+A especificação OAuth2 define "escopos" como uma lista de strings separadas por espaços.
+
+O conteúdo de cada uma dessas strings pode ter qualquer formato, mas não devem possuir espaços.
+
+Estes escopos representam "permissões".
+
+No OpenAPI (e.g. os documentos da API), você pode definir "esquemas de segurança".
+
+Quando um desses esquemas de segurança utiliza OAuth2, você pode também declarar e utilizar escopos.
+
+Cada "escopo" é apenas uma string (sem espaços).
+
+Eles são normalmente utilizados para declarar permissões de segurança específicas, como por exemplo:
+
+* `users:read` or `users:write` são exemplos comuns.
+* `instagram_basic` é utilizado pelo Facebook / Instagram.
+* `https://www.googleapis.com/auth/drive` é utilizado pelo Google.
+
+/// info | Informação
+
+No OAuth2, um "escopo" é apenas uma string que declara uma permissão específica necessária.
+
+Não importa se ela contém outros caracteres como `:` ou se ela é uma URL.
+
+Estes detalhes são específicos da implementação.
+
+Para o OAuth2, eles são apenas strings.
+
+///
+
+## Visão global { #global-view }
+
+Primeiro, vamos olhar rapidamente as partes que mudam dos exemplos do **Tutorial - Guia de Usuário** para [OAuth2 com Senha (e hash), Bearer com tokens JWT](../../tutorial/security/oauth2-jwt.md). Agora utilizando escopos OAuth2:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}
+
+Agora vamos revisar essas mudanças passo a passo.
+
+## Esquema de segurança OAuth2 { #oauth2-security-scheme }
+
+A primeira mudança é que agora nós estamos declarando o esquema de segurança OAuth2 com dois escopos disponíveis, `me` e `items`.
+
+O parâmetro `scopes` recebe um `dict` contendo cada escopo como chave e a descrição como valor:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *}
+
+Pelo motivo de estarmos declarando estes escopos, eles aparecerão nos documentos da API quando você se autenticar/autorizar.
+
+E você poderá selecionar quais escopos você deseja dar acesso: `me` e `items`.
+
+Este é o mesmo mecanismo utilizado quando você adiciona permissões enquanto se autentica com o Facebook, Google, GitHub, etc:
+
+
+
+## Token JWT com escopos { #jwt-token-with-scopes }
+
+Agora, modifique a *operação de rota* do token para retornar os escopos solicitados.
+
+Nós ainda estamos utilizando o mesmo `OAuth2PasswordRequestForm`. Ele inclui a propriedade `scopes` com uma `list` de `str`, com cada escopo que ele recebeu na requisição.
+
+E nós retornamos os escopos como parte do token JWT.
+
+/// danger | Cuidado
+
+Para manter as coisas simples, aqui nós estamos apenas adicionando os escopos recebidos diretamente ao token.
+
+Porém em sua aplicação, por segurança, você deveria garantir que você apenas adiciona os escopos que o usuário possui permissão de fato, ou aqueles que você predefiniu.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}
+
+## Declare escopos em *operações de rota* e dependências { #declare-scopes-in-path-operations-and-dependencies }
+
+Agora nós declaramos que a *operação de rota* para `/users/me/items/` exige o escopo `items`.
+
+Para isso, nós importamos e utilizamos `Security` de `fastapi`.
+
+Você pode utilizar `Security` para declarar dependências (assim como `Depends`), porém o `Security` também recebe o parâmetro `scopes` com uma lista de escopos (strings).
+
+Neste caso, nós passamos a função `get_current_active_user` como dependência para `Security` (da mesma forma que nós faríamos com `Depends`).
+
+Mas nós também passamos uma `list` de escopos, neste caso com apenas um escopo: `items` (poderia ter mais).
+
+E a função de dependência `get_current_active_user` também pode declarar subdependências, não apenas com `Depends`, mas também com `Security`. Ao declarar sua própria função de subdependência (`get_current_user`), e mais requisitos de escopo.
+
+Neste caso, ele requer o escopo `me` (poderia requerer mais de um escopo).
+
+/// note | Nota
+
+Você não necessariamente precisa adicionar diferentes escopos em diferentes lugares.
+
+Nós estamos fazendo isso aqui para demonstrar como o **FastAPI** lida com escopos declarados em diferentes níveis.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}
+
+/// note | Detalhes Técnicos
+
+`Security` é na verdade uma subclasse de `Depends`, e ele possui apenas um parâmetro extra que veremos depois.
+
+Porém ao utilizar `Security` no lugar de `Depends`, o **FastAPI** saberá que ele pode declarar escopos de segurança, utilizá-los internamente, e documentar a API com o OpenAPI.
+
+Mas quando você importa `Query`, `Path`, `Depends`, `Security` entre outros de `fastapi`, eles são na verdade funções que retornam classes especiais.
+
+///
+
+## Utilize `SecurityScopes` { #use-securityscopes }
+
+Agora atualize a dependência `get_current_user`.
+
+Este é o usado pelas dependências acima.
+
+Aqui é onde estamos utilizando o mesmo esquema OAuth2 que nós declaramos antes, declarando-o como uma dependência: `oauth2_scheme`.
+
+Porque esta função de dependência não possui nenhum requerimento de escopo, nós podemos utilizar `Depends` com o `oauth2_scheme`. Nós não precisamos utilizar `Security` quando nós não precisamos especificar escopos de segurança.
+
+Nós também declaramos um parâmetro especial do tipo `SecurityScopes`, importado de `fastapi.security`.
+
+A classe `SecurityScopes` é semelhante à classe `Request` (`Request` foi utilizada para obter o objeto da requisição diretamente).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}
+
+## Utilize os `scopes` { #use-the-scopes }
+
+O parâmetro `security_scopes` será do tipo `SecurityScopes`.
+
+Ele terá a propriedade `scopes` com uma lista contendo todos os escopos requeridos por ele e todas as dependências que utilizam ele como uma subdependência. Isso significa, todos os "dependentes"... pode soar meio confuso, e isso será explicado novamente mais adiante.
+
+O objeto `security_scopes` (da classe `SecurityScopes`) também oferece um atributo `scope_str` com uma única string, contendo os escopos separados por espaços (nós vamos utilizar isso).
+
+Nós criamos uma `HTTPException` que nós podemos reutilizar (`raise`) mais tarde em diversos lugares.
+
+Nesta exceção, nós incluímos os escopos necessários (se houver algum) como uma string separada por espaços (utilizando `scope_str`). Nós colocamos esta string contendo os escopos no cabeçalho `WWW-Authenticate` (isso é parte da especificação).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}
+
+## Verifique o `username` e o formato dos dados { #verify-the-username-and-data-shape }
+
+Nós verificamos que nós obtemos um `username`, e extraímos os escopos.
+
+E depois nós validamos esse dado com o modelo Pydantic (capturando a exceção `ValidationError`), e se nós obtemos um erro ao ler o token JWT ou validando os dados com o Pydantic, nós levantamos a exceção `HTTPException` que criamos anteriormente.
+
+Para isso, nós atualizamos o modelo Pydantic `TokenData` com a nova propriedade `scopes`.
+
+Ao validar os dados com o Pydantic nós podemos garantir que temos, por exemplo, exatamente uma `list` de `str` com os escopos e uma `str` com o `username`.
+
+No lugar de, por exemplo, um `dict`, ou alguma outra coisa, que poderia quebrar a aplicação em algum lugar mais tarde, tornando isso um risco de segurança.
+
+Nós também verificamos que nós temos um usuário com o "*username*", e caso contrário, nós levantamos a mesma exceção que criamos anteriormente.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}
+
+## Verifique os `scopes` { #verify-the-scopes }
+
+Nós verificamos agora que todos os escopos necessários, por essa dependência e todos os dependentes (incluindo as *operações de rota*) estão incluídas nos escopos fornecidos pelo token recebido, caso contrário, levantamos uma `HTTPException`.
+
+Para isso, nós utilizamos `security_scopes.scopes`, que contém uma `list` com todos esses escopos como uma `str`.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}
+
+## Árvore de dependência e escopos { #dependency-tree-and-scopes }
+
+Vamos rever novamente essa árvore de dependência e os escopos.
+
+Como a dependência `get_current_active_user` possui uma subdependência em `get_current_user`, o escopo `"me"` declarado em `get_current_active_user` será incluído na lista de escopos necessários em `security_scopes.scopes` passado para `get_current_user`.
+
+A própria *operação de rota* também declara o escopo, `"items"`, então ele também estará na lista de `security_scopes.scopes` passado para o `get_current_user`.
+
+Aqui está como a hierarquia de dependências e escopos parecem:
+
+* A *operação de rota* `read_own_items` possui:
+ * Escopos necessários `["items"]` com a dependência:
+ * `get_current_active_user`:
+ * A função de dependência `get_current_active_user` possui:
+ * Escopos necessários `["me"]` com a dependência:
+ * `get_current_user`:
+ * A função de dependência `get_current_user` possui:
+ * Nenhum escopo necessário.
+ * Uma dependência utilizando `oauth2_scheme`.
+ * Um parâmetro `security_scopes` do tipo `SecurityScopes`:
+ * Este parâmetro `security_scopes` possui uma propriedade `scopes` com uma `list` contendo todos estes escopos declarados acima, então:
+ * `security_scopes.scopes` terá `["me", "items"]` para a *operação de rota* `read_own_items`.
+ * `security_scopes.scopes` terá `["me"]` para a *operação de rota* `read_users_me`, porque ela declarou na dependência `get_current_active_user`.
+ * `security_scopes.scopes` terá `[]` (nada) para a *operação de rota* `read_system_status`, porque ele não declarou nenhum `Security` com `scopes`, e sua dependência, `get_current_user`, não declara nenhum `scopes` também.
+
+/// tip | Dica
+
+A coisa importante e "mágica" aqui é que `get_current_user` terá diferentes listas de `scopes` para validar para cada *operação de rota*.
+
+Tudo depende dos `scopes` declarados em cada *operação de rota* e cada dependência da árvore de dependências para aquela *operação de rota* específica.
+
+///
+
+## Mais detalhes sobre `SecurityScopes` { #more-details-about-securityscopes }
+
+Você pode utilizar `SecurityScopes` em qualquer lugar, e em diversos lugares. Ele não precisa estar na dependência "raiz".
+
+Ele sempre terá os escopos de segurança declarados nas dependências atuais de `Security` e todos os dependentes para **aquela** *operação de rota* **específica** e **aquela** árvore de dependência **específica**.
+
+Porque o `SecurityScopes` terá todos os escopos declarados por dependentes, você pode utilizá-lo para verificar se o token possui os escopos necessários em uma função de dependência central, e depois declarar diferentes requisitos de escopo em diferentes *operações de rota*.
+
+Todos eles serão validados independentemente para cada *operação de rota*.
+
+## Verifique { #check-it }
+
+Se você abrir os documentos da API, você pode autenticar e especificar quais escopos você quer autorizar.
+
+
+
+Se você não selecionar nenhum escopo, você terá "autenticado", mas quando você tentar acessar `/users/me/` ou `/users/me/items/`, você vai obter um erro dizendo que você não possui as permissões necessárias. Você ainda poderá acessar `/status/`.
+
+E se você selecionar o escopo `me`, mas não o escopo `items`, você poderá acessar `/users/me/`, mas não `/users/me/items/`.
+
+Isso é o que aconteceria se uma aplicação terceira que tentou acessar uma dessas *operações de rota* com um token fornecido por um usuário, dependendo de quantas permissões o usuário forneceu para a aplicação.
+
+## Sobre integrações de terceiros { #about-third-party-integrations }
+
+Neste exemplo nós estamos utilizando o fluxo de senha do OAuth2.
+
+Isso é apropriado quando nós estamos autenticando em nossa própria aplicação, provavelmente com o nosso próprio "*frontend*".
+
+Porque nós podemos confiar nele para receber o `username` e o `password`, pois nós controlamos isso.
+
+Mas se nós estamos construindo uma aplicação OAuth2 que outros poderiam conectar (i.e., se você está construindo um provedor de autenticação equivalente ao Facebook, Google, GitHub, etc.) você deveria utilizar um dos outros fluxos.
+
+O mais comum é o fluxo implícito.
+
+O mais seguro é o fluxo de código, mas ele é mais complexo para implementar, pois ele necessita mais passos. Como ele é mais complexo, muitos provedores terminam sugerindo o fluxo implícito.
+
+/// note | Nota
+
+É comum que cada provedor de autenticação nomeie os seus fluxos de forma diferente, para torná-lo parte de sua marca.
+
+Mas no final, eles estão implementando o mesmo padrão OAuth2.
+
+///
+
+O **FastAPI** inclui utilitários para todos esses fluxos de autenticação OAuth2 em `fastapi.security.oauth2`.
+
+## `Security` em decoradores de `dependencies` { #security-in-decorator-dependencies }
+
+Da mesma forma que você pode definir uma `list` de `Depends` no parâmetro `dependencies` do decorador (como explicado em [Dependências em decoradores de operações de rota](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md)), você também pode utilizar `Security` com escopos lá.
diff --git a/docs/pt/docs/advanced/settings.md b/docs/pt/docs/advanced/settings.md
new file mode 100644
index 0000000000000..371d5711bdfcb
--- /dev/null
+++ b/docs/pt/docs/advanced/settings.md
@@ -0,0 +1,302 @@
+# Configurações e Variáveis de Ambiente { #settings-and-environment-variables }
+
+Em muitos casos, sua aplicação pode precisar de configurações externas, por exemplo chaves secretas, credenciais de banco de dados, credenciais para serviços de e-mail, etc.
+
+A maioria dessas configurações é variável (pode mudar), como URLs de banco de dados. E muitas podem ser sensíveis, como segredos.
+
+Por esse motivo, é comum fornecê-las em variáveis de ambiente lidas pela aplicação.
+
+/// tip | Dica
+
+Para entender variáveis de ambiente, você pode ler [Variáveis de Ambiente](../environment-variables.md).
+
+///
+
+## Tipagem e validação { #types-and-validation }
+
+Essas variáveis de ambiente só conseguem lidar com strings de texto, pois são externas ao Python e precisam ser compatíveis com outros programas e com o resto do sistema (e até com diferentes sistemas operacionais, como Linux, Windows, macOS).
+
+Isso significa que qualquer valor lido em Python a partir de uma variável de ambiente será uma `str`, e qualquer conversão para um tipo diferente ou validação precisa ser feita em código.
+
+## Pydantic `Settings` { #pydantic-settings }
+
+Felizmente, o Pydantic fornece uma ótima utilidade para lidar com essas configurações vindas de variáveis de ambiente com [Pydantic: Settings management](https://docs.pydantic.dev/latest/concepts/pydantic_settings/).
+
+### Instalar `pydantic-settings` { #install-pydantic-settings }
+
+Primeiro, certifique-se de criar seu [ambiente virtual](../virtual-environments.md), ativá-lo e então instalar o pacote `pydantic-settings`:
+
+
+
+E então, abra a documentação para a sub-aplicação, em [http://127.0.0.1:8000/subapi/docs](http://127.0.0.1:8000/subapi/docs).
+
+Você verá a documentação automática da API para a sub-aplicação, incluindo apenas suas próprias _operações de rota_, todas sob o prefixo de sub-path correto `/subapi`:
+
+
+
+Se você tentar interagir com qualquer uma das duas interfaces de usuário, elas funcionarão corretamente, porque o navegador será capaz de se comunicar com cada aplicação ou sub-aplicação específica.
+
+### Detalhes Técnicos: `root_path` { #technical-details-root-path }
+
+Quando você monta uma sub-aplicação como descrito acima, o FastAPI se encarrega de comunicar o path de montagem para a sub-aplicação usando um mecanismo da especificação ASGI chamado `root_path`.
+
+Dessa forma, a sub-aplicação saberá usar esse prefixo de path para a interface de documentação.
+
+E a sub-aplicação também poderia ter suas próprias sub-aplicações montadas e tudo funcionaria corretamente, porque o FastAPI lida com todos esses `root_path`s automaticamente.
+
+Você aprenderá mais sobre o `root_path` e como usá-lo explicitamente na seção sobre [Atrás de um Proxy](behind-a-proxy.md).
diff --git a/docs/pt/docs/advanced/templates.md b/docs/pt/docs/advanced/templates.md
new file mode 100644
index 0000000000000..d3a8ad9b5035e
--- /dev/null
+++ b/docs/pt/docs/advanced/templates.md
@@ -0,0 +1,126 @@
+# Templates { #templates }
+
+Você pode usar qualquer template engine com o **FastAPI**.
+
+Uma escolha comum é o Jinja2, o mesmo usado pelo Flask e outras ferramentas.
+
+Existem utilitários para configurá-lo facilmente que você pode usar diretamente em sua aplicação **FastAPI** (fornecidos pelo Starlette).
+
+## Instalar dependências { #install-dependencies }
+
+Certifique-se de criar um [ambiente virtual](../virtual-environments.md), ativá-lo e instalar `jinja2`:
+
+
+
+Você pode digitar mensagens na caixa de entrada e enviá-las:
+
+
+
+E sua aplicação **FastAPI** com WebSockets responderá de volta:
+
+
+
+Você pode enviar (e receber) muitas mensagens:
+
+
+
+E todas elas usarão a mesma conexão WebSocket.
+
+## Usando `Depends` e outros { #using-depends-and-others }
+
+Nos endpoints WebSocket você pode importar do `fastapi` e usar:
+
+* `Depends`
+* `Security`
+* `Cookie`
+* `Header`
+* `Path`
+* `Query`
+
+Eles funcionam da mesma forma que para outros endpoints FastAPI/*operações de rota*:
+
+{* ../../docs_src/websockets_/tutorial002_an_py310.py hl[68:69,82] *}
+
+/// info | Informação
+
+Como isso é um WebSocket, não faz muito sentido levantar uma `HTTPException`, em vez disso levantamos uma `WebSocketException`.
+
+Você pode usar um código de fechamento dos [códigos válidos definidos na especificação](https://tools.ietf.org/html/rfc6455#section-7.4.1).
+
+///
+
+### Tente os WebSockets com dependências { #try-the-websockets-with-dependencies }
+
+Execute sua aplicação:
+
+
+
+## Lidando com desconexões e múltiplos clientes { #handling-disconnections-and-multiple-clients }
+
+Quando uma conexão WebSocket é fechada, o `await websocket.receive_text()` levantará uma exceção `WebSocketDisconnect`, que você pode então capturar e lidar como neste exemplo.
+
+{* ../../docs_src/websockets_/tutorial003_py310.py hl[79:81] *}
+
+Para testar:
+
+* Abra o aplicativo com várias abas do navegador.
+* Escreva mensagens a partir delas.
+* Então feche uma das abas.
+
+Isso levantará a exceção `WebSocketDisconnect`, e todos os outros clientes receberão uma mensagem como:
+
+```
+Client #1596980209979 left the chat
+```
+
+/// tip | Dica
+
+O app acima é um exemplo mínimo e simples para demonstrar como lidar e transmitir mensagens para várias conexões WebSocket.
+
+Mas tenha em mente que, como tudo é manipulado na memória, em uma única list, ele só funcionará enquanto o processo estiver em execução e só funcionará com um único processo.
+
+Se você precisa de algo fácil de integrar com o FastAPI, mas que seja mais robusto, suportado por Redis, PostgreSQL ou outros, verifique [encode/broadcaster](https://github.com/encode/broadcaster).
+
+///
+
+## Mais informações { #more-info }
+
+Para aprender mais sobre as opções, verifique a documentação do Starlette para:
+
+* [A classe `WebSocket`](https://www.starlette.dev/websockets/).
+* [Manipulação de WebSockets baseada em classes](https://www.starlette.dev/endpoints/#websocketendpoint).
diff --git a/docs/pt/docs/advanced/wsgi.md b/docs/pt/docs/advanced/wsgi.md
new file mode 100644
index 0000000000000..110bba05380ae
--- /dev/null
+++ b/docs/pt/docs/advanced/wsgi.md
@@ -0,0 +1,51 @@
+# Adicionando WSGI - Flask, Django, entre outros { #including-wsgi-flask-django-others }
+
+Como você viu em [Subaplicações - Montagens](sub-applications.md) e [Atrás de um Proxy](behind-a-proxy.md), você pode montar aplicações WSGI.
+
+Para isso, você pode utilizar o `WSGIMiddleware` para encapsular a sua aplicação WSGI, como por exemplo Flask, Django, etc.
+
+## Usando `WSGIMiddleware` { #using-wsgimiddleware }
+
+/// info | Informação
+
+Isso requer instalar `a2wsgi`, por exemplo com `pip install a2wsgi`.
+
+///
+
+Você precisa importar o `WSGIMiddleware` de `a2wsgi`.
+
+Em seguida, encapsule a aplicação WSGI (e.g. Flask) com o middleware.
+
+E então monte isso sob um path.
+
+{* ../../docs_src/wsgi/tutorial001_py310.py hl[1,3,23] *}
+
+/// note | Nota
+
+Anteriormente, recomendava-se usar `WSGIMiddleware` de `fastapi.middleware.wsgi`, mas agora está descontinuado.
+
+É aconselhável usar o pacote `a2wsgi` em seu lugar. O uso permanece o mesmo.
+
+Apenas certifique-se de que o pacote `a2wsgi` está instalado e importe `WSGIMiddleware` corretamente de `a2wsgi`.
+
+///
+
+## Confira { #check-it }
+
+Agora, todas as requisições sob o path `/v1/` serão manipuladas pela aplicação Flask.
+
+E o resto será manipulado pelo **FastAPI**.
+
+Se você rodar a aplicação e ir até [http://localhost:8000/v1/](http://localhost:8000/v1/), você verá o retorno do Flask:
+
+```txt
+Hello, World from Flask!
+```
+
+E se você for até [http://localhost:8000/v2](http://localhost:8000/v2), você verá o retorno do FastAPI:
+
+```JSON
+{
+ "message": "Hello World"
+}
+```
diff --git a/docs/pt/docs/alternatives.md b/docs/pt/docs/alternatives.md
index 61ee4f9000e10..828561542d3e6 100644
--- a/docs/pt/docs/alternatives.md
+++ b/docs/pt/docs/alternatives.md
@@ -1,85 +1,94 @@
-# Alternativas, Inspiração e Comparações
+# Alternativas, Inspiração e Comparações { #alternatives-inspiration-and-comparisons }
-O que inspirou **FastAPI**, como ele se compara a outras alternativas e o que FastAPI aprendeu delas.
+O que inspirou o **FastAPI**, como ele se compara às alternativas e o que ele aprendeu com elas.
-## Introdução
+## Introdução { #intro }
-**FastAPI** não poderia existir se não fosse pelos trabalhos anteriores de outras pessoas.
+**FastAPI** não existiria se não fosse pelo trabalho anterior de outras pessoas.
-Houveram tantas ferramentas criadas que ajudaram a inspirar sua criação.
+Houve muitas ferramentas criadas antes que ajudaram a inspirar sua criação.
-Tenho evitado criar um novo framework por anos. Primeiramente tentei resolver todos os recursos cobertos pelo **FastAPI** utilizando muitos frameworks diferentes, plug-ins e ferramentas.
+Tenho evitado criar um novo framework por vários anos. Primeiro tentei resolver todas as funcionalidades cobertas pelo **FastAPI** utilizando muitos frameworks, plug-ins e ferramentas diferentes.
-Mas em algum ponto, não houve outra opção senão criar algo que fornecesse todos esses recursos, pegando as melhores idéias de ferramentas anteriores, e combinando eles da melhor forma possível, utilizando recursos da linguagem que não estavam disponíveis antes (_Type Hints_ no Python 3.6+).
+Mas em algum momento, não havia outra opção senão criar algo que fornecesse todos esses recursos, pegando as melhores ideias de ferramentas anteriores e combinando-as da melhor maneira possível, usando funcionalidades da linguagem que nem sequer estavam disponíveis antes (anotações de tipo no Python 3.6+).
-## Ferramentas anteriores
+## Ferramentas anteriores { #previous-tools }
-### Django
+### [Django](https://www.djangoproject.com/) { #django }
-É o framework mais popular e largamente confiável. É utilizado para construir sistemas como o _Instagram_.
+É o framework Python mais popular e amplamente confiável. É utilizado para construir sistemas como o Instagram.
-É bem acoplado com banco de dados relacional (como MySQL ou PostgreSQL), então, tendo um banco de dados NoSQL (como Couchbase, MongoDB, Cassandra etc) como a principal ferramenta de armazenamento não é muito fácil.
+É relativamente bem acoplado com bancos de dados relacionais (como MySQL ou PostgreSQL), então, ter um banco de dados NoSQL (como Couchbase, MongoDB, Cassandra, etc.) como mecanismo principal de armazenamento não é muito fácil.
-Foi criado para gerar HTML no _backend_, não para criar APIs utilizando um _frontend_ moderno (como React, Vue.js e Angular) ou por outros sistemas (como dispositivos IoT) comunicando com ele.
+Foi criado para gerar o HTML no backend, não para criar APIs usadas por um frontend moderno (como React, Vue.js e Angular) ou por outros sistemas (como dispositivos IoT) comunicando com ele.
-### Django REST Framework
+### [Django REST Framework](https://www.django-rest-framework.org/) { #django-rest-framework }
-Django REST framework foi criado para ser uma caixa de ferramentas flexível para construção de APIs web utilizando Django por baixo, para melhorar suas capacidades de API.
+Django REST framework foi criado para ser uma caixa de ferramentas flexível para construção de APIs Web utilizando Django por baixo, para melhorar suas capacidades de API.
-Ele é utilizado por muitas companhias incluindo Mozilla, Red Hat e Eventbrite.
+Ele é utilizado por muitas empresas incluindo Mozilla, Red Hat e Eventbrite.
-Ele foi um dos primeiros exemplos de **documentação automática de API**, e essa foi especificamente uma das primeiras idéias que inspirou "a busca por" **FastAPI**.
+Foi um dos primeiros exemplos de **documentação automática de API**, e essa foi especificamente uma das primeiras ideias que inspirou "a busca por" **FastAPI**.
-!!! note "Nota"
- Django REST Framework foi criado por Tom Christie. O mesmo criador de Starlette e Uvicorn, nos quais **FastAPI** é baseado.
+/// note | Nota
-!!! check "**FastAPI** inspirado para"
- Ter uma documentação automática da API em interface web.
+Django REST Framework foi criado por Tom Christie. O mesmo criador de Starlette e Uvicorn, nos quais **FastAPI** é baseado.
-### Flask
+///
-Flask é um "microframework", não inclui integração com banco de dados nem muitas das coisas que vêm por padrão no Django.
+/// check | Inspirou o **FastAPI** a
-Sua simplicidade e flexibilidade permitem fazer coisas como utilizar bancos de dados NoSQL como principal sistema de armazenamento de dados.
+Ter uma interface web de documentação automática da API.
-Por ser tão simples, é relativamente intuitivo de aprender, embora a documentação esteja de forma mais técnica em alguns pontos.
+///
-Ele é comumente utilizado por outras aplicações que não necessariamente precisam de banco de dados, gerenciamento de usuários, ou algum dos muitos recursos que já vem instalados no Django. Embora muitos desses recursos possam ser adicionados com plug-ins.
+### [Flask](https://flask.palletsprojects.com) { #flask }
-Esse desacoplamento de partes, e sendo um "microframework" que pode ser extendido para cobrir exatamente o que é necessário era um recurso chave que eu queria manter.
+Flask é um "microframework", não inclui integrações com banco de dados nem muitas das coisas que vêm por padrão no Django.
-Dada a simplicidade do Flask, parecia uma ótima opção para construção de APIs. A próxima coisa a procurar era um "Django REST Framework" para Flask.
+Essa simplicidade e flexibilidade permitem fazer coisas como utilizar bancos de dados NoSQL como o principal sistema de armazenamento de dados.
-!!! check "**FastAPI** inspirado para"
- Ser um microframework. Fazer ele fácil para misturar e combinar com ferramentas e partes necessárias.
+Por ser muito simples, é relativamente intuitivo de aprender, embora a documentação se torne um pouco técnica em alguns pontos.
- Ser simples e com sistema de roteamento fácil de usar.
+Ele também é comumente utilizado por outras aplicações que não necessariamente precisam de banco de dados, gerenciamento de usuários, ou qualquer uma das muitas funcionalidades que já vêm prontas no Django. Embora muitas dessas funcionalidades possam ser adicionadas com plug-ins.
-### Requests
+Esse desacoplamento de partes, e ser um "microframework" que pode ser estendido para cobrir exatamente o que é necessário era uma funcionalidade chave que eu queria manter.
-**FastAPI** não é uma alternativa para **Requests**. O escopo deles é muito diferente.
+Dada a simplicidade do Flask, ele parecia uma boa opção para construção de APIs. A próxima coisa a encontrar era um "Django REST Framework" para Flask.
-Na verdade é comum utilizar Requests *dentro* de uma aplicação FastAPI.
+/// check | Inspirou o **FastAPI** a
-Ainda assim, FastAPI pegou alguma inspiração do Requests.
+Ser um microframework. Tornar fácil misturar e combinar as ferramentas e partes necessárias.
-**Requests** é uma biblioteca para interagir com APIs (como um cliente), enquanto **FastAPI** é uma biblioteca para *construir* APIs (como um servidor).
+Ter um sistema de roteamento simples e fácil de usar.
-Eles estão, mais ou menos, em pontas opostas, um complementando o outro.
+///
-Requests tem um projeto muito simples e intuitivo, fácil de usar, com padrões sensíveis. Mas ao mesmo tempo, é muito poderoso e customizável.
+### [Requests](https://requests.readthedocs.io) { #requests }
+
+**FastAPI** na verdade não é uma alternativa ao **Requests**. O escopo deles é muito diferente.
+
+Na verdade, é comum utilizar Requests dentro de uma aplicação FastAPI.
+
+Ainda assim, o FastAPI tirou bastante inspiração do Requests.
+
+**Requests** é uma biblioteca para interagir com APIs (como um cliente), enquanto **FastAPI** é uma biblioteca para construir APIs (como um servidor).
+
+Eles estão, mais ou menos, em pontas opostas, complementando-se.
+
+Requests tem um design muito simples e intuitivo, é muito fácil de usar, com padrões sensatos. Mas ao mesmo tempo, é muito poderoso e personalizável.
É por isso que, como dito no site oficial:
> Requests é um dos pacotes Python mais baixados de todos os tempos
-O jeito de usar é muito simples. Por exemplo, para fazer uma requisição `GET`, você deveria escrever:
+O jeito de usar é muito simples. Por exemplo, para fazer uma requisição `GET`, você escreveria:
```Python
response = requests.get("http://example.com/some/url")
```
-A contra-parte da aplicação FastAPI, *rota de operação*, poderia parecer como:
+A contra-parte na aplicação FastAPI, a operação de rota, poderia ficar assim:
```Python hl_lines="1"
@app.get("/some/url")
@@ -89,325 +98,388 @@ def read_url():
Veja as similaridades em `requests.get(...)` e `@app.get(...)`.
-!!! check "**FastAPI** inspirado para"
- * Ter uma API simples e intuitiva.
- * Utilizar nomes de métodos HTTP (operações) diretamente, de um jeito direto e intuitivo.
- * Ter padrões sensíveis, mas customizações poderosas.
+/// check | Inspirou o **FastAPI** a
+
+* Ter uma API simples e intuitiva.
+* Utilizar nomes de métodos HTTP (operações) diretamente, de um jeito direto e intuitivo.
+* Ter padrões sensatos, mas customizações poderosas.
-### Swagger / OpenAPI
+///
-O principal recurso que eu queria do Django REST Framework era a documentação automática da API.
+### [Swagger](https://swagger.io/) / [OpenAPI](https://github.com/OAI/OpenAPI-Specification/) { #swagger-openapi }
-Então eu descobri que existia um padrão para documentar APIs, utilizando JSON (ou YAML, uma extensão do JSON) chamado Swagger.
+A principal funcionalidade que eu queria do Django REST Framework era a documentação automática da API.
-E tinha uma interface web para APIs Swagger já criada. Então, sendo capaz de gerar documentação Swagger para uma API poderia permitir utilizar essa interface web automaticamente.
+Então descobri que existia um padrão para documentar APIs, utilizando JSON (ou YAML, uma extensão do JSON) chamado Swagger.
-Em algum ponto, Swagger foi dado para a Fundação Linux, e foi renomeado OpenAPI.
+E havia uma interface web para APIs Swagger já criada. Então, ser capaz de gerar documentação Swagger para uma API permitiria usar essa interface web automaticamente.
-Isso acontece porquê quando alguém fala sobre a versão 2.0 é comum dizer "Swagger", e para a versão 3+, "OpenAPI".
+Em algum ponto, Swagger foi doado para a Fundação Linux, para ser renomeado OpenAPI.
-!!! check "**FastAPI** inspirado para"
- Adotar e usar um padrão aberto para especificações API, ao invés de algum esquema customizado.
+É por isso que ao falar sobre a versão 2.0 é comum dizer "Swagger", e para a versão 3+ "OpenAPI".
- E integrar ferramentas de interface para usuários baseado nos padrões:
+/// check | Inspirou o **FastAPI** a
- * Swagger UI
- * ReDoc
+Adotar e usar um padrão aberto para especificações de API, em vez de um schema personalizado.
- Esses dois foram escolhidos por serem bem populares e estáveis, mas fazendo uma pesquisa rápida, você pode encontrar dúzias de interfaces alternativas adicionais para OpenAPI (assim você poderá utilizar com **FastAPI**).
+E integrar ferramentas de interface para usuários baseadas nos padrões:
-### Flask REST frameworks
+* [Swagger UI](https://github.com/swagger-api/swagger-ui)
+* [ReDoc](https://github.com/Rebilly/ReDoc)
-Existem vários Flask REST frameworks, mas depois de investir tempo e trabalho investigando eles, eu descobri que muitos estão descontinuados ou abandonados, com alguns tendo questões que fizeram eles inadequados.
+Essas duas foram escolhidas por serem bem populares e estáveis, mas fazendo uma pesquisa rápida, você pode encontrar dúzias de interfaces alternativas adicionais para OpenAPI (que você pode utilizar com **FastAPI**).
-### Marshmallow
+///
-Um dos principais recursos necessários em sistemas API é "serialização" de dados, que é pegar dados do código (Python) e converter eles em alguma coisa que possa ser enviado através da rede. Por exemplo, converter um objeto contendo dados de um banco de dados em um objeto JSON. Converter objetos `datetime` em strings etc.
+### Flask REST frameworks { #flask-rest-frameworks }
-Outro grande recurso necessário nas APIs é validação de dados, certificando que os dados são válidos, dados certos parâmetros. Por exemplo, algum campo é `int`, e não alguma string aleatória. Isso é especialmente útil para dados que estão chegando.
+Existem vários Flask REST frameworks, mas depois de investir tempo e trabalho investigando-os, descobri que muitos estão descontinuados ou abandonados, com diversas questões em aberto que os tornaram inadequados.
+
+### [Marshmallow](https://marshmallow.readthedocs.io/en/stable/) { #marshmallow }
+
+Uma das principais funcionalidades necessárias em sistemas de API é a "serialização" de dados, que é pegar dados do código (Python) e convertê-los em algo que possa ser enviado pela rede. Por exemplo, converter um objeto contendo dados de um banco de dados em um objeto JSON. Converter objetos `datetime` em strings, etc.
+
+Outra grande funcionalidade necessária pelas APIs é a validação de dados, garantindo que os dados são válidos, dados certos parâmetros. Por exemplo, que algum campo seja `int`, e não alguma string aleatória. Isso é especialmente útil para dados de entrada.
Sem um sistema de validação de dados, você teria que realizar todas as verificações manualmente, no código.
-Esses recursos são o que Marshmallow foi construído para fornecer. Ele é uma ótima biblioteca, e eu já utilizei muito antes.
+Essas funcionalidades são o que o Marshmallow foi construído para fornecer. É uma ótima biblioteca, e eu a utilizei bastante antes.
+
+Mas ele foi criado antes de existirem as anotações de tipo do Python. Então, para definir cada schema você precisa utilizar utilitários e classes específicos fornecidos pelo Marshmallow.
+
+/// check | Inspirou o **FastAPI** a
+
+Usar código para definir "schemas" que forneçam, automaticamente, tipos de dados e validação.
+
+///
+
+### [Webargs](https://webargs.readthedocs.io/en/latest/) { #webargs }
+
+Outra grande funcionalidade requerida pelas APIs é o parsing de dados vindos de requisições de entrada.
+
+Webargs é uma ferramenta feita para fornecer isso no topo de vários frameworks, inclusive Flask.
+
+Ele utiliza Marshmallow por baixo para a validação de dados. E foi criado pelos mesmos desenvolvedores.
+
+É uma grande ferramenta e eu também a utilizei bastante, antes de ter o **FastAPI**.
+
+/// info | Informação
+
+Webargs foi criado pelos mesmos desenvolvedores do Marshmallow.
+
+///
+
+/// check | Inspirou o **FastAPI** a
+
+Ter validação automática dos dados de requisições de entrada.
+
+///
-Mas ele foi criado antes da existência do _type hints_ do Python. Então, para definir todo o _schema_ você precisa utilizar específicas ferramentas e classes fornecidas pelo Marshmallow.
+### [APISpec](https://apispec.readthedocs.io/en/stable/) { #apispec }
-!!! check "**FastAPI** inspirado para"
- Usar código para definir "schemas" que forneçam, automaticamente, tipos de dados e validação.
+Marshmallow e Webargs fornecem validação, parsing e serialização como plug-ins.
-### Webargs
+Mas a documentação ainda estava faltando. Então APISpec foi criado.
-Outro grande recurso necessário pelas APIs é a análise de dados vindos de requisições.
+É um plug-in para muitos frameworks (e há um plug-in para Starlette também).
-Webargs é uma ferramente feita para fornecer o que está no topo de vários frameworks, inclusive Flask.
+O jeito como ele funciona é que você escreve a definição do schema usando formato YAML dentro da docstring de cada função que lida com uma rota.
-Ele utiliza Marshmallow por baixo para validação de dados. E ele foi criado pelos mesmos desenvolvedores.
+E ele gera schemas OpenAPI.
-Ele é uma grande ferramenta e eu também a utilizei muito, antes de ter o **FastAPI**.
+É assim como funciona no Flask, Starlette, Responder, etc.
-!!! info
- Webargs foi criado pelos mesmos desenvolvedores do Marshmallow.
+Mas então, temos novamente o problema de ter uma micro-sintaxe, dentro de uma string Python (um grande YAML).
-!!! check "**FastAPI** inspirado para"
- Ter validação automática de dados vindos de requisições.
+O editor não pode ajudar muito com isso. E se modificarmos parâmetros ou schemas do Marshmallow e esquecermos de também modificar aquela docstring em YAML, o schema gerado ficaria obsoleto.
-### APISpec
+/// info | Informação
-Marshmallow e Webargs fornecem validação, análise e serialização como plug-ins.
+APISpec foi criado pelos mesmos desenvolvedores do Marshmallow.
-Mas a documentação ainda está faltando. Então APISpec foi criado.
+///
-APISpec tem plug-ins para muitos frameworks (e tem um plug-in para Starlette também).
+/// check | Inspirou o **FastAPI** a
-O jeito como ele funciona é que você escreve a definição do _schema_ usando formato YAML dentro da _docstring_ de cada função controlando uma rota.
+Dar suporte ao padrão aberto para APIs, OpenAPI.
-E ele gera _schemas_ OpenAPI.
+///
-É assim como funciona no Flask, Starlette, Responder etc.
+### [Flask-apispec](https://flask-apispec.readthedocs.io/en/latest/) { #flask-apispec }
-Mas então, nós temos novamente o problema de ter uma micro-sintaxe, dentro de uma string Python (um grande YAML).
+É um plug-in Flask, que amarra juntos Webargs, Marshmallow e APISpec.
-O editor não poderá ajudar muito com isso. E se nós modificarmos os parâmetros dos _schemas_ do Marshmallow e esquecer de modificar também aquela _docstring_ YAML, o _schema_ gerado pode ficar obsoleto.
+Ele utiliza a informação do Webargs e Marshmallow para gerar automaticamente schemas OpenAPI, usando APISpec.
-!!! info
- APISpec foi criado pelos mesmos desenvolvedores do Marshmallow.
+É uma grande ferramenta, muito subestimada. Deveria ser bem mais popular do que muitos plug-ins Flask por aí. Pode ser devido à sua documentação ser concisa e abstrata demais.
-!!! check "**FastAPI** inspirado para"
- Dar suporte a padrões abertos para APIs, OpenAPI.
+Isso resolveu ter que escrever YAML (outra sintaxe) dentro das docstrings do Python.
-### Flask-apispec
+Essa combinação de Flask, Flask-apispec com Marshmallow e Webargs foi a minha stack de backend favorita até construir o **FastAPI**.
-É um plug-in Flask, que amarra junto Webargs, Marshmallow e APISpec.
+Usá-la levou à criação de vários geradores Flask full-stack. Estas são as principais stacks que eu (e várias equipes externas) tenho utilizado até agora:
-Ele utiliza a informação do Webargs e Marshmallow para gerar automaticamente _schemas_ OpenAPI, usando APISpec.
+* [https://github.com/tiangolo/full-stack](https://github.com/tiangolo/full-stack)
+* [https://github.com/tiangolo/full-stack-flask-couchbase](https://github.com/tiangolo/full-stack-flask-couchbase)
+* [https://github.com/tiangolo/full-stack-flask-couchdb](https://github.com/tiangolo/full-stack-flask-couchdb)
-É uma grande ferramenta, mas muito subestimada. Ela deveria ser um pouco mais popular do que muitos outros plug-ins Flask. É de ser esperado que sua documentação seja bem concisa e abstrata.
+E esses mesmos geradores full-stack foram a base dos [Geradores de Projetos **FastAPI**](project-generation.md).
-Isso resolveu o problema de ter que escrever YAML (outra sintaxe) dentro das _docstrings_ Python.
+/// info | Informação
-Essa combinação de Flask, Flask-apispec com Marshmallow e Webargs foi meu _backend stack_ favorito até construir **FastAPI**.
+Flask-apispec foi criado pelos mesmos desenvolvedores do Marshmallow.
-Usando essa combinação levou a criação de vários geradores Flask _full-stack_. Há muitas _stacks_ que eu (e vários times externos) estou utilizando até agora:
+///
-* https://github.com/tiangolo/full-stack
-* https://github.com/tiangolo/full-stack-flask-couchbase
-* https://github.com/tiangolo/full-stack-flask-couchdb
+/// check | Inspirou o **FastAPI** a
-E esses mesmos geradores _full-stack_ foram a base dos [Geradores de Projetos **FastAPI**](project-generation.md){.internal-link target=_blank}.
+Gerar o schema OpenAPI automaticamente, a partir do mesmo código que define serialização e validação.
-!!! info
- Flask-apispec foi criado pelos mesmos desenvolvedores do Marshmallow.
+///
-!!! check "**FastAPI** inspirado para"
- Gerar _schema_ OpenAPI automaticamente, a partir do mesmo código que define serialização e validação.
+### [NestJS](https://nestjs.com/) (e [Angular](https://angular.io/)) { #nestjs-and-angular }
-### NestJS (and Angular)
+Isso nem é Python, NestJS é um framework NodeJS em JavaScript (TypeScript) inspirado pelo Angular.
-NestJS, que não é nem Python, é um framework NodeJS JavaScript (TypeScript) inspirado pelo Angular.
+Ele alcança algo um tanto similar ao que pode ser feito com Flask-apispec.
-Ele alcança de uma forma similar ao que pode ser feito com o Flask-apispec.
+Ele tem um sistema de injeção de dependência integrado, inspirado pelo Angular 2. É necessário fazer o pré-registro dos "injetáveis" (como todos os sistemas de injeção de dependência que conheço), então, adiciona verbosidade e repetição de código.
-Ele tem um sistema de injeção de dependência integrado, inspirado pelo Angular dois. É necessário fazer o pré-registro dos "injetáveis" (como todos os sistemas de injeção de dependência que conheço), então, adicionando verbosidade e repetição de código.
+Como os parâmetros são descritos com tipos do TypeScript (similares às anotações de tipo do Python), o suporte do editor é muito bom.
-Como os parâmetros são descritos com tipos TypeScript (similar aos _type hints_ do Python), o suporte ao editor é muito bom.
+Mas como os dados do TypeScript não são preservados após a compilação para JavaScript, ele não pode depender dos tipos para definir validação, serialização e documentação ao mesmo tempo. Devido a isso e a algumas decisões de projeto, para obter validação, serialização e geração automática de schema, é necessário adicionar decorators em muitos lugares. Então, ele se torna bastante verboso.
-Mas como os dados TypeScript não são preservados após a compilação para o JavaScript, ele não pode depender dos tipos para definir a validação, serialização e documentação ao mesmo tempo. Devido a isso e a algumas decisões de projeto, para pegar a validação, serialização e geração automática do _schema_, é necessário adicionar decoradores em muitos lugares. Então, ele se torna muito verboso.
+Ele não consegue lidar muito bem com modelos aninhados. Então, se o corpo JSON na requisição for um objeto JSON que contém campos internos que por sua vez são objetos JSON aninhados, ele não consegue ser documentado e validado apropriadamente.
-Ele também não controla modelos aninhados muito bem. Então, se o corpo JSON na requisição for um objeto JSON que contém campos internos que contém objetos JSON aninhados, ele não consegue ser validado e documentado apropriadamente.
+/// check | Inspirou o **FastAPI** a
-!!! check "**FastAPI** inspirado para"
- Usar tipos Python para ter um ótimo suporte do editor.
+Usar tipos do Python para ter um ótimo suporte do editor.
- Ter um sistema de injeção de dependência poderoso. Achar um jeito de minimizar repetição de código.
+Ter um sistema de injeção de dependência poderoso. Encontrar um jeito de minimizar repetição de código.
-### Sanic
+///
-Ele foi um dos primeiros frameworks Python extremamente rápido baseado em `asyncio`. Ele foi feito para ser muito similar ao Flask.
+### [Sanic](https://sanic.readthedocs.io/en/latest/) { #sanic }
-!!! note "Detalhes técnicos"
- Ele utiliza `uvloop` ao invés do '_loop_' `asyncio` padrão do Python. É isso que deixa ele tão rápido.
+Ele foi um dos primeiros frameworks Python extremamente rápidos baseados em `asyncio`. Ele foi feito para ser muito similar ao Flask.
- Ele claramente inspirou Uvicorn e Starlette, que são atualmente mais rápidos que o Sanic em testes de performance abertos.
+/// note | Detalhes Técnicos
-!!! check "**FastAPI** inspirado para"
- Achar um jeito de ter uma performance insana.
+Ele utilizava [`uvloop`](https://github.com/MagicStack/uvloop) em vez do loop `asyncio` padrão do Python. É isso que o deixava tão rápido.
- É por isso que o **FastAPI** é baseado em Starlette, para que ele seja o framework mais rápido disponível (performance testada por terceiros).
+Ele claramente inspirou Uvicorn e Starlette, que atualmente são mais rápidos que o Sanic em benchmarks abertos.
-### Falcon
+///
-Falcon é outro framework Python de alta performance, e é projetado para ser minimalista, e funciona como fundação de outros frameworks como Hug.
+/// check | Inspirou o **FastAPI** a
-Ele usa o padrão anterior para frameworks web Python (WSGI) que é síncrono, então ele não pode controlar _WebSockets_ e outros casos de uso. No entanto, ele também tem uma boa performance.
+Encontrar um jeito de ter uma performance insana.
-Ele é projetado para ter funções que recebem dois parâmetros, uma "requisição" e uma "resposta". Então você "lê" as partes da requisição, e "escreve" partes para a resposta. Devido ao seu design, não é possível declarar parâmetros de requisição e corpos com _type hints_ Python padrão como parâmetros de funções.
+É por isso que o **FastAPI** é baseado em Starlette, pois ela é o framework mais rápido disponível (testado por benchmarks de terceiros).
-Então, validação de dados, serialização e documentação tem que ser feitos no código, não automaticamente. Ou eles terão que ser implementados como um framework acima do Falcon, como o Hug. Essa mesma distinção acontece em outros frameworks que são inspirados pelo design do Falcon, tendo um objeto de requisição e um objeto de resposta como parâmetros.
+///
-!!! check "**FastAPI** inspirado para"
- Achar jeitos de conseguir melhor performance.
+### [Falcon](https://falconframework.org/) { #falcon }
- Juntamente com Hug (como Hug é baseado no Falcon) inspirou **FastAPI** para declarar um parâmetro de `resposta`nas funções.
+Falcon é outro framework Python de alta performance, projetado para ser minimalista, e servir como base para outros frameworks como Hug.
- Embora no FastAPI seja opcional, é utilizado principalmente para configurar cabeçalhos, cookies e códigos de status alternativos.
+Ele é projetado para ter funções que recebem dois parâmetros, uma "request" e uma "response". Então você "lê" partes da requisição, e "escreve" partes para a resposta. Por causa desse design, não é possível declarar parâmetros de requisição e corpos com as anotações de tipo padrão do Python como parâmetros de função.
-### Molten
+Então, validação de dados, serialização e documentação têm que ser feitos no código, não automaticamente. Ou eles têm que ser implementados como um framework acima do Falcon, como o Hug. Essa mesma distinção acontece em outros frameworks inspirados pelo design do Falcon, de ter um objeto de request e um objeto de response como parâmetros.
-Eu descobri Molten nos primeiros estágios da construção do **FastAPI**. E ele tem umas idéias bem similares:
+/// check | Inspirou o **FastAPI** a
-* Baseado em _type hints_ Python.
-* Validação e documentação desses tipos.
-* Sistema de injeção de dependência.
+Encontrar maneiras de obter uma ótima performance.
-Ele não utiliza validação de dados, seriallização e documentação de bibliotecas de terceiros como o Pydantic, ele tem seu prórpio. Então, essas definições de tipo de dados não podem ser reutilizados tão facilmente.
+Juntamente com Hug (como Hug é baseado no Falcon) inspirou **FastAPI** a declarar um parâmetro de `response` nas funções.
-Ele exige um pouco mais de verbosidade nas configurações. E como é baseado no WSGI (ao invés de ASGI), ele não é projetado para ter a vantagem da alta performance fornecida por ferramentas como Uvicorn, Starlette e Sanic.
+Embora no FastAPI seja opcional, é utilizado principalmente para configurar cabeçalhos, cookies e códigos de status alternativos.
-O sistema de injeção de dependência exige pré-registro das dependências e as dependências são resolvidas baseadas nos tipos declarados. Então, não é possível declarar mais do que um "componente" que fornece um certo tipo.
+///
-Rotas são declaradas em um único lugar, usando funções declaradas em outros lugares (ao invés de usar decoradores que possam ser colocados diretamente acima da função que controla o _endpoint_). Isso é mais perto de como o Django faz isso do que como Flask (e Starlette) faz. Ele separa no código coisas que são relativamente amarradas.
+### [Molten](https://moltenframework.com/) { #molten }
-!!! check "**FastAPI** inspirado para"
- Definir validações extras para tipos de dados usando valores "padrão" de atributos dos modelos. Isso melhora o suporte do editor, e não estava disponível no Pydantic antes.
+Eu descobri Molten nos primeiros estágios da construção do **FastAPI**. E ele tem ideias bastante similares:
- Isso na verdade inspirou a atualização de partes do Pydantic, para dar suporte ao mesmo estilo de declaração da validação (toda essa funcionalidade já está disponível no Pydantic).
+* Baseado nas anotações de tipo do Python.
+* Validação e documentação a partir desses tipos.
+* Sistema de Injeção de Dependência.
-### Hug
+Ele não utiliza uma biblioteca de terceiros para validação de dados, serialização e documentação como o Pydantic, ele tem a sua própria. Então, essas definições de tipos de dados não seriam reutilizáveis tão facilmente.
-Hug foi um dos primeiros frameworks a implementar a declaração de tipos de parâmetros usando Python _type hints_. Isso foi uma ótima idéia que inspirou outras ferramentas a fazer o mesmo.
+Ele exige configurações um pouco mais verbosas. E como é baseado em WSGI (em vez de ASGI), ele não é projetado para tirar vantagem da alta performance fornecida por ferramentas como Uvicorn, Starlette e Sanic.
-Ele usou tipos customizados em suas declarações ao invés dos tipos padrão Python, mas mesmo assim foi um grande passo.
+O sistema de injeção de dependência exige pré-registro das dependências e elas são resolvidas com base nos tipos declarados. Então, não é possível declarar mais de um "componente" que forneça um certo tipo.
-Ele também foi um dos primeiros frameworks a gerar um _schema_ customizado declarando a API inteira em JSON.
+As rotas são declaradas em um único lugar, usando funções declaradas em outros lugares (em vez de usar decorators que possam ser colocados diretamente acima da função que lida com o endpoint). Isso é mais próximo de como o Django faz do que de como o Flask (e o Starlette) fazem. Separa no código coisas que são relativamente bem acopladas.
-Ele não era baseado em um padrão como OpenAPI e JSON Schema. Então não poderia ter interação direta com outras ferramentas, como Swagger UI. Mas novamente, era uma idéia muito inovadora.
+/// check | Inspirou o **FastAPI** a
-Hug tinha um incomum, interessante recurso: usando o mesmo framework, é possível criar tanto APIs como CLIs.
+Definir validações extras para tipos de dados usando o valor "padrão" de atributos dos modelos. Isso melhora o suporte do editor, e não estava disponível no Pydantic antes.
-Como é baseado nos padrões anteriores de frameworks web síncronos (WSGI), ele não pode controlar _Websockets_ e outras coisas, embora ele ainda tenha uma alta performance também.
+Isso na verdade inspirou a atualização de partes do Pydantic, para dar suporte ao mesmo estilo de declaração da validação (toda essa funcionalidade já está disponível no Pydantic).
-!!! info
- Hug foi criado por Timothy Crosley, o mesmo criador do `isort`, uma grande ferramenta para ordenação automática de _imports_ em arquivos Python.
+///
-!!! check "Idéias inspiradas para o **FastAPI**"
- Hug inspirou partes do APIStar, e foi uma das ferramentas que eu achei mais promissora, ao lado do APIStar.
+### [Hug](https://github.com/hugapi/hug) { #hug }
- Hug ajudou a inspirar o **FastAPI** a usar _type hints_ do Python para declarar parâmetros, e para gerar um _schema_ definindo a API automaticamente.
+Hug foi um dos primeiros frameworks a implementar a declaração de tipos de parâmetros de API usando anotações de tipo do Python. Isso foi uma ótima ideia que inspirou outras ferramentas a fazer o mesmo.
- Hug inspirou **FastAPI** a declarar um parâmetro de `resposta` em funções para definir cabeçalhos e cookies.
+Ele usou tipos personalizados em suas declarações em vez dos tipos padrão do Python, mas mesmo assim foi um grande passo adiante.
-### APIStar (<= 0.5)
+Ele também foi um dos primeiros frameworks a gerar um schema personalizado declarando a API inteira em JSON.
-Antes de decidir construir **FastAPI** eu encontrei o servidor **APIStar**. Tinha quase tudo que eu estava procurando e tinha um grande projeto.
+Ele não era baseado em um padrão como OpenAPI e JSON Schema. Então não seria simples integrá-lo com outras ferramentas, como Swagger UI. Mas novamente, era uma ideia muito inovadora.
-Ele foi uma das primeiras implementações de um framework usando Python _type hints_ para declarar parâmetros e requisições que eu nunca vi (antes no NestJS e Molten). Eu encontrei ele mais ou menos na mesma época que o Hug. Mas o APIStar utilizava o padrão OpenAPI.
+Ele tem um recurso interessante e incomum: usando o mesmo framework, é possível criar APIs e também CLIs.
-Ele tinha validação de dados automática, serialização de dados e geração de _schema_ OpenAPI baseado nos mesmos _type hints_ em vários locais.
+Como é baseado no padrão anterior para frameworks web Python síncronos (WSGI), ele não consegue lidar com Websockets e outras coisas, embora ainda tenha alta performance também.
-Definições de _schema_ de corpo não utilizavam os mesmos Python _type hints_ como Pydantic, ele era um pouco mais similar ao Marshmallow, então, o suporte ao editor não seria tão bom, ainda assim, APIStar era a melhor opção disponível.
+/// info | Informação
-Ele obteve as melhores performances em testes na época (somente batido por Starlette).
+Hug foi criado por Timothy Crosley, o mesmo criador do [`isort`](https://github.com/timothycrosley/isort), uma ótima ferramenta para ordenar automaticamente imports em arquivos Python.
+
+///
+
+/// check | Ideias que inspiraram o **FastAPI**
+
+Hug inspirou partes do APIStar, e foi uma das ferramentas que achei mais promissoras, ao lado do APIStar.
+
+Hug ajudou a inspirar o **FastAPI** a usar anotações de tipo do Python para declarar parâmetros e para gerar um schema definindo a API automaticamente.
+
+Hug inspirou **FastAPI** a declarar um parâmetro de `response` em funções para definir cabeçalhos e cookies.
+
+///
+
+### [APIStar](https://github.com/encode/apistar) (<= 0.5) { #apistar-0-5 }
+
+Pouco antes de decidir construir o **FastAPI** eu encontrei o servidor **APIStar**. Ele tinha quase tudo o que eu estava procurando e tinha um ótimo design.
+
+Foi uma das primeiras implementações de um framework usando anotações de tipo do Python para declarar parâmetros e requisições que eu já vi (antes do NestJS e Molten). Eu o encontrei mais ou menos na mesma época que o Hug. Mas o APIStar utilizava o padrão OpenAPI.
+
+Ele tinha validação de dados automática, serialização de dados e geração de schema OpenAPI baseadas nas mesmas anotações de tipo em vários locais.
+
+As definições de schema de corpo não utilizavam as mesmas anotações de tipo do Python como o Pydantic, eram um pouco mais similares ao Marshmallow, então o suporte do editor não seria tão bom, ainda assim, APIStar era a melhor opção disponível.
+
+Ele obteve os melhores benchmarks de performance na época (somente ultrapassado por Starlette).
A princípio, ele não tinha uma interface web com documentação automática da API, mas eu sabia que poderia adicionar o Swagger UI a ele.
-Ele tinha um sistema de injeção de dependência. Ele exigia pré-registro dos componentes, como outras ferramentas já discutidas acima. Mas ainda era um grande recurso.
+Ele tinha um sistema de injeção de dependência. Exigia pré-registro dos componentes, como outras ferramentas já discutidas acima. Mas ainda assim era um grande recurso.
-Eu nunca fui capaz de usar ele num projeto inteiro, por não ter integração de segurança, então, eu não pude substituir todos os recursos que eu tinha com os geradores _full-stack_ baseados no Flask-apispec. Eu tive em minha gaveta de projetos a idéia de criar um _pull request_ adicionando essa funcionalidade.
+Eu nunca fui capaz de usá-lo em um projeto completo, pois ele não tinha integração de segurança, então, eu não pude substituir todos os recursos que eu tinha com os geradores full-stack baseados no Flask-apispec. Eu tinha no meu backlog de projetos criar um pull request adicionando essa funcionalidade.
Mas então, o foco do projeto mudou.
-Ele não era mais um framework web API, como o criador precisava focar no Starlette.
+Ele não era mais um framework web de API, pois o criador precisava focar no Starlette.
Agora APIStar é um conjunto de ferramentas para validar especificações OpenAPI, não um framework web.
-!!! info
- APIStar foi criado por Tom Christie. O mesmo cara que criou:
+/// info | Informação
- * Django REST Framework
- * Starlette (no qual **FastAPI** é baseado)
- * Uvicorn (usado por Starlette e **FastAPI**)
+APIStar foi criado por Tom Christie. O mesmo cara que criou:
-!!! check "**FastAPI** inspirado para"
- Existir.
+* Django REST Framework
+* Starlette (no qual **FastAPI** é baseado)
+* Uvicorn (usado por Starlette e **FastAPI**)
- A idéia de declarar múltiplas coisas (validação de dados, serialização e documentação) com os mesmos tipos Python, que ao mesmo tempo fornecesse grande suporte ao editor, era algo que eu considerava uma brilhante idéia.
+///
- E após procurar por um logo tempo por um framework similar e testar muitas alternativas diferentes, APIStar foi a melhor opção disponível.
+/// check | Inspirou o **FastAPI** a
- Então APIStar parou de existir como um servidor e Starlette foi criado, e foi uma nova melhor fundação para tal sistema. Essa foi a inspiração final para construir **FastAPI**.
+Existir.
- Eu considero **FastAPI** um "sucessor espiritual" para o APIStar, evoluindo e melhorando os recursos, sistema de tipagem e outras partes, baseado na aprendizagem de todas essas ferramentas acima.
+A ideia de declarar múltiplas coisas (validação de dados, serialização e documentação) com os mesmos tipos do Python, que ao mesmo tempo fornecessem grande suporte ao editor, era algo que eu considerava uma ideia brilhante.
-## Usados por **FastAPI**
+E após procurar por muito tempo por um framework similar e testar muitas alternativas diferentes, APIStar foi a melhor opção disponível.
-### Pydantic
+Então APIStar deixou de existir como servidor e o Starlette foi criado, sendo uma nova e melhor fundação para tal sistema. Essa foi a inspiração final para construir o **FastAPI**.
-Pydantic é uma biblioteca para definir validação de dados, serialização e documentação (usando JSON Schema) baseado nos Python _type hints_.
+Eu considero o **FastAPI** um "sucessor espiritual" do APIStar, enquanto aprimora e amplia as funcionalidades, o sistema de tipagem e outras partes, baseado nos aprendizados de todas essas ferramentas anteriores.
-Isso faz dele extremamente intuitivo.
+///
-Ele é comparável ao Marshmallow. Embora ele seja mais rápido que Marshmallow em testes de performance. E ele é baseado nos mesmos Python _type hints_, o suporte ao editor é ótimo.
+## Usados por **FastAPI** { #used-by-fastapi }
-!!! check "**FastAPI** usa isso para"
- Controlar toda a validação de dados, serialização de dados e modelo de documentação automática (baseado no JSON Schema).
+### [Pydantic](https://docs.pydantic.dev/) { #pydantic }
- **FastAPI** então pega dados do JSON Schema e coloca eles no OpenAPI, à parte de todas as outras coisas que ele faz.
+Pydantic é uma biblioteca para definir validação de dados, serialização e documentação (usando JSON Schema) com base nas anotações de tipo do Python.
-### Starlette
+Isso o torna extremamente intuitivo.
-Starlette é um framework/caixa de ferramentas ASGI peso leve, o que é ideal para construir serviços assíncronos de alta performance.
+Ele é comparável ao Marshmallow. Embora seja mais rápido que o Marshmallow em benchmarks. E como é baseado nas mesmas anotações de tipo do Python, o suporte do editor é ótimo.
-Ele é muito simples e intuitivo. É projetado para ser extensível facilmente, e ter componentes modulares.
+/// check | **FastAPI** usa isso para
+
+Controlar toda a validação de dados, serialização de dados e documentação automática de modelos (baseada no JSON Schema).
+
+**FastAPI** então pega esses dados do JSON Schema e os coloca no OpenAPI, além de todas as outras coisas que faz.
+
+///
+
+### [Starlette](https://www.starlette.dev/) { #starlette }
+
+Starlette é um framework/caixa de ferramentas ASGI leve, o que é ideal para construir serviços asyncio de alta performance.
+
+Ele é muito simples e intuitivo. É projetado para ser facilmente extensível, e ter componentes modulares.
Ele tem:
* Performance seriamente impressionante.
* Suporte a WebSocket.
-* Suporte a GraphQL.
-* Tarefas de processamento interno por trás dos panos.
+* Tarefas em segundo plano dentro do processo.
* Eventos de inicialização e encerramento.
-* Cliente de testes construído com requests.
-* Respostas CORS, GZip, Arquivos Estáticos, Streaming.
+* Cliente de testes construído com HTTPX.
+* CORS, GZip, Arquivos Estáticos, respostas Streaming.
* Suporte para Sessão e Cookie.
* 100% coberto por testes.
* Código base 100% anotado com tipagem.
-* Dependências complexas Zero.
+* Poucas dependências obrigatórias.
-Starlette é atualmente o mais rápido framework Python testado. Somente ultrapassado pelo Uvicorn, que não é um framework, mas um servidor.
+Starlette é atualmente o framework Python mais rápido testado. Somente ultrapassado pelo Uvicorn, que não é um framework, mas um servidor.
Starlette fornece toda a funcionalidade básica de um microframework web.
-Mas ele não fornece validação de dados automática, serialização e documentação.
+Mas ele não fornece validação de dados automática, serialização ou documentação.
-Essa é uma das principais coisas que **FastAPI** adiciona no topo, tudo baseado em Python _type hints_ (usando Pydantic). Isso, mais o sistema de injeção de dependência, utilidades de segurança, geração de _schema_ OpenAPI, etc.
+Essa é uma das principais coisas que o **FastAPI** adiciona por cima, tudo baseado nas anotações de tipo do Python (usando Pydantic). Isso, mais o sistema de injeção de dependência, utilidades de segurança, geração de schema OpenAPI, etc.
-!!! note "Detalhes Técnicos"
- ASGI é um novo "padrão" sendo desenvolvido pelos membros do time central do Django. Ele ainda não está como "Padrão Python" (PEP), embora eles estejam em processo de fazer isso.
+/// note | Detalhes Técnicos
- No entanto, ele já está sendo utilizado como "padrão" por diversas ferramentas. Isso melhora enormemente a interoperabilidade, como você poderia trocar Uvicorn por qualquer outro servidor ASGI (como Daphne ou Hypercorn), ou você poderia adicionar ferramentas compatíveis com ASGI, como `python-socketio`.
+ASGI é um novo "padrão" sendo desenvolvido por membros do time central do Django. Ele ainda não é um "padrão Python" (uma PEP), embora eles estejam no processo de fazer isso.
-!!! check "**FastAPI** usa isso para"
- Controlar todas as partes web centrais. Adiciona recursos no topo.
+No entanto, ele já está sendo utilizado como "padrão" por diversas ferramentas. Isso melhora enormemente a interoperabilidade, pois você poderia trocar Uvicorn por qualquer outro servidor ASGI (como Daphne ou Hypercorn), ou você poderia adicionar ferramentas compatíveis com ASGI, como `python-socketio`.
- A classe `FastAPI` em si herda `Starlette`.
+///
- Então, qualquer coisa que você faz com Starlette, você pode fazer diretamente com **FastAPI**, pois ele é basicamente um Starlette com esteróides.
+/// check | **FastAPI** usa isso para
-### Uvicorn
+Controlar todas as partes web centrais. Adiciona funcionalidades por cima.
-Uvicorn é um servidor ASGI peso leve, construído com uvloop e httptools.
+A classe `FastAPI` em si herda diretamente da classe `Starlette`.
-Ele não é um framework web, mas sim um servidor. Por exemplo, ele não fornece ferramentas para roteamento por rotas. Isso é algo que um framework como Starlette (ou **FastAPI**) poderia fornecer por cima.
+Então, qualquer coisa que você pode fazer com Starlette, você pode fazer diretamente com o **FastAPI**, pois ele é basicamente um Starlette com esteróides.
+
+///
+
+### [Uvicorn](https://www.uvicorn.dev/) { #uvicorn }
+
+Uvicorn é um servidor ASGI extremamente rápido, construído com uvloop e httptools.
+
+Ele não é um framework web, mas sim um servidor. Por exemplo, ele não fornece ferramentas para roteamento por paths. Isso é algo que um framework como Starlette (ou **FastAPI**) forneceria por cima.
Ele é o servidor recomendado para Starlette e **FastAPI**.
-!!! check "**FastAPI** recomenda isso para"
- O principal servidor web para rodar aplicações **FastAPI**.
+/// check | **FastAPI** o recomenda como
+
+O principal servidor web para rodar aplicações **FastAPI**.
+
+Você também pode usar a opção de linha de comando `--workers` para ter um servidor assíncrono multi-processos.
- Você pode combinar ele com o Gunicorn, para ter um servidor multi-processos assíncrono.
+Verifique mais detalhes na seção [Implantação](deployment/index.md).
- Verifique mais detalhes na seção [Deployment](deployment/index.md){.internal-link target=_blank}.
+///
-## Performance e velocidade
+## Benchmarks e velocidade { #benchmarks-and-speed }
-Para entender, comparar e ver a diferença entre Uvicorn, Starlette e FastAPI, verifique a seção sobre [Benchmarks](benchmarks.md){.internal-link target=_blank}.
+Para entender, comparar e ver a diferença entre Uvicorn, Starlette e FastAPI, verifique a seção sobre [Benchmarks](benchmarks.md).
diff --git a/docs/pt/docs/async.md b/docs/pt/docs/async.md
index be1278a1b3098..fa1e430036d57 100644
--- a/docs/pt/docs/async.md
+++ b/docs/pt/docs/async.md
@@ -1,10 +1,10 @@
-# Concorrência e async / await
+# Concorrência e async / await { #concurrency-and-async-await }
Detalhes sobre a sintaxe `async def` para *funções de operação de rota* e alguns conceitos de código assíncrono, concorrência e paralelismo.
-## Com pressa?
+## Com pressa? { #in-a-hurry }
-TL;DR:
+TL;DR:
Se você estiver utilizando bibliotecas de terceiros que dizem para você chamar as funções com `await`, como:
@@ -12,7 +12,7 @@ Se você estiver utilizando bibliotecas de terceiros que dizem para você chamar
results = await some_library()
```
-Então, declare sua *função de operação de rota* com `async def` como:
+Então, declare suas *funções de operação de rota* com `async def` como:
```Python hl_lines="2"
@app.get('/')
@@ -21,12 +21,15 @@ async def read_results():
return results
```
-!!! note
- Você só pode usar `await` dentro de funções criadas com `async def`.
+/// note | Nota
+
+Você só pode usar `await` dentro de funções criadas com `async def`.
+
+///
---
-Se você está usando biblioteca de terceiros que se comunica com alguma coisa (um banco de dados, uma API, sistema de arquivos etc) e não tem suporte para utilizar `await` (esse é atualmente o caso para a maioria das bibliotecas de banco de dados), então declare suas *funções de operação de rota* normalmente, com apenas `def`, como:
+Se você está usando uma biblioteca de terceiros que se comunica com alguma coisa (um banco de dados, uma API, o sistema de arquivos etc.) e não tem suporte para utilizar `await` (esse é atualmente o caso para a maioria das bibliotecas de banco de dados), então declare suas *funções de operação de rota* normalmente, com apenas `def`, como:
```Python hl_lines="2"
@app.get('/')
@@ -37,7 +40,7 @@ def results():
---
-Se sua aplicação (de alguma forma) não tem que se comunicar com nada mais e tem que esperar que o respondam, use `async def`.
+Se sua aplicação (de alguma forma) não tem que se comunicar com nada mais e esperar que o respondam, use `async def`, mesmo que você não precise usar `await` dentro dela.
---
@@ -49,50 +52,50 @@ Se você simplesmente não sabe, use apenas `def`.
De qualquer forma, em ambos os casos acima, FastAPI irá trabalhar assincronamente e ser extremamente rápido.
-Seguindo os passos acima, ele será capaz de fazer algumas otimizações de performance.
+Mas, seguindo os passos acima, ele será capaz de fazer algumas otimizações de performance.
-## Detalhes Técnicos
+## Detalhes Técnicos { #technical-details }
-Versões modernas de Python tem suporte para **"código assíncrono"** usando algo chamado **"corrotinas"**, com sintaxe **`async` e `await`**.
+Versões modernas de Python têm suporte para **"código assíncrono"** usando algo chamado **"corrotinas"**, com sintaxe **`async` e `await`**.
-Vamos ver aquela frase por partes na seção abaixo:
+Vamos ver aquela frase por partes nas seções abaixo:
* **Código assíncrono**
* **`async` e `await`**
* **Corrotinas**
-## Código assíncrono
+## Código assíncrono { #asynchronous-code }
-Código assíncrono apenas significa que a linguagem 💬 tem um jeito de dizer para o computador / programa 🤖 que em certo ponto, ele 🤖 terá que esperar por *algo* para finalizar em outro lugar. Vamos dizer que esse *algo* seja chamado "arquivo lento" 📝.
+Código assíncrono apenas significa que a linguagem 💬 tem um jeito de dizer para o computador / programa 🤖 que em certo ponto do código, ele 🤖 terá que esperar *algo* finalizar em outro lugar. Vamos dizer que esse *algo* seja chamado "arquivo lento" 📝.
-Então, durante esse tempo, o computador pode ir e fazer outro trabalho, enquanto o "arquivo lento" 📝 termine.
+Então, durante esse tempo, o computador pode ir e fazer outro trabalho, enquanto o "arquivo lento" 📝 termina.
-Então o computador / programa 🤖 irá voltar toda hora que tiver uma chance porquê ele ainda está esperando o "arquivo lento", ou ele 🤖 nunca irá terminar todo o trabalho que tem até esse ponto. E ele 🤖 irá ver se alguma das tarefas que estava esperando já terminaram, fazendo o que quer que tinham que fazer.
+Então o computador / programa 🤖 irá voltar sempre que tiver uma chance, seja porque ele está esperando novamente, ou quando ele 🤖 terminar todo o trabalho que tem até esse ponto. E ele 🤖 irá ver se alguma das tarefas que estava esperando já terminaram de fazer o que quer que tinham que fazer.
-Depois, ele 🤖 pega a primeira tarefa para finalizar (vamos dizer, nosso "arquivo lento" 📝) e continua o que ele tem que fazer com isso.
+Depois, ele 🤖 pega a primeira tarefa para finalizar (vamos dizer, nosso "arquivo lento" 📝) e continua o que tem que fazer com ela.
-Esse "esperar por algo" normalmente se refere a operações I/O que são relativamente "lentas" (comparadas a velocidade do processador e da memória RAM), como esperar por:
+Esse "esperar por algo" normalmente se refere a operações I/O que são relativamente "lentas" (comparadas à velocidade do processador e da memória RAM), como esperar por:
* dados do cliente para serem enviados através da rede
-* dados enviados pelo seu programa para serem recebidos pelo clente através da rede
-* conteúdo de um arquivo no disco pra ser lido pelo sistema e entregar ao seu programa
+* dados enviados pelo seu programa serem recebidos pelo cliente através da rede
+* conteúdo de um arquivo no disco ser lido pelo sistema e entregue ao seu programa
* conteúdo que seu programa deu ao sistema para ser escrito no disco
-* uma operação remota API
-* uma operação no banco de dados para finalizar
-* uma solicitação no banco de dados esperando o retorno do resultado
+* uma operação em uma API remota
+* uma operação no banco de dados finalizar
+* uma solicitação no banco de dados retornar o resultado
* etc.
-Enquanto o tempo de execução é consumido mais pela espera das operações I/O, essas operações são chamadas de operações "limitadas por I/O".
+Quanto o tempo de execução é consumido majoritariamente pela espera de operações I/O, essas operações são chamadas operações "limitadas por I/O".
-Isso é chamado de "assíncrono" porquê o computador / programa não tem que ser "sincronizado" com a tarefa lenta, esperando pelo exato momento que a tarefa finalize, enquanto não faz nada, para ser capaz de pegar o resultado da tarefa e dar continuidade ao trabalho.
+Isso é chamado de "assíncrono" porque o computador / programa não tem que ser "sincronizado" com a tarefa lenta, esperando pelo momento exato em que a tarefa finaliza, enquanto não faz nada, para ser capaz de pegar o resultado da tarefa e dar continuidade ao trabalho.
-Ao invés disso, sendo um sistema "assíncrono", uma vez finalizada, a tarefa pode esperar um pouco (alguns microssegundos) para que o computador / programa finalize o que quer que esteja fazendo,e então volte para pegar o resultado e continue trabalhando com ele.
+Ao invés disso, sendo um sistema "assíncrono", uma vez finalizada, a tarefa pode esperar na fila um pouco (alguns microssegundos) para que o computador / programa finalize o que quer que esteja fazendo, e então volte para pegar o resultado e continue trabalhando com ele.
-Para "síncrono" (contrário de "assíncrono") também é utilizado o termo "sequencial", porquê o computador / programa segue todos os passos, na sequência, antes de trocar para uma tarefa diferente, mesmo se alguns passos envolvam esperar.
+Para "síncrono" (contrário de "assíncrono") também é utilizado o termo "sequencial", porquê o computador / programa segue todos os passos, em sequência, antes de trocar para uma tarefa diferente, mesmo se alguns passos envolvam esperar.
-### Concorrência e hambúrgueres
+### Concorrência e hambúrgueres { #concurrency-and-burgers }
-Essa idéia de código **assíncrono** descrito acima é algo às vezes chamado de **"concorrência"**. E é diferente de **"paralelismo"**.
+Essa ideia de código **assíncrono** descrita acima é às vezes chamada de **"concorrência"**. Isso é diferente de **"paralelismo"**.
**Concorrência** e **paralelismo** ambos são relacionados a "diferentes coisas acontecendo mais ou menos ao mesmo tempo".
@@ -100,121 +103,157 @@ Mas os detalhes entre *concorrência* e *paralelismo* são bem diferentes.
Para ver essa diferença, imagine a seguinte história sobre hambúrgueres:
-### Hambúrgueres concorrentes
+### Hambúrgueres concorrentes { #concurrent-burgers }
+
+Você vai com seu _crush_ na lanchonete, e fica na fila enquanto o caixa pega os pedidos das pessoas na sua frente. 😍
+
+
+
+Então chega a sua vez, você pede dois saborosos hambúrgueres para você e seu _crush_. 🍔🍔
-Você vai com seu _crush_ :heart_eyes: na lanchonete, fica na fila enquanto o caixa pega os pedidos das pessoas na sua frente.
+
-Então chega a sua vez, você pede dois saborosos hambúrgueres para você e seu _crush_ :heart_eyes:.
+O caixa diz alguma coisa para o cozinheiro na cozinha para que eles saibam que têm que preparar seus hambúrgueres (mesmo que ele esteja atualmente preparando os lanches dos outros clientes).
-Você paga.
+
-O caixa diz alguma coisa para o cara na cozinha para que ele tenha que preparar seus hambúrgueres (mesmo embora ele esteja preparando os lanches dos outros clientes).
+Você paga. 💸
O caixa te entrega seu número de chamada.
-Enquanto você espera, você vai com seu _crush_ :heart_eyes: e pega uma mesa, senta e conversa com seu _crush_ :heart_eyes: por um bom tempo (como seus hambúrgueres são muito saborosos, leva um tempo para serem preparados).
+
+
+Enquanto você espera, você vai com seu _crush_ e pega uma mesa, senta e conversa com seu _crush_ por um bom tempo (já que seus hambúrgueres são muito saborosos, e leva um tempo para serem preparados).
+
+Já que você está sentado na mesa com seu _crush_, esperando os hambúrgueres, você pode passar esse tempo admirando o quão lindo, maravilhoso e esperto é seu _crush_ ✨😍✨.
+
+
+
+Enquanto espera e conversa com seu _crush_, de tempos em tempos, você verifica o número da chamada exibido no balcão para ver se já é sua vez.
-Enquanto você está sentado na mesa com seu _crush_ :heart_eyes:, esperando os hambúrgueres, você pode gastar o tempo admirando como lindo, maravilhoso e esperto é seu _crush_ :heart_eyes:.
+Então em algum momento, é finalmente sua vez. Você vai ao balcão, pega seus hambúrgueres e volta para a mesa.
-Enquanto espera e conversa com seu _crush_ :heart_eyes:, de tempos em tempos, você verifica o número de chamada exibido no balcão para ver se já é sua vez.
+
-Então a certo ponto, é finalmente sua vez. Você vai no balcão, pega seus hambúrgueres e volta para a mesa.
+Você e seu _crush_ comem os hambúrgueres e aproveitam o tempo. ✨
-Você e seu _crush_ :heart_eyes: comem os hambúrgueres e aproveitam o tempo.
+
+
+/// info | Informação
+
+Belas ilustrações de [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨
+
+///
---
-Imagine que você seja o computador / programa nessa história.
+Imagine que você seja o computador / programa 🤖 nessa história.
+
+Enquanto você está na fila, você está somente ocioso 😴, esperando por sua vez, sem fazer nada muito "produtivo". Mas a fila é rápida porque o caixa só está pegando os pedidos (não os preparando), então está tudo bem.
-Enquanto você está na fila, tranquilo, esperando por sua vez, não está fazendo nada "produtivo". Mas a fila é rápida porquê o caixa só está pegando os pedidos, então está tudo bem.
+Então, quando é sua vez, você faz trabalho realmente "produtivo", você processa o menu, decide o que quer, pega a escolha de seu _crush_, paga, verifica se entregou o cartão ou a cédula correta, verifica se foi cobrado corretamente, verifica se seu pedido está correto etc.
-Então, quando é sua vez, você faz o trabalho "produtivo" de verdade, você processa o menu, decide o que quer, pega a escolha de seu _crush_ :heart_eyes:, paga, verifica se entregou o valor correto em dinheiro ou cartão de crédito, verifica se foi cobrado corretamente, verifica se seu pedido está correto etc.
+Mas então, embora você ainda não tenha os hambúrgueres, seu trabalho no caixa está "pausado" ⏸, porque você tem que esperar 🕙 seus hambúrgueres ficarem prontos.
-Mas então, embora você ainda não tenha os hambúrgueres, seu trabalho no caixa está "pausado", porquê você tem que esperar seus hambúrgueres estarem prontos.
+Contudo, à medida que você se afasta do balcão e senta na mesa, com um número para sua chamada, você pode trocar 🔀 sua atenção para seu _crush_, e "trabalhar" ⏯ 🤓 nisso. Então você está novamente fazendo algo muito "produtivo", como flertar com seu _crush_ 😍.
-Mas enquanto você se afasta do balcão e senta na mesa com o número da sua chamada, você pode trocar sua atenção para seu _crush_ :heart_eyes:, e "trabalhar" nisso. Então você está novamente fazendo algo muito "produtivo", como flertar com seu _crush_ :heart_eyes:.
+Então o caixa 💁 diz que "seus hambúrgueres estão prontos" colocando seu número no balcão, mas você não corre que nem um maluco imediatamente quando o número exibido é o seu. Você sabe que ninguém irá roubar seus hambúrgueres porque você tem o seu número da chamada, e os outros têm os deles.
-Então o caixa diz que "seus hambúrgueres estão prontos" colocando seu número no balcão, mas você não corre que nem um maluco imediatamente quando o número exibido é o seu. Você sabe que ninguém irá roubar seus hambúrgueres porquê você tem o número de chamada, e os outros tem os números deles.
+Então você espera seu _crush_ terminar a história que estava contando (terminar o trabalho atual ⏯ / tarefa sendo processada 🤓), sorri gentilmente e diz que você está indo buscar os hambúrgueres ⏸.
-Então você espera que seu _crush_ :heart_eyes: termine a história que estava contando (terminar o trabalho atual / tarefa sendo processada), sorri gentilmente e diz que você está indo buscar os hambúrgueres.
+Então você vai ao balcão 🔀, para a tarefa inicial que agora está finalizada ⏯, pega os hambúrgueres, agradece, e leva-os para a mesa. Isso finaliza esse passo / tarefa da interação com o balcão ⏹. Isso, por sua vez, cria uma nova tarefa, a de "comer hambúrgueres" 🔀 ⏯, mas a tarefa anterior de "pegar os hambúrgueres" já está finalizada ⏹.
-Então você vai no balcão, para a tarefa inicial que agora está finalizada, pega os hambúrgueres, e leva para a mesa. Isso finaliza esse passo / tarefa da interação com o balcão. Agora é criada uma nova tarefa, "comer hambúrgueres", mas a tarefa anterior, "pegar os hambúrgueres" já está finalizada.
+### Hambúrgueres paralelos { #parallel-burgers }
-### Hambúrgueres paralelos
+Agora vamos imaginar que esses não são "Hambúrgueres Concorrentes", e sim "Hambúrgueres Paralelos".
-Você vai com seu _crush_ :heart_eyes: em uma lanchonete paralela.
+Você vai com seu _crush_ na lanchonete paralela.
-Você fica na fila enquanto alguns (vamos dizer 8) caixas pegam os pedidos das pessoas na sua frente.
+Você fica na fila enquanto vários (vamos dizer 8) caixas que também são cozinheiros pegam os pedidos das pessoas na sua frente.
-Todo mundo antes de você está esperando pelos hambúrgueres estarem prontos antes de deixar o caixa porquê cada um dos 8 caixas vai e prepara o hambúrguer antes de pegar o próximo pedido.
+Todo mundo na sua frente está esperando seus hambúrgueres ficarem prontos antes de deixar o caixa porque cada um dos 8 caixas vai e prepara o hambúrguer logo após receber o pedido, antes de pegar o próximo pedido.
-Então é finalmente sua vez, e pede 2 hambúrgueres muito saborosos para você e seu _crush_ :heart_eyes:.
+
-Você paga.
+Então é finalmente sua vez, você pede 2 hambúrgueres muito saborosos para você e seu _crush_.
+
+Você paga 💸.
+
+
O caixa vai para a cozinha.
-Você espera, na frente do balcão, para que ninguém pegue seus hambúrgueres antes de você, já que não tem números de chamadas.
+Você espera, na frente do balcão 🕙, para que ninguém pegue seus hambúrgueres antes de você, já que não tem números de chamadas.
+
+
+
+Como você e seu _crush_ estão ocupados não permitindo que ninguém passe na frente e pegue seus hambúrgueres assim que estiverem prontos, você não pode dar atenção ao seu _crush_. 😞
-Enquanto você e seu _crush_ :heart_eyes: estão ocupados não permitindo que ninguém passe a frente e pegue seus hambúrgueres assim que estiverem prontos, você não pode dar atenção ao seu _crush_ :heart_eyes:.
+Isso é trabalho "síncrono", você está "sincronizado" com o caixa / cozinheiro 👨🍳. Você tem que esperar 🕙 e estar lá no exato momento que o caixa / cozinheiro 👨🍳 terminar os hambúrgueres e os der a você, ou então, outro alguém pode pegá-los.
-Isso é trabalho "síncrono", você está "sincronizado" com o caixa / cozinheiro. Você tem que esperar e estar lá no exato momento que o caixa / cozinheiro terminar os hambúrgueres e dá-los a você, ou então, outro alguém pode pegá-los.
+
-Então seu caixa / cozinheiro finalmente volta com seus hambúrgueres, depois de um longo tempo esperando por eles em frente ao balcão.
+Então seu caixa / cozinheiro 👨🍳 finalmente volta com seus hambúrgueres, depois de um longo tempo esperando 🕙 por eles em frente ao balcão.
-Você pega seus hambúrgueres e vai para a mesa com seu _crush_ :heart_eyes:.
+
-Vocês comem os hambúrgueres, e o trabalho está terminado.
+Você pega seus hambúrgueres e vai para a mesa com seu _crush_.
-Não houve muita conversa ou flerte já que a maior parte do tempo foi gasto esperando os lanches na frente do balcão.
+Vocês comem os hambúrgueres, e o trabalho está terminado. ⏹
+
+
+
+Não houve muita conversa ou flerte já que a maior parte do tempo foi gasto esperando 🕙 na frente do balcão. 😞
+
+/// info | Informação
+
+Belas ilustrações de [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨
+
+///
---
-Nesse cenário dos hambúrgueres paralelos, você é um computador / programa com dois processadores (você e seu _crush_ :heart_eyes:), ambos esperando e dedicando a atenção de estar "esperando no balcão" por um bom tempo.
+Nesse cenário dos hambúrgueres paralelos, você é um computador / programa 🤖 com dois processadores (você e seu _crush_), ambos esperando 🕙 e dedicando sua atenção ⏯ "esperando no balcão" 🕙 por um bom tempo.
-A lanchonete paralela tem 8 processadores (caixas / cozinheiros). Enquanto a lanchonete dos hambúrgueres concorrentes tinham apenas 2 (um caixa e um cozinheiro).
+A lanchonete paralela tem 8 processadores (caixas / cozinheiros), enquanto a lanchonete dos hambúrgueres concorrentes tinha apenas 2 (um caixa e um cozinheiro).
-Ainda assim, a última experiência não foi a melhor.
+Ainda assim, a experiência final não foi a melhor. 😞
---
-Essa poderia ser a história paralela equivalente aos hambúrgueres.
+Essa seria o equivalente paralelo à história dos hambúrgueres. 🍔
Para um exemplo "mais real", imagine um banco.
-Até recentemente, a maioria dos bancos tinha muitos caixas e uma grande fila.
+Até recentemente, a maioria dos bancos tinham muitos caixas 👨💼👨💼👨💼👨💼 e uma grande fila 🕙🕙🕙🕙🕙🕙🕙🕙.
-Todos os caixas fazendo todo o trabalho, um cliente após o outro.
+Todos os caixas fazendo todo o trabalho, um cliente após o outro 👨💼⏯.
-E você tinha que esperar na fila por um longo tempo ou poderia perder a vez.
+E você tinha que esperar 🕙 na fila por um longo tempo ou poderia perder a vez.
-Você provavelmente não gostaria de levar seu _crush_ :heart_eyes: com você para um rolezinho no banco.
+Você provavelmente não gostaria de levar seu _crush_ 😍 com você para um rolezinho no banco 🏦.
-### Conclusão dos hambúrgueres
+### Conclusão dos hambúrgueres { #burger-conclusion }
-Nesse cenário dos "hambúrgueres com seu _crush_ :heart_eyes:", como tem muita espera, faz mais sentido ter um sistema concorrente.
+Nesse cenário dos "hambúrgueres com seu _crush_", como tem muita espera, faz mais sentido ter um sistema concorrente ⏸🔀⏯.
Esse é o caso da maioria das aplicações web.
-Geralmente são muitos usuários, e seu servidor está esperando pelas suas conexões não tão boas para enviar as requisições.
-
-E então esperando novamente pelas respostas voltarem.
+Muitos, muitos usuários, mas seu servidor está esperando 🕙 pela sua conexão não tão boa enviar suas requisições.
-Essa "espera" é medida em microssegundos, e ainda assim, somando tudo, é um monte de espera no final.
+E então esperando 🕙 novamente as respostas voltarem.
-Por isso que faz muito mais sentido utilizar código assíncrono para APIs web.
+Essa "espera" 🕙 é medida em microssegundos, mas ainda assim, somando tudo, é um monte de espera no final.
-A maioria dos frameworks Python existentes mais populares (incluindo Flask e Django) foram criados antes que os novos recursos assíncronos existissem em Python. Então, os meios que eles podem ser colocados em produção para suportar execução paralela mais a forma antiga de execução assíncrona não são tão poderosos quanto as novas capacidades.
+Por isso que faz bastante sentido utilizar código assíncrono ⏸🔀⏯ para APIs web.
-Mesmo embora a especificação principal para web assíncrono em Python (ASGI) foi desenvolvida no Django, para adicionar suporte para WebSockets.
-
-Esse tipo de assincronicidade é o que fez NodeJS popular (embora NodeJS não seja paralelo) e que essa seja a força do Go como uma linguagem de programa.
+Esse tipo de assincronicidade é o que fez NodeJS popular (embora NodeJS não seja paralelo) e essa é a força do Go como uma linguagem de programação.
E esse é o mesmo nível de performance que você tem com o **FastAPI**.
-E como você pode ter paralelismo e sincronicidade ao mesmo tempo, você tem uma maior performance do que a maioria dos frameworks NodeJS testados e lado a lado com Go, que é uma linguagem compilada próxima ao C (tudo graças ao Starlette).
+E como você pode ter paralelismo e assincronicidade ao mesmo tempo, você tem uma maior performance do que a maioria dos frameworks NodeJS testados e lado a lado com Go, que é uma linguagem compilada, mais próxima ao C [(tudo graças ao Starlette)](https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=query&l=zijmkf-1).
-### Concorrência é melhor que paralelismo?
+### Concorrência é melhor que paralelismo? { #is-concurrency-better-than-parallelism }
Não! Essa não é a moral da história.
@@ -222,64 +261,62 @@ Concorrência é diferente de paralelismo. E é melhor em cenários **específic
Então, para equilibrar tudo, imagine a seguinte historinha:
-> Você tem que limpar uma grande casa suja.
+> Você tem que limpar uma casa grande e suja.
*Sim, essa é toda a história*.
---
-Não há espera em lugar algum, apenas um monte de trabalho para ser feito, em múltiplos cômodos da casa.
+Não há espera 🕙 em lugar algum, apenas um monte de trabalho para ser feito, em múltiplos cômodos da casa.
-Você poderia ter chamadas como no exemplo dos hambúrgueres, primeiro a sala de estar, então a cozinha, mas você não está esperando por nada, apenas limpar e limpar, as chamadas não afetariam em nada.
+Você poderia ter turnos como no exemplo dos hambúrgueres, primeiro a sala de estar, então a cozinha, mas como você não está esperando por nada, apenas limpando e limpando, as chamadas não afetariam em nada.
-Levaria o mesmo tempo para finalizar com ou sem chamadas (concorrência) e você teria feito o mesmo tanto de trabalho.
+Levaria o mesmo tempo para finalizar com ou sem turnos (concorrência) e você teria feito o mesmo tanto de trabalho.
Mas nesse caso, se você trouxesse os 8 ex-caixas / cozinheiros / agora-faxineiros, e cada um deles (mais você) pudessem dividir a casa para limpá-la, vocês fariam toda a limpeza em **paralelo**, com a ajuda extra, e terminariam muito mais cedo.
Nesse cenário, cada um dos faxineiros (incluindo você) poderia ser um processador, fazendo a sua parte do trabalho.
-E a maior parte do tempo de execução é tomada por trabalho (ao invés de ficar esperando), e o trabalho em um computador é feito pela CPU, que podem gerar problemas que são chamados de "limite de CPU".
+E a maior parte do tempo de execução é tomada por trabalho real (ao invés de ficar esperando), e o trabalho em um computador é feito pela CPU. Eles chamam esses problemas de "limitados por CPU".
---
-Exemplos comuns de limite de CPU são coisas que exigem processamento matemático complexo.
+Exemplos comuns de operações limitadas por CPU são coisas que exigem processamento matemático complexo.
Por exemplo:
* **Processamento de áudio** ou **imagem**
-* **Visão do Computador**: uma imagem é composta por milhões de pixels, cada pixel tem 3 valores (cores, processamento que normalmente exige alguma computação em todos esses pixels ao mesmo tempo)
-
-* **Machine Learning**: Normalmente exige muita multiplicação de matrizes e vetores. Pense numa grande folha de papel com números e multiplicando todos eles juntos e ao mesmo tempo.
+* **Visão Computacional**: uma imagem é composta por milhões de pixels, cada pixel tem 3 valores / cores, processar isso normalmente exige alguma computação em todos esses pixels ao mesmo tempo
+* **Aprendizado de Máquina**: Normalmente exige muita multiplicação de matrizes e vetores. Pense numa grande planilha com números e em multiplicar todos eles juntos e ao mesmo tempo.
+* **Deep Learning**: Esse é um subcampo do Aprendizado de Máquina, então, o mesmo se aplica. A diferença é que não há apenas uma grande planilha com números para multiplicar, mas um grande conjunto delas, e em muitos casos, você utiliza um processador especial para construir e/ou usar esses modelos.
-* **Deep Learning**: Esse é um subcampo do Machine Learning, então o mesmo se aplica. A diferença é que não há apenas uma grande folha de papel com números para multiplicar, mas um grande conjunto de folhas de papel, e em muitos casos, você utiliza um processador especial para construir e/ou usar modelos.
-
-### Concorrência + Paralelismo: Web + Machine learning
+### Concorrência + Paralelismo: Web + Aprendizado de Máquina { #concurrency-parallelism-web-machine-learning }
Com **FastAPI** você pode levar a vantagem da concorrência que é muito comum para desenvolvimento web (o mesmo atrativo de NodeJS).
-Mas você também pode explorar os benefícios do paralelismo e multiprocessamento (tendo múltiplos processadores rodando em paralelo) para trabalhos pesados que geram **limite de CPU** como aqueles em sistemas de Machine Learning.
+Mas você também pode explorar os benefícios do paralelismo e multiprocessamento (tendo múltiplos processadores rodando em paralelo) para trabalhos **limitados por CPU** como aqueles em sistemas de Aprendizado de Máquina.
-Isso, mais o simples fato que Python é a principal linguagem para **Data Science**, Machine Learning e especialmente Deep Learning, faz do FastAPI uma ótima escolha para APIs web e aplicações com Data Science / Machine Learning (entre muitas outras).
+Isso, somado ao simples fato que Python é a principal linguagem para **Data Science**, Aprendizado de Máquina e especialmente Deep Learning, faz do FastAPI uma ótima escolha para APIs web e aplicações com Data Science / Aprendizado de Máquina (entre muitas outras).
-Para ver como alcançar esse paralelismo em produção veja a seção sobre [Deployment](deployment.md){.internal-link target=_blank}.
+Para ver como alcançar esse paralelismo em produção veja a seção sobre [Implantação](deployment/index.md).
-## `async` e `await`
+## `async` e `await` { #async-and-await }
-Versões modernas do Python tem um modo muito intuitivo para definir código assíncrono. Isso faz parecer normal o código "sequencial" e fazer o "esperar" para você nos momentos certos.
+Versões modernas do Python têm um modo muito intuitivo para definir código assíncrono. Isso faz parecer do mesmo jeito do código normal "sequencial" e fazer a "espera" para você nos momentos certos.
-Quando tem uma operação que exigirá espera antes de dar os resultados e tem suporte para esses recursos Python, você pode escrever assim:
+Quando tem uma operação que exigirá espera antes de dar os resultados e tem suporte para esses novos recursos do Python, você pode escrever assim:
```Python
burgers = await get_burgers(2)
```
-A chave aqui é o `await`. Ele diz ao Python que ele tem que esperar por `get_burgers(2)` para finalizar suas coisas antes de armazenar os resultados em `burgers`. Com isso, o Python saberá que ele pode ir e fazer outras coisas nesse meio tempo (como receber outra requisição).
+A chave aqui é o `await`. Ele diz ao Python que ele tem que esperar ⏸ por `get_burgers(2)` finalizar suas coisas 🕙 antes de armazenar os resultados em `burgers`. Com isso, o Python saberá que ele pode ir e fazer outras coisas 🔀 ⏯ nesse meio tempo (como receber outra requisição).
Para o `await` funcionar, tem que estar dentro de uma função que suporte essa assincronicidade. Para fazer isso, apenas declare a função com `async def`:
```Python hl_lines="1"
async def get_burgers(number: int):
- # Fazer alguma coisa assíncrona para criar os hambúrgueres
+ # Faz alguma coisa assíncrona para criar os hambúrgueres
return burgers
```
@@ -292,9 +329,9 @@ def get_sequential_burgers(number: int):
return burgers
```
-Com `async def`, o Python sabe que, dentro dessa função, tem que estar ciente das expressões `await`, e que isso pode "pausar" a execução dessa função, e poderá fazer outra coisa antes de voltar.
+Com `async def`, o Python sabe que, dentro dessa função, ele deve estar ciente das expressões `await`, e que isso poderá "pausar" ⏸ a execução dessa função, e ir fazer outra coisa 🔀 antes de voltar.
-Quando você quiser chamar uma função `async def`, você tem que "esperar". Então, isso não funcionará:
+Quando você quiser chamar uma função `async def`, você tem que "esperar" ela. Então, isso não funcionará:
```Python
# Isso não irá funcionar, porquê get_burgers foi definido com: async def
@@ -305,26 +342,36 @@ burgers = get_burgers(2)
Então, se você está usando uma biblioteca que diz que você pode chamá-la com `await`, você precisa criar as *funções de operação de rota* com `async def`, como em:
-```Python hl_lines="2 3"
+```Python hl_lines="2-3"
@app.get('/burgers')
async def read_burgers():
burgers = await get_burgers(2)
return burgers
```
-### Mais detalhes técnicos
+### Mais detalhes técnicos { #more-technical-details }
Você deve ter observado que `await` pode ser usado somente dentro de funções definidas com `async def`.
-Mas ao mesmo tempo, funções definidas com `async def` tem que ser aguardadas. Então, funções com `async def` pdem ser chamadas somente dentro de funções definidas com `async def` também.
+Mas ao mesmo tempo, funções definidas com `async def` têm que ser "aguardadas". Então, funções com `async def` podem ser chamadas somente dentro de funções definidas com `async def` também.
Então, sobre o ovo e a galinha, como você chama a primeira função async?
Se você estivar trabalhando com **FastAPI** não terá que se preocupar com isso, porquê essa "primeira" função será a sua *função de operação de rota*, e o FastAPI saberá como fazer a coisa certa.
-Mas se você quiser usar `async` / `await` sem FastAPI, verifique a documentação oficial Python.
+Mas se você quiser usar `async` / `await` sem FastAPI, você também pode fazê-lo.
+
+### Escreva seu próprio código assíncrono { #write-your-own-async-code }
+
+Starlette (e **FastAPI**) são baseados no [AnyIO](https://anyio.readthedocs.io/en/stable/), o que o torna compatível com ambos o [asyncio](https://docs.python.org/3/library/asyncio-task.html) da biblioteca padrão do Python, e o [Trio](https://trio.readthedocs.io/en/stable/).
+
+Em particular, você pode usar diretamente o [AnyIO](https://anyio.readthedocs.io/en/stable/) para seus casos de uso avançados de concorrência que requerem padrões mais avançados no seu próprio código.
-### Outras formas de código assíncrono
+E até se você não estiver utilizando FastAPI, você também pode escrever suas próprias aplicações assíncronas com o [AnyIO](https://anyio.readthedocs.io/en/stable/) por ser altamente compatível e ganhar seus benefícios (e.g. *concorrência estruturada*).
+
+Eu criei outra biblioteca em cima do AnyIO, como uma fina camada acima, para melhorar um pouco as anotações de tipo e obter melhor **preenchimento automático**, **erros inline**, etc. Ela também possui uma introdução amigável e um tutorial para ajudar você a **entender** e escrever **seu próprio código async**: [Asyncer](https://asyncer.tiangolo.com/). Seria particularmente útil se você precisar **combinar código async com código regular** (bloqueador/síncrono).
+
+### Outras formas de código assíncrono { #other-forms-of-asynchronous-code }
Esse estilo de usar `async` e `await` é relativamente novo na linguagem.
@@ -334,52 +381,55 @@ Essa mesma sintaxe (ou quase a mesma) foi também incluída recentemente em vers
Mas antes disso, controlar código assíncrono era bem mais complexo e difícil.
-Nas versões anteriores do Python, você poderia utilizar threads ou Gevent. Mas o código é um pouco mais complexo de entender, debugar, e pensar sobre.
+Nas versões anteriores do Python, você poderia utilizar threads ou [Gevent](https://www.gevent.org/). Mas o código é bem mais complexo de entender, debugar, e pensar sobre.
+
+Nas versões anteriores do NodeJS / Navegador JavaScript, você utilizaria "callbacks". O que leva ao "inferno do callback".
+
+## Corrotinas { #coroutines }
-Nas versões anteriores do NodeJS / Navegador JavaScript, você poderia utilizar "callbacks". O que leva ao inferno do callback.
+**Corrotina** é apenas um jeito bonitinho para a coisa que é retornada de uma função `async def`. O Python sabe que é algo como uma função, que pode começar e que vai terminar em algum ponto, mas que pode ser pausada ⏸ internamente também, sempre que tiver um `await` dentro dela.
-## Corrotinas
+Mas toda essa funcionalidade de código assíncrono com `async` e `await` é muitas vezes resumida como usando "corrotinas". É comparável ao principal recurso chave do Go, a "Gorrotina".
-**Corrotina** é apenas um jeito bonitinho para a coisa que é retornada de uma função `async def`. O Python sabe que é uma função que pode começar e terminar em algum ponto, mas que pode ser pausada internamente também, sempre que tiver um `await` dentro dela.
+## Conclusão { #conclusion }
-Mas toda essa funcionalidade de código assíncrono com `async` e `await` é muitas vezes resumida como "corrotina". É comparável ao principal recurso chave do Go, a "Gorotina".
+Vamos ver a mesma frase de cima:
-## Conclusão
+> Versões modernas do Python têm suporte para **"código assíncrono"** usando algo chamado **"corrotinas"**, com sintaxe **`async` e `await`**.
-Vamos ver a mesma frase com o conteúdo cima:
+Isso pode fazer mais sentido agora. ✨
-> Versões modernas do Python tem suporte para **"código assíncrono"** usando algo chamado **"corrotinas"**, com sintaxe **`async` e `await`**.
+Tudo isso é o que empodera o FastAPI (através do Starlette) e que o faz ter uma performance tão impressionante.
-Isso pode fazer mais sentido agora.
+## Detalhes muito técnicos { #very-technical-details }
-Tudo isso é o que deixa o FastAPI poderoso (através do Starlette) e que o faz ter uma performance impressionante.
+/// warning | Atenção
-## Detalhes muito técnicos
+Você pode provavelmente pular isso.
-!!! warning
- Você pode provavelmente pular isso.
+Esses são detalhes muito técnicos de como **FastAPI** funciona por baixo do capô.
- Esses são detalhes muito técnicos de como **FastAPI** funciona por baixo do capô.
+Se você tem certo conhecimento técnico (corrotinas, threads, blocking etc) e está curioso sobre como o FastAPI controla o `async def` vs normal `def`, vá em frente.
- Se você tem algum conhecimento técnico (corrotinas, threads, blocking etc) e está curioso sobre como o FastAPI controla o `async def` vs normal `def`, vá em frente.
+///
-### Funções de operação de rota
+### Funções de operação de rota { #path-operation-functions }
-Quando você declara uma *função de operação de rota* com `def` normal ao invés de `async def`, ela é rodada em uma threadpool externa que então é aguardada, ao invés de ser chamada diretamente (ela poderia bloquear o servidor).
+Quando você declara uma *função de operação de rota* com `def` normal ao invés de `async def`, ela é rodada em uma threadpool externa que é então aguardada, ao invés de ser chamada diretamente (já que ela bloquearia o servidor).
-Se você está chegando de outro framework assíncrono que não faz o trabalho descrito acima e você está acostumado a definir triviais *funções de operação de rota* com simples `def` para ter um mínimo ganho de performance (cerca de 100 nanosegundos), por favor observe que no **FastAPI** o efeito pode ser bem o oposto. Nesses casos, é melhor usar `async def` a menos que suas *funções de operação de rota* utilizem código que performem bloqueamento IO.
+Se você está chegando de outro framework assíncrono que não funciona como descrito acima e você está acostumado a definir *funções de operação de rota* triviais somente de computação com simples `def` para ter um mínimo ganho de performance (cerca de 100 nanosegundos), por favor observe que no **FastAPI** o efeito pode ser bem o oposto. Nesses casos, é melhor usar `async def` a menos que suas *funções de operação de rota* utilizem código que performe bloqueamento I/O.
-Ainda, em ambas as situações, as chances são que o **FastAPI** será [ainda mais rápido](/#performance){.internal-link target=_blank} do que (ou ao menos comparável a) seus frameworks antecessores.
+Ainda, em ambas as situações, as chances são que o **FastAPI** [ainda será mais rápido](index.md#performance) do que (ou ao menos comparável a) seu framework anterior.
-### Dependências
+### Dependências { #dependencies }
-O mesmo se aplica para as dependências. Se uma dependência tem as funções com padrão `def` ao invés de `async def`, ela é rodada no threadpool externo.
+O mesmo se aplica para as [dependências](tutorial/dependencies/index.md). Se uma dependência tem as funções com padrão `def` ao invés de `async def`, ela é rodada no threadpool externo.
-### Sub-dependências
+### Sub-dependências { #sub-dependencies }
-Você pode ter múltiplas dependências e sub-dependências exigindo uma a outra (como parâmetros de definições de funções), algumas delas podem ser criadas com `async def` e algumas com `def` normal. Isso ainda poderia funcionar, e aquelas criadas com `def` podem ser chamadas em uma thread externa ao invés de serem "aguardadas".
+Você pode ter múltiplas dependências e [sub-dependências](tutorial/dependencies/sub-dependencies.md) requisitando uma à outra (como parâmetros de definições de funções), algumas delas podem ser criadas com `async def` e algumas com `def` normal. Isso ainda funcionaria, e aquelas criadas com `def` normal seriam chamadas em uma thread externa (do threadpool) ao invés de serem "aguardadas".
-### Outras funções de utilidade
+### Outras funções de utilidade { #other-utility-functions }
Qualquer outra função de utilidade que você chame diretamente pode ser criada com `def` normal ou `async def` e o FastAPI não irá afetar o modo como você a chama.
@@ -389,6 +439,6 @@ Se sua função de utilidade é uma função normal com `def`, ela será chamada
---
-Novamente, esses são detalhes muito técnicos que provavelmente possam ser úteis caso você esteja procurando por eles.
+Novamente, esses são detalhes muito técnicos que provavelmente seriam úteis caso você esteja procurando por eles.
Caso contrário, você deve ficar bem com as dicas da seção acima: Com pressa?.
diff --git a/docs/pt/docs/benchmarks.md b/docs/pt/docs/benchmarks.md
index 07461ce46387c..ac34a4e5e0910 100644
--- a/docs/pt/docs/benchmarks.md
+++ b/docs/pt/docs/benchmarks.md
@@ -1,10 +1,10 @@
-# Comparações
+# Benchmarks { #benchmarks }
-As comparações independentes da TechEmpower mostram as aplicações **FastAPI** rodando com Uvicorn como um dos _frameworks_ Python mais rápidos disponíveis, somente atrás dos próprios Starlette e Uvicorn (utilizados internamente pelo FastAPI). (*)
+Benchmarks independentes da TechEmpower mostram as aplicações **FastAPI** rodando com Uvicorn como [um dos frameworks Python mais rápidos disponíveis](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7), somente atrás dos próprios Starlette e Uvicorn (utilizados internamente pelo FastAPI).
Mas quando se checa _benchmarks_ e comparações você deveria ter o seguinte em mente.
-## Comparações e velocidade
+## Benchmarks e velocidade { #benchmarks-and-speed }
Ao verificar os _benchmarks_, é comum observar algumas ferramentas de diferentes tipos comparadas como equivalentes.
@@ -29,6 +29,6 @@ A hierarquia segue assim:
* **FastAPI**:
* Do mesmo modo que Starlette utiliza Uvicorn e não pode ser mais rápido que ele, **FastAPI** utiliza o Starlette, então não tem como ser mais rápido do que o Starlette.
* FastAPI fornece mais recursos acima do Starlette. Recursos que você quase sempre precisará quando construir APIs, como validação de dados e serialização. E utilizando eles, você terá uma documentação automática de graça (a documentação automática nem sequer adiciona peso para rodar as aplicações, ela é gerada na inicialização).
- * Se você nunca utilizou FastAPI mas utilizou diretamente o Starlette (ou outra ferramenta, como Sanic, Flask, Responder, etc) você teria que implementar toda validação de dados e serialização por conta. Então, sua aplicação final poderia ainda ter a mesma sobrecarga como se fosse desenvolvida com FastAPI. Em muitos casos, a validação de dados e serialização é o maior pedaço de código escrito em aplicações.
+ * Se você não utilizasse o FastAPI e utilizasse diretamente o Starlette (ou outra ferramenta, como Sanic, Flask, Responder, etc), você teria que implementar toda a validação de dados e serialização por conta. Então, sua aplicação final poderia ainda ter a mesma sobrecarga como se fosse desenvolvida com FastAPI. Em muitos casos, a validação de dados e serialização é o maior pedaço de código escrito em aplicações.
* Então, ao utilizar o FastAPI você estará economizando tempo de desenvolvimento, evitará _bugs_, linhas de código, e você provavelmente terá a mesma performance (ou melhor) do que não utilizá-lo (já que você teria que implementar tudo isso em seu código).
* Se você quer fazer comparações com o FastAPI, compare com um _framework_ (ou conjunto de ferramentas) para aplicações _web_ que forneça validação de dados, serialização e documentação, como Flask-apispec, NestJS, Molten, etc. _Frameworks_ com validação de dados automática, serialização e documentação integradas.
diff --git a/docs/pt/docs/contributing.md b/docs/pt/docs/contributing.md
deleted file mode 100644
index 02895fcfc8b79..0000000000000
--- a/docs/pt/docs/contributing.md
+++ /dev/null
@@ -1,479 +0,0 @@
-# Desenvolvimento - Contribuindo
-
-Primeiramente, você deveria ver os meios básicos para [ajudar FastAPI e pedir ajuda](help-fastapi.md){.internal-link target=_blank}.
-
-## Desenvolvendo
-
-Se você já clonou o repositório e precisa mergulhar no código, aqui estão algumas orientações para configurar seu ambiente.
-
-### Ambiente virtual com `venv`
-
-Você pode criar um ambiente virtual em um diretório utilizando o módulo `venv` do Python:
-
-
+
+---
+
+Agora que sabemos a diferença entre os termos **processo** e **programa**, vamos continuar falando sobre implantações.
+
+## Executando na inicialização { #running-on-startup }
+
+Na maioria dos casos, quando você cria uma API web, você quer que ela esteja **sempre em execução**, ininterrupta, para que seus clientes possam sempre acessá-la. Isso é claro, a menos que você tenha um motivo específico para querer que ela seja executada somente em certas situações, mas na maioria das vezes você quer que ela esteja constantemente em execução e **disponível**.
+
+### Em um servidor remoto { #in-a-remote-server }
+
+Ao configurar um servidor remoto (um servidor em nuvem, uma máquina virtual, etc.), a coisa mais simples que você pode fazer é usar `fastapi run` (que usa Uvicorn) ou algo semelhante, manualmente, da mesma forma que você faz ao desenvolver localmente.
+
+E funcionará e será útil **durante o desenvolvimento**.
+
+Mas se sua conexão com o servidor for perdida, o **processo em execução** provavelmente morrerá.
+
+E se o servidor for reiniciado (por exemplo, após atualizações ou migrações do provedor de nuvem), você provavelmente **não notará**. E por causa disso, você nem saberá que precisa reiniciar o processo manualmente. Então, sua API simplesmente permanecerá inativa. 😱
+
+### Executar automaticamente na inicialização { #run-automatically-on-startup }
+
+Em geral, você provavelmente desejará que o programa do servidor (por exemplo, Uvicorn) seja iniciado automaticamente na inicialização do servidor e, sem precisar de nenhuma **intervenção humana**, tenha um processo sempre em execução com sua API (por exemplo, Uvicorn executando seu aplicativo FastAPI).
+
+### Programa separado { #separate-program }
+
+Para conseguir isso, você normalmente terá um **programa separado** que garantiria que seu aplicativo fosse executado na inicialização. E em muitos casos, ele também garantiria que outros componentes ou aplicativos também fossem executados, por exemplo, um banco de dados.
+
+### Ferramentas de exemplo para executar na inicialização { #example-tools-to-run-at-startup }
+
+Alguns exemplos de ferramentas que podem fazer esse trabalho são:
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Docker em Modo Swarm
+* Systemd
+* Supervisor
+* Gerenciado internamente por um provedor de nuvem como parte de seus serviços
+* Outros...
+
+Darei exemplos mais concretos nos próximos capítulos.
+
+## Reinicializações { #restarts }
+
+Semelhante a garantir que seu aplicativo seja executado na inicialização, você provavelmente também deseja garantir que ele seja **reiniciado** após falhas.
+
+### Nós cometemos erros { #we-make-mistakes }
+
+Nós, como humanos, cometemos **erros** o tempo todo. O software quase *sempre* tem **bugs** escondidos em lugares diferentes. 🐛
+
+E nós, como desenvolvedores, continuamos aprimorando o código à medida que encontramos esses bugs e implementamos novos recursos (possivelmente adicionando novos bugs também 😅).
+
+### Pequenos erros são tratados automaticamente { #small-errors-automatically-handled }
+
+Ao criar APIs da web com FastAPI, se houver um erro em nosso código, o FastAPI normalmente o conterá na única solicitação que acionou o erro. 🛡
+
+O cliente receberá um **Erro Interno do Servidor 500** para essa solicitação, mas o aplicativo continuará funcionando para as próximas solicitações em vez de travar completamente.
+
+### Erros maiores - Travamentos { #bigger-errors-crashes }
+
+No entanto, pode haver casos em que escrevemos algum código que **trava todo o aplicativo**, fazendo com que o Uvicorn e o Python travem. 💥
+
+E ainda assim, você provavelmente não gostaria que o aplicativo permanecesse inativo porque houve um erro em um lugar, você provavelmente quer que ele **continue em execução** pelo menos para as *operações de rota* que não estão quebradas.
+
+### Reiniciar após falha { #restart-after-crash }
+
+Mas nos casos com erros realmente graves que travam o **processo** em execução, você vai querer um componente externo que seja responsável por **reiniciar** o processo, pelo menos algumas vezes...
+
+/// tip | Dica
+
+...Embora se o aplicativo inteiro estiver **travando imediatamente**, provavelmente não faça sentido reiniciá-lo para sempre. Mas nesses casos, você provavelmente notará isso durante o desenvolvimento, ou pelo menos logo após a implantação.
+
+Então, vamos nos concentrar nos casos principais, onde ele pode travar completamente em alguns casos específicos **no futuro**, e ainda faz sentido reiniciá-lo.
+
+///
+
+Você provavelmente gostaria de ter a coisa responsável por reiniciar seu aplicativo como um **componente externo**, porque a essa altura, o mesmo aplicativo com Uvicorn e Python já havia travado, então não há nada no mesmo código do mesmo aplicativo que possa fazer algo a respeito.
+
+### Ferramentas de exemplo para reiniciar automaticamente { #example-tools-to-restart-automatically }
+
+Na maioria dos casos, a mesma ferramenta usada para **executar o programa na inicialização** também é usada para lidar com **reinicializações** automáticas.
+
+Por exemplo, isso poderia ser resolvido por:
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Docker no Modo Swarm
+* Systemd
+* Supervisor
+* Gerenciado internamente por um provedor de nuvem como parte de seus serviços
+* Outros...
+
+## Replicação - Processos e Memória { #replication-processes-and-memory }
+
+Com um aplicativo FastAPI, usando um programa de servidor como o comando `fastapi` que executa o Uvicorn, executá-lo uma vez em **um processo** pode atender a vários clientes simultaneamente.
+
+Mas em muitos casos, você desejará executar vários processos de trabalho ao mesmo tempo.
+
+### Processos Múltiplos - Trabalhadores { #multiple-processes-workers }
+
+Se você tiver mais clientes do que um único processo pode manipular (por exemplo, se a máquina virtual não for muito grande) e tiver **vários núcleos** na CPU do servidor, você poderá ter **vários processos** em execução com o mesmo aplicativo ao mesmo tempo e distribuir todas as solicitações entre eles.
+
+Quando você executa **vários processos** do mesmo programa de API, eles são comumente chamados de **trabalhadores**.
+
+### Processos do Trabalhador e Portas { #worker-processes-and-ports }
+
+Lembra da documentação [Sobre HTTPS](https.md) que diz que apenas um processo pode escutar em uma combinação de porta e endereço IP em um servidor?
+
+Isso ainda é verdade.
+
+Então, para poder ter **vários processos** ao mesmo tempo, tem que haver um **único processo escutando em uma porta** que então transmite a comunicação para cada processo de trabalho de alguma forma.
+
+### Memória por Processo { #memory-per-process }
+
+Agora, quando o programa carrega coisas na memória, por exemplo, um modelo de aprendizado de máquina em uma variável, ou o conteúdo de um arquivo grande em uma variável, tudo isso **consome um pouco da memória (RAM)** do servidor.
+
+E vários processos normalmente **não compartilham nenhuma memória**. Isso significa que cada processo em execução tem suas próprias coisas, variáveis e memória. E se você estiver consumindo uma grande quantidade de memória em seu código, **cada processo** consumirá uma quantidade equivalente de memória.
+
+### Memória do servidor { #server-memory }
+
+Por exemplo, se seu código carrega um modelo de Aprendizado de Máquina com **1 GB de tamanho**, quando você executa um processo com sua API, ele consumirá pelo menos 1 GB de RAM. E se você iniciar **4 processos** (4 trabalhadores), cada um consumirá 1 GB de RAM. Então, no total, sua API consumirá **4 GB de RAM**.
+
+E se o seu servidor remoto ou máquina virtual tiver apenas 3 GB de RAM, tentar carregar mais de 4 GB de RAM causará problemas. 🚨
+
+### Processos Múltiplos - Um Exemplo { #multiple-processes-an-example }
+
+Neste exemplo, há um **Processo Gerenciador** que inicia e controla dois **Processos de Trabalhadores**.
+
+Este Processo de Gerenciador provavelmente seria o que escutaria na **porta** no IP. E ele transmitiria toda a comunicação para os processos de trabalho.
+
+Esses processos de trabalho seriam aqueles que executariam seu aplicativo, eles executariam os cálculos principais para receber uma **solicitação** e retornar uma **resposta**, e carregariam qualquer coisa que você colocasse em variáveis na RAM.
+
+@@ -24,51 +24,51 @@ Há muitas ferramentas criadas antes que ajudaram a inspirar sua criação. Eu estive evitando a criação de um novo _framework_ por vários anos. Primeiro tentei resolver todas as funcionalidades cobertas por **FastAPI** usando muitos _frameworks_, _plug-ins_ e ferramentas diferentes. -Mas em algum ponto, não havia outra opção senão criar algo que oferecia todas as funcionalidades, aproveitando as melhores ideias de ferramentas anteriores, e combinando-as da melhor maneira possível, usando funcionalidades da linguagem que nem estavam disponíveis antes (_type hints_ do Python 3.6+). +Mas em algum ponto, não havia outra opção senão criar algo que oferecia todas as funcionalidades, aproveitando as melhores ideias de ferramentas anteriores, e combinando-as da melhor maneira possível, usando funcionalidades da linguagem que nem estavam disponíveis antes (anotações de tipo do Python 3.6+).-## Investigação +## Investigação { #investigation } Ao usar todas as alternativas anteriores, eu tive a chance de aprender com todas elas, aproveitar ideias e combiná-las da melhor maneira que encontrei para mim e para os times de desenvolvedores com os quais trabalhava. -Por exemplo, estava claro que idealmente ele deveria ser baseado nos _type hints_ padrões do Python. +Por exemplo, estava claro que idealmente ele deveria ser baseado nas anotações de tipo padrão do Python. Também, a melhor abordagem era usar padrões já existentes. Então, antes mesmo de começar a codificar o **FastAPI**, eu investi vários meses estudando as especificações do OpenAPI, JSON Schema, OAuth2 etc. Entendendo suas relações, sobreposições e diferenças. -## Design +## Design { #design } Eu então dediquei algum tempo projetando a "API" de desenvolvimento que eu queria como usuário (como um desenvolvedor usando o FastAPI). Eu testei várias ideias nos editores Python mais populares: PyCharm, VS Code, e editores baseados no Jedi. -Pela última Pesquisa do Desenvolvedor Python, isso cobre cerca de 80% dos usuários. +Pela última [Pesquisa do Desenvolvedor Python](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools), isso cobre cerca de 80% dos usuários. Isso significa que o **FastAPI** foi testado especificamente com os editores usados por 80% dos desenvolvedores Python. Como a maioria dos outros editores tendem a funcionar de forma similar, todos os seus benefícios devem funcionar para virtualmente todos os editores. -Dessa forma eu pude encontrar a melhor maneira de reduzir duplicação de código o máximo possível, ter completação de texto em todos os lugares, conferência de tipos e erros etc. +Dessa forma eu pude encontrar a melhor maneira de reduzir duplicação de código o máximo possível, ter preenchimento automático em todos os lugares, conferência de tipos e erros etc. Tudo de uma forma que oferecesse a melhor experiência de desenvolvimento para todos os desenvolvedores. -## Requisitos +## Requisitos { #requirements } -Após testar várias alternativas, eu decidi que usaria o **Pydantic** por suas vantagens. +Após testar várias alternativas, eu decidi que usaria o [**Pydantic**](https://docs.pydantic.dev/) por suas vantagens. -Então eu contribuí com ele, para deixá-lo completamente de acordo com o JSON Schema, para dar suporte a diferentes maneiras de definir declarações de restrições, e melhorar o suporte a editores (conferências de tipos, auto completações) baseado nos testes em vários editores. +Então eu contribuí com ele, para deixá-lo completamente de acordo com o JSON Schema, para dar suporte a diferentes maneiras de definir declarações de restrições, e melhorar o suporte a editores (conferências de tipos, preenchimento automático) baseado nos testes em vários editores. -Durante o desenvolvimento, eu também contribuí com o **Starlette**, outro requisito chave. +Durante o desenvolvimento, eu também contribuí com o [**Starlette**](https://www.starlette.dev/), outro requisito chave. -## Desenvolvimento +## Desenvolvimento { #development } Quando comecei a criar o **FastAPI** de fato, a maior parte das peças já estavam encaixadas, o design estava definido, os requisitos e ferramentas já estavam prontos, e o conhecimento sobre os padrões e especificações estavam claros e frescos. -## Futuro +## Futuro { #future } Nesse ponto, já está claro que o **FastAPI** com suas ideias está sendo útil para muitas pessoas. -Ele foi escolhido sobre outras alternativas anteriores por se adequar melhor em muitos casos. +Ele está sendo escolhido em relação a alternativas anteriores por se adequar melhor em muitos casos. Muitos desenvolvedores e times já dependem do **FastAPI** para seus projetos (incluindo eu e meu time). @@ -76,4 +76,4 @@ Mas ainda há muitas melhorias e funcionalidades a vir. **FastAPI** tem um grande futuro à frente. -E [sua ajuda](help-fastapi.md){.internal-link target=_blank} é muito bem-vinda. +E [sua ajuda](help-fastapi.md) é muito bem-vinda. diff --git a/docs/pt/docs/how-to/authentication-error-status-code.md b/docs/pt/docs/how-to/authentication-error-status-code.md new file mode 100644 index 0000000000000..62b660e732f8c --- /dev/null +++ b/docs/pt/docs/how-to/authentication-error-status-code.md @@ -0,0 +1,17 @@ +# Usar antigos códigos de status de erro de autenticação 403 { #use-old-403-authentication-error-status-codes } + +Antes da versão `0.122.0` do FastAPI, quando os utilitários de segurança integrados retornavam um erro ao cliente após uma falha na autenticação, eles usavam o código de status HTTP `403 Forbidden`. + +A partir da versão `0.122.0` do FastAPI, eles usam o código de status HTTP `401 Unauthorized`, mais apropriado, e retornam um cabeçalho `WWW-Authenticate` adequado na response, seguindo as especificações HTTP, [RFC 7235](https://datatracker.ietf.org/doc/html/rfc7235#section-3.1), [RFC 9110](https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized). + +Mas, se por algum motivo seus clientes dependem do comportamento antigo, você pode voltar a ele sobrescrevendo o método `make_not_authenticated_error` nas suas classes de segurança. + +Por exemplo, você pode criar uma subclasse de `HTTPBearer` que retorne um erro `403 Forbidden` em vez do erro padrão `401 Unauthorized`: + +{* ../../docs_src/authentication_error_status_code/tutorial001_an_py310.py hl[9:13] *} + +/// tip | Dica + +Perceba que a função retorna a instância da exceção, ela não a lança. O lançamento é feito no restante do código interno. + +/// diff --git a/docs/pt/docs/how-to/conditional-openapi.md b/docs/pt/docs/how-to/conditional-openapi.md new file mode 100644 index 0000000000000..f6838eb6d8caf --- /dev/null +++ b/docs/pt/docs/how-to/conditional-openapi.md @@ -0,0 +1,56 @@ +# OpenAPI condicional { #conditional-openapi } + +Se necessário, você pode usar configurações e variáveis de ambiente para configurar o OpenAPI condicionalmente dependendo do ambiente e até mesmo desativá-lo completamente. + +## Sobre segurança, APIs e documentação { #about-security-apis-and-docs } + +Ocultar suas interfaces de usuário de documentação na produção não *deveria* ser a maneira de proteger sua API. + +Isso não adiciona nenhuma segurança extra à sua API; as *operações de rota* ainda estarão disponíveis onde estão. + +Se houver uma falha de segurança no seu código, ela ainda existirá. + +Ocultar a documentação apenas torna mais difícil entender como interagir com sua API e pode dificultar sua depuração na produção. Pode ser considerado simplesmente uma forma de [Segurança através da obscuridade](https://en.wikipedia.org/wiki/Security_through_obscurity). + +Se você quiser proteger sua API, há várias coisas melhores que você pode fazer, por exemplo: + +* Certifique-se de ter modelos Pydantic bem definidos para seus corpos de request e respostas. +* Configure quaisquer permissões e funções necessárias usando dependências. +* Nunca armazene senhas em texto simples, apenas hashes de senha. +* Implemente e use ferramentas criptográficas bem conhecidas, como pwdlib e tokens JWT, etc. +* Adicione controles de permissão mais granulares com escopos OAuth2 quando necessário. +* ...etc. + +No entanto, você pode ter um caso de uso muito específico em que realmente precisa desabilitar a documentação da API para algum ambiente (por exemplo, para produção) ou dependendo de configurações de variáveis de ambiente. + +## OpenAPI condicional com configurações e variáveis de ambiente { #conditional-openapi-from-settings-and-env-vars } + +Você pode usar facilmente as mesmas configurações do Pydantic para configurar sua OpenAPI gerada e as interfaces de usuário da documentação. + +Por exemplo: + +{* ../../docs_src/conditional_openapi/tutorial001_py310.py hl[6,11] *} + +Aqui declaramos a configuração `openapi_url` com o mesmo padrão de `"/openapi.json"`. + +E então a usamos ao criar a aplicação `FastAPI`. + +Então você pode desabilitar o OpenAPI (incluindo a documentação da interface do usuário) definindo a variável de ambiente `OPENAPI_URL` como a string vazia, como: + +
+
+Mas você pode desabilitá-lo definindo `syntaxHighlight` como `False`:
+
+{* ../../docs_src/configure_swagger_ui/tutorial001_py310.py hl[3] *}
+
+...e então o Swagger UI não mostrará mais o destaque de sintaxe:
+
+
+
+## Alterar o tema { #change-the-theme }
+
+Da mesma forma que você pode definir o tema de destaque de sintaxe com a chave `"syntaxHighlight.theme"` (observe que há um ponto no meio):
+
+{* ../../docs_src/configure_swagger_ui/tutorial002_py310.py hl[3] *}
+
+Essa configuração alteraria o tema de cores de destaque de sintaxe:
+
+
+
+## Alterar parâmetros de UI padrão do Swagger { #change-default-swagger-ui-parameters }
+
+O FastAPI inclui alguns parâmetros de configuração padrão apropriados para a maioria dos casos de uso.
+
+Inclui estas configurações padrão:
+
+{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}
+
+Você pode substituir qualquer um deles definindo um valor diferente no argumento `swagger_ui_parameters`.
+
+Por exemplo, para desabilitar `deepLinking` você pode passar essas configurações para `swagger_ui_parameters`:
+
+{* ../../docs_src/configure_swagger_ui/tutorial003_py310.py hl[3] *}
+
+## Outros parâmetros da UI do Swagger { #other-swagger-ui-parameters }
+
+Para ver todas as outras configurações possíveis que você pode usar, leia a [documentação oficial dos parâmetros da UI do Swagger](https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/).
+
+## Configurações somente JavaScript { #javascript-only-settings }
+
+A UI do Swagger também permite que outras configurações sejam objetos **somente JavaScript** (por exemplo, funções JavaScript).
+
+O FastAPI também inclui estas configurações `presets` somente para JavaScript:
+
+```JavaScript
+presets: [
+ SwaggerUIBundle.presets.apis,
+ SwaggerUIBundle.SwaggerUIStandalonePreset
+]
+```
+
+Esses são objetos **JavaScript**, não strings, então você não pode passá-los diretamente do código Python.
+
+Se você precisar usar configurações somente JavaScript como essas, você pode usar um dos métodos acima. Substitua toda a *operação de rota* do Swagger UI e escreva manualmente qualquer JavaScript que você precisar.
diff --git a/docs/pt/docs/how-to/custom-docs-ui-assets.md b/docs/pt/docs/how-to/custom-docs-ui-assets.md
new file mode 100644
index 0000000000000..5437434d57e46
--- /dev/null
+++ b/docs/pt/docs/how-to/custom-docs-ui-assets.md
@@ -0,0 +1,185 @@
+# Recursos Estáticos Personalizados para a UI de Documentação (Hospedagem Própria) { #custom-docs-ui-static-assets-self-hosting }
+
+A documentação da API usa **Swagger UI** e **ReDoc**, e cada um deles precisa de alguns arquivos JavaScript e CSS.
+
+Por padrão, esses arquivos são fornecidos por um CDN.
+
+Mas é possível personalizá-los, você pode definir um CDN específico ou providenciar os arquivos você mesmo.
+
+## CDN Personalizado para JavaScript e CSS { #custom-cdn-for-javascript-and-css }
+
+Vamos supor que você deseja usar um CDN diferente, por exemplo, você deseja usar `https://unpkg.com/`.
+
+Isso pode ser útil se, por exemplo, você mora em um país que restringe algumas URLs.
+
+### Desativar a documentação automática { #disable-the-automatic-docs }
+
+O primeiro passo é desativar a documentação automática, pois por padrão, ela usa o CDN padrão.
+
+Para desativá-los, defina suas URLs como `None` ao criar sua aplicação FastAPI:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[8] *}
+
+### Incluir a documentação personalizada { #include-the-custom-docs }
+
+Agora você pode criar as *operações de rota* para a documentação personalizada.
+
+Você pode reutilizar as funções internas do FastAPI para criar as páginas HTML para a documentação e passar os argumentos necessários:
+
+* `openapi_url`: a URL onde a página HTML para a documentação pode obter o esquema OpenAPI para a sua API. Você pode usar aqui o atributo `app.openapi_url`.
+* `title`: o título da sua API.
+* `oauth2_redirect_url`: você pode usar `app.swagger_ui_oauth2_redirect_url` aqui para usar o padrão.
+* `swagger_js_url`: a URL onde a página HTML para a sua documentação do Swagger UI pode obter o arquivo **JavaScript**. Este é o URL do CDN personalizado.
+* `swagger_css_url`: a URL onde a página HTML para a sua documentação do Swagger UI pode obter o arquivo **CSS**. Este é o URL do CDN personalizado.
+
+E de forma semelhante para o ReDoc...
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[2:6,11:19,22:24,27:33] *}
+
+/// tip | Dica
+
+A *operação de rota* para `swagger_ui_redirect` é um auxiliar para quando você usa OAuth2.
+
+Se você integrar sua API com um provedor OAuth2, você poderá autenticar e voltar para a documentação da API com as credenciais adquiridas. E interagir com ela usando a autenticação OAuth2 real.
+
+Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse auxiliar de "redirecionamento".
+
+///
+
+### Criar uma *operação de rota* para testar { #create-a-path-operation-to-test-it }
+
+Agora, para poder testar se tudo funciona, crie uma *operação de rota*:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[36:38] *}
+
+### Teste { #test-it }
+
+Agora, você deve ser capaz de ir para a documentação em [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs), e recarregar a página, ela carregará esses recursos do novo CDN.
+
+## Hospedagem Própria de JavaScript e CSS para a documentação { #self-hosting-javascript-and-css-for-docs }
+
+Hospedar o JavaScript e o CSS pode ser útil se, por exemplo, você precisa que seu aplicativo continue funcionando mesmo offline, sem acesso aberto à Internet, ou em uma rede local.
+
+Aqui você verá como providenciar esses arquivos você mesmo, na mesma aplicação FastAPI, e configurar a documentação para usá-los.
+
+### Estrutura de Arquivos do Projeto { #project-file-structure }
+
+Vamos supor que a estrutura de arquivos do seu projeto se pareça com isso:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+```
+
+Agora crie um diretório para armazenar esses arquivos estáticos.
+
+Sua nova estrutura de arquivos poderia se parecer com isso:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static/
+```
+
+### Baixe os arquivos { #download-the-files }
+
+Baixe os arquivos estáticos necessários para a documentação e coloque-os no diretório `static/`.
+
+Você provavelmente pode clicar com o botão direito em cada link e selecionar uma opção semelhante a "Salvar link como...".
+
+**Swagger UI** usa os arquivos:
+
+* [`swagger-ui-bundle.js`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js)
+* [`swagger-ui.css`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css)
+
+E o **ReDoc** usa o arquivo:
+
+* [`redoc.standalone.js`](https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js)
+
+Depois disso, sua estrutura de arquivos deve se parecer com:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static
+ ├── redoc.standalone.js
+ ├── swagger-ui-bundle.js
+ └── swagger-ui.css
+```
+
+### Prover os arquivos estáticos { #serve-the-static-files }
+
+* Importe `StaticFiles`.
+* "Monte" a instância `StaticFiles()` em um caminho específico.
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[7,11] *}
+
+### Teste os arquivos estáticos { #test-the-static-files }
+
+Inicialize seu aplicativo e vá para [http://127.0.0.1:8000/static/redoc.standalone.js](http://127.0.0.1:8000/static/redoc.standalone.js).
+
+Você deverá ser ver um arquivo JavaScript muito longo para o **ReDoc**.
+
+Esse arquivo pode começar com algo como:
+
+```JavaScript
+/*! For license information please see redoc.standalone.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")):
+...
+```
+
+Isso confirma que você está conseguindo fornecer arquivos estáticos do seu aplicativo e que você colocou os arquivos estáticos para a documentação no local correto.
+
+Agora, podemos configurar o aplicativo para usar esses arquivos estáticos para a documentação.
+
+### Desativar a documentação automática para arquivos estáticos { #disable-the-automatic-docs-for-static-files }
+
+Da mesma forma que ao usar um CDN personalizado, o primeiro passo é desativar a documentação automática, pois ela usa o CDN padrão.
+
+Para desativá-los, defina suas URLs como `None` ao criar sua aplicação FastAPI:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[9] *}
+
+### Incluir a documentação personalizada para arquivos estáticos { #include-the-custom-docs-for-static-files }
+
+E da mesma forma que com um CDN personalizado, agora você pode criar as *operações de rota* para a documentação personalizada.
+
+Novamente, você pode reutilizar as funções internas do FastAPI para criar as páginas HTML para a documentação e passar os argumentos necessários:
+
+* `openapi_url`: a URL onde a página HTML para a documentação pode obter o esquema OpenAPI para a sua API. Você pode usar aqui o atributo `app.openapi_url`.
+* `title`: o título da sua API.
+* `oauth2_redirect_url`: Você pode usar `app.swagger_ui_oauth2_redirect_url` aqui para usar o padrão.
+* `swagger_js_url`: a URL onde a página HTML para a sua documentação do Swagger UI pode obter o arquivo **JavaScript**. **Este é o URL que seu aplicativo está fornecendo**.
+* `swagger_css_url`: a URL onde a página HTML para a sua documentação do Swagger UI pode obter o arquivo **CSS**. **Esse é o que seu aplicativo está fornecendo**.
+
+E de forma semelhante para o ReDoc...
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[2:6,14:22,25:27,30:36] *}
+
+/// tip | Dica
+
+A *operação de rota* para `swagger_ui_redirect` é um auxiliar para quando você usa OAuth2.
+
+Se você integrar sua API com um provedor OAuth2, você poderá autenticar e voltar para a documentação da API com as credenciais adquiridas. E, então, interagir com ela usando a autenticação OAuth2 real.
+
+Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse auxiliar de "redirect".
+
+///
+
+### Criar uma *operação de rota* para testar arquivos estáticos { #create-a-path-operation-to-test-static-files }
+
+Agora, para poder testar se tudo funciona, crie uma *operação de rota*:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[39:41] *}
+
+### Teste a UI de Arquivos Estáticos { #test-static-files-ui }
+
+Agora, você deve ser capaz de desconectar o WiFi, ir para a documentação em [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs), e recarregar a página.
+
+E mesmo sem Internet, você será capaz de ver a documentação da sua API e interagir com ela.
diff --git a/docs/pt/docs/how-to/custom-request-and-route.md b/docs/pt/docs/how-to/custom-request-and-route.md
new file mode 100644
index 0000000000000..5603535320891
--- /dev/null
+++ b/docs/pt/docs/how-to/custom-request-and-route.md
@@ -0,0 +1,109 @@
+# Request e classe APIRoute personalizadas { #custom-request-and-apiroute-class }
+
+Em alguns casos, você pode querer sobrescrever a lógica usada pelas classes `Request` e `APIRoute`.
+
+Em particular, isso pode ser uma boa alternativa para uma lógica em um middleware.
+
+Por exemplo, se você quiser ler ou manipular o corpo da requisição antes que ele seja processado pela sua aplicação.
+
+/// danger | Cuidado
+
+Isso é um recurso "avançado".
+
+Se você for um iniciante em **FastAPI** você deve considerar pular essa seção.
+
+///
+
+## Casos de Uso { #use-cases }
+
+Alguns casos de uso incluem:
+
+* Converter requisições não-JSON para JSON (por exemplo, [`msgpack`](https://msgpack.org/index.html)).
+* Descomprimir corpos de requisição comprimidos com gzip.
+* Registrar automaticamente todos os corpos de requisição.
+
+## Manipulando codificações de corpo de requisição personalizadas { #handling-custom-request-body-encodings }
+
+Vamos ver como usar uma subclasse personalizada de `Request` para descomprimir requisições gzip.
+
+E uma subclasse de `APIRoute` para usar essa classe de requisição personalizada.
+
+### Criar uma classe `GzipRequest` personalizada { #create-a-custom-gziprequest-class }
+
+/// tip | Dica
+
+Isso é um exemplo de brincadeira para demonstrar como funciona, se você precisar de suporte para Gzip, você pode usar o [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware) fornecido.
+
+///
+
+Primeiro, criamos uma classe `GzipRequest`, que irá sobrescrever o método `Request.body()` para descomprimir o corpo na presença de um cabeçalho apropriado.
+
+Se não houver `gzip` no cabeçalho, ele não tentará descomprimir o corpo.
+
+Dessa forma, a mesma classe de rota pode lidar com requisições comprimidas ou não comprimidas.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[9:16] *}
+
+### Criar uma classe `GzipRoute` personalizada { #create-a-custom-gziproute-class }
+
+Em seguida, criamos uma subclasse personalizada de `fastapi.routing.APIRoute` que fará uso do `GzipRequest`.
+
+Dessa vez, ele irá sobrescrever o método `APIRoute.get_route_handler()`.
+
+Esse método retorna uma função. E essa função é o que irá receber uma requisição e retornar uma resposta.
+
+Aqui nós usamos para criar um `GzipRequest` a partir da requisição original.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[19:27] *}
+
+/// note | Detalhes Técnicos
+
+Um `Request` tem um atributo `request.scope`, que é apenas um `dict` do Python contendo os metadados relacionados à requisição.
+
+Um `Request` também tem um `request.receive`, que é uma função para "receber" o corpo da requisição.
+
+O dicionário `scope` e a função `receive` são ambos parte da especificação ASGI.
+
+E essas duas coisas, `scope` e `receive`, são o que é necessário para criar uma nova instância de `Request`.
+
+Para aprender mais sobre o `Request` confira a [documentação do Starlette sobre Requests](https://www.starlette.dev/requests/).
+
+///
+
+A única coisa que a função retornada por `GzipRequest.get_route_handler` faz de diferente é converter o `Request` para um `GzipRequest`.
+
+Fazendo isso, nosso `GzipRequest` irá cuidar de descomprimir os dados (se necessário) antes de passá-los para nossas *operações de rota*.
+
+Depois disso, toda a lógica de processamento é a mesma.
+
+Mas por causa das nossas mudanças em `GzipRequest.body`, o corpo da requisição será automaticamente descomprimido quando for carregado pelo **FastAPI** quando necessário.
+
+## Acessando o corpo da requisição em um manipulador de exceção { #accessing-the-request-body-in-an-exception-handler }
+
+/// tip | Dica
+
+Para resolver esse mesmo problema, é provavelmente muito mais fácil usar o `body` em um manipulador personalizado para `RequestValidationError` ([Tratando Erros](../tutorial/handling-errors.md#use-the-requestvalidationerror-body)).
+
+Mas esse exemplo ainda é valido e mostra como interagir com os componentes internos.
+
+///
+
+Também podemos usar essa mesma abordagem para acessar o corpo da requisição em um manipulador de exceção.
+
+Tudo que precisamos fazer é manipular a requisição dentro de um bloco `try`/`except`:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[14,16] *}
+
+Se uma exceção ocorrer, a instância `Request` ainda estará em escopo, então podemos ler e fazer uso do corpo da requisição ao lidar com o erro:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[17:19] *}
+
+## Classe `APIRoute` personalizada em um router { #custom-apiroute-class-in-a-router }
+
+Você também pode definir o parâmetro `route_class` de uma `APIRouter`:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[26] *}
+
+Nesse exemplo, as *operações de rota* sob o `router` irão usar a classe `TimedRoute` personalizada, e terão um cabeçalho extra `X-Response-Time` na resposta com o tempo que levou para gerar a resposta:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[13:20] *}
diff --git a/docs/pt/docs/how-to/extending-openapi.md b/docs/pt/docs/how-to/extending-openapi.md
new file mode 100644
index 0000000000000..23737e5fa125c
--- /dev/null
+++ b/docs/pt/docs/how-to/extending-openapi.md
@@ -0,0 +1,80 @@
+# Extendendo o OpenAPI { #extending-openapi }
+
+Existem alguns casos em que pode ser necessário modificar o esquema OpenAPI gerado.
+
+Nesta seção, você verá como fazer isso.
+
+## O processo normal { #the-normal-process }
+
+O processo normal (padrão) é o seguinte:
+
+Uma aplicação (instância) do `FastAPI` possui um método `.openapi()` que deve retornar o esquema OpenAPI.
+
+Como parte da criação do objeto de aplicação, uma *operação de rota* para `/openapi.json` (ou para o que você definir como `openapi_url`) é registrada.
+
+Ela apenas retorna uma resposta JSON com o resultado do método `.openapi()` da aplicação.
+
+Por padrão, o que o método `.openapi()` faz é verificar se a propriedade `.openapi_schema` tem conteúdo e retorná-lo.
+
+Se não tiver, ele gera o conteúdo usando a função utilitária em `fastapi.openapi.utils.get_openapi`.
+
+E essa função `get_openapi()` recebe como parâmetros:
+
+* `title`: O título do OpenAPI, exibido na documentação.
+* `version`: A versão da sua API, por exemplo, `2.5.0`.
+* `openapi_version`: A versão da especificação OpenAPI utilizada. Por padrão, a mais recente: `3.1.0`.
+* `summary`: Um resumo curto da API.
+* `description`: A descrição da sua API, que pode incluir markdown e será exibida na documentação.
+* `routes`: Uma lista de rotas, que são cada uma das *operações de rota* registradas. Elas são obtidas de `app.routes`.
+
+/// info | Informação
+
+O parâmetro `summary` está disponível no OpenAPI 3.1.0 e superior, suportado pelo FastAPI 0.99.0 e superior.
+
+///
+
+## Sobrescrevendo os padrões { #overriding-the-defaults }
+
+Com as informações acima, você pode usar a mesma função utilitária para gerar o esquema OpenAPI e sobrescrever cada parte que precisar.
+
+Por exemplo, vamos adicionar [Extensão OpenAPI do ReDoc para incluir um logo personalizado](https://github.com/Rebilly/ReDoc/blob/master/docs/redoc-vendor-extensions.md#x-logo).
+
+### **FastAPI** Normal { #normal-fastapi }
+
+Primeiro, escreva toda a sua aplicação **FastAPI** normalmente:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[1,4,7:9] *}
+
+### Gerar o esquema OpenAPI { #generate-the-openapi-schema }
+
+Em seguida, use a mesma função utilitária para gerar o esquema OpenAPI, dentro de uma função `custom_openapi()`:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[2,15:21] *}
+
+### Modificar o esquema OpenAPI { #modify-the-openapi-schema }
+
+Agora, você pode adicionar a extensão do ReDoc, incluindo um `x-logo` personalizado ao "objeto" `info` no esquema OpenAPI:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[22:24] *}
+
+### Armazenar em cache o esquema OpenAPI { #cache-the-openapi-schema }
+
+Você pode usar a propriedade `.openapi_schema` como um "cache" para armazenar o esquema gerado.
+
+Dessa forma, sua aplicação não precisará gerar o esquema toda vez que um usuário abrir a documentação da sua API.
+
+Ele será gerado apenas uma vez, e o mesmo esquema armazenado em cache será utilizado nas próximas requisições.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[13:14,25:26] *}
+
+### Sobrescrever o método { #override-the-method }
+
+Agora, você pode substituir o método `.openapi()` pela sua nova função.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[29] *}
+
+### Verificar { #check-it }
+
+Uma vez que você acessar [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc), verá que está usando seu logo personalizado (neste exemplo, o logo do **FastAPI**):
+
+
diff --git a/docs/pt/docs/how-to/general.md b/docs/pt/docs/how-to/general.md
new file mode 100644
index 0000000000000..ce04ada16e65a
--- /dev/null
+++ b/docs/pt/docs/how-to/general.md
@@ -0,0 +1,42 @@
+# Geral - Como Fazer - Receitas { #general-how-to-recipes }
+
+Aqui estão vários links para outros locais na documentação, para perguntas gerais ou frequentes.
+
+## Filtro de dados- Segurança { #filter-data-security }
+
+Para assegurar que você não vai retornar mais dados do que deveria, leia a documentação de [Tutorial - Modelo de Resposta - Tipo de Retorno](../tutorial/response-model.md).
+
+## Otimizar Desempenho da Resposta - Modelo de Resposta - Tipo de Retorno { #optimize-response-performance-response-model-return-type }
+
+Para otimizar o desempenho ao retornar dados JSON, use um tipo de retorno ou modelo de resposta; assim, o Pydantic fará a serialização para JSON no lado do Rust, sem passar pelo Python. Leia mais na documentação de [Tutorial - Modelo de Resposta - Tipo de Retorno](../tutorial/response-model.md).
+
+## Tags de Documentação - OpenAPI { #documentation-tags-openapi }
+Para adicionar tags às suas *operações de rota* e agrupá-las na UI da documentação, leia a documentação de [Tutorial - Configurações da Operação de Rota - Tags](../tutorial/path-operation-configuration.md#tags).
+
+## Resumo e Descrição da documentação - OpenAPI { #documentation-summary-and-description-openapi }
+
+Para adicionar um resumo e uma descrição às suas *operações de rota* e exibi-los na UI da documentação, leia a documentação de [Tutorial - Configurações da Operação de Rota - Resumo e Descrição](../tutorial/path-operation-configuration.md#summary-and-description).
+
+## Documentação - Descrição da Resposta - OpenAPI { #documentation-response-description-openapi }
+
+Para definir a descrição de uma resposta exibida na interface da documentação, leia a documentação de [Tutorial - Configurações da Operação de Rota - Descrição da Resposta](../tutorial/path-operation-configuration.md#response-description).
+
+## Documentação - Descontinuar uma *Operação de Rota* - OpenAPI { #documentation-deprecate-a-path-operation-openapi }
+
+Para descontinuar uma *operação de rota* e exibi-la na UI da documentação, leia a documentação de [Tutorial - Configurações da Operação de Rota - Descontinuação](../tutorial/path-operation-configuration.md#deprecate-a-path-operation).
+
+## Converter qualquer dado para compatível com JSON { #convert-any-data-to-json-compatible }
+
+Para converter qualquer dado para um formato compatível com JSON, leia a documentação de [Tutorial - Codificador Compatível com JSON](../tutorial/encoder.md).
+
+## OpenAPI Metadata - Docs { #openapi-metadata-docs }
+
+Para adicionar metadados ao seu esquema OpenAPI, incluindo licença, versão, contato, etc, leia a documentação de [Tutorial - Metadados e URLs da Documentação](../tutorial/metadata.md).
+
+## OpenAPI com URL customizada { #openapi-custom-url }
+
+Para customizar a URL do OpenAPI (ou removê-la), leia a documentação de [Tutorial - Metadados e URLs da Documentação](../tutorial/metadata.md#openapi-url).
+
+## URLs de documentação do OpenAPI { #openapi-docs-urls }
+
+Para alterar as URLs usadas para as interfaces de usuário da documentação gerada automaticamente, leia a documentação de [Tutorial - Metadados e URLs da Documentação](../tutorial/metadata.md#docs-urls).
diff --git a/docs/pt/docs/how-to/graphql.md b/docs/pt/docs/how-to/graphql.md
new file mode 100644
index 0000000000000..f96a202f0823f
--- /dev/null
+++ b/docs/pt/docs/how-to/graphql.md
@@ -0,0 +1,60 @@
+# GraphQL { #graphql }
+
+Como o **FastAPI** é baseado no padrão **ASGI**, é muito fácil integrar qualquer biblioteca **GraphQL** também compatível com ASGI.
+
+Você pode combinar *operações de rota* normais do FastAPI com GraphQL na mesma aplicação.
+
+/// tip | Dica
+
+**GraphQL** resolve alguns casos de uso muito específicos.
+
+Ele tem **vantagens** e **desvantagens** quando comparado a **web APIs** comuns.
+
+Certifique-se de avaliar se os **benefícios** para o seu caso de uso compensam as **desvantagens**. 🤓
+
+///
+
+## Bibliotecas GraphQL { #graphql-libraries }
+
+Aqui estão algumas das bibliotecas **GraphQL** que têm suporte **ASGI**. Você pode usá-las com **FastAPI**:
+
+* [Strawberry](https://strawberry.rocks/) 🍓
+ * Com [documentação para FastAPI](https://strawberry.rocks/docs/integrations/fastapi)
+* [Ariadne](https://ariadnegraphql.org/)
+ * Com [documentação para FastAPI](https://ariadnegraphql.org/docs/fastapi-integration)
+* [Tartiflette](https://tartiflette.io/)
+ * Com [Tartiflette ASGI](https://tartiflette.github.io/tartiflette-asgi/) para fornecer integração ASGI
+* [Graphene](https://graphene-python.org/)
+ * Com [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3)
+
+## GraphQL com Strawberry { #graphql-with-strawberry }
+
+Se você precisar ou quiser trabalhar com **GraphQL**, [**Strawberry**](https://strawberry.rocks/) é a biblioteca **recomendada** pois tem o design mais próximo ao design do **FastAPI**, ela é toda baseada em **anotações de tipo**.
+
+Dependendo do seu caso de uso, você pode preferir usar uma biblioteca diferente, mas se você me perguntasse, eu provavelmente sugeriria que você experimentasse o **Strawberry**.
+
+Aqui está uma pequena prévia de como você poderia integrar Strawberry com FastAPI:
+
+{* ../../docs_src/graphql_/tutorial001_py310.py hl[3,22,25] *}
+
+Você pode aprender mais sobre Strawberry na [documentação do Strawberry](https://strawberry.rocks/).
+
+E também na documentação sobre [Strawberry com FastAPI](https://strawberry.rocks/docs/integrations/fastapi).
+
+## Antigo `GraphQLApp` do Starlette { #older-graphqlapp-from-starlette }
+
+Versões anteriores do Starlette incluiam uma classe `GraphQLApp` para integrar com [Graphene](https://graphene-python.org/).
+
+Ela foi descontinuada do Starlette, mas se você tem código que a utilizava, você pode facilmente **migrar** para [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3), que cobre o mesmo caso de uso e tem uma **interface quase idêntica**.
+
+/// tip | Dica
+
+Se você precisa de GraphQL, eu ainda recomendaria que você desse uma olhada no [Strawberry](https://strawberry.rocks/), pois ele é baseado em anotações de tipo em vez de classes e tipos personalizados.
+
+///
+
+## Saiba Mais { #learn-more }
+
+Você pode aprender mais sobre **GraphQL** na [documentação oficial do GraphQL](https://graphql.org/).
+
+Você também pode ler mais sobre cada uma das bibliotecas descritas acima em seus links.
diff --git a/docs/pt/docs/how-to/index.md b/docs/pt/docs/how-to/index.md
new file mode 100644
index 0000000000000..3f3d344354c25
--- /dev/null
+++ b/docs/pt/docs/how-to/index.md
@@ -0,0 +1,13 @@
+# Como Fazer - Receitas { #how-to-recipes }
+
+Aqui você encontrará diferentes exemplos práticos ou tutoriais de "como fazer" para **vários tópicos**.
+
+A maioria dessas ideias será mais ou menos **independente**, e na maioria dos casos você deveria estudá-las apenas se elas se aplicarem diretamente ao **seu projeto**.
+
+Se algo parecer interessante e útil para o seu projeto, vá em frente e dê uma olhada. Caso contrário, você pode simplesmente ignorá-las.
+
+/// tip | Dica
+
+Se você deseja **aprender FastAPI** de forma estruturada (recomendado), leia capítulo por capítulo [Tutorial - Guia de Usuário](../tutorial/index.md) em vez disso.
+
+///
diff --git a/docs/pt/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/pt/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
new file mode 100644
index 0000000000000..1352abda944ed
--- /dev/null
+++ b/docs/pt/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -0,0 +1,135 @@
+# Migrar do Pydantic v1 para o Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 }
+
+Se você tem uma aplicação FastAPI antiga, pode estar usando o Pydantic versão 1.
+
+O FastAPI versão 0.100.0 tinha suporte ao Pydantic v1 ou v2. Ele usaria aquele que você tivesse instalado.
+
+O FastAPI versão 0.119.0 introduziu suporte parcial ao Pydantic v1 a partir de dentro do Pydantic v2 (como `pydantic.v1`), para facilitar a migração para o v2.
+
+O FastAPI 0.126.0 removeu o suporte ao Pydantic v1, enquanto ainda oferece suporte a `pydantic.v1` por mais algum tempo.
+
+/// warning | Atenção
+
+A equipe do Pydantic interrompeu o suporte ao Pydantic v1 para as versões mais recentes do Python, a partir do **Python 3.14**.
+
+Isso inclui `pydantic.v1`, que não é mais suportado no Python 3.14 e superiores.
+
+Se quiser usar as funcionalidades mais recentes do Python, você precisará garantir que usa o Pydantic v2.
+
+///
+
+Se você tem uma aplicação FastAPI antiga com Pydantic v1, aqui vou mostrar como migrá-la para o Pydantic v2, e as **funcionalidades no FastAPI 0.119.0** para ajudar em uma migração gradual.
+
+## Guia oficial { #official-guide }
+
+O Pydantic tem um [Guia de Migração](https://docs.pydantic.dev/latest/migration/) oficial do v1 para o v2.
+
+Ele também inclui o que mudou, como as validações agora são mais corretas e rigorosas, possíveis ressalvas, etc.
+
+Você pode lê-lo para entender melhor o que mudou.
+
+## Testes { #tests }
+
+Garanta que você tenha [testes](../tutorial/testing.md) para sua aplicação e que os execute na integração contínua (CI).
+
+Assim, você pode fazer a atualização e garantir que tudo continua funcionando como esperado.
+
+## `bump-pydantic` { #bump-pydantic }
+
+Em muitos casos, quando você usa modelos Pydantic regulares sem personalizações, será possível automatizar a maior parte do processo de migração do Pydantic v1 para o Pydantic v2.
+
+Você pode usar [`bump-pydantic`](https://github.com/pydantic/bump-pydantic) da própria equipe do Pydantic.
+
+Essa ferramenta ajuda a alterar automaticamente a maior parte do código que precisa ser modificado.
+
+Depois disso, você pode rodar os testes e verificar se tudo funciona. Se funcionar, está concluído. 😎
+
+## Pydantic v1 no v2 { #pydantic-v1-in-v2 }
+
+O Pydantic v2 inclui tudo do Pydantic v1 como um submódulo `pydantic.v1`. Mas isso não é mais suportado em versões acima do Python 3.13.
+
+Isso significa que você pode instalar a versão mais recente do Pydantic v2 e importar e usar os componentes antigos do Pydantic v1 a partir desse submódulo, como se tivesse o Pydantic v1 antigo instalado.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}
+
+### Suporte do FastAPI ao Pydantic v1 no v2 { #fastapi-support-for-pydantic-v1-in-v2 }
+
+Desde o FastAPI 0.119.0, há também suporte parcial ao Pydantic v1 a partir de dentro do Pydantic v2, para facilitar a migração para o v2.
+
+Assim, você pode atualizar o Pydantic para a versão 2 mais recente e alterar os imports para usar o submódulo `pydantic.v1`, e em muitos casos tudo simplesmente funcionará.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py hl[2,5,15] *}
+
+/// warning | Atenção
+
+Tenha em mente que, como a equipe do Pydantic não oferece mais suporte ao Pydantic v1 nas versões recentes do Python, a partir do Python 3.14, o uso de `pydantic.v1` também não é suportado no Python 3.14 e superiores.
+
+///
+
+### Pydantic v1 e v2 na mesma aplicação { #pydantic-v1-and-v2-on-the-same-app }
+
+Não é **suportado** pelo Pydantic ter um modelo do Pydantic v2 com campos próprios definidos como modelos do Pydantic v1, ou vice-versa.
+
+```mermaid
+graph TB
+ subgraph "❌ Not Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+...mas, você pode ter modelos separados usando Pydantic v1 e v2 na mesma aplicação.
+
+```mermaid
+graph TB
+ subgraph "✅ Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+Em alguns casos, é até possível ter modelos Pydantic v1 e v2 na mesma **operação de rota** na sua aplicação FastAPI:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}
+
+No exemplo acima, o modelo de entrada é um modelo Pydantic v1, e o modelo de saída (definido em `response_model=ItemV2`) é um modelo Pydantic v2.
+
+### Parâmetros do Pydantic v1 { #pydantic-v1-parameters }
+
+Se você precisar usar algumas das ferramentas específicas do FastAPI para parâmetros como `Body`, `Query`, `Form` etc. com modelos do Pydantic v1, pode importá-las de `fastapi.temp_pydantic_v1_params` enquanto conclui a migração para o Pydantic v2:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py hl[4,18] *}
+
+### Migre em etapas { #migrate-in-steps }
+
+/// tip | Dica
+
+Primeiro tente com o `bump-pydantic`, se seus testes passarem e isso funcionar, então você concluiu tudo com um único comando. ✨
+
+///
+
+Se o `bump-pydantic` não funcionar para o seu caso, você pode usar o suporte a modelos Pydantic v1 e v2 na mesma aplicação para fazer a migração para o Pydantic v2 gradualmente.
+
+Você poderia primeiro atualizar o Pydantic para usar a versão 2 mais recente e alterar os imports para usar `pydantic.v1` para todos os seus modelos.
+
+Depois, você pode começar a migrar seus modelos do Pydantic v1 para o v2 em grupos, em etapas graduais. 🚶
diff --git a/docs/pt/docs/how-to/separate-openapi-schemas.md b/docs/pt/docs/how-to/separate-openapi-schemas.md
new file mode 100644
index 0000000000000..f757025a097d0
--- /dev/null
+++ b/docs/pt/docs/how-to/separate-openapi-schemas.md
@@ -0,0 +1,102 @@
+# Esquemas OpenAPI Separados para Entrada e Saída ou Não { #separate-openapi-schemas-for-input-and-output-or-not }
+
+Desde que o **Pydantic v2** foi lançado, o OpenAPI gerado é um pouco mais exato e **correto** do que antes. 😎
+
+De fato, em alguns casos, ele terá até **dois JSON Schemas** no OpenAPI para o mesmo modelo Pydantic, para entrada e saída, dependendo se eles possuem **valores padrão**.
+
+Vamos ver como isso funciona e como alterar se for necessário.
+
+## Modelos Pydantic para Entrada e Saída { #pydantic-models-for-input-and-output }
+
+Digamos que você tenha um modelo Pydantic com valores padrão, como este:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *}
+
+### Modelo para Entrada { #model-for-input }
+
+Se você usar esse modelo como entrada, como aqui:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *}
+
+... então o campo `description` **não será obrigatório**. Porque ele tem um valor padrão de `None`.
+
+### Modelo de Entrada na Documentação { #input-model-in-docs }
+
+Você pode confirmar que na documentação, o campo `description` não tem um **asterisco vermelho**, não é marcado como obrigatório:
+
+
+
+
+
+
+- Framework FastAPI, alta performance, fácil de aprender, fácil de codar, pronto para produção + Framework FastAPI, alta performance, fácil de aprender, rápido para codar, pronto para produção
--- -**Documentação**: https://fastapi.tiangolo.com +**Documentação**: [https://fastapi.tiangolo.com/pt](https://fastapi.tiangolo.com/pt) -**Código fonte**: https://github.com/tiangolo/fastapi +**Código fonte**: [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi) --- -FastAPI é um moderno e rápido (alta performance) _framework web_ para construção de APIs com Python 3.6 ou superior, baseado nos _type hints_ padrões do Python. +FastAPI é um framework web moderno e rápido (alta performance) para construção de APIs com Python, baseado nos type hints padrões do Python. Os recursos chave são: -* **Rápido**: alta performance, equivalente a **NodeJS** e **Go** (graças ao Starlette e Pydantic). [Um dos frameworks mais rápidos disponíveis](#performance). +* **Rápido**: alta performance, equivalente a **NodeJS** e **Go** (graças ao Starlette e Pydantic). [Um dos frameworks Python mais rápidos disponíveis](#performance). * **Rápido para codar**: Aumenta a velocidade para desenvolver recursos entre 200% a 300%. * * **Poucos bugs**: Reduz cerca de 40% de erros induzidos por humanos (desenvolvedores). * -* **Intuitivo**: Grande suporte a _IDEs_. _Auto-Complete_ em todos os lugares. Menos tempo debugando. -* **Fácil**: Projetado para ser fácil de aprender e usar. Menos tempo lendo documentação. -* **Enxuto**: Minimize duplicação de código. Múltiplos recursos para cada declaração de parâmetro. Menos bugs. +* **Intuitivo**: Grande suporte a editores. Completação em todos os lugares. Menos tempo debugando. +* **Fácil**: Projetado para ser fácil de aprender e usar. Menos tempo lendo docs. +* **Enxuto**: Minimize duplicação de código. Múltiplas funcionalidades para cada declaração de parâmetro. Menos bugs. * **Robusto**: Tenha código pronto para produção. E com documentação interativa automática. -* **Baseado em padrões**: Baseado em (e totalmente compatível com) os padrões abertos para APIs: OpenAPI (anteriormente conhecido como Swagger) e _JSON Schema_. +* **Baseado em padrões**: Baseado em (e totalmente compatível com) os padrões abertos para APIs: [OpenAPI](https://github.com/OAI/OpenAPI-Specification) (anteriormente conhecido como Swagger) e [JSON Schema](https://json-schema.org/). * estimativas baseadas em testes realizados com equipe interna de desenvolvimento, construindo aplicações em produção. -## Patrocinadores Ouro +## Patrocinadores { #sponsors } -{% if sponsors %} +### Patrocinador Keystone { #keystone-sponsor } + +{% for sponsor in sponsors.keystone -%} +
-FastAPI está nos ombros de gigantes:
+## **Typer**, o FastAPI das interfaces de linhas de comando { #typer-the-fastapi-of-clis }
-* Starlette para as partes web.
-* Pydantic para a parte de dados.
+uvicorn main:app --reload...fastapi dev...email_validator - para validação de email.
+### Dependências opcionais adicionais { #additional-optional-dependencies }
-Usados por Starlette:
+Existem algumas dependências adicionais que você pode querer instalar.
-* httpx - Necessário se você quiser utilizar o `TestClient`.
-* jinja2 - Necessário se você quiser utilizar a configuração padrão de templates.
-* python-multipart - Necessário se você quiser suporte com "parsing" de formulário, com `request.form()`.
-* itsdangerous - Necessário para suporte a `SessionMiddleware`.
-* pyyaml - Necessário para suporte a `SchemaGenerator` da Starlette (você provavelmente não precisará disso com o FastAPI).
-* graphene - Necessário para suporte a `GraphQLApp`.
-* ujson - Necessário se você quer utilizar `UJSONResponse`.
+Dependências opcionais adicionais do Pydantic:
-Usados por FastAPI / Starlette:
+* [`pydantic-settings`](https://docs.pydantic.dev/latest/usage/pydantic_settings/) - para gerenciamento de configurações.
+* [`pydantic-extra-types`](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/) - para tipos extras a serem utilizados com o Pydantic.
-* uvicorn - para o servidor que carrega e serve sua aplicação.
-* orjson - Necessário se você quer utilizar `ORJSONResponse`.
+Dependências opcionais adicionais do FastAPI:
-Você pode instalar todas essas dependências com `pip install fastapi[all]`.
+* [`orjson`](https://github.com/ijl/orjson) - Obrigatório se você deseja utilizar o `ORJSONResponse`.
+* [`ujson`](https://github.com/esnme/ultrajson) - Obrigatório se você deseja utilizar o `UJSONResponse`.
-## Licença
+## Licença { #license }
Esse projeto é licenciado sob os termos da licença MIT.
diff --git a/docs/pt/docs/learn/index.md b/docs/pt/docs/learn/index.md
new file mode 100644
index 0000000000000..1f04929f7d4fb
--- /dev/null
+++ b/docs/pt/docs/learn/index.md
@@ -0,0 +1,5 @@
+# Aprender { #learn }
+
+Aqui estão as seções introdutórias e os tutoriais para aprender o **FastAPI**.
+
+Pode considerar isto um **livro**, um **curso**, a forma **oficial** e recomendada de aprender o FastAPI. 😎
diff --git a/docs/pt/docs/project-generation.md b/docs/pt/docs/project-generation.md
index c98bd069df5ae..8a34071a655ad 100644
--- a/docs/pt/docs/project-generation.md
+++ b/docs/pt/docs/project-generation.md
@@ -1,84 +1,28 @@
-# Geração de Projetos - Modelo
-
-Você pode usar um gerador de projetos para começar, por já incluir configurações iniciais, segurança, banco de dados e os primeiros _endpoints_ API já feitos para você.
-
-Um gerador de projetos sempre terá uma pré-configuração que você pode atualizar e adaptar para suas próprias necessidades, mas pode ser um bom ponto de partida para seu projeto.
-
-## Full Stack FastAPI PostgreSQL
-
-GitHub: https://github.com/tiangolo/full-stack-fastapi-postgresql
-
-### Full Stack FastAPI PostgreSQL - Recursos
-
-* Integração completa **Docker**.
-* Modo de implantação Docker Swarm.
-* Integração e otimização **Docker Compose** para desenvolvimento local.
-* **Pronto para Produção** com servidor _web_ usando Uvicorn e Gunicorn.
-* _Backend_ **FastAPI** Python:
- * **Rápido**: Alta performance, no nível de **NodeJS** e **Go** (graças ao Starlette e Pydantic).
- * **Intuitivo**: Ótimo suporte de editor. _Auto-Complete_ em todo lugar. Menos tempo _debugando_.
- * **Fácil**: Projetado para ser fácil de usar e aprender. Menos tempo lendo documentações.
- * **Curto**: Minimize duplicação de código. Múltiplos recursos para cada declaração de parâmetro.
- * **Robusto**: Tenha código pronto para produção. Com documentação interativa automática.
- * **Baseado em Padrões**: Baseado em (e completamente compatível com) padrões abertos para APIs: OpenAPI e JSON Schema.
- * **Muitos outros recursos** incluindo validação automática, serialização, documentação interativa, autenticação com _tokens_ OAuth2 JWT etc.
-* **Senha segura** _hashing_ por padrão.
-* Autenticação **Token JWT**.
-* Modelos **SQLAlchemy** (independente de extensões Flask, para que eles possam ser usados com _workers_ Celery diretamente).
-* Modelos básicos para usuários (modifique e remova conforme suas necessidades).
-* Migrações **Alembic**.
-* **CORS** (_Cross Origin Resource Sharing_ - Compartilhamento de Recursos Entre Origens).
-* _Worker_ **Celery** que pode importar e usar modelos e códigos do resto do _backend_ seletivamente.
-* Testes _backend_ _REST_ baseados no **Pytest**, integrados com Docker, então você pode testar a interação completa da API, independente do banco de dados. Como roda no Docker, ele pode construir um novo repositório de dados do zero toda vez (assim você pode usar ElasticSearch, MongoDB, CouchDB, ou o que quiser, e apenas testar que a API esteja funcionando).
-* Fácil integração com Python através dos **Kernels Jupyter** para desenvolvimento remoto ou no Docker com extensões como Atom Hydrogen ou Visual Studio Code Jupyter.
-* _Frontend_ **Vue**:
- * Gerado com Vue CLI.
- * Controle de **Autenticação JWT**.
- * Visualização de _login_.
- * Após o _login_, visualização do painel de controle principal.
- * Painel de controle principal com criação e edição de usuário.
- * Edição do próprio usuário.
- * **Vuex**.
- * **Vue-router**.
- * **Vuetify** para belos componentes _material design_.
- * **TypeScript**.
- * Servidor Docker baseado em **Nginx** (configurado para rodar "lindamente" com Vue-router).
- * Construção multi-estágio Docker, então você não precisa salvar ou _commitar_ código compilado.
- * Testes _frontend_ rodados na hora da construção (pode ser desabilitado também).
- * Feito tão modular quanto possível, então ele funciona fora da caixa, mas você pode gerar novamente com Vue CLI ou criar conforme você queira, e reutilizar o que quiser.
-* **PGAdmin** para banco de dados PostgreSQL, você pode modificar para usar PHPMyAdmin e MySQL facilmente.
-* **Flower** para monitoração de tarefas Celery.
-* Balanceamento de carga entre _frontend_ e _backend_ com **Traefik**, então você pode ter ambos sob o mesmo domínio, separados por rota, mas servidos por diferentes containers.
-* Integração Traefik, incluindo geração automática de certificados **HTTPS** Let's Encrypt.
-* GitLab **CI** (integração contínua), incluindo testes _frontend_ e _backend_.
-
-## Full Stack FastAPI Couchbase
-
-GitHub: https://github.com/tiangolo/full-stack-fastapi-couchbase
-
-⚠️ **WARNING** ⚠️
-
-Se você está iniciando um novo projeto do zero, verifique as alternativas aqui.
-
-Por exemplo, o gerador de projetos Full Stack FastAPI PostgreSQL pode ser uma alternativa melhor, como ele é ativamente mantido e utilizado. E ele inclui todos os novos recursos e melhorias.
-
-Você ainda é livre para utilizar o gerador baseado em Couchbase se quiser, ele provavelmente ainda funciona bem, e você já tem um projeto gerado com ele que roda bem também (e você provavelmente já atualizou ele para encaixar nas suas necessidades).
-
-Você pode ler mais sobre nas documentaçãoes do repositório.
-
-## Full Stack FastAPI MongoDB
-
-...pode demorar, dependendo do meu tempo disponível e outros fatores. 😅 🎉
-
-## Modelos de Aprendizado de Máquina com spaCy e FastAPI
-
-GitHub: https://github.com/microsoft/cookiecutter-spacy-fastapi
-
-### Modelos de Aprendizado de Máquina com spaCy e FastAPI - Recursos
-
-* Integração com modelo NER **spaCy**.
-* Formato de requisição **Busca Cognitiva Azure** acoplado.
-* Servidor Python _web_ **Pronto para Produção** usando Uvicorn e Gunicorn.
-* Implantação **Azure DevOps** Kubernetes (AKS) CI/CD acoplada.
-* **Multilingual** facilmente escolhido como uma das linguagens spaCy acopladas durante a configuração do projeto.
-* **Facilmente extensível** para outros modelos de _frameworks_ (Pytorch, Tensorflow), não apenas spaCy.
+# Full Stack FastAPI Template { #full-stack-fastapi-template }
+
+_Templates_, embora tipicamente venham com alguma configuração específica, são desenhados para serem flexíveis e customizáveis. Isso permite que você os modifique e adapte para as especificações do seu projeto, fazendo-os um excelente ponto de partida. 🏁
+
+Você pode usar esse _template_ para começar, já que ele inclui várias configurações iniciais, segurança, banco de dados, e alguns _endpoints_ de API já feitos para você.
+
+Repositório GitHub: [Full Stack FastAPI Template](https://github.com/tiangolo/full-stack-fastapi-template)
+
+## Full Stack FastAPI Template - Pilha de Tecnologias e Recursos { #full-stack-fastapi-template-technology-stack-and-features }
+
+- ⚡ [**FastAPI**](https://fastapi.tiangolo.com/pt) para a API do backend em Python.
+ - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) para as interações do Python com bancos de dados SQL (ORM).
+ - 🔍 [Pydantic](https://docs.pydantic.dev), usado pelo FastAPI, para validação de dados e gerenciamento de configurações.
+ - 💾 [PostgreSQL](https://www.postgresql.org) como banco de dados SQL.
+- 🚀 [React](https://react.dev) para o frontend.
+ - 💃 Usando TypeScript, hooks, Vite, e outras partes de uma _stack_ frontend moderna.
+ - 🎨 [Tailwind CSS](https://tailwindcss.com) e [shadcn/ui](https://ui.shadcn.com) para os componentes de frontend.
+ - 🤖 Um cliente frontend automaticamente gerado.
+ - 🧪 [Playwright](https://playwright.dev) para testes Ponta-a-Ponta.
+ - 🦇 Suporte para modo escuro.
+- 🐋 [Docker Compose](https://www.docker.com) para desenvolvimento e produção.
+- 🔒 Hash seguro de senhas por padrão.
+- 🔑 Autenticação JWT (JSON Web Token).
+- 📫 Recuperação de senhas baseada em email.
+- ✅ Testes com [Pytest](https://pytest.org).
+- 📞 [Traefik](https://traefik.io) como proxy reverso / balanceador de carga.
+- 🚢 Instruções de deployment usando Docker Compose, incluindo como configurar um proxy frontend com Traefik para gerenciar automaticamente certificados HTTPS.
+- 🏭 CI (Integração Contínua) e CD (_Deploy_ Contínuo) baseado em GitHub Actions.
diff --git a/docs/pt/docs/python-types.md b/docs/pt/docs/python-types.md
index 9f12211c74010..42953653be444 100644
--- a/docs/pt/docs/python-types.md
+++ b/docs/pt/docs/python-types.md
@@ -1,28 +1,28 @@
-# Introdução aos tipos Python
+# Introdução aos tipos Python { #python-types-intro }
-**Python 3.6 +** tem suporte para "type hints" opcionais.
+O Python possui suporte para "type hints" opcionais (também chamados de "type annotations").
-Esses **"type hints"** são uma nova sintaxe (desde Python 3.6+) que permite declarar o tipo de uma variável.
+Esses **"type hints"** ou anotações são uma sintaxe especial que permite declarar o tipo de uma variável.
Ao declarar tipos para suas variáveis, editores e ferramentas podem oferecer um melhor suporte.
-Este é apenas um **tutorial rápido / atualização** sobre type hints Python. Ele cobre apenas o mínimo necessário para usá-los com o **FastAPI** ... que é realmente muito pouco.
+Este é apenas um **tutorial rápido / atualização** sobre type hints do Python. Ele cobre apenas o mínimo necessário para usá-los com o **FastAPI**... que é realmente muito pouco.
-O **FastAPI** é baseado nesses type hints, eles oferecem muitas vantagens e benefícios.
+O **FastAPI** é todo baseado nesses type hints, eles oferecem muitas vantagens e benefícios.
Mas mesmo que você nunca use o **FastAPI**, você se beneficiaria de aprender um pouco sobre eles.
-!!! note "Nota"
- Se você é um especialista em Python e já sabe tudo sobre type hints, pule para o próximo capítulo.
+/// note | Nota
+Se você é um especialista em Python e já sabe tudo sobre type hints, pule para o próximo capítulo.
-## Motivação
+///
+
+## Motivação { #motivation }
Vamos começar com um exemplo simples:
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001_py310.py *}
A chamada deste programa gera:
@@ -33,20 +33,18 @@ John Doe
A função faz o seguinte:
* Pega um `first_name` e `last_name`.
-* Converte a primeira letra de cada uma em maiúsculas com `title ()`.
-* Concatena com um espaço no meio.
+* Converte a primeira letra de cada uma em maiúsculas com `title()`.
+* Concatena com um espaço no meio.
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}
-### Edite-o
+### Edite-o { #edit-it }
É um programa muito simples.
Mas agora imagine que você estava escrevendo do zero.
-Em algum momento você teria iniciado a definição da função, já tinha os parâmetros prontos ...
+Em algum momento você teria iniciado a definição da função, já tinha os parâmetros prontos...
Mas então você deve chamar "esse método que converte a primeira letra em maiúscula".
@@ -54,13 +52,13 @@ Era `upper`? Era `uppercase`? `first_uppercase`? `capitalize`?
Em seguida, tente com o velho amigo do programador, o preenchimento automático do editor.
-Você digita o primeiro parâmetro da função, `first_name`, depois um ponto (`.`) e, em seguida, pressiona `Ctrl + Space` para acionar a conclusão.
+Você digita o primeiro parâmetro da função, `first_name`, depois um ponto (`.`) e, em seguida, pressiona `Ctrl+Space` para acionar o preenchimento automático.
Mas, infelizmente, você não obtém nada útil:
-### Adicionar tipos
+### Adicionar tipos { #add-types }
Vamos modificar uma única linha da versão anterior.
@@ -80,9 +78,7 @@ para:
Esses são os "type hints":
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
Isso não é o mesmo que declarar valores padrão como seria com:
@@ -92,45 +88,41 @@ Isso não é o mesmo que declarar valores padrão como seria com:
É uma coisa diferente.
-Estamos usando dois pontos (`:`), não é igual a (`=`).
+Estamos usando dois pontos (`:`), não sinal de igual (`=`).
-E adicionar type hints normalmente não muda o que acontece do que aconteceria sem elas.
+E adicionar type hints normalmente não muda o que acontece do que aconteceria sem eles.
Mas agora, imagine que você está novamente no meio da criação dessa função, mas com type hints.
-No mesmo ponto, você tenta acionar o preenchimento automático com o `Ctrl Space` e vê:
+No mesmo ponto, você tenta acionar o preenchimento automático com o `Ctrl+Space` e vê:
-Com isso, você pode rolar, vendo as opções, até encontrar o que "toca uma campainha":
+Com isso, você pode rolar, vendo as opções, até encontrar o que "soa familiar":
-## Mais motivação
+## Mais motivação { #more-motivation }
-Marque esta função, ela já possui type hints:
+Verifique esta função, ela já possui type hints:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
-Como o editor conhece os tipos de variáveis, você não apenas obtém a conclusão, mas também as verificações de erro:
+Como o editor conhece os tipos das variáveis, você não obtém apenas o preenchimento automático, mas também as verificações de erro:
-Agora você sabe que precisa corrigí-lo, converta `age` em uma string com `str (age)`:
+Agora você sabe que precisa corrigi-la, convertendo `age` em uma string com `str(age)`:
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
-## Tipos de declaração
+## Declarando tipos { #declaring-types }
Você acabou de ver o local principal para declarar type hints. Como parâmetros de função.
Este também é o principal local em que você os usaria com o **FastAPI**.
-### Tipos simples
+### Tipos simples { #simple-types }
Você pode declarar todos os tipos padrão de Python, não apenas `str`.
@@ -141,44 +133,54 @@ Você pode usar, por exemplo:
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
+
+### Módulo `typing` { #typing-module }
+
+Para alguns casos adicionais, você pode precisar importar alguns itens do módulo padrão `typing`, por exemplo, quando quiser declarar que algo pode ter "qualquer tipo", você pode usar `Any` de `typing`:
+
+```python
+from typing import Any
+
+
+def some_function(data: Any):
+ print(data)
```
-### Tipos genéricos com parâmetros de tipo
+### Tipos genéricos { #generic-types }
-Existem algumas estruturas de dados que podem conter outros valores, como `dict`, `list`, `set` e `tuple`. E os valores internos também podem ter seu próprio tipo.
+Alguns tipos podem receber "parâmetros de tipo" entre colchetes, para definir seus tipos internos, por exemplo, uma "lista de strings" seria declarada como `list[str]`.
-Para declarar esses tipos e os tipos internos, você pode usar o módulo Python padrão `typing`.
+Esses tipos que podem receber parâmetros de tipo são chamados **tipos genéricos** ou **genéricos**.
-Ele existe especificamente para suportar esses type hints.
+Você pode usar os mesmos tipos internos como genéricos (com colchetes e tipos dentro):
-#### `List`
+* `list`
+* `tuple`
+* `set`
+* `dict`
-Por exemplo, vamos definir uma variável para ser uma `lista` de `str`.
+#### List { #list }
-Em `typing`, importe `List` (com um `L` maiúsculo):
+Por exemplo, vamos definir uma variável para ser uma `list` de `str`.
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+Declare a variável, com a mesma sintaxe com dois pontos (`:`).
-Declare a variável com a mesma sintaxe de dois pontos (`:`).
+Como o tipo, coloque `list`.
-Como o tipo, coloque a `List`.
+Como a lista é um tipo que contém tipos internos, você os coloca entre colchetes:
-Como a lista é um tipo que contém alguns tipos internos, você os coloca entre colchetes:
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
-```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+/// info | Informação
+
+Esses tipos internos dentro dos colchetes são chamados de "parâmetros de tipo".
-!!! tip "Dica"
- Esses tipos internos entre colchetes são chamados de "parâmetros de tipo".
+Neste caso, `str` é o parâmetro de tipo passado para `list`.
- Nesse caso, `str` é o parâmetro de tipo passado para `List`.
+///
-Isso significa que: "a variável `items` é uma `list`, e cada um dos itens desta lista é uma `str`".
+Isso significa: "a variável `items` é uma `list`, e cada um dos itens desta lista é uma `str`".
Ao fazer isso, seu editor pode fornecer suporte mesmo durante o processamento de itens da lista:
@@ -190,20 +192,18 @@ Observe que a variável `item` é um dos elementos da lista `items`.
E, ainda assim, o editor sabe que é um `str` e fornece suporte para isso.
-#### `Tuple` e `Set`
+#### Tuple e Set { #tuple-and-set }
Você faria o mesmo para declarar `tuple`s e `set`s:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
-```
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
-Isso significa que:
+Isso significa:
* A variável `items_t` é uma `tuple` com 3 itens, um `int`, outro `int` e uma `str`.
* A variável `items_s` é um `set`, e cada um de seus itens é do tipo `bytes`.
-#### `Dict`
+#### Dict { #dict }
Para definir um `dict`, você passa 2 parâmetros de tipo, separados por vírgulas.
@@ -211,62 +211,65 @@ O primeiro parâmetro de tipo é para as chaves do `dict`.
O segundo parâmetro de tipo é para os valores do `dict`:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
-```
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
Isso significa que:
-* A variável `prices` é um dict`:
+* A variável `prices` é um `dict`:
* As chaves deste `dict` são do tipo `str` (digamos, o nome de cada item).
* Os valores deste `dict` são do tipo `float` (digamos, o preço de cada item).
-#### `Opcional`
+#### Union { #union }
+
+Você pode declarar que uma variável pode ser de qualquer um dentre **vários tipos**, por exemplo, um `int` ou um `str`.
-Você também pode usar o `Opcional` para declarar que uma variável tem um tipo, como `str`, mas que é "opcional", o que significa que também pode ser `None`:
+Para defini-la, você usa a barra vertical (`|`) para separar ambos os tipos.
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+Isso é chamado de "união", porque a variável pode ser qualquer coisa na união desses dois conjuntos de tipos.
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
```
-O uso de `Opcional [str]` em vez de apenas `str` permitirá que o editor o ajude a detectar erros, onde você pode estar assumindo que um valor é sempre um `str`, quando na verdade também pode ser `None`.
+Isso significa que `item` pode ser um `int` ou um `str`.
+
+#### Possivelmente `None` { #possibly-none }
-#### Tipos genéricos
+Você pode declarar que um valor pode ter um tipo, como `str`, mas que ele também pode ser `None`.
-Esses tipos que usam parâmetros de tipo entre colchetes, como:
+//// tab | Python 3.10+
-* `List`
-* `Tuple`
-* `Set`
-* `Dict`
-* `Opcional`
-* ...e outros.
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
-são chamados **tipos genéricos** ou **genéricos**.
+////
-### Classes como tipos
+Usar `str | None` em vez de apenas `str` permitirá que o editor o ajude a detectar erros em que você poderia estar assumindo que um valor é sempre um `str`, quando na verdade ele também pode ser `None`.
+
+### Classes como tipos { #classes-as-types }
Você também pode declarar uma classe como o tipo de uma variável.
Digamos que você tenha uma classe `Person`, com um nome:
-```Python hl_lines="1 2 3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
Então você pode declarar que uma variável é do tipo `Person`:
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
E então, novamente, você recebe todo o suporte do editor:
-## Modelos Pydantic
+Perceba que isso significa que "`one_person` é uma **instância** da classe `Person`".
+
+Isso não significa que "`one_person` é a **classe** chamada `Person`".
+
+## Modelos Pydantic { #pydantic-models }
- Pydantic é uma biblioteca Python para executar a validação de dados.
+[Pydantic](https://docs.pydantic.dev/) é uma biblioteca Python para executar a validação de dados.
Você declara a "forma" dos dados como classes com atributos.
@@ -276,20 +279,47 @@ Em seguida, você cria uma instância dessa classe com alguns valores e ela os v
E você recebe todo o suporte do editor com esse objeto resultante.
-Retirado dos documentos oficiais dos Pydantic:
+Um exemplo da documentação oficial do Pydantic:
-```Python
-{!../../../docs_src/python_types/tutorial011.py!}
-```
+{* ../../docs_src/python_types/tutorial011_py310.py *}
+
+/// info | Informação
+
+Para saber mais sobre o [Pydantic, verifique a documentação](https://docs.pydantic.dev/).
+
+///
+
+O **FastAPI** é todo baseado em Pydantic.
-!!! info "Informação"
- Para saber mais sobre o Pydantic, verifique seus documentos .
+Você verá muito mais disso na prática no [Tutorial - Guia do usuário](tutorial/index.md).
-**FastAPI** é todo baseado em Pydantic.
+## Type Hints com Metadados de Anotações { #type-hints-with-metadata-annotations }
-Você verá muito mais disso na prática no [Tutorial - Guia do usuário](tutorial/index.md){.internal-link target=_blank}.
+O Python também possui uma funcionalidade que permite incluir **metadados adicionais** nesses type hints utilizando `Annotated`.
-## Type hints em **FastAPI**
+Você pode importar `Annotated` de `typing`.
+
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
+
+O Python em si não faz nada com este `Annotated`. E para editores e outras ferramentas, o tipo ainda é `str`.
+
+Mas você pode utilizar este espaço dentro do `Annotated` para fornecer ao **FastAPI** metadados adicionais sobre como você deseja que a sua aplicação se comporte.
+
+O importante aqui de se lembrar é que **o primeiro *type parameter*** que você informar ao `Annotated` é o **tipo de fato**. O resto é apenas metadado para outras ferramentas.
+
+Por hora, você precisa apenas saber que o `Annotated` existe, e que ele é Python padrão. 😎
+
+Mais tarde você verá o quão **poderoso** ele pode ser.
+
+/// tip | Dica
+
+O fato de que isso é **Python padrão** significa que você ainda obtém a **melhor experiência de desenvolvedor possível** no seu editor, com as ferramentas que você utiliza para analisar e refatorar o seu código, etc. ✨
+
+E também que o seu código será muito compatível com diversas outras ferramentas e bibliotecas Python. 🚀
+
+///
+
+## Type hints no **FastAPI** { #type-hints-in-fastapi }
O **FastAPI** aproveita esses type hints para fazer várias coisas.
@@ -298,18 +328,21 @@ Com o **FastAPI**, você declara parâmetros com type hints e obtém:
* **Suporte ao editor**.
* **Verificações de tipo**.
-... e **FastAPI** usa as mesmas declarações para:
+... e o **FastAPI** usa as mesmas declarações para:
-* **Definir requisitos**: dos parâmetros do caminho da solicitação, parâmetros da consulta, cabeçalhos, corpos, dependências, etc.
-* **Converter dados**: da solicitação para o tipo necessário.
-* **Validar dados**: provenientes de cada solicitação:
- * A geração de **erros automáticos** retornou ao cliente quando os dados são inválidos.
-* **Documente** a API usando OpenAPI:
- * que é usado pelas interfaces de usuário da documentação interativa automática.
+* **Definir requisitos**: dos parâmetros de path da request, parâmetros da query, cabeçalhos, corpos, dependências, etc.
+* **Converter dados**: da request para o tipo necessário.
+* **Validar dados**: provenientes de cada request:
+ * Gerando **erros automáticos** retornados ao cliente quando os dados são inválidos.
+* **Documentar** a API usando OpenAPI:
+ * que é usada pelas interfaces de usuário da documentação interativa automática.
-Tudo isso pode parecer abstrato. Não se preocupe. Você verá tudo isso em ação no [Tutorial - Guia do usuário](tutorial/index.md){.internal-link target=_blank}.
+Tudo isso pode parecer abstrato. Não se preocupe. Você verá tudo isso em ação no [Tutorial - Guia do usuário](tutorial/index.md).
O importante é que, usando tipos padrão de Python, em um único local (em vez de adicionar mais classes, decoradores, etc.), o **FastAPI** fará muito trabalho para você.
-!!! info "Informação"
- Se você já passou por todo o tutorial e voltou para ver mais sobre os tipos, um bom recurso é a "cheat sheet" do `mypy` .
+/// info | Informação
+
+Se você já passou por todo o tutorial e voltou para ver mais sobre os tipos, um bom recurso é [a "cheat sheet" do `mypy`](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html).
+
+///
diff --git a/docs/pt/docs/resources/index.md b/docs/pt/docs/resources/index.md
new file mode 100644
index 0000000000000..24cea95641a15
--- /dev/null
+++ b/docs/pt/docs/resources/index.md
@@ -0,0 +1,3 @@
+# Recursos { #resources }
+
+Material complementar, links externos e mais. ✈️
diff --git a/docs/pt/docs/translation-banner.md b/docs/pt/docs/translation-banner.md
new file mode 100644
index 0000000000000..f3069ddd77916
--- /dev/null
+++ b/docs/pt/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 Tradução por IA e humanos
+
+Esta tradução foi feita por IA orientada por humanos. 🤝
+
+Ela pode conter erros de interpretação do significado original ou soar pouco natural, etc. 🤖
+
+Você pode melhorar esta tradução [ajudando-nos a orientar melhor o LLM de IA](https://fastapi.tiangolo.com/pt/contributing/#translations).
+
+[Versão em inglês](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/pt/docs/tutorial/background-tasks.md b/docs/pt/docs/tutorial/background-tasks.md
index 625fa2b111d23..20152d9cf4817 100644
--- a/docs/pt/docs/tutorial/background-tasks.md
+++ b/docs/pt/docs/tutorial/background-tasks.md
@@ -1,94 +1,85 @@
-# Tarefas em segundo plano
+# Tarefas em segundo plano { #background-tasks }
-Você pode definir tarefas em segundo plano a serem executadas _ após _ retornar uma resposta.
+Você pode definir tarefas em segundo plano para serem executadas *após* retornar uma resposta.
-Isso é útil para operações que precisam acontecer após uma solicitação, mas que o cliente realmente não precisa esperar a operação ser concluída para receber a resposta.
+Isso é útil para operações que precisam acontecer após uma request, mas que o cliente não precisa realmente esperar a operação terminar antes de receber a resposta.
Isso inclui, por exemplo:
-- Envio de notificações por email após a realização de uma ação:
- - Como conectar-se a um servidor de e-mail e enviar um e-mail tende a ser "lento" (vários segundos), você pode retornar a resposta imediatamente e enviar a notificação por e-mail em segundo plano.
-- Processando dados:
- - Por exemplo, digamos que você receba um arquivo que deve passar por um processo lento, você pode retornar uma resposta de "Aceito" (HTTP 202) e processá-lo em segundo plano.
+* Notificações por e-mail enviadas após realizar uma ação:
+ * Como conectar-se a um servidor de e-mail e enviar um e-mail tende a ser “lento” (vários segundos), você pode retornar a resposta imediatamente e enviar a notificação por e-mail em segundo plano.
+* Processamento de dados:
+ * Por exemplo, digamos que você receba um arquivo que precisa passar por um processo lento; você pode retornar uma resposta “Accepted” (HTTP 202) e processar o arquivo em segundo plano.
-## Usando `BackgroundTasks`
+## Usando `BackgroundTasks` { #using-backgroundtasks }
-Primeiro, importe `BackgroundTasks` e defina um parâmetro em sua _função de operação de caminho_ com uma declaração de tipo de `BackgroundTasks`:
+Primeiro, importe `BackgroundTasks` e defina um parâmetro na sua *função de operação de rota* com uma declaração de tipo `BackgroundTasks`:
-```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
O **FastAPI** criará o objeto do tipo `BackgroundTasks` para você e o passará como esse parâmetro.
-## Criar uma função de tarefa
+## Crie uma função de tarefa { #create-a-task-function }
-Crie uma função a ser executada como tarefa em segundo plano.
+Crie uma função para ser executada como a tarefa em segundo plano.
É apenas uma função padrão que pode receber parâmetros.
-Pode ser uma função `async def` ou `def` normal, o **FastAPI** saberá como lidar com isso corretamente.
+Pode ser uma função `async def` ou um `def` normal, o **FastAPI** saberá como lidar com isso corretamente.
-Nesse caso, a função de tarefa gravará em um arquivo (simulando o envio de um e-mail).
+Neste caso, a função da tarefa escreverá em um arquivo (simulando o envio de um e-mail).
-E como a operação de gravação não usa `async` e `await`, definimos a função com `def` normal:
+E como a operação de escrita não usa `async` e `await`, definimos a função com um `def` normal:
-```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
-## Adicionar a tarefa em segundo plano
+## Adicione a tarefa em segundo plano { #add-the-background-task }
-Dentro de sua _função de operação de caminho_, passe sua função de tarefa para o objeto _tarefas em segundo plano_ com o método `.add_task()`:
+Dentro da sua *função de operação de rota*, passe sua função de tarefa para o objeto de *tarefas em segundo plano* com o método `.add_task()`:
-```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
-`.add_task()` recebe como argumentos:
+O `.add_task()` recebe como argumentos:
-- Uma função de tarefa a ser executada em segundo plano (`write_notification`).
-- Qualquer sequência de argumentos que deve ser passada para a função de tarefa na ordem (`email`).
-- Quaisquer argumentos nomeados que devem ser passados para a função de tarefa (`mensagem = "alguma notificação"`).
+* Uma função de tarefa a ser executada em segundo plano (`write_notification`).
+* Qualquer sequência de argumentos que deve ser passada para a função de tarefa na ordem (`email`).
+* Quaisquer argumentos nomeados que devem ser passados para a função de tarefa (`message="some notification"`).
-## Injeção de dependência
+## Injeção de dependências { #dependency-injection }
-Usar `BackgroundTasks` também funciona com o sistema de injeção de dependência, você pode declarar um parâmetro do tipo `BackgroundTasks` em vários níveis: em uma _função de operação de caminho_, em uma dependência (confiável), em uma subdependência, etc.
+Usar `BackgroundTasks` também funciona com o sistema de injeção de dependências; você pode declarar um parâmetro do tipo `BackgroundTasks` em vários níveis: em uma *função de operação de rota*, em uma dependência (dependable), em uma subdependência, etc.
-O **FastAPI** sabe o que fazer em cada caso e como reutilizar o mesmo objeto, de forma que todas as tarefas em segundo plano sejam mescladas e executadas em segundo plano posteriormente:
+O **FastAPI** sabe o que fazer em cada caso e como reutilizar o mesmo objeto, de forma que todas as tarefas em segundo plano sejam combinadas e executadas em segundo plano depois:
-```Python hl_lines="13 15 22 25"
-{!../../../docs_src/background_tasks/tutorial002.py!}
-```
-Neste exemplo, as mensagens serão gravadas no arquivo `log.txt` _após_ o envio da resposta.
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
-Se houver uma consulta na solicitação, ela será gravada no log em uma tarefa em segundo plano.
+Neste exemplo, as mensagens serão escritas no arquivo `log.txt` *após* o envio da resposta.
-E então outra tarefa em segundo plano gerada na _função de operação de caminho_ escreverá uma mensagem usando o parâmetro de caminho `email`.
+Se houver uma query na request, ela será registrada em uma tarefa em segundo plano.
-## Detalhes técnicos
+E então outra tarefa em segundo plano gerada na *função de operação de rota* escreverá uma mensagem usando o parâmetro de path `email`.
-A classe `BackgroundTasks` vem diretamente de `starlette.background`.
+## Detalhes técnicos { #technical-details }
-Ela é importada/incluída diretamente no FastAPI para que você possa importá-la do `fastapi` e evitar a importação acidental da alternativa `BackgroundTask` (sem o `s` no final) de `starlette.background`.
+A classe `BackgroundTasks` vem diretamente de [`starlette.background`](https://www.starlette.dev/background/).
-Usando apenas `BackgroundTasks` (e não `BackgroundTask`), é então possível usá-la como um parâmetro de _função de operação de caminho_ e deixar o **FastAPI** cuidar do resto para você, assim como ao usar o objeto `Request` diretamente.
+Ela é importada/incluída diretamente no FastAPI para que você possa importá-la de `fastapi` e evitar importar acidentalmente a alternativa `BackgroundTask` (sem o `s` no final) de `starlette.background`.
-Ainda é possível usar `BackgroundTask` sozinho no FastAPI, mas você deve criar o objeto em seu código e retornar uma Starlette `Response` incluindo-o.
+Usando apenas `BackgroundTasks` (e não `BackgroundTask`), é possível usá-la como um parâmetro de *função de operação de rota* e deixar o **FastAPI** cuidar do resto para você, assim como ao usar o objeto `Request` diretamente.
-Você pode ver mais detalhes na documentação oficiais da Starlette para tarefas em segundo plano .
+Ainda é possível usar `BackgroundTask` sozinho no FastAPI, mas você precisa criar o objeto no seu código e retornar uma `Response` da Starlette incluindo-o.
-## Ressalva
+Você pode ver mais detalhes na [documentação oficial da Starlette para tarefas em segundo plano](https://www.starlette.dev/background/).
-Se você precisa realizar cálculos pesados em segundo plano e não necessariamente precisa que seja executado pelo mesmo processo (por exemplo, você não precisa compartilhar memória, variáveis, etc), você pode se beneficiar do uso de outras ferramentas maiores, como Celery .
+## Ressalva { #caveat }
-Eles tendem a exigir configurações mais complexas, um gerenciador de fila de mensagens/tarefas, como RabbitMQ ou Redis, mas permitem que você execute tarefas em segundo plano em vários processos e, especialmente, em vários servidores.
+Se você precisar realizar computação pesada em segundo plano e não necessariamente precisar que seja executada pelo mesmo processo (por exemplo, você não precisa compartilhar memória, variáveis, etc.), pode se beneficiar do uso de outras ferramentas maiores, como o [Celery](https://docs.celeryq.dev).
-Para ver um exemplo, verifique os [Geradores de projeto](../project-generation.md){.internal-link target=\_blank}, todos incluem celery já configurado.
+Elas tendem a exigir configurações mais complexas, um gerenciador de fila de mensagens/tarefas, como RabbitMQ ou Redis, mas permitem executar tarefas em segundo plano em vários processos e, especialmente, em vários servidores.
-Mas se você precisa acessar variáveis e objetos do mesmo aplicativo **FastAPI**, ou precisa realizar pequenas tarefas em segundo plano (como enviar uma notificação por e-mail), você pode simplesmente usar `BackgroundTasks`.
+Mas se você precisa acessar variáveis e objetos da mesma aplicação **FastAPI**, ou precisa realizar pequenas tarefas em segundo plano (como enviar uma notificação por e-mail), você pode simplesmente usar `BackgroundTasks`.
-## Recapitulando
+## Recapitulando { #recap }
-Importe e use `BackgroundTasks` com parâmetros em _funções de operação de caminho_ e dependências para adicionar tarefas em segundo plano.
+Importe e use `BackgroundTasks` com parâmetros em *funções de operação de rota* e dependências para adicionar tarefas em segundo plano.
diff --git a/docs/pt/docs/tutorial/bigger-applications.md b/docs/pt/docs/tutorial/bigger-applications.md
new file mode 100644
index 0000000000000..971504fa4fe2a
--- /dev/null
+++ b/docs/pt/docs/tutorial/bigger-applications.md
@@ -0,0 +1,535 @@
+# Aplicações Maiores - Múltiplos Arquivos { #bigger-applications-multiple-files }
+
+Se você está construindo uma aplicação ou uma API web, é raro que você possa colocar tudo em um único arquivo.
+
+**FastAPI** oferece uma ferramenta conveniente para estruturar sua aplicação, mantendo toda a flexibilidade.
+
+/// info | Informação
+
+Se você vem do Flask, isso seria o equivalente aos Blueprints do Flask.
+
+///
+
+## Um exemplo de estrutura de arquivos { #an-example-file-structure }
+
+Digamos que você tenha uma estrutura de arquivos como esta:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ ├── dependencies.py
+│ └── routers
+│ │ ├── __init__.py
+│ │ ├── items.py
+│ │ └── users.py
+│ └── internal
+│ ├── __init__.py
+│ └── admin.py
+```
+
+/// tip | Dica
+
+Existem vários arquivos `__init__.py`: um em cada diretório ou subdiretório.
+
+Isso permite a importação de código de um arquivo para outro.
+
+Por exemplo, no arquivo `app/main.py`, você poderia ter uma linha como:
+
+```
+from app.routers import items
+```
+
+///
+
+* O diretório `app` contém tudo. E possui um arquivo vazio `app/__init__.py`, então ele é um "pacote Python" (uma coleção de "módulos Python"): `app`.
+* Ele contém um arquivo `app/main.py`. Como está dentro de um pacote Python (um diretório com um arquivo `__init__.py`), ele é um "módulo" desse pacote: `app.main`.
+* Existe também um arquivo `app/dependencies.py`, assim como `app/main.py`, ele é um "módulo": `app.dependencies`.
+* Há um subdiretório `app/routers/` com outro arquivo `__init__.py`, então ele é um "subpacote Python": `app.routers`.
+* O arquivo `app/routers/items.py` está dentro de um pacote, `app/routers/`, portanto é um submódulo: `app.routers.items`.
+* O mesmo com `app/routers/users.py`, ele é outro submódulo: `app.routers.users`.
+* Há também um subdiretório `app/internal/` com outro arquivo `__init__.py`, então ele é outro "subpacote Python": `app.internal`.
+* E o arquivo `app/internal/admin.py` é outro submódulo: `app.internal.admin`.
+
+
+
+## Inclua o mesmo router várias vezes com `prefix` diferentes { #include-the-same-router-multiple-times-with-different-prefix }
+
+Você também pode usar `.include_router()` várias vezes com o *mesmo* router usando prefixos diferentes.
+
+Isso pode ser útil, por exemplo, para expor a mesma API sob prefixos diferentes, por exemplo, `/api/v1` e `/api/latest`.
+
+Esse é um uso avançado que você pode não precisar, mas está lá caso precise.
+
+## Inclua um `APIRouter` em outro { #include-an-apirouter-in-another }
+
+Da mesma forma que você pode incluir um `APIRouter` em uma aplicação `FastAPI`, você pode incluir um `APIRouter` em outro `APIRouter` usando:
+
+```Python
+router.include_router(other_router)
+```
+
+Certifique-se de fazer isso antes de incluir `router` na aplicação `FastAPI`, para que as *operações de rota* de `other_router` também sejam incluídas.
diff --git a/docs/pt/docs/tutorial/body-fields.md b/docs/pt/docs/tutorial/body-fields.md
index 8f3313ae92c5c..25e11189e7731 100644
--- a/docs/pt/docs/tutorial/body-fields.md
+++ b/docs/pt/docs/tutorial/body-fields.md
@@ -1,47 +1,59 @@
-# Corpo - Campos
+# Corpo - Campos { #body-fields }
-Da mesma forma que você pode declarar validações adicionais e metadados nos parâmetros de *funções de operações de rota* com `Query`, `Path` e `Body`, você pode declarar validações e metadados dentro de modelos do Pydantic usando `Field` do Pydantic.
+Da mesma forma que você pode declarar validações adicionais e metadados nos parâmetros de uma *função de operação de rota* com `Query`, `Path` e `Body`, você pode declarar validações e metadados dentro de modelos do Pydantic usando `Field` do Pydantic.
-## Importe `Field`
+## Importe `Field` { #import-field }
Primeiro, você tem que importá-lo:
-```Python hl_lines="4"
-{!../../../docs_src/body_fields/tutorial001.py!}
-```
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}
-!!! warning "Aviso"
- Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como todo o resto (`Query`, `Path`, `Body`, etc).
+/// warning | Atenção
-## Declare atributos do modelo
+Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como todo o resto (`Query`, `Path`, `Body`, etc).
+
+///
+
+## Declare atributos do modelo { #declare-model-attributes }
Você pode então utilizar `Field` com atributos do modelo:
-```Python hl_lines="11-14"
-{!../../../docs_src/body_fields/tutorial001.py!}
-```
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}
`Field` funciona da mesma forma que `Query`, `Path` e `Body`, ele possui todos os mesmos parâmetros, etc.
-!!! note "Detalhes técnicos"
- Na realidade, `Query`, `Path` e outros que você verá em seguida, criam objetos de subclasses de uma classe `Param` comum, que é ela mesma uma subclasse da classe `FieldInfo` do Pydantic.
+/// note | Detalhes Técnicos
+
+Na realidade, `Query`, `Path` e outros que você verá em seguida, criam objetos de subclasses de uma classe `Param` comum, que é ela mesma uma subclasse da classe `FieldInfo` do Pydantic.
+
+E `Field` do Pydantic retorna uma instância de `FieldInfo` também.
+
+`Body` também retorna objetos de uma subclasse de `FieldInfo` diretamente. E tem outras que você verá mais tarde que são subclasses da classe `Body`.
- E `Field` do Pydantic retorna uma instância de `FieldInfo` também.
+Lembre-se que quando você importa `Query`, `Path`, e outros de `fastapi`, esse são na realidade funções que retornam classes especiais.
- `Body` também retorna objetos de uma subclasse de `FieldInfo` diretamente. E tem outras que você verá mais tarde que são subclasses da classe `Body`.
+///
- Lembre-se que quando você importa `Query`, `Path`, e outros de `fastapi`, esse são na realidade funções que retornam classes especiais.
+/// tip | Dica
-!!! tip "Dica"
- Note como cada atributo do modelo com um tipo, valor padrão e `Field` possuem a mesma estrutura que parâmetros de *funções de operações de rota*, com `Field` ao invés de `Path`, `Query` e `Body`.
+Note como cada atributo do modelo com um tipo, valor padrão e `Field` possuem a mesma estrutura que parâmetros de *funções de operações de rota*, com `Field` ao invés de `Path`, `Query` e `Body`.
-## Adicione informações extras
+///
+
+## Adicione informações extras { #add-extra-information }
Você pode declarar informação extra em `Field`, `Query`, `Body`, etc. E isso será incluído no JSON Schema gerado.
Você irá aprender mais sobre adicionar informações extras posteriormente nessa documentação, quando estiver aprendendo a declarar exemplos.
-## Recapitulando
+/// warning | Atenção
+
+Chaves extras passadas para `Field` também estarão presentes no schema OpenAPI resultante da sua aplicação.
+Como essas chaves podem não fazer necessariamente parte da especificação OpenAPI, algumas ferramentas de OpenAPI, por exemplo [o validador do OpenAPI](https://validator.swagger.io/), podem não funcionar com o schema gerado.
+
+///
+
+## Recapitulando { #recap }
Você pode usar `Field` do Pydantic para declarar validações extras e metadados para atributos do modelo.
diff --git a/docs/pt/docs/tutorial/body-multiple-params.md b/docs/pt/docs/tutorial/body-multiple-params.md
index 22f5856a69cce..828cde633a2e2 100644
--- a/docs/pt/docs/tutorial/body-multiple-params.md
+++ b/docs/pt/docs/tutorial/body-multiple-params.md
@@ -1,29 +1,22 @@
-# Corpo - Múltiplos parâmetros
+# Corpo - Múltiplos parâmetros { #body-multiple-parameters }
Agora que nós vimos como usar `Path` e `Query`, veremos usos mais avançados de declarações no corpo da requisição.
-## Misture `Path`, `Query` e parâmetros de corpo
+## Misture `Path`, `Query` e parâmetros de corpo { #mix-path-query-and-body-parameters }
Primeiro, é claro, você pode misturar `Path`, `Query` e declarações de parâmetro no corpo da requisição livremente e o **FastAPI** saberá o que fazer.
E você também pode declarar parâmetros de corpo como opcionais, definindo o valor padrão com `None`:
-=== "Python 3.10+"
+{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
+/// note | Nota
-=== "Python 3.6+"
+Repare que, neste caso, o `item` que seria capturado a partir do corpo é opcional. Visto que ele possui `None` como valor padrão.
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
+///
-!!! nota
- Repare que, neste caso, o `item` que seria capturado a partir do corpo é opcional. Visto que ele possui `None` como valor padrão.
-
-## Múltiplos parâmetros de corpo
+## Múltiplos parâmetros de corpo { #multiple-body-parameters }
No exemplo anterior, as *operações de rota* esperariam um JSON no corpo contendo os atributos de um `Item`, exemplo:
@@ -38,17 +31,7 @@ No exemplo anterior, as *operações de rota* esperariam um JSON no corpo conten
Mas você pode também declarar múltiplos parâmetros de corpo, por exemplo, `item` e `user`:
-=== "Python 3.10+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}
Neste caso, o **FastAPI** perceberá que existe mais de um parâmetro de corpo na função (dois parâmetros que são modelos Pydantic).
@@ -69,15 +52,17 @@ Então, ele usará o nome dos parâmetros como chaves (nome dos campos) no corpo
}
```
-!!! nota
- Repare que mesmo que o `item` esteja declarado da mesma maneira que antes, agora é esperado que ele esteja dentro do corpo com uma chave `item`.
+/// note | Nota
+Repare que mesmo que o `item` esteja declarado da mesma maneira que antes, agora é esperado que ele esteja dentro do corpo com uma chave `item`.
+
+///
O **FastAPI** fará a conversão automática a partir da requisição, assim esse parâmetro `item` receberá seu respectivo conteúdo e o mesmo ocorrerá com `user`.
Ele executará a validação dos dados compostos e irá documentá-los de maneira compatível com o esquema OpenAPI e documentação automática.
-## Valores singulares no corpo
+## Valores singulares no corpo { #singular-values-in-body }
Assim como existem uma `Query` e uma `Path` para definir dados adicionais para parâmetros de consulta e de rota, o **FastAPI** provê o equivalente para `Body`.
@@ -87,17 +72,7 @@ Se você declará-lo como é, porque é um valor singular, o **FastAPI** assumir
Mas você pode instruir o **FastAPI** para tratá-lo como outra chave do corpo usando `Body`:
-=== "Python 3.6+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
-
-=== "Python 3.10+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
Neste caso, o **FastAPI** esperará um corpo como:
@@ -119,40 +94,27 @@ Neste caso, o **FastAPI** esperará um corpo como:
Mais uma vez, ele converterá os tipos de dados, validar, documentar, etc.
-## Múltiplos parâmetros de corpo e consulta
+## Múltiplos parâmetros de corpo e consulta { #multiple-body-params-and-query }
Obviamente, você também pode declarar parâmetros de consulta assim que você precisar, de modo adicional a quaisquer parâmetros de corpo.
Dado que, por padrão, valores singulares são interpretados como parâmetros de consulta, você não precisa explicitamente adicionar uma `Query`, você pode somente:
-```Python
-q: Union[str, None] = None
-```
-
-Ou como em Python 3.10 e versões superiores:
-
```Python
q: str | None = None
```
Por exemplo:
-=== "Python 3.10+"
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
- ```Python hl_lines="26"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
+/// info | Informação
-=== "Python 3.6+"
+`Body` também possui todas as validações adicionais e metadados de parâmetros como em `Query`,`Path` e outras que você verá depois.
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+///
-!!! info "Informação"
- `Body` também possui todas as validações adicionais e metadados de parâmetros como em `Query`,`Path` e outras que você verá depois.
-
-## Declare um único parâmetro de corpo indicando sua chave
+## Declare um único parâmetro de corpo indicando sua chave { #embed-a-single-body-parameter }
Suponha que você tem um único parâmetro de corpo `item`, a partir de um modelo Pydantic `Item`.
@@ -166,17 +128,7 @@ item: Item = Body(embed=True)
como em:
-=== "Python 3.10+"
-
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}
Neste caso o **FastAPI** esperará um corpo como:
@@ -202,7 +154,7 @@ ao invés de:
}
```
-## Recapitulando
+## Recapitulando { #recap }
Você pode adicionar múltiplos parâmetros de corpo para sua *função de operação de rota*, mesmo que a requisição possa ter somente um único corpo.
diff --git a/docs/pt/docs/tutorial/body-nested-models.md b/docs/pt/docs/tutorial/body-nested-models.md
index 8ab77173e96d0..343f94997a635 100644
--- a/docs/pt/docs/tutorial/body-nested-models.md
+++ b/docs/pt/docs/tutorial/body-nested-models.md
@@ -1,40 +1,26 @@
-# Corpo - Modelos aninhados
+# Corpo - Modelos aninhados { #body-nested-models }
-Com o **FastAPI**, você pode definir, validar, documentar e usar modelos profundamente aninhados de forma arbitrária (graças ao Pydantic).
+Com o **FastAPI**, você pode definir, validar, documentar e usar modelos arbitrariamente e profundamente aninhados (graças ao Pydantic).
-## Campos do tipo Lista
+## Campos do tipo Lista { #list-fields }
Você pode definir um atributo como um subtipo. Por exemplo, uma `list` do Python:
-```Python hl_lines="14"
-{!../../../docs_src/body_nested_models/tutorial001.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}
Isso fará com que tags seja uma lista de itens mesmo sem declarar o tipo dos elementos desta lista.
-## Campos do tipo Lista com um parâmetro de tipo
+## Campos do tipo Lista com um parâmetro de tipo { #list-fields-with-type-parameter }
Mas o Python tem uma maneira específica de declarar listas com tipos internos ou "parâmetros de tipo":
-### Importe `List` do typing
-
-Primeiramente, importe `List` do módulo `typing` que já vem por padrão no Python:
-
-```Python hl_lines="1"
-{!../../../docs_src/body_nested_models/tutorial002.py!}
-```
+### Declare uma `list` com um parâmetro de tipo { #declare-a-list-with-a-type-parameter }
-### Declare a `List` com um parâmetro de tipo
-
-Para declarar tipos que têm parâmetros de tipo(tipos internos), como `list`, `dict`, `tuple`:
-
-* Importe os do modulo `typing`
-* Passe o(s) tipo(s) interno(s) como "parâmetros de tipo" usando colchetes: `[` e `]`
+Para declarar tipos que têm parâmetros de tipo (tipos internos), como `list`, `dict`, `tuple`,
+passe o(s) tipo(s) interno(s) como "parâmetros de tipo" usando colchetes: `[` e `]`
```Python
-from typing import List
-
-my_list: List[str]
+my_list: list[str]
```
Essa é a sintaxe padrão do Python para declarações de tipo.
@@ -43,24 +29,17 @@ Use a mesma sintaxe padrão para atributos de modelo com tipos internos.
Portanto, em nosso exemplo, podemos fazer com que `tags` sejam especificamente uma "lista de strings":
+{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}
-```Python hl_lines="14"
-{!../../../docs_src/body_nested_models/tutorial002.py!}
-```
-
-## Tipo "set"
-
+## Tipos "set" { #set-types }
Mas então, quando nós pensamos mais, percebemos que as tags não devem se repetir, elas provavelmente devem ser strings únicas.
E que o Python tem um tipo de dados especial para conjuntos de itens únicos, o `set`.
-Então podemos importar `Set` e declarar `tags` como um `set` de `str`s:
+Então podemos declarar `tags` como um conjunto de strings:
-
-```Python hl_lines="1 14"
-{!../../../docs_src/body_nested_models/tutorial003.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}
Com isso, mesmo que você receba uma requisição contendo dados duplicados, ela será convertida em um conjunto de itens exclusivos.
@@ -68,7 +47,7 @@ E sempre que você enviar esses dados como resposta, mesmo se a fonte tiver dupl
E também teremos anotações/documentação em conformidade.
-## Modelos aninhados
+## Modelos aninhados { #nested-models }
Cada atributo de um modelo Pydantic tem um tipo.
@@ -78,21 +57,17 @@ Portanto, você pode declarar "objects" JSON profundamente aninhados com nomes,
Tudo isso, aninhado arbitrariamente.
-### Defina um sub-modelo
+### Defina um sub-modelo { #define-a-submodel }
Por exemplo, nós podemos definir um modelo `Image`:
-```Python hl_lines="9-11"
-{!../../../docs_src/body_nested_models/tutorial004.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}
-### Use o sub-modelo como um tipo
+### Use o sub-modelo como um tipo { #use-the-submodel-as-a-type }
-E então podemos usa-lo como o tipo de um atributo:
+E então podemos usá-lo como o tipo de um atributo:
-```Python hl_lines="20"
-{!../../../docs_src/body_nested_models/tutorial004.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}
Isso significa que o **FastAPI** vai esperar um corpo similar à:
@@ -112,34 +87,30 @@ Isso significa que o **FastAPI** vai esperar um corpo similar à:
Novamente, apenas fazendo essa declaração, com o **FastAPI**, você ganha:
-* Suporte do editor de texto (compleção, etc), inclusive para modelos aninhados
+* Suporte do editor (preenchimento automático, etc.), inclusive para modelos aninhados
* Conversão de dados
* Validação de dados
-* Documentação automatica
+* Documentação automática
-## Tipos especiais e validação
+## Tipos especiais e validação { #special-types-and-validation }
Além dos tipos singulares normais como `str`, `int`, `float`, etc. Você também pode usar tipos singulares mais complexos que herdam de `str`.
-Para ver todas as opções possíveis, cheque a documentação para ostipos exoticos do Pydantic. Você verá alguns exemplos no próximo capitulo.
+Para ver todas as opções possíveis, consulte a [Visão geral dos tipos do Pydantic](https://docs.pydantic.dev/latest/concepts/types/). Você verá alguns exemplos no próximo capítulo.
-Por exemplo, no modelo `Image` nós temos um campo `url`, nós podemos declara-lo como um `HttpUrl` do Pydantic invés de como uma `str`:
+Por exemplo, no modelo `Image` nós temos um campo `url`, nós podemos declará-lo como um `HttpUrl` do Pydantic invés de como uma `str`:
-```Python hl_lines="4 10"
-{!../../../docs_src/body_nested_models/tutorial005.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}
-A string será verificada para se tornar uma URL válida e documentada no esquema JSON/1OpenAPI como tal.
+A string será verificada para se tornar uma URL válida e documentada no JSON Schema / OpenAPI como tal.
-## Atributos como listas de submodelos
+## Atributos como listas de submodelos { #attributes-with-lists-of-submodels }
Você também pode usar modelos Pydantic como subtipos de `list`, `set`, etc:
-```Python hl_lines="20"
-{!../../../docs_src/body_nested_models/tutorial006.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}
-Isso vai esperar(converter, validar, documentar, etc) um corpo JSON tal qual:
+Isso vai esperar (converter, validar, documentar, etc) um corpo JSON tal qual:
```JSON hl_lines="11"
{
@@ -165,36 +136,37 @@ Isso vai esperar(converter, validar, documentar, etc) um corpo JSON tal qual:
}
```
-!!! Informação
- Note como o campo `images` agora tem uma lista de objetos de image.
+/// info | Informação
+
+Observe como a chave `images` agora tem uma lista de objetos de imagem.
-## Modelos profundamente aninhados
+///
+
+## Modelos profundamente aninhados { #deeply-nested-models }
Você pode definir modelos profundamente aninhados de forma arbitrária:
-```Python hl_lines="9 14 20 23 27"
-{!../../../docs_src/body_nested_models/tutorial007.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}
-!!! Informação
- Note como `Offer` tem uma lista de `Item`s, que por sua vez possui opcionalmente uma lista `Image`s
+/// info | Informação
-## Corpos de listas puras
+Observe como `Offer` tem uma lista de `Item`s, que por sua vez têm uma lista opcional de `Image`s
-Se o valor de primeiro nível do corpo JSON que você espera for um `array` do JSON (uma` lista` do Python), você pode declarar o tipo no parâmetro da função, da mesma forma que nos modelos do Pydantic:
+///
+## Corpos de listas puras { #bodies-of-pure-lists }
+
+Se o valor de primeiro nível do corpo JSON que você espera for um `array` do JSON (uma` lista` do Python), você pode declarar o tipo no parâmetro da função, da mesma forma que nos modelos do Pydantic:
```Python
-images: List[Image]
+images: list[Image]
```
como em:
-```Python hl_lines="15"
-{!../../../docs_src/body_nested_models/tutorial008.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
-## Suporte de editor em todo canto
+## Suporte de editor em todo canto { #editor-support-everywhere }
E você obtém suporte do editor em todos os lugares.
@@ -206,7 +178,7 @@ Você não conseguiria este tipo de suporte de editor se estivesse trabalhando d
Mas você também não precisa se preocupar com eles, os dicts de entrada são convertidos automaticamente e sua saída é convertida automaticamente para JSON também.
-## Corpos de `dict`s arbitrários
+## Corpos de `dict`s arbitrários { #bodies-of-arbitrary-dicts }
Você também pode declarar um corpo como um `dict` com chaves de algum tipo e valores de outro tipo.
@@ -222,27 +194,28 @@ Outro caso útil é quando você deseja ter chaves de outro tipo, por exemplo, `
Neste caso, você aceitaria qualquer `dict`, desde que tenha chaves` int` com valores `float`:
-```Python hl_lines="9"
-{!../../../docs_src/body_nested_models/tutorial009.py!}
-```
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
+
+/// tip | Dica
+
+Leve em consideração que o JSON só suporta `str` como chaves.
-!!! Dica
- Leve em condideração que o JSON só suporta `str` como chaves.
+Mas o Pydantic tem conversão automática de dados.
- Mas o Pydantic tem conversão automática de dados.
+Isso significa que, embora os clientes da API só possam enviar strings como chaves, desde que essas strings contenham inteiros puros, o Pydantic irá convertê-los e validá-los.
- Isso significa que, embora os clientes da API só possam enviar strings como chaves, desde que essas strings contenham inteiros puros, o Pydantic irá convertê-los e validá-los.
+E o `dict` que você recebe como `weights` terá, na verdade, chaves `int` e valores` float`.
- E o `dict` que você recebe como `weights` terá, na verdade, chaves `int` e valores` float`.
+///
-## Recapitulação
+## Recapitulação { #recap }
Com **FastAPI** você tem a flexibilidade máxima fornecida pelos modelos Pydantic, enquanto seu código é mantido simples, curto e elegante.
Mas com todos os benefícios:
-* Suporte do editor (compleção em todo canto!)
-* Conversão de dados (leia-se parsing/serialização)
+* Suporte do editor (preenchimento automático em todo canto!)
+* Conversão de dados (parsing/serialização)
* Validação de dados
* Documentação dos esquemas
* Documentação automática
diff --git a/docs/pt/docs/tutorial/body-updates.md b/docs/pt/docs/tutorial/body-updates.md
new file mode 100644
index 0000000000000..abd14c42ceee2
--- /dev/null
+++ b/docs/pt/docs/tutorial/body-updates.md
@@ -0,0 +1,100 @@
+# Corpo - Atualizações { #body-updates }
+
+## Atualização substituindo com `PUT` { #update-replacing-with-put }
+
+Para atualizar um item, você pode usar a operação [HTTP `PUT`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT).
+
+Você pode usar `jsonable_encoder` para converter os dados de entrada em dados que podem ser armazenados como JSON (por exemplo, com um banco de dados NoSQL). Por exemplo, convertendo `datetime` em `str`.
+
+{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}
+
+`PUT` é usado para receber dados que devem substituir os dados existentes.
+
+### Aviso sobre a substituição { #warning-about-replacing }
+
+Isso significa que, se você quiser atualizar o item `bar` usando `PUT` com um corpo contendo:
+
+```Python
+{
+ "name": "Barz",
+ "price": 3,
+ "description": None,
+}
+```
+
+como ele não inclui o atributo já armazenado `"tax": 20.2`, o modelo de entrada assumiria o valor padrão de `"tax": 10.5`.
+
+E os dados seriam salvos com esse "novo" `tax` de `10.5`.
+
+## Atualizações parciais com `PATCH` { #partial-updates-with-patch }
+
+Você também pode usar a operação [HTTP `PATCH`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) para atualizar dados *parcialmente*.
+
+Isso significa que você pode enviar apenas os dados que deseja atualizar, deixando o restante intacto.
+
+/// note | Nota
+
+`PATCH` é menos comumente usado e conhecido do que `PUT`.
+
+E muitas equipes usam apenas `PUT`, mesmo para atualizações parciais.
+
+Você é **livre** para usá-los como preferir, **FastAPI** não impõe restrições.
+
+Mas este guia mostra, mais ou menos, como eles são destinados a serem usados.
+
+///
+
+### Usando o parâmetro `exclude_unset` do Pydantic { #using-pydantics-exclude-unset-parameter }
+
+Se você quiser receber atualizações parciais, é muito útil usar o parâmetro `exclude_unset` no `.model_dump()` do modelo do Pydantic.
+
+Como `item.model_dump(exclude_unset=True)`.
+
+Isso geraria um `dict` com apenas os dados que foram definidos ao criar o modelo `item`, excluindo os valores padrão.
+
+Então, você pode usar isso para gerar um `dict` com apenas os dados definidos (enviados na solicitação), omitindo valores padrão:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}
+
+### Usando o parâmetro `update` do Pydantic { #using-pydantics-update-parameter }
+
+Agora, você pode criar uma cópia do modelo existente usando `.model_copy()`, e passar o parâmetro `update` com um `dict` contendo os dados para atualizar.
+
+Como `stored_item_model.model_copy(update=update_data)`:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}
+
+### Recapitulando as atualizações parciais { #partial-updates-recap }
+
+Resumindo, para aplicar atualizações parciais você deveria:
+
+* (Opcionalmente) usar `PATCH` em vez de `PUT`.
+* Recuperar os dados armazenados.
+* Colocar esses dados em um modelo do Pydantic.
+* Gerar um `dict` sem valores padrão a partir do modelo de entrada (usando `exclude_unset`).
+ * Dessa forma, você pode atualizar apenas os valores realmente definidos pelo usuário, em vez de substituir valores já armazenados por valores padrão do modelo.
+* Criar uma cópia do modelo armazenado, atualizando seus atributos com as atualizações parciais recebidas (usando o parâmetro `update`).
+* Converter o modelo copiado em algo que possa ser armazenado no seu BD (por exemplo, usando o `jsonable_encoder`).
+ * Isso é comparável a usar o método `.model_dump()` do modelo novamente, mas garante (e converte) os valores para tipos de dados que possam ser convertidos em JSON, por exemplo, `datetime` para `str`.
+* Salvar os dados no seu BD.
+* Retornar o modelo atualizado.
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *}
+
+/// tip | Dica
+
+Você pode realmente usar essa mesma técnica com uma operação HTTP `PUT`.
+
+Mas o exemplo aqui usa `PATCH` porque foi criado para esses casos de uso.
+
+///
+
+/// note | Nota
+
+Observe que o modelo de entrada ainda é validado.
+
+Portanto, se você quiser receber atualizações parciais que possam omitir todos os atributos, você precisa ter um modelo com todos os atributos marcados como opcionais (com valores padrão ou `None`).
+
+Para distinguir entre os modelos com todos os valores opcionais para **atualizações** e modelos com valores obrigatórios para **criação**, você pode usar as ideias descritas em [Modelos Adicionais](extra-models.md).
+
+///
diff --git a/docs/pt/docs/tutorial/body.md b/docs/pt/docs/tutorial/body.md
index 99e05ab77e95f..926de84facc73 100644
--- a/docs/pt/docs/tutorial/body.md
+++ b/docs/pt/docs/tutorial/body.md
@@ -1,52 +1,52 @@
-# Corpo da Requisição
+# Corpo da requisição { #request-body }
-Quando você precisa enviar dados de um cliente (como de um navegador web) para sua API, você o envia como um **corpo da requisição**.
+Quando você precisa enviar dados de um cliente (como de um navegador) para sua API, você os envia como um **corpo da requisição**.
O corpo da **requisição** é a informação enviada pelo cliente para sua API. O corpo da **resposta** é a informação que sua API envia para o cliente.
-Sua API quase sempre irá enviar um corpo na **resposta**. Mas os clientes não necessariamente precisam enviar um corpo em toda **requisição**.
+Sua API quase sempre precisa enviar um corpo na **resposta**. Mas os clientes não necessariamente precisam enviar **corpos de requisição** o tempo todo, às vezes eles apenas requisitam um path, talvez com alguns parâmetros de consulta, mas não enviam um corpo.
-Para declarar um corpo da **requisição**, você utiliza os modelos do Pydantic com todos os seus poderes e benefícios.
+Para declarar um corpo da **requisição**, você utiliza os modelos do [Pydantic](https://docs.pydantic.dev/) com todos os seus poderes e benefícios.
-!!! info "Informação"
- Para enviar dados, você deve usar utilizar um dos métodos: `POST` (Mais comum), `PUT`, `DELETE` ou `PATCH`.
+/// info | Informação
- Enviar um corpo em uma requisição `GET` não tem um comportamento definido nas especificações, porém é suportado pelo FastAPI, apenas para casos de uso bem complexos/extremos.
+Para enviar dados, você deveria usar um dos: `POST` (o mais comum), `PUT`, `DELETE` ou `PATCH`.
- Como é desencorajado, a documentação interativa com Swagger UI não irá mostrar a documentação para o corpo da requisição para um `GET`, e proxies que intermediarem podem não suportar o corpo da requisição.
+Enviar um corpo em uma requisição `GET` não tem um comportamento definido nas especificações, porém é suportado pelo FastAPI, apenas para casos de uso bem complexos/extremos.
-## Importe o `BaseModel` do Pydantic
+Como é desencorajado, a documentação interativa com Swagger UI não irá mostrar a documentação para o corpo da requisição ao usar `GET`, e proxies intermediários podem não suportá-lo.
+
+///
+
+## Importe o `BaseModel` do Pydantic { #import-pydantics-basemodel }
Primeiro, você precisa importar `BaseModel` do `pydantic`:
-```Python hl_lines="4"
-{!../../../docs_src/body/tutorial001.py!}
-```
+{* ../../docs_src/body/tutorial001_py310.py hl[2] *}
-## Crie seu modelo de dados
+## Crie seu modelo de dados { #create-your-data-model }
Então você declara seu modelo de dados como uma classe que herda `BaseModel`.
Utilize os tipos Python padrão para todos os atributos:
-```Python hl_lines="7-11"
-{!../../../docs_src/body/tutorial001.py!}
-```
+{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}
-Assim como quando declaramos parâmetros de consulta, quando um atributo do modelo possui um valor padrão, ele se torna opcional. Caso contrário, se torna obrigatório. Use `None` para torná-lo opcional.
+
+Assim como quando declaramos parâmetros de consulta, quando um atributo do modelo possui um valor padrão, ele não é obrigatório. Caso contrário, é obrigatório. Use `None` para torná-lo apenas opcional.
Por exemplo, o modelo acima declara um JSON "`object`" (ou `dict` no Python) como esse:
```JSON
{
"name": "Foo",
- "description": "Uma descrição opcional",
+ "description": "An optional description",
"price": 45.2,
"tax": 3.5
}
```
-...como `description` e `tax` são opcionais (Com um valor padrão de `None`), esse JSON "`object`" também é válido:
+...como `description` e `tax` são opcionais (com um valor padrão de `None`), esse JSON "`object`" também é válido:
```JSON
{
@@ -55,42 +55,40 @@ Por exemplo, o modelo acima declara um JSON "`object`" (ou `dict` no Python) com
}
```
-## Declare como um parâmetro
+## Declare como um parâmetro { #declare-it-as-a-parameter }
-Para adicionar o corpo na *função de operação de rota*, declare-o da mesma maneira que você declarou parâmetros de rota e consulta:
+Para adicioná-lo à sua *operação de rota*, declare-o da mesma maneira que você declarou parâmetros de rota e de consulta:
-```Python hl_lines="18"
-{!../../../docs_src/body/tutorial001.py!}
-```
+{* ../../docs_src/body/tutorial001_py310.py hl[16] *}
-...E declare o tipo como o modelo que você criou, `Item`.
+...e declare o seu tipo como o modelo que você criou, `Item`.
-## Resultados
+## Resultados { #results }
-Apenas com esse declaração de tipos do Python, o **FastAPI** irá:
+Apenas com essa declaração de tipos do Python, o **FastAPI** irá:
-* Ler o corpo da requisição como um JSON.
+* Ler o corpo da requisição como JSON.
* Converter os tipos correspondentes (se necessário).
* Validar os dados.
- * Se algum dados for inválido, irá retornar um erro bem claro, indicando exatamente onde e o que está incorreto.
+ * Se algum dado for inválido, irá retornar um erro bem claro, indicando exatamente onde e o que estava incorreto.
* Entregar a você a informação recebida no parâmetro `item`.
- * Como você o declarou na função como do tipo `Item`, você também terá o suporte do editor (completação, etc) para todos os atributos e seus tipos.
-* Gerar um Esquema JSON com as definições do seu modelo, você também pode utilizá-lo em qualquer lugar que quiser, se fizer sentido para seu projeto.
-* Esses esquemas farão parte do esquema OpenAPI, e utilizados nas UIs de documentação automática.
+ * Como você o declarou na função como do tipo `Item`, você também terá o suporte do editor (preenchimento automático, etc) para todos os atributos e seus tipos.
+* Gerar definições de [JSON Schema](https://json-schema.org) para o seu modelo; você também pode usá-las em qualquer outro lugar se fizer sentido para o seu projeto.
+* Esses schemas farão parte do esquema OpenAPI gerado, e serão usados pelas UIs de documentação automática.
-## Documentação automática
+## Documentação automática { #automatic-docs }
-Os esquemas JSON dos seus modelos farão parte do esquema OpenAPI gerado para sua aplicação, e aparecerão na documentação interativa da API:
+Os JSON Schemas dos seus modelos farão parte do esquema OpenAPI gerado para sua aplicação, e aparecerão na documentação interativa da API:
-E também serão utilizados em cada *função de operação de rota* que utilizá-los:
+E também serão utilizados na documentação da API dentro de cada *operação de rota* que precisar deles:
-## Suporte do editor de texto:
+## Suporte do editor { #editor-support }
-No seu editor de texto, dentro da função você receberá dicas de tipos e completação em todo lugar (isso não aconteceria se você recebesse um `dict` em vez de um modelo Pydantic):
+No seu editor, dentro da função você receberá dicas de tipos e preenchimento automático em todo lugar (isso não aconteceria se você recebesse um `dict` em vez de um modelo Pydantic):
@@ -104,62 +102,65 @@ E foi imensamente testado na fase de design, antes de qualquer implementação,
Houveram mudanças no próprio Pydantic para que isso fosse possível.
-As capturas de tela anteriores foram capturas no Visual Studio Code.
+As capturas de tela anteriores foram capturas no [Visual Studio Code](https://code.visualstudio.com).
-Mas você terá o mesmo suporte do editor no PyCharm e na maioria dos editores Python:
+Mas você terá o mesmo suporte do editor no [PyCharm](https://www.jetbrains.com/pycharm/) e na maioria dos editores Python:
-!!! tip "Dica"
- Se você utiliza o PyCharm como editor, você pode utilizar o Plugin do Pydantic para o PyCharm .
+/// tip | Dica
+
+Se você utiliza o [PyCharm](https://www.jetbrains.com/pycharm/) como editor, você pode utilizar o [Plugin do Pydantic para o PyCharm](https://github.com/koxudaxi/pydantic-pycharm-plugin/).
+
+Melhora o suporte do editor para seus modelos Pydantic com:
- Melhora o suporte do editor para seus modelos Pydantic com::
+* preenchimento automático
+* verificação de tipos
+* refatoração
+* buscas
+* inspeções
- * completação automática
- * verificação de tipos
- * refatoração
- * buscas
- * inspeções
+///
-## Use o modelo
+## Use o modelo { #use-the-model }
Dentro da função, você pode acessar todos os atributos do objeto do modelo diretamente:
-```Python hl_lines="21"
-{!../../../docs_src/body/tutorial002.py!}
-```
+{* ../../docs_src/body/tutorial002_py310.py *}
-## Corpo da requisição + parâmetros de rota
+## Corpo da requisição + parâmetros de rota { #request-body-path-parameters }
Você pode declarar parâmetros de rota e corpo da requisição ao mesmo tempo.
-O **FastAPI** irá reconhecer que os parâmetros da função que combinam com parâmetros de rota devem ser **retirados da rota**, e parâmetros da função que são declarados como modelos Pydantic sejam **retirados do corpo da requisição**.
+O **FastAPI** irá reconhecer que os parâmetros da função que combinam com parâmetros de rota devem ser **retirados da rota**, e que parâmetros da função que são declarados como modelos Pydantic sejam **retirados do corpo da requisição**.
-```Python hl_lines="17-18"
-{!../../../docs_src/body/tutorial003.py!}
-```
+{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}
-## Corpo da requisição + parâmetros de rota + parâmetros de consulta
+
+## Corpo da requisição + parâmetros de rota + parâmetros de consulta { #request-body-path-query-parameters }
Você também pode declarar parâmetros de **corpo**, **rota** e **consulta**, ao mesmo tempo.
O **FastAPI** irá reconhecer cada um deles e retirar a informação do local correto.
-```Python hl_lines="18"
-{!../../../docs_src/body/tutorial004.py!}
-```
+{* ../../docs_src/body/tutorial004_py310.py hl[16] *}
Os parâmetros da função serão reconhecidos conforme abaixo:
-* Se o parâmetro também é declarado na **rota**, será utilizado como um parâmetro de rota.
+* Se o parâmetro também é declarado no **path**, será utilizado como um parâmetro de rota.
* Se o parâmetro é de um **tipo único** (como `int`, `float`, `str`, `bool`, etc) será interpretado como um parâmetro de **consulta**.
* Se o parâmetro é declarado como um **modelo Pydantic**, será interpretado como o **corpo** da requisição.
-!!! note "Observação"
- O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`.
+/// note | Nota
+
+O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`.
+
+O `str | None` não é utilizado pelo FastAPI para determinar que o valor não é obrigatório, ele saberá que não é obrigatório porque tem um valor padrão `= None`.
+
+Mas adicionar as anotações de tipo permitirá ao seu editor oferecer um suporte melhor e detectar erros.
- O `Union` em `Union[str, None]` não é utilizado pelo FastAPI, mas permite ao seu editor de texto lhe dar um suporte melhor e detectar erros.
+///
-## Sem o Pydantic
+## Sem o Pydantic { #without-pydantic }
-Se você não quer utilizar os modelos Pydantic, você também pode utilizar o parâmetro **Body**. Veja a documentação para [Body - Parâmetros múltiplos: Valores singulares no body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}.
+Se você não quer utilizar os modelos Pydantic, você também pode utilizar o parâmetro **Body**. Veja a documentação para [Body - Parâmetros múltiplos: Valores singulares no body](body-multiple-params.md#singular-values-in-body).
diff --git a/docs/pt/docs/tutorial/cookie-param-models.md b/docs/pt/docs/tutorial/cookie-param-models.md
new file mode 100644
index 0000000000000..f125314c8b4c3
--- /dev/null
+++ b/docs/pt/docs/tutorial/cookie-param-models.md
@@ -0,0 +1,76 @@
+# Modelos de Parâmetros de Cookie { #cookie-parameter-models }
+
+Se você possui um grupo de **cookies** que estão relacionados, você pode criar um **modelo Pydantic** para declará-los. 🍪
+
+Isso lhe permitiria **reutilizar o modelo** em **diversos lugares** e também declarar validações e metadata para todos os parâmetros de uma vez. 😎
+
+/// note | Nota
+
+Isso é suportado desde a versão `0.115.0` do FastAPI. 🤓
+
+///
+
+/// tip | Dica
+
+Essa mesma técnica se aplica para `Query`, `Cookie`, e `Header`. 😎
+
+///
+
+## Cookies com Modelos Pydantic { #cookies-with-a-pydantic-model }
+
+Declare os parâmetros de **cookie** de que você precisa em um **modelo Pydantic**, e depois declare o parâmetro como `Cookie`:
+
+{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}
+
+O **FastAPI** irá **extrair** os dados para **cada campo** dos **cookies** recebidos na requisição e lhe fornecer o modelo Pydantic que você definiu.
+
+## Verifique a Documentação { #check-the-docs }
+
+Você pode ver os cookies definidos na IU da documentação em `/docs`:
+
+
+
+
+---
+
+Se você usar o Pycharm, você pode:
+
+* Abrir o menu "Executar".
+* Selecionar a opção "Depurar...".
+* Então um menu de contexto aparece.
+* Selecionar o arquivo para depurar (neste caso, `main.py`).
+
+Em seguida, ele iniciará o servidor com seu código **FastAPI**, parará em seus pontos de interrupção, etc.
+
+Veja como pode parecer:
+
+
diff --git a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md
new file mode 100644
index 0000000000000..7231373a7233c
--- /dev/null
+++ b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -0,0 +1,288 @@
+# Classes como Dependências { #classes-as-dependencies }
+
+Antes de nos aprofundarmos no sistema de **Injeção de Dependência**, vamos melhorar o exemplo anterior.
+
+## `dict` do exemplo anterior { #a-dict-from-the-previous-example }
+
+No exemplo anterior, nós retornávamos um `dict` da nossa dependência ("injetável"):
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *}
+
+Mas assim obtemos um `dict` como valor do parâmetro `commons` na *função de operação de rota*.
+
+E sabemos que editores de texto não têm como oferecer muitas funcionalidades (como sugestões automáticas) para objetos do tipo `dict`, por que não há como eles saberem o tipo das chaves e dos valores.
+
+Podemos fazer melhor...
+
+## O que caracteriza uma dependência { #what-makes-a-dependency }
+
+Até agora você apenas viu dependências declaradas como funções.
+
+Mas essa não é a única forma de declarar dependências (mesmo que provavelmente seja a mais comum).
+
+O fator principal para uma dependência é que ela deve ser "chamável"
+
+Um objeto "chamável" em Python é qualquer coisa que o Python possa "chamar" como uma função
+
+Então se você tiver um objeto `alguma_coisa` (que pode *não* ser uma função) que você possa "chamar" (executá-lo) dessa maneira:
+
+```Python
+something()
+```
+
+ou
+
+```Python
+something(some_argument, some_keyword_argument="foo")
+```
+
+Então esse objeto é um "chamável".
+
+## Classes como dependências { #classes-as-dependencies_1 }
+
+Você deve ter percebido que para criar um instância de uma classe em Python, a mesma sintaxe é utilizada.
+
+Por exemplo:
+
+```Python
+class Cat:
+ def __init__(self, name: str):
+ self.name = name
+
+
+fluffy = Cat(name="Mr Fluffy")
+```
+
+Nesse caso, `fluffy` é uma instância da classe `Cat`.
+
+E para criar `fluffy`, você está "chamando" `Cat`.
+
+Então, uma classe Python também é "chamável".
+
+Então, no **FastAPI**, você pode utilizar uma classe Python como uma dependência.
+
+O que o FastAPI realmente verifica, é se a dependência é algo chamável (função, classe, ou outra coisa) e os parâmetros que foram definidos.
+
+Se você passar algo "chamável" como uma dependência do **FastAPI**, o framework irá analisar os parâmetros desse "chamável" e processá-los da mesma forma que os parâmetros de uma *função de operação de rota*. Incluindo as sub-dependências.
+
+Isso também se aplica a objetos chamáveis que não recebem nenhum parâmetro. Da mesma forma que uma *função de operação de rota* sem parâmetros.
+
+Então, podemos mudar o "injetável" na dependência `common_parameters` acima para a classe `CommonQueryParams`:
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *}
+
+Observe o método `__init__` usado para criar uma instância da classe:
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *}
+
+...ele possui os mesmos parâmetros que nosso `common_parameters` anterior:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *}
+
+Esses parâmetros são utilizados pelo **FastAPI** para "definir" a dependência.
+
+Em ambos os casos teremos:
+
+* Um parâmetro de consulta `q` opcional do tipo `str`.
+* Um parâmetro de consulta `skip` do tipo `int`, com valor padrão `0`.
+* Um parâmetro de consulta `limit` do tipo `int`, com valor padrão `100`.
+
+Os dados serão convertidos, validados, documentados no esquema da OpenAPI e etc nos dois casos.
+
+## Utilizando { #use-it }
+
+Agora você pode declarar sua dependência utilizando essa classe.
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *}
+
+O **FastAPI** chama a classe `CommonQueryParams`. Isso cria uma "instância" dessa classe e é a instância que será passada para o parâmetro `commons` na sua função.
+
+## Anotações de Tipo vs `Depends` { #type-annotation-vs-depends }
+
+Perceba como escrevemos `CommonQueryParams` duas vezes no código abaixo:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | Dica
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+O último `CommonQueryParams`, em:
+
+```Python
+... Depends(CommonQueryParams)
+```
+
+...é o que o **FastAPI** irá realmente usar para saber qual é a dependência.
+
+É a partir dele que o FastAPI irá extrair os parâmetros passados e será o que o FastAPI irá realmente chamar.
+
+---
+
+Nesse caso, o primeiro `CommonQueryParams`, em:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, ...
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | Dica
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python
+commons: CommonQueryParams ...
+```
+
+////
+
+...não tem nenhum signficado especial para o **FastAPI**. O FastAPI não irá utilizá-lo para conversão dos dados, validação, etc (já que ele utiliza `Depends(CommonQueryParams)` para isso).
+
+Na verdade você poderia escrever apenas:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[Any, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | Dica
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python
+commons = Depends(CommonQueryParams)
+```
+
+////
+
+...como em:
+
+{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *}
+
+Mas declarar o tipo é encorajado por que é a forma que o seu editor de texto sabe o que será passado como valor do parâmetro `commons`, e assim ele pode ajudar com preenchimento automático, verificações de tipo, etc:
+
+
+
+## Pegando um Atalho { #shortcut }
+
+Mas você pode ver que temos uma repetição do código neste exemplo, escrevendo `CommonQueryParams` duas vezes:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | Dica
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+O **FastAPI** nos fornece um atalho para esses casos, onde a dependência é *especificamente* uma classe que o **FastAPI** irá "chamar" para criar uma instância da própria classe.
+
+Para esses casos específicos, você pode fazer o seguinte:
+
+Em vez de escrever:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | Dica
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+...escreva:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | Dica
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
+
+Você declara a dependência como o tipo do parâmetro, e utiliza `Depends()` sem nenhum parâmetro, em vez de ter que escrever a classe *novamente* dentro de `Depends(CommonQueryParams)`.
+
+O mesmo exemplo ficaria então dessa forma:
+
+{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *}
+
+...e o **FastAPI** saberá o que fazer.
+
+/// tip | Dica
+
+Se isso parece mais confuso do que útil, não utilize, você não *precisa* disso.
+
+É apenas um atalho. Por que o **FastAPI** se preocupa em ajudar a minimizar a repetição de código.
+
+///
diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
new file mode 100644
index 0000000000000..05742c8e0c611
--- /dev/null
+++ b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -0,0 +1,69 @@
+# Dependências em decoradores de operações de rota { #dependencies-in-path-operation-decorators }
+
+Em alguns casos você não precisa necessariamente do valor de retorno de uma dependência dentro de uma *função de operação de rota*.
+
+Ou a dependência não retorna nenhum valor.
+
+Mas você ainda precisa que ela seja executada/resolvida.
+
+Para esses casos, em vez de declarar um parâmetro em uma *função de operação de rota* com `Depends`, você pode adicionar um argumento `dependencies` do tipo `list` ao decorador da operação de rota.
+
+## Adicione `dependencies` ao *decorador da operação de rota* { #add-dependencies-to-the-path-operation-decorator }
+
+O *decorador da operação de rota* recebe um argumento opcional `dependencies`.
+
+Ele deve ser uma lista de `Depends()`:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
+
+Essas dependências serão executadas/resolvidas da mesma forma que dependências comuns. Mas o valor delas (se existir algum) não será passado para a sua *função de operação de rota*.
+
+/// tip | Dica
+
+Alguns editores de texto checam parâmetros de funções não utilizados, e os mostram como erros.
+
+Utilizando `dependencies` no *decorador da operação de rota* você pode garantir que elas serão executadas enquanto evita erros de editores/ferramentas.
+
+Isso também pode ser útil para evitar confundir novos desenvolvedores que ao ver um parâmetro não usado no seu código podem pensar que ele é desnecessário.
+
+///
+
+/// info | Informação
+
+Neste exemplo utilizamos cabeçalhos personalizados inventados `X-Key` e `X-Token`.
+
+Mas em situações reais, como implementações de segurança, você pode obter mais vantagens em usar as [Ferramentas de segurança integradas (o próximo capítulo)](../security/index.md).
+
+///
+
+## Erros das dependências e valores de retorno { #dependencies-errors-and-return-values }
+
+Você pode utilizar as mesmas *funções* de dependências que você usaria normalmente.
+
+### Requisitos de Dependências { #dependency-requirements }
+
+Dependências podem declarar requisitos de requisições (como cabeçalhos) ou outras subdependências:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
+
+### Levantar exceções { #raise-exceptions }
+
+Essas dependências podem `raise` exceções, da mesma forma que dependências comuns:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
+
+### Valores de retorno { #return-values }
+
+E elas também podem ou não retornar valores, eles não serão utilizados.
+
+Então, você pode reutilizar uma dependência comum (que retorna um valor) que já seja utilizada em outro lugar, e mesmo que o valor não seja utilizado, a dependência será executada:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
+
+## Dependências para um grupo de *operações de rota* { #dependencies-for-a-group-of-path-operations }
+
+Mais a frente, quando você ler sobre como estruturar aplicações maiores ([Aplicações maiores - Múltiplos arquivos](../../tutorial/bigger-applications.md)), possivelmente com múltiplos arquivos, você aprenderá a declarar um único parâmetro `dependencies` para um grupo de *operações de rota*.
+
+## Dependências globais { #global-dependencies }
+
+No próximo passo veremos como adicionar dependências para uma aplicação `FastAPI` inteira, para que elas sejam aplicadas em toda *operação de rota*.
diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md
new file mode 100644
index 0000000000000..3e4a31d6ff883
--- /dev/null
+++ b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -0,0 +1,289 @@
+# Dependências com yield { #dependencies-with-yield }
+
+O **FastAPI** possui suporte para dependências que realizam alguns passos extras ao finalizar.
+
+Para fazer isso, utilize `yield` em vez de `return`, e escreva os passos extras (código) depois.
+
+/// tip | Dica
+
+Garanta utilizar `yield` apenas uma vez por dependência.
+
+///
+
+/// note | Detalhes Técnicos
+
+Qualquer função que possa ser utilizada com:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) ou
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+pode ser utilizada como uma dependência do **FastAPI**.
+
+Na realidade, o FastAPI utiliza esses dois decoradores internamente.
+
+///
+
+## Uma dependência de banco de dados com `yield` { #a-database-dependency-with-yield }
+
+Por exemplo, você poderia utilizar isso para criar uma sessão do banco de dados, e fechá-la após terminar.
+
+Apenas o código anterior à declaração com `yield` e o código contendo essa declaração são executados antes de criar uma resposta:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
+
+O valor gerado (yielded) é o que é injetado nas *operações de rota* e outras dependências:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
+
+O código após o `yield` é executado após a resposta:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
+
+/// tip | Dica
+
+Você pode usar funções assíncronas (`async`) ou funções comuns.
+
+O **FastAPI** saberá o que fazer com cada uma, da mesma forma que as dependências comuns.
+
+///
+
+## Uma dependência com `yield` e `try` { #a-dependency-with-yield-and-try }
+
+Se você utilizar um bloco `try` em uma dependência com `yield`, você irá capturar qualquer exceção que for lançada enquanto a dependência é utilizada.
+
+Por exemplo, se algum código em um certo momento no meio, em outra dependência ou em uma *operação de rota*, fizer um "rollback" de uma transação de banco de dados ou causar qualquer outra exceção, você irá capturar a exceção em sua dependência.
+
+Então, você pode procurar por essa exceção específica dentro da dependência com `except AlgumaExcecao`.
+
+Da mesma forma, você pode utilizar `finally` para garantir que os passos de saída são executados, com ou sem exceções.
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
+
+## Subdependências com `yield` { #sub-dependencies-with-yield }
+
+Você pode ter subdependências e "árvores" de subdependências de qualquer tamanho e forma, e qualquer uma ou todas elas podem utilizar `yield`.
+
+O **FastAPI** garantirá que o "código de saída" em cada dependência com `yield` é executado na ordem correta.
+
+Por exemplo, `dependency_c` pode depender de `dependency_b`, e `dependency_b` depender de `dependency_a`:
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
+
+E todas elas podem utilizar `yield`.
+
+Neste caso, `dependency_c`, para executar seu código de saída, precisa que o valor de `dependency_b` (nomeado de `dep_b` aqui) continue disponível.
+
+E, por outro lado, `dependency_b` precisa que o valor de `dependency_a` (nomeado de `dep_a`) esteja disponível para executar seu código de saída.
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
+
+Da mesma forma, você pode ter algumas dependências com `yield` e outras com `return` e ter uma relação de dependência entre algumas das duas.
+
+E você poderia ter uma única dependência que precisa de diversas outras dependências com `yield`, etc.
+
+Você pode ter qualquer combinação de dependências que você quiser.
+
+O **FastAPI** se encarrega de executá-las na ordem certa.
+
+/// note | Detalhes Técnicos
+
+Tudo isso funciona graças aos [gerenciadores de contexto](https://docs.python.org/3/library/contextlib.html) do Python.
+
+O **FastAPI** utiliza eles internamente para alcançar isso.
+
+///
+
+## Dependências com `yield` e `HTTPException` { #dependencies-with-yield-and-httpexception }
+
+Você viu que pode usar dependências com `yield` e ter blocos `try` que tentam executar algum código e depois executar algum código de saída com `finally`.
+
+Você também pode usar `except` para capturar a exceção que foi levantada e fazer algo com ela.
+
+Por exemplo, você pode levantar uma exceção diferente, como `HTTPException`.
+
+/// tip | Dica
+
+Essa é uma técnica relativamente avançada, e na maioria dos casos você não vai precisar dela, já que você pode levantar exceções (incluindo `HTTPException`) dentro do resto do código da sua aplicação, por exemplo, na *função de operação de rota*.
+
+Mas ela existe para ser utilizada caso você precise. 🤓
+
+///
+
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
+
+Se você quiser capturar exceções e criar uma resposta personalizada com base nisso, crie um [Manipulador de Exceções Customizado](../handling-errors.md#install-custom-exception-handlers).
+
+## Dependências com `yield` e `except` { #dependencies-with-yield-and-except }
+
+Se você capturar uma exceção com `except` em uma dependência que utilize `yield` e ela não for levantada novamente (ou uma nova exceção for levantada), o FastAPI não será capaz de identificar que houve uma exceção, da mesma forma que aconteceria com Python puro:
+
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
+
+Neste caso, o cliente irá ver uma resposta *HTTP 500 Internal Server Error* como deveria acontecer, já que não estamos levantando nenhuma `HTTPException` ou coisa parecida, mas o servidor **não terá nenhum log** ou qualquer outra indicação de qual foi o erro. 😱
+
+### Sempre levante (`raise`) em Dependências com `yield` e `except` { #always-raise-in-dependencies-with-yield-and-except }
+
+Se você capturar uma exceção em uma dependência com `yield`, a menos que você esteja levantando outra `HTTPException` ou coisa parecida, **você deve relançar a exceção original**.
+
+Você pode relançar a mesma exceção utilizando `raise`:
+
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
+
+Agora o cliente irá receber a mesma resposta *HTTP 500 Internal Server Error*, mas o servidor terá nosso `InternalError` personalizado nos logs. 😎
+
+## Execução de dependências com `yield` { #execution-of-dependencies-with-yield }
+
+A sequência de execução é mais ou menos como esse diagrama. O tempo passa do topo para baixo. E cada coluna é uma das partes interagindo ou executando código.
+
+```mermaid
+sequenceDiagram
+
+participant client as Cliente
+participant handler as Manipulador de exceções
+participant dep as Dep com yield
+participant operation as Operação de Rota
+participant tasks as Tarefas de Background
+
+ Note over client,operation: pode lançar exceções, incluindo HTTPException
+ client ->> dep: Iniciar requisição
+ Note over dep: Executar código até o yield
+ opt lançar Exceção
+ dep -->> handler: lançar Exceção
+ handler -->> client: resposta de erro HTTP
+ end
+ dep ->> operation: Executar dependência, e.g. sessão de BD
+ opt raise
+ operation -->> dep: Lançar exceção (e.g. HTTPException)
+ opt handle
+ dep -->> dep: Pode capturar exceções, lançar uma nova HTTPException, lançar outras exceções
+ end
+ handler -->> client: resposta de erro HTTP
+ end
+
+ operation ->> client: Retornar resposta ao cliente
+ Note over client,operation: Resposta já foi enviada, e não pode ser modificada
+ opt Tarefas
+ operation -->> tasks: Enviar tarefas de background
+ end
+ opt Lançar outra exceção
+ tasks -->> tasks: Manipula exceções no código da tarefa de background
+ end
+```
+
+/// info | Informação
+
+Apenas **uma resposta** será enviada para o cliente. Ela pode ser uma das respostas de erro, ou então a resposta da *operação de rota*.
+
+Após uma dessas respostas ser enviada, nenhuma outra resposta pode ser enviada.
+
+///
+
+/// tip | Dica
+
+Se você levantar qualquer exceção no código da *função de operação de rota*, ela será passada para as dependências com `yield`, incluindo `HTTPException`. Na maioria dos casos, você vai querer relançar essa mesma exceção ou uma nova a partir da dependência com `yield` para garantir que ela seja tratada adequadamente.
+
+///
+
+## Saída antecipada e `scope` { #early-exit-and-scope }
+
+Normalmente, o código de saída das dependências com `yield` é executado **após a resposta** ser enviada ao cliente.
+
+Mas se você sabe que não precisará usar a dependência depois de retornar da *função de operação de rota*, você pode usar `Depends(scope="function")` para dizer ao FastAPI que deve fechar a dependência depois que a *função de operação de rota* retornar, mas **antes** de a **resposta ser enviada**.
+
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
+
+`Depends()` recebe um parâmetro `scope` que pode ser:
+
+* `"function"`: iniciar a dependência antes da *função de operação de rota* que trata a requisição, encerrar a dependência depois que a *função de operação de rota* termina, mas **antes** de a resposta ser enviada de volta ao cliente. Assim, a função da dependência será executada **em torno** da *função de operação de rota*.
+* `"request"`: iniciar a dependência antes da *função de operação de rota* que trata a requisição (semelhante a quando se usa `"function"`), mas encerrar **depois** que a resposta é enviada de volta ao cliente. Assim, a função da dependência será executada **em torno** do ciclo de **requisição** e resposta.
+
+Se não for especificado e a dependência tiver `yield`, ela terá `scope` igual a `"request"` por padrão.
+
+### `scope` para subdependências { #scope-for-sub-dependencies }
+
+Quando você declara uma dependência com `scope="request"` (o padrão), qualquer subdependência também precisa ter `scope` igual a `"request"`.
+
+Mas uma dependência com `scope` igual a `"function"` pode ter dependências com `scope` igual a `"function"` e com `scope` igual a `"request"`.
+
+Isso porque qualquer dependência precisa conseguir executar seu código de saída antes das subdependências, pois pode ainda precisar usá-las durante seu código de saída.
+
+```mermaid
+sequenceDiagram
+
+participant client as Cliente
+participant dep_req as Dep scope="request"
+participant dep_func as Dep scope="function"
+participant operation as Operação de Rota
+
+ client ->> dep_req: Iniciar requisição
+ Note over dep_req: Executar código até o yield
+ dep_req ->> dep_func: Passar dependência
+ Note over dep_func: Executar código até o yield
+ dep_func ->> operation: Executar operação de rota com dependência
+ operation ->> dep_func: Retornar da operação de rota
+ Note over dep_func: Executar código após o yield
+ Note over dep_func: ✅ Dependência fechada
+ dep_func ->> client: Enviar resposta ao cliente
+ Note over client: Resposta enviada
+ Note over dep_req: Executar código após o yield
+ Note over dep_req: ✅ Dependência fechada
+```
+
+## Dependências com `yield`, `HTTPException`, `except` e Tarefas de Background { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+Dependências com `yield` evoluíram ao longo do tempo para cobrir diferentes casos de uso e corrigir alguns problemas.
+
+Se você quiser ver o que mudou em diferentes versões do FastAPI, você pode ler mais sobre isso no guia avançado, em [Dependências Avançadas - Dependências com `yield`, `HTTPException`, `except` e Tarefas de Background](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks).
+## Gerenciadores de contexto { #context-managers }
+
+### O que são "Gerenciadores de Contexto" { #what-are-context-managers }
+
+"Gerenciadores de Contexto" são qualquer um dos objetos Python que podem ser utilizados com a declaração `with`.
+
+Por exemplo, [você pode utilizar `with` para ler um arquivo](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files):
+
+```Python
+with open("./somefile.txt") as f:
+ contents = f.read()
+ print(contents)
+```
+
+Por baixo dos panos, o código `open("./somefile.txt")` cria um objeto que é chamado de "Gerenciador de Contexto".
+
+Quando o bloco `with` finaliza, ele se certifica de fechar o arquivo, mesmo que tenha ocorrido alguma exceção.
+
+Quando você cria uma dependência com `yield`, o **FastAPI** irá criar um gerenciador de contexto internamente para ela, e combiná-lo com algumas outras ferramentas relacionadas.
+
+### Utilizando gerenciadores de contexto em dependências com `yield` { #using-context-managers-in-dependencies-with-yield }
+
+/// warning | Atenção
+
+Isso é uma ideia mais ou menos "avançada".
+
+Se você está apenas iniciando com o **FastAPI** você pode querer pular isso por enquanto.
+
+///
+
+Em Python, você pode criar Gerenciadores de Contexto ao [criar uma classe com dois métodos: `__enter__()` e `__exit__()`](https://docs.python.org/3/reference/datamodel.html#context-managers).
+
+Você também pode usá-los dentro de dependências com `yield` do **FastAPI** ao utilizar
+`with` ou `async with` dentro da função da dependência:
+
+{* ../../docs_src/dependencies/tutorial010_py310.py hl[1:9,13] *}
+
+/// tip | Dica
+
+Outra forma de criar um gerenciador de contexto é utilizando:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) ou
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+Para decorar uma função com um único `yield`.
+
+Isso é o que o **FastAPI** usa internamente para dependências com `yield`.
+
+Mas você não precisa usar esses decoradores para as dependências do FastAPI (e você não deveria).
+
+O FastAPI irá fazer isso para você internamente.
+
+///
diff --git a/docs/pt/docs/tutorial/dependencies/global-dependencies.md b/docs/pt/docs/tutorial/dependencies/global-dependencies.md
new file mode 100644
index 0000000000000..5ff106c230515
--- /dev/null
+++ b/docs/pt/docs/tutorial/dependencies/global-dependencies.md
@@ -0,0 +1,16 @@
+# Dependências Globais { #global-dependencies }
+
+Para alguns tipos de aplicação você pode querer adicionar dependências para toda a aplicação.
+
+De forma semelhante a [adicionar `dependencies` aos *decoradores de operação de rota*](dependencies-in-path-operation-decorators.md), você pode adicioná-las à aplicação `FastAPI`.
+
+Nesse caso, elas serão aplicadas a todas as *operações de rota* da aplicação:
+
+{* ../../docs_src/dependencies/tutorial012_an_py310.py hl[17] *}
+
+
+E todos os conceitos apresentados na seção sobre [adicionar `dependencies` aos *decoradores de operação de rota*](dependencies-in-path-operation-decorators.md) ainda se aplicam, mas nesse caso, para todas as *operações de rota* da aplicação.
+
+## Dependências para conjuntos de *operações de rota* { #dependencies-for-groups-of-path-operations }
+
+Mais para a frente, quando você ler sobre como estruturar aplicações maiores ([Aplicações Maiores - Múltiplos Arquivos](../../tutorial/bigger-applications.md)), possivelmente com múltiplos arquivos, você irá aprender a declarar um único parâmetro `dependencies` para um conjunto de *operações de rota*.
diff --git a/docs/pt/docs/tutorial/dependencies/index.md b/docs/pt/docs/tutorial/dependencies/index.md
new file mode 100644
index 0000000000000..baea97f7ffec5
--- /dev/null
+++ b/docs/pt/docs/tutorial/dependencies/index.md
@@ -0,0 +1,250 @@
+# Dependências { #dependencies }
+
+O **FastAPI** possui um poderoso, mas intuitivo sistema de **Injeção de Dependência**.
+
+Esse sistema foi pensado para ser fácil de usar, e permitir que qualquer desenvolvedor possa integrar facilmente outros componentes ao **FastAPI**.
+
+## O que é "Injeção de Dependência" { #what-is-dependency-injection }
+
+**"Injeção de Dependência"** no mundo da programação significa, que existe uma maneira de declarar no seu código (nesse caso, suas *funções de operação de rota*) para declarar as coisas que ele precisa para funcionar e que serão utilizadas: "dependências".
+
+Então, esse sistema (nesse caso o **FastAPI**) se encarrega de fazer o que for preciso para fornecer essas dependências para o código ("injetando" as dependências).
+
+Isso é bastante útil quando você precisa:
+
+* Definir uma lógica compartilhada (mesmo formato de código repetidamente).
+* Compartilhar conexões com banco de dados.
+* Aplicar regras de segurança, autenticação, papéis de usuários, etc.
+* E muitas outras coisas...
+
+Tudo isso, enquanto minimizamos a repetição de código.
+
+## Primeiros passos { #first-steps }
+
+Vamos ver um exemplo simples. Tão simples que não será muito útil, por enquanto.
+
+Mas dessa forma podemos focar em como o sistema de **Injeção de Dependência** funciona.
+
+### Criando uma dependência, ou "dependable" { #create-a-dependency-or-dependable }
+
+Primeiro vamos focar na dependência.
+
+Ela é apenas uma função que pode receber os mesmos parâmetros de uma *função de operação de rota*:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}
+
+E pronto.
+
+**2 linhas**.
+
+E com a mesma forma e estrutura de todas as suas *funções de operação de rota*.
+
+Você pode pensar nela como uma *função de operação de rota* sem o "decorador" (sem a linha `@app.get("/some-path")`).
+
+E com qualquer retorno que você desejar.
+
+Neste caso, a dependência espera por:
+
+* Um parâmetro de consulta opcional `q` do tipo `str`.
+* Um parâmetro de consulta opcional `skip` do tipo `int`, e igual a `0` por padrão.
+* Um parâmetro de consulta opcional `limit` do tipo `int`, e igual a `100` por padrão.
+
+E então retorna um `dict` contendo esses valores.
+
+/// info | Informação
+
+FastAPI passou a suportar a notação `Annotated` (e começou a recomendá-la) na versão 0.95.0.
+
+Se você utiliza uma versão anterior, ocorrerão erros ao tentar utilizar `Annotated`.
+
+Certifique-se de [Atualizar a versão do FastAPI](../../deployment/versions.md#upgrading-the-fastapi-versions) para pelo menos 0.95.1 antes de usar `Annotated`.
+
+///
+
+### Importando `Depends` { #import-depends }
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}
+
+### Declarando a dependência, no "dependente" { #declare-the-dependency-in-the-dependant }
+
+Da mesma forma que você utiliza `Body`, `Query`, etc. Como parâmetros de sua *função de operação de rota*, utilize `Depends` com um novo parâmetro:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}
+
+Ainda que `Depends` seja utilizado nos parâmetros da função da mesma forma que `Body`, `Query`, etc, `Depends` funciona de uma forma um pouco diferente.
+
+Você fornece um único parâmetro para `Depends`.
+
+Esse parâmetro deve ser algo como uma função.
+
+Você **não chama a função** diretamente (não adicione os parênteses no final), apenas a passe como parâmetro de `Depends()`.
+
+E essa função vai receber os parâmetros da mesma forma que uma *função de operação de rota*.
+
+/// tip | Dica
+
+Você verá quais outras "coisas", além de funções, podem ser usadas como dependências no próximo capítulo.
+
+///
+
+Sempre que uma nova requisição for realizada, o **FastAPI** se encarrega de:
+
+* Chamar sua dependência ("dependable") com os parâmetros corretos.
+* Obter o resultado da função.
+* Atribuir esse resultado para o parâmetro em sua *função de operação de rota*.
+
+```mermaid
+graph TB
+
+common_parameters(["common_parameters"])
+read_items["/items/"]
+read_users["/users/"]
+
+common_parameters --> read_items
+common_parameters --> read_users
+```
+
+Assim, você escreve um código compartilhado apenas uma vez e o **FastAPI** se encarrega de chamá-lo em suas *operações de rota*.
+
+/// check | Verifique
+
+Perceba que você não precisa criar uma classe especial e enviar a dependência para algum outro lugar em que o **FastAPI** a "registre" ou realize qualquer operação similar.
+
+Você apenas envia para `Depends` e o **FastAPI** sabe como fazer o resto.
+
+///
+
+## Compartilhando dependências `Annotated` { #share-annotated-dependencies }
+
+Nos exemplos acima, você pode ver que existe uma pequena **duplicação de código**.
+
+Quando você precisa utilizar a dependência `common_parameters()`, você precisa escrever o parâmetro inteiro com uma anotação de tipo e `Depends()`:
+
+```Python
+commons: Annotated[dict, Depends(common_parameters)]
+```
+
+Mas como estamos utilizando `Annotated`, podemos guardar esse valor `Annotated` em uma variável e utilizá-la em múltiplos locais:
+
+{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}
+
+/// tip | Dica
+
+Isso é apenas Python padrão, essa funcionalidade é chamada de "type alias", e na verdade não é específica ao **FastAPI**.
+
+Mas como o **FastAPI** se baseia em convenções do Python, incluindo `Annotated`, você pode incluir esse truque no seu código. 😎
+
+///
+
+As dependências continuarão funcionando como esperado, e a **melhor parte** é que a **informação sobre o tipo é preservada**, o que signfica que seu editor de texto ainda irá incluir **preenchimento automático**, **visualização de erros**, etc. O mesmo vale para ferramentas como `mypy`.
+
+Isso é especialmente útil para uma **base de código grande** onde **as mesmas dependências** são utilizadas repetidamente em **muitas *operações de rota***.
+
+## `Async` ou não, eis a questão { #to-async-or-not-to-async }
+
+Como as dependências também serão chamadas pelo **FastAPI** (da mesma forma que *funções de operação de rota*), as mesmas regras se aplicam ao definir suas funções.
+
+Você pode utilizar `async def` ou apenas `def`.
+
+E você pode declarar dependências utilizando `async def` dentro de *funções de operação de rota* definidas com `def`, ou declarar dependências com `def` e utilizar dentro de *funções de operação de rota* definidas com `async def`, etc.
+
+Não faz diferença. O **FastAPI** sabe o que fazer.
+
+/// note | Nota
+
+Caso você não conheça, veja em [Async: *"Com Pressa?"*](../../async.md#in-a-hurry) a sessão acerca de `async` e `await` na documentação.
+
+///
+
+## Integrando com OpenAPI { #integrated-with-openapi }
+
+Todas as declarações de requisições, validações e requisitos para suas dependências (e sub-dependências) serão integradas em um mesmo esquema OpenAPI.
+
+Então, a documentação interativa também terá toda a informação sobre essas dependências:
+
+
+
+## Caso de Uso Simples { #simple-usage }
+
+Se você parar para ver, *funções de operação de rota* são declaradas para serem usadas sempre que uma *rota* e uma *operação* se encaixam, e então o **FastAPI** se encarrega de chamar a função correspondente com os argumentos corretos, extraindo os dados da requisição.
+
+Na verdade, todos (ou a maioria) dos frameworks web funcionam da mesma forma.
+
+Você nunca chama essas funções diretamente. Elas são chamadas pelo framework utilizado (nesse caso, **FastAPI**).
+
+Com o Sistema de Injeção de Dependência, você também pode informar ao **FastAPI** que sua *função de operação de rota* também "depende" em algo a mais que deve ser executado antes de sua *função de operação de rota*, e o **FastAPI** se encarrega de executar e "injetar" os resultados.
+
+Outros termos comuns para essa mesma ideia de "injeção de dependência" são:
+
+* recursos
+* provedores
+* serviços
+* injetáveis
+* componentes
+
+## Plug-ins em **FastAPI** { #fastapi-plug-ins }
+
+Integrações e "plug-ins" podem ser construídos com o sistema de **Injeção de Dependência**. Mas na verdade, **não há necessidade de criar "plug-ins"**, já que utilizando dependências é possível declarar um número infinito de integrações e interações que se tornam disponíveis para as suas *funções de operação de rota*.
+
+E as dependências podem ser criadas de uma forma bastante simples e intuitiva que permite que você importe apenas os pacotes Python que forem necessários, e integrá-los com as funções de sua API em algumas linhas de código, *literalmente*.
+
+Você verá exemplos disso nos próximos capítulos, acerca de bancos de dados relacionais e NoSQL, segurança, etc.
+
+## Compatibilidade do **FastAPI** { #fastapi-compatibility }
+
+A simplicidade do sistema de injeção de dependência do **FastAPI** faz ele compatível com:
+
+* todos os bancos de dados relacionais
+* bancos de dados NoSQL
+* pacotes externos
+* APIs externas
+* sistemas de autenticação e autorização
+* sistemas de monitoramento de uso para APIs
+* sistemas de injeção de dados de resposta
+* etc.
+
+## Simples e Poderoso { #simple-and-powerful }
+
+Mesmo que o sistema hierárquico de injeção de dependência seja simples de definir e utilizar, ele ainda é bastante poderoso.
+
+Você pode definir dependências que por sua vez definem suas próprias dependências.
+
+Por fim, uma árvore hierárquica de dependências é criada, e o sistema de **Injeção de Dependência** toma conta de resolver todas essas dependências (e as sub-dependências delas) para você, e provê (injeta) os resultados em cada passo.
+
+Por exemplo, vamos supor que você possua 4 endpoints na sua API (*operações de rota*):
+
+* `/items/public/`
+* `/items/private/`
+* `/users/{user_id}/activate`
+* `/items/pro/`
+
+Você poderia adicionar diferentes requisitos de permissão para cada um deles utilizando apenas dependências e sub-dependências:
+
+```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
+```
+
+## Integração com **OpenAPI** { #integrated-with-openapi_1 }
+
+Todas essas dependências, ao declarar os requisitos para suas *operações de rota*, também adicionam parâmetros, validações, etc.
+
+O **FastAPI** se encarrega de adicionar tudo isso ao esquema OpenAPI, para que seja mostrado nos sistemas de documentação interativa.
diff --git a/docs/pt/docs/tutorial/dependencies/sub-dependencies.md b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md
new file mode 100644
index 0000000000000..63ed0e48ad78c
--- /dev/null
+++ b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md
@@ -0,0 +1,105 @@
+# Subdependências { #sub-dependencies }
+
+Você pode criar dependências que possuem **subdependências**.
+
+Elas podem ter o nível de **profundidade** que você achar necessário.
+
+O **FastAPI** se encarrega de resolver essas dependências.
+
+## Primeira dependência "dependable" { #first-dependency-dependable }
+
+Você pode criar uma primeira dependência ("dependable") dessa forma:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}
+
+Esse código declara um parâmetro de consulta opcional, `q`, com o tipo `str`, e então retorna esse parâmetro.
+
+Isso é bastante simples (e não muito útil), mas irá nos ajudar a focar em como as subdependências funcionam.
+
+## Segunda dependência, "dependable" e "dependente" { #second-dependency-dependable-and-dependant }
+
+Então, você pode criar uma outra função para uma dependência (um "dependable") que ao mesmo tempo declara sua própria dependência (o que faz dela um "dependente" também):
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}
+
+Vamos focar nos parâmetros declarados:
+
+* Mesmo que essa função seja uma dependência ("dependable") por si mesma, ela também declara uma outra dependência (ela "depende" de outra coisa).
+ * Ela depende do `query_extractor`, e atribui o valor retornado pela função ao parâmetro `q`.
+* Ela também declara um cookie opcional `last_query`, do tipo `str`.
+ * Se o usuário não passou nenhuma consulta `q`, a última consulta é utilizada, que foi salva em um cookie anteriormente.
+
+## Utilizando a dependência { #use-the-dependency }
+
+Então podemos utilizar a dependência com:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}
+
+/// info | Informação
+
+Perceba que nós estamos declarando apenas uma dependência na *função de operação de rota*, em `query_or_cookie_extractor`.
+
+Mas o **FastAPI** saberá que precisa solucionar `query_extractor` primeiro, para passar o resultado para `query_or_cookie_extractor` enquanto chama a função.
+
+///
+
+```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
+```
+
+## Utilizando a mesma dependência múltiplas vezes { #using-the-same-dependency-multiple-times }
+
+Se uma de suas dependências é declarada várias vezes para a mesma *operação de rota*, por exemplo, múltiplas dependências com uma mesma subdependência, o **FastAPI** irá chamar essa subdependência uma única vez para cada requisição.
+
+E o valor retornado é salvo em um "cache" e repassado para todos os "dependentes" que precisam dele em uma requisição específica, em vez de chamar a dependência múltiplas vezes para uma mesma requisição.
+
+Em um cenário avançado onde você precise que a dependência seja calculada em cada passo (possivelmente várias vezes) de uma requisição em vez de utilizar o valor em "cache", você pode definir o parâmetro `use_cache=False` em `Depends`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+//// tab | Python 3.10+ non-Annotated
+
+/// tip | Dica
+
+Utilize a versão com `Annotated` se possível.
+
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+## Recapitulando { #recap }
+
+Com exceção de todas as palavras complicadas usadas aqui, o sistema de **Injeção de Dependência** é bastante simples.
+
+Consiste apenas de funções que parecem idênticas a *funções de operação de rota*.
+
+Mas ainda assim, é bastante poderoso, e permite que você declare grafos (árvores) de dependências com uma profundidade arbitrária.
+
+/// tip | Dica
+
+Tudo isso pode não parecer muito útil com esses exemplos.
+
+Mas você verá o quão útil isso é nos capítulos sobre **segurança**.
+
+E você também verá a quantidade de código que você não precisara escrever.
+
+///
diff --git a/docs/pt/docs/tutorial/encoder.md b/docs/pt/docs/tutorial/encoder.md
index bb4483fdc8f0f..e1ee2eccfd5d2 100644
--- a/docs/pt/docs/tutorial/encoder.md
+++ b/docs/pt/docs/tutorial/encoder.md
@@ -1,4 +1,4 @@
-# Codificador Compatível com JSON
+# Codificador Compatível com JSON { #json-compatible-encoder }
Existem alguns casos em que você pode precisar converter um tipo de dados (como um modelo Pydantic) para algo compatível com JSON (como um `dict`, `list`, etc).
@@ -6,13 +6,13 @@ Por exemplo, se você precisar armazená-lo em um banco de dados.
Para isso, **FastAPI** fornece uma função `jsonable_encoder()`.
-## Usando a função `jsonable_encoder`
+## Usando a função `jsonable_encoder` { #using-the-jsonable-encoder }
Vamos imaginar que você tenha um banco de dados `fake_db` que recebe apenas dados compatíveis com JSON.
Por exemplo, ele não recebe objetos `datetime`, pois estes objetos não são compatíveis com JSON.
-Então, um objeto `datetime` teria que ser convertido em um `str` contendo os dados no formato ISO.
+Então, um objeto `datetime` teria que ser convertido em um `str` contendo os dados no [formato ISO](https://en.wikipedia.org/wiki/ISO_8601).
Da mesma forma, este banco de dados não receberia um modelo Pydantic (um objeto com atributos), apenas um `dict`.
@@ -20,23 +20,16 @@ Você pode usar a função `jsonable_encoder` para resolver isso.
A função recebe um objeto, como um modelo Pydantic e retorna uma versão compatível com JSON:
-=== "Python 3.10+"
-
- ```Python hl_lines="4 21"
- {!> ../../../docs_src/encoder/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="5 22"
- {!> ../../../docs_src/encoder/tutorial001.py!}
- ```
+{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *}
Neste exemplo, ele converteria o modelo Pydantic em um `dict`, e o `datetime` em um `str`.
-O resultado de chamar a função é algo que pode ser codificado com o padrão do Python `json.dumps()`.
+O resultado de chamar a função é algo que pode ser codificado com o padrão do Python [`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps).
A função não retorna um grande `str` contendo os dados no formato JSON (como uma string). Mas sim, retorna uma estrutura de dados padrão do Python (por exemplo, um `dict`) com valores e subvalores compatíveis com JSON.
-!!! nota
- `jsonable_encoder` é realmente usado pelo **FastAPI** internamente para converter dados. Mas também é útil em muitos outros cenários.
+/// note | Nota
+
+`jsonable_encoder` é realmente usado pelo **FastAPI** internamente para converter dados. Mas também é útil em muitos outros cenários.
+
+///
diff --git a/docs/pt/docs/tutorial/extra-data-types.md b/docs/pt/docs/tutorial/extra-data-types.md
index e4b9913dc3387..e323d573013dc 100644
--- a/docs/pt/docs/tutorial/extra-data-types.md
+++ b/docs/pt/docs/tutorial/extra-data-types.md
@@ -1,4 +1,4 @@
-# Tipos de dados extras
+# Tipos de dados extras { #extra-data-types }
Até agora, você tem usado tipos de dados comuns, tais como:
@@ -17,7 +17,7 @@ E você ainda terá os mesmos recursos que viu até agora:
* Validação de dados.
* Anotação e documentação automáticas.
-## Outros tipos de dados
+## Outros tipos de dados { #other-data-types }
Aqui estão alguns dos tipos de dados adicionais que você pode usar:
@@ -36,12 +36,12 @@ Aqui estão alguns dos tipos de dados adicionais que você pode usar:
* `datetime.timedelta`:
* O `datetime.timedelta` do Python.
* Em requisições e respostas será representado como um `float` de segundos totais.
- * O Pydantic também permite representá-lo como uma "codificação ISO 8601 diferença de tempo", cheque a documentação para mais informações.
+ * O Pydantic também permite representá-lo como uma "codificação ISO 8601 diferença de tempo", [cheque a documentação para mais informações](https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers).
* `frozenset`:
* Em requisições e respostas, será tratado da mesma forma que um `set`:
* Nas requisições, uma lista será lida, eliminando duplicadas e convertendo-a em um `set`.
* Nas respostas, o `set` será convertido para uma `list`.
- * O esquema gerado vai especificar que os valores do `set` são unicos (usando o `uniqueItems` do JSON Schema).
+ * O esquema gerado vai especificar que os valores do `set` são únicos (usando o `uniqueItems` do JSON Schema).
* `bytes`:
* O `bytes` padrão do Python.
* Em requisições e respostas será representado como uma `str`.
@@ -49,18 +49,14 @@ Aqui estão alguns dos tipos de dados adicionais que você pode usar:
* `Decimal`:
* O `Decimal` padrão do Python.
* Em requisições e respostas será representado como um `float`.
-* Você pode checar todos os tipos de dados válidos do Pydantic aqui: Tipos de dados do Pydantic.
+* Você pode checar todos os tipos de dados válidos do Pydantic aqui: [Tipos de dados do Pydantic](https://docs.pydantic.dev/latest/usage/types/types/).
-## Exemplo
+## Exemplo { #example }
Aqui está um exemplo de *operação de rota* com parâmetros utilizando-se de alguns dos tipos acima.
-```Python hl_lines="1 3 12-16"
-{!../../../docs_src/extra_data_types/tutorial001.py!}
-```
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *}
-Note que os parâmetros dentro da função tem seu tipo de dados natural, e você pode, por exemplo, realizar manipulações normais de data, como:
+Note que os parâmetros dentro da função têm seu tipo de dados natural, e você pode, por exemplo, realizar manipulações normais de data, como:
-```Python hl_lines="18-19"
-{!../../../docs_src/extra_data_types/tutorial001.py!}
-```
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *}
diff --git a/docs/pt/docs/tutorial/extra-models.md b/docs/pt/docs/tutorial/extra-models.md
index dd5407eb2d13e..424e0fe185f1b 100644
--- a/docs/pt/docs/tutorial/extra-models.md
+++ b/docs/pt/docs/tutorial/extra-models.md
@@ -1,4 +1,4 @@
-# Modelos Adicionais
+# Modelos Adicionais { #extra-models }
Continuando com o exemplo anterior, será comum ter mais de um modelo relacionado.
@@ -6,36 +6,29 @@ Isso é especialmente o caso para modelos de usuários, porque:
* O **modelo de entrada** precisa ser capaz de ter uma senha.
* O **modelo de saída** não deve ter uma senha.
-* O **modelo de banco de dados** provavelmente precisaria ter uma senha criptografada.
+* O **modelo de banco de dados** provavelmente precisaria ter uma senha com hash.
-!!! danger
- Nunca armazene senhas em texto simples dos usuários. Sempre armazene uma "hash segura" que você pode verificar depois.
+/// danger | Cuidado
- Se não souber, você aprenderá o que é uma "senha hash" nos [capítulos de segurança](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}.
+Nunca armazene senhas em texto simples dos usuários. Sempre armazene uma "hash segura" que você pode verificar depois.
-## Múltiplos modelos
+Se não souber, você aprenderá o que é uma "senha hash" nos [capítulos de segurança](security/simple-oauth2.md#password-hashing).
-Aqui está uma ideia geral de como os modelos poderiam parecer com seus campos de senha e os lugares onde são usados:
-
-=== "Python 3.6 and above"
+///
- ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
- {!> ../../../docs_src/extra_models/tutorial001.py!}
- ```
+## Múltiplos modelos { #multiple-models }
-=== "Python 3.10 and above"
+Aqui está uma ideia geral de como os modelos poderiam parecer com seus campos de senha e os lugares onde são usados:
- ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
- {!> ../../../docs_src/extra_models/tutorial001_py310.py!}
- ```
+{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}
-### Sobre `**user_in.dict()`
+### Sobre `**user_in.model_dump()` { #about-user-in-model-dump }
-#### O `.dict()` do Pydantic
+#### O `.model_dump()` do Pydantic { #pydantics-model-dump }
`user_in` é um modelo Pydantic da classe `UserIn`.
-Os modelos Pydantic possuem um método `.dict()` que retorna um `dict` com os dados do modelo.
+Os modelos Pydantic possuem um método `.model_dump()` que retorna um `dict` com os dados do modelo.
Então, se criarmos um objeto Pydantic `user_in` como:
@@ -46,7 +39,7 @@ user_in = UserIn(username="john", password="secret", email="john.doe@example.com
e depois chamarmos:
```Python
-user_dict = user_in.dict()
+user_dict = user_in.model_dump()
```
agora temos um `dict` com os dados na variável `user_dict` (é um `dict` em vez de um objeto de modelo Pydantic).
@@ -68,7 +61,7 @@ teríamos um `dict` Python com:
}
```
-#### Desembrulhando um `dict`
+#### Desembrulhando um `dict` { #unpacking-a-dict }
Se tomarmos um `dict` como `user_dict` e passarmos para uma função (ou classe) com `**user_dict`, o Python irá "desembrulhá-lo". Ele passará as chaves e valores do `user_dict` diretamente como argumentos chave-valor.
@@ -100,31 +93,31 @@ UserInDB(
)
```
-#### Um modelo Pydantic a partir do conteúdo de outro
+#### Um modelo Pydantic a partir do conteúdo de outro { #a-pydantic-model-from-the-contents-of-another }
-Como no exemplo acima, obtivemos o `user_dict` a partir do `user_in.dict()`, este código:
+Como no exemplo acima, obtivemos o `user_dict` a partir do `user_in.model_dump()`, este código:
```Python
-user_dict = user_in.dict()
+user_dict = user_in.model_dump()
UserInDB(**user_dict)
```
seria equivalente a:
```Python
-UserInDB(**user_in.dict())
+UserInDB(**user_in.model_dump())
```
-...porque `user_in.dict()` é um `dict`, e depois fazemos o Python "desembrulhá-lo" passando-o para UserInDB precedido por `**`.
+...porque `user_in.model_dump()` é um `dict`, e depois fazemos o Python "desembrulhá-lo" passando-o para `UserInDB` precedido por `**`.
Então, obtemos um modelo Pydantic a partir dos dados em outro modelo Pydantic.
-#### Desembrulhando um `dict` e palavras-chave extras
+#### Desembrulhando um `dict` e palavras-chave extras { #unpacking-a-dict-and-extra-keywords }
E, então, adicionando o argumento de palavra-chave extra `hashed_password=hashed_password`, como em:
```Python
-UserInDB(**user_in.dict(), hashed_password=hashed_password)
+UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
```
...acaba sendo como:
@@ -139,10 +132,13 @@ UserInDB(
)
```
-!!! warning
- As funções adicionais de suporte são apenas para demonstração de um fluxo possível dos dados, mas é claro que elas não fornecem segurança real.
+/// warning | Atenção
+
+As funções adicionais de suporte `fake_password_hasher` e `fake_save_user` servem apenas para demonstrar um fluxo possível dos dados, mas é claro que elas não fornecem segurança real.
-## Reduzir duplicação
+///
+
+## Reduzir duplicação { #reduce-duplication }
Reduzir a duplicação de código é uma das ideias principais no **FastAPI**.
@@ -158,42 +154,25 @@ Toda conversão de dados, validação, documentação, etc. ainda funcionará no
Dessa forma, podemos declarar apenas as diferenças entre os modelos (com `password` em texto claro, com `hashed_password` e sem senha):
-=== "Python 3.6 and above"
-
- ```Python hl_lines="9 15-16 19-20 23-24"
- {!> ../../../docs_src/extra_models/tutorial002.py!}
- ```
-
-=== "Python 3.10 and above"
-
- ```Python hl_lines="7 13-14 17-18 21-22"
- {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
- ```
+{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}
-## `Union` ou `anyOf`
+## `Union` ou `anyOf` { #union-or-anyof }
-Você pode declarar uma resposta como o `Union` de dois tipos, o que significa que a resposta seria qualquer um dos dois.
+Você pode declarar uma resposta como o `Union` de dois ou mais tipos, o que significa que a resposta seria qualquer um deles.
Isso será definido no OpenAPI com `anyOf`.
-Para fazer isso, use a dica de tipo padrão do Python `typing.Union`:
+Para fazer isso, use a anotação de tipo padrão do Python [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union):
-!!! note
- Ao definir um `Union`, inclua o tipo mais específico primeiro, seguido pelo tipo menos específico. No exemplo abaixo, o tipo mais específico `PlaneItem` vem antes de `CarItem` em `Union[PlaneItem, CarItem]`.
+/// note | Nota
-=== "Python 3.6 and above"
+Ao definir um [`Union`](https://docs.pydantic.dev/latest/concepts/types/#unions), inclua o tipo mais específico primeiro, seguido pelo tipo menos específico. No exemplo abaixo, o tipo mais específico `PlaneItem` vem antes de `CarItem` em `Union[PlaneItem, CarItem]`.
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003.py!}
- ```
+///
-=== "Python 3.10 and above"
+{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003_py310.py!}
- ```
-
-### `Union` no Python 3.10
+### `Union` no Python 3.10 { #union-in-python-3-10 }
Neste exemplo, passamos `Union[PlaneItem, CarItem]` como o valor do argumento `response_model`.
@@ -205,47 +184,27 @@ Se estivesse em uma anotação de tipo, poderíamos ter usado a barra vertical,
some_variable: PlaneItem | CarItem
```
-Mas se colocarmos isso em `response_model=PlaneItem | CarItem` teríamos um erro, pois o Python tentaria executar uma **operação inválida** entre `PlaneItem` e `CarItem` em vez de interpretar isso como uma anotação de tipo.
+Mas se colocarmos isso na atribuição `response_model=PlaneItem | CarItem`, teríamos um erro, pois o Python tentaria executar uma **operação inválida** entre `PlaneItem` e `CarItem` em vez de interpretar isso como uma anotação de tipo.
-## Lista de modelos
+## Lista de modelos { #list-of-models }
Da mesma forma, você pode declarar respostas de listas de objetos.
-Para isso, use o padrão Python `typing.List` (ou simplesmente `list` no Python 3.9 e superior):
-
-=== "Python 3.6 and above"
-
- ```Python hl_lines="1 20"
- {!> ../../../docs_src/extra_models/tutorial004.py!}
- ```
-
-=== "Python 3.9 and above"
+Para isso, use o padrão Python `list`:
- ```Python hl_lines="18"
- {!> ../../../docs_src/extra_models/tutorial004_py39.py!}
- ```
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
-## Resposta com `dict` arbitrário
+## Resposta com `dict` arbitrário { #response-with-arbitrary-dict }
Você também pode declarar uma resposta usando um simples `dict` arbitrário, declarando apenas o tipo das chaves e valores, sem usar um modelo Pydantic.
Isso é útil se você não souber os nomes de campo / atributo válidos (que seriam necessários para um modelo Pydantic) antecipadamente.
-Neste caso, você pode usar `typing.Dict` (ou simplesmente dict no Python 3.9 e superior):
-
-=== "Python 3.6 and above"
-
- ```Python hl_lines="1 8"
- {!> ../../../docs_src/extra_models/tutorial005.py!}
- ```
-
-=== "Python 3.9 and above"
+Neste caso, você pode usar `dict`:
- ```Python hl_lines="6"
- {!> ../../../docs_src/extra_models/tutorial005_py39.py!}
- ```
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
-## Em resumo
+## Recapitulação { #recap }
Use vários modelos Pydantic e herde livremente para cada caso.
diff --git a/docs/pt/docs/tutorial/first-steps.md b/docs/pt/docs/tutorial/first-steps.md
index 9fcdaf91f2d32..719a38c2098a5 100644
--- a/docs/pt/docs/tutorial/first-steps.md
+++ b/docs/pt/docs/tutorial/first-steps.md
@@ -1,47 +1,64 @@
-# Primeiros Passos
+# Primeiros Passos { #first-steps }
O arquivo FastAPI mais simples pode se parecer com:
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
Copie o conteúdo para um arquivo `main.py`.
-Execute o servidor:
+Execute o servidor ao vivo:
get
+* o path `/`
+* usando uma get operação
+
+/// info | Informações sobre `@decorator`
-!!! info "`@decorador`"
- Essa sintaxe `@alguma_coisa` em Python é chamada de "decorador".
+Essa sintaxe `@alguma_coisa` em Python é chamada de "decorador".
- Você o coloca em cima de uma função. Como um chapéu decorativo (acho que é daí que vem o termo).
+Você o coloca em cima de uma função. Como um chapéu decorativo (acho que é daí que vem o termo).
- Um "decorador" pega a função abaixo e faz algo com ela.
+Um "decorador" pega a função abaixo e faz algo com ela.
- Em nosso caso, este decorador informa ao **FastAPI** que a função abaixo corresponde a **rota** `/` com uma **operação** `get`.
+Em nosso caso, este decorador informa ao **FastAPI** que a função abaixo corresponde ao **path** `/` com uma **operação** `get`.
- É o "**decorador de rota**".
+É o "**decorador de operação de rota**".
+
+///
Você também pode usar as outras operações:
@@ -274,60 +349,81 @@ E os mais exóticos:
* `@app.patch()`
* `@app.trace()`
-!!! tip "Dica"
- Você está livre para usar cada operação (método HTTP) como desejar.
+/// tip | Dica
+
+Você está livre para usar cada operação (método HTTP) como desejar.
+
+O **FastAPI** não impõe nenhum significado específico.
- O **FastAPI** não impõe nenhum significado específico.
+As informações aqui são apresentadas como uma orientação, não uma exigência.
- As informações aqui são apresentadas como uma orientação, não uma exigência.
+Por exemplo, ao usar GraphQL, você normalmente executa todas as ações usando apenas operações `POST`.
- Por exemplo, ao usar GraphQL, você normalmente executa todas as ações usando apenas operações `POST`.
+///
-### Passo 4: defina uma **função de rota**
+### Passo 4: defina a **função de operação de rota** { #step-4-define-the-path-operation-function }
-Esta é a nossa "**função de rota**":
+Esta é a nossa "**função de operação de rota**":
-* **rota**: é `/`.
+* **path**: é `/`.
* **operação**: é `get`.
* **função**: é a função abaixo do "decorador" (abaixo do `@app.get("/")`).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
Esta é uma função Python.
-Ela será chamada pelo **FastAPI** sempre que receber uma requisição para a URL "`/ `" usando uma operação `GET`.
+Ela será chamada pelo **FastAPI** sempre que receber uma requisição para a URL "`/`" usando uma operação `GET`.
-Neste caso, é uma função `assíncrona`.
+Neste caso, é uma função `async`.
---
Você também pode defini-la como uma função normal em vez de `async def`:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
-!!! nota
- Se você não sabe a diferença, verifique o [Async: *"Com pressa?"*](../async.md#com-pressa){.internal-link target=_blank}.
+/// note | Nota
-### Passo 5: retorne o conteúdo
+Se você não sabe a diferença, verifique o [Async: *"Com pressa?"*](../async.md#in-a-hurry).
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+///
+
+### Passo 5: retorne o conteúdo { #step-5-return-the-content }
+
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
Você pode retornar um `dict`, `list` e valores singulares como `str`, `int`, etc.
-Você também pode devolver modelos Pydantic (você verá mais sobre isso mais tarde).
+Você também pode devolver modelos Pydantic ( você verá mais sobre isso mais tarde).
Existem muitos outros objetos e modelos que serão convertidos automaticamente para JSON (incluindo ORMs, etc). Tente usar seus favoritos, é altamente provável que já sejam compatíveis.
-## Recapitulando
+### Passo 6: Faça o deploy { #step-6-deploy-it }
+
+Faça o deploy da sua aplicação para a **[FastAPI Cloud](https://fastapicloud.com)** com um comando: `fastapi deploy`. 🎉
+
+#### Sobre o FastAPI Cloud { #about-fastapi-cloud }
+
+A **[FastAPI Cloud](https://fastapicloud.com)** é construída pelo mesmo autor e equipe por trás do **FastAPI**.
+
+Ela simplifica o processo de **construir**, **fazer deploy** e **acessar** uma API com o mínimo de esforço.
+
+Traz a mesma **experiência do desenvolvedor** de criar aplicações com FastAPI para **fazer o deploy** delas na nuvem. 🎉
+
+A FastAPI Cloud é a principal patrocinadora e financiadora dos projetos open source do ecossistema *FastAPI and friends*. ✨
+
+#### Faça o deploy em outros provedores de nuvem { #deploy-to-other-cloud-providers }
+
+FastAPI é open source e baseado em padrões. Você pode fazer deploy de aplicações FastAPI em qualquer provedor de nuvem que preferir.
+
+Siga os tutoriais do seu provedor de nuvem para fazer deploy de aplicações FastAPI com eles. 🤓
+
+## Recapitulando { #recap }
* Importe `FastAPI`.
* Crie uma instância do `app`.
-* Coloque o **decorador que define a operação** (como `@app.get("/")`).
-* Escreva uma **função para a operação da rota** (como `def root(): ...`) abaixo.
-* Execute o servidor de desenvolvimento (como `uvicorn main:app --reload`).
+* Escreva um **decorador de operação de rota** usando decoradores como `@app.get("/")`.
+* Defina uma **função de operação de rota**; por exemplo, `def root(): ...`.
+* Execute o servidor de desenvolvimento usando o comando `fastapi dev`.
+* Opcionalmente, faça o deploy da sua aplicação com `fastapi deploy`.
diff --git a/docs/pt/docs/tutorial/handling-errors.md b/docs/pt/docs/tutorial/handling-errors.md
index 97a2e3eac9531..c400a1e84813c 100644
--- a/docs/pt/docs/tutorial/handling-errors.md
+++ b/docs/pt/docs/tutorial/handling-errors.md
@@ -1,4 +1,4 @@
-# Manipulação de erros
+# Manipulação de erros { #handling-errors }
Há diversas situações em que você precisa notificar um erro a um cliente que está utilizando a sua API.
@@ -11,7 +11,6 @@ Pode ser que você precise comunicar ao cliente que:
* O item que o cliente está tentando acessar não existe.
* etc.
-
Nesses casos, você normalmente retornaria um **HTTP status code** próximo ao status code na faixa do status code **400** (do 400 ao 499).
Isso é bastante similar ao caso do HTTP status code 200 (do 200 ao 299). Esses "200" status codes significam que, de algum modo, houve sucesso na requisição.
@@ -20,39 +19,34 @@ Os status codes na faixa dos 400 significam que houve um erro por parte do clien
Você se lembra de todos aqueles erros (e piadas) a respeito do "**404 Not Found**"?
-## Use o `HTTPException`
+## Use o `HTTPException` { #use-httpexception }
Para retornar ao cliente *responses* HTTP com erros, use o `HTTPException`.
-### Import `HTTPException`
+### Import `HTTPException` { #import-httpexception }
-```Python hl_lines="1"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-```
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
-### Lance o `HTTPException` no seu código.
+### Lance o `HTTPException` no seu código { #raise-an-httpexception-in-your-code }
`HTTPException`, ao fundo, nada mais é do que a conjunção entre uma exceção comum do Python e informações adicionais relevantes para APIs.
E porque é uma exceção do Python, você não **retorna** (return) o `HTTPException`, você lança o (raise) no seu código.
-Isso também significa que, se você está escrevendo uma função de utilidade, a qual você está chamando dentro da sua função de operações de caminhos, e você lança o `HTTPException` dentro da função de utilidade, o resto do seu código não será executado dentro da função de operações de caminhos. Ao contrário, o `HTTPException` irá finalizar a requisição no mesmo instante e enviará o erro HTTP oriundo do `HTTPException` para o cliente.
+Isso também significa que, se você está escrevendo uma função de utilidade, a qual você está chamando dentro da sua função de operação de rota, e você lança o `HTTPException` dentro da função de utilidade, o resto do seu código não será executado dentro da função de operação de rota. Ao contrário, o `HTTPException` irá finalizar a requisição no mesmo instante e enviará o erro HTTP oriundo do `HTTPException` para o cliente.
O benefício de lançar uma exceção em vez de retornar um valor ficará mais evidente na seção sobre Dependências e Segurança.
Neste exemplo, quando o cliente pede, na requisição, por um item cujo ID não existe, a exceção com o status code `404` é lançada:
-```Python hl_lines="11"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-```
-
-### A response resultante
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
+### A response resultante { #the-resulting-response }
Se o cliente faz uma requisição para `http://example.com/items/foo` (um `item_id` `"foo"`), esse cliente receberá um HTTP status code 200, e uma resposta JSON:
-```
+```JSON
{
"item": "The Foo Wrestlers"
}
@@ -66,14 +60,16 @@ Mas se o cliente faz uma requisição para `http://example.com/items/bar` (ou se
}
```
-!!! tip "Dica"
- Quando você lançar um `HTTPException`, você pode passar qualquer valor convertível em JSON como parâmetro de `detail`, e não apenas `str`.
+/// tip | Dica
- Você pode passar um `dict` ou um `list`, etc.
- Esses tipos de dados são manipulados automaticamente pelo **FastAPI** e convertidos em JSON.
+Quando você lançar um `HTTPException`, você pode passar qualquer valor convertível em JSON como parâmetro de `detail`, e não apenas `str`.
+Você pode passar um `dict` ou um `list`, etc.
+Esses tipos de dados são manipulados automaticamente pelo **FastAPI** e convertidos em JSON.
-## Adicione headers customizados
+///
+
+## Adicione headers customizados { #add-custom-headers }
Há certas situações em que é bastante útil poder adicionar headers customizados no HTTP error. Exemplo disso seria adicionar headers customizados para tipos de segurança.
@@ -81,23 +77,19 @@ Você provavelmente não precisará utilizar esses headers diretamente no seu c
Mas caso você precise, para um cenário mais complexo, você pode adicionar headers customizados:
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial002.py!}
-```
+{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
-## Instalando manipuladores de exceções customizados
+## Instale manipuladores de exceções customizados { #install-custom-exception-handlers }
-Você pode adicionar manipuladores de exceção customizados com a mesma seção de utilidade de exceções presentes no Starlette
+Você pode adicionar manipuladores de exceção customizados com [a mesma seção de utilidade de exceções presentes no Starlette](https://www.starlette.dev/exceptions/).
Digamos que você tenha uma exceção customizada `UnicornException` que você (ou uma biblioteca que você use) precise lançar (`raise`).
Nesse cenário, se você precisa manipular essa exceção de modo global com o FastAPI, você pode adicionar um manipulador de exceção customizada com `@app.exception_handler()`.
-```Python hl_lines="5-7 13-18 24"
-{!../../../docs_src/handling_errors/tutorial003.py!}
-```
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
-Nesse cenário, se você fizer uma requisição para `/unicorns/yolo`, a *operação de caminho* vai lançar (`raise`) o `UnicornException`.
+Nesse cenário, se você fizer uma requisição para `/unicorns/yolo`, a *operação de rota* vai lançar (`raise`) o `UnicornException`.
Essa exceção será manipulada, contudo, pelo `unicorn_exception_handler`.
@@ -107,28 +99,33 @@ Dessa forma você receberá um erro "limpo", com o HTTP status code `418` e um J
{"message": "Oops! yolo did something. There goes a rainbow..."}
```
-!!! note "Detalhes Técnicos"
- Você também pode usar `from starlette.requests import Request` and `from starlette.responses import JSONResponse`.
+/// note | Detalhes Técnicos
+
+Você também pode usar `from starlette.requests import Request` e `from starlette.responses import JSONResponse`.
+
+**FastAPI** disponibiliza o mesmo `starlette.responses` através do `fastapi.responses` por conveniência ao desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. O mesmo acontece com o `Request`.
- **FastAPI** disponibiliza o mesmo `starlette.responses` através do `fastapi.responses` por conveniência ao desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. O mesmo acontece com o `Request`.
+///
-## Sobrescreva o manipulador padrão de exceções
+## Sobrescreva os manipuladores de exceções padrão { #override-the-default-exception-handlers }
**FastAPI** tem alguns manipuladores padrão de exceções.
-Esses manipuladores são os responsáveis por retornar o JSON padrão de respostas quando você lança (`raise`) o `HTTPException` e quando a requisição tem dados invalidos.
+Esses manipuladores são os responsáveis por retornar o JSON padrão de respostas quando você lança (`raise`) o `HTTPException` e quando a requisição tem dados inválidos.
Você pode sobrescrever esses manipuladores de exceção com os seus próprios manipuladores.
-## Sobrescreva exceções de validação da requisição
+### Sobrescreva exceções de validação da requisição { #override-request-validation-exceptions }
Quando a requisição contém dados inválidos, **FastAPI** internamente lança para o `RequestValidationError`.
+E também inclui um manipulador de exceções padrão para ele.
+
Para sobrescrevê-lo, importe o `RequestValidationError` e use-o com o `@app.exception_handler(RequestValidationError)` para decorar o manipulador de exceções.
-```Python hl_lines="2 14-16"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-```
+O manipulador de exceções receberá um `Request` e a exceção.
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
Se você for ao `/items/foo`, em vez de receber o JSON padrão com o erro:
@@ -150,45 +147,41 @@ Se você for ao `/items/foo`, em vez de receber o JSON padrão com o erro:
você receberá a versão em texto:
```
-1 validation error
-path -> item_id
- value is not a valid integer (type=type_error.integer)
+Validation errors:
+Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer
```
-### `RequestValidationError` vs `ValidationError`
+### Sobrescreva o manipulador de erro `HTTPException` { #override-the-httpexception-error-handler }
-!!! warning "Aviso"
- Você pode pular estes detalhes técnicos caso eles não sejam importantes para você neste momento.
+Do mesmo modo, você pode sobrescrever o `HTTPException`.
-`RequestValidationError` é uma subclasse do `ValidationError` existente no Pydantic.
+Por exemplo, você pode querer retornar uma *response* em *plain text* ao invés de um JSON para os seguintes erros:
-**FastAPI** faz uso dele para que você veja o erro no seu log, caso você utilize um modelo de Pydantic em `response_model`, e seus dados tenham erro.
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
-Contudo, o cliente ou usuário não terão acesso a ele. Ao contrário, o cliente receberá um "Internal Server Error" com o HTTP status code `500`.
+/// note | Detalhes Técnicos
-E assim deve ser porque seria um bug no seu código ter o `ValidationError` do Pydantic na sua *response*, ou em qualquer outro lugar do seu código (que não na requisição do cliente).
+Você pode usar `from starlette.responses import PlainTextResponse`.
-E enquanto você conserta o bug, os clientes / usuários não deveriam ter acesso às informações internas do erro, porque, desse modo, haveria exposição de uma vulnerabilidade de segurança.
+**FastAPI** disponibiliza o mesmo `starlette.responses` como `fastapi.responses`, como conveniência a você, desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette.
-Do mesmo modo, você pode sobreescrever o `HTTPException`.
+///
-Por exemplo, você pode querer retornar uma *response* em *plain text* ao invés de um JSON para os seguintes erros:
+/// warning | Atenção
-```Python hl_lines="3-4 9-11 22"
-{!../../../docs_src/handling_errors/tutorial004.py!}
-```
+Tenha em mente que o `RequestValidationError` contém as informações do nome do arquivo e da linha onde o erro de validação acontece, para que você possa mostrá-las nos seus logs com as informações relevantes, se quiser.
-!!! note "Detalhes Técnicos"
- Você pode usar `from starlette.responses import PlainTextResponse`.
+Mas isso significa que, se você simplesmente convertê-lo para uma string e retornar essa informação diretamente, você pode acabar vazando um pouco de informação sobre o seu sistema; por isso, aqui o código extrai e mostra cada erro de forma independente.
- **FastAPI** disponibiliza o mesmo `starlette.responses` como `fastapi.responses`, como conveniência a você, desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette.
+///
-
-### Use o body do `RequestValidationError`.
+### Use o body do `RequestValidationError` { #use-the-requestvalidationerror-body }
O `RequestValidationError` contém o `body` que ele recebeu de dados inválidos.
-Você pode utilizá-lo enquanto desenvolve seu app para conectar o *body* e debugá-lo, e assim retorná-lo ao usuário, etc.
+Você pode utilizá-lo enquanto desenvolve seu app para registrar o *body* e debugá-lo, e assim retorná-lo ao usuário, etc.
+
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
Tente enviar um item inválido como este:
@@ -199,7 +192,7 @@ Tente enviar um item inválido como este:
}
```
-Você receberá uma *response* informando-o de que a data é inválida, e contendo o *body* recebido:
+Você receberá uma *response* informando-o de que os dados são inválidos, e contendo o *body* recebido:
```JSON hl_lines="12-15"
{
@@ -220,32 +213,30 @@ Você receberá uma *response* informando-o de que a data é inválida, e conten
}
```
-#### O `HTTPException` do FastAPI vs o `HTTPException` do Starlette.
+#### O `HTTPException` do FastAPI vs o `HTTPException` do Starlette { #fastapis-httpexception-vs-starlettes-httpexception }
O **FastAPI** tem o seu próprio `HTTPException`.
E a classe de erro `HTTPException` do **FastAPI** herda da classe de erro do `HTTPException` do Starlette.
-A diferença entre os dois é a de que o `HTTPException` do **FastAPI** permite que você adicione *headers* que serão incluídos nas *responses*.
-
-Esses *headers* são necessários/utilizados internamente pelo OAuth 2.0 e também por outras utilidades de segurança.
+A única diferença é que o `HTTPException` do **FastAPI** aceita qualquer dado que possa ser convertido em JSON para o campo `detail`, enquanto o `HTTPException` do Starlette aceita apenas strings para esse campo.
Portanto, você pode continuar lançando o `HTTPException` do **FastAPI** normalmente no seu código.
Porém, quando você registrar um manipulador de exceção, você deve registrá-lo através do `HTTPException` do Starlette.
-Dessa forma, se qualquer parte do código interno, extensão ou plug-in do Starlette lançar o `HTTPException`, o seu manipulador de exceção poderá capturar esse lançamento e tratá-lo.
+Dessa forma, se qualquer parte do código interno, extensão ou plug-in do Starlette lançar um `HTTPException` do Starlette, o seu manipulador poderá capturar e tratá-lo.
+
+Neste exemplo, para poder ter ambos os `HTTPException` no mesmo código, a exceção do Starlette é renomeada para `StarletteHTTPException`:
```Python
from starlette.exceptions import HTTPException as StarletteHTTPException
```
-### Re-use os manipulares de exceção do **FastAPI**
+### Reutilize os manipuladores de exceção do **FastAPI** { #reuse-fastapis-exception-handlers }
Se você quer usar a exceção em conjunto com o mesmo manipulador de exceção *default* do **FastAPI**, você pode importar e re-usar esses manipuladores de exceção do `fastapi.exception_handlers`:
-```Python hl_lines="2-5 15 21"
-{!../../../docs_src/handling_errors/tutorial006.py!}
-```
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
Nesse exemplo você apenas imprime (`print`) o erro com uma mensagem expressiva. Mesmo assim, dá para pegar a ideia. Você pode usar a exceção e então apenas re-usar o manipulador de exceção *default*.
diff --git a/docs/pt/docs/tutorial/header-param-models.md b/docs/pt/docs/tutorial/header-param-models.md
new file mode 100644
index 0000000000000..046c99c29187b
--- /dev/null
+++ b/docs/pt/docs/tutorial/header-param-models.md
@@ -0,0 +1,72 @@
+# Modelos de Parâmetros do Cabeçalho { #header-parameter-models }
+
+Se você possui um grupo de **parâmetros de cabeçalho** relacionados, você pode criar um **modelo do Pydantic** para declará-los.
+
+Isso vai lhe permitir **reusar o modelo** em **múltiplos lugares** e também declarar validações e metadados para todos os parâmetros de uma vez. 😎
+
+/// note | Nota
+
+Isso é possível desde a versão `0.115.0` do FastAPI. 🤓
+
+///
+
+## Parâmetros do Cabeçalho com um Modelo Pydantic { #header-parameters-with-a-pydantic-model }
+
+Declare os **parâmetros de cabeçalho** que você precisa em um **modelo do Pydantic**, e então declare o parâmetro como `Header`:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+O **FastAPI** irá **extrair** os dados de **cada campo** a partir dos **cabeçalhos** da requisição e te retornará o modelo do Pydantic que você definiu.
+
+## Checando a documentação { #check-the-docs }
+
+Você pode ver os headers necessários na interface gráfica da documentação em `/docs`:
+
+
+contact| Parâmetro | Tipo | Descrição |
|---|---|---|
name | str | O nome identificador da pessoa/organização de contato. |
url | str | A URL que aponta para as informações de contato. DEVE estar no formato de uma URL. |
email | str | O endereço de e-mail da pessoa/organização de contato. DEVE estar no formato de um endereço de e-mail. |
license_info| Parâmetro | Tipo | Descrição |
|---|---|---|
name | str | OBRIGATÓRIO (se um license_info for definido). O nome da licença usada para a API. |
identifier | str | Uma expressão de licença [SPDX](https://spdx.org/licenses/) para a API. O campo identifier é mutuamente exclusivo do campo url. Disponível desde OpenAPI 3.1.0, FastAPI 0.99.0. |
url | str | Uma URL para a licença usada para a API. DEVE estar no formato de uma URL. |
+
+## Identificador de Licença { #license-identifier }
+
+Desde o OpenAPI 3.1.0 e FastAPI 0.99.0, você também pode definir o `license_info` com um `identifier` em vez de uma `url`.
+
+Por exemplo:
+
+{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}
+
+## Metadados para tags { #metadata-for-tags }
+
+Você também pode adicionar metadados adicionais para as diferentes tags usadas para agrupar suas operações de rota com o parâmetro `openapi_tags`.
+
+Ele recebe uma lista contendo um dicionário para cada tag.
+
+Cada dicionário pode conter:
+
+* `name` (**obrigatório**): uma `str` com o mesmo nome da tag que você usa no parâmetro `tags` nas suas *operações de rota* e `APIRouter`s.
+* `description`: uma `str` com uma breve descrição da tag. Pode conter Markdown e será exibido na interface de documentação.
+* `externalDocs`: um `dict` descrevendo a documentação externa com:
+ * `description`: uma `str` com uma breve descrição da documentação externa.
+ * `url` (**obrigatório**): uma `str` com a URL da documentação externa.
+
+### Criar Metadados para tags { #create-metadata-for-tags }
+
+Vamos tentar isso em um exemplo com tags para `users` e `items`.
+
+Crie metadados para suas tags e passe-os para o parâmetro `openapi_tags`:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}
+
+Observe que você pode usar Markdown dentro das descrições. Por exemplo, "login" será exibido em negrito (**login**) e "fancy" será exibido em itálico (_fancy_).
+
+/// tip | Dica
+
+Você não precisa adicionar metadados para todas as tags que você usa.
+
+///
+
+### Use suas tags { #use-your-tags }
+
+Use o parâmetro `tags` com suas *operações de rota* (e `APIRouter`s) para atribuí-los a diferentes tags:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}
+
+/// info | Informação
+
+Leia mais sobre tags em [Configuração de operação de rota](path-operation-configuration.md#tags).
+
+///
+
+### Cheque os documentos { #check-the-docs }
+
+Agora, se você verificar a documentação, ela exibirá todos os metadados adicionais:
+
+
+
+### Ordem das tags { #order-of-tags }
+
+A ordem de cada dicionário de metadados de tag também define a ordem exibida na interface de documentação.
+
+Por exemplo, embora `users` apareça após `items` em ordem alfabética, ele é exibido antes deles, porque adicionamos seus metadados como o primeiro dicionário na lista.
+
+## URL da OpenAPI { #openapi-url }
+
+Por padrão, o esquema OpenAPI é servido em `/openapi.json`.
+
+Mas você pode configurá-lo com o parâmetro `openapi_url`.
+
+Por exemplo, para defini-lo para ser servido em `/api/v1/openapi.json`:
+
+{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}
+
+Se você quiser desativar completamente o esquema OpenAPI, pode definir `openapi_url=None`, o que também desativará as interfaces de documentação que o utilizam.
+
+## URLs da Documentação { #docs-urls }
+
+Você pode configurar as duas interfaces de documentação incluídas:
+
+* **Swagger UI**: acessível em `/docs`.
+ * Você pode definir sua URL com o parâmetro `docs_url`.
+ * Você pode desativá-la definindo `docs_url=None`.
+* **ReDoc**: acessível em `/redoc`.
+ * Você pode definir sua URL com o parâmetro `redoc_url`.
+ * Você pode desativá-la definindo `redoc_url=None`.
+
+Por exemplo, para definir o Swagger UI para ser servido em `/documentation` e desativar o ReDoc:
+
+{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}
diff --git a/docs/pt/docs/tutorial/middleware.md b/docs/pt/docs/tutorial/middleware.md
new file mode 100644
index 0000000000000..5ae5854da7a66
--- /dev/null
+++ b/docs/pt/docs/tutorial/middleware.md
@@ -0,0 +1,95 @@
+# Middleware { #middleware }
+
+Você pode adicionar middleware à suas aplicações **FastAPI**.
+
+Um "middleware" é uma função que manipula cada **requisição** antes de ser processada por qualquer *operação de rota* específica. E também cada **resposta** antes de retorná-la.
+
+* Ele pega cada **requisição** que chega ao seu aplicativo.
+* Ele pode então fazer algo com essa **requisição** ou executar qualquer código necessário.
+* Então ele passa a **requisição** para ser processada pelo resto do aplicativo (por alguma *operação de rota*).
+* Ele então pega a **resposta** gerada pelo aplicativo (por alguma *operação de rota*).
+* Ele pode fazer algo com essa **resposta** ou executar qualquer código necessário.
+* Então ele retorna a **resposta**.
+
+/// note | Detalhes Técnicos
+
+Se você tiver dependências com `yield`, o código de saída será executado *depois* do middleware.
+
+Se houver alguma tarefa em segundo plano (abordada na seção [Tarefas em segundo plano](background-tasks.md), que você verá mais adiante), ela será executada *depois* de todo o middleware.
+
+///
+
+## Criar um middleware { #create-a-middleware }
+
+Para criar um middleware, use o decorador `@app.middleware("http")` logo acima de uma função.
+
+A função middleware recebe:
+
+* A `request`.
+* Uma função `call_next` que receberá o `request` como um parâmetro.
+ * Esta função passará a `request` para a *operação de rota* correspondente.
+ * Então ela retorna a `response` gerada pela *operação de rota* correspondente.
+* Você pode então modificar ainda mais o `response` antes de retorná-lo.
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}
+
+/// tip | Dica
+
+Tenha em mente que cabeçalhos proprietários personalizados podem ser adicionados [usando o prefixo `X-`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers).
+
+Mas se você tiver cabeçalhos personalizados desejando que um cliente em um navegador esteja apto a ver, você precisa adicioná-los às suas configurações CORS ([CORS (Cross-Origin Resource Sharing)](cors.md)) usando o parâmetro `expose_headers` documentado na [Documentação CORS da Starlette](https://www.starlette.dev/middleware/#corsmiddleware).
+
+///
+
+/// note | Detalhes Técnicos
+
+Você também pode usar `from starlette.requests import Request`.
+
+**FastAPI** fornece isso como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette.
+
+///
+
+### Antes e depois da `response` { #before-and-after-the-response }
+
+Você pode adicionar código para ser executado com a `request`, antes que qualquer *operação de rota* o receba.
+
+E também depois que a `response` é gerada, antes de retorná-la.
+
+Por exemplo, você pode adicionar um cabeçalho personalizado `X-Process-Time` contendo o tempo em segundos que levou para processar a solicitação e gerar uma resposta:
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}
+
+/// tip | Dica
+
+Aqui usamos [`time.perf_counter()`](https://docs.python.org/3/library/time.html#time.perf_counter) em vez de `time.time()` porque ele pode ser mais preciso para esses casos de uso. 🤓
+
+///
+
+## Ordem de execução de múltiplos middlewares { #multiple-middleware-execution-order }
+
+Quando você adiciona múltiplos middlewares usando o decorador `@app.middleware()` ou o método `app.add_middleware()`, cada novo middleware envolve a aplicação, formando uma pilha. O último middleware adicionado é o mais externo, e o primeiro é o mais interno.
+
+No caminho da requisição, o middleware mais externo roda primeiro.
+
+No caminho da resposta, ele roda por último.
+
+Por exemplo:
+
+```Python
+app.add_middleware(MiddlewareA)
+app.add_middleware(MiddlewareB)
+```
+
+Isso resulta na seguinte ordem de execução:
+
+* **Requisição**: MiddlewareB → MiddlewareA → rota
+
+* **Resposta**: rota → MiddlewareA → MiddlewareB
+
+Esse comportamento de empilhamento garante que os middlewares sejam executados em uma ordem previsível e controlável.
+
+## Outros middlewares { #other-middlewares }
+
+Mais tarde, você pode ler mais sobre outros middlewares no [Guia do usuário avançado: Middleware avançado](../advanced/middleware.md).
+
+Você lerá sobre como manipular CORS com um middleware na próxima seção.
diff --git a/docs/pt/docs/tutorial/path-operation-configuration.md b/docs/pt/docs/tutorial/path-operation-configuration.md
index e0a23f6655e39..745b9b6980730 100644
--- a/docs/pt/docs/tutorial/path-operation-configuration.md
+++ b/docs/pt/docs/tutorial/path-operation-configuration.md
@@ -1,11 +1,14 @@
-# Configuração da Operação de Rota
+# Configuração da Operação de Rota { #path-operation-configuration }
Existem vários parâmetros que você pode passar para o seu *decorador de operação de rota* para configurá-lo.
-!!! warning "Aviso"
- Observe que esses parâmetros são passados diretamente para o *decorador de operação de rota*, não para a sua *função de operação de rota*.
+/// warning | Atenção
-## Código de Status da Resposta
+Observe que esses parâmetros são passados diretamente para o *decorador de operação de rota*, não para a sua *função de operação de rota*.
+
+///
+
+## Código de Status da Resposta { #response-status-code }
Você pode definir o `status_code` (HTTP) para ser usado na resposta da sua *operação de rota*.
@@ -13,159 +16,83 @@ Você pode passar diretamente o código `int`, como `404`.
Mas se você não se lembrar o que cada código numérico significa, pode usar as constantes de atalho em `status`:
-=== "Python 3.6 and above"
-
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
- ```
-
-=== "Python 3.9 and above"
-
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
- ```
-
-=== "Python 3.10 and above"
-
- ```Python hl_lines="1 15"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *}
Esse código de status será usado na resposta e será adicionado ao esquema OpenAPI.
-!!! note "Detalhes Técnicos"
- Você também poderia usar `from starlette import status`.
-
- **FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente do Starlette.
-
-## Tags
+/// note | Detalhes Técnicos
-Você pode adicionar tags para sua *operação de rota*, passe o parâmetro `tags` com uma `list` de `str` (comumente apenas um `str`):
-
-=== "Python 3.6 and above"
+Você também poderia usar `from starlette import status`.
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
- ```
+**FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente do Starlette.
-=== "Python 3.9 and above"
+///
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
- ```
+## Tags { #tags }
-=== "Python 3.10 and above"
+Você pode adicionar tags para sua *operação de rota*, passe o parâmetro `tags` com uma `list` de `str` (comumente apenas um `str`):
- ```Python hl_lines="15 20 25"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *}
Eles serão adicionados ao esquema OpenAPI e usados pelas interfaces de documentação automática:
-### Tags com Enums
+### Tags com Enums { #tags-with-enums }
-Se você tem uma grande aplicação, você pode acabar acumulando **várias tags**, e você gostaria de ter certeza de que você sempre usa a **mesma tag** para *operações de rota* relacionadas.
+Se você tem uma grande aplicação, você pode acabar acumulando **várias tags**, e você gostaria de ter certeza de que você sempre usa a ** mesma tag** para *operações de rota* relacionadas.
Nestes casos, pode fazer sentido armazenar as tags em um `Enum`.
**FastAPI** suporta isso da mesma maneira que com strings simples:
-```Python hl_lines="1 8-10 13 18"
-{!../../../docs_src/path_operation_configuration/tutorial002b.py!}
-```
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
-## Resumo e descrição
+## Resumo e descrição { #summary-and-description }
Você pode adicionar um `summary` e uma `description`:
-=== "Python 3.6 and above"
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *}
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
- ```
+## Descrição do docstring { #description-from-docstring }
-=== "Python 3.9 and above"
+Como as descrições tendem a ser longas e cobrir várias linhas, você pode declarar a descrição da *operação de rota* na docstring da função e o **FastAPI** irá lê-la de lá.
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
- ```
+Você pode escrever [Markdown](https://en.wikipedia.org/wiki/Markdown) na docstring, ele será interpretado e exibido corretamente (levando em conta a indentação da docstring).
-=== "Python 3.10 and above"
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
- ```
-
-## Descrição do docstring
-
-Como as descrições tendem a ser longas e cobrir várias linhas, você pode declarar a descrição da *operação de rota* na docstring da função e o **FastAPI** irá lê-la de lá.
-
-Você pode escrever Markdown na docstring, ele será interpretado e exibido corretamente (levando em conta a indentação da docstring).
-
-=== "Python 3.6 and above"
-
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
- ```
-
-=== "Python 3.9 and above"
-
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
- ```
-
-=== "Python 3.10 and above"
-
- ```Python hl_lines="17-25"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}
Ela será usada nas documentações interativas:
-
-## Descrição da resposta
+## Descrição da resposta { #response-description }
Você pode especificar a descrição da resposta com o parâmetro `response_description`:
-=== "Python 3.6 and above"
-
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
-=== "Python 3.9 and above"
+/// info | Informação
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
- ```
+Note que `response_description` se refere especificamente à resposta, a `description` se refere à *operação de rota* em geral.
-=== "Python 3.10 and above"
+///
- ```Python hl_lines="19"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
- ```
+/// check | Verifique
-!!! info "Informação"
- Note que `response_description` se refere especificamente à resposta, a `description` se refere à *operação de rota* em geral.
+OpenAPI especifica que cada *operação de rota* requer uma descrição de resposta.
-!!! check
- OpenAPI especifica que cada *operação de rota* requer uma descrição de resposta.
+Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma de "Resposta bem-sucedida".
- Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma de "Resposta bem-sucedida".
+///
-## Depreciar uma *operação de rota*
+## Descontinuar uma *operação de rota* { #deprecate-a-path-operation }
-Se você precisar marcar uma *operação de rota* como descontinuada, mas sem removê-la, passe o parâmetro `deprecated`:
+Se você precisar marcar uma *operação de rota* como descontinuada, mas sem removê-la, passe o parâmetro `deprecated`:
-```Python hl_lines="16"
-{!../../../docs_src/path_operation_configuration/tutorial006.py!}
-```
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
Ela será claramente marcada como descontinuada nas documentações interativas:
@@ -175,6 +102,6 @@ Verifique como *operações de rota* descontinuadas e não descontinuadas se par
-## Resumindo
+## Resumindo { #recap }
Você pode configurar e adicionar metadados para suas *operações de rota* facilmente passando parâmetros para os *decoradores de operação de rota*.
diff --git a/docs/pt/docs/tutorial/path-params-numeric-validations.md b/docs/pt/docs/tutorial/path-params-numeric-validations.md
index ec9b74b300d2b..9bbe14c759ac6 100644
--- a/docs/pt/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/pt/docs/tutorial/path-params-numeric-validations.md
@@ -1,118 +1,128 @@
-# Parâmetros da Rota e Validações Numéricas
+# Parâmetros de path e validações numéricas { #path-parameters-and-numeric-validations }
-Do mesmo modo que você pode declarar mais validações e metadados para parâmetros de consulta com `Query`, você pode declarar os mesmos tipos de validações e metadados para parâmetros de rota com `Path`.
+Da mesma forma que você pode declarar mais validações e metadados para parâmetros de consulta com `Query`, você pode declarar o mesmo tipo de validações e metadados para parâmetros de path com `Path`.
-## Importe `Path`
+## Importe `Path` { #import-path }
-Primeiro, importe `Path` de `fastapi`:
+Primeiro, importe `Path` de `fastapi`, e importe `Annotated`:
-=== "Python 3.10+"
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+/// info | Informação
-=== "Python 3.6+"
+O FastAPI adicionou suporte a `Annotated` (e passou a recomendá-lo) na versão 0.95.0.
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+Se você tiver uma versão mais antiga, verá erros ao tentar usar `Annotated`.
-## Declare metadados
+Certifique-se de [Atualizar a versão do FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions) para pelo menos 0.95.1 antes de usar `Annotated`.
-Você pode declarar todos os parâmetros da mesma maneira que na `Query`.
+///
-Por exemplo para declarar um valor de metadado `title` para o parâmetro de rota `item_id` você pode digitar:
+## Declare metadados { #declare-metadata }
-=== "Python 3.10+"
+Você pode declarar todos os mesmos parâmetros que em `Query`.
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+Por exemplo, para declarar um valor de metadado `title` para o parâmetro de path `item_id` você pode digitar:
-=== "Python 3.6+"
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *}
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+/// note | Nota
-!!! note "Nota"
- Um parâmetro de rota é sempre obrigatório, como se fizesse parte da rota.
+Um parâmetro de path é sempre obrigatório, pois precisa fazer parte do path. Mesmo que você o declare como `None` ou defina um valor padrão, isso não afetaria nada, ele ainda seria sempre obrigatório.
- Então, você deve declará-lo com `...` para marcá-lo como obrigatório.
+///
- Mesmo que você declare-o como `None` ou defina um valor padrão, isso não teria efeito algum, o parâmetro ainda seria obrigatório.
+## Ordene os parâmetros de acordo com sua necessidade { #order-the-parameters-as-you-need }
-## Ordene os parâmetros de acordo com sua necessidade
+/// tip | Dica
-Suponha que você queira declarar o parâmetro de consulta `q` como uma `str` obrigatória.
+Isso provavelmente não é tão importante ou necessário se você usar `Annotated`.
-E você não precisa declarar mais nada em relação a este parâmetro, então você não precisa necessariamente usar `Query`.
+///
-Mas você ainda precisa usar `Path` para o parâmetro de rota `item_id`.
+Vamos supor que você queira declarar o parâmetro de consulta `q` como uma `str` obrigatória.
-O Python irá acusar se você colocar um elemento com um valor padrão definido antes de outro que não tenha um valor padrão.
+E você não precisa declarar mais nada para esse parâmetro, então você realmente não precisa usar `Query`.
-Mas você pode reordená-los, colocando primeiro o elemento sem o valor padrão (o parâmetro de consulta `q`).
+Mas você ainda precisa usar `Path` para o parâmetro de path `item_id`. E você não quer usar `Annotated` por algum motivo.
-Isso não faz diferença para o **FastAPI**. Ele vai detectar os parâmetros pelos seus nomes, tipos e definições padrão (`Query`, `Path`, etc), sem se importar com a ordem.
+O Python vai reclamar se você colocar um valor com “padrão” antes de um valor que não tem “padrão”.
+
+Mas você pode reordená-los e colocar primeiro o valor sem padrão (o parâmetro de consulta `q`).
+
+Isso não faz diferença para o **FastAPI**. Ele vai detectar os parâmetros pelos seus nomes, tipos e declarações de padrão (`Query`, `Path`, etc.), sem se importar com a ordem.
Então, você pode declarar sua função assim:
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial002.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
+
+Mas tenha em mente que, se você usar `Annotated`, você não terá esse problema, não fará diferença, pois você não está usando valores padrão de parâmetros de função para `Query()` ou `Path()`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
+
+## Ordene os parâmetros de acordo com sua necessidade, truques { #order-the-parameters-as-you-need-tricks }
+
+/// tip | Dica
+
+Isso provavelmente não é tão importante ou necessário se você usar `Annotated`.
+
+///
+
+Aqui vai um pequeno truque que pode ser útil, mas você não vai precisar dele com frequência.
-## Ordene os parâmetros de a acordo com sua necessidade, truques
+Se você quiser:
-Se você quiser declarar o parâmetro de consulta `q` sem um `Query` nem um valor padrão, e o parâmetro de rota `item_id` usando `Path`, e definí-los em uma ordem diferente, Python tem um pequeno truque na sintaxe para isso.
+* declarar o parâmetro de consulta `q` sem um `Query` nem qualquer valor padrão
+* declarar o parâmetro de path `item_id` usando `Path`
+* tê-los em uma ordem diferente
+* não usar `Annotated`
+
+...o Python tem uma pequena sintaxe especial para isso.
Passe `*`, como o primeiro parâmetro da função.
-O Python não vai fazer nada com esse `*`, mas ele vai saber que a partir dali os parâmetros seguintes deverão ser chamados argumentos nomeados (pares chave-valor), também conhecidos como kwargs. Mesmo que eles não possuam um valor padrão.
+O Python não fará nada com esse `*`, mas saberá que todos os parâmetros seguintes devem ser chamados como argumentos nomeados (pares chave-valor), também conhecidos como kwargs. Mesmo que eles não tenham um valor padrão.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
+
+### Melhor com `Annotated` { #better-with-annotated }
+
+Tenha em mente que, se você usar `Annotated`, como você não está usando valores padrão de parâmetros de função, você não terá esse problema e provavelmente não precisará usar `*`.
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
-## Validações numéricas: maior que ou igual
+## Validações numéricas: maior que ou igual { #number-validations-greater-than-or-equal }
-Com `Query` e `Path` (e outras que você verá mais tarde) você pode declarar restrições numéricas.
+Com `Query` e `Path` (e outras que você verá depois) você pode declarar restrições numéricas.
-Aqui, com `ge=1`, `item_id` precisará ser um número inteiro maior que ("`g`reater than") ou igual ("`e`qual") a 1.
+Aqui, com `ge=1`, `item_id` precisará ser um número inteiro “`g`reater than or `e`qual” a `1`.
-```Python hl_lines="8"
-{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
-## Validações numéricas: maior que e menor que ou igual
+## Validações numéricas: maior que e menor que ou igual { #number-validations-greater-than-and-less-than-or-equal }
-O mesmo se aplica para:
+O mesmo se aplica a:
* `gt`: maior que (`g`reater `t`han)
* `le`: menor que ou igual (`l`ess than or `e`qual)
-```Python hl_lines="9"
-{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
-## Validações numéricas: valores do tipo float, maior que e menor que
+## Validações numéricas: floats, maior que e menor que { #number-validations-floats-greater-than-and-less-than }
-Validações numéricas também funcionam para valores do tipo `float`.
+Validações numéricas também funcionam para valores `float`.
-Aqui é onde se torna importante a possibilidade de declarar gt e não apenas ge. Com isso você pode especificar, por exemplo, que um valor deve ser maior que `0`, ainda que seja menor que `1`.
+Aqui é onde se torna importante poder declarar gt e não apenas ge. Com isso você pode exigir, por exemplo, que um valor seja maior que `0`, mesmo que seja menor que `1`.
-Assim, `0.5` seria um valor válido. Mas `0.0` ou `0` não seria.
+Assim, `0.5` seria um valor válido. Mas `0.0` ou `0` não seriam.
-E o mesmo para lt.
+E o mesmo para lt.
-```Python hl_lines="11"
-{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
-## Recapitulando
+## Recapitulando { #recap }
-Com `Query`, `Path` (e outras que você ainda não viu) você pode declarar metadados e validações de texto do mesmo modo que com [Parâmetros de consulta e validações de texto](query-params-str-validations.md){.internal-link target=_blank}.
+Com `Query`, `Path` (e outras que você ainda não viu) você pode declarar metadados e validações de string do mesmo modo que em [Parâmetros de consulta e validações de string](query-params-str-validations.md).
E você também pode declarar validações numéricas:
@@ -121,18 +131,24 @@ E você também pode declarar validações numéricas:
* `lt`: menor que (`l`ess `t`han)
* `le`: menor que ou igual (`l`ess than or `e`qual)
-!!! info "Informação"
- `Query`, `Path` e outras classes que você verá a frente são subclasses de uma classe comum `Param`.
+/// info | Informação
+
+`Query`, `Path` e outras classes que você verá depois são subclasses de uma classe comum `Param`.
+
+Todas elas compartilham os mesmos parâmetros para validação adicional e metadados que você viu.
+
+///
+
+/// note | Detalhes Técnicos
- Todas elas compartilham os mesmos parâmetros para validação adicional e metadados que você viu.
+Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções.
-!!! note "Detalhes Técnicos"
- Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções.
+Que, quando chamadas, retornam instâncias de classes de mesmo nome.
- Que quando chamadas, retornam instâncias de classes de mesmo nome.
+Então, você importa `Query`, que é uma função. E quando você a chama, ela retorna uma instância de uma classe também chamada `Query`.
- Então, você importa `Query`, que é uma função. E quando você a chama, ela retorna uma instância de uma classe também chamada `Query`.
+Essas funções existem (em vez de usar diretamente as classes) para que seu editor não marque erros sobre seus tipos.
- Estas funções são assim (ao invés de apenas usar as classes diretamente) para que seu editor não acuse erros sobre seus tipos.
+Dessa forma, você pode usar seu editor e ferramentas de codificação normais sem precisar adicionar configurações personalizadas para desconsiderar esses erros.
- Dessa maneira você pode user seu editor e ferramentas de desenvolvimento sem precisar adicionar configurações customizadas para ignorar estes erros.
+///
diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md
index cd8c188584da9..ea9af63f36f68 100644
--- a/docs/pt/docs/tutorial/path-params.md
+++ b/docs/pt/docs/tutorial/path-params.md
@@ -1,190 +1,184 @@
-# Parâmetros da rota da URL
+# Parâmetros de path { #path-parameters }
-Você pode declarar os "parâmetros" ou "variáveis" com a mesma sintaxe utilizada pelo formato de strings do Python:
+Você pode declarar "parâmetros" ou "variáveis" de path com a mesma sintaxe usada por strings de formatação do Python:
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
-O valor do parâmetro que foi passado à `item_id` será passado para a sua função como o argumento `item_id`.
+O valor do parâmetro de path `item_id` será passado para a sua função como o argumento `item_id`.
-Então, se você rodar este exemplo e for até http://127.0.0.1:8000/items/foo, você verá a seguinte resposta:
+Então, se você executar este exemplo e acessar [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo), você verá uma resposta:
```JSON
{"item_id":"foo"}
```
-## Parâmetros da rota com tipos
+## Parâmetros de path com tipos { #path-parameters-with-types }
-Você pode declarar o tipo de um parâmetro na função usando as anotações padrões do Python:
+Você pode declarar o tipo de um parâmetro de path na função, usando as anotações de tipo padrão do Python:
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
+{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}
-Nesse caso, `item_id` está sendo declarado como um `int`.
+Neste caso, `item_id` é declarado como um `int`.
-!!! Check Verifique
- Isso vai dar à você suporte do seu editor dentro das funções, com verificações de erros, autocompletar, etc.
+/// check | Verifique
+Isso fornecerá suporte do editor dentro da sua função, com verificações de erros, preenchimento automático, etc.
+///
-## Conversão de dados
+## Dados conversão { #data-conversion }
-Se você rodar esse exemplo e abrir o seu navegador em http://127.0.0.1:8000/items/3, você verá a seguinte resposta:
+Se você executar este exemplo e abrir seu navegador em [http://127.0.0.1:8000/items/3](http://127.0.0.1:8000/items/3), você verá uma resposta:
```JSON
{"item_id":3}
```
-!!! Verifique
- Observe que o valor recebido pela função (e também retornado por ela) é `3`, como um Python `int`, não como uma string `"3"`.
+/// check | Verifique
+Perceba que o valor que sua função recebeu (e retornou) é `3`, como um `int` do Python, não uma string `"3"`.
- Então, com essa declaração de tipo, o **FastAPI** dá pra você um "parsing" automático no request .
+Então, com essa declaração de tipo, o **FastAPI** fornece "parsing" automático do request.
+///
-## Validação de dados
+## Validação de dados { #data-validation }
-Mas se você abrir o seu navegador em http://127.0.0.1:8000/items/foo, você verá um belo erro HTTP:
+Mas se você for no navegador para [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo), verá um bom erro HTTP:
```JSON
{
- "detail": [
- {
- "loc": [
- "path",
- "item_id"
- ],
- "msg": "value is not a valid integer",
- "type": "type_error.integer"
- }
- ]
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo"
+ }
+ ]
}
```
-devido ao parâmetro da rota `item_id` ter um valor `"foo"`, que não é um `int`.
+porque o parâmetro de path `item_id` tinha o valor `"foo"`, que não é um `int`.
-O mesmo erro apareceria se você tivesse fornecido um `float` ao invés de um `int`, como em: http://127.0.0.1:8000/items/4.2
+O mesmo erro apareceria se você fornecesse um `float` em vez de um `int`, como em: [http://127.0.0.1:8000/items/4.2](http://127.0.0.1:8000/items/4.2)
-!!! Verifique
- Então, com a mesma declaração de tipo do Python, o **FastAPI** dá pra você validação de dados.
+/// check | Verifique
+Então, com a mesma declaração de tipo do Python, o **FastAPI** fornece validação de dados.
- Observe que o erro também mostra claramente o ponto exato onde a validação não passou.
+Observe que o erro também declara claramente exatamente o ponto onde a validação não passou.
- Isso é incrivelmente útil enquanto se desenvolve e debuga o código que interage com a sua API.
+Isso é incrivelmente útil ao desenvolver e depurar código que interage com sua API.
+///
-## Documentação
+## Documentação { #documentation }
-Quando você abrir o seu navegador em http://127.0.0.1:8000/docs, você verá de forma automática e interativa a documentação da API como:
+E quando você abrir seu navegador em [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs), você verá documentação automática, interativa, da API como:
-!!! check
- Novamente, apenas com a mesma declaração de tipo do Python, o **FastAPI** te dá de forma automática e interativa a documentação (integrada com o Swagger UI).
+/// check | Verifique
+Novamente, apenas com a mesma declaração de tipo do Python, o **FastAPI** fornece documentação automática e interativa (integrando o Swagger UI).
- Veja que o parâmetro de rota está declarado como sendo um inteiro (int).
+Observe que o parâmetro de path está declarado como um inteiro.
+///
-## Beneficios baseados em padrões, documentação alternativa
+## Benefícios baseados em padrões, documentação alternativa { #standards-based-benefits-alternative-documentation }
-Devido ao schema gerado ser o padrão do OpenAPI, existem muitas ferramentas compatíveis.
+E como o schema gerado é do padrão [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md), existem muitas ferramentas compatíveis.
-Por esse motivo, o próprio **FastAPI** fornece uma API alternativa para documentação (utilizando ReDoc), que você pode acessar em http://127.0.0.1:8000/redoc:
+Por causa disso, o próprio **FastAPI** fornece uma documentação alternativa da API (usando ReDoc), que você pode acessar em [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc):
Da mesma forma, existem muitas ferramentas compatíveis. Incluindo ferramentas de geração de código para muitas linguagens.
-## Pydantic
+## Pydantic { #pydantic }
-Toda a validação de dados é feita por baixo dos panos pelo Pydantic, então você tem todos os benefícios disso. E assim você sabe que está em boas mãos.
+Toda a validação de dados é realizada nos bastidores pelo [Pydantic](https://docs.pydantic.dev/), então você recebe todos os benefícios disso. E você sabe que está em boas mãos.
-Você pode usar as mesmas declarações de tipo com `str`, `float`, `bool` e muitos outros tipos complexos de dados.
+Você pode usar as mesmas declarações de tipo com `str`, `float`, `bool` e muitos outros tipos de dados complexos.
-Vamos explorar muitos destes tipos nos próximos capítulos do tutorial.
+Vários deles são explorados nos próximos capítulos do tutorial.
-## A ordem importa
+## A ordem importa { #order-matters }
-Quando você cria operações de rota, você pode se deparar com situações onde você pode ter uma rota fixa.
+Ao criar *operações de rota*, você pode encontrar situações em que tem um path fixo.
-Algo como `/users/me` por exemplo, digamos que essa rota seja utilizada para pegar dados sobre o usuário atual.
+Como `/users/me`, digamos que seja para obter dados sobre o usuário atual.
-E então você pode ter também uma rota `/users/{user_id}` para pegar dados sobre um usuário específico associado a um ID de usuário.
+E então você também pode ter um path `/users/{user_id}` para obter dados sobre um usuário específico por algum ID de usuário.
-Porque as operações de rota são avaliadas em ordem, você precisa ter certeza que a rota para `/users/me` está sendo declarado antes da rota `/users/{user_id}`:
+Como as *operações de rota* são avaliadas em ordem, você precisa garantir que o path para `/users/me` seja declarado antes do de `/users/{user_id}`:
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
-```
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
-Caso contrário, a rota para `/users/{user_id}` coincidiria também para `/users/me`, "pensando" que estaria recebendo o parâmetro `user_id` com o valor de `"me"`.
+Caso contrário, o path para `/users/{user_id}` também corresponderia a `/users/me`, "achando" que está recebendo um parâmetro `user_id` com o valor `"me"`.
-## Valores predefinidos
+Da mesma forma, você não pode redefinir uma operação de rota:
-Se você tem uma operação de rota que recebe um parâmetro da rota, mas que você queira que esses valores possíveis do parâmetro da rota sejam predefinidos, você pode usar `Enum` padrão do Python.
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
-### Criando uma classe `Enum`
+A primeira sempre será usada, já que o path corresponde primeiro.
-Importe `Enum` e crie uma sub-classe que herde de `str` e de `Enum`.
+## Valores predefinidos { #predefined-values }
-Por herdar de `str` a documentação da API vai ser capaz de saber que os valores devem ser do tipo `string` e assim ser capaz de mostrar eles corretamente.
+Se você tem uma *operação de rota* que recebe um *parâmetro de path*, mas quer que os valores válidos possíveis do *parâmetro de path* sejam predefinidos, você pode usar um `Enum` padrão do Python.
-Assim, crie atributos de classe com valores fixos, que serão os valores válidos disponíveis.
+### Crie uma classe `Enum` { #create-an-enum-class }
-```Python hl_lines="1 6-9"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+Importe `Enum` e crie uma subclasse que herde de `str` e de `Enum`.
-!!! informação
- Enumerations (ou enums) estão disponíveis no Python desde a versão 3.4.
+Ao herdar de `str`, a documentação da API saberá que os valores devem ser do tipo `string` e poderá renderizá-los corretamente.
-!!! dica
- Se você está se perguntando, "AlexNet", "ResNet", e "LeNet" são apenas nomes de modelos de Machine Learning (aprendizado de máquina).
+Em seguida, crie atributos de classe com valores fixos, que serão os valores válidos disponíveis:
-### Declare um *parâmetro de rota*
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
-Logo, crie um *parâmetro de rota* com anotações de tipo usando a classe enum que você criou (`ModelName`):
+/// tip | Dica
+Se você está se perguntando, "AlexNet", "ResNet" e "LeNet" são apenas nomes de modelos de Aprendizado de Máquina modelos.
+///
-```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+### Declare um parâmetro de path { #declare-a-path-parameter }
+
+Em seguida, crie um *parâmetro de path* com anotação de tipo usando a classe enum que você criou (`ModelName`):
-### Revise a documentação
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
-Visto que os valores disponíveis para o parâmetro da rota estão predefinidos, a documentação interativa pode mostrar esses valores de uma forma bem legal:
+### Verifique a documentação { #check-the-docs }
+
+Como os valores disponíveis para o *parâmetro de path* são predefinidos, a documentação interativa pode mostrá-los de forma agradável:
-### Trabalhando com os *enumeration* do Python
+### Trabalhando com *enumerações* do Python { #working-with-python-enumerations }
-O valor do *parâmetro da rota* será um *membro de enumeration*.
+O valor do *parâmetro de path* será um *membro de enumeração*.
-#### Compare *membros de enumeration*
+#### Compare membros de enumeração { #compare-enumeration-members }
-Você pode comparar eles com o *membro de enumeration* no enum `ModelName` que você criou:
+Você pode compará-lo com o *membro de enumeração* no seu enum `ModelName` criado:
-```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}
-#### Obtenha o *valor de enumerate*
+#### Obtenha o valor da enumeração { #get-the-enumeration-value }
-Você pode ter o valor exato de enumerate (um `str` nesse caso) usando `model_name.value`, ou em geral, `your_enum_member.value`:
+Você pode obter o valor real (um `str` neste caso) usando `model_name.value`, ou, em geral, `your_enum_member.value`:
-```Python hl_lines="20"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}
-!!! conselho
- Você também poderia acessar o valor `"lenet"` com `ModelName.lenet.value`
+/// tip | Dica
+Você também pode acessar o valor `"lenet"` com `ModelName.lenet.value`.
+///
-#### Retorne *membros de enumeration*
+#### Retorne membros de enumeração { #return-enumeration-members }
-Você pode retornar *membros de enum* da sua *rota de operação*, em um corpo JSON aninhado (por exemplo um `dict`).
+Você pode retornar *membros de enum* da sua *operação de rota*, até mesmo aninhados em um corpo JSON (por exemplo, um `dict`).
-Eles serão convertidos para o seus valores correspondentes (strings nesse caso) antes de serem retornados ao cliente:
+Eles serão convertidos para seus valores correspondentes (strings neste caso) antes de serem retornados ao cliente:
-```Python hl_lines="18 21 23"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}
-No seu cliente você vai obter uma resposta JSON como:
+No seu cliente, você receberá uma resposta JSON como:
```JSON
{
@@ -193,53 +187,51 @@ No seu cliente você vai obter uma resposta JSON como:
}
```
-## Parâmetros de rota que contém caminhos
+## Parâmetros de path que contêm paths { #path-parameters-containing-paths }
-Digamos que você tenha uma *operação de rota* com uma rota `/files/{file_path}`.
+Digamos que você tenha uma *operação de rota* com um path `/files/{file_path}`.
-Mas você precisa que o próprio `file_path` contenha uma *rota*, como `home/johndoe/myfile.txt`.
+Mas você precisa que o próprio `file_path` contenha um *path*, como `home/johndoe/myfile.txt`.
-Então, a URL para este arquivo deveria ser algo como: `/files/home/johndoe/myfile.txt`.
+Então, a URL para esse arquivo seria algo como: `/files/home/johndoe/myfile.txt`.
-### Suporte do OpenAPI
+### Suporte do OpenAPI { #openapi-support }
-O OpenAPI não suporta uma maneira de declarar um *parâmetro de rota* que contenha uma *rota* dentro, dado que isso poderia levar a cenários que são difíceis de testar e definir.
+O OpenAPI não oferece suporte a uma maneira de declarar um *parâmetro de path* que contenha um *path* dentro, pois isso poderia levar a cenários difíceis de testar e definir.
-No entanto, você pode fazer isso no **FastAPI**, usando uma das ferramentas internas do Starlette.
+Ainda assim, você pode fazer isso no **FastAPI**, usando uma das ferramentas internas do Starlette.
-A documentação continuaria funcionando, ainda que não adicionaria nenhuma informação dizendo que o parâmetro deveria conter uma rota.
+E a documentação continuará funcionando, embora não adicione nenhuma informação dizendo que o parâmetro deve conter um path.
-### Conversor de rota
+### Conversor de path { #path-convertor }
-Usando uma opção direta do Starlette você pode declarar um *parâmetro de rota* contendo uma *rota* usando uma URL como:
+Usando uma opção diretamente do Starlette você pode declarar um *parâmetro de path* contendo um *path* usando uma URL como:
```
/files/{file_path:path}
```
-Nesse caso, o nome do parâmetro é `file_path`, e a última parte, `:path`, diz que o parâmetro deveria coincidir com qualquer *rota*.
-
-Então, você poderia usar ele com:
+Nesse caso, o nome do parâmetro é `file_path`, e a última parte, `:path`, diz que o parâmetro deve corresponder a qualquer *path*.
-```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
-```
+Então, você pode usá-lo com:
-!!! dica
- Você poderia precisar que o parâmetro contivesse `/home/johndoe/myfile.txt`, com uma barra no inicio (`/`).
+{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}
- Neste caso, a URL deveria ser: `/files//home/johndoe/myfile.txt`, com barra dupla (`//`) entre `files` e `home`.
+/// tip | Dica
+Você pode precisar que o parâmetro contenha `/home/johndoe/myfile.txt`, com uma barra inicial (`/`).
+Nesse caso, a URL seria: `/files//home/johndoe/myfile.txt`, com uma barra dupla (`//`) entre `files` e `home`.
+///
-## Recapitulando
+## Recapitulação { #recap }
-Com o **FastAPI**, usando as declarações de tipo do Python, você obtém:
+Com o **FastAPI**, ao usar declarações de tipo do Python curtas, intuitivas e padrão, você obtém:
-* Suporte no editor: verificação de erros, e opção de autocompletar, etc.
-* "Parsing" de dados
-* Validação de dados
-* Anotação da API e documentação automática
+- Suporte no editor: verificações de erro, preenchimento automático, etc.
+- "parsing" de dados
+- Validação de dados
+- Anotação da API e documentação automática
-Você apenas tem que declará-los uma vez.
+E você só precisa declará-los uma vez.
-Essa é provavelmente a vantagem mais visível do **FastAPI** se comparado com frameworks alternativos (além do desempenho puro).
+Essa é provavelmente a principal vantagem visível do **FastAPI** em comparação com frameworks alternativos (além do desempenho bruto).
diff --git a/docs/pt/docs/tutorial/query-param-models.md b/docs/pt/docs/tutorial/query-param-models.md
new file mode 100644
index 0000000000000..7fc59c0335931
--- /dev/null
+++ b/docs/pt/docs/tutorial/query-param-models.md
@@ -0,0 +1,68 @@
+# Modelos de Parâmetros de Consulta { #query-parameter-models }
+
+Se você possui um grupo de **parâmetros de consultas** que são relacionados, você pode criar um **modelo Pydantic** para declará-los.
+
+Isso permitiria que você **reutilizasse o modelo** em **diversos lugares**, e também declarasse validações e metadados de todos os parâmetros de uma única vez. 😎
+
+/// note | Nota
+
+Isso é suportado desde o FastAPI versão `0.115.0`. 🤓
+
+///
+
+## Parâmetros de Consulta com um Modelo Pydantic { #query-parameters-with-a-pydantic-model }
+
+Declare os **parâmetros de consulta** que você precisa em um **modelo Pydantic**, e então declare o parâmetro como `Query`:
+
+{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}
+
+O **FastAPI** **extrairá** os dados para **cada campo** dos **parâmetros de consulta** presentes na requisição, e fornecerá o modelo Pydantic que você definiu.
+
+## Verifique a Documentação { #check-the-docs }
+
+Você pode ver os parâmetros de consulta na IU da documentação em `/docs`:
+
+
+
-### Lista de parâmetros de consulta / múltiplos valores por padrão
+### Lista de parâmetros de consulta / múltiplos valores com valores padrão { #query-parameter-list-multiple-values-with-defaults }
-E você também pode definir uma lista (`list`) de valores padrão caso nenhum seja informado:
+Você também pode definir uma `list` de valores padrão caso nenhum seja fornecido:
-```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial012.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
Se você for até:
@@ -196,7 +277,7 @@ Se você for até:
http://localhost:8000/items/
```
-O valor padrão de `q` será: `["foo", "bar"]` e sua resposta será:
+o valor padrão de `q` será: `["foo", "bar"]` e sua resposta será:
```JSON
{
@@ -207,97 +288,163 @@ O valor padrão de `q` será: `["foo", "bar"]` e sua resposta será:
}
```
-#### Usando `list`
+#### Usando apenas `list` { #using-just-list }
-Você também pode utilizar o tipo `list` diretamente em vez de `List[str]`:
+Você também pode usar `list` diretamente em vez de `list[str]`:
-```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial013.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
+
+/// note | Nota
-!!! note "Observação"
- Tenha em mente que neste caso, o FastAPI não irá validar os conteúdos da lista.
+Tenha em mente que, neste caso, o FastAPI não verificará o conteúdo da lista.
- Por exemplo, um `List[int]` iria validar (e documentar) que os contéudos da lista são números inteiros. Mas apenas `list` não.
+Por exemplo, `list[int]` verificaria (and documentaria) que os conteúdos da lista são inteiros. Mas `list` sozinho não.
-## Declarando mais metadados
+///
+
+## Declare mais metadados { #declare-more-metadata }
Você pode adicionar mais informações sobre o parâmetro.
-Essa informações serão inclusas no esquema do OpenAPI e utilizado pela documentação interativa e ferramentas externas.
+Essas informações serão incluídas no OpenAPI gerado e usadas pelas interfaces de documentação e por ferramentas externas.
+
+/// note | Nota
+
+Tenha em mente que ferramentas diferentes podem ter níveis diferentes de suporte ao OpenAPI.
-!!! note "Observação"
- Tenha em mente que cada ferramenta oferece diferentes níveis de suporte ao OpenAPI.
+Algumas delas podem ainda não mostrar todas as informações extras declaradas, embora na maioria dos casos a funcionalidade ausente já esteja planejada para desenvolvimento.
- Algumas delas não exibem todas as informações extras que declaramos, ainda que na maioria dos casos, esses recursos estão planejados para desenvolvimento.
+///
Você pode adicionar um `title`:
-```Python hl_lines="10"
-{!../../../docs_src/query_params_str_validations/tutorial007.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *}
E uma `description`:
-```Python hl_lines="13"
-{!../../../docs_src/query_params_str_validations/tutorial008.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *}
-## Apelidos (alias) de parâmetros
+## Parâmetros com alias { #alias-parameters }
-Imagine que você queira que um parâmetro tenha o nome `item-query`.
+Imagine que você queira que o parâmetro seja `item-query`.
-Desta maneira:
+Assim:
```
http://127.0.0.1:8000/items/?item-query=foobaritems
```
-Mas o nome `item-query` não é um nome de váriavel válido no Python.
+Mas `item-query` não é um nome de variável Python válido.
-O que mais se aproxima é `item_query`.
+O mais próximo seria `item_query`.
-Mas ainda você precisa que o nome seja exatamente `item-query`...
+Mas você ainda precisa que seja exatamente `item-query`...
-Então você pode declarar um `alias`, e esse apelido (alias) que será utilizado para encontrar o valor do parâmetro:
+Então você pode declarar um `alias`, e esse alias será usado para encontrar o valor do parâmetro:
-```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial009.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *}
-## Parâmetros descontinuados
+## Descontinuando parâmetros { #deprecating-parameters }
-Agora vamos dizer que você não queria mais utilizar um parâmetro.
+Agora digamos que você não gosta mais desse parâmetro.
-Você tem que deixá-lo ativo por um tempo, já que existem clientes o utilizando. Mas você quer que a documentação deixe claro que este parâmetro será descontinuado.
+Você tem que deixá-lo por um tempo, pois há clientes usando-o, mas quer que a documentação mostre claramente que ele está descontinuado.
-Então você passa o parâmetro `deprecated=True` para `Query`:
+Então passe o parâmetro `deprecated=True` para `Query`:
-```Python hl_lines="18"
-{!../../../docs_src/query_params_str_validations/tutorial010.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *}
-Na documentação aparecerá assim:
+A documentação vai mostrar assim:
-## Recapitulando
+## Excluir parâmetros do OpenAPI { #exclude-parameters-from-openapi }
+
+Para excluir um parâmetro de consulta do OpenAPI gerado (e portanto, dos sistemas de documentação automáticos), defina o parâmetro `include_in_schema` de `Query` como `False`:
+
+{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *}
+
+## Validação personalizada { #custom-validation }
+
+Podem existir casos em que você precise fazer alguma validação personalizada que não pode ser feita com os parâmetros mostrados acima.
+
+Nesses casos, você pode usar uma função validadora personalizada que é aplicada após a validação normal (por exemplo, depois de validar que o valor é uma `str`).
+
+Você pode fazer isso usando o [`AfterValidator` do Pydantic](https://docs.pydantic.dev/latest/concepts/validators/#field-after-validator) dentro de `Annotated`.
+
+/// tip | Dica
+
+O Pydantic também tem [`BeforeValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-before-validator) e outros. 🤓
+
+///
-Você pode adicionar validações e metadados adicionais aos seus parâmetros.
+Por exemplo, este validador personalizado verifica se o ID do item começa com `isbn-` para um número de livro ISBN ou com `imdb-` para um ID de URL de filme IMDB:
-Validações genéricas e metadados:
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
+
+/// info | Informação
+
+Isso está disponível com a versão 2 do Pydantic ou superior. 😎
+
+///
+
+/// tip | Dica
+
+Se você precisar fazer qualquer tipo de validação que exija comunicação com algum componente externo, como um banco de dados ou outra API, você deveria usar Dependências do FastAPI em vez disso; você aprenderá sobre elas mais adiante.
+
+Esses validadores personalizados são para coisas que podem ser verificadas apenas com os mesmos dados fornecidos na requisição.
+
+///
+
+### Entenda esse código { #understand-that-code }
+
+O ponto importante é apenas usar `AfterValidator` com uma função dentro de `Annotated`. Sinta-se à vontade para pular esta parte. 🤸
+
+---
+
+Mas se você estiver curioso sobre este exemplo de código específico e ainda entretido, aqui vão alguns detalhes extras.
+
+#### String com `value.startswith()` { #string-with-value-startswith }
+
+Percebeu? Uma string usando `value.startswith()` pode receber uma tupla, e verificará cada valor na tupla:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *}
+
+#### Um item aleatório { #a-random-item }
+
+Com `data.items()` obtemos um objeto iterável com tuplas contendo a chave e o valor de cada item do dicionário.
+
+Convertimos esse objeto iterável em uma `list` adequada com `list(data.items())`.
+
+Em seguida, com `random.choice()` podemos obter um valor aleatório da lista, então obtemos uma tupla com `(id, name)`. Será algo como `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")`.
+
+Depois atribuímos esses dois valores da tupla às variáveis `id` e `name`.
+
+Assim, se o usuário não fornecer um ID de item, ele ainda receberá uma sugestão aleatória.
+
+...fazemos tudo isso em uma única linha simples. 🤯 Você não ama Python? 🐍
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *}
+
+## Recapitulando { #recap }
+
+Você pode declarar validações adicionais e metadados para seus parâmetros.
+
+Validações e metadados genéricos:
* `alias`
* `title`
* `description`
* `deprecated`
-Validações específicas para textos:
+Validações específicas para strings:
* `min_length`
* `max_length`
-* `regex`
+* `pattern`
+
+Validações personalizadas usando `AfterValidator`.
-Nesses exemplos você viu como declarar validações em valores do tipo `str`.
+Nestes exemplos você viu como declarar validações para valores `str`.
-Leia os próximos capítulos para ver como declarar validação de outros tipos, como números.
+Veja os próximos capítulos para aprender a declarar validações para outros tipos, como números.
diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md
index 3ada4fd213cb5..472c12be64d0b 100644
--- a/docs/pt/docs/tutorial/query-params.md
+++ b/docs/pt/docs/tutorial/query-params.md
@@ -1,10 +1,8 @@
-# Parâmetros de Consulta
+# Parâmetros de Consulta { #query-parameters }
Quando você declara outros parâmetros na função que não fazem parte dos parâmetros da rota, esses parâmetros são automaticamente interpretados como parâmetros de "consulta".
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial001.py!}
-```
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
A consulta é o conjunto de pares chave-valor que vai depois de `?` na URL, separado pelo caractere `&`.
@@ -26,11 +24,11 @@ Mas quando você declara eles com os tipos do Python (no exemplo acima, como `in
Todo o processo que era aplicado para parâmetros de rota também é aplicado para parâmetros de consulta:
* Suporte do editor (obviamente)
-* "Parsing" de dados
+* "análise" de dados
* Validação de dados
* Documentação automática
-## Valores padrão
+## Valores padrão { #defaults }
Como os parâmetros de consulta não são uma parte fixa da rota, eles podem ser opcionais e podem ter valores padrão.
@@ -59,43 +57,25 @@ Os valores dos parâmetros na sua função serão:
* `skip=20`: Por que você definiu isso na URL
* `limit=10`: Por que esse era o valor padrão
-## Parâmetros opcionais
+## Parâmetros opcionais { #optional-parameters }
Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo o valor padrão para `None`:
-=== "Python 3.10+"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
- ```
+{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *}
Nesse caso, o parâmetro da função `q` será opcional, e `None` será o padrão.
-!!! check "Verificar"
- Você também pode notar que o **FastAPI** é esperto o suficiente para perceber que o parâmetro da rota `item_id` é um parâmetro da rota, e `q` não é, portanto, `q` é o parâmetro de consulta.
+/// check | Verifique
+Você também pode notar que o **FastAPI** é esperto o suficiente para perceber que o parâmetro da rota `item_id` é um parâmetro da rota, e `q` não é, portanto, `q` é o parâmetro de consulta.
-## Conversão dos tipos de parâmetros de consulta
+///
-Você também pode declarar tipos `bool`, e eles serão convertidos:
+## Conversão dos tipos de parâmetros de consulta { #query-parameter-type-conversion }
-=== "Python 3.10+"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
- ```
-
-=== "Python 3.6+"
+Você também pode declarar tipos `bool`, e eles serão convertidos:
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *}
Nesse caso, se você for para:
@@ -129,7 +109,7 @@ http://127.0.0.1:8000/items/foo?short=yes
ou qualquer outra variação (tudo em maiúscula, primeira letra em maiúscula, etc), a sua função vai ver o parâmetro `short` com um valor `bool` de `True`. Caso contrário `False`.
-## Múltiplos parâmetros de rota e consulta
+## Múltiplos parâmetros de rota e consulta { #multiple-path-and-query-parameters }
Você pode declarar múltiplos parâmetros de rota e parâmetros de consulta ao mesmo tempo, o **FastAPI** vai saber o quê é o quê.
@@ -137,19 +117,9 @@ E você não precisa declarar eles em nenhuma ordem específica.
Eles serão detectados pelo nome:
-=== "Python 3.10+"
-
- ```Python hl_lines="6 8"
- {!> ../../../docs_src/query_params/tutorial004_py310.py!}
- ```
+{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *}
-=== "Python 3.6+"
-
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
-
-## Parâmetros de consulta obrigatórios
+## Parâmetros de consulta obrigatórios { #required-query-parameters }
Quando você declara um valor padrão para parâmetros que não são de rota (até agora, nós vimos apenas parâmetros de consulta), então eles não são obrigatórios.
@@ -157,11 +127,9 @@ Caso você não queira adicionar um valor específico mas queira apenas torná-l
Porém, quando você quiser fazer com que o parâmetro de consulta seja obrigatório, você pode simplesmente não declarar nenhum valor como padrão.
-```Python hl_lines="6-7"
-{!../../../docs_src/query_params/tutorial005.py!}
-```
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
-Aqui o parâmetro de consulta `needy` é um valor obrigatório, do tipo `str`.
+Aqui o parâmetro da consulta `needy` é um valor obrigatório, do tipo `str`.
Se você abrir no seu navegador a URL:
@@ -173,16 +141,17 @@ http://127.0.0.1:8000/items/foo-item
```JSON
{
- "detail": [
- {
- "loc": [
- "query",
- "needy"
- ],
- "msg": "field required",
- "type": "value_error.missing"
- }
- ]
+ "detail": [
+ {
+ "type": "missing",
+ "loc": [
+ "query",
+ "needy"
+ ],
+ "msg": "Field required",
+ "input": null
+ }
+ ]
}
```
@@ -203,17 +172,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
E claro, você pode definir alguns parâmetros como obrigatórios, alguns possuindo um valor padrão, e outros sendo totalmente opcionais:
-=== "Python 3.10+"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params/tutorial006_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params/tutorial006.py!}
- ```
+{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *}
Nesse caso, existem 3 parâmetros de consulta:
@@ -221,5 +180,8 @@ Nesse caso, existem 3 parâmetros de consulta:
* `skip`, um `int` com o valor padrão `0`.
* `limit`, um `int` opcional.
-!!! tip "Dica"
- Você também poderia usar `Enum` da mesma forma que com [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}.
+/// tip | Dica
+
+Você também poderia usar `Enum`s da mesma forma que com [Parâmetros de rota](path-params.md#predefined-values).
+
+///
diff --git a/docs/pt/docs/tutorial/request-files.md b/docs/pt/docs/tutorial/request-files.md
new file mode 100644
index 0000000000000..912878cd52adb
--- /dev/null
+++ b/docs/pt/docs/tutorial/request-files.md
@@ -0,0 +1,176 @@
+# Arquivos de Requisição { #request-files }
+
+Você pode definir arquivos para serem enviados pelo cliente usando `File`.
+
+/// info | Informação
+
+Para receber arquivos enviados, primeiro instale [`python-multipart`](https://github.com/Kludex/python-multipart).
+
+Garanta que você criou um [ambiente virtual](../virtual-environments.md), o ativou e então o instalou, por exemplo:
+
+```console
+$ pip install python-multipart
+```
+
+Isso é necessário, visto que os arquivos enviados são enviados como "dados de formulário".
+
+///
+
+## Importe `File` { #import-file }
+
+Importe `File` e `UploadFile` de `fastapi`:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
+
+## Definir Parâmetros `File` { #define-file-parameters }
+
+Crie parâmetros de arquivo da mesma forma que você faria para `Body` ou `Form`:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
+
+/// info | Informação
+
+`File` é uma classe que herda diretamente de `Form`.
+
+Mas lembre-se que quando você importa `Query`, `Path`, `File` e outros de `fastapi`, eles são, na verdade, funções que retornam classes especiais.
+
+///
+
+/// tip | Dica
+
+Para declarar corpos de arquivos, você precisa usar `File`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta ou parâmetros de corpo (JSON).
+
+///
+
+Os arquivos serão enviados como "dados de formulário".
+
+Se você declarar o tipo do parâmetro da função da sua *operação de rota* como `bytes`, o **FastAPI** lerá o arquivo para você e você receberá o conteúdo como `bytes`.
+
+Mantenha em mente que isso significa que todo o conteúdo será armazenado na memória. Isso funcionará bem para arquivos pequenos.
+
+Mas há muitos casos em que você pode se beneficiar do uso de `UploadFile`.
+
+## Parâmetros de Arquivo com `UploadFile` { #file-parameters-with-uploadfile }
+
+Defina um parâmetro de arquivo com um tipo de `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
+
+Utilizar `UploadFile` tem várias vantagens sobre `bytes`:
+
+* Você não precisa utilizar o `File()` no valor padrão do parâmetro.
+* Ele utiliza um arquivo "spooled":
+ * Um arquivo armazenado na memória até um limite máximo de tamanho, e após passar esse limite, ele será armazenado no disco.
+* Isso significa que funcionará bem para arquivos grandes como imagens, vídeos, binários grandes, etc., sem consumir toda a memória.
+* Você pode receber metadados do arquivo enviado.
+* Ele tem uma [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) interface `assíncrona`.
+* Ele expõe um objeto python [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) que você pode passar diretamente para outras bibliotecas que esperam um objeto semelhante a um arquivo.
+
+### `UploadFile` { #uploadfile }
+
+`UploadFile` tem os seguintes atributos:
+
+* `filename`: Uma `str` com o nome do arquivo original que foi enviado (por exemplo, `myimage.jpg`).
+* `content_type`: Uma `str` com o tipo de conteúdo (MIME type / media type) (por exemplo, `image/jpeg`).
+* `file`: Um [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) (um [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) objeto). Este é o objeto de arquivo Python que você pode passar diretamente para outras funções ou bibliotecas que esperam um objeto semelhante a um arquivo.
+
+`UploadFile` tem os seguintes métodos `assíncronos`. Todos eles chamam os métodos de arquivo correspondentes por baixo dos panos (usando o `SpooledTemporaryFile` interno).
+
+* `write(data)`: Escreve `data` (`str` ou `bytes`) no arquivo.
+* `read(size)`: Lê `size` (`int`) bytes/caracteres do arquivo.
+* `seek(offset)`: Vai para o byte na posição `offset` (`int`) no arquivo.
+ * Por exemplo, `await myfile.seek(0)` irá para o início do arquivo.
+ * Isso é especialmente útil se você executar `await myfile.read()` uma vez e precisar ler o conteúdo novamente.
+* `close()`: Fecha o arquivo.
+
+Como todos esses métodos são métodos `assíncronos`, você precisa "aguardar" por eles.
+
+Por exemplo, dentro de uma função de *operação de rota* `assíncrona`, você pode obter o conteúdo com:
+
+```Python
+contents = await myfile.read()
+```
+
+Se você estiver dentro de uma função de *operação de rota* normal `def`, você pode acessar o `UploadFile.file` diretamente, por exemplo:
+
+```Python
+contents = myfile.file.read()
+```
+
+/// note | Detalhes Técnicos do `async`
+
+Quando você usa os métodos `async`, o **FastAPI** executa os métodos de arquivo em um threadpool e aguarda por eles.
+
+///
+
+/// note | Detalhes Técnicos do Starlette
+
+O `UploadFile` do **FastAPI** herda diretamente do `UploadFile` do **Starlette**, mas adiciona algumas partes necessárias para torná-lo compatível com o **Pydantic** e as outras partes do FastAPI.
+
+///
+
+## O que é "Form Data" { #what-is-form-data }
+
+O jeito que os formulários HTML (``) enviam os dados para o servidor normalmente usa uma codificação "especial" para esses dados, a qual é diferente do JSON.
+
+**FastAPI** se certificará de ler esses dados do lugar certo, ao invés de JSON.
+
+/// note | Detalhes Técnicos
+
+Dados de formulários normalmente são codificados usando o "media type" `application/x-www-form-urlencoded` quando não incluem arquivos.
+
+Mas quando o formulário inclui arquivos, ele é codificado como `multipart/form-data`. Se você usar `File`, o **FastAPI** saberá que tem que pegar os arquivos da parte correta do corpo da requisição.
+
+Se você quiser ler mais sobre essas codificações e campos de formulário, vá para a [MDN web docs para `POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST).
+
+///
+
+/// warning | Atenção
+
+Você pode declarar múltiplos parâmetros `File` e `Form` em uma *operação de rota*, mas você não pode declarar campos `Body` que você espera receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`.
+
+Isso não é uma limitação do **FastAPI**, é parte do protocolo HTTP.
+
+///
+
+## Upload de Arquivo Opcional { #optional-file-upload }
+
+Você pode tornar um arquivo opcional usando anotações de tipo padrão e definindo um valor padrão de `None`:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## `UploadFile` com Metadados Adicionais { #uploadfile-with-additional-metadata }
+
+Você também pode usar `File()` com `UploadFile`, por exemplo, para definir metadados adicionais:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
+
+## Uploads de Múltiplos Arquivos { #multiple-file-uploads }
+
+É possível realizar o upload de vários arquivos ao mesmo tempo.
+
+Eles serão associados ao mesmo "campo de formulário" enviado usando "dados de formulário".
+
+Para usar isso, declare uma lista de `bytes` ou `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
+
+Você receberá, tal como declarado, uma `list` de `bytes` ou `UploadFile`.
+
+/// note | Detalhes Técnicos
+
+Você também pode usar `from starlette.responses import HTMLResponse`.
+
+**FastAPI** providencia o mesmo `starlette.responses` que `fastapi.responses` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vem diretamente do Starlette.
+
+///
+
+### Uploads de Múltiplos Arquivos com Metadados Adicionais { #multiple-file-uploads-with-additional-metadata }
+
+Da mesma forma de antes, você pode usar `File()` para definir parâmetros adicionais, mesmo para `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
+
+## Recapitulando { #recap }
+
+Utilize `File`, `bytes` e `UploadFile` para declarar arquivos a serem enviados na requisição, enviados como dados de formulário.
diff --git a/docs/pt/docs/tutorial/request-form-models.md b/docs/pt/docs/tutorial/request-form-models.md
new file mode 100644
index 0000000000000..953c3fdcee210
--- /dev/null
+++ b/docs/pt/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Modelos de Formulários { #form-models }
+
+Você pode utilizar **Modelos Pydantic** para declarar **campos de formulários** no FastAPI.
+
+/// info | Informação
+
+Para utilizar formulários, instale primeiramente o [`python-multipart`](https://github.com/Kludex/python-multipart).
+
+Certifique-se de criar um [ambiente virtual](../virtual-environments.md), ativá-lo, e então instalar. Por exemplo:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | Nota
+
+Isto é suportado desde a versão `0.113.0` do FastAPI. 🤓
+
+///
+
+## Modelos Pydantic para Formulários { #pydantic-models-for-forms }
+
+Você precisa apenas declarar um **modelo Pydantic** com os campos que deseja receber como **campos de formulários**, e então declarar o parâmetro como um `Form`:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
+
+O **FastAPI** irá **extrair** as informações para **cada campo** dos **dados do formulário** na requisição e dar para você o modelo Pydantic que você definiu.
+
+## Confira os Documentos { #check-the-docs }
+
+Você pode verificar na UI de documentação em `/docs`:
+
+
+POST.
+Você pode declarar vários parâmetros `Form` em uma *operação de rota*, mas não pode declarar campos `Body` que espera receber como JSON, pois a requisição terá o corpo codificado usando `application/x-www-form-urlencoded` em vez de `application/json`.
-!!! warning "Aviso"
- Você pode declarar vários parâmetros `Form` em uma *operação de caminho*, mas não pode declarar campos `Body` que espera receber como JSON, pois a solicitação terá o corpo codificado usando `application/x-www- form-urlencoded` em vez de `application/json`.
+Isso não é uma limitação do **FastAPI**, é parte do protocolo HTTP.
- Esta não é uma limitação do **FastAPI**, é parte do protocolo HTTP.
+///
-## Recapitulando
+## Recapitulando { #recap }
Use `Form` para declarar os parâmetros de entrada de dados de formulário.
diff --git a/docs/pt/docs/tutorial/response-model.md b/docs/pt/docs/tutorial/response-model.md
new file mode 100644
index 0000000000000..7a28bcecdd878
--- /dev/null
+++ b/docs/pt/docs/tutorial/response-model.md
@@ -0,0 +1,344 @@
+# Modelo de resposta - Tipo de retorno { #response-model-return-type }
+
+Você pode declarar o tipo usado para a resposta anotando o **tipo de retorno** da *função de operação de rota*.
+
+Você pode usar **anotações de tipo** da mesma forma que usaria para dados de entrada em **parâmetros** de função, você pode usar modelos Pydantic, listas, dicionários, valores escalares como inteiros, booleanos, etc.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+O FastAPI usará este tipo de retorno para:
+
+* **Validar** os dados retornados.
+ * Se os dados forem inválidos (por exemplo, se estiver faltando um campo), significa que o código do *seu* aplicativo está quebrado, não retornando o que deveria, e retornará um erro de servidor em vez de retornar dados incorretos. Dessa forma, você e seus clientes podem ter certeza de que receberão os dados e o formato de dados esperados.
+* Adicionar um **JSON Schema** para a resposta, na *operação de rota* do OpenAPI.
+ * Isso será usado pela **documentação automática**.
+ * Também será usado por ferramentas de geração automática de código do cliente.
+* **Serializar** os dados retornados para JSON usando Pydantic, que é escrito em **Rust**, então será **muito mais rápido**.
+
+Mas o mais importante:
+
+* Ele **limitará e filtrará** os dados de saída para o que está definido no tipo de retorno.
+ * Isso é particularmente importante para a **segurança**, veremos mais sobre isso abaixo.
+
+## Parâmetro `response_model` { #response-model-parameter }
+
+Existem alguns casos em que você precisa ou deseja retornar alguns dados que não são exatamente o que o tipo declara.
+
+Por exemplo, você pode querer **retornar um dicionário** ou um objeto de banco de dados, mas **declará-lo como um modelo Pydantic**. Dessa forma, o modelo Pydantic faria toda a documentação de dados, validação, etc. para o objeto que você retornou (por exemplo, um dicionário ou objeto de banco de dados).
+
+Se você adicionasse a anotação do tipo de retorno, ferramentas e editores reclamariam com um erro (correto) informando que sua função está retornando um tipo (por exemplo, um dict) diferente do que você declarou (por exemplo, um modelo Pydantic).
+
+Nesses casos, você pode usar o parâmetro `response_model` do *decorador de operação de rota* em vez do tipo de retorno.
+
+Você pode usar o parâmetro `response_model` em qualquer uma das *operações de rota*:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* etc.
+
+{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *}
+
+/// note | Nota
+
+Observe que `response_model` é um parâmetro do método "decorator" (`get`, `post`, etc). Não da sua *função de operação de rota*, como todos os parâmetros e corpo.
+
+///
+
+`response_model` recebe o mesmo tipo que você declararia para um campo de modelo Pydantic, então, pode ser um modelo Pydantic, mas também pode ser, por exemplo, uma `list` de modelos Pydantic, como `List[Item]`.
+
+O FastAPI usará este `response_model` para fazer toda a documentação de dados, validação, etc. e também para **converter e filtrar os dados de saída** para sua declaração de tipo.
+
+/// tip | Dica
+
+Se você tiver verificações de tipo rigorosas em seu editor, mypy, etc, você pode declarar o tipo de retorno da função como `Any`.
+
+Dessa forma, você diz ao editor que está retornando qualquer coisa intencionalmente. Mas o FastAPI ainda fará a documentação de dados, validação, filtragem, etc. com o `response_model`.
+
+///
+
+### Prioridade `response_model` { #response-model-priority }
+
+Se você declarar tanto um tipo de retorno quanto um `response_model`, o `response_model` terá prioridade e será usado pelo FastAPI.
+
+Dessa forma, você pode adicionar anotações de tipo corretas às suas funções, mesmo quando estiver retornando um tipo diferente do modelo de resposta, para ser usado pelo editor e ferramentas como mypy. E ainda assim você pode fazer com que o FastAPI faça a validação de dados, documentação, etc. usando o `response_model`.
+
+Você também pode usar `response_model=None` para desabilitar a criação de um modelo de resposta para essa *operação de rota*, você pode precisar fazer isso se estiver adicionando anotações de tipo para coisas que não são campos Pydantic válidos, você verá um exemplo disso em uma das seções abaixo.
+
+## Retorne os mesmos dados de entrada { #return-the-same-input-data }
+
+Aqui estamos declarando um modelo `UserIn`, ele conterá uma senha em texto simples:
+
+{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *}
+
+/// info | Informação
+
+Para usar `EmailStr`, primeiro instale [`email-validator`](https://github.com/JoshData/python-email-validator).
+
+Certifique-se de criar um [ambiente virtual](../virtual-environments.md), ative-o e então instale-o, por exemplo:
+
+```console
+$ pip install email-validator
+```
+
+ou com:
+
+```console
+$ pip install "pydantic[email]"
+```
+
+///
+
+E estamos usando este modelo para declarar nossa entrada e o mesmo modelo para declarar nossa saída:
+
+{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *}
+
+Agora, sempre que um navegador estiver criando um usuário com uma senha, a API retornará a mesma senha na resposta.
+
+Neste caso, pode não ser um problema, porque é o mesmo usuário enviando a senha.
+
+Mas se usarmos o mesmo modelo para outra *operação de rota*, poderíamos estar enviando as senhas dos nossos usuários para todos os clientes.
+
+/// danger | Cuidado
+
+Nunca armazene a senha simples de um usuário ou envie-a em uma resposta como esta, a menos que você saiba todas as ressalvas e saiba o que está fazendo.
+
+///
+
+## Adicione um modelo de saída { #add-an-output-model }
+
+Podemos, em vez disso, criar um modelo de entrada com a senha em texto simples e um modelo de saída sem ela:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *}
+
+Aqui, embora nossa *função de operação de rota* esteja retornando o mesmo usuário de entrada que contém a senha:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *}
+
+...declaramos o `response_model` como nosso modelo `UserOut`, que não inclui a senha:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *}
+
+Então, **FastAPI** cuidará de filtrar todos os dados que não são declarados no modelo de saída (usando Pydantic).
+
+### `response_model` ou Tipo de Retorno { #response-model-or-return-type }
+
+Neste caso, como os dois modelos são diferentes, se anotássemos o tipo de retorno da função como `UserOut`, o editor e as ferramentas reclamariam que estamos retornando um tipo inválido, pois são classes diferentes.
+
+É por isso que neste exemplo temos que declará-lo no parâmetro `response_model`.
+
+...mas continue lendo abaixo para ver como superar isso.
+
+## Tipo de Retorno e Filtragem de Dados { #return-type-and-data-filtering }
+
+Vamos continuar do exemplo anterior. Queríamos **anotar a função com um tipo**, mas queríamos poder retornar da função algo que realmente incluísse **mais dados**.
+
+Queremos que o FastAPI continue **filtrando** os dados usando o modelo de resposta. Para que, embora a função retorne mais dados, a resposta inclua apenas os campos declarados no modelo de resposta.
+
+No exemplo anterior, como as classes eram diferentes, tivemos que usar o parâmetro `response_model`. Mas isso também significa que não temos suporte do editor e das ferramentas verificando o tipo de retorno da função.
+
+Mas na maioria dos casos em que precisamos fazer algo assim, queremos que o modelo apenas **filtre/remova** alguns dados como neste exemplo.
+
+E nesses casos, podemos usar classes e herança para aproveitar as **anotações de tipo** de função para obter melhor suporte no editor e nas ferramentas, e ainda obter a **filtragem de dados** FastAPI.
+
+{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *}
+
+Com isso, temos suporte de ferramentas, de editores e mypy, pois este código está correto em termos de tipos, mas também obtemos a filtragem de dados do FastAPI.
+
+Como isso funciona? Vamos verificar. 🤓
+
+### Anotações de tipo e ferramentas { #type-annotations-and-tooling }
+
+Primeiro, vamos ver como editores, mypy e outras ferramentas veriam isso.
+
+`BaseUser` tem os campos base. Então `UserIn` herda de `BaseUser` e adiciona o campo `password`, então, ele incluirá todos os campos de ambos os modelos.
+
+Anotamos o tipo de retorno da função como `BaseUser`, mas na verdade estamos retornando uma instância `UserIn`.
+
+O editor, mypy e outras ferramentas não reclamarão disso porque, em termos de digitação, `UserIn` é uma subclasse de `BaseUser`, o que significa que é um tipo *válido* quando o que é esperado é qualquer coisa que seja um `BaseUser`.
+
+### Filtragem de dados FastAPI { #fastapi-data-filtering }
+
+Agora, para FastAPI, ele verá o tipo de retorno e garantirá que o que você retornar inclua **apenas** os campos que são declarados no tipo.
+
+O FastAPI faz várias coisas internamente com o Pydantic para garantir que essas mesmas regras de herança de classe não sejam usadas para a filtragem de dados retornados, caso contrário, você pode acabar retornando muito mais dados do que o esperado.
+
+Dessa forma, você pode obter o melhor dos dois mundos: anotações de tipo com **suporte a ferramentas** e **filtragem de dados**.
+
+## Veja na documentação { #see-it-in-the-docs }
+
+Quando você vê a documentação automática, pode verificar se o modelo de entrada e o modelo de saída terão seus próprios esquemas JSON:
+
+
+
+E ambos os modelos serão usados para a documentação interativa da API:
+
+
+
+## Outras anotações de tipo de retorno { #other-return-type-annotations }
+
+Pode haver casos em que você retorna algo que não é um campo Pydantic válido e anota na função, apenas para obter o suporte fornecido pelas ferramentas (o editor, mypy, etc).
+
+### Retorne uma Response diretamente { #return-a-response-directly }
+
+O caso mais comum seria [retornar uma Response diretamente, conforme explicado posteriormente na documentação avançada](../advanced/response-directly.md).
+
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
+
+Este caso simples é tratado automaticamente pelo FastAPI porque a anotação do tipo de retorno é a classe (ou uma subclasse de) `Response`.
+
+E as ferramentas também ficarão felizes porque `RedirectResponse` e `JSONResponse` são subclasses de `Response`, então a anotação de tipo está correta.
+
+### Anote uma subclasse de Response { #annotate-a-response-subclass }
+
+Você também pode usar uma subclasse de `Response` na anotação de tipo:
+
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
+
+Isso também funcionará porque `RedirectResponse` é uma subclasse de `Response`, e o FastAPI tratará automaticamente este caso simples.
+
+### Anotações de Tipo de Retorno Inválido { #invalid-return-type-annotations }
+
+Mas quando você retorna algum outro objeto arbitrário que não é um tipo Pydantic válido (por exemplo, um objeto de banco de dados) e você o anota dessa forma na função, o FastAPI tentará criar um modelo de resposta Pydantic a partir dessa anotação de tipo e falhará.
+
+O mesmo aconteceria se você tivesse algo como uma união entre tipos diferentes onde um ou mais deles não são tipos Pydantic válidos, por exemplo, isso falharia 💥:
+
+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
+
+...isso falha porque a anotação de tipo não é um tipo Pydantic e não é apenas uma única classe ou subclasse `Response`, é uma união (qualquer uma das duas) entre um `Response` e um `dict`.
+
+### Desative o modelo de resposta { #disable-response-model }
+
+Continuando com o exemplo acima, você pode não querer ter a validação de dados padrão, documentação, filtragem, etc. que é realizada pelo FastAPI.
+
+Mas você pode querer manter a anotação do tipo de retorno na função para obter o suporte de ferramentas como editores e verificadores de tipo (por exemplo, mypy).
+
+Neste caso, você pode desabilitar a geração do modelo de resposta definindo `response_model=None`:
+
+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}
+
+Isso fará com que o FastAPI pule a geração do modelo de resposta e, dessa forma, você pode ter quaisquer anotações de tipo de retorno que precisar sem afetar seu aplicativo FastAPI. 🤓
+
+## Parâmetros de codificação do modelo de resposta { #response-model-encoding-parameters }
+
+Seu modelo de resposta pode ter valores padrão, como:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}
+
+* `description: Union[str, None] = None` (ou `str | None = None` no Python 3.10) tem um padrão de `None`.
+* `tax: float = 10.5` tem um padrão de `10.5`.
+* `tags: List[str] = []` tem um padrão de uma lista vazia: `[]`.
+
+mas você pode querer omiti-los do resultado se eles não foram realmente armazenados.
+
+Por exemplo, se você tem modelos com muitos atributos opcionais em um banco de dados NoSQL, mas não quer enviar respostas JSON muito longas cheias de valores padrão.
+
+### Use o parâmetro `response_model_exclude_unset` { #use-the-response-model-exclude-unset-parameter }
+
+Você pode definir o parâmetro `response_model_exclude_unset=True` do *decorador de operação de rota*:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}
+
+e esses valores padrão não serão incluídos na resposta, apenas os valores realmente definidos.
+
+Então, se você enviar uma solicitação para essa *operação de rota* para o item com ID `foo`, a resposta (sem incluir valores padrão) será:
+
+```JSON
+{
+ "name": "Foo",
+ "price": 50.2
+}
+```
+
+/// info | Informação
+
+Você também pode usar:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+conforme descrito na [documentação do Pydantic](https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict) para `exclude_defaults` e `exclude_none`.
+
+///
+
+#### Dados com valores para campos com padrões { #data-with-values-for-fields-with-defaults }
+
+Mas se seus dados tiverem valores para os campos do modelo com valores padrões, como o item com ID `bar`:
+
+```Python hl_lines="3 5"
+{
+ "name": "Bar",
+ "description": "The bartenders",
+ "price": 62,
+ "tax": 20.2
+}
+```
+
+eles serão incluídos na resposta.
+
+#### Dados com os mesmos valores que os padrões { #data-with-the-same-values-as-the-defaults }
+
+Se os dados tiverem os mesmos valores que os padrões, como o item com ID `baz`:
+
+```Python hl_lines="3 5-6"
+{
+ "name": "Baz",
+ "description": None,
+ "price": 50.2,
+ "tax": 10.5,
+ "tags": []
+}
+```
+
+O FastAPI é inteligente o suficiente (na verdade, o Pydantic é inteligente o suficiente) para perceber que, embora `description`, `tax` e `tags` tenham os mesmos valores que os padrões, eles foram definidos explícita e diretamente (em vez de retirados dos padrões).
+
+Portanto, eles serão incluídos na resposta JSON.
+
+/// tip | Dica
+
+Observe que os valores padrão podem ser qualquer coisa, não apenas `None`.
+
+Eles podem ser uma lista (`[]`), um `float` de `10.5`, etc.
+
+///
+
+### `response_model_include` e `response_model_exclude` { #response-model-include-and-response-model-exclude }
+
+Você também pode usar os parâmetros `response_model_include` e `response_model_exclude` do *decorador de operação de rota*.
+
+Eles pegam um `set` de `str` com o nome dos atributos para incluir (omitindo o resto) ou para excluir (incluindo o resto).
+
+Isso pode ser usado como um atalho rápido se você tiver apenas um modelo Pydantic e quiser remover alguns dados da saída.
+
+/// tip | Dica
+
+Mas ainda é recomendado usar as ideias acima, usando várias classes, em vez desses parâmetros.
+
+Isso ocorre porque o JSON Schema gerado no OpenAPI do seu aplicativo (e a documentação) ainda será o único para o modelo completo, mesmo que você use `response_model_include` ou `response_model_exclude` para omitir alguns atributos.
+
+Isso também se aplica ao `response_model_by_alias` que funciona de forma semelhante.
+
+///
+
+{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}
+
+/// tip | Dica
+
+A sintaxe `{"name", "description"}` cria um `set` com esses dois valores.
+
+É equivalente a `set(["name", "description"])`.
+
+///
+
+#### Usando `list`s em vez de `set`s { #using-lists-instead-of-sets }
+
+Se você esquecer de usar um `set` e usar uma `list` ou `tuple` em vez disso, o FastAPI ainda o converterá em um `set` e funcionará corretamente:
+
+{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}
+
+## Recapitulação { #recap }
+
+Use o parâmetro `response_model` do *decorador de operação de rota* para definir modelos de resposta e, especialmente, para garantir que dados privados sejam filtrados.
+
+Use `response_model_exclude_unset` para retornar apenas os valores definidos explicitamente.
diff --git a/docs/pt/docs/tutorial/response-status-code.md b/docs/pt/docs/tutorial/response-status-code.md
index 2df17d4ea11db..d5a81fa03bea9 100644
--- a/docs/pt/docs/tutorial/response-status-code.md
+++ b/docs/pt/docs/tutorial/response-status-code.md
@@ -1,6 +1,6 @@
-# Código de status de resposta
+# Código de status de resposta { #response-status-code }
-Da mesma forma que você pode especificar um modelo de resposta, você também pode declarar o código de status HTTP usado para a resposta com o parâmetro `status_code` em qualquer uma das *operações de caminho*:
+Da mesma forma que você pode especificar um modelo de resposta, você também pode declarar o código de status HTTP usado para a resposta com o parâmetro `status_code` em qualquer uma das *operações de rota*:
* `@app.get()`
* `@app.post()`
@@ -8,17 +8,21 @@ Da mesma forma que você pode especificar um modelo de resposta, você também p
* `@app.delete()`
* etc.
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
-!!! note "Nota"
- Observe que `status_code` é um parâmetro do método "decorador" (get, post, etc). Não da sua função de *operação de caminho*, como todos os parâmetros e corpo.
+/// note | Nota
+
+Observe que `status_code` é um parâmetro do método "decorador" (`get`, `post`, etc). Não da sua função de *operação de rota*, como todos os parâmetros e corpo.
+
+///
O parâmetro `status_code` recebe um número com o código de status HTTP.
-!!! info "Informação"
- `status_code` também pode receber um `IntEnum`, como o do Python `http.HTTPStatus`.
+/// info | Informação
+
+`status_code` também pode receber um `IntEnum`, como [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus) do Python.
+
+///
Dessa forma:
@@ -27,15 +31,21 @@ Dessa forma:
-!!! note "Nota"
- Alguns códigos de resposta (consulte a próxima seção) indicam que a resposta não possui um corpo.
+/// note | Nota
+
+Alguns códigos de resposta (consulte a próxima seção) indicam que a resposta não possui um corpo.
+
+O FastAPI sabe disso e produzirá documentos OpenAPI informando que não há corpo de resposta.
- O FastAPI sabe disso e produzirá documentos OpenAPI informando que não há corpo de resposta.
+///
-## Sobre os códigos de status HTTP
+## Sobre os códigos de status HTTP { #about-http-status-codes }
-!!! note "Nota"
- Se você já sabe o que são códigos de status HTTP, pule para a próxima seção.
+/// note | Nota
+
+Se você já sabe o que são códigos de status HTTP, pule para a próxima seção.
+
+///
Em HTTP, você envia um código de status numérico de 3 dígitos como parte da resposta.
@@ -43,28 +53,28 @@ Esses códigos de status têm um nome associado para reconhecê-los, mas o impor
Resumidamente:
-
-* `100` e acima são para "Informações". Você raramente os usa diretamente. As respostas com esses códigos de status não podem ter um corpo.
-* **`200`** e acima são para respostas "Bem-sucedidas". Estes são os que você mais usaria.
+* `100 - 199` são para "Informações". Você raramente os usa diretamente. As respostas com esses códigos de status não podem ter um corpo.
+* **`200 - 299`** são para respostas "Bem-sucedidas". Estes são os que você mais usaria.
* `200` é o código de status padrão, o que significa que tudo estava "OK".
* Outro exemplo seria `201`, "Criado". É comumente usado após a criação de um novo registro no banco de dados.
* Um caso especial é `204`, "Sem Conteúdo". Essa resposta é usada quando não há conteúdo para retornar ao cliente e, portanto, a resposta não deve ter um corpo.
-* **`300`** e acima são para "Redirecionamento". As respostas com esses códigos de status podem ou não ter um corpo, exceto `304`, "Não modificado", que não deve ter um.
-* **`400`** e acima são para respostas de "Erro do cliente". Este é o segundo tipo que você provavelmente mais usaria.
+* **`300 - 399`** são para "Redirecionamento". As respostas com esses códigos de status podem ou não ter um corpo, exceto `304`, "Não modificado", que não deve ter um.
+* **`400 - 499`** são para respostas de "Erro do cliente". Este é o segundo tipo que você provavelmente mais usaria.
* Um exemplo é `404`, para uma resposta "Não encontrado".
* Para erros genéricos do cliente, você pode usar apenas `400`.
-* `500` e acima são para erros do servidor. Você quase nunca os usa diretamente. Quando algo der errado em alguma parte do código do seu aplicativo ou servidor, ele retornará automaticamente um desses códigos de status.
+* `500 - 599` são para erros do servidor. Você quase nunca os usa diretamente. Quando algo der errado em alguma parte do código do seu aplicativo ou servidor, ele retornará automaticamente um desses códigos de status.
-!!! tip "Dica"
- Para saber mais sobre cada código de status e qual código serve para quê, verifique o MDN documentação sobre códigos de status HTTP.
+/// tip | Dica
-## Atalho para lembrar os nomes
+Para saber mais sobre cada código de status e qual código serve para quê, verifique a [documentação do MDN sobre códigos de status HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status).
+
+///
+
+## Atalho para lembrar os nomes { #shortcut-to-remember-the-names }
Vamos ver o exemplo anterior novamente:
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
`201` é o código de status para "Criado".
@@ -72,20 +82,20 @@ Mas você não precisa memorizar o que cada um desses códigos significa.
Você pode usar as variáveis de conveniência de `fastapi.status`.
-```Python hl_lines="1 6"
-{!../../../docs_src/response_status_code/tutorial002.py!}
-```
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
-Eles são apenas uma conveniência, eles possuem o mesmo número, mas dessa forma você pode usar o autocomplete do editor para encontrá-los:
+Eles são apenas uma conveniência, eles possuem o mesmo número, mas dessa forma você pode usar o preenchimento automático do editor para encontrá-los:
-!!! note "Detalhes técnicos"
- Você também pode usar `from starlette import status`.
+/// note | Detalhes Técnicos
+
+Você também pode usar `from starlette import status`.
- **FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette.
+**FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette.
+///
-## Alterando o padrão
+## Alterando o padrão { #changing-the-default }
-Mais tarde, no [Guia do usuário avançado](../advanced/response-change-status-code.md){.internal-link target=_blank}, você verá como retornar um código de status diferente do padrão que você está declarando aqui.
+Mais tarde, no [Guia do Usuário Avançado](../advanced/response-change-status-code.md), você verá como retornar um código de status diferente do padrão que você está declarando aqui.
diff --git a/docs/pt/docs/tutorial/schema-extra-example.md b/docs/pt/docs/tutorial/schema-extra-example.md
new file mode 100644
index 0000000000000..cd2ac13c5f75e
--- /dev/null
+++ b/docs/pt/docs/tutorial/schema-extra-example.md
@@ -0,0 +1,202 @@
+# Declare dados de exemplo da requisição { #declare-request-example-data }
+
+Você pode declarar exemplos dos dados que sua aplicação pode receber.
+
+Aqui estão várias maneiras de fazer isso.
+
+## Dados extras de JSON Schema em modelos Pydantic { #extra-json-schema-data-in-pydantic-models }
+
+Você pode declarar `examples` para um modelo Pydantic que serão adicionados ao JSON Schema gerado.
+
+{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}
+
+Essas informações extras serão adicionadas como estão ao **JSON Schema** de saída para esse modelo e serão usadas na documentação da API.
+
+Você pode usar o atributo `model_config`, que recebe um `dict`, conforme descrito na [documentação do Pydantic: Configuration](https://docs.pydantic.dev/latest/api/config/).
+
+Você pode definir `"json_schema_extra"` com um `dict` contendo quaisquer dados adicionais que você queira que apareçam no JSON Schema gerado, incluindo `examples`.
+
+/// tip | Dica
+
+Você poderia usar a mesma técnica para estender o JSON Schema e adicionar suas próprias informações extras personalizadas.
+
+Por exemplo, você poderia usá-la para adicionar metadados para uma interface de usuário de front-end, etc.
+
+///
+
+/// info | Informação
+
+O OpenAPI 3.1.0 (usado desde o FastAPI 0.99.0) adicionou suporte a `examples`, que faz parte do padrão **JSON Schema**.
+
+Antes disso, ele suportava apenas a palavra‑chave `example` com um único exemplo. Isso ainda é suportado pelo OpenAPI 3.1.0, mas é descontinuado e não faz parte do padrão JSON Schema. Portanto, você é incentivado a migrar de `example` para `examples`. 🤓
+
+Você pode ler mais no final desta página.
+
+///
+
+## Argumentos adicionais de `Field` { #field-additional-arguments }
+
+Ao usar `Field()` com modelos Pydantic, você também pode declarar `examples` adicionais:
+
+{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}
+
+## `examples` no JSON Schema - OpenAPI { #examples-in-json-schema-openapi }
+
+Ao usar qualquer um de:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+você também pode declarar um grupo de `examples` com informações adicionais que serão adicionadas aos seus **JSON Schemas** dentro do **OpenAPI**.
+
+### `Body` com `examples` { #body-with-examples }
+
+Aqui passamos `examples` contendo um exemplo dos dados esperados em `Body()`:
+
+{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *}
+
+### Exemplo na UI da documentação { #example-in-the-docs-ui }
+
+Com qualquer um dos métodos acima, ficaria assim em `/docs`:
+
+
+
+### `Body` com vários `examples` { #body-with-multiple-examples }
+
+Você também pode, é claro, passar vários `examples`:
+
+{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *}
+
+Quando fizer isso, os exemplos farão parte do **JSON Schema** interno para esses dados do body.
+
+No entanto, no momento em que isto foi escrito, o Swagger UI, a ferramenta responsável por exibir a UI da documentação, não suporta mostrar vários exemplos para os dados no **JSON Schema**. Mas leia abaixo para uma solução alternativa.
+
+### `examples` específicos do OpenAPI { #openapi-specific-examples }
+
+Antes do **JSON Schema** suportar `examples`, o OpenAPI já tinha suporte para um campo diferente também chamado `examples`.
+
+Esse `examples` **específico do OpenAPI** vai em outra seção da especificação OpenAPI. Ele fica nos **detalhes de cada *operação de rota***, não dentro de cada JSON Schema.
+
+E o Swagger UI tem suportado esse campo `examples` particular há algum tempo. Então, você pode usá-lo para **mostrar** diferentes **exemplos na UI da documentação**.
+
+O formato desse campo `examples` específico do OpenAPI é um `dict` com **vários exemplos** (em vez de uma `list`), cada um com informações extras que também serão adicionadas ao **OpenAPI**.
+
+Isso não vai dentro de cada JSON Schema contido no OpenAPI, vai fora, diretamente na *operação de rota*.
+
+### Usando o parâmetro `openapi_examples` { #using-the-openapi-examples-parameter }
+
+Você pode declarar o `examples` específico do OpenAPI no FastAPI com o parâmetro `openapi_examples` para:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+As chaves do `dict` identificam cada exemplo, e cada valor é outro `dict`.
+
+Cada `dict` de exemplo específico em `examples` pode conter:
+
+* `summary`: Descrição curta do exemplo.
+* `description`: Uma descrição longa que pode conter texto em Markdown.
+* `value`: Este é o exemplo em si, por exemplo, um `dict`.
+* `externalValue`: Alternativa a `value`, uma URL apontando para o exemplo. Embora isso possa não ser suportado por tantas ferramentas quanto `value`.
+
+Você pode usá-lo assim:
+
+{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *}
+
+### Exemplos do OpenAPI na UI da documentação { #openapi-examples-in-the-docs-ui }
+
+Com `openapi_examples` adicionado a `Body()`, o `/docs` ficaria assim:
+
+
+
+## Detalhes Técnicos { #technical-details }
+
+/// tip | Dica
+
+Se você já está usando o **FastAPI** na versão **0.99.0 ou superior**, você provavelmente pode **pular** esses detalhes.
+
+Eles são mais relevantes para versões antigas, antes de o OpenAPI 3.1.0 estar disponível.
+
+Você pode considerar isto uma breve **aula de história** sobre OpenAPI e JSON Schema. 🤓
+
+///
+
+/// warning | Atenção
+
+Estes são detalhes muito técnicos sobre os padrões **JSON Schema** e **OpenAPI**.
+
+Se as ideias acima já funcionam para você, isso pode ser suficiente, e você provavelmente não precisa desses detalhes, sinta-se à vontade para pular.
+
+///
+
+Antes do OpenAPI 3.1.0, o OpenAPI usava uma versão mais antiga e modificada do **JSON Schema**.
+
+O JSON Schema não tinha `examples`, então o OpenAPI adicionou seu próprio campo `example` à sua versão modificada.
+
+O OpenAPI também adicionou os campos `example` e `examples` a outras partes da especificação:
+
+* [`Parameter Object` (na especificação)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object), usado no FastAPI por:
+ * `Path()`
+ * `Query()`
+ * `Header()`
+ * `Cookie()`
+* [`Request Body Object`, no campo `content`, no `Media Type Object` (na especificação)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object), usado no FastAPI por:
+ * `Body()`
+ * `File()`
+ * `Form()`
+
+/// info | Informação
+
+Esse parâmetro antigo `examples` específico do OpenAPI agora é `openapi_examples` desde o FastAPI `0.103.0`.
+
+///
+
+### Campo `examples` do JSON Schema { #json-schemas-examples-field }
+
+Depois, o JSON Schema adicionou um campo [`examples`](https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.9.5) em uma nova versão da especificação.
+
+E então o novo OpenAPI 3.1.0 passou a se basear na versão mais recente (JSON Schema 2020-12), que incluiu esse novo campo `examples`.
+
+E agora esse novo campo `examples` tem precedência sobre o antigo campo único (e customizado) `example`, que agora está descontinuado.
+
+Esse novo campo `examples` no JSON Schema é **apenas uma `list`** de exemplos, não um dict com metadados extras como nos outros lugares do OpenAPI (descritos acima).
+
+/// info | Informação
+
+Mesmo após o lançamento do OpenAPI 3.1.0 com essa nova integração mais simples com o JSON Schema, por um tempo o Swagger UI, a ferramenta que fornece a documentação automática, não suportava OpenAPI 3.1.0 (passou a suportar desde a versão 5.0.0 🎉).
+
+Por causa disso, versões do FastAPI anteriores à 0.99.0 ainda usavam versões do OpenAPI inferiores à 3.1.0.
+
+///
+
+### `examples` no Pydantic e no FastAPI { #pydantic-and-fastapi-examples }
+
+Quando você adiciona `examples` dentro de um modelo Pydantic, usando `schema_extra` ou `Field(examples=["something"])`, esse exemplo é adicionado ao **JSON Schema** para esse modelo Pydantic.
+
+E esse **JSON Schema** do modelo Pydantic é incluído no **OpenAPI** da sua API e, então, é usado na UI da documentação.
+
+Em versões do FastAPI anteriores à 0.99.0 (0.99.0 e superiores usam o novo OpenAPI 3.1.0), quando você usava `example` ou `examples` com qualquer uma das outras utilidades (`Query()`, `Body()`, etc.), esses exemplos não eram adicionados ao JSON Schema que descreve esses dados (nem mesmo à versão própria do JSON Schema do OpenAPI), eles eram adicionados diretamente à declaração da *operação de rota* no OpenAPI (fora das partes do OpenAPI que usam o JSON Schema).
+
+Mas agora que o FastAPI 0.99.0 e superiores usam o OpenAPI 3.1.0, que usa o JSON Schema 2020-12, e o Swagger UI 5.0.0 e superiores, tudo é mais consistente e os exemplos são incluídos no JSON Schema.
+
+### Swagger UI e `examples` específicos do OpenAPI { #swagger-ui-and-openapi-specific-examples }
+
+Agora, como o Swagger UI não suportava vários exemplos no JSON Schema (em 2023-08-26), os usuários não tinham uma forma de mostrar vários exemplos na documentação.
+
+Para resolver isso, o FastAPI `0.103.0` **adicionou suporte** para declarar o mesmo antigo campo **específico do OpenAPI** `examples` com o novo parâmetro `openapi_examples`. 🤓
+
+### Resumo { #summary }
+
+Eu costumava dizer que não gostava tanto de história... e olha eu aqui agora dando aulas de "história tech". 😅
+
+Em resumo, **atualize para o FastAPI 0.99.0 ou superior**, e as coisas ficam muito mais **simples, consistentes e intuitivas**, e você não precisa saber todos esses detalhes históricos. 😎
diff --git a/docs/pt/docs/tutorial/security/first-steps.md b/docs/pt/docs/tutorial/security/first-steps.md
index ed07d1c963102..d16c15140e5c6 100644
--- a/docs/pt/docs/tutorial/security/first-steps.md
+++ b/docs/pt/docs/tutorial/security/first-steps.md
@@ -1,181 +1,203 @@
-# Segurança - Primeiros Passos
+# Segurança - Primeiros Passos { #security-first-steps }
-Vamos imaginar que você tem a sua API **backend** em algum domínio.
+Vamos imaginar que você tem a sua API de **backend** em algum domínio.
E você tem um **frontend** em outro domínio ou em um path diferente no mesmo domínio (ou em uma aplicação mobile).
-E você quer uma maneira de o frontend autenticar o backend, usando um **username** e **senha**.
+E você quer uma maneira de o frontend autenticar com o backend, usando um **username** e **password**.
-Nós podemos usar o **OAuth2** junto com o **FastAPI**.
+Podemos usar **OAuth2** para construir isso com o **FastAPI**.
-Mas, vamos poupar-lhe o tempo de ler toda a especificação apenas para achar as pequenas informações que você precisa.
+Mas vamos poupar o seu tempo de ler toda a especificação extensa apenas para achar as pequenas informações de que você precisa.
-Vamos usar as ferramentas fornecidas pela **FastAPI** para lidar com segurança.
+Vamos usar as ferramentas fornecidas pelo **FastAPI** para lidar com segurança.
-## Como Parece
+## Como Parece { #how-it-looks }
Vamos primeiro usar o código e ver como funciona, e depois voltaremos para entender o que está acontecendo.
-## Crie um `main.py`
+## Crie um `main.py` { #create-main-py }
+
Copie o exemplo em um arquivo `main.py`:
-```Python
-{!../../../docs_src/security/tutorial001.py!}
-```
+{* ../../docs_src/security/tutorial001_an_py310.py *}
+
+## Execute-o { #run-it }
+
+/// info | Informação
+
+O pacote [`python-multipart`](https://github.com/Kludex/python-multipart) é instalado automaticamente com o **FastAPI** quando você executa o comando `pip install "fastapi[standard]"`.
-## Execute-o
+Entretanto, se você usar o comando `pip install fastapi`, o pacote `python-multipart` não é incluído por padrão.
-!!! informação
- Primeiro, instale `python-multipart`.
+Para instalá-lo manualmente, certifique-se de criar um [ambiente virtual](../../virtual-environments.md), ativá-lo e então instalá-lo com:
- Ex: `pip install python-multipart`.
+```console
+$ pip install python-multipart
+```
+
+Isso ocorre porque o **OAuth2** usa "form data" para enviar o `username` e o `password`.
- Isso ocorre porque o **OAuth2** usa "dados de um formulário" para mandar o **username** e **senha**.
+///
-Execute esse exemplo com:
+Execute o exemplo com:
-!!! marque o "botão de Autorizar!"
- Você já tem um novo "botão de autorizar!".
+/// check | Botão Autorizar!
- E seu *path operation* tem um pequeno cadeado no canto superior direito que você pode clicar.
+Você já tem um novo botão 'Authorize'.
-E se você clicar, você terá um pequeno formulário de autorização para digitar o `username` e `senha` (e outros campos opcionais):
+E sua operação de rota tem um pequeno cadeado no canto superior direito em que você pode clicar.
+
+///
+
+E se você clicar, verá um pequeno formulário de autorização para digitar um `username` e um `password` (e outros campos opcionais):
-!!! nota
- Não importa o que você digita no formulário, não vai funcionar ainda. Mas nós vamos chegar lá.
+/// note | Nota
+
+Não importa o que você digite no formulário, ainda não vai funcionar. Mas nós vamos chegar lá.
-Claro que este não é o frontend para os usuários finais, mas é uma ótima ferramenta automática para documentar interativamente toda sua API.
+///
-Pode ser usado pelo time de frontend (que pode ser você no caso).
+Claro que este não é o frontend para os usuários finais, mas é uma ótima ferramenta automática para documentar interativamente toda a sua API.
-Pode ser usado por aplicações e sistemas third party (de terceiros).
+Pode ser usada pelo time de frontend (que pode ser você mesmo).
-E também pode ser usada por você mesmo, para debugar, checar e testar a mesma aplicação.
+Pode ser usada por aplicações e sistemas de terceiros.
-## O Fluxo da `senha`
+E também pode ser usada por você mesmo, para depurar, verificar e testar a mesma aplicação.
+
+## O fluxo de `password` { #the-password-flow }
Agora vamos voltar um pouco e entender o que é isso tudo.
-O "fluxo" da `senha` é um dos caminhos ("fluxos") definidos no OAuth2, para lidar com a segurança e autenticação.
+O "fluxo" `password` é uma das formas ("fluxos") definidas no OAuth2 para lidar com segurança e autenticação.
-OAuth2 foi projetado para que o backend ou a API pudesse ser independente do servidor que autentica o usuário.
+O OAuth2 foi projetado para que o backend ou a API pudesse ser independente do servidor que autentica o usuário.
-Mas nesse caso, a mesma aplicação **FastAPI** irá lidar com a API e a autenticação.
+Mas, neste caso, a mesma aplicação **FastAPI** irá lidar com a API e com a autenticação.
Então, vamos rever de um ponto de vista simplificado:
-* O usuário digita o `username` e a `senha` no frontend e aperta `Enter`.
-* O frontend (rodando no browser do usuário) manda o `username` e a `senha` para uma URL específica na sua API (declarada com `tokenUrl="token"`).
-* A API checa aquele `username` e `senha`, e responde com um "token" (nós não implementamos nada disso ainda).
- * Um "token" é apenas uma string com algum conteúdo que nós podemos utilizar mais tarde para verificar o usuário.
- * Normalmente, um token é definido para expirar depois de um tempo.
- * Então, o usuário terá que se logar de novo depois de um tempo.
- * E se o token for roubado, o risco é menor. Não é como se fosse uma chave permanente que vai funcionar para sempre (na maioria dos casos).
- * O frontend armazena aquele token temporariamente em algum lugar.
- * O usuário clica no frontend para ir à outra seção daquele frontend do aplicativo web.
- * O frontend precisa buscar mais dados daquela API.
- * Mas precisa de autenticação para aquele endpoint em específico.
- * Então, para autenticar com nossa API, ele manda um header de `Autorização` com o valor `Bearer` mais o token.
- * Se o token contém `foobar`, o conteúdo do header de `Autorização` será: `Bearer foobar`.
+* O usuário digita o `username` e o `password` no frontend e pressiona `Enter`.
+* O frontend (rodando no navegador do usuário) envia esse `username` e `password` para uma URL específica na nossa API (declarada com `tokenUrl="token"`).
+* A API verifica esse `username` e `password`, e responde com um "token" (ainda não implementamos nada disso).
+ * Um "token" é apenas uma string com algum conteúdo que podemos usar depois para verificar esse usuário.
+ * Normalmente, um token é definido para expirar depois de algum tempo.
+ * Então, o usuário terá que fazer login novamente em algum momento.
+ * E se o token for roubado, o risco é menor. Não é como uma chave permanente que funcionará para sempre (na maioria dos casos).
+* O frontend armazena esse token temporariamente em algum lugar.
+* O usuário clica no frontend para ir para outra seção do aplicativo web.
+* O frontend precisa buscar mais dados da API.
+ * Mas precisa de autenticação para aquele endpoint específico.
+ * Então, para autenticar com nossa API, ele envia um header `Authorization` com o valor `Bearer ` mais o token.
+ * Se o token contém `foobar`, o conteúdo do header `Authorization` seria: `Bearer foobar`.
-## **FastAPI**'s `OAuth2PasswordBearer`
+## O `OAuth2PasswordBearer` do **FastAPI** { #fastapis-oauth2passwordbearer }
-**FastAPI** fornece várias ferramentas, em diferentes níveis de abstração, para implementar esses recursos de segurança.
+O **FastAPI** fornece várias ferramentas, em diferentes níveis de abstração, para implementar essas funcionalidades de segurança.
-Neste exemplo, nós vamos usar o **OAuth2** com o fluxo de **Senha**, usando um token **Bearer**. Fazemos isso usando a classe `OAuth2PasswordBearer`.
+Neste exemplo, vamos usar **OAuth2**, com o fluxo **Password**, usando um token **Bearer**. Fazemos isso usando a classe `OAuth2PasswordBearer`.
-!!! informação
- Um token "bearer" não é a única opção.
+/// info | Informação
- Mas é a melhor no nosso caso.
+Um token "bearer" não é a única opção.
- E talvez seja a melhor para a maioria dos casos, a não ser que você seja um especialista em OAuth2 e saiba exatamente o porquê de existir outras opções que se adequam melhor às suas necessidades.
+Mas é a melhor para o nosso caso de uso.
- Nesse caso, **FastAPI** também fornece as ferramentas para construir.
+E pode ser a melhor para a maioria dos casos de uso, a menos que você seja um especialista em OAuth2 e saiba exatamente por que existe outra opção que se adapta melhor às suas necessidades.
-Quando nós criamos uma instância da classe `OAuth2PasswordBearer`, nós passamos pelo parâmetro `tokenUrl` Esse parâmetro contém a URL que o client (o frontend rodando no browser do usuário) vai usar para mandar o `username` e `senha` para obter um token.
+Nesse caso, o **FastAPI** também fornece as ferramentas para construí-la.
-```Python hl_lines="6"
-{!../../../docs_src/security/tutorial001.py!}
-```
+///
+
+Quando criamos uma instância da classe `OAuth2PasswordBearer`, passamos o parâmetro `tokenUrl`. Esse parâmetro contém a URL que o client (o frontend rodando no navegador do usuário) usará para enviar o `username` e o `password` para obter um token.
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
+
+/// tip | Dica
+
+Aqui `tokenUrl="token"` refere-se a uma URL relativa `token` que ainda não criamos. Como é uma URL relativa, é equivalente a `./token`.
-!!! dica
- Esse `tokenUrl="token"` se refere a uma URL relativa que nós não criamos ainda. Como é uma URL relativa, é equivalente a `./token`.
+Como estamos usando uma URL relativa, se sua API estivesse localizada em `https://example.com/`, então se referiria a `https://example.com/token`. Mas se sua API estivesse localizada em `https://example.com/api/v1/`, então se referiria a `https://example.com/api/v1/token`.
- Porque estamos usando uma URL relativa, se sua API estava localizada em `https://example.com/`, então irá referir-se à `https://example.com/token`. Mas se sua API estava localizada em `https://example.com/api/v1/`, então irá referir-se à `https://example.com/api/v1/token`.
+Usar uma URL relativa é importante para garantir que sua aplicação continue funcionando mesmo em um caso de uso avançado como [Atrás de um Proxy](../../advanced/behind-a-proxy.md).
- Usar uma URL relativa é importante para garantir que sua aplicação continue funcionando, mesmo em um uso avançado tipo [Atrás de um Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+///
-Esse parâmetro não cria um endpoint / *path operation*, mas declara que a URL `/token` vai ser aquela que o client deve usar para obter o token. Essa informação é usada no OpenAPI, e depois na API Interativa de documentação de sistemas.
+Esse parâmetro não cria aquele endpoint/operação de rota, mas declara que a URL `/token` será aquela que o client deve usar para obter o token. Essa informação é usada no OpenAPI e depois nos sistemas de documentação interativa da API.
-Em breve também criaremos o atual path operation.
+Em breve também criaremos a operação de rota real.
-!!! informação
- Se você é um "Pythonista" muito rigoroso, você pode não gostar do estilo do nome do parâmetro `tokenUrl` em vez de `token_url`.
+/// info | Informação
- Isso ocorre porque está utilizando o mesmo nome que está nas especificações do OpenAPI. Então, se você precisa investigar mais sobre qualquer um desses esquemas de segurança, você pode simplesmente copiar e colar para encontrar mais informações sobre isso.
+Se você é um "Pythonista" muito rigoroso, pode não gostar do estilo do nome do parâmetro `tokenUrl` em vez de `token_url`.
-A variável `oauth2_scheme` é um instância de `OAuth2PasswordBearer`, mas também é um "callable".
+Isso ocorre porque ele usa o mesmo nome da especificação do OpenAPI. Assim, se você precisar investigar mais sobre qualquer um desses esquemas de segurança, pode simplesmente copiar e colar para encontrar mais informações sobre isso.
-Pode ser chamada de:
+///
+
+A variável `oauth2_scheme` é uma instância de `OAuth2PasswordBearer`, mas também é um "callable".
+
+Ela pode ser chamada como:
```Python
oauth2_scheme(some, parameters)
```
-Então, pode ser usado com `Depends`.
+Então, pode ser usada com `Depends`.
-## Use-o
+### Use-o { #use-it }
-Agora você pode passar aquele `oauth2_scheme` em uma dependência com `Depends`.
+Agora você pode passar esse `oauth2_scheme` em uma dependência com `Depends`.
-```Python hl_lines="10"
-{!../../../docs_src/security/tutorial001.py!}
-```
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+Essa dependência fornecerá uma `str` que é atribuída ao parâmetro `token` da função de operação de rota.
+
+O **FastAPI** saberá que pode usar essa dependência para definir um "esquema de segurança" no esquema OpenAPI (e na documentação automática da API).
-Esse dependência vai fornecer uma `str` que é atribuído ao parâmetro `token da *função do path operation*
+/// info | Detalhes Técnicos
-A **FastAPI** saberá que pode usar essa dependência para definir um "esquema de segurança" no esquema da OpenAPI (e na documentação da API automática).
+O **FastAPI** saberá que pode usar a classe `OAuth2PasswordBearer` (declarada em uma dependência) para definir o esquema de segurança no OpenAPI porque ela herda de `fastapi.security.oauth2.OAuth2`, que por sua vez herda de `fastapi.security.base.SecurityBase`.
-!!! informação "Detalhes técnicos"
- **FastAPI** saberá que pode usar a classe `OAuth2PasswordBearer` (declarada na dependência) para definir o esquema de segurança na OpenAPI porque herda de `fastapi.security.oauth2.OAuth2`, que por sua vez herda de `fastapi.security.base.Securitybase`.
+Todos os utilitários de segurança que se integram com o OpenAPI (e com a documentação automática da API) herdam de `SecurityBase`, é assim que o **FastAPI** sabe como integrá-los ao OpenAPI.
- Todos os utilitários de segurança que se integram com OpenAPI (e na documentação da API automática) herdam de `SecurityBase`, é assim que **FastAPI** pode saber como integrá-los no OpenAPI.
+///
-## O que ele faz
+## O que ele faz { #what-it-does }
-Ele irá e olhará na requisição para aquele header de `Autorização`, verificará se o valor é `Bearer` mais algum token, e vai retornar o token como uma `str`
+Ele irá procurar na requisição pelo header `Authorization`, verificar se o valor é `Bearer ` mais algum token e retornará o token como uma `str`.
-Se ele não ver o header de `Autorização` ou o valor não tem um token `Bearer`, vai responder com um código de erro 401 (`UNAUTHORIZED`) diretamente.
+Se não houver um header `Authorization`, ou se o valor não tiver um token `Bearer `, ele responderá diretamente com um erro de status 401 (`UNAUTHORIZED`).
-Você nem precisa verificar se o token existe para retornar um erro. Você pode ter certeza de que se a sua função for executada, ela terá um `str` nesse token.
+Você nem precisa verificar se o token existe para retornar um erro. Você pode ter certeza de que, se sua função for executada, ela terá uma `str` nesse token.
Você já pode experimentar na documentação interativa:
-Não estamos verificando a validade do token ainda, mas isso já é um começo
+Ainda não estamos verificando a validade do token, mas isso já é um começo.
-## Recapitulando
+## Recapitulando { #recap }
-Então, em apenas 3 ou 4 linhas extras, você já tem alguma forma primitiva de segurança.
+Então, com apenas 3 ou 4 linhas extras, você já tem alguma forma primitiva de segurança.
diff --git a/docs/pt/docs/tutorial/security/get-current-user.md b/docs/pt/docs/tutorial/security/get-current-user.md
new file mode 100644
index 0000000000000..4c6397c31f2da
--- /dev/null
+++ b/docs/pt/docs/tutorial/security/get-current-user.md
@@ -0,0 +1,105 @@
+# Obter Usuário Atual { #get-current-user }
+
+No capítulo anterior, o sistema de segurança (que é baseado no sistema de injeção de dependências) estava fornecendo à *função de operação de rota* um `token` como uma `str`:
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+Mas isso ainda não é tão útil.
+
+Vamos fazer com que ele nos forneça o usuário atual.
+
+## Criar um modelo de usuário { #create-a-user-model }
+
+Primeiro, vamos criar um modelo de usuário com Pydantic.
+
+Da mesma forma que usamos o Pydantic para declarar corpos, podemos usá-lo em qualquer outro lugar:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *}
+
+## Criar uma dependência `get_current_user` { #create-a-get-current-user-dependency }
+
+Vamos criar uma dependência chamada `get_current_user`.
+
+Lembra que as dependências podem ter subdependências?
+
+`get_current_user` terá uma dependência com o mesmo `oauth2_scheme` que criamos antes.
+
+Da mesma forma que estávamos fazendo antes diretamente na *operação de rota*, a nossa nova dependência `get_current_user` receberá um `token` como uma `str` da subdependência `oauth2_scheme`:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *}
+
+## Obter o usuário { #get-the-user }
+
+`get_current_user` usará uma função utilitária (falsa) que criamos, que recebe um token como uma `str` e retorna nosso modelo Pydantic `User`:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *}
+
+## Injetar o usuário atual { #inject-the-current-user }
+
+Então agora nós podemos usar o mesmo `Depends` com nosso `get_current_user` na *operação de rota*:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *}
+
+Observe que nós declaramos o tipo de `current_user` como o modelo Pydantic `User`.
+
+Isso nos ajudará dentro da função com todo o preenchimento automático e verificações de tipo.
+
+/// tip | Dica
+
+Você pode se lembrar que corpos de requisição também são declarados com modelos Pydantic.
+
+Aqui, o **FastAPI** não ficará confuso porque você está usando `Depends`.
+
+///
+
+/// check | Verifique
+
+A forma como esse sistema de dependências foi projetado nos permite ter diferentes dependências (diferentes "dependables") que retornam um modelo `User`.
+
+Não estamos restritos a ter apenas uma dependência que possa retornar esse tipo de dado.
+
+///
+
+## Outros modelos { #other-models }
+
+Agora você pode obter o usuário atual diretamente nas *funções de operação de rota* e lidar com os mecanismos de segurança no nível da **Injeção de Dependências**, usando `Depends`.
+
+E você pode usar qualquer modelo ou dado para os requisitos de segurança (neste caso, um modelo Pydantic `User`).
+
+Mas você não está restrito a usar um modelo de dados, classe ou tipo específico.
+
+Você quer ter apenas um `id` e `email`, sem incluir nenhum `username` no modelo? Claro. Você pode usar essas mesmas ferramentas.
+
+Você quer ter apenas uma `str`? Ou apenas um `dict`? Ou uma instância de modelo de classe de banco de dados diretamente? Tudo funciona da mesma forma.
+
+Na verdade, você não tem usuários que fazem login no seu aplicativo, mas sim robôs, bots ou outros sistemas, que possuem apenas um token de acesso? Novamente, tudo funciona da mesma forma.
+
+Apenas use qualquer tipo de modelo, qualquer tipo de classe, qualquer tipo de banco de dados que você precise para a sua aplicação. O **FastAPI** cobre tudo com o sistema de injeção de dependências.
+
+## Tamanho do código { #code-size }
+
+Este exemplo pode parecer verboso. Lembre-se de que estamos misturando segurança, modelos de dados, funções utilitárias e *operações de rota* no mesmo arquivo.
+
+Mas aqui está o ponto principal.
+
+O código relacionado à segurança e à injeção de dependências é escrito apenas uma vez.
+
+E você pode torná-lo tão complexo quanto quiser. E ainda assim, tê-lo escrito apenas uma vez, em um único lugar. Com toda a flexibilidade.
+
+Mas você pode ter milhares de endpoints (*operações de rota*) usando o mesmo sistema de segurança.
+
+E todos eles (ou qualquer parte deles que você desejar) podem aproveitar o reuso dessas dependências ou de quaisquer outras dependências que você criar.
+
+E todos esses milhares de *operações de rota* podem ter apenas 3 linhas:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *}
+
+## Recapitulação { #recap }
+
+Agora você pode obter o usuário atual diretamente na sua *função de operação de rota*.
+
+Já estamos na metade do caminho.
+
+Só precisamos adicionar uma *operação de rota* para que o usuário/cliente realmente envie o `username` e `password`.
+
+Isso vem a seguir.
diff --git a/docs/pt/docs/tutorial/security/index.md b/docs/pt/docs/tutorial/security/index.md
index f94a8ab626e35..f4c92ea567793 100644
--- a/docs/pt/docs/tutorial/security/index.md
+++ b/docs/pt/docs/tutorial/security/index.md
@@ -1,4 +1,4 @@
-# Segurança
+# Segurança { #security }
Há várias formas de lidar segurança, autenticação e autorização.
@@ -10,11 +10,11 @@ Em muitos frameworks e sistemas, apenas lidar com segurança e autenticação ex
Mas primeiro, vamos verificar alguns pequenos conceitos.
-## Está com pressa?
+## Está com pressa? { #in-a-hurry }
Se você não se importa com qualquer um desses termos e só precisa adicionar segurança com autenticação baseada em usuário e senha _agora_, pule para os próximos capítulos.
-## OAuth2
+## OAuth2 { #oauth2 }
OAuth2 é uma especificação que define várias formas para lidar com autenticação e autorização.
@@ -22,9 +22,9 @@ Ela é bastante extensiva na especificação e cobre casos de uso muito complexo
Ela inclui uma forma para autenticação usando “third party”/aplicações de terceiros.
-Isso é o que todos os sistemas com “Login with Facebook, Google, Twitter, GitHub” usam por baixo.
+Isso é o que todos os sistemas com “Login with Facebook, Google, X (Twitter), GitHub” usam por baixo.
-### OAuth 1
+### OAuth 1 { #oauth-1 }
Havia um OAuth 1, que é bem diferente do OAuth2, e mais complexo, isso incluía diretamente as especificações de como criptografar a comunicação.
@@ -32,11 +32,13 @@ Não é muito popular ou usado nos dias atuais.
OAuth2 não especifica como criptografar a comunicação, ele espera que você tenha sua aplicação em um servidor HTTPS.
-!!! tip "Dica"
- Na seção sobre **deployment** você irá ver como configurar HTTPS de modo gratuito, usando Traefik e Let’s Encrypt.
+/// tip | Dica
+Na seção sobre **deployment** você irá ver como configurar HTTPS de modo gratuito, usando Traefik e Let’s Encrypt.
-## OpenID Connect
+///
+
+## OpenID Connect { #openid-connect }
OpenID Connect é outra especificação, baseada em **OAuth2**.
@@ -46,7 +48,7 @@ Por exemplo, o login do Google usa OpenID Connect (que por baixo dos panos usa O
Mas o login do Facebook não tem suporte para OpenID Connect. Ele tem a própria implementação do OAuth2.
-### OpenID (não "OpenID Connect")
+### OpenID (não "OpenID Connect") { #openid-not-openid-connect }
Houve também uma especificação “OpenID”. Ela tentou resolver a mesma coisa que a **OpenID Connect**, mas não baseada em OAuth2.
@@ -54,7 +56,7 @@ Então, ela foi um sistema adicional completo.
Ela não é muito popular ou usada nos dias de hoje.
-## OpenAPI
+## OpenAPI { #openapi }
OpenAPI (anteriormente conhecido como Swagger) é a especificação aberta para a criação de APIs (agora parte da Linux Foundation).
@@ -77,7 +79,7 @@ OpenAPI define os seguintes esquemas de segurança:
* HTTP Basic authentication.
* HTTP Digest, etc.
* `oauth2`: todas as formas do OAuth2 para lidar com segurança (chamados "fluxos").
- * Vários desses fluxos são apropriados para construir um provedor de autenticação OAuth2 (como Google, Facebook, Twitter, GitHub, etc):
+ * Vários desses fluxos são apropriados para construir um provedor de autenticação OAuth2 (como Google, Facebook, X (Twitter), GitHub, etc):
* `implicit`
* `clientCredentials`
* `authorizationCode`
@@ -86,15 +88,17 @@ OpenAPI define os seguintes esquemas de segurança:
* `openIdConnect`: tem uma forma para definir como descobrir automaticamente o dado da autenticação OAuth2.
* Essa descoberta automática é o que é definido na especificação OpenID Connect.
+/// tip | Dica
+
+Integração com outros provedores de autenticação/autorização como Google, Facebook, X (Twitter), GitHub, etc. é bem possível e relativamente fácil.
-!!! tip "Dica"
- Integração com outros provedores de autenticação/autorização como Google, Facebook, Twitter, GitHub, etc. é bem possível e relativamente fácil.
+O problema mais complexo é criar um provedor de autenticação/autorização como eles, mas o FastAPI dá a você ferramentas para fazer isso facilmente, enquanto faz o trabalho pesado para você.
- O problema mais complexo é criar um provedor de autenticação/autorização como eles, mas o FastAPI dá a você ferramentas para fazer isso facilmente, enquanto faz o trabalho pesado para você.
+///
-## **FastAPI** utilitários
+## **FastAPI** utilitários { #fastapi-utilities }
-**FastAPI** fornece várias ferramentas para cada um desses esquemas de segurança no módulo `fastapi.security` que simplesmente usa esses mecanismos de segurança.
+**FastAPI** fornece várias ferramentas para cada um desses esquemas de segurança no módulo `fastapi.security` que simplificam o uso desses mecanismos de segurança.
Nos próximos capítulos você irá ver como adicionar segurança à sua API usando essas ferramentas disponibilizadas pelo **FastAPI**.
diff --git a/docs/pt/docs/tutorial/security/oauth2-jwt.md b/docs/pt/docs/tutorial/security/oauth2-jwt.md
new file mode 100644
index 0000000000000..6397664fbfd7d
--- /dev/null
+++ b/docs/pt/docs/tutorial/security/oauth2-jwt.md
@@ -0,0 +1,277 @@
+# OAuth2 com Senha (e hashing), Bearer com tokens JWT { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
+
+Agora que temos todo o fluxo de segurança, vamos tornar a aplicação realmente segura, usando tokens JWT e hashing de senhas seguras.
+
+Este código é algo que você pode realmente usar na sua aplicação, salvar os hashes das senhas no seu banco de dados, etc.
+
+Vamos começar de onde paramos no capítulo anterior e incrementá-lo.
+
+## Sobre o JWT { #about-jwt }
+
+JWT significa "JSON Web Tokens".
+
+É um padrão para codificar um objeto JSON em uma string longa e densa sem espaços. Ele se parece com isso:
+
+```
+eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
+```
+
+Ele não é criptografado, então qualquer pessoa pode recuperar as informações do seu conteúdo.
+
+Mas ele é assinado. Assim, quando você recebe um token que você emitiu, você pode verificar que foi realmente você quem o emitiu.
+
+Dessa forma, você pode criar um token com um prazo de expiração, digamos, de 1 semana. E então, quando o usuário voltar no dia seguinte com o token, você sabe que ele ainda está logado no seu sistema.
+
+Depois de uma semana, o token expirará e o usuário não estará autorizado, precisando fazer login novamente para obter um novo token. E se o usuário (ou uma terceira parte) tentar modificar o token para alterar a expiração, você seria capaz de descobrir isso, pois as assinaturas não iriam corresponder.
+
+Se você quiser brincar com tokens JWT e ver como eles funcionam, visite [https://jwt.io](https://jwt.io/).
+
+## Instalar `PyJWT` { #install-pyjwt }
+
+Nós precisamos instalar o `PyJWT` para criar e verificar os tokens JWT em Python.
+
+Certifique-se de criar um [ambiente virtual](../../virtual-environments.md), ativá-lo e então instalar o `pyjwt`:
+
+
+
+Autorize a aplicação da mesma maneira que antes.
+
+Usando as credenciais:
+
+Username: `johndoe`
+Password: `secret`
+
+/// check | Verifique
+
+Observe que em nenhuma parte do código está a senha em texto puro "`secret`", nós temos apenas o hash.
+
+///
+
+
+
+Chame o endpoint `/users/me/`, você receberá o retorno como:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false
+}
+```
+
+
+
+Se você abrir as ferramentas de desenvolvedor, poderá ver que os dados enviados incluem apenas o token. A senha é enviada apenas na primeira requisição para autenticar o usuário e obter o token de acesso, mas não é enviada nas próximas requisições:
+
+
+
+/// note | Nota
+
+Perceba que o cabeçalho `Authorization`, com o valor que começa com `Bearer `.
+
+///
+
+## Uso avançado com `scopes` { #advanced-usage-with-scopes }
+
+O OAuth2 tem a noção de "scopes" (escopos).
+
+Você pode usá-los para adicionar um conjunto específico de permissões a um token JWT.
+
+Então, você pode dar este token diretamente a um usuário ou a uma terceira parte para interagir com sua API com um conjunto de restrições.
+
+Você pode aprender como usá-los e como eles são integrados ao **FastAPI** mais adiante no **Guia Avançado do Usuário**.
+
+## Recapitulação { #recap }
+
+Com o que você viu até agora, você pode configurar uma aplicação **FastAPI** segura usando padrões como OAuth2 e JWT.
+
+Em quase qualquer framework, lidar com a segurança se torna rapidamente um assunto bastante complexo.
+
+Muitos pacotes que simplificam bastante isso precisam fazer muitas concessões com o modelo de dados, o banco de dados e os recursos disponíveis. E alguns desses pacotes que simplificam demais na verdade têm falhas de segurança subjacentes.
+
+---
+
+O **FastAPI** não faz nenhuma concessão com nenhum banco de dados, modelo de dados ou ferramenta.
+
+Ele oferece toda a flexibilidade para você escolher as opções que melhor se ajustam ao seu projeto.
+
+E você pode usar diretamente muitos pacotes bem mantidos e amplamente utilizados, como `pwdlib` e `PyJWT`, porque o **FastAPI** não exige mecanismos complexos para integrar pacotes externos.
+
+Mas ele fornece as ferramentas para simplificar o processo o máximo possível, sem comprometer a flexibilidade, robustez ou segurança.
+
+E você pode usar e implementar protocolos padrão seguros, como o OAuth2, de uma maneira relativamente simples.
+
+Você pode aprender mais no **Guia Avançado do Usuário** sobre como usar os "scopes" do OAuth2 para um sistema de permissões mais refinado, seguindo esses mesmos padrões. O OAuth2 com scopes é o mecanismo usado por muitos provedores grandes de autenticação, como o Facebook, Google, GitHub, Microsoft, X (Twitter), etc. para autorizar aplicativos de terceiros a interagir com suas APIs em nome de seus usuários.
diff --git a/docs/pt/docs/tutorial/security/simple-oauth2.md b/docs/pt/docs/tutorial/security/simple-oauth2.md
new file mode 100644
index 0000000000000..f582a81417dbc
--- /dev/null
+++ b/docs/pt/docs/tutorial/security/simple-oauth2.md
@@ -0,0 +1,290 @@
+# Simples OAuth2 com senha e Bearer { #simple-oauth2-with-password-and-bearer }
+
+Agora vamos construir a partir do capítulo anterior e adicionar as partes que faltam para ter um fluxo de segurança completo.
+
+## Obtenha o `username` e a `password` { #get-the-username-and-password }
+
+É utilizado o utils de segurança da **FastAPI** para obter o `username` e a `password`.
+
+OAuth2 especifica que ao usar o "password flow" (fluxo de senha), que estamos usando, o cliente/usuário deve enviar os campos `username` e `password` como dados do formulário.
+
+E a especificação diz que os campos devem ser nomeados assim. Portanto, `user-name` ou `email` não funcionariam.
+
+Mas não se preocupe, você pode mostrá-lo como quiser aos usuários finais no frontend.
+
+E seus modelos de banco de dados podem usar qualquer outro nome que você desejar.
+
+Mas para a *operação de rota* de login, precisamos usar esses nomes para serem compatíveis com a especificação (e poder, por exemplo, usar o sistema integrado de documentação da API).
+
+A especificação também afirma que o `username` e a `password` devem ser enviados como dados de formulário (portanto, não há JSON aqui).
+
+### `scope` { #scope }
+
+A especificação também diz que o cliente pode enviar outro campo de formulário "`scope`".
+
+O nome do campo do formulário é `scope` (no singular), mas na verdade é uma longa string com "escopos" separados por espaços.
+
+Cada “scope” é apenas uma string (sem espaços).
+
+Normalmente são usados para declarar permissões de segurança específicas, por exemplo:
+
+* `users:read` ou `users:write` são exemplos comuns.
+* `instagram_basic` é usado pelo Facebook e Instagram.
+* `https://www.googleapis.com/auth/drive` é usado pelo Google.
+
+/// info | Informação
+
+No OAuth2, um "scope" é apenas uma string que declara uma permissão específica necessária.
+
+Não importa se tem outros caracteres como `:` ou se é uma URL.
+
+Esses detalhes são específicos da implementação.
+
+Para OAuth2 são apenas strings.
+
+///
+
+## Código para conseguir o `username` e a `password` { #code-to-get-the-username-and-password }
+
+Agora vamos usar os utilitários fornecidos pelo **FastAPI** para lidar com isso.
+
+### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform }
+
+Primeiro, importe `OAuth2PasswordRequestForm` e use-o como uma dependência com `Depends` na *operação de rota* para `/token`:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}
+
+`OAuth2PasswordRequestForm` é uma dependência de classe que declara um corpo de formulário com:
+
+* O `username`.
+* A `password`.
+* Um campo `scope` opcional como uma string grande, composta de strings separadas por espaços.
+* Um `grant_type` opcional.
+
+/// tip | Dica
+
+A especificação OAuth2 na verdade *requer* um campo `grant_type` com um valor fixo de `password`, mas `OAuth2PasswordRequestForm` não o impõe.
+
+Se você precisar aplicá-lo, use `OAuth2PasswordRequestFormStrict` em vez de `OAuth2PasswordRequestForm`.
+
+///
+
+* Um `client_id` opcional (não precisamos dele em nosso exemplo).
+* Um `client_secret` opcional (não precisamos dele em nosso exemplo).
+
+/// info | Informação
+
+O `OAuth2PasswordRequestForm` não é uma classe especial para **FastAPI** como é `OAuth2PasswordBearer`.
+
+`OAuth2PasswordBearer` faz com que **FastAPI** saiba que é um esquema de segurança. Portanto, é adicionado dessa forma ao OpenAPI.
+
+Mas `OAuth2PasswordRequestForm` é apenas uma dependência de classe que você mesmo poderia ter escrito ou poderia ter declarado os parâmetros do `Form` (formulário) diretamente.
+
+Mas como é um caso de uso comum, ele é fornecido diretamente pelo **FastAPI**, apenas para facilitar.
+
+///
+
+### Use os dados do formulário { #use-the-form-data }
+
+/// tip | Dica
+
+A instância da classe de dependência `OAuth2PasswordRequestForm` não terá um atributo `scope` com a string longa separada por espaços, em vez disso, terá um atributo `scopes` com a lista real de strings para cada escopo enviado.
+
+Não estamos usando `scopes` neste exemplo, mas a funcionalidade está disponível se você precisar.
+
+///
+
+Agora, obtenha os dados do usuário do banco de dados (falso), usando o `username` do campo do formulário.
+
+Se não existir tal usuário, retornaremos um erro dizendo "Incorrect username or password".
+
+Para o erro, usamos a exceção `HTTPException`:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}
+
+### Confira a senha { #check-the-password }
+
+Neste ponto temos os dados do usuário do nosso banco de dados, mas não verificamos a senha.
+
+Vamos colocar esses dados primeiro no modelo `UserInDB` do Pydantic.
+
+Você nunca deve salvar senhas em texto simples, portanto, usaremos o sistema de hashing de senhas (falsas).
+
+Se as senhas não corresponderem, retornaremos o mesmo erro.
+
+#### Hashing de senha { #password-hashing }
+
+"Hashing" significa: converter algum conteúdo (uma senha neste caso) em uma sequência de bytes (apenas uma string) que parece algo sem sentido.
+
+Sempre que você passa exatamente o mesmo conteúdo (exatamente a mesma senha), você obtém exatamente a mesma sequência aleatória de caracteres.
+
+Mas você não pode converter a sequência aleatória de caracteres de volta para a senha.
+
+##### Porque usar hashing de senha { #why-use-password-hashing }
+
+Se o seu banco de dados for roubado, o ladrão não terá as senhas em texto simples dos seus usuários, apenas os hashes.
+
+Assim, o ladrão não poderá tentar usar essas mesmas senhas em outro sistema (como muitos usuários usam a mesma senha em todos os lugares, isso seria perigoso).
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}
+
+#### Sobre `**user_dict` { #about-user-dict }
+
+`UserInDB(**user_dict)` significa:
+
+*Passe as chaves e valores de `user_dict` diretamente como argumentos de valor-chave, equivalente a:*
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ disabled = user_dict["disabled"],
+ hashed_password = user_dict["hashed_password"],
+)
+```
+
+
+/// info | Informação
+
+Para uma explicação mais completa de `**user_dict`, verifique [a documentação para **Extra Models**](../extra-models.md#about-user-in-dict).
+
+///
+
+## Retorne o token { #return-the-token }
+
+A resposta do endpoint `token` deve ser um objeto JSON.
+
+Deve ter um `token_type`. No nosso caso, como estamos usando tokens "Bearer", o tipo de token deve ser "`bearer`".
+
+E deve ter um `access_token`, com uma string contendo nosso token de acesso.
+
+Para este exemplo simples, seremos completamente inseguros e retornaremos o mesmo `username` do token.
+
+/// tip | Dica
+
+No próximo capítulo, você verá uma implementação realmente segura, com hash de senha e tokens JWT.
+
+Mas, por enquanto, vamos nos concentrar nos detalhes específicos de que precisamos.
+
+///
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}
+
+/// tip | Dica
+
+Pela especificação, você deve retornar um JSON com um `access_token` e um `token_type`, o mesmo que neste exemplo.
+
+Isso é algo que você mesmo deve fazer em seu código e certifique-se de usar essas chaves JSON.
+
+É quase a única coisa que você deve se lembrar de fazer corretamente, para estar em conformidade com as especificações.
+
+De resto, **FastAPI** cuida disso para você.
+
+///
+
+## Atualize as dependências { #update-the-dependencies }
+
+Agora vamos atualizar nossas dependências.
+
+Queremos obter o `current_user` *somente* se este usuário estiver ativo.
+
+Portanto, criamos uma dependência adicional `get_current_active_user` que por sua vez usa `get_current_user` como dependência.
+
+Ambas as dependências retornarão apenas um erro HTTP se o usuário não existir ou se estiver inativo.
+
+Portanto, em nosso endpoint, só obteremos um usuário se o usuário existir, tiver sido autenticado corretamente e estiver ativo:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}
+
+/// info | Informação
+
+O cabeçalho adicional `WWW-Authenticate` com valor `Bearer` que estamos retornando aqui também faz parte da especificação.
+
+Qualquer código de status HTTP (erro) 401 "UNAUTHORIZED" também deve retornar um cabeçalho `WWW-Authenticate`.
+
+No caso de tokens ao portador (nosso caso), o valor desse cabeçalho deve ser `Bearer`.
+
+Na verdade, você pode pular esse cabeçalho extra e ainda funcionaria.
+
+Mas é fornecido aqui para estar em conformidade com as especificações.
+
+Além disso, pode haver ferramentas que esperam e usam isso (agora ou no futuro) e que podem ser úteis para você ou seus usuários, agora ou no futuro.
+
+Esse é o benefício dos padrões...
+
+///
+
+## Veja em ação { #see-it-in-action }
+
+Abra o docs interativo: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).
+
+### Autentique-se { #authenticate }
+
+Clique no botão "Authorize".
+
+Use as credenciais:
+
+User: `johndoe`
+
+Password: `secret`
+
+
+
+Após autenticar no sistema, você verá assim:
+
+
+
+### Obtenha seus próprios dados de usuário { #get-your-own-user-data }
+
+Agora use a operação `GET` com o caminho `/users/me`.
+
+Você obterá os dados do seu usuário, como:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false,
+ "hashed_password": "fakehashedsecret"
+}
+```
+
+
+
+Se você clicar no ícone de cadeado, sair e tentar a mesma operação novamente, receberá um erro HTTP 401 de:
+
+```JSON
+{
+ "detail": "Not authenticated"
+}
+```
+
+### Usuário inativo { #inactive-user }
+
+Agora tente com um usuário inativo, autentique-se com:
+
+User: `alice`
+
+Password: `secret2`
+
+E tente usar a operação `GET` com o caminho `/users/me`.
+
+Você receberá um erro "Usuário inativo", como:
+
+```JSON
+{
+ "detail": "Inactive user"
+}
+```
+
+## Recapitulando { #recap }
+
+Agora você tem as ferramentas para implementar um sistema de segurança completo baseado em `username` e `password` para sua API.
+
+Usando essas ferramentas, você pode tornar o sistema de segurança compatível com qualquer banco de dados e com qualquer usuário ou modelo de dados.
+
+O único detalhe que falta é que ainda não é realmente "seguro".
+
+No próximo capítulo você verá como usar uma biblioteca de hashing de senha segura e tokens JWT.
diff --git a/docs/pt/docs/tutorial/server-sent-events.md b/docs/pt/docs/tutorial/server-sent-events.md
new file mode 100644
index 0000000000000..33389873ce824
--- /dev/null
+++ b/docs/pt/docs/tutorial/server-sent-events.md
@@ -0,0 +1,120 @@
+# Eventos Enviados pelo Servidor (SSE) { #server-sent-events-sse }
+
+Você pode transmitir dados para o cliente usando Server-Sent Events (SSE).
+
+Isso é semelhante a [Stream de JSON Lines](stream-json-lines.md), mas usa o formato `text/event-stream`, que é suportado nativamente pelos navegadores com a [`EventSource` API](https://developer.mozilla.org/en-US/docs/Web/API/EventSource).
+
+/// info | Informação
+
+Adicionado no FastAPI 0.135.0.
+
+///
+
+## O que são Server-Sent Events? { #what-are-server-sent-events }
+
+SSE é um padrão para transmitir dados do servidor para o cliente via HTTP.
+
+Cada evento é um pequeno bloco de texto com “campos” como `data`, `event`, `id` e `retry`, separados por linhas em branco.
+
+Fica assim:
+
+```
+data: {"name": "Portal Gun", "price": 999.99}
+
+data: {"name": "Plumbus", "price": 32.99}
+
+```
+
+SSE é comumente usado para streaming de chat de IA, notificações em tempo real, logs e observabilidade, e outros casos em que o servidor envia atualizações para o cliente.
+
+/// tip | Dica
+
+Se você quiser transmitir dados binários, por exemplo vídeo ou áudio, veja o guia avançado: [Stream de Dados](../advanced/stream-data.md).
+
+///
+
+## Transmitir SSE com FastAPI { #stream-sse-with-fastapi }
+
+Para transmitir SSE com FastAPI, use `yield` na sua função de operação de rota e defina `response_class=EventSourceResponse`.
+
+Importe `EventSourceResponse` de `fastapi.sse`:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[4,22] *}
+
+Cada item produzido é codificado como JSON e enviado no campo `data:` de um evento SSE.
+
+Se você declarar o tipo de retorno como `AsyncIterable[Item]`, o FastAPI o usará para validar, documentar e serializar os dados com o Pydantic.
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[10:12,23] *}
+
+/// tip | Dica
+
+Como o Pydantic fará a serialização no lado em **Rust**, você terá um desempenho muito maior do que se não declarar um tipo de retorno.
+
+///
+
+### *Funções de operação de rota* não assíncronas { #non-async-path-operation-functions }
+
+Você também pode usar funções `def` normais (sem `async`) e usar `yield` da mesma forma.
+
+O FastAPI garantirá a execução correta para não bloquear o event loop.
+
+Como, neste caso, a função não é assíncrona, o tipo de retorno adequado seria `Iterable[Item]`:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[28:31] hl[29] *}
+
+### Sem tipo de retorno { #no-return-type }
+
+Você também pode omitir o tipo de retorno. O FastAPI usará o [`jsonable_encoder`](./encoder.md) para converter os dados e enviá-los.
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[34:37] hl[35] *}
+
+## `ServerSentEvent` { #serversentevent }
+
+Se você precisar definir campos de SSE como `event`, `id`, `retry` ou `comment`, você pode produzir objetos `ServerSentEvent` em vez de dados simples.
+
+Importe `ServerSentEvent` de `fastapi.sse`:
+
+{* ../../docs_src/server_sent_events/tutorial002_py310.py hl[4,26] *}
+
+O campo `data` é sempre codificado como JSON. Você pode passar qualquer valor que possa ser serializado como JSON, incluindo modelos do Pydantic.
+
+## Dados brutos { #raw-data }
+
+Se você precisar enviar dados sem codificação JSON, use `raw_data` em vez de `data`.
+
+Isto é útil para enviar texto pré-formatado, linhas de log ou valores "sentinela" especiais como `[DONE]`.
+
+{* ../../docs_src/server_sent_events/tutorial003_py310.py hl[17] *}
+
+/// note | Nota
+
+`data` e `raw_data` são mutuamente exclusivos. Você só pode definir um deles em cada `ServerSentEvent`.
+
+///
+
+## Retomando com `Last-Event-ID` { #resuming-with-last-event-id }
+
+Quando um navegador se reconecta após uma queda na conexão, ele envia o último `id` recebido no cabeçalho `Last-Event-ID`.
+
+Você pode lê-lo como um parâmetro de cabeçalho e usá-lo para retomar o stream de onde o cliente parou:
+
+{* ../../docs_src/server_sent_events/tutorial004_py310.py hl[25,27,31] *}
+
+## SSE com POST { #sse-with-post }
+
+SSE funciona com qualquer método HTTP, não apenas `GET`.
+
+Isso é útil para protocolos como o [MCP](https://modelcontextprotocol.io) que fazem stream de SSE via `POST`:
+
+{* ../../docs_src/server_sent_events/tutorial005_py310.py hl[14] *}
+
+## Detalhes Técnicos { #technical-details }
+
+O FastAPI implementa algumas boas práticas de SSE prontas para uso.
+
+- Enviar um comentário de keep alive `ping` a cada 15 segundos quando não houver mensagens, para evitar que alguns proxies fechem a conexão, como sugerido na [especificação HTML: Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes).
+- Definir o cabeçalho `Cache-Control: no-cache` para evitar o cache do stream.
+- Definir o cabeçalho especial `X-Accel-Buffering: no` para evitar buffering em alguns proxies como o Nginx.
+
+Você não precisa fazer nada, isso funciona automaticamente. 🤓
diff --git a/docs/pt/docs/tutorial/sql-databases.md b/docs/pt/docs/tutorial/sql-databases.md
new file mode 100644
index 0000000000000..10be4c865c64f
--- /dev/null
+++ b/docs/pt/docs/tutorial/sql-databases.md
@@ -0,0 +1,356 @@
+# Bancos de Dados SQL (Relacionais) { #sql-relational-databases }
+
+**FastAPI** não exige que você use um banco de dados SQL (relacional). Mas você pode usar **qualquer banco de dados** que quiser.
+
+Aqui veremos um exemplo usando [SQLModel](https://sqlmodel.tiangolo.com/).
+
+**SQLModel** é construído sobre [SQLAlchemy](https://www.sqlalchemy.org/) e Pydantic. Ele foi criado pelo mesmo autor do **FastAPI** para ser o par perfeito para aplicações **FastAPI** que precisam usar **bancos de dados SQL**.
+
+/// tip | Dica
+
+Você pode usar qualquer outra biblioteca de banco de dados SQL ou NoSQL que quiser (em alguns casos chamadas de "ORMs"), o FastAPI não obriga você a usar nada. 😎
+
+///
+
+Como o SQLModel é baseado no SQLAlchemy, você pode facilmente usar **qualquer banco de dados suportado** pelo SQLAlchemy (o que também os torna suportados pelo SQLModel), como:
+
+* PostgreSQL
+* MySQL
+* SQLite
+* Oracle
+* Microsoft SQL Server, etc.
+
+Neste exemplo, usaremos **SQLite**, porque ele usa um único arquivo e o Python tem suporte integrado. Assim, você pode copiar este exemplo e executá-lo como está.
+
+Mais tarde, para sua aplicação em produção, você pode querer usar um servidor de banco de dados como o **PostgreSQL**.
+
+/// tip | Dica
+
+Existe um gerador de projetos oficial com **FastAPI** e **PostgreSQL** incluindo um frontend e mais ferramentas: [https://github.com/fastapi/full-stack-fastapi-template](https://github.com/fastapi/full-stack-fastapi-template)
+
+///
+
+Este é um tutorial muito simples e curto, se você quiser aprender sobre bancos de dados em geral, sobre SQL ou recursos mais avançados, acesse a [documentação do SQLModel](https://sqlmodel.tiangolo.com/).
+
+## Instalar o `SQLModel` { #install-sqlmodel }
+
+Primeiro, certifique-se de criar seu [ambiente virtual](../virtual-environments.md), ativá-lo e, em seguida, instalar o `sqlmodel`:
+
+
+
+lt
+* XWT
+* PSGI
+
+### abbr даёт полную расшифровку и объяснение { #the-abbr-gives-a-full-phrase-and-an-explanation }
+
+* MDN
+* I/O.
+
+////
+
+//// tab | Информация
+
+Атрибуты "title" элементов "abbr" переводятся по определённым правилам.
+
+Переводы могут добавлять свои собственные элементы "abbr", которые LLM не должна удалять. Например, чтобы объяснить английские слова.
+
+См. раздел `### HTML abbr elements` в общем промпте в `scripts/translate.py`.
+
+////
+
+## HTML-элементы "dfn" { #html-dfn-elements }
+
+* кластер
+* Глубокое обучение
+
+## Заголовки { #headings }
+
+//// tab | Тест
+
+### Разработка веб‑приложения — руководство { #develop-a-webapp-a-tutorial }
+
+Привет.
+
+### Аннотации типов и -аннотации { #type-hints-and-annotations }
+
+Снова привет.
+
+### Супер- и подклассы { #super-and-subclasses }
+
+Снова привет.
+
+////
+
+//// tab | Информация
+
+Единственное жёсткое правило для заголовков — LLM должна оставить часть хеша в фигурных скобках без изменений, чтобы ссылки не ломались.
+
+См. раздел `### Headings` в общем промпте в `scripts/translate.py`.
+
+Для некоторых языковых инструкций см., например, раздел `### Headings` в `docs/de/llm-prompt.md`.
+
+////
+
+## Термины, используемые в документации { #terms-used-in-the-docs }
+
+//// tab | Тест
+
+* вы
+* ваш
+
+* например
+* и т.д.
+
+* `foo` как `int`
+* `bar` как `str`
+* `baz` как `list`
+
+* Учебник — Руководство пользователя
+* Расширенное руководство пользователя
+* Документация по SQLModel
+* Документация API
+* Автоматическая документация
+
+* Наука о данных
+* Глубокое обучение
+* Машинное обучение
+* Внедрение зависимостей
+* Аутентификация HTTP Basic
+* HTTP Digest
+* формат ISO
+* стандарт JSON Schema
+* JSON-схема
+* определение схемы
+* password flow
+* Мобильный
+
+* устаревший
+* спроектированный
+* некорректный
+* на лету
+* стандарт
+* по умолчанию
+* чувствительный к регистру
+* нечувствительный к регистру
+
+* отдавать приложение
+* отдавать страницу
+
+* приложение
+* приложение
+
+* HTTP-запрос
+* HTTP-ответ
+* ответ с ошибкой
+
+* операция пути
+* декоратор операции пути
+* функция-обработчик пути
+
+* тело
+* тело запроса
+* тело ответа
+* JSON-тело
+* тело формы
+* тело файла
+* тело функции
+
+* параметр
+* body-параметр
+* path-параметр
+* query-параметр
+* cookie-параметр
+* параметр заголовка
+* параметр формы
+* параметр функции
+
+* событие
+* событие запуска
+* запуск сервера
+* событие остановки
+* событие lifespan
+
+* обработчик
+* обработчик события
+* обработчик исключений
+* обрабатывать
+
+* модель
+* Pydantic-модель
+* модель данных
+* модель базы данных
+* модель формы
+* объект модели
+
+* класс
+* базовый класс
+* родительский класс
+* подкласс
+* дочерний класс
+* родственный класс
+* метод класса
+
+* заголовок
+* HTTP-заголовки
+* заголовок авторизации
+* заголовок `Authorization`
+* заголовок `Forwarded`
+
+* система внедрения зависимостей
+* зависимость
+* зависимый объект
+* зависимый
+
+* ограниченный вводом/выводом
+* ограниченный процессором
+* конкурентность
+* параллелизм
+* многопроцессность
+
+* переменная окружения
+* переменная окружения
+* `PATH`
+* переменная `PATH`
+
+* аутентификация
+* провайдер аутентификации
+* авторизация
+* форма авторизации
+* провайдер авторизации
+* пользователь аутентифицируется
+* система аутентифицирует пользователя
+
+* CLI
+* интерфейс командной строки
+
+* сервер
+* клиент
+
+* облачный провайдер
+* облачный сервис
+
+* разработка
+* этапы разработки
+
+* dict
+* словарь
+* перечисление
+* enum
+* член перечисления
+
+* кодировщик
+* декодировщик
+* кодировать
+* декодировать
+
+* исключение
+* вызвать
+
+* выражение
+* оператор
+
+* фронтенд
+* бэкенд
+
+* обсуждение на GitHub
+* Issue на GitHub (тикет/обращение)
+
+* производительность
+* оптимизация производительности
+
+* тип возвращаемого значения
+* возвращаемое значение
+
+* безопасность
+* схема безопасности
+
+* задача
+* фоновая задача
+* функция задачи
+
+* шаблон
+* шаблонизатор
+
+* аннотация типов
+* аннотация типов
+
+* воркер сервера
+* воркер Uvicorn
+* воркер Gunicorn
+* воркер-процесс
+* класс воркера
+* рабочая нагрузка
+
+* деплой
+* развернуть
+
+* SDK
+* набор средств разработки ПО
+
+* `APIRouter`
+* `requirements.txt`
+* токен Bearer
+* несовместимое изменение
+* баг
+* кнопка
+* вызываемый объект
+* код
+* коммит
+* менеджер контекста
+* корутина
+* сессия базы данных
+* диск
+* домен
+* движок
+* фиктивный X
+* метод HTTP GET
+* элемент
+* библиотека
+* lifespan
+* блокировка
+* middleware (Промежуточный слой)
+* мобильное приложение
+* модуль
+* монтирование
+* сеть
+* origin (источник)
+* переопределение
+* полезная нагрузка
+* процессор
+* свойство
+* прокси
+* пулл-реквест (запрос на изменение)
+* запрос
+* ОЗУ
+* удалённая машина
+* статус-код
+* строка
+* тег
+* веб‑фреймворк
+* подстановочный знак
+* вернуть
+* валидировать
+
+////
+
+//// tab | Информация
+
+Это неполный и ненормативный список (в основном) технических терминов, встречающихся в документации. Он может помочь автору промпта понять, по каким терминам LLM нужна подсказка. Например, когда она продолжает возвращать действительно хороший перевод к неоптимальному. Или когда у неё возникают проблемы со склонением/спряжением термина на вашем языке.
+
+См., например, раздел `### List of English terms and their preferred German translations` в `docs/de/llm-prompt.md`.
+
+////
diff --git a/docs/ru/docs/about/index.md b/docs/ru/docs/about/index.md
new file mode 100644
index 0000000000000..4f48266a7ad55
--- /dev/null
+++ b/docs/ru/docs/about/index.md
@@ -0,0 +1,3 @@
+# О проекте { #about }
+
+О FastAPI, его дизайне, источниках вдохновения и многом другом. 🤓
diff --git a/docs/ru/docs/advanced/additional-responses.md b/docs/ru/docs/advanced/additional-responses.md
new file mode 100644
index 0000000000000..f7e8d9dec07b2
--- /dev/null
+++ b/docs/ru/docs/advanced/additional-responses.md
@@ -0,0 +1,247 @@
+# Дополнительные ответы в OpenAPI { #additional-responses-in-openapi }
+
+/// warning | Предупреждение
+
+Это довольно продвинутая тема.
+
+Если вы только начинаете работать с **FastAPI**, возможно, вам это пока не нужно.
+
+///
+
+Вы можете объявлять дополнительные ответы с дополнительными статус-кодами, типами содержимого, описаниями и т.д.
+
+Эти дополнительные ответы будут включены в схему OpenAPI, и поэтому появятся в документации API.
+
+Но для таких дополнительных ответов убедитесь, что вы возвращаете `Response`, например `JSONResponse`, напрямую, со своим статус-кодом и содержимым.
+
+## Дополнительный ответ с `model` { #additional-response-with-model }
+
+Вы можете передать вашим декораторам операции пути параметр `responses`.
+
+Он принимает `dict`: ключи — это статус-коды для каждого ответа (например, `200`), а значения — другие `dict` с информацией для каждого из них.
+
+Каждый из этих `dict` для ответа может иметь ключ `model`, содержащий Pydantic-модель, аналогично `response_model`.
+
+**FastAPI** возьмёт эту модель, сгенерирует для неё JSON‑схему и включит её в нужное место в OpenAPI.
+
+Например, чтобы объявить ещё один ответ со статус-кодом `404` и Pydantic-моделью `Message`, можно написать:
+
+{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}
+
+/// note | Примечание
+
+Имейте в виду, что необходимо возвращать `JSONResponse` напрямую.
+
+///
+
+/// info | Информация
+
+Ключ `model` не является частью OpenAPI.
+
+**FastAPI** возьмёт Pydantic-модель оттуда, сгенерирует JSON‑схему и поместит её в нужное место.
+
+Нужное место:
+
+* В ключе `content`, значением которого является другой JSON‑объект (`dict`), содержащий:
+ * Ключ с типом содержимого, например `application/json`, значением которого является другой JSON‑объект, содержащий:
+ * Ключ `schema`, значением которого является JSON‑схема из модели — вот нужное место.
+ * **FastAPI** добавляет здесь ссылку на глобальные JSON‑схемы в другом месте вашего OpenAPI вместо того, чтобы включать схему напрямую. Так другие приложения и клиенты смогут использовать эти JSON‑схемы напрямую, предоставлять лучшие инструменты генерации кода и т.д.
+
+///
+
+Сгенерированные в OpenAPI ответы для этой операции пути будут такими:
+
+```JSON hl_lines="3-12"
+{
+ "responses": {
+ "404": {
+ "description": "Additional Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Message"
+ }
+ }
+ }
+ },
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+Схемы даны как ссылки на другое место внутри схемы OpenAPI:
+
+```JSON hl_lines="4-16"
+{
+ "components": {
+ "schemas": {
+ "Message": {
+ "title": "Message",
+ "required": [
+ "message"
+ ],
+ "type": "object",
+ "properties": {
+ "message": {
+ "title": "Message",
+ "type": "string"
+ }
+ }
+ },
+ "Item": {
+ "title": "Item",
+ "required": [
+ "id",
+ "value"
+ ],
+ "type": "object",
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
+ },
+ "value": {
+ "title": "Value",
+ "type": "string"
+ }
+ }
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": [
+ "loc",
+ "msg",
+ "type"
+ ],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string"
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string"
+ }
+ }
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+## Дополнительные типы содержимого для основного ответа { #additional-media-types-for-the-main-response }
+
+Вы можете использовать этот же параметр `responses`, чтобы добавить разные типы содержимого для того же основного ответа.
+
+Например, вы можете добавить дополнительный тип содержимого `image/png`, объявив, что ваша операция пути может возвращать JSON‑объект (с типом содержимого `application/json`) или PNG‑изображение:
+
+{* ../../docs_src/additional_responses/tutorial002_py310.py hl[17:22,26] *}
+
+/// note | Примечание
+
+Учтите, что изображение нужно возвращать напрямую, используя `FileResponse`.
+
+///
+
+/// info | Информация
+
+Если вы явно не укажете другой тип содержимого в параметре `responses`, FastAPI будет считать, что ответ имеет тот же тип содержимого, что и основной класс ответа (по умолчанию `application/json`).
+
+Но если вы указали пользовательский класс ответа с `None` в качестве его типа содержимого, FastAPI использует `application/json` для любого дополнительного ответа, у которого есть связанная модель.
+
+///
+
+## Комбинирование информации { #combining-information }
+
+Вы также можете комбинировать информацию об ответах из нескольких мест, включая параметры `response_model`, `status_code` и `responses`.
+
+Вы можете объявить `response_model`, используя статус-код по умолчанию `200` (или свой, если нужно), а затем объявить дополнительную информацию для этого же ответа в `responses`, напрямую в схеме OpenAPI.
+
+**FastAPI** сохранит дополнительную информацию из `responses` и объединит её с JSON‑схемой из вашей модели.
+
+Например, вы можете объявить ответ со статус-кодом `404`, который использует Pydantic-модель и имеет пользовательское `description`.
+
+А также ответ со статус-кодом `200`, который использует ваш `response_model`, но включает пользовательский `example`:
+
+{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}
+
+Всё это будет объединено и включено в ваш OpenAPI и отображено в документации API:
+
+
+
+## Комбинирование предопределённых и пользовательских ответов { #combine-predefined-responses-and-custom-ones }
+
+Возможно, вы хотите иметь некоторые предопределённые ответы, применимые ко многим операциям пути, но при этом комбинировать их с пользовательскими ответами, необходимыми для каждой конкретной операции пути.
+
+В таких случаях вы можете использовать приём Python «распаковки» `dict` с помощью `**dict_to_unpack`:
+
+```Python
+old_dict = {
+ "old key": "old value",
+ "second old key": "second old value",
+}
+new_dict = {**old_dict, "new key": "new value"}
+```
+
+Здесь `new_dict` будет содержать все пары ключ-значение из `old_dict` плюс новую пару ключ-значение:
+
+```Python
+{
+ "old key": "old value",
+ "second old key": "second old value",
+ "new key": "new value",
+}
+```
+
+Вы можете использовать этот приём, чтобы переиспользовать некоторые предопределённые ответы в ваших операциях пути и комбинировать их с дополнительными пользовательскими.
+
+Например:
+
+{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}
+
+## Дополнительная информация об ответах OpenAPI { #more-information-about-openapi-responses }
+
+Чтобы увидеть, что именно можно включать в ответы, посмотрите эти разделы спецификации OpenAPI:
+
+* [Объект Responses OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responses-object), он включает `Response Object`.
+* [Объект Response OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#response-object), вы можете включить всё из этого объекта напрямую в каждый ответ внутри вашего параметра `responses`. Включая `description`, `headers`, `content` (внутри него вы объявляете разные типы содержимого и JSON‑схемы) и `links`.
diff --git a/docs/ru/docs/advanced/additional-status-codes.md b/docs/ru/docs/advanced/additional-status-codes.md
new file mode 100644
index 0000000000000..aec66a13ff191
--- /dev/null
+++ b/docs/ru/docs/advanced/additional-status-codes.md
@@ -0,0 +1,41 @@
+# Дополнительные статус-коды { #additional-status-codes }
+
+По умолчанию **FastAPI** будет возвращать ответы, используя `JSONResponse`, помещая содержимое, которое вы возвращаете из вашей *операции пути*, внутрь этого `JSONResponse`.
+
+Он будет использовать статус-код по умолчанию или тот, который вы укажете в вашей *операции пути*.
+
+## Дополнительные статус-коды { #additional-status-codes_1 }
+
+Если вы хотите возвращать дополнительные статус-коды помимо основного, вы можете сделать это, возвращая `Response` напрямую, например `JSONResponse`, и устанавливая дополнительный статус-код напрямую.
+
+Например, предположим, что вы хотите иметь *операцию пути*, которая позволяет обновлять элементы и возвращает HTTP статус-код 200 «OK» при успешном выполнении.
+
+Но вы также хотите, чтобы она принимала новые элементы. И если элементы ранее не существовали, она создаёт их и возвращает HTTP статус-код 201 «Created».
+
+Чтобы добиться этого, импортируйте `JSONResponse` и верните туда свой контент напрямую, установив нужный вам `status_code`:
+
+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
+
+/// warning | Внимание
+
+Когда вы возвращаете `Response` напрямую, как в примере выше, он будет возвращён как есть.
+
+Он не будет сериализован с помощью модели и т.п.
+
+Убедитесь, что в нём именно те данные, которые вы хотите, и что значения являются валидным JSON (если вы используете `JSONResponse`).
+
+///
+
+/// note | Технические детали
+
+Вы также можете использовать `from starlette.responses import JSONResponse`.
+
+**FastAPI** предоставляет тот же `starlette.responses` через `fastapi.responses` просто для вашего удобства как разработчика. Но большинство доступных Response-классов приходят напрямую из Starlette. То же самое со `status`.
+
+///
+
+## OpenAPI и документация API { #openapi-and-api-docs }
+
+Если вы возвращаете дополнительные статус-коды и ответы напрямую, они не будут включены в схему OpenAPI (документацию API), потому что у FastAPI нет способа заранее знать, что вы собираетесь вернуть.
+
+Но вы можете задокументировать это в своём коде, используя: [Дополнительные ответы](additional-responses.md).
diff --git a/docs/ru/docs/advanced/advanced-dependencies.md b/docs/ru/docs/advanced/advanced-dependencies.md
new file mode 100644
index 0000000000000..fe37a79c1f08b
--- /dev/null
+++ b/docs/ru/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,163 @@
+# Продвинутые зависимости { #advanced-dependencies }
+
+## Параметризованные зависимости { #parameterized-dependencies }
+
+Все зависимости, которые мы видели, — это конкретная функция или класс.
+
+Но бывают случаи, когда нужно задавать параметры зависимости, не объявляя много разных функций или классов.
+
+Представим, что нам нужна зависимость, которая проверяет, содержит ли query-параметр `q` некоторое фиксированное содержимое.
+
+Но при этом мы хотим иметь возможность параметризовать это фиксированное содержимое.
+
+## «Вызываемый» экземпляр { #a-callable-instance }
+
+В Python есть способ сделать экземпляр класса «вызываемым» объектом.
+
+Не сам класс (он уже является вызываемым), а экземпляр этого класса.
+
+Для этого объявляем метод `__call__`:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}
+
+В этом случае именно `__call__` **FastAPI** использует для проверки дополнительных параметров и подзависимостей, и именно он будет вызван, чтобы позже передать значение параметру в вашей *функции-обработчике пути*.
+
+## Параметризуем экземпляр { #parameterize-the-instance }
+
+Теперь мы можем использовать `__init__`, чтобы объявить параметры экземпляра, с помощью которых будем «параметризовать» зависимость:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}
+
+В этом случае **FastAPI** вовсе не трогает `__init__` и не зависит от него — мы используем его напрямую в нашем коде.
+
+## Создаём экземпляр { #create-an-instance }
+
+Мы можем создать экземпляр этого класса так:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}
+
+Так мы «параметризуем» нашу зависимость: теперь внутри неё хранится "bar" в атрибуте `checker.fixed_content`.
+
+## Используем экземпляр как зависимость { #use-the-instance-as-a-dependency }
+
+Затем мы можем использовать этот `checker` в `Depends(checker)` вместо `Depends(FixedContentQueryChecker)`, потому что зависимостью является экземпляр `checker`, а не сам класс.
+
+И при разрешении зависимости **FastAPI** вызовет `checker` примерно так:
+
+```Python
+checker(q="somequery")
+```
+
+…и передаст возвращённое значение как значение зависимости в параметр `fixed_content_included` нашей *функции-обработчику пути*:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}
+
+/// tip | Совет
+
+Все это может показаться притянутым за уши. И пока может быть не совсем понятно, чем это полезно.
+
+Эти примеры намеренно простые, но они показывают, как всё устроено.
+
+В главах про безопасность есть вспомогательные функции, реализованные тем же способом.
+
+Если вы поняли всё выше, вы уже знаете, как «под капотом» работают эти утилиты для безопасности.
+
+///
+
+## Зависимости с `yield`, `HTTPException`, `except` и фоновыми задачами { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+/// warning | Предупреждение
+
+Скорее всего, вам не понадобятся эти технические детали.
+
+Они полезны главным образом, если у вас было приложение FastAPI версии ниже 0.121.0 и вы столкнулись с проблемами зависимостей с `yield`.
+
+///
+
+Зависимости с `yield` со временем изменялись, чтобы учитывать разные случаи применения и исправлять проблемы. Ниже — краткое резюме изменений.
+
+### Зависимости с `yield` и `scope` { #dependencies-with-yield-and-scope }
+
+В версии 0.121.0 FastAPI добавил поддержку `Depends(scope="function")` для зависимостей с `yield`.
+
+При использовании `Depends(scope="function")` код после `yield` выполняется сразу после завершения *функции-обработчика пути*, до отправки ответа клиенту.
+
+А при использовании `Depends(scope="request")` (значение по умолчанию) код после `yield` выполняется после отправки ответа.
+
+Подробнее читайте в документации: [Зависимости с `yield` — раннее завершение и `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope).
+
+### Зависимости с `yield` и `StreamingResponse`, технические детали { #dependencies-with-yield-and-streamingresponse-technical-details }
+
+До FastAPI 0.118.0, если вы использовали зависимость с `yield`, код после `yield` выполнялся после возврата из *функции-обработчика пути*, но прямо перед отправкой ответа.
+
+Идея состояла в том, чтобы не удерживать ресурсы дольше необходимого, пока ответ «путешествует» по сети.
+
+Это изменение также означало, что если вы возвращали `StreamingResponse`, код после `yield` в зависимости уже успевал выполниться.
+
+Например, если у вас была сессия базы данных в зависимости с `yield`, `StreamingResponse` не смог бы использовать эту сессию во время стриминга данных, потому что сессия уже была закрыта в коде после `yield`.
+
+В версии 0.118.0 это поведение было возвращено к тому, что код после `yield` выполняется после отправки ответа.
+
+/// info | Информация
+
+Как вы увидите ниже, это очень похоже на поведение до версии 0.106.0, но с несколькими улучшениями и исправлениями краевых случаев.
+
+///
+
+#### Сценарии с ранним выполнением кода после `yield` { #use-cases-with-early-exit-code }
+
+Есть некоторые сценарии со специфическими условиями, которым могло бы помочь старое поведение — выполнение кода после `yield` перед отправкой ответа.
+
+Например, представьте, что вы используете сессию базы данных в зависимости с `yield` только для проверки пользователя, а в самой *функции-обработчике пути* эта сессия больше не используется, и при этом ответ отправляется долго, например, это `StreamingResponse`, который медленно отправляет данные и по какой-то причине не использует базу данных.
+
+В таком случае сессия базы данных будет удерживаться до завершения отправки ответа, хотя если вы её не используете, удерживать её не требуется.
+
+Это могло бы выглядеть так:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
+
+Код после `yield`, автоматическое закрытие `Session` в:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
+
+…будет выполнен после того, как ответ закончит отправку медленных данных:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
+
+Но поскольку `generate_stream()` не использует сессию базы данных, нет реальной необходимости держать сессию открытой во время отправки ответа.
+
+Если у вас именно такой сценарий с SQLModel (или SQLAlchemy), вы можете явно закрыть сессию, когда она больше не нужна:
+
+{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}
+
+Так сессия освободит подключение к базе данных, и другие запросы смогут его использовать.
+
+Если у вас есть другой сценарий, где нужно раннее завершение зависимости с `yield`, пожалуйста, создайте [вопрос в GitHub Discussions](https://github.com/fastapi/fastapi/discussions/new?category=questions) с описанием конкретного кейса и почему вам было бы полезно иметь раннее закрытие для зависимостей с `yield`.
+
+Если появятся веские причины для раннего закрытия в зависимостях с `yield`, я рассмотрю добавление нового способа опционально включать раннее закрытие.
+
+### Зависимости с `yield` и `except`, технические детали { #dependencies-with-yield-and-except-technical-details }
+
+До FastAPI 0.110.0, если вы использовали зависимость с `yield`, затем перехватывали исключение с `except` в этой зависимости и не пробрасывали исключение снова, исключение автоматически пробрасывалось дальше к обработчикам исключений или к обработчику внутренней ошибки сервера.
+
+В версии 0.110.0 это было изменено, чтобы исправить неконтролируемое потребление памяти из‑за проброшенных исключений без обработчика (внутренние ошибки сервера) и привести поведение в соответствие с обычным поведением Python-кода.
+
+### Фоновые задачи и зависимости с `yield`, технические детали { #background-tasks-and-dependencies-with-yield-technical-details }
+
+До FastAPI 0.106.0 вызывать исключения после `yield` было невозможно: код после `yield` в зависимостях выполнялся уже после отправки ответа, поэтому [Обработчики исключений](../tutorial/handling-errors.md#install-custom-exception-handlers) к тому моменту уже отработали.
+
+Так было сделано в основном для того, чтобы можно было использовать те же объекты, «отданные» зависимостями через `yield`, внутри фоновых задач, потому что код после `yield` выполнялся после завершения фоновых задач.
+
+В FastAPI 0.106.0 это изменили, чтобы не удерживать ресурсы, пока ответ передаётся по сети.
+
+/// tip | Совет
+
+Кроме того, фоновая задача обычно — это самостоятельный фрагмент логики, который следует обрабатывать отдельно, со своими ресурсами (например, со своим подключением к базе данных).
+
+Так код, скорее всего, будет чище.
+
+///
+
+Если вы полагались на прежнее поведение, теперь ресурсы для фоновых задач следует создавать внутри самой фоновой задачи и использовать внутри неё только данные, которые не зависят от ресурсов зависимостей с `yield`.
+
+Например, вместо использования той же сессии базы данных, создайте новую сессию в фоновой задаче и получите объекты из базы данных с помощью этой новой сессии. И затем, вместо передачи объекта из базы данных параметром в функцию фоновой задачи, передавайте идентификатор этого объекта и заново получайте объект внутри функции фоновой задачи.
diff --git a/docs/ru/docs/advanced/advanced-python-types.md b/docs/ru/docs/advanced/advanced-python-types.md
new file mode 100644
index 0000000000000..62dcf8c4f1bd2
--- /dev/null
+++ b/docs/ru/docs/advanced/advanced-python-types.md
@@ -0,0 +1,61 @@
+# Продвинутые типы Python { #advanced-python-types }
+
+Ниже несколько дополнительных идей, которые могут быть полезны при работе с типами Python.
+
+## Использование `Union` или `Optional` { #using-union-or-optional }
+
+Если по какой-то причине ваш код не может использовать `|`, например, если это не аннотация типов, а что-то вроде `response_model=`, вместо вертикальной черты (`|`) можно использовать `Union` из `typing`.
+
+Например, вы можете объявить, что значение может быть `str` или `None`:
+
+```python
+from typing import Union
+
+
+def say_hi(name: Union[str, None]):
+ print(f"Hi {name}!")
+```
+
+В `typing` также есть сокращение, чтобы объявить, что значение может быть `None`, — `Optional`.
+
+Вот совет с моей очень субъективной точки зрения:
+
+- 🚨 Избегайте использования `Optional[SomeType]`
+- Вместо этого ✨ используйте **`Union[SomeType, None]`** ✨.
+
+Оба варианта эквивалентны и под капотом это одно и то же, но я бы рекомендовал `Union` вместо `Optional`, потому что слово «optional» может наводить на мысль, что значение необязательное, тогда как на самом деле это означает «значение может быть `None`», даже если оно не является необязательным и по-прежнему требуется.
+
+По-моему, `Union[SomeType, None]` более явно передаёт смысл.
+
+Речь только о словах и названиях. Но эти слова могут влиять на то, как вы и ваша команда думаете о коде.
+
+В качестве примера возьмём такую функцию:
+
+```python
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+ print(f"Hey {name}!")
+```
+
+Параметр `name` объявлен как `Optional[str]`, но он не является необязательным: вы не можете вызвать функцию без этого параметра:
+
+```Python
+say_hi() # О нет, это вызывает ошибку! 😱
+```
+
+Параметр `name` по-прежнему обязателен (не «optional»), так как у него нет значения по умолчанию. При этом `name` принимает `None` в качестве значения:
+
+```Python
+say_hi(name=None) # Это работает, None допустим 🎉
+```
+
+Хорошая новость: в большинстве случаев вы сможете просто использовать `|` для объявления объединений типов:
+
+```python
+def say_hi(name: str | None):
+ print(f"Hey {name}!")
+```
+
+Так что обычно вам не о чем переживать из‑за названий вроде `Optional` и `Union`. 😎
diff --git a/docs/ru/docs/advanced/async-tests.md b/docs/ru/docs/advanced/async-tests.md
new file mode 100644
index 0000000000000..1c0b888cc9eab
--- /dev/null
+++ b/docs/ru/docs/advanced/async-tests.md
@@ -0,0 +1,99 @@
+# Асинхронное тестирование { #async-tests }
+
+Вы уже видели как тестировать **FastAPI** приложение, используя имеющийся класс `TestClient`. К этому моменту вы видели только как писать тесты в синхронном стиле без использования `async` функций.
+
+Возможность использования асинхронных функций в ваших тестах может быть полезнa, когда, например, вы асинхронно обращаетесь к вашей базе данных. Представьте, что вы хотите отправить запросы в ваше FastAPI приложение, а затем при помощи асинхронной библиотеки для работы с базой данных удостовериться, что ваш бекэнд корректно записал данные в базу данных.
+
+Давайте рассмотрим, как мы можем это реализовать.
+
+## pytest.mark.anyio { #pytest-mark-anyio }
+
+Если мы хотим вызывать асинхронные функции в наших тестах, то наши тестовые функции должны быть асинхронными. AnyIO предоставляет для этого отличный плагин, который позволяет нам указывать, какие тестовые функции должны вызываться асинхронно.
+
+## HTTPX { #httpx }
+
+Даже если **FastAPI** приложение использует обычные функции `def` вместо `async def`, это все равно `async` приложение 'под капотом'.
+
+Чтобы работать с асинхронным FastAPI приложением в ваших обычных тестовых функциях `def`, используя стандартный pytest, `TestClient` внутри себя делает некоторую магию. Но эта магия перестает работать, когда мы используем его внутри асинхронных функций. Запуская наши тесты асинхронно, мы больше не можем использовать `TestClient` внутри наших тестовых функций.
+
+`TestClient` основан на [HTTPX](https://www.python-httpx.org), и, к счастью, мы можем использовать его (`HTTPX`) напрямую для тестирования API.
+
+## Пример { #example }
+
+В качестве простого примера, давайте рассмотрим файловую структуру, схожую с описанной в [Большие приложения](../tutorial/bigger-applications.md) и [Тестирование](../tutorial/testing.md):
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+Файл `main.py`:
+
+{* ../../docs_src/async_tests/app_a_py310/main.py *}
+
+Файл `test_main.py` содержит тесты для `main.py`, теперь он может выглядеть так:
+
+{* ../../docs_src/async_tests/app_a_py310/test_main.py *}
+
+## Запуск тестов { #run-it }
+
+Вы можете запустить свои тесты как обычно:
+
+
+
+А вот если открыть интерфейс документации по «официальному» URL через прокси на порту `9999`, по `/api/v1/docs`, всё работает корректно! 🎉
+
+Проверьте по адресу [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs):
+
+
+
+Именно как и хотелось. ✔️
+
+Это потому, что FastAPI использует `root_path`, чтобы создать в OpenAPI сервер по умолчанию с URL из `root_path`.
+
+## Дополнительные серверы { #additional-servers }
+
+/// warning | Предупреждение
+
+Это более продвинутый сценарий. Можно пропустить.
+
+///
+
+По умолчанию FastAPI создаёт в схеме OpenAPI `server` с URL из `root_path`.
+
+Но вы также можете указать дополнительные `servers`, например, если хотите, чтобы один и тот же интерфейс документации работал и со стейджингом, и с продакшн.
+
+Если вы передадите свой список `servers` и при этом задан `root_path` (потому что ваш API работает за прокси), FastAPI вставит «server» с этим `root_path` в начало списка.
+
+Например:
+
+{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}
+
+Будет сгенерирована схема OpenAPI примерно такая:
+
+```JSON hl_lines="5-7"
+{
+ "openapi": "3.1.0",
+ // Здесь ещё что-то
+ "servers": [
+ {
+ "url": "/api/v1"
+ },
+ {
+ "url": "https://stag.example.com",
+ "description": "Staging environment"
+ },
+ {
+ "url": "https://prod.example.com",
+ "description": "Production environment"
+ }
+ ],
+ "paths": {
+ // Здесь ещё что-то
+ }
+}
+```
+
+/// tip | Совет
+
+Обратите внимание на автоматически добавленный сервер с `url` равным `/api/v1`, взятым из `root_path`.
+
+///
+
+В интерфейсе документации по адресу [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs) это будет выглядеть так:
+
+
+
+/// tip | Совет
+
+Интерфейс документации будет взаимодействовать с сервером, который вы выберете.
+
+///
+
+/// note | Технические детали
+
+Свойство `servers` в спецификации OpenAPI является необязательным.
+
+Если вы не укажете параметр `servers`, а `root_path` равен `/`, то свойство `servers` в сгенерированной схеме OpenAPI по умолчанию будет опущено. Это эквивалентно серверу со значением `url` равным `/`.
+
+///
+
+### Отключить автоматическое добавление сервера из `root_path` { #disable-automatic-server-from-root-path }
+
+Если вы не хотите, чтобы FastAPI добавлял автоматический сервер, используя `root_path`, укажите параметр `root_path_in_servers=False`:
+
+{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}
+
+и тогда этот сервер не будет добавлен в схему OpenAPI.
+
+## Монтирование вложенного приложения { #mounting-a-sub-application }
+
+Если вам нужно смонтировать вложенное приложение (как описано в [Вложенные приложения — монтирование](sub-applications.md)), и при этом вы используете прокси с `root_path`, делайте это обычным образом — всё будет работать, как ожидается.
+
+FastAPI умно использует `root_path` внутри, так что всё просто работает. ✨
diff --git a/docs/ru/docs/advanced/custom-response.md b/docs/ru/docs/advanced/custom-response.md
new file mode 100644
index 0000000000000..fdfe2c5498828
--- /dev/null
+++ b/docs/ru/docs/advanced/custom-response.md
@@ -0,0 +1,272 @@
+# Кастомные ответы — HTML, поток, файл и другие { #custom-response-html-stream-file-others }
+
+По умолчанию **FastAPI** возвращает ответы в формате JSON.
+
+Вы можете переопределить это, вернув `Response` напрямую, как показано в разделе [Вернуть Response напрямую](response-directly.md).
+
+Но если вы возвращаете `Response` напрямую (или любой его подкласс, например `JSONResponse`), данные не будут автоматически преобразованы (даже если вы объявили `response_model`), и документация не будет автоматически сгенерирована (например, со специфичным «типом содержимого» в HTTP-заголовке `Content-Type` как частью сгенерированного OpenAPI).
+
+Но вы также можете объявить `Response`, который хотите использовать (например, любой подкласс `Response`), в декораторе операции пути, указав параметр `response_class`.
+
+Содержимое, которое вы возвращаете из своей функции-обработчика пути, будет помещено внутрь этого `Response`.
+
+/// note | Примечание
+
+Если вы используете класс ответа без типа содержимого, FastAPI будет ожидать, что у вашего ответа нет содержимого, поэтому он не будет документировать формат ответа в сгенерированной документации OpenAPI.
+
+///
+
+## JSON-ответы { #json-responses }
+
+По умолчанию FastAPI возвращает ответы в формате JSON.
+
+Если вы объявите [Модель ответа](../tutorial/response-model.md), FastAPI использует её для сериализации данных в JSON с помощью Pydantic.
+
+Если вы не объявите модель ответа, FastAPI использует `jsonable_encoder`, описанный в разделе [JSON-совместимый энкодер](../tutorial/encoder.md), и поместит результат в `JSONResponse`.
+
+Если вы объявите `response_class` с JSON типом содержимого (`application/json`), как в случае с `JSONResponse`, данные, которые вы возвращаете, будут автоматически преобразованы (и отфильтрованы) любой Pydantic-моделью ответа (`response_model`), объявленной вами в декораторе операции пути. Но данные не будут сериализованы в JSON-байты через Pydantic; вместо этого они будут преобразованы с помощью `jsonable_encoder`, а затем переданы в класс `JSONResponse`, который сериализует их в байты, используя стандартную JSON-библиотеку Python.
+
+### Производительность JSON { #json-performance }
+
+Коротко: если вам нужна максимальная производительность, используйте [Модель ответа](../tutorial/response-model.md) и не объявляйте `response_class` в декораторе операции пути.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py ln[15:17] hl[16] *}
+
+## HTML-ответ { #html-response }
+
+Чтобы вернуть ответ с HTML напрямую из **FastAPI**, используйте `HTMLResponse`.
+
+- Импортируйте `HTMLResponse`.
+- Передайте `HTMLResponse` в параметр `response_class` вашего декоратора операции пути.
+
+{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}
+
+/// info | Информация
+
+Параметр `response_class` также используется для указания «типа содержимого» ответа.
+
+В этом случае HTTP-заголовок `Content-Type` будет установлен в `text/html`.
+
+И это будет задокументировано как таковое в OpenAPI.
+
+///
+
+### Вернуть `Response` { #return-a-response }
+
+Как показано в разделе [Вернуть Response напрямую](response-directly.md), вы также можете переопределить ответ прямо в своей операции пути, просто вернув его.
+
+Тот же пример сверху, возвращающий `HTMLResponse`, может выглядеть так:
+
+{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}
+
+/// warning | Предупреждение
+
+`Response`, возвращённый напрямую вашей функцией-обработчиком пути, не будет задокументирован в OpenAPI (например, `Content-Type` не будет задокументирован) и не будет виден в автоматически сгенерированной интерактивной документации.
+
+///
+
+/// info | Информация
+
+Разумеется, фактический заголовок `Content-Type`, статус-код и т.д. возьмутся из объекта `Response`, который вы вернули.
+
+///
+
+### Задокументировать в OpenAPI и переопределить `Response` { #document-in-openapi-and-override-response }
+
+Если вы хотите переопределить ответ внутри функции, но при этом задокументировать «тип содержимого» в OpenAPI, вы можете использовать параметр `response_class` И вернуть объект `Response`.
+
+Тогда `response_class` будет использоваться только для документирования *операции пути* в OpenAPI, а ваш `Response` будет использован как есть.
+
+#### Вернуть `HTMLResponse` напрямую { #return-an-htmlresponse-directly }
+
+Например, это может быть что-то вроде:
+
+{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}
+
+В этом примере функция `generate_html_response()` уже генерирует и возвращает `Response` вместо возврата HTML в `str`.
+
+Возвращая результат вызова `generate_html_response()`, вы уже возвращаете `Response`, который переопределит поведение **FastAPI** по умолчанию.
+
+Но поскольку вы также передали `HTMLResponse` в `response_class`, **FastAPI** будет знать, как задокументировать это в OpenAPI и интерактивной документации как HTML с `text/html`:
+
+
+
+## Доступные ответы { #available-responses }
+
+Ниже перечислены некоторые доступные классы ответов.
+
+Учтите, что вы можете использовать `Response`, чтобы вернуть что угодно ещё, или даже создать собственный подкласс.
+
+/// note | Технические детали
+
+Вы также могли бы использовать `from starlette.responses import HTMLResponse`.
+
+**FastAPI** предоставляет те же `starlette.responses` как `fastapi.responses` для вашего удобства как разработчика. Но большинство доступных классов ответов приходят непосредственно из Starlette.
+
+///
+
+### `Response` { #response }
+
+Базовый класс `Response`, от него наследуются все остальные ответы.
+
+Его можно возвращать напрямую.
+
+Он принимает следующие параметры:
+
+- `content` — `str` или `bytes`.
+- `status_code` — целое число, HTTP статус-код.
+- `headers` — словарь строк.
+- `media_type` — строка, задающая тип содержимого. Например, `"text/html"`.
+
+FastAPI (фактически Starlette) автоматически добавит заголовок Content-Length. Также будет добавлен заголовок Content-Type, основанный на `media_type` и с добавлением charset для текстовых типов.
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+### `HTMLResponse` { #htmlresponse }
+
+Принимает текст или байты и возвращает HTML-ответ, как описано выше.
+
+### `PlainTextResponse` { #plaintextresponse }
+
+Принимает текст или байты и возвращает ответ в виде простого текста.
+
+{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}
+
+### `JSONResponse` { #jsonresponse }
+
+Принимает данные и возвращает ответ, кодированный как `application/json`.
+
+Это ответ по умолчанию, используемый в **FastAPI**, как было сказано выше.
+
+/// note | Технические детали
+
+Но если вы объявите модель ответа или тип возвращаемого значения, они будут использованы напрямую для сериализации данных в JSON, и ответ с корректным типом содержимого для JSON будет возвращён напрямую, без использования класса `JSONResponse`.
+
+Это идеальный способ получить наилучшую производительность.
+
+///
+
+### `RedirectResponse` { #redirectresponse }
+
+Возвращает HTTP-редирект. По умолчанию использует статус-код 307 (Temporary Redirect — временное перенаправление).
+
+Вы можете вернуть `RedirectResponse` напрямую:
+
+{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}
+
+---
+
+Или можно использовать его в параметре `response_class`:
+
+{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}
+
+Если вы сделаете так, то сможете возвращать URL напрямую из своей функции-обработчика пути.
+
+В этом случае будет использован статус-код по умолчанию для `RedirectResponse`, то есть `307`.
+
+---
+
+Также вы можете использовать параметр `status_code` в сочетании с параметром `response_class`:
+
+{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}
+
+### `StreamingResponse` { #streamingresponse }
+
+Принимает асинхронный генератор или обычный генератор/итератор (функцию с `yield`) и отправляет тело ответа потоково.
+
+{* ../../docs_src/custom_response/tutorial007_py310.py hl[3,16] *}
+
+/// note | Технические детали
+
+Задача `async` может быть отменена только при достижении `await`. Если `await` отсутствует, генератор (функция с `yield`) не может быть корректно отменён и может продолжить работу даже после запроса на отмену.
+
+Так как этому небольшому примеру не нужны операторы `await`, мы добавляем `await anyio.sleep(0)`, чтобы дать циклу событий возможность обработать отмену.
+
+Это ещё более важно для больших или бесконечных потоков.
+
+///
+
+/// tip | Совет
+
+Вместо того чтобы возвращать `StreamingResponse` напрямую, вероятно, лучше следовать стилю из раздела [Передача данных потоком](./stream-data.md) - так гораздо удобнее, и отмена обрабатывается «за кулисами».
+
+Если вы передаёте JSON Lines потоком, следуйте руководству [Поток JSON Lines](../tutorial/stream-json-lines.md).
+
+///
+
+### `FileResponse` { #fileresponse }
+
+Асинхронно отправляет файл как ответ.
+
+Для создания экземпляра принимает иной набор аргументов, чем другие типы ответов:
+
+- `path` — путь к файлу, который будет отправлен.
+- `headers` — любые дополнительные заголовки для включения, в виде словаря.
+- `media_type` — строка, задающая тип содержимого. Если не задан, для определения типа содержимого будет использовано имя файла или путь.
+- `filename` — если задан, будет включён в заголовок ответа `Content-Disposition`.
+
+Файловые ответы будут содержать соответствующие заголовки `Content-Length`, `Last-Modified` и `ETag`.
+
+{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}
+
+Вы также можете использовать параметр `response_class`:
+
+{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}
+
+В этом случае вы можете возвращать путь к файлу напрямую из своей функции-обработчика пути.
+
+## Пользовательский класс ответа { #custom-response-class }
+
+Вы можете создать собственный класс ответа, унаследовавшись от `Response`, и использовать его.
+
+Например, предположим, что вы хотите использовать [`orjson`](https://github.com/ijl/orjson) с некоторыми настройками.
+
+Скажем, вы хотите, чтобы возвращался отформатированный JSON с отступами, то есть хотите использовать опцию orjson `orjson.OPT_INDENT_2`.
+
+Вы могли бы создать `CustomORJSONResponse`. Главное, что вам нужно сделать — реализовать метод `Response.render(content)`, который возвращает содержимое как `bytes`:
+
+{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}
+
+Теперь вместо того, чтобы возвращать:
+
+```json
+{"message": "Hello World"}
+```
+
+...этот ответ вернёт:
+
+```json
+{
+ "message": "Hello World"
+}
+```
+
+Разумеется, вы наверняка найдёте гораздо более полезные способы воспользоваться этим, чем просто форматирование JSON. 😉
+
+### `orjson` или Модель ответа { #orjson-or-response-model }
+
+Если вы стремитесь увеличить производительность, вероятно, лучше использовать [Модель ответа](../tutorial/response-model.md), чем ответ на базе `orjson`.
+
+С моделью ответа FastAPI использует Pydantic для сериализации данных в JSON, без промежуточных шагов, таких как преобразование через `jsonable_encoder`, которое происходило бы в любом другом случае.
+
+А под капотом Pydantic использует те же базовые механизмы на Rust, что и `orjson`, для сериализации в JSON, так что с моделью ответа вы и так получите лучшую производительность.
+
+## Класс ответа по умолчанию { #default-response-class }
+
+При создании экземпляра класса **FastAPI** или `APIRouter` вы можете указать, какой класс ответа использовать по умолчанию.
+
+Параметр, который это определяет, — `default_response_class`.
+
+В примере ниже **FastAPI** будет использовать `HTMLResponse` по умолчанию во всех операциях пути, вместо JSON.
+
+{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}
+
+/// tip | Совет
+
+Вы по-прежнему можете переопределять `response_class` в операциях пути, как и раньше.
+
+///
+
+## Дополнительная документация { #additional-documentation }
+
+Вы также можете объявить тип содержимого и многие другие детали в OpenAPI с помощью `responses`: [Дополнительные ответы в OpenAPI](additional-responses.md).
diff --git a/docs/ru/docs/advanced/dataclasses.md b/docs/ru/docs/advanced/dataclasses.md
new file mode 100644
index 0000000000000..f9f8689b04948
--- /dev/null
+++ b/docs/ru/docs/advanced/dataclasses.md
@@ -0,0 +1,95 @@
+# Использование dataclasses { #using-dataclasses }
+
+FastAPI построен поверх **Pydantic**, и я показывал вам, как использовать Pydantic-модели для объявления HTTP-запросов и HTTP-ответов.
+
+Но FastAPI также поддерживает использование [`dataclasses`](https://docs.python.org/3/library/dataclasses.html) тем же способом:
+
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
+
+Это по-прежнему поддерживается благодаря **Pydantic**, так как в нём есть [встроенная поддержка `dataclasses`](https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel).
+
+Так что даже если в коде выше Pydantic не используется явно, FastAPI использует Pydantic, чтобы конвертировать стандартные dataclasses в собственный вариант dataclasses от Pydantic.
+
+И, конечно, поддерживаются те же возможности:
+
+- валидация данных
+- сериализация данных
+- документирование данных и т.д.
+
+Это работает так же, как с Pydantic-моделями. И на самом деле под капотом это достигается тем же образом, с использованием Pydantic.
+
+/// info | Информация
+
+Помните, что dataclasses не умеют всего того, что умеют Pydantic-модели.
+
+Поэтому вам всё ещё может потребоваться использовать Pydantic-модели.
+
+Но если у вас уже есть набор dataclasses, это полезный приём — задействовать их для веб-API на FastAPI. 🤓
+
+///
+
+## Dataclasses в `response_model` { #dataclasses-in-response-model }
+
+Вы также можете использовать `dataclasses` в параметре `response_model`:
+
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
+
+Этот dataclass будет автоматически преобразован в Pydantic dataclass.
+
+Таким образом, его схема появится в интерфейсе документации API:
+
+
+
+## Dataclasses во вложенных структурах данных { #dataclasses-in-nested-data-structures }
+
+Вы также можете комбинировать `dataclasses` с другими аннотациями типов, чтобы создавать вложенные структуры данных.
+
+В некоторых случаях вам всё же может понадобиться использовать версию `dataclasses` из Pydantic. Например, если у вас возникают ошибки с автоматически генерируемой документацией API.
+
+В таком случае вы можете просто заменить стандартные `dataclasses` на `pydantic.dataclasses`, которая является полностью совместимой заменой (drop-in replacement):
+
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+
+1. Мы по-прежнему импортируем `field` из стандартных `dataclasses`.
+
+2. `pydantic.dataclasses` — полностью совместимая замена (drop-in replacement) для `dataclasses`.
+
+3. Dataclass `Author` содержит список dataclass `Item`.
+
+4. Dataclass `Author` используется в параметре `response_model`.
+
+5. Вы можете использовать и другие стандартные аннотации типов вместе с dataclasses в качестве тела запроса.
+
+ В этом случае это список dataclass `Item`.
+
+6. Здесь мы возвращаем словарь, содержащий `items`, который является списком dataclass.
+
+ FastAPI по-прежнему способен сериализовать данные в JSON.
+
+7. Здесь `response_model` использует аннотацию типа — список dataclass `Author`.
+
+ Снова, вы можете комбинировать `dataclasses` со стандартными аннотациями типов.
+
+8. Обратите внимание, что эта *функция-обработчик пути* использует обычный `def` вместо `async def`.
+
+ Как и всегда в FastAPI, вы можете сочетать `def` и `async def` по необходимости.
+
+ Если хотите освежить в памяти, когда что использовать, посмотрите раздел _"Нет времени?"_ в документации про [`async` и `await`](../async.md#in-a-hurry).
+
+9. Эта *функция-обработчик пути* возвращает не dataclasses (хотя могла бы), а список словарей с внутренними данными.
+
+ FastAPI использует параметр `response_model` (в котором заданы dataclasses), чтобы преобразовать HTTP-ответ.
+
+Вы можете комбинировать `dataclasses` с другими аннотациями типов множеством способов, чтобы формировать сложные структуры данных.
+
+Смотрите подсказки в коде выше, чтобы увидеть более конкретные детали.
+
+## Узнать больше { #learn-more }
+
+Вы также можете комбинировать `dataclasses` с другими Pydantic-моделями, наследоваться от них, включать их в свои модели и т.д.
+
+Чтобы узнать больше, посмотрите [документацию Pydantic о dataclasses](https://docs.pydantic.dev/latest/concepts/dataclasses/).
+
+## Версия { #version }
+
+Доступно начиная с версии FastAPI `0.67.0`. 🔖
diff --git a/docs/ru/docs/advanced/events.md b/docs/ru/docs/advanced/events.md
new file mode 100644
index 0000000000000..464bba93e97a7
--- /dev/null
+++ b/docs/ru/docs/advanced/events.md
@@ -0,0 +1,165 @@
+# События lifespan { #lifespan-events }
+
+Вы можете определить логику (код), которую нужно выполнить перед тем, как приложение начнет запускаться. Это означает, что этот код будет выполнен один раз, перед тем как приложение начнет получать HTTP-запросы.
+
+Аналогично, вы можете определить логику (код), которую нужно выполнить, когда приложение завершает работу. В этом случае код будет выполнен один раз, после обработки, возможно, многих запросов.
+
+Поскольку этот код выполняется до того, как приложение начинает принимать запросы, и сразу после того, как оно заканчивает их обрабатывать, он охватывает весь lifespan (жизненный цикл) приложения (слово «lifespan» станет важным через секунду 😉).
+
+Это может быть очень полезно для настройки ресурсов, которые нужны для всего приложения, которые разделяются между запросами и/или которые нужно затем очистить. Например, пул подключений к базе данных или загрузка общей модели Машинного обучения.
+
+## Вариант использования { #use-case }
+
+Начнем с примера варианта использования, а затем посмотрим, как это решить.
+
+Представим, что у вас есть несколько моделей Машинного обучения, которые вы хотите использовать для обработки запросов. 🤖
+
+Эти же модели разделяются между запросами, то есть это не одна модель на запрос, не одна на пользователя и т.п.
+
+Представим, что загрузка модели может занимать довольно много времени, потому что ей нужно прочитать много данных с диска. Поэтому вы не хотите делать это для каждого запроса.
+
+Вы могли бы загрузить её на верхнем уровне модуля/файла, но это означало бы, что модель загружается даже если вы просто запускаете простой автоматический тест; тогда этот тест будет медленным, так как ему придется ждать загрузки модели перед запуском независимой части кода.
+
+Именно это мы и решим: давайте загружать модель перед тем, как начнётся обработка запросов, но только непосредственно перед тем, как приложение начнет принимать запросы, а не во время загрузки кода.
+
+## Lifespan { #lifespan }
+
+Вы можете определить логику для startup и shutdown, используя параметр `lifespan` приложения `FastAPI` и «менеджер контекста» (через секунду покажу что это).
+
+Начнем с примера, а затем разберём его подробнее.
+
+Мы создаём асинхронную функцию `lifespan()` с `yield` примерно так:
+
+{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}
+
+Здесь мы симулируем дорогую операцию startup по загрузке модели, помещая (фиктивную) функцию модели в словарь с моделями Машинного обучения до `yield`. Этот код будет выполнен до того, как приложение начнет принимать запросы, во время startup.
+
+А затем сразу после `yield` мы выгружаем модель. Этот код будет выполнен после того, как приложение закончит обрабатывать запросы, непосредственно перед shutdown. Это может, например, освободить ресурсы, такие как память или GPU.
+
+/// tip | Совет
+
+`shutdown` произойдёт, когда вы останавливаете приложение.
+
+Возможно, вам нужно запустить новую версию, или вы просто устали от него. 🤷
+
+///
+
+### Функция lifespan { #lifespan-function }
+
+Первое, на что стоит обратить внимание, — мы определяем асинхронную функцию с `yield`. Это очень похоже на Зависимости с `yield`.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}
+
+Первая часть функции, до `yield`, будет выполнена до запуска приложения.
+
+А часть после `yield` будет выполнена после завершения работы приложения.
+
+### Асинхронный менеджер контекста { #async-context-manager }
+
+Если присмотреться, функция декорирована `@asynccontextmanager`.
+
+Это превращает функцию в «асинхронный менеджер контекста».
+
+{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}
+
+Менеджер контекста в Python — это то, что можно использовать в операторе `with`. Например, `open()` можно использовать как менеджер контекста:
+
+```Python
+with open("file.txt") as file:
+ file.read()
+```
+
+В последних версиях Python есть также асинхронный менеджер контекста. Его используют с `async with`:
+
+```Python
+async with lifespan(app):
+ await do_stuff()
+```
+
+Когда вы создаёте менеджер контекста или асинхронный менеджер контекста, как выше, он перед входом в блок `with` выполнит код до `yield`, а после выхода из блока `with` выполнит код после `yield`.
+
+В нашем примере выше мы не используем его напрямую, а передаём его в FastAPI, чтобы он использовал его сам.
+
+Параметр `lifespan` приложения `FastAPI` принимает асинхронный менеджер контекста, поэтому мы можем передать ему наш новый асинхронный менеджер контекста `lifespan`.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[22] *}
+
+## Альтернативные события (устаревшие) { #alternative-events-deprecated }
+
+/// warning | Предупреждение
+
+Рекомендуемый способ обрабатывать startup и shutdown — использовать параметр `lifespan` приложения `FastAPI`, как описано выше. Если вы укажете параметр `lifespan`, обработчики событий `startup` и `shutdown` больше вызываться не будут. Либо всё через `lifespan`, либо всё через события — не одновременно.
+
+Эту часть, скорее всего, можно пропустить.
+
+///
+
+Есть альтернативный способ определить логику, которую нужно выполнить во время startup и во время shutdown.
+
+Вы можете определить обработчики событий (функции), которые нужно выполнить до старта приложения или при его завершении.
+
+Эти функции можно объявить с `async def` или обычным `def`.
+
+### Событие `startup` { #startup-event }
+
+Чтобы добавить функцию, которую нужно запустить до старта приложения, объявите её как обработчик события `"startup"`:
+
+{* ../../docs_src/events/tutorial001_py310.py hl[8] *}
+
+В этом случае функция-обработчик события `startup` инициализирует «базу данных» items (это просто `dict`) некоторыми значениями.
+
+Вы можете добавить более одного обработчика события.
+
+И ваше приложение не начнет принимать запросы, пока все обработчики события `startup` не завершатся.
+
+### Событие `shutdown` { #shutdown-event }
+
+Чтобы добавить функцию, которую нужно запустить при завершении работы приложения, объявите её как обработчик события `"shutdown"`:
+
+{* ../../docs_src/events/tutorial002_py310.py hl[6] *}
+
+Здесь функция-обработчик события `shutdown` запишет строку текста `"Application shutdown"` в файл `log.txt`.
+
+/// info | Информация
+
+В функции `open()` параметр `mode="a"` означает «добавление» (append), то есть строка будет добавлена в конец файла, без перезаписи предыдущего содержимого.
+
+///
+
+/// tip | Совет
+
+Обратите внимание, что в этом случае мы используем стандартную Python-функцию `open()`, которая взаимодействует с файлом.
+
+То есть это I/O (ввод/вывод), требующий «ожидания» записи на диск.
+
+Но `open()` не использует `async` и `await`.
+
+Поэтому мы объявляем обработчик события обычным `def` вместо `async def`.
+
+///
+
+### `startup` и `shutdown` вместе { #startup-and-shutdown-together }
+
+С высокой вероятностью логика для вашего startup и shutdown связана: вы можете хотеть что-то запустить, а затем завершить, получить ресурс, а затем освободить его и т.д.
+
+Делать это в отдельных функциях, которые не разделяют общую логику или переменные, сложнее, так как придётся хранить значения в глобальных переменных или использовать похожие приёмы.
+
+Поэтому теперь рекомендуется использовать `lifespan`, как описано выше.
+
+## Технические детали { #technical-details }
+
+Немного технических подробностей для любопытных умников. 🤓
+
+Под капотом, в ASGI-технической спецификации, это часть [Протокола Lifespan](https://asgi.readthedocs.io/en/latest/specs/lifespan.html), и он определяет события `startup` и `shutdown`.
+
+/// info | Информация
+
+Вы можете прочитать больше про обработчики `lifespan` в Starlette в [документации Starlette по Lifespan](https://www.starlette.dev/lifespan/).
+
+Включая то, как работать с состоянием lifespan, которое можно использовать в других частях вашего кода.
+
+///
+
+## Подприложения { #sub-applications }
+
+🚨 Имейте в виду, что эти события lifespan (startup и shutdown) будут выполнены только для основного приложения, а не для [Подприложения — Mounts](sub-applications.md).
diff --git a/docs/ru/docs/advanced/generate-clients.md b/docs/ru/docs/advanced/generate-clients.md
new file mode 100644
index 0000000000000..75bd7c47c413a
--- /dev/null
+++ b/docs/ru/docs/advanced/generate-clients.md
@@ -0,0 +1,208 @@
+# Генерация SDK { #generating-sdks }
+
+Поскольку **FastAPI** основан на спецификации **OpenAPI**, его API можно описать в стандартном формате, понятном множеству инструментов.
+
+Это упрощает генерацию актуальной **документации**, клиентских библиотек (**SDKs**) на разных языках, а также **тестирования** или **воркфлоу автоматизации**, которые остаются синхронизированными с вашим кодом.
+
+В этом руководстве вы узнаете, как сгенерировать **TypeScript SDK** для вашего бэкенда на FastAPI.
+
+## Генераторы SDK с открытым исходным кодом { #open-source-sdk-generators }
+
+Гибкий вариант — [OpenAPI Generator](https://openapi-generator.tech/), который поддерживает **многие языки программирования** и умеет генерировать SDK из вашей спецификации OpenAPI.
+
+Для **TypeScript‑клиентов** [Hey API](https://heyapi.dev/) — специализированное решение, обеспечивающее оптимальный опыт для экосистемы TypeScript.
+
+Больше генераторов SDK можно найти на [OpenAPI.Tools](https://openapi.tools/#sdk).
+
+/// tip | Совет
+
+FastAPI автоматически генерирует спецификации **OpenAPI 3.1**, поэтому любой используемый инструмент должен поддерживать эту версию.
+
+///
+
+## Генераторы SDK от спонсоров FastAPI { #sdk-generators-from-fastapi-sponsors }
+
+В этом разделе представлены решения с **венчурной поддержкой** и **поддержкой компаний** от компаний, которые спонсируют FastAPI. Эти продукты предоставляют **дополнительные возможности** и **интеграции** сверх высококачественно генерируемых SDK.
+
+Благодаря ✨ [**спонсорству FastAPI**](../help-fastapi.md#sponsor-the-author) ✨ эти компании помогают обеспечивать, чтобы фреймворк и его **экосистема** оставались здоровыми и **устойчивыми**.
+
+Их спонсорство также демонстрирует серьёзную приверженность **сообществу** FastAPI (вам), показывая, что им важно не только предоставлять **отличный сервис**, но и поддерживать **надёжный и процветающий фреймворк** FastAPI. 🙇
+
+Например, вы можете попробовать:
+
+* [Speakeasy](https://speakeasy.com/editor?utm_source=fastapi+repo&utm_medium=github+sponsorship)
+* [Stainless](https://www.stainless.com/?utm_source=fastapi&utm_medium=referral)
+* [liblab](https://developers.liblab.com/tutorials/sdk-for-fastapi?utm_source=fastapi)
+
+Некоторые из этих решений также могут быть open source или иметь бесплатные тарифы, так что вы сможете попробовать их без финансовых затрат. Другие коммерческие генераторы SDK доступны и их можно найти онлайн. 🤓
+
+## Создать TypeScript SDK { #create-a-typescript-sdk }
+
+Начнём с простого приложения FastAPI:
+
+{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}
+
+Обратите внимание, что *операции пути (обработчики пути)* определяют модели, которые они используют для полезной нагрузки запроса и полезной нагрузки ответа, с помощью моделей `Item` и `ResponseMessage`.
+
+### Документация API { #api-docs }
+
+Если перейти на `/docs`, вы увидите **схемы** данных, отправляемых в запросах и принимаемых в ответах:
+
+
+
+Вы видите эти схемы, потому что они были объявлены с моделями в приложении.
+
+Эта информация доступна в **схеме OpenAPI** приложения и затем отображается в документации API.
+
+Та же информация из моделей, включённая в OpenAPI, может использоваться для **генерации клиентского кода**.
+
+### Hey API { #hey-api }
+
+Как только у нас есть приложение FastAPI с моделями, мы можем использовать Hey API для генерации TypeScript‑клиента. Самый быстрый способ сделать это — через npx.
+
+```sh
+npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
+```
+
+Это сгенерирует TypeScript SDK в `./src/client`.
+
+Вы можете узнать, как [установить `@hey-api/openapi-ts`](https://heyapi.dev/openapi-ts/get-started) и почитать о [сгенерированном результате](https://heyapi.dev/openapi-ts/output) на их сайте.
+
+### Использование SDK { #using-the-sdk }
+
+Теперь вы можете импортировать и использовать клиентский код. Это может выглядеть так, обратите внимание, что вы получаете автозавершение для методов:
+
+
+
+Вы также получите автозавершение для отправляемой полезной нагрузки:
+
+
+
+/// tip | Совет
+
+Обратите внимание на автозавершение для `name` и `price`, это было определено в приложении FastAPI, в модели `Item`.
+
+///
+
+Вы получите ошибки прямо в редакторе для отправляемых данных:
+
+
+
+Объект ответа также будет иметь автозавершение:
+
+
+
+## Приложение FastAPI с тегами { #fastapi-app-with-tags }
+
+Во многих случаях ваше приложение FastAPI будет больше, и вы, вероятно, будете использовать теги, чтобы разделять разные группы *операций пути*.
+
+Например, у вас может быть раздел для **items** и другой раздел для **users**, и они могут быть разделены тегами:
+
+{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}
+
+### Генерация TypeScript‑клиента с тегами { #generate-a-typescript-client-with-tags }
+
+Если вы генерируете клиент для приложения FastAPI с использованием тегов, обычно клиентский код также будет разделён по тегам.
+
+Таким образом вы сможете иметь всё правильно упорядоченным и сгруппированным в клиентском коде:
+
+
+
+В этом случае у вас есть:
+
+* `ItemsService`
+* `UsersService`
+
+### Имена методов клиента { #client-method-names }
+
+Сейчас сгенерированные имена методов вроде `createItemItemsPost` выглядят не очень аккуратно:
+
+```TypeScript
+ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
+```
+
+...это потому, что генератор клиента использует внутренний **ID операции** OpenAPI для каждой *операции пути*.
+
+OpenAPI требует, чтобы каждый ID операции был уникален среди всех *операций пути*, поэтому FastAPI использует **имя функции**, **путь** и **HTTP‑метод/операцию** для генерации этого ID операции, так как таким образом можно гарантировать уникальность ID операций.
+
+Но далее я покажу, как это улучшить. 🤓
+
+## Пользовательские ID операций и лучшие имена методов { #custom-operation-ids-and-better-method-names }
+
+Вы можете **изменить** способ **генерации** этих ID операций, чтобы сделать их проще, а имена методов в клиентах — **более простыми**.
+
+В этом случае вам нужно будет обеспечить, чтобы каждый ID операции был **уникальным** другим способом.
+
+Например, вы можете гарантировать, что у каждой *операции пути* есть тег, и затем генерировать ID операции на основе **тега** и **имени** *операции пути* (имени функции).
+
+### Пользовательская функция генерации уникального ID { #custom-generate-unique-id-function }
+
+FastAPI использует **уникальный ID** для каждой *операции пути*, который применяется для **ID операции**, а также для имён любых необходимых пользовательских моделей запросов или ответов.
+
+Вы можете кастомизировать эту функцию. Она принимает `APIRoute` и возвращает строку.
+
+Например, здесь берётся первый тег (скорее всего у вас один тег) и имя *операции пути* (имя функции).
+
+Затем вы можете передать эту пользовательскую функцию в **FastAPI** через параметр `generate_unique_id_function`:
+
+{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}
+
+### Генерация TypeScript‑клиента с пользовательскими ID операций { #generate-a-typescript-client-with-custom-operation-ids }
+
+Теперь, если снова сгенерировать клиент, вы увидите, что имена методов улучшились:
+
+
+
+Как видите, теперь имена методов содержат тег, а затем имя функции; больше они не включают информацию из URL‑пути и HTTP‑операции.
+
+### Предобработка спецификации OpenAPI для генератора клиента { #preprocess-the-openapi-specification-for-the-client-generator }
+
+В сгенерированном коде всё ещё есть **дублирующаяся информация**.
+
+Мы уже знаем, что этот метод относится к **items**, потому что это слово есть в `ItemsService` (взято из тега), но при этом имя тега всё ещё добавлено префиксом к имени метода. 😕
+
+Скорее всего мы захотим оставить это в OpenAPI в целом, так как это гарантирует, что ID операций будут **уникальны**.
+
+Но для сгенерированного клиента мы можем **модифицировать** ID операций OpenAPI непосредственно перед генерацией клиентов, чтобы сделать имена методов более приятными и **чистыми**.
+
+Мы можем скачать OpenAPI JSON в файл `openapi.json`, а затем **убрать этот префикс‑тег** таким скриптом:
+
+{* ../../docs_src/generate_clients/tutorial004_py310.py *}
+
+//// tab | Node.js
+
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
+```
+
+////
+
+После этого ID операций будут переименованы с чего‑то вроде `items-get_items` просто в `get_items`, и генератор клиента сможет создавать более простые имена методов.
+
+### Генерация TypeScript‑клиента с предобработанным OpenAPI { #generate-a-typescript-client-with-the-preprocessed-openapi }
+
+Так как конечный результат теперь в файле `openapi.json`, нужно обновить входное расположение:
+
+```sh
+npx @hey-api/openapi-ts -i ./openapi.json -o src/client
+```
+
+После генерации нового клиента у вас будут **чистые имена методов**, со всем **автозавершением**, **ошибками прямо в редакторе** и т.д.:
+
+
+
+## Преимущества { #benefits }
+
+При использовании автоматически сгенерированных клиентов вы получите **автозавершение** для:
+
+* Методов.
+* Данных запроса — в теле запроса, query‑параметрах и т.д.
+* Данных ответа.
+
+У вас также будут **ошибки прямо в редакторе** для всего.
+
+И каждый раз, когда вы обновляете код бэкенда и **перегенерируете** фронтенд, в нём появятся новые *операции пути* как методы, старые будут удалены, а любые другие изменения отразятся в сгенерированном коде. 🤓
+
+Это также означает, что если что‑то изменилось, это будет **отражено** в клиентском коде автоматически. И если вы **соберёте** клиент, он завершится с ошибкой, если где‑то есть **несоответствие** в используемых данных.
+
+Таким образом, вы **обнаружите многие ошибки** очень рано в цикле разработки, вместо того чтобы ждать, когда ошибки проявятся у конечных пользователей в продакшн, и затем пытаться отладить, в чём проблема. ✨
diff --git a/docs/ru/docs/advanced/index.md b/docs/ru/docs/advanced/index.md
new file mode 100644
index 0000000000000..6cb92dd004958
--- /dev/null
+++ b/docs/ru/docs/advanced/index.md
@@ -0,0 +1,21 @@
+# Расширенное руководство пользователя { #advanced-user-guide }
+
+## Дополнительные возможности { #additional-features }
+
+Основное [Учебник - Руководство пользователя](../tutorial/index.md) должно быть достаточно, чтобы познакомить вас со всеми основными функциями **FastAPI**.
+
+В следующих разделах вы увидите другие варианты, конфигурации и дополнительные возможности.
+
+/// tip | Совет
+
+Следующие разделы **не обязательно являются "продвинутыми"**.
+
+И вполне возможно, что для вашего случая использования решение находится в одном из них.
+
+///
+
+## Сначала прочитайте Учебник - Руководство пользователя { #read-the-tutorial-first }
+
+Вы все еще можете использовать большинство функций **FastAPI** со знаниями из [Учебник - Руководство пользователя](../tutorial/index.md).
+
+И следующие разделы предполагают, что вы уже прочитали его, и предполагают, что вы знаете эти основные идеи.
diff --git a/docs/ru/docs/advanced/json-base64-bytes.md b/docs/ru/docs/advanced/json-base64-bytes.md
new file mode 100644
index 0000000000000..390dd17fa1ade
--- /dev/null
+++ b/docs/ru/docs/advanced/json-base64-bytes.md
@@ -0,0 +1,63 @@
+# JSON с байтами в Base64 { #json-with-bytes-as-base64 }
+
+Если вашему приложению нужно принимать и отправлять JSON-данные, но при этом необходимо включать в них бинарные данные, вы можете кодировать их в base64.
+
+## Base64 и файлы { #base64-vs-files }
+
+Сначала рассмотрите возможность использовать [Файлы в запросе](../tutorial/request-files.md) для загрузки бинарных данных и [Пользовательский HTTP-ответ — FileResponse](./custom-response.md#fileresponse--fileresponse-) для отправки бинарных данных вместо кодирования их в JSON.
+
+JSON может содержать только строки в кодировке UTF-8, поэтому он не может содержать «сырые» байты.
+
+Base64 может кодировать бинарные данные в строки, но для этого используется больше символов, чем в исходных бинарных данных, поэтому обычно это менее эффективно, чем обычные файлы.
+
+Используйте base64 только если вам действительно нужно включать бинарные данные в JSON и вы не можете использовать файлы для этого.
+
+## Pydantic `bytes` { #pydantic-bytes }
+
+Вы можете объявить Pydantic-модель с полями `bytes`, а затем использовать `val_json_bytes` в конфиге модели, чтобы указать использовать base64 для валидации входящих JSON-данных; как часть этой валидации строка base64 будет декодирована в байты.
+
+{* ../../docs_src/json_base64_bytes/tutorial001_py310.py ln[1:9,29:35] hl[9] *}
+
+Если вы откроете `/docs`, вы увидите, что поле `data` ожидает байты, закодированные в base64:
+
+
+
diff --git a/docs/ru/docs/advanced/openapi-webhooks.md b/docs/ru/docs/advanced/openapi-webhooks.md
new file mode 100644
index 0000000000000..9b1988ff31a52
--- /dev/null
+++ b/docs/ru/docs/advanced/openapi-webhooks.md
@@ -0,0 +1,55 @@
+# Вебхуки OpenAPI { #openapi-webhooks }
+
+Бывают случаи, когда вы хотите сообщить пользователям вашего API, что ваше приложение может вызвать их приложение (отправив HTTP-запрос) с некоторыми данными, обычно чтобы уведомить о каком-то событии.
+
+Это означает, что вместо обычного процесса, когда пользователи отправляют запросы вашему API, ваш API (или ваше приложение) может отправлять запросы в их систему (в их API, их приложение).
+
+Обычно это называется вебхуком.
+
+## Шаги вебхуков { #webhooks-steps }
+
+Обычно процесс таков: вы определяете в своем коде, какое сообщение вы будете отправлять, то есть тело запроса.
+
+Вы также определяете, в какие моменты (при каких событиях) ваше приложение будет отправлять эти запросы (события).
+
+А ваши пользователи каким-то образом (например, в веб‑панели) указывают URL-адрес, на который ваше приложение должно отправлять эти запросы.
+
+Вся логика регистрации URL-адресов для вебхуков и код, который реально отправляет эти запросы, целиком на вашей стороне. Вы пишете это так, как вам нужно, в своем собственном коде.
+
+## Документирование вебхуков с помощью **FastAPI** и OpenAPI { #documenting-webhooks-with-fastapi-and-openapi }
+
+С **FastAPI**, используя OpenAPI, вы можете определить имена этих вебхуков, типы HTTP-операций, которые ваше приложение может отправлять (например, `POST`, `PUT` и т.д.), а также тела запросов, которые ваше приложение будет отправлять.
+
+Это значительно упростит вашим пользователям реализацию их API для приема ваших вебхук-запросов; возможно, они даже смогут автоматически сгенерировать часть кода своего API.
+
+/// info | Информация
+
+Вебхуки доступны в OpenAPI 3.1.0 и выше, поддерживаются в FastAPI `0.99.0` и новее.
+
+///
+
+## Приложение с вебхуками { #an-app-with-webhooks }
+
+При создании приложения на **FastAPI** есть атрибут `webhooks`, с помощью которого можно объявлять вебхуки так же, как вы объявляете операции пути (обработчики пути), например с `@app.webhooks.post()`.
+
+{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}
+
+Определенные вами вебхуки попадут в схему **OpenAPI** и в автоматический **интерфейс документации**.
+
+/// info | Информация
+
+Объект `app.webhooks` на самом деле — это обычный `APIRouter`, тот же тип, который вы используете при структурировании приложения по нескольким файлам.
+
+///
+
+Обратите внимание: в случае с вебхуками вы на самом деле не объявляете путь (например, `/items/`), передаваемый туда текст — это лишь идентификатор вебхука (имя события). Например, в `@app.webhooks.post("new-subscription")` имя вебхука — `new-subscription`.
+
+Это связано с тем, что предполагается: фактический URL‑путь, по которому они хотят получать запрос вебхука, ваши пользователи укажут каким-то другим образом (например, в веб‑панели).
+
+### Посмотрите документацию { #check-the-docs }
+
+Теперь вы можете запустить приложение и перейти по ссылке [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).
+
+Вы увидите, что в документации есть обычные операции пути, а также появились вебхуки:
+
+
diff --git a/docs/ru/docs/advanced/path-operation-advanced-configuration.md b/docs/ru/docs/advanced/path-operation-advanced-configuration.md
new file mode 100644
index 0000000000000..fe2996362b7da
--- /dev/null
+++ b/docs/ru/docs/advanced/path-operation-advanced-configuration.md
@@ -0,0 +1,172 @@
+# Расширенная конфигурация операций пути { #path-operation-advanced-configuration }
+
+## OpenAPI operationId { #openapi-operationid }
+
+/// warning | Предупреждение
+
+Если вы не «эксперт» по OpenAPI, скорее всего, это вам не нужно.
+
+///
+
+Вы можете задать OpenAPI `operationId`, который будет использоваться в вашей *операции пути*, с помощью параметра `operation_id`.
+
+Нужно убедиться, что он уникален для каждой операции.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
+
+### Использование имени *функции-обработчика пути* как operationId { #using-the-path-operation-function-name-as-the-operationid }
+
+Если вы хотите использовать имена функций ваших API в качестве `operationId`, вы можете пройти по всем из них и переопределить `operation_id` каждой *операции пути* с помощью их `APIRoute.name`.
+
+Делать это следует после добавления всех *операций пути*.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *}
+
+/// tip | Совет
+
+Если вы вызываете `app.openapi()` вручную, обновите `operationId` до этого.
+
+///
+
+/// warning | Предупреждение
+
+Если вы делаете это, убедитесь, что каждая из ваших *функций-обработчиков пути* имеет уникальное имя.
+
+Даже если они находятся в разных модулях (файлах Python).
+
+///
+
+## Исключить из OpenAPI { #exclude-from-openapi }
+
+Чтобы исключить *операцию пути* из генерируемой схемы OpenAPI (а значит, и из автоматических систем документации), используйте параметр `include_in_schema` и установите его в `False`:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}
+
+## Расширенное описание из docstring { #advanced-description-from-docstring }
+
+Вы можете ограничить количество строк из docstring *функции-обработчика пути*, используемых для OpenAPI.
+
+Добавление `\f` (экранированного символа «form feed») заставит **FastAPI** обрезать текст, используемый для OpenAPI, в этой точке.
+
+Это не отобразится в документации, но другие инструменты (например, Sphinx) смогут использовать остальное.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}
+
+## Дополнительные ответы { #additional-responses }
+
+Вы, вероятно, уже видели, как объявлять `response_model` и `status_code` для *операции пути*.
+
+Это определяет метаданные об основном HTTP-ответе *операции пути*.
+
+Также можно объявлять дополнительные ответы с их моделями, статус-кодами и т.д.
+
+В документации есть целая глава об этом — [Дополнительные ответы в OpenAPI](additional-responses.md).
+
+## Дополнительные данные OpenAPI { #openapi-extra }
+
+Когда вы объявляете *операцию пути* в своём приложении, **FastAPI** автоматически генерирует соответствующие метаданные об этой *операции пути* для включения в схему OpenAPI.
+
+/// note | Технические детали
+
+В спецификации OpenAPI это называется [Объект операции](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object).
+
+///
+
+Он содержит всю информацию об *операции пути* и используется для генерации автоматической документации.
+
+Там есть `tags`, `parameters`, `requestBody`, `responses` и т.д.
+
+Эта специфичная для *операции пути* схема OpenAPI обычно генерируется автоматически **FastAPI**, но вы также можете её расширить.
+
+/// tip | Совет
+
+Это низкоуровневая возможность расширения.
+
+Если вам нужно лишь объявить дополнительные ответы, удобнее сделать это через [Дополнительные ответы в OpenAPI](additional-responses.md).
+
+///
+
+Вы можете расширить схему OpenAPI для *операции пути* с помощью параметра `openapi_extra`.
+
+### Расширения OpenAPI { #openapi-extensions }
+
+`openapi_extra` может пригодиться, например, чтобы объявить [Расширения OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py310.py hl[6] *}
+
+Если вы откроете автоматическую документацию API, ваше расширение появится внизу страницы конкретной *операции пути*.
+
+
+
+И если вы посмотрите на итоговый OpenAPI (по адресу `/openapi.json` вашего API), вы также увидите своё расширение в составе описания соответствующей *операции пути*:
+
+```JSON hl_lines="22"
+{
+ "openapi": "3.1.0",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0"
+ },
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ }
+ },
+ "x-aperture-labs-portal": "blue"
+ }
+ }
+ }
+}
+```
+
+### Пользовательская схема OpenAPI для *операции пути* { #custom-openapi-path-operation-schema }
+
+Словарь в `openapi_extra` будет глубоко объединён с автоматически сгенерированной схемой OpenAPI для *операции пути*.
+
+Таким образом, вы можете добавить дополнительные данные к автоматически сгенерированной схеме.
+
+Например, вы можете решить читать и валидировать HTTP-запрос своим кодом, не используя автоматические возможности FastAPI и Pydantic, но при этом захотите описать HTTP-запрос в схеме OpenAPI.
+
+Это можно сделать с помощью `openapi_extra`:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py310.py hl[19:36, 39:40] *}
+
+В этом примере мы не объявляли никакую Pydantic-модель. Фактически тело запроса даже не распарсено как JSON, оно читается напрямую как `bytes`, а функция `magic_data_reader()` будет отвечать за его парсинг каким-то способом.
+
+Тем не менее, мы можем объявить ожидаемую схему для тела запроса.
+
+### Пользовательский тип содержимого в OpenAPI { #custom-openapi-content-type }
+
+Используя тот же приём, вы можете воспользоваться Pydantic-моделью, чтобы определить JSON Schema, которая затем будет включена в пользовательский раздел схемы OpenAPI для *операции пути*.
+
+И вы можете сделать это, даже если тип данных в HTTP-запросе — не JSON.
+
+Например, в этом приложении мы не используем встроенную функциональность FastAPI для извлечения JSON Schema из моделей Pydantic, равно как и автоматическую валидацию JSON. Мы объявляем тип содержимого HTTP-запроса как YAML, а не JSON:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[15:20, 22] *}
+
+Тем не менее, хотя мы не используем встроенную функциональность по умолчанию, мы всё равно используем Pydantic-модель, чтобы вручную сгенерировать JSON Schema для данных, которые мы хотим получить в YAML.
+
+Затем мы работаем с HTTP-запросом напрямую и извлекаем тело как `bytes`. Это означает, что FastAPI даже не попытается распарсить полезную нагрузку HTTP-запроса как JSON.
+
+А затем в нашем коде мы напрямую парсим это содержимое YAML и снова используем ту же Pydantic-модель, чтобы валидировать YAML-содержимое:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *}
+
+/// tip | Совет
+
+Здесь мы переиспользуем ту же Pydantic-модель.
+
+Но аналогично мы могли бы валидировать данные и каким-то другим способом.
+
+///
diff --git a/docs/ru/docs/advanced/response-change-status-code.md b/docs/ru/docs/advanced/response-change-status-code.md
new file mode 100644
index 0000000000000..3dd0c9446ec87
--- /dev/null
+++ b/docs/ru/docs/advanced/response-change-status-code.md
@@ -0,0 +1,31 @@
+# Response - Изменение статус-кода { #response-change-status-code }
+
+Вы, вероятно, уже читали о том, что можно установить [статус-код ответа по умолчанию](../tutorial/response-status-code.md).
+
+Но в некоторых случаях нужно вернуть другой статус-код, отличный от значения по умолчанию.
+
+## Пример использования { #use-case }
+
+Например, представьте, что вы хотите по умолчанию возвращать HTTP статус-код «OK» `200`.
+
+Но если данные не существовали, вы хотите создать их и вернуть HTTP статус-код «CREATED» `201`.
+
+При этом вы всё ещё хотите иметь возможность фильтровать и преобразовывать возвращаемые данные с помощью `response_model`.
+
+Для таких случаев вы можете использовать параметр `Response`.
+
+## Использование параметра `Response` { #use-a-response-parameter }
+
+Вы можете объявить параметр типа `Response` в вашей *функции обработки пути* (как и для cookies и HTTP-заголовков).
+
+И затем вы можете установить `status_code` в этом *временном* объекте ответа.
+
+{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}
+
+После этого вы можете вернуть любой объект, который вам нужен, как обычно (`dict`, модель базы данных и т.д.).
+
+И если вы объявили `response_model`, он всё равно будет использоваться для фильтрации и преобразования возвращаемого объекта.
+
+**FastAPI** будет использовать этот *временный* ответ для извлечения статус-кода (а также cookies и HTTP-заголовков) и поместит их в финальный ответ, который содержит возвращаемое вами значение, отфильтрованное любым `response_model`.
+
+Вы также можете объявить параметр `Response` в зависимостях и установить в них статус-код. Но помните, что последнее установленное значение будет иметь приоритет.
diff --git a/docs/ru/docs/advanced/response-cookies.md b/docs/ru/docs/advanced/response-cookies.md
new file mode 100644
index 0000000000000..2adc1af85ac48
--- /dev/null
+++ b/docs/ru/docs/advanced/response-cookies.md
@@ -0,0 +1,51 @@
+# Cookies в ответе { #response-cookies }
+
+## Использование параметра `Response` { #use-a-response-parameter }
+
+Вы можете объявить параметр типа `Response` в вашей функции-обработчике пути.
+
+Затем установить cookies в этом временном объекте ответа.
+
+{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}
+
+После этого можно вернуть любой объект, как и раньше (например, `dict`, объект модели базы данных и так далее).
+
+Если вы указали `response_model`, он всё равно будет использоваться для фильтрации и преобразования возвращаемого объекта.
+
+**FastAPI** извлечет cookies (а также HTTP-заголовки и статус-код) из временного ответа и включит их в окончательный ответ, содержащий ваше возвращаемое значение, отфильтрованное через `response_model`.
+
+Вы также можете объявить параметр типа `Response` в зависимостях и устанавливать cookies (и HTTP-заголовки) там.
+
+## Возвращение `Response` напрямую { #return-a-response-directly }
+
+Вы также можете установить Cookies, если возвращаете `Response` напрямую в вашем коде.
+
+Для этого создайте объект `Response`, как описано в разделе [Возвращение ответа напрямую](response-directly.md).
+
+Затем установите cookies и верните этот объект:
+
+{* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *}
+
+/// tip | Совет
+
+Имейте в виду, что если вы возвращаете ответ напрямую, вместо использования параметра `Response`, FastAPI вернёт его напрямую.
+
+Убедитесь, что ваши данные имеют корректный тип. Например, они должны быть совместимы с JSON, если вы возвращаете `JSONResponse`.
+
+Также убедитесь, что вы не отправляете данные, которые должны были быть отфильтрованы через `response_model`.
+
+///
+
+### Дополнительная информация { #more-info }
+
+/// note | Технические детали
+
+Вы также можете использовать `from starlette.responses import Response` или `from starlette.responses import JSONResponse`.
+
+**FastAPI** предоставляет `fastapi.responses`, которые являются теми же объектами, что и `starlette.responses`, просто для удобства. Однако большинство доступных типов ответов поступает непосредственно из **Starlette**.
+
+И так как `Response` часто используется для установки HTTP-заголовков и cookies, **FastAPI** также предоставляет его как `fastapi.Response`.
+
+///
+
+Чтобы увидеть все доступные параметры и настройки, ознакомьтесь с [документацией Starlette](https://www.starlette.dev/responses/#set-cookie).
diff --git a/docs/ru/docs/advanced/response-directly.md b/docs/ru/docs/advanced/response-directly.md
new file mode 100644
index 0000000000000..fcb8d533db547
--- /dev/null
+++ b/docs/ru/docs/advanced/response-directly.md
@@ -0,0 +1,83 @@
+# Возврат ответа напрямую { #return-a-response-directly }
+
+Когда вы создаёте **FastAPI** *операцию пути*, вы можете возвращать из неё любые данные: `dict`, `list`, Pydantic-модель, модель базы данных и т.д.
+
+Если вы объявите [Модель ответа](../tutorial/response-model.md), FastAPI будет использовать её для сериализации данных в JSON с помощью Pydantic.
+
+Если вы не объявите модель ответа, FastAPI использует `jsonable_encoder`, как описано в [JSON кодировщик](../tutorial/encoder.md), и поместит результат в `JSONResponse`.
+
+Также вы можете создать `JSONResponse` напрямую и вернуть его.
+
+/// tip | Подсказка
+
+Обычно вы получите значительно лучшую производительность, если будете использовать [Модель ответа](../tutorial/response-model.md), а не возвращать `JSONResponse` напрямую, так как в этом случае сериализация данных с помощью Pydantic происходит на стороне Rust.
+
+///
+
+## Возврат `Response` { #return-a-response }
+
+Вы можете возвращать `Response` или любой его подкласс.
+
+/// info | Информация
+
+`JSONResponse` сам по себе является подклассом `Response`.
+
+///
+
+И когда вы возвращаете `Response`, **FastAPI** передаст его напрямую.
+
+Это не приведет к преобразованию данных с помощью Pydantic-моделей, содержимое не будет преобразовано в какой-либо тип и т.д.
+
+Это даёт вам большую гибкость. Вы можете возвращать любые типы данных, переопределять любые объявления или валидацию данных и т.д.
+
+Это также накладывает на вас ответственность. Вам нужно удостовериться, что возвращаемые данные корректны, в правильном формате, что их можно сериализовать и т.д.
+
+## Использование `jsonable_encoder` в `Response` { #using-the-jsonable-encoder-in-a-response }
+
+Поскольку **FastAPI** не изменяет объект `Response`, который вы возвращаете, вы должны убедиться, что его содержимое готово к отправке.
+
+Например, вы не можете поместить Pydantic-модель в `JSONResponse`, не преобразовав её сначала в `dict` с помощью преобразования всех типов данных (таких как `datetime`, `UUID` и т.д.) в совместимые с JSON типы.
+
+В таких случаях вы можете использовать `jsonable_encoder` для преобразования данных перед передачей их в ответ:
+
+{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}
+
+/// note | Технические детали
+
+Вы также можете использовать `from starlette.responses import JSONResponse`.
+
+**FastAPI** предоставляет `starlette.responses` через `fastapi.responses` просто для вашего удобства, как разработчика. Но большинство доступных Response-классов поступают напрямую из Starlette.
+
+///
+
+## Возврат пользовательского `Response` { #returning-a-custom-response }
+
+Пример выше показывает все необходимые части, но он пока не очень полезен, так как вы могли бы просто вернуть `item` напрямую, и **FastAPI** поместил бы его в `JSONResponse`, преобразовав в `dict` и т.д. Всё это происходит по умолчанию.
+
+Теперь давайте посмотрим, как можно использовать это для возврата пользовательского ответа.
+
+Допустим, вы хотите вернуть ответ в формате [XML](https://en.wikipedia.org/wiki/XML).
+
+Вы можете поместить ваш XML-контент в строку, поместить её в `Response` и вернуть:
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+## Как работает модель ответа { #how-a-response-model-works }
+
+Когда вы объявляете [Модель ответа - возвращаемый тип](../tutorial/response-model.md) в операции пути, **FastAPI** будет использовать её для сериализации данных в JSON с помощью Pydantic.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+Поскольку это происходит на стороне Rust, производительность будет значительно выше, чем если бы это выполнялось обычным Python и классом `JSONResponse`.
+
+При использовании `response_model` или возвращаемого типа FastAPI не будет использовать `jsonable_encoder` для преобразования данных (что было бы медленнее) и не будет использовать класс `JSONResponse`.
+
+Вместо этого он берёт JSON-байты, сгенерированные Pydantic с использованием модели ответа (или возвращаемого типа), и возвращает `Response` с правильным типом содержимого для JSON (`application/json`) напрямую.
+
+## Примечания { #notes }
+
+Когда вы возвращаете объект `Response` напрямую, его данные не валидируются, не преобразуются (не сериализуются) и не документируются автоматически.
+
+Но вы всё равно можете задокументировать это, как описано в [Дополнительные ответы в OpenAPI](additional-responses.md).
+
+В следующих разделах вы увидите, как использовать/объявлять такие кастомные `Response`, при этом сохраняя автоматическое преобразование данных, документацию и т.д.
diff --git a/docs/ru/docs/advanced/response-headers.md b/docs/ru/docs/advanced/response-headers.md
new file mode 100644
index 0000000000000..806b89e1f859e
--- /dev/null
+++ b/docs/ru/docs/advanced/response-headers.md
@@ -0,0 +1,41 @@
+# HTTP-заголовки ответа { #response-headers }
+
+## Использовать параметр `Response` { #use-a-response-parameter }
+
+Вы можете объявить параметр типа `Response` в вашей функции-обработчике пути (как можно сделать и для cookie).
+
+А затем вы можете устанавливать HTTP-заголовки в этом *временном* объекте ответа.
+
+{* ../../docs_src/response_headers/tutorial002_py310.py hl[1, 7:8] *}
+
+После этого вы можете вернуть любой нужный объект, как обычно (например, `dict`, модель из базы данных и т.д.).
+
+И, если вы объявили `response_model`, он всё равно будет использован для фильтрации и преобразования возвращённого объекта.
+
+**FastAPI** использует этот *временный* ответ, чтобы извлечь HTTP-заголовки (а также cookie и статус-код) и поместит их в финальный HTTP-ответ, который содержит возвращённое вами значение, отфильтрованное согласно `response_model`.
+
+Вы также можете объявлять параметр `Response` в зависимостях и устанавливать в них заголовки (и cookie).
+
+## Вернуть `Response` напрямую { #return-a-response-directly }
+
+Вы также можете добавить HTTP-заголовки, когда возвращаете `Response` напрямую.
+
+Создайте ответ, как описано в [Вернуть Response напрямую](response-directly.md), и передайте заголовки как дополнительный параметр:
+
+{* ../../docs_src/response_headers/tutorial001_py310.py hl[10:12] *}
+
+/// note | Технические детали
+
+Вы также можете использовать `from starlette.responses import Response` или `from starlette.responses import JSONResponse`.
+
+**FastAPI** предоставляет те же самые `starlette.responses` как `fastapi.responses` — для вашего удобства как разработчика. Но большинство доступных классов ответов поступают напрямую из Starlette.
+
+И поскольку `Response` часто используется для установки заголовков и cookie, **FastAPI** также предоставляет его как `fastapi.Response`.
+
+///
+
+## Пользовательские HTTP-заголовки { #custom-headers }
+
+Помните, что собственные проприетарные заголовки можно добавлять, [используя префикс `X-`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers).
+
+Но если у вас есть пользовательские заголовки, которые вы хотите показывать клиенту в браузере, вам нужно добавить их в настройки CORS (подробнее см. в [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md)), используя параметр `expose_headers`, описанный в [документации Starlette по CORS](https://www.starlette.dev/middleware/#corsmiddleware).
diff --git a/docs/ru/docs/advanced/security/http-basic-auth.md b/docs/ru/docs/advanced/security/http-basic-auth.md
new file mode 100644
index 0000000000000..b094fec7730de
--- /dev/null
+++ b/docs/ru/docs/advanced/security/http-basic-auth.md
@@ -0,0 +1,107 @@
+# HTTP Basic Auth { #http-basic-auth }
+
+Для самых простых случаев можно использовать HTTP Basic Auth.
+
+При HTTP Basic Auth приложение ожидает HTTP-заголовок, который содержит имя пользователя и пароль.
+
+Если его нет, возвращается ошибка HTTP 401 «Unauthorized».
+
+Также возвращается заголовок `WWW-Authenticate` со значением `Basic` и необязательным параметром `realm`.
+
+Это говорит браузеру показать встроенное окно запроса имени пользователя и пароля.
+
+Затем, когда вы вводите эти данные, браузер автоматически отправляет их в заголовке.
+
+## Простой HTTP Basic Auth { #simple-http-basic-auth }
+
+* Импортируйте `HTTPBasic` и `HTTPBasicCredentials`.
+* Создайте «схему» `security` с помощью `HTTPBasic`.
+* Используйте эту `security` как зависимость в вашей *операции пути*.
+* Она возвращает объект типа `HTTPBasicCredentials`:
+ * Он содержит отправленные `username` и `password`.
+
+{* ../../docs_src/security/tutorial006_an_py310.py hl[4,8,12] *}
+
+Когда вы впервые откроете URL (или нажмёте кнопку «Execute» в документации), браузер попросит ввести имя пользователя и пароль:
+
+
+
+## Проверка имени пользователя { #check-the-username }
+
+Вот более полный пример.
+
+Используйте зависимость, чтобы проверить, корректны ли имя пользователя и пароль.
+
+Для этого используйте стандартный модуль Python [`secrets`](https://docs.python.org/3/library/secrets.html) для проверки имени пользователя и пароля.
+
+`secrets.compare_digest()` должен получать `bytes` или `str`, который содержит только символы ASCII (английские символы). Это значит, что он не будет работать с символами вроде `á`, как в `Sebastián`.
+
+Чтобы это обработать, сначала преобразуем `username` и `password` в `bytes`, закодировав их в UTF-8.
+
+Затем можно использовать `secrets.compare_digest()`, чтобы убедиться, что `credentials.username` равен `"stanleyjobson"`, а `credentials.password` — `"swordfish"`.
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[1,12:24] *}
+
+Это было бы похоже на:
+
+```Python
+if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
+ # Вернуть ошибку
+ ...
+```
+
+Но используя `secrets.compare_digest()`, вы защитите код от атак типа «тайминговая атака» (атака по времени).
+
+### Тайминговые атаки { #timing-attacks }
+
+Что такое «тайминговая атака»?
+
+Представим, что злоумышленники пытаются угадать имя пользователя и пароль.
+
+И они отправляют запрос с именем пользователя `johndoe` и паролем `love123`.
+
+Тогда Python-код в вашем приложении будет эквивалентен чему-то вроде:
+
+```Python
+if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Но в момент, когда Python сравнит первую `j` в `johndoe` с первой `s` в `stanleyjobson`, он вернёт `False`, потому что уже ясно, что строки не совпадают, решив, что «нет смысла тратить ресурсы на сравнение остальных букв». И ваше приложение ответит «Неверное имя пользователя или пароль».
+
+Затем злоумышленники попробуют имя пользователя `stanleyjobsox` и пароль `love123`.
+
+И ваш код сделает что-то вроде:
+
+```Python
+if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Pythonу придётся сравнить весь общий префикс `stanleyjobso` в `stanleyjobsox` и `stanleyjobson`, прежде чем понять, что строки отличаются. Поэтому на ответ «Неверное имя пользователя или пароль» уйдёт на несколько микросекунд больше.
+
+#### Время ответа помогает злоумышленникам { #the-time-to-answer-helps-the-attackers }
+
+Замечая, что сервер прислал «Неверное имя пользователя или пароль» на несколько микросекунд позже, злоумышленники поймут, что какая-то часть была угадана — начальные буквы верны.
+
+Тогда они могут попробовать снова, зная, что правильнее что-то ближе к `stanleyjobsox`, чем к `johndoe`.
+
+#### «Профессиональная» атака { #a-professional-attack }
+
+Конечно, злоумышленники не будут делать всё это вручную — они напишут программу, возможно, с тысячами или миллионами попыток в секунду. И будут подбирать по одной дополнительной верной букве за раз.
+
+Так за минуты или часы они смогут угадать правильные имя пользователя и пароль — с «помощью» нашего приложения — используя лишь время, затраченное на ответ.
+
+#### Исправление с помощью `secrets.compare_digest()` { #fix-it-with-secrets-compare-digest }
+
+Но в нашем коде мы используем `secrets.compare_digest()`.
+
+Вкратце: сравнение `stanleyjobsox` с `stanleyjobson` займёт столько же времени, сколько и сравнение `johndoe` с `stanleyjobson`. То же относится и к паролю.
+
+Таким образом, используя `secrets.compare_digest()` в коде приложения, вы защитите его от всего этого класса атак на безопасность.
+
+### Возврат ошибки { #return-the-error }
+
+После того как обнаружено, что учётные данные некорректны, верните `HTTPException` со статус-кодом ответа 401 (тем же, что и при отсутствии учётных данных) и добавьте HTTP-заголовок `WWW-Authenticate`, чтобы браузер снова показал окно входа:
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[26:30] *}
diff --git a/docs/ru/docs/advanced/security/index.md b/docs/ru/docs/advanced/security/index.md
new file mode 100644
index 0000000000000..89a7236d81ee3
--- /dev/null
+++ b/docs/ru/docs/advanced/security/index.md
@@ -0,0 +1,19 @@
+# Расширенная безопасность { #advanced-security }
+
+## Дополнительные возможности { #additional-features }
+
+Есть дополнительные возможности для работы с безопасностью помимо тех, что описаны в [Учебник — Руководство пользователя: Безопасность](../../tutorial/security/index.md).
+
+/// tip | Совет
+
+Следующие разделы не обязательно являются «продвинутыми».
+
+И возможно, что решение для вашего варианта использования находится в одном из них.
+
+///
+
+## Сначала прочитайте руководство { #read-the-tutorial-first }
+
+В следующих разделах предполагается, что вы уже прочитали основной [Учебник — Руководство пользователя: Безопасность](../../tutorial/security/index.md).
+
+Все они основаны на тех же концепциях, но предоставляют дополнительные возможности.
diff --git a/docs/ru/docs/advanced/security/oauth2-scopes.md b/docs/ru/docs/advanced/security/oauth2-scopes.md
new file mode 100644
index 0000000000000..944baeeeb6f2b
--- /dev/null
+++ b/docs/ru/docs/advanced/security/oauth2-scopes.md
@@ -0,0 +1,274 @@
+# OAuth2 scopes { #oauth2-scopes }
+
+Вы можете использовать OAuth2 scopes напрямую с **FastAPI** — они интегрированы и работают бесшовно.
+
+Это позволит вам иметь более детальную систему разрешений по стандарту OAuth2, интегрированную в ваше OpenAPI‑приложение (и документацию API).
+
+OAuth2 со scopes — это механизм, который используют многие крупные провайдеры аутентификации: Facebook, Google, GitHub, Microsoft, X (Twitter) и т.д. Они применяют его, чтобы предоставлять конкретные разрешения пользователям и приложениям.
+
+Каждый раз, когда вы «входите через» Facebook, Google, GitHub, Microsoft, X (Twitter), это приложение использует OAuth2 со scopes.
+
+В этом разделе вы увидите, как управлять аутентификацией и авторизацией с теми же OAuth2 scopes в вашем приложении на **FastAPI**.
+
+/// warning | Предупреждение
+
+Это более-менее продвинутый раздел. Если вы только начинаете, можете пропустить его.
+
+Вам не обязательно нужны OAuth2 scopes — аутентификацию и авторизацию можно реализовать любым нужным вам способом.
+
+Но OAuth2 со scopes можно красиво интегрировать в ваш API (через OpenAPI) и документацию API.
+
+Так или иначе, вы все равно будете применять эти scopes или какие-то другие требования безопасности/авторизации, как вам нужно, в вашем коде.
+
+Во многих случаях OAuth2 со scopes может быть избыточным.
+
+Но если вы знаете, что это нужно, или вам просто интересно — продолжайте чтение.
+
+///
+
+## OAuth2 scopes и OpenAPI { #oauth2-scopes-and-openapi }
+
+Спецификация OAuth2 определяет «scopes» как список строк, разделённых пробелами.
+
+Содержимое каждой такой строки может иметь любой формат, но не должно содержать пробелов.
+
+Эти scopes представляют «разрешения».
+
+В OpenAPI (например, в документации API) можно определить «схемы безопасности» (security schemes).
+
+Когда одна из таких схем безопасности использует OAuth2, вы также можете объявлять и использовать scopes.
+
+Каждый «scope» — это просто строка (без пробелов).
+
+Обычно они используются для объявления конкретных разрешений безопасности, например:
+
+- `users:read` или `users:write` — распространённые примеры.
+- `instagram_basic` используется Facebook / Instagram.
+- `https://www.googleapis.com/auth/drive` используется Google.
+
+/// info | Информация
+
+В OAuth2 «scope» — это просто строка, объявляющая требуемое конкретное разрешение.
+
+Неважно, есть ли там другие символы, такие как `:`, или это URL.
+
+Эти детали зависят от реализации.
+
+Для OAuth2 это просто строки.
+
+///
+
+## Взгляд издалека { #global-view }
+
+Сначала быстро посмотрим, что изменилось по сравнению с примерами из основного раздела **Учебник - Руководство пользователя** — [OAuth2 с паролем (и хешированием), Bearer с JWT-токенами](../../tutorial/security/oauth2-jwt.md). Теперь — с использованием OAuth2 scopes:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}
+
+Теперь рассмотрим эти изменения шаг за шагом.
+
+## OAuth2 схема безопасности { #oauth2-security-scheme }
+
+Первое изменение — мы объявляем схему безопасности OAuth2 с двумя доступными scopes: `me` и `items`.
+
+Параметр `scopes` получает `dict`, где каждый scope — это ключ, а описание — значение:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *}
+
+Так как теперь мы объявляем эти scopes, они появятся в документации API при входе/авторизации.
+
+И вы сможете выбрать, какие scopes вы хотите выдать доступ: `me` и `items`.
+
+Это тот же механизм, когда вы даёте разрешения при входе через Facebook, Google, GitHub и т.д.:
+
+
+
+## JWT-токены со scopes { #jwt-token-with-scopes }
+
+Теперь измените операцию пути, выдающую токен, чтобы возвращать запрошенные scopes.
+
+Мы всё ещё используем тот же `OAuth2PasswordRequestForm`. Он включает свойство `scopes` с `list` из `str` — каждый scope, полученный в запросе.
+
+И мы возвращаем scopes как часть JWT‑токена.
+
+/// danger | Опасность
+
+Для простоты здесь мы просто добавляем полученные scopes прямо в токен.
+
+Но в вашем приложении, в целях безопасности, следует убедиться, что вы добавляете только те scopes, которые пользователь действительно может иметь, или те, которые вы заранее определили.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}
+
+## Объявление scopes в *обработчиках путей* и зависимостях { #declare-scopes-in-path-operations-and-dependencies }
+
+Теперь объявим, что операция пути для `/users/me/items/` требует scope `items`.
+
+Для этого импортируем и используем `Security` из `fastapi`.
+
+Вы можете использовать `Security` для объявления зависимостей (как `Depends`), но `Security` также принимает параметр `scopes` со списком scopes (строк).
+
+В этом случае мы передаём функцию‑зависимость `get_current_active_user` в `Security` (точно так же, как сделали бы с `Depends`).
+
+Но мы также передаём `list` scopes — в данном случае только один scope: `items` (их могло быть больше).
+
+И функция‑зависимость `get_current_active_user` тоже может объявлять подзависимости не только через `Depends`, но и через `Security`, объявляя свою подзависимость (`get_current_user`) и дополнительные требования по scopes.
+
+В данном случае требуется scope `me` (их также могло быть больше одного).
+
+/// note | Примечание
+
+Вам не обязательно добавлять разные scopes в разных местах.
+
+Мы делаем это здесь, чтобы показать, как **FastAPI** обрабатывает scopes, объявленные на разных уровнях.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}
+
+/// info | Технические детали
+
+`Security` на самом деле является подклассом `Depends` и имеет всего один дополнительный параметр, который мы рассмотрим позже.
+
+Но используя `Security` вместо `Depends`, **FastAPI** будет знать, что можно объявлять security scopes, использовать их внутри и документировать API в OpenAPI.
+
+Однако когда вы импортируете `Query`, `Path`, `Depends`, `Security` и другие из `fastapi`, это на самом деле функции, возвращающие специальные классы.
+
+///
+
+## Использование `SecurityScopes` { #use-securityscopes }
+
+Теперь обновим зависимость `get_current_user`.
+
+Именно её используют зависимости выше.
+
+Здесь мы используем ту же схему OAuth2, созданную ранее, объявляя её как зависимость: `oauth2_scheme`.
+
+Поскольку у этой функции‑зависимости нет собственных требований по scopes, мы можем использовать `Depends` с `oauth2_scheme` — нам не нужно использовать `Security`, если не требуется указывать security scopes.
+
+Мы также объявляем специальный параметр типа `SecurityScopes`, импортированный из `fastapi.security`.
+
+Класс `SecurityScopes` похож на `Request` (через `Request` мы получали сам объект запроса).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}
+
+## Использование `scopes` { #use-the-scopes }
+
+Параметр `security_scopes` будет типа `SecurityScopes`.
+
+У него есть свойство `scopes` со списком, содержащим все scopes, требуемые им самим и всеми зависимостями, использующими его как подзависимость. То есть всеми «зависящими»… это может звучать запутанно, ниже есть дополнительное объяснение.
+
+Объект `security_scopes` (класс `SecurityScopes`) также предоставляет атрибут `scope_str` — это одна строка с этими scopes, разделёнными пробелами (мы будем её использовать).
+
+Мы создаём `HTTPException`, который можем переиспользовать (`raise`) в нескольких местах.
+
+В этом исключении мы включаем требуемые scopes (если есть) в виде строки, разделённой пробелами (используя `scope_str`). Эту строку со scopes мы помещаем в HTTP‑заголовок `WWW-Authenticate` (это часть спецификации).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}
+
+## Проверка `username` и формата данных { #verify-the-username-and-data-shape }
+
+Мы проверяем, что получили `username`, и извлекаем scopes.
+
+Затем валидируем эти данные с помощью Pydantic‑модели (перехватывая исключение `ValidationError`), и если возникает ошибка при чтении JWT‑токена или при валидации данных с Pydantic, мы вызываем `HTTPException`, созданное ранее.
+
+Для этого мы обновляем Pydantic‑модель `TokenData`, добавляя новое свойство `scopes`.
+
+Валидируя данные с помощью Pydantic, мы можем удостовериться, что у нас, например, именно `list` из `str` со scopes и `str` с `username`.
+
+А не, скажем, `dict` или что‑то ещё — ведь это могло бы где‑то позже сломать приложение и создать риск для безопасности.
+
+Мы также проверяем, что существует пользователь с таким именем, и если нет — вызываем то же исключение, созданное ранее.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}
+
+## Проверка `scopes` { #verify-the-scopes }
+
+Теперь проверяем, что все требуемые scopes — этой зависимостью и всеми зависящими (включая операции пути) — присутствуют среди scopes, предоставленных в полученном токене, иначе вызываем `HTTPException`.
+
+Для этого используем `security_scopes.scopes`, содержащий `list` со всеми этими scopes как `str`.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}
+
+## Дерево зависимостей и scopes { #dependency-tree-and-scopes }
+
+Ещё раз рассмотрим дерево зависимостей и scopes.
+
+Так как у зависимости `get_current_active_user` есть подзависимость `get_current_user`, scope `"me"`, объявленный в `get_current_active_user`, будет включён в список требуемых scopes в `security_scopes.scopes`, передаваемый в `get_current_user`.
+
+Сама операция пути тоже объявляет scope — `"items"`, поэтому он также будет в списке `security_scopes.scopes`, передаваемом в `get_current_user`.
+
+Иерархия зависимостей и scopes выглядит так:
+
+- Операция пути `read_own_items`:
+ - Запрашивает scopes `["items"]` с зависимостью:
+ - `get_current_active_user`:
+ - Функция‑зависимость `get_current_active_user`:
+ - Запрашивает scopes `["me"]` с зависимостью:
+ - `get_current_user`:
+ - Функция‑зависимость `get_current_user`:
+ - Собственных scopes не запрашивает.
+ - Имеет зависимость, использующую `oauth2_scheme`.
+ - Имеет параметр `security_scopes` типа `SecurityScopes`:
+ - Этот параметр `security_scopes` имеет свойство `scopes` с `list`, содержащим все объявленные выше scopes, то есть:
+ - `security_scopes.scopes` будет содержать `["me", "items"]` для операции пути `read_own_items`.
+ - `security_scopes.scopes` будет содержать `["me"]` для операции пути `read_users_me`, потому что он объявлен в зависимости `get_current_active_user`.
+ - `security_scopes.scopes` будет содержать `[]` (ничего) для операции пути `read_system_status`, потому что там не объявлялся `Security` со `scopes`, и его зависимость `get_current_user` тоже не объявляет `scopes`.
+
+/// tip | Совет
+
+Важный и «магический» момент здесь в том, что `get_current_user` будет иметь разный список `scopes` для проверки для каждой операции пути.
+
+Всё это зависит от `scopes`, объявленных в каждой операции пути и в каждой зависимости в дереве зависимостей конкретной операции пути.
+
+///
+
+## Больше деталей о `SecurityScopes` { #more-details-about-securityscopes }
+
+Вы можете использовать `SecurityScopes` в любой точке и в нескольких местах — необязательно в «корневой» зависимости.
+
+Он всегда будет содержать security scopes, объявленные в текущих зависимостях `Security`, и всеми зависящими — для этой конкретной операции пути и этого конкретного дерева зависимостей.
+
+Поскольку `SecurityScopes` будет содержать все scopes, объявленные зависящими, вы можете использовать его, чтобы централизованно проверять наличие требуемых scopes в токене в одной функции‑зависимости, а затем объявлять разные требования по scopes в разных операциях пути.
+
+Они будут проверяться независимо для каждой операции пути.
+
+## Проверим это { #check-it }
+
+Откройте документацию API — вы сможете аутентифицироваться и указать, какие scopes вы хотите авторизовать.
+
+
+
+Если вы не выберете ни один scope, вы будете «аутентифицированы», но при попытке доступа к `/users/me/` или `/users/me/items/` получите ошибку о недостаточных разрешениях. При этом доступ к `/status/` будет возможен.
+
+Если вы выберете scope `me`, но не `items`, вы сможете получить доступ к `/users/me/`, но не к `/users/me/items/`.
+
+Так и будет происходить со сторонним приложением, которое попытается обратиться к одной из этих операций пути с токеном, предоставленным пользователем, — в зависимости от того, сколько разрешений пользователь дал приложению.
+
+## О сторонних интеграциях { #about-third-party-integrations }
+
+В этом примере мы используем OAuth2 «password flow» (аутентификация по паролю).
+
+Это уместно, когда мы входим в наше собственное приложение, вероятно, с нашим собственным фронтендом.
+
+Мы можем ему доверять при получении `username` и `password`, потому что он под нашим контролем.
+
+Но если вы создаёте OAuth2‑приложение, к которому будут подключаться другие (т.е. вы строите провайдера аутентификации наподобие Facebook, Google, GitHub и т.п.), вам следует использовать один из других «flows».
+
+Самый распространённый — «implicit flow».
+
+Самый безопасный — «code flow», но он сложнее в реализации, так как требует больше шагов. Из‑за сложности многие провайдеры в итоге рекомендуют «implicit flow».
+
+/// note | Примечание
+
+Часто каждый провайдер аутентификации называет свои «flows» по‑разному — как часть бренда.
+
+Но в итоге они реализуют один и тот же стандарт OAuth2.
+
+///
+
+**FastAPI** включает утилиты для всех этих OAuth2‑flows в `fastapi.security.oauth2`.
+
+## `Security` в параметре `dependencies` декоратора { #security-in-decorator-dependencies }
+
+Точно так же, как вы можете определить `list` из `Depends` в параметре `dependencies` декоратора (см. [Зависимости в декораторах операции пути](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md)), вы можете использовать там и `Security` со `scopes`.
diff --git a/docs/ru/docs/advanced/settings.md b/docs/ru/docs/advanced/settings.md
new file mode 100644
index 0000000000000..3ae063340bf15
--- /dev/null
+++ b/docs/ru/docs/advanced/settings.md
@@ -0,0 +1,302 @@
+# Настройки и переменные окружения { #settings-and-environment-variables }
+
+Во многих случаях вашему приложению могут понадобиться внешние настройки или конфигурации, например секретные ключи, учетные данные для базы данных, учетные данные для email‑сервисов и т.д.
+
+Большинство таких настроек являются изменяемыми (могут меняться), например URL базы данных. И многие из них могут быть «чувствительными», например секреты.
+
+По этой причине обычно их передают через переменные окружения, которые считываются приложением.
+
+/// tip | Совет
+
+Чтобы понять, что такое переменные окружения, вы можете прочитать [Переменные окружения](../environment-variables.md).
+
+///
+
+## Типы и валидация { #types-and-validation }
+
+Переменные окружения могут содержать только текстовые строки, так как они внешние по отношению к Python и должны быть совместимы с другими программами и остальной системой (и даже с разными операционными системами, такими как Linux, Windows, macOS).
+
+Это означает, что любое значение, прочитанное в Python из переменной окружения, будет `str`, а любые преобразования к другим типам или любая валидация должны выполняться в коде.
+
+## Pydantic `Settings` { #pydantic-settings }
+
+К счастью, Pydantic предоставляет отличную утилиту для работы с этими настройками, поступающими из переменных окружения, — [Pydantic: управление настройками](https://docs.pydantic.dev/latest/concepts/pydantic_settings/).
+
+### Установка `pydantic-settings` { #install-pydantic-settings }
+
+Сначала убедитесь, что вы создали [виртуальное окружение](../virtual-environments.md), активировали его, а затем установили пакет `pydantic-settings`:
+
+
+
+Затем откройте документацию для подприложения по адресу [http://127.0.0.1:8000/subapi/docs](http://127.0.0.1:8000/subapi/docs).
+
+Вы увидите автоматическую документацию API для подприложения, включающую только его собственные _операции пути_, все под корректным префиксом подпути `/subapi`:
+
+
+
+Если вы попробуете взаимодействовать с любым из двух интерфейсов, всё будет работать корректно, потому что браузер сможет обращаться к каждому конкретному приложению и подприложению.
+
+### Технические подробности: `root_path` { #technical-details-root-path }
+
+Когда вы монтируете подприложение, как описано выше, FastAPI позаботится о передаче пути монтирования для подприложения, используя механизм из спецификации ASGI под названием `root_path`.
+
+Таким образом подприложение будет знать, что для интерфейса документации нужно использовать этот префикс пути.
+
+У подприложения также могут быть свои собственные смонтированные подприложения, и всё будет работать корректно, потому что FastAPI автоматически обрабатывает все эти `root_path`.
+
+Вы узнаете больше о `root_path` и о том, как использовать его явно, в разделе [За прокси](behind-a-proxy.md).
diff --git a/docs/ru/docs/advanced/templates.md b/docs/ru/docs/advanced/templates.md
new file mode 100644
index 0000000000000..5fc938eec2e7f
--- /dev/null
+++ b/docs/ru/docs/advanced/templates.md
@@ -0,0 +1,126 @@
+# Шаблоны { #templates }
+
+Вы можете использовать любой шаблонизатор вместе с **FastAPI**.
+
+Часто выбирают Jinja2 — тот же, что используется во Flask и других инструментах.
+
+Есть утилиты для простой настройки, которые вы можете использовать прямо в своем приложении **FastAPI** (предоставляются Starlette).
+
+## Установка зависимостей { #install-dependencies }
+
+Убедитесь, что вы создали [виртуальное окружение](../virtual-environments.md), активировали его и установили `jinja2`:
+
+
+
+Вы можете набирать сообщения в поле ввода и отправлять их:
+
+
+
+И ваше **FastAPI** приложение с веб-сокетами ответит:
+
+
+
+Вы можете отправлять и получать множество сообщений:
+
+
+
+И все они будут использовать одно и то же веб-сокет соединение.
+
+## Использование `Depends` и не только { #using-depends-and-others }
+
+Вы можете импортировать из `fastapi` и использовать в эндпоинте вебсокета:
+
+* `Depends`
+* `Security`
+* `Cookie`
+* `Header`
+* `Path`
+* `Query`
+
+Они работают так же, как и в других FastAPI эндпоинтах/*операциях пути*:
+
+{* ../../docs_src/websockets_/tutorial002_an_py310.py hl[68:69,82] *}
+
+/// info | Примечание
+
+В веб-сокете вызывать `HTTPException` не имеет смысла. Вместо этого нужно использовать `WebSocketException`.
+
+Вы можете использовать код закрытия из [допустимых кодов, определённых в спецификации](https://tools.ietf.org/html/rfc6455#section-7.4.1).
+
+///
+
+### Веб-сокеты с зависимостями: проверка в действии { #try-the-websockets-with-dependencies }
+
+Запустите приложение:
+
+
+
+## Обработка отключений и работа с несколькими клиентами { #handling-disconnections-and-multiple-clients }
+
+Если веб-сокет соединение закрыто, то `await websocket.receive_text()` вызовет исключение `WebSocketDisconnect`, которое можно поймать и обработать как в этом примере.
+
+{* ../../docs_src/websockets_/tutorial003_py310.py hl[79:81] *}
+
+Чтобы воспроизвести пример:
+
+* Откройте приложение в нескольких вкладках браузера.
+* Отправьте из них сообщения.
+* Затем закройте одну из вкладок.
+
+Это вызовет исключение `WebSocketDisconnect`, и все остальные клиенты получат следующее сообщение:
+
+```
+Client #1596980209979 left the chat
+```
+
+/// tip | Подсказка
+
+Приложение выше - это всего лишь простой минимальный пример, демонстрирующий обработку и передачу сообщений нескольким веб-сокет соединениям.
+
+Но имейте в виду, что это будет работать только в одном процессе и только пока он активен, так как всё обрабатывается в простом списке в оперативной памяти.
+
+Если нужно что-то легко интегрируемое с FastAPI, но более надежное и с поддержкой Redis, PostgreSQL или другого, то можно воспользоваться [encode/broadcaster](https://github.com/encode/broadcaster).
+
+///
+
+## Дополнительная информация { #more-info }
+
+Для более глубокого изучения темы воспользуйтесь документацией Starlette:
+
+* [Класс `WebSocket`](https://www.starlette.dev/websockets/).
+* [Обработка WebSocket на основе классов](https://www.starlette.dev/endpoints/#websocketendpoint).
diff --git a/docs/ru/docs/advanced/wsgi.md b/docs/ru/docs/advanced/wsgi.md
new file mode 100644
index 0000000000000..3ed85d0e9526e
--- /dev/null
+++ b/docs/ru/docs/advanced/wsgi.md
@@ -0,0 +1,51 @@
+# Подключение WSGI — Flask, Django и другие { #including-wsgi-flask-django-others }
+
+Вы можете монтировать WSGI‑приложения, как вы видели в [Подприложения — Mounts](sub-applications.md), [За прокси‑сервером](behind-a-proxy.md).
+
+Для этого вы можете использовать `WSGIMiddleware` и обернуть им ваше WSGI‑приложение, например Flask, Django и т.д.
+
+## Использование `WSGIMiddleware` { #using-wsgimiddleware }
+
+/// info | Информация
+
+Для этого требуется установить `a2wsgi`, например с помощью `pip install a2wsgi`.
+
+///
+
+Нужно импортировать `WSGIMiddleware` из `a2wsgi`.
+
+Затем оберните WSGI‑приложение (например, Flask) в middleware (Промежуточный слой).
+
+После этого смонтируйте его на путь.
+
+{* ../../docs_src/wsgi/tutorial001_py310.py hl[1,3,23] *}
+
+/// note | Примечание
+
+Ранее рекомендовалось использовать `WSGIMiddleware` из `fastapi.middleware.wsgi`, но теперь он помечен как устаревший.
+
+Вместо него рекомендуется использовать пакет `a2wsgi`. Использование остаётся таким же.
+
+Просто убедитесь, что пакет `a2wsgi` установлен, и импортируйте `WSGIMiddleware` из `a2wsgi`.
+
+///
+
+## Проверьте { #check-it }
+
+Теперь каждый HTTP‑запрос по пути `/v1/` будет обрабатываться приложением Flask.
+
+А всё остальное будет обрабатываться **FastAPI**.
+
+Если вы запустите это и перейдёте по [http://localhost:8000/v1/](http://localhost:8000/v1/), вы увидите HTTP‑ответ от Flask:
+
+```txt
+Hello, World from Flask!
+```
+
+А если вы перейдёте по [http://localhost:8000/v2](http://localhost:8000/v2), вы увидите HTTP‑ответ от FastAPI:
+
+```JSON
+{
+ "message": "Hello World"
+}
+```
diff --git a/docs/ru/docs/alternatives.md b/docs/ru/docs/alternatives.md
index 9e3c497d10b41..13bac7f92b8e6 100644
--- a/docs/ru/docs/alternatives.md
+++ b/docs/ru/docs/alternatives.md
@@ -1,96 +1,94 @@
-# Альтернативы, источники вдохновения и сравнения
+# Альтернативы, источники вдохновения и сравнения { #alternatives-inspiration-and-comparisons }
-Что вдохновило на создание **FastAPI**, сравнение его с альтернативами и чему он научился у них.
+Что вдохновило **FastAPI**, сравнение с альтернативами и чему он у них научился.
-## Введение
+## Введение { #intro }
-**FastAPI** не существовал бы, если б не было более ранних работ других людей.
+**FastAPI** не существовал бы без предыдущих работ других людей.
-Они создали большое количество инструментов, которые вдохновили меня на создание **FastAPI**.
+Было создано множество инструментов, которые вдохновили на его появление.
-Я всячески избегал создания нового фреймворка в течение нескольких лет.
-Сначала я пытался собрать все нужные функции, которые ныне есть в **FastAPI**, используя множество различных фреймворков, плагинов и инструментов.
+Я несколько лет избегал создания нового фреймворка. Сначала пытался закрыть все возможности, которые сейчас предоставляет **FastAPI**, с помощью множества разных фреймворков, плагинов и инструментов.
-Но в какой-то момент не осталось другого выбора, кроме как создать что-то, что предоставляло бы все эти функции сразу.
-Взять самые лучшие идеи из предыдущих инструментов и, используя новые возможности Python (которых не было до версии 3.6, то есть подсказки типов), объединить их.
+Но в какой-то момент не осталось другого варианта, кроме как создать что-то, что включает все эти возможности, взяв лучшие идеи из прежних инструментов и совместив их максимально удачным образом, используя возможности языка, которых прежде не было (аннотации типов в Python 3.6+).
-## Предшествующие инструменты
+## Предшествующие инструменты { #previous-tools }
-### Django
+### [Django](https://www.djangoproject.com/) { #django }
-Это самый популярный Python-фреймворк, и он пользуется доверием.
-Он используется для создания проектов типа Instagram.
+Это самый популярный Python-фреймворк, ему широко доверяют. Он используется для построения систем вроде Instagram.
-Django довольно тесно связан с реляционными базами данных (такими как MySQL или PostgreSQL), потому использовать NoSQL базы данных (например, Couchbase, MongoDB, Cassandra и т.п.) в качестве основного хранилища данных - непросто.
+Он относительно тесно связан с реляционными базами данных (например, MySQL или PostgreSQL), поэтому использовать NoSQL-базу данных (например, Couchbase, MongoDB, Cassandra и т. п.) в качестве основного хранилища не очень просто.
-Он был создан для генерации HTML-страниц на сервере, а не для создания API, используемых современными веб-интерфейсами (React, Vue.js, Angular и т.п.) или другими системами (например, IoT) взаимодействующими с сервером.
+Он был создан для генерации HTML на бэкенде, а не для создания API, используемых современным фронтендом (например, React, Vue.js и Angular) или другими системами (например, устройствами IoT), которые с ним общаются.
-### Django REST Framework
+### [Django REST Framework](https://www.django-rest-framework.org/) { #django-rest-framework }
-Фреймворк Django REST был создан, как гибкий инструментарий для создания веб-API на основе Django.
+Django REST Framework был создан как гибкий набор инструментов для построения веб-API поверх Django, чтобы улучшить его возможности в части API.
-DRF использовался многими компаниями, включая Mozilla, Red Hat и Eventbrite.
+Он используется многими компаниями, включая Mozilla, Red Hat и Eventbrite.
-Это был один из первых примеров **автоматического документирования API** и это была одна из первых идей, вдохновивших на создание **FastAPI**.
+Это был один из первых примеров **автоматической документации API**, и именно эта идея одной из первых вдохновила на «поиск» **FastAPI**.
-!!! note "Заметка"
- Django REST Framework был создан Tom Christie.
- Он же создал Starlette и Uvicorn, на которых основан **FastAPI**.
+/// note | Заметка
-!!! check "Идея для **FastAPI**"
- Должно быть автоматическое создание документации API с пользовательским веб-интерфейсом.
+Django REST Framework был создан Томом Кристи. Он же создал Starlette и Uvicorn, на которых основан **FastAPI**.
-### Flask
+///
-Flask - это "микрофреймворк", в нём нет интеграции с базами данных и многих других вещей, которые предустановлены в Django.
+/// check | Вдохновило **FastAPI** на
-Его простота и гибкость дают широкие возможности, такие как использование баз данных NoSQL в качестве основной системы хранения данных.
+Наличие пользовательского веб-интерфейса с автоматической документацией API.
-Он очень прост, его изучение интуитивно понятно, хотя в некоторых местах документация довольно техническая.
+///
-Flask часто используется и для приложений, которым не нужна база данных, настройки прав доступа для пользователей и прочие из множества функций, предварительно встроенных в Django.
-Хотя многие из этих функций могут быть добавлены с помощью плагинов.
+### [Flask](https://flask.palletsprojects.com) { #flask }
-Такое разделение на части и то, что это "микрофреймворк", который можно расширить, добавляя необходимые возможности, было ключевой особенностью, которую я хотел сохранить.
+Flask — это «микрофреймворк», он не включает интеграции с базами данных и многие другие вещи, которые в Django идут «из коробки».
-Простота Flask, показалась мне подходящей для создания API.
-Но ещё нужно было найти "Django REST Framework" для Flask.
+Эта простота и гибкость позволяет, например, использовать NoSQL-базы в качестве основной системы хранения данных.
-!!! check "Идеи для **FastAPI**"
- Это будет микрофреймворк. К нему легко будет добавить необходимые инструменты и части.
+Он очень прост, его относительно легко интуитивно освоить, хотя местами документация довольно техническая.
- Должна быть простая и лёгкая в использовании система маршрутизации запросов.
+Его также часто используют для приложений, которым не нужна база данных, управление пользователями или многие другие функции, предварительно встроенные в Django. Хотя многие из этих возможностей можно добавить плагинами.
+Такое разбиение на части и то, что это «микрофреймворк», который можно расширять ровно под нужды, — ключевая особенность, которую хотелось сохранить.
-### Requests
+С учётом простоты Flask он казался хорошим вариантом для создания API. Следующим было найти «Django REST Framework» для Flask.
-На самом деле **FastAPI** не является альтернативой **Requests**.
-Их область применения очень разная.
+/// check | Вдохновило **FastAPI** на
-В принципе, можно использовать Requests *внутри* приложения FastAPI.
+Быть микро-фреймворком. Облегчить комбинирование необходимых инструментов и компонентов.
-Но всё же я использовал в FastAPI некоторые идеи из Requests.
+Иметь простую и удобную систему маршрутизации.
-**Requests** - это библиотека для взаимодействия с API в качестве клиента,
-в то время как **FastAPI** - это библиотека для *создания* API (то есть сервера).
+///
-Они, так или иначе, диаметрально противоположны и дополняют друг друга.
+### [Requests](https://requests.readthedocs.io) { #requests }
-Requests имеет очень простой и понятный дизайн, очень прост в использовании и имеет разумные значения по умолчанию.
-И в то же время он очень мощный и настраиваемый.
+**FastAPI** на самом деле не альтернатива **Requests**. Их области применения очень различны.
-Вот почему на официальном сайте написано:
+Обычно Requests используют даже внутри приложения FastAPI.
-> Requests - один из самых загружаемых пакетов Python всех времен
+И всё же **FastAPI** во многом вдохновлялся Requests.
+**Requests** — это библиотека для взаимодействия с API (как клиент), а **FastAPI** — библиотека для создания API (как сервер).
-Использовать его очень просто. Например, чтобы выполнить запрос `GET`, Вы бы написали:
+Они, в каком-то смысле, находятся на противоположных концах и дополняют друг друга.
+
+Requests имеет очень простой и понятный дизайн, им очень легко пользоваться, есть разумные значения по умолчанию. И при этом он очень мощный и настраиваемый.
+
+Именно поэтому на официальном сайте сказано:
+
+> Requests — один из самых загружаемых Python-пакетов всех времён
+
+Пользоваться им очень просто. Например, чтобы сделать запрос `GET`, вы бы написали:
```Python
response = requests.get("http://example.com/some/url")
```
-Противоположная *операция пути* в FastAPI может выглядеть следующим образом:
+Соответствующая в FastAPI API-операция пути могла бы выглядеть так:
```Python hl_lines="1"
@app.get("/some/url")
@@ -98,363 +96,390 @@ def read_url():
return {"message": "Hello World"}
```
-Глядите, как похоже `requests.get(...)` и `@app.get(...)`.
+Посмотрите, насколько похожи `requests.get(...)` и `@app.get(...)`.
-!!! check "Идеи для **FastAPI**"
- * Должен быть простой и понятный API.
- * Нужно использовать названия HTTP-методов (операций) для упрощения понимания происходящего.
- * Должны быть разумные настройки по умолчанию и широкие возможности их кастомизации.
+/// check | Вдохновило **FastAPI** на
+* Иметь простой и понятный API.
+* Использовать названия HTTP-методов (операций) напрямую, простым и интуитивным образом.
+* Иметь разумные значения по умолчанию, но и мощные настройки.
-### Swagger / OpenAPI
+///
-Главной функцией, которую я хотел унаследовать от Django REST Framework, была автоматическая документация API.
+### [Swagger](https://swagger.io/) / [OpenAPI](https://github.com/OAI/OpenAPI-Specification/) { #swagger-openapi }
-Но потом я обнаружил, что существует стандарт документирования API, использующий JSON (или YAML, расширение JSON) под названием Swagger.
+Главной возможностью, которую хотелось взять из Django REST Framework, была автоматическая документация API.
-И к нему уже был создан пользовательский веб-интерфейс.
-Таким образом, возможность генерировать документацию Swagger для API позволила бы использовать этот интерфейс.
+Затем я обнаружил, что есть стандарт для документирования API с использованием JSON (или YAML — расширения JSON), под названием Swagger.
+
+И уже существовал веб-интерфейс для Swagger API. Поэтому возможность генерировать документацию Swagger для API позволила бы автоматически использовать этот веб-интерфейс.
В какой-то момент Swagger был передан Linux Foundation и переименован в OpenAPI.
-Вот почему, когда говорят о версии 2.0, обычно говорят "Swagger", а для версии 3+ "OpenAPI".
+Вот почему, говоря о версии 2.0, обычно говорят «Swagger», а о версии 3+ — «OpenAPI».
+
+/// check | Вдохновило **FastAPI** на
+
+Использовать открытый стандарт для спецификаций API вместо самодельной схемы.
+
+И интегрировать основанные на стандартах инструменты пользовательского интерфейса:
+
+* [Swagger UI](https://github.com/swagger-api/swagger-ui)
+* [ReDoc](https://github.com/Rebilly/ReDoc)
+
+Эти два инструмента выбраны за популярность и стабильность, но даже при беглом поиске можно найти десятки альтернативных интерфейсов для OpenAPI (которые можно использовать с **FastAPI**).
+
+///
+
+### REST-фреймворки для Flask { #flask-rest-frameworks }
+
+Существует несколько REST-фреймворков для Flask, но, вложив время и усилия в исследование, я обнаружил, что многие из них прекращены или заброшены, с несколькими нерешёнными Issue (тикет\обращение), из-за которых они непригодны.
+
+### [Marshmallow](https://marshmallow.readthedocs.io/en/stable/) { #marshmallow }
+
+Одна из основных возможностей, нужных системам API, — «сериализация» данных, то есть преобразование данных из кода (Python) во что-то, что можно отправить по сети. Например, преобразование объекта с данными из базы в JSON-объект. Преобразование объектов `datetime` в строки и т. п.
+
+Ещё одна важная возможность, востребованная API, — валидация данных: убеждаться, что данные валидны с учётом заданных параметров. Например, что какое-то поле — `int`, а не произвольная строка. Это особенно полезно для входящих данных.
+
+Без системы валидации данных вам пришлось бы выполнять все проверки вручную в коде.
+
+Именно для этих возможностей и был создан Marshmallow. Это отличная библиотека, я много ей пользовался раньше.
+
+Но она появилась до того, как в Python появились аннотации типов. Поэтому для определения каждой схемы нужно использовать специальные утилиты и классы, предоставляемые Marshmallow.
+
+/// check | Вдохновило **FastAPI** на
+
+Использовать код для автоматического определения «схем», задающих типы данных и их валидацию.
+
+///
+
+### [Webargs](https://webargs.readthedocs.io/en/latest/) { #webargs }
+
+Ещё одна важная возможность для API — парсинг данных из входящих HTTP-запросов.
+
+Webargs — это инструмент, созданный для этого поверх нескольких фреймворков, включая Flask.
-!!! check "Идеи для **FastAPI**"
- Использовать открытые стандарты для спецификаций API вместо самодельных схем.
+Он использует Marshmallow для валидации данных. И создан теми же разработчиками.
- Совместимость с основанными на стандартах пользовательскими интерфейсами:
+Это отличный инструмент, и я тоже много им пользовался до появления **FastAPI**.
- * Swagger UI
- * ReDoc
+/// info | Информация
- Они были выбраны за популярность и стабильность.
- Но сделав беглый поиск, Вы можете найти десятки альтернативных пользовательских интерфейсов для OpenAPI, которые Вы можете использовать с **FastAPI**.
+Webargs был создан теми же разработчиками, что и Marshmallow.
-### REST фреймворки для Flask
+///
-Существует несколько REST фреймворков для Flask, но потратив время и усилия на их изучение, я обнаружил, что многие из них не обновляются или заброшены и имеют нерешённые проблемы из-за которых они непригодны к использованию.
+/// check | Вдохновило **FastAPI** на
-### Marshmallow
+Автоматическую валидацию входящих данных HTTP-запроса.
-Одной из основных функций, необходимых системам API, является "сериализация" данных, то есть преобразование данных из кода (Python) во что-то, что может быть отправлено по сети.
-Например, превращение объекта содержащего данные из базы данных в объект JSON, конвертация объекта `datetime` в строку и т.п.
+///
-Еще одна важная функция, необходимая API — проверка данных, позволяющая убедиться, что данные действительны и соответствуют заданным параметрам.
-Как пример, можно указать, что ожидаются данные типа `int`, а не какая-то произвольная строка.
-Это особенно полезно для входящих данных.
+### [APISpec](https://apispec.readthedocs.io/en/stable/) { #apispec }
-Без системы проверки данных Вам пришлось бы прописывать все проверки вручную.
+Marshmallow и Webargs предоставляют валидацию, парсинг и сериализацию как плагины.
-Именно для обеспечения этих функций и была создана Marshmallow.
-Это отличная библиотека и я много раз пользовался ею раньше.
+Но документации всё ещё не было. Тогда появился APISpec.
-Но она была создана до того, как появились подсказки типов Python.
-Итак, чтобы определить каждую схему,
-Вам нужно использовать определенные утилиты и классы, предоставляемые Marshmallow.
+Это плагин для многих фреймворков (есть плагин и для Starlette).
-!!! check "Идея для **FastAPI**"
- Использовать код программы для автоматического создания "схем", определяющих типы данных и их проверку.
+Он работает так: вы пишете определение схемы в формате YAML внутри докстринга каждой функции, обрабатывающей маршрут.
-### Webargs
+И он генерирует схемы OpenAPI.
-Другая немаловажная функция API - парсинг данных из входящих запросов.
+Так это работает во Flask, Starlette, Responder и т. д.
-Webargs - это инструмент, который был создан для этого и поддерживает несколько фреймворков, включая Flask.
+Но у нас снова возникает проблема: появляется микро-синтаксис внутри строки Python (большой YAML).
-Для проверки данных он использует Marshmallow и создан теми же авторами.
+Редактор кода мало чем может помочь. И если мы изменим параметры или схемы Marshmallow и забудем также изменить YAML в докстринге, сгенерированная схема устареет.
-Это превосходный инструмент и я тоже часто пользовался им до **FastAPI**.
+/// info | Информация
-!!! info "Информация"
- Webargs бы создан разработчиками Marshmallow.
+APISpec был создан теми же разработчиками, что и Marshmallow.
-!!! check "Идея для **FastAPI**"
- Должна быть автоматическая проверка входных данных.
+///
-### APISpec
+/// check | Вдохновило **FastAPI** на
-Marshmallow и Webargs осуществляют проверку, анализ и сериализацию данных как плагины.
+Поддержку открытого стандарта для API — OpenAPI.
-Но документации API всё ещё не было. Тогда был создан APISpec.
+///
-Это плагин для множества фреймворков, в том числе и для Starlette.
+### [Flask-apispec](https://flask-apispec.readthedocs.io/en/latest/) { #flask-apispec }
-Он работает так - Вы записываете определение схем, используя формат YAML, внутри докстринга каждой функции, обрабатывающей маршрут.
+Это плагин для Flask, который связывает Webargs, Marshmallow и APISpec.
-Используя эти докстринги, он генерирует схему OpenAPI.
+Он использует информацию из Webargs и Marshmallow, чтобы автоматически генерировать схемы OpenAPI с помощью APISpec.
-Так это работает для Flask, Starlette, Responder и т.п.
+Отличный и недооценённый инструмент. Он заслуживает большей популярности, чем многие плагины для Flask. Возможно, из-за слишком краткой и абстрактной документации.
-Но теперь у нас возникает новая проблема - наличие постороннего микро-синтаксиса внутри кода Python (большие YAML).
+Это решило проблему необходимости писать YAML (ещё один синтаксис) в докстрингах Python.
-Редактор кода не особо может помочь в такой парадигме.
-А изменив какие-то параметры или схемы для Marshmallow можно забыть отредактировать докстринг с YAML и сгенерированная схема становится недействительной.
+Комбинация Flask, Flask-apispec с Marshmallow и Webargs была моим любимым бэкенд-стеком до создания **FastAPI**.
-!!! info "Информация"
- APISpec тоже был создан авторами Marshmallow.
+Его использование привело к созданию нескольких full-stack генераторов на Flask. Это основные стеки, которые я (и несколько внешних команд) использовали до сих пор:
-!!! check "Идея для **FastAPI**"
- Необходима поддержка открытого стандарта для API - OpenAPI.
+* [https://github.com/tiangolo/full-stack](https://github.com/tiangolo/full-stack)
+* [https://github.com/tiangolo/full-stack-flask-couchbase](https://github.com/tiangolo/full-stack-flask-couchbase)
+* [https://github.com/tiangolo/full-stack-flask-couchdb](https://github.com/tiangolo/full-stack-flask-couchdb)
-### Flask-apispec
+И эти же full-stack генераторы стали основой для [Генераторов проектов **FastAPI**](project-generation.md).
-Это плагин для Flask, который связан с Webargs, Marshmallow и APISpec.
+/// info | Информация
-Он получает информацию от Webargs и Marshmallow, а затем использует APISpec для автоматического создания схемы OpenAPI.
+Flask-apispec был создан теми же разработчиками, что и Marshmallow.
-Это отличный, но крайне недооценённый инструмент.
-Он должен быть более популярен, чем многие плагины для Flask.
-Возможно, это связано с тем, что его документация слишком скудна и абстрактна.
+///
-Он избавил от необходимости писать чужеродный синтаксис YAML внутри докстрингов.
+/// check | Вдохновило **FastAPI** на
-Такое сочетание Flask, Flask-apispec, Marshmallow и Webargs было моим любимым стеком при построении бэкенда до появления **FastAPI**.
+Автоматическую генерацию схемы OpenAPI из того же кода, который определяет сериализацию и валидацию.
-Использование этого стека привело к созданию нескольких генераторов проектов. Я и некоторые другие команды до сих пор используем их:
+///
-* https://github.com/tiangolo/full-stack
-* https://github.com/tiangolo/full-stack-flask-couchbase
-* https://github.com/tiangolo/full-stack-flask-couchdb
+### [NestJS](https://nestjs.com/) (и [Angular](https://angular.io/)) { #nestjs-and-angular }
-Эти генераторы проектов также стали основой для [Генераторов проектов с **FastAPI**](project-generation.md){.internal-link target=_blank}.
+Это даже не Python. NestJS — это JavaScript/TypeScript-фреймворк на NodeJS, вдохновлённый Angular.
-!!! info "Информация"
- Как ни странно, но Flask-apispec тоже создан авторами Marshmallow.
+Он достигает чего-то отчасти похожего на то, что можно сделать с Flask-apispec.
-!!! check "Идея для **FastAPI**"
- Схема OpenAPI должна создаваться автоматически и использовать тот же код, который осуществляет сериализацию и проверку данных.
+В нём встроена система внедрения зависимостей, вдохновлённая Angular 2. Требуется предварительная регистрация «инжектируемых» компонентов (как и во всех известных мне системах внедрения зависимостей), что добавляет многословности и повторяемости кода.
-### NestJS (и Angular)
+Поскольку параметры описываются с помощью типов TypeScript (аналог аннотаций типов в Python), поддержка редактора кода весьма хороша.
-Здесь даже не используется Python. NestJS - этот фреймворк написанный на JavaScript (TypeScript), основанный на NodeJS и вдохновлённый Angular.
+Но так как данные о типах TypeScript не сохраняются после компиляции в JavaScript, он не может полагаться на типы для одновременного определения валидации, сериализации и документации. Из‑за этого и некоторых проектных решений для получения валидации, сериализации и автоматической генерации схем приходится добавлять декораторы во многих местах. В итоге это становится довольно многословным.
-Он позволяет получить нечто похожее на то, что можно сделать с помощью Flask-apispec.
+Он плохо справляется с вложенными моделями. Если JSON-тело запроса — это объект JSON, содержащий внутренние поля, которые сами являются вложенными объектами JSON, это нельзя как следует задокументировать и провалидировать.
-В него встроена система внедрения зависимостей, ещё одна идея взятая от Angular.
-Однако требуется предварительная регистрация "внедрений" (как и во всех других известных мне системах внедрения зависимостей), что увеличивает количество и повторяемость кода.
+/// check | Вдохновило **FastAPI** на
-Так как параметры в нём описываются с помощью типов TypeScript (аналогично подсказкам типов в Python), поддержка редактора работает довольно хорошо.
+Использовать типы Python для отличной поддержки в редакторе кода.
-Но поскольку данные из TypeScript не сохраняются после компиляции в JavaScript, он не может полагаться на подсказки типов для определения проверки данных, сериализации и документации.
-Из-за этого и некоторых дизайнерских решений, для валидации, сериализации и автоматической генерации схем, приходится во многих местах добавлять декораторы.
-Таким образом, это становится довольно многословным.
+Иметь мощную систему внедрения зависимостей. Найти способ минимизировать повторение кода.
-Кроме того, он не очень хорошо справляется с вложенными моделями.
-Если в запросе имеется объект JSON, внутренние поля которого, в свою очередь, являются вложенными объектами JSON, это не может быть должным образом задокументировано и проверено.
+///
-!!! check "Идеи для **FastAPI** "
- Нужно использовать подсказки типов, чтоб воспользоваться поддержкой редактора кода.
+### [Sanic](https://sanic.readthedocs.io/en/latest/) { #sanic }
- Нужна мощная система внедрения зависимостей. Необходим способ для уменьшения повторов кода.
+Это был один из первых чрезвычайно быстрых Python-фреймворков на основе `asyncio`. Он был сделан очень похожим на Flask.
-### Sanic
+/// note | Технические детали
-Sanic был одним из первых чрезвычайно быстрых Python-фреймворков основанных на `asyncio`.
-Он был сделан очень похожим на Flask.
+Он использовал [`uvloop`](https://github.com/MagicStack/uvloop) вместо стандартного цикла `asyncio` в Python. Это и сделало его таким быстрым.
-!!! note "Технические детали"
- В нём использован `uvloop` вместо стандартного цикла событий `asyncio`, что и сделало его таким быстрым.
+Он явно вдохновил Uvicorn и Starlette, которые сейчас быстрее Sanic в открытых бенчмарках.
- Он явно вдохновил создателей Uvicorn и Starlette, которые в настоящее время быстрее Sanic в открытых бенчмарках.
+///
-!!! check "Идеи для **FastAPI**"
- Должна быть сумасшедшая производительность.
+/// check | Вдохновило **FastAPI** на
- Для этого **FastAPI** основан на Starlette, самом быстром из доступных фреймворков (по замерам незаинтересованных лиц).
+Поиск способа достичь сумасшедшей производительности.
-### Falcon
+Именно поэтому **FastAPI** основан на Starlette, так как это самый быстрый доступный фреймворк (по данным сторонних бенчмарков).
-Falcon - ещё один высокопроизводительный Python-фреймворк.
-В нём минимум функций и он создан, чтоб быть основой для других фреймворков, например, Hug.
+///
-Функции в нём получают два параметра - "запрос к серверу" и "ответ сервера".
-Затем Вы "читаете" часть запроса и "пишите" часть ответа.
-Из-за такой конструкции невозможно объявить параметры запроса и тела сообщения со стандартными подсказками типов Python в качестве параметров функции.
+### [Falcon](https://falconframework.org/) { #falcon }
-Таким образом, и валидацию данных, и их сериализацию, и документацию нужно прописывать вручную.
-Либо эти функции должны быть встроены во фреймворк, сконструированный поверх Falcon, как в Hug.
-Такая же особенность присутствует и в других фреймворках, вдохновлённых идеей Falcon, использовать только один объект запроса и один объект ответа.
+Falcon — ещё один высокопроизводительный Python-фреймворк, он минималистичен и служит основой для других фреймворков, таких как Hug.
-!!! check "Идея для **FastAPI**"
- Найдите способы добиться отличной производительности.
+Он спроектирован так, что функции получают два параметра: «request» и «response». Затем вы «читаете» части из запроса и «пишете» части в ответ. Из‑за такого дизайна невозможно объявить параметры запроса и тело запроса стандартными аннотациями типов Python как параметры функции.
- Объявлять параметры `ответа сервера` в функциях, как в Hug.
+Поэтому валидация данных, сериализация и документация должны выполняться в коде вручную, не автоматически. Либо должны быть реализованы во фреймворке поверх Falcon, как в Hug. Та же особенность есть и в других фреймворках, вдохновлённых дизайном Falcon — с одним объектом запроса и одним объектом ответа в параметрах.
- Хотя в FastAPI это необязательно и используется в основном для установки заголовков, куки и альтернативных кодов состояния.
+/// check | Вдохновило **FastAPI** на
-### Molten
+Поиск способов получить отличную производительность.
-Molten мне попался на начальной стадии написания **FastAPI**. В нём были похожие идеи:
+Вместе с Hug (так как Hug основан на Falcon) вдохновило **FastAPI** объявлять параметр `response` в функциях.
-* Использование подсказок типов.
-* Валидация и документация исходя из этих подсказок.
+Хотя в FastAPI это необязательно, и используется в основном для установки HTTP-заголовков, cookie и альтернативных статус-кодов.
+
+///
+
+### [Molten](https://moltenframework.com/) { #molten }
+
+Я обнаружил Molten на ранних этапах создания **FastAPI**. И у него были очень похожие идеи:
+
+* Основан на аннотациях типов Python.
+* Валидация и документация из этих типов.
* Система внедрения зависимостей.
-В нём не используются сторонние библиотеки (такие, как Pydantic) для валидации, сериализации и документации.
-Поэтому переиспользовать эти определения типов непросто.
+Он не использует стороннюю библиотеку для валидации, сериализации и документации, такую как Pydantic, — у него своя. Поэтому такие определения типов данных будет сложнее переиспользовать.
+
+Требуются более многословные конфигурации. И так как он основан на WSGI (вместо ASGI), он не предназначен для использования преимуществ высокой производительности инструментов вроде Uvicorn, Starlette и Sanic.
+
+Система внедрения зависимостей требует предварительной регистрации зависимостей, а зависимости разрешаются по объявленным типам. Поэтому невозможно объявить более одного «компонента», предоставляющего определённый тип.
+
+Маршруты объявляются в одном месте, используя функции, объявленные в других местах (вместо декораторов, которые можно разместить прямо над функцией, обрабатывающей эндпоинт). Это ближе к тому, как это делает Django, чем Flask (и Starlette). Это разделяет в коде вещи, которые довольно тесно связаны.
+
+/// check | Вдохновило **FastAPI** на
+
+Определять дополнительные проверки типов данных, используя значение «по умолчанию» атрибутов модели. Это улучшает поддержку в редакторе кода, и раньше этого не было в Pydantic.
+
+Фактически это вдохновило на обновление частей Pydantic, чтобы поддерживать такой же стиль объявления валидации (вся эта функциональность теперь уже есть в Pydantic).
+
+///
+
+### [Hug](https://github.com/hugapi/hug) { #hug }
-Также требуется более подробная конфигурация и используется стандарт WSGI, который не предназначен для использования с высокопроизводительными инструментами, такими как Uvicorn, Starlette и Sanic, в отличие от ASGI.
+Hug был одним из первых фреймворков, реализовавших объявление типов параметров API с использованием аннотаций типов Python. Это была отличная идея, которая вдохновила и другие инструменты.
-Его система внедрения зависимостей требует предварительной регистрации, и зависимости определяются, как объявления типов.
-Из-за этого невозможно объявить более одного "компонента" (зависимости), который предоставляет определенный тип.
+Он использовал собственные типы в объявлениях вместо стандартных типов Python, но это всё равно был огромный шаг вперёд.
-Маршруты объявляются в единственном месте с использованием функций, объявленных в других местах (вместо использования декораторов, в которые могут быть обёрнуты функции, обрабатывающие конкретные ресурсы).
-Это больше похоже на Django, чем на Flask и Starlette.
-Он разделяет в коде вещи, которые довольно тесно связаны.
+Он также был одним из первых фреймворков, генерировавших собственную схему, описывающую весь API в JSON.
-!!! check "Идея для **FastAPI**"
- Определить дополнительные проверки типов данных, используя значения атрибутов модели "по умолчанию".
- Это улучшает помощь редактора и раньше это не было доступно в Pydantic.
+Он не был основан на стандартах вроде OpenAPI и JSON Schema. Поэтому интегрировать его с другими инструментами, такими как Swagger UI, было бы непросто. Но, опять же, это была очень инновационная идея.
- Фактически это подтолкнуло на обновление Pydantic для поддержки одинакового стиля проверок (теперь этот функционал уже доступен в Pydantic).
+У него есть интересная и необычная особенность: с помощью одного и того же фреймворка можно создавать и API, и CLI.
-### Hug
+Так как он основан на предыдущем стандарте для синхронных веб-фреймворков Python (WSGI), он не может работать с WebSocket и прочим, хотя также демонстрирует высокую производительность.
-Hug был одним из первых фреймворков, реализовавших объявление параметров API с использованием подсказок типов Python.
-Эта отличная идея была использована и другими инструментами.
+/// info | Информация
-При объявлении параметров вместо стандартных типов Python использовались собственные типы, но всё же это был огромный шаг вперед.
+Hug был создан Тимоти Кросли, тем же автором [`isort`](https://github.com/timothycrosley/isort), отличного инструмента для автоматической сортировки импортов в файлах Python.
-Это также был один из первых фреймворков, генерировавших полную API-схему в формате JSON.
+///
-Данная схема не придерживалась стандартов вроде OpenAPI и JSON Schema.
-Поэтому было бы непросто совместить её с другими инструментами, такими как Swagger UI.
-Но опять же, это была очень инновационная идея.
+/// check | Идеи, вдохновившие **FastAPI**
-Ещё у него есть интересная и необычная функция: используя один и тот же фреймворк можно создавать и API, и CLI.
+Hug вдохновил части APIStar и был одним из наиболее многообещающих инструментов, которые я нашёл, наряду с APIStar.
-Поскольку он основан на WSGI, старом стандарте для синхронных веб-фреймворков, он не может работать с веб-сокетами и другими модными штуками, но всё равно обладает высокой производительностью.
+Hug помог вдохновить **FastAPI** использовать аннотации типов Python для объявления параметров и автоматически генерировать схему, определяющую API.
-!!! info "Информация"
- Hug создан Timothy Crosley, автором `isort`, отличного инструмента для автоматической сортировки импортов в Python-файлах.
+Hug вдохновил **FastAPI** объявлять параметр `response` в функциях для установки HTTP-заголовков и cookie.
-!!! check "Идеи для **FastAPI**"
- Hug повлиял на создание некоторых частей APIStar и был одним из инструментов, которые я счел наиболее многообещающими, наряду с APIStar.
+///
- Hug натолкнул на мысли использовать в **FastAPI** подсказки типов Python для автоматического создания схемы, определяющей API и его параметры.
+### [APIStar](https://github.com/encode/apistar) (<= 0.5) { #apistar-0-5 }
- Hug вдохновил **FastAPI** объявить параметр `ответа` в функциях для установки заголовков и куки.
+Прямо перед решением строить **FastAPI** я нашёл сервер **APIStar**. В нём было почти всё, что я искал, и отличный дизайн.
-### APIStar (<= 0.5)
+Это была одна из первых реализаций фреймворка, использующего аннотации типов Python для объявления параметров и запросов (до NestJS и Molten), которые я видел. Я обнаружил его примерно в то же время, что и Hug. Но APIStar использовал стандарт OpenAPI.
-Непосредственно перед тем, как принять решение о создании **FastAPI**, я обнаружил **APIStar**.
-В нем было почти все, что я искал и у него был отличный дизайн.
+В нём были автоматические валидация данных, сериализация данных и генерация схемы OpenAPI на основе тех же аннотаций типов в нескольких местах.
-Это была одна из первых реализаций фреймворка, использующего подсказки типов для объявления параметров и запросов, которые я когда-либо видел (до NestJS и Molten).
-Я нашёл его примерно в то же время, что и Hug, но APIStar использовал стандарт OpenAPI.
+Определение схемы тела запроса не использовало те же аннотации типов Python, как в Pydantic, — это было ближе к Marshmallow, поэтому поддержка редактора кода была бы хуже, но всё равно APIStar оставался лучшим доступным вариантом.
-В нём были автоматические проверка и сериализация данных и генерация схемы OpenAPI основанные на подсказках типов в нескольких местах.
+На тот момент у него были лучшие показатели в бенчмарках (его превосходил только Starlette).
-При определении схемы тела сообщения не использовались подсказки типов, как в Pydantic, это больше похоже на Marshmallow, поэтому помощь редактора была недостаточно хорошей, но всё же APIStar был лучшим доступным вариантом.
+Сначала у него не было веб‑UI для автоматической документации API, но я знал, что могу добавить к нему Swagger UI.
-На тот момент у него были лучшие показатели производительности (проигрывающие только Starlette).
+У него была система внедрения зависимостей. Она требовала предварительной регистрации компонентов, как и другие инструменты, обсуждавшиеся выше. Но всё же это была отличная возможность.
-Изначально у него не было автоматической документации API для веб-интерфейса, но я знал, что могу добавить к нему Swagger UI.
+Мне так и не удалось использовать его в полном проекте, поскольку не было интеграции с системой безопасности, поэтому я не мог заменить все возможности, которые имел с full-stack генераторами на основе Flask-apispec. В моём бэклоге было создать пулл-реквест (запрос на изменение), добавляющий эту функциональность.
-В APIStar была система внедрения зависимостей, которая тоже требовала предварительную регистрацию компонентов, как и ранее описанные инструменты.
-Но, тем не менее, это была отличная штука.
+Затем фокус проекта сместился.
-Я не смог использовать его в полноценном проекте, так как были проблемы со встраиванием функций безопасности в схему OpenAPI, из-за которых невозможно было встроить все функции, применяемые в генераторах проектов на основе Flask-apispec.
-Я добавил в свой список задач создание пул-реквеста, добавляющего эту функциональность.
+Это перестал быть веб-фреймворк для API, так как автору нужно было сосредоточиться на Starlette.
-В дальнейшем фокус проекта сместился.
+Сейчас APIStar — это набор инструментов для валидации спецификаций OpenAPI, а не веб-фреймворк.
-Это больше не был API-фреймворк, так как автор сосредоточился на Starlette.
+/// info | Информация
-Ныне APIStar - это набор инструментов для проверки спецификаций OpenAPI.
+APIStar был создан Томом Кристи. Тем самым человеком, который создал:
-!!! info "Информация"
- APIStar был создан Tom Christie. Тот самый парень, который создал:
+* Django REST Framework
+* Starlette (на котором основан **FastAPI**)
+* Uvicorn (используется Starlette и **FastAPI**)
- * Django REST Framework
- * Starlette (на котором основан **FastAPI**)
- * Uvicorn (используемый в Starlette и **FastAPI**)
+///
-!!! check "Идеи для **FastAPI**"
- Воплощение.
+/// check | Вдохновило **FastAPI** на
- Мне казалось блестящей идеей объявлять множество функций (проверка данных, сериализация, документация) с помощью одних и тех же типов Python, которые при этом обеспечивают ещё и помощь редактора кода.
+Существование.
- После долгих поисков среди похожих друг на друга фреймворков и сравнения их различий, APIStar стал самым лучшим выбором.
+Идея объявлять сразу несколько вещей (валидацию данных, сериализацию и документацию) с помощью одних и тех же типов Python, которые одновременно обеспечивают отличную поддержку в редакторе кода, показалась мне блестящей.
- Но APIStar перестал быть фреймворком для создания веб-сервера, зато появился Starlette, новая и лучшая основа для построения подобных систем.
- Это была последняя капля, сподвигнувшая на создание **FastAPI**.
+После долгих поисков похожего фреймворка и тестирования множества альтернатив APIStar был лучшим доступным вариантом.
- Я считаю **FastAPI** "духовным преемником" APIStar, улучившим его возможности благодаря урокам, извлечённым из всех упомянутых выше инструментов.
+Затем APIStar перестал существовать как сервер, а был создан Starlette — новая и лучшая основа для такой системы. Это стало окончательным вдохновением для создания **FastAPI**.
-## Что используется в **FastAPI**
+Я считаю **FastAPI** «духовным преемником» APIStar, который улучшает и расширяет возможности, систему типов и другие части, опираясь на уроки от всех этих предыдущих инструментов.
-### Pydantic
+///
-Pydantic - это библиотека для валидации данных, сериализации и документирования (используя JSON Schema), основываясь на подсказках типов Python, что делает его чрезвычайно интуитивным.
+## Что используется в **FastAPI** { #used-by-fastapi }
-Его можно сравнить с Marshmallow, хотя в бенчмарках Pydantic быстрее, чем Marshmallow.
-И он основан на тех же подсказках типов, которые отлично поддерживаются редакторами кода.
+### [Pydantic](https://docs.pydantic.dev/) { #pydantic }
-!!! check "**FastAPI** использует Pydantic"
- Для проверки данных, сериализации данных и автоматической документации моделей (на основе JSON Schema).
+Pydantic — это библиотека для определения валидации данных, сериализации и документации (с использованием JSON Schema) на основе аннотаций типов Python.
- Затем **FastAPI** берёт эти схемы JSON и помещает их в схему OpenAPI, не касаясь других вещей, которые он делает.
+Благодаря этому он чрезвычайно интуитивен.
-### Starlette
+Его можно сравнить с Marshmallow. Хотя в бенчмарках он быстрее Marshmallow. И поскольку он основан на тех же аннотациях типов Python, поддержка в редакторе кода отличная.
-Starlette - это легковесный ASGI фреймворк/набор инструментов, который идеален для построения высокопроизводительных асинхронных сервисов.
+/// check | **FastAPI** использует его для
-Starlette очень простой и интуитивный.
-Он разработан таким образом, чтобы быть легко расширяемым и иметь модульные компоненты.
+Обработки всей валидации данных, сериализации данных и автоматической документации моделей (на основе JSON Schema).
+
+Затем **FastAPI** берёт эти данные JSON Schema и помещает их в OpenAPI, помимо всех прочих функций.
+
+///
+
+### [Starlette](https://www.starlette.dev/) { #starlette }
+
+Starlette — это лёгкий ASGI фреймворк/набор инструментов, идеально подходящий для создания высокопроизводительных asyncio‑сервисов.
+
+Он очень простой и интуитивный. Спроектирован так, чтобы его было легко расширять, и чтобы компоненты были модульными.
В нём есть:
* Впечатляющая производительность.
-* Поддержка веб-сокетов.
-* Фоновые задачи.
-* Обработка событий при старте и финише приложения.
-* Тестовый клиент на основе HTTPX.
-* Поддержка CORS, сжатие GZip, статические файлы, потоковая передача данных.
-* Поддержка сессий и куки.
+* Поддержка WebSocket.
+* Фоновые задачи, выполняемые в том же процессе.
+* События запуска и завершения.
+* Тестовый клиент на базе HTTPX.
+* CORS, GZip, статические файлы, потоковые ответы.
+* Поддержка сессий и cookie.
* 100% покрытие тестами.
-* 100% аннотированный код.
-* Несколько жёстких зависимостей.
+* 100% кодовой базы с аннотациями типов.
+* Мало жёстких зависимостей.
+
+В настоящее время Starlette — самый быстрый из протестированных Python-фреймворков. Его превосходит только Uvicorn, который не фреймворк, а сервер.
+
+Starlette предоставляет весь базовый функционал веб-микрофреймворка.
+
+Но он не предоставляет автоматическую валидацию данных, сериализацию или документацию.
+
+Это одна из главных вещей, которые **FastAPI** добавляет поверх, всё на основе аннотаций типов Python (с использованием Pydantic). Плюс система внедрения зависимостей, утилиты безопасности, генерация схемы OpenAPI и т. д.
+
+/// note | Технические детали
+
+ASGI — это новый «стандарт», разрабатываемый участниками core-команды Django. Он всё ещё не является «стандартом Python» (PEP), хотя процесс идёт.
+
+Тем не менее его уже используют как «стандарт» несколько инструментов. Это сильно улучшает совместимость: вы можете заменить Uvicorn на любой другой ASGI-сервер (например, Daphne или Hypercorn) или добавить совместимые с ASGI инструменты, такие как `python-socketio`.
-В настоящее время Starlette показывает самую высокую скорость среди Python-фреймворков в тестовых замерах.
-Быстрее только Uvicorn, который является сервером, а не фреймворком.
+///
-Starlette обеспечивает весь функционал микрофреймворка, но не предоставляет автоматическую валидацию данных, сериализацию и документацию.
+/// check | **FastAPI** использует его для
-**FastAPI** добавляет эти функции используя подсказки типов Python и Pydantic.
-Ещё **FastAPI** добавляет систему внедрения зависимостей, утилиты безопасности, генерацию схемы OpenAPI и т.д.
+Обработки всех основных веб-частей. Добавляя возможности поверх.
-!!! note "Технические детали"
- ASGI - это новый "стандарт" разработанный участниками команды Django.
- Он пока что не является "стандартом в Python" (то есть принятым PEP), но процесс принятия запущен.
+Класс `FastAPI` напрямую наследуется от класса `Starlette`.
- Тем не менее он уже используется в качестве "стандарта" несколькими инструментами.
- Это значительно улучшает совместимость, поскольку Вы можете переключиться с Uvicorn на любой другой ASGI-сервер (например, Daphne или Hypercorn) или Вы можете добавить ASGI-совместимые инструменты, такие как `python-socketio`.
+Так что всё, что вы можете сделать со Starlette, вы можете сделать напрямую с **FastAPI**, по сути это «Starlette на стероидах».
-!!! check "**FastAPI** использует Starlette"
- В качестве ядра веб-сервиса для обработки запросов, добавив некоторые функции сверху.
+///
- Класс `FastAPI` наследуется напрямую от класса `Starlette`.
+### [Uvicorn](https://www.uvicorn.dev/) { #uvicorn }
- Таким образом, всё что Вы могли делать со Starlette, Вы можете делать с **FastAPI**, по сути это прокачанный Starlette.
+Uvicorn — молниеносный ASGI-сервер, построенный на uvloop и httptools.
-### Uvicorn
+Это не веб-фреймворк, а сервер. Например, он не предоставляет инструменты для маршрутизации по путям. Это предоставляет сверху фреймворк, такой как Starlette (или **FastAPI**).
-Uvicorn - это молниеносный ASGI-сервер, построенный на uvloop и httptools.
+Это рекомендуемый сервер для Starlette и **FastAPI**.
-Uvicorn является сервером, а не фреймворком.
-Например, он не предоставляет инструментов для маршрутизации запросов по ресурсам.
-Для этого нужна надстройка, такая как Starlette (или **FastAPI**).
+/// check | **FastAPI** рекомендует его как
-Он рекомендуется в качестве сервера для Starlette и **FastAPI**.
+Основной веб-сервер для запуска приложений **FastAPI**.
-!!! check "**FastAPI** рекомендует его"
- Как основной сервер для запуска приложения **FastAPI**.
+Также вы можете использовать опцию командной строки `--workers`, чтобы получить асинхронный многопроцессный сервер.
- Вы можете объединить его с Gunicorn, чтобы иметь асинхронный многопроцессный сервер.
+Подробнее см. раздел [Развёртывание](deployment/index.md).
- Узнать больше деталей можно в разделе [Развёртывание](deployment/index.md){.internal-link target=_blank}.
+///
-## Тестовые замеры и скорость
+## Бенчмарки и скорость { #benchmarks-and-speed }
-Чтобы понять, сравнить и увидеть разницу между Uvicorn, Starlette и FastAPI, ознакомьтесь с разделом [Тестовые замеры](benchmarks.md){.internal-link target=_blank}.
+Чтобы понять, сравнить и увидеть разницу между Uvicorn, Starlette и FastAPI, см. раздел о [Бенчмарках](benchmarks.md).
diff --git a/docs/ru/docs/async.md b/docs/ru/docs/async.md
index 4c44fc22d37f4..7fd702184c37f 100644
--- a/docs/ru/docs/async.md
+++ b/docs/ru/docs/async.md
@@ -1,18 +1,18 @@
-# Конкурентность и async / await
+# Конкурентность и async / await { #concurrency-and-async-await }
-Здесь приведена подробная информация об использовании синтаксиса `async def` при написании *функций обработки пути*, а также рассмотрены основы асинхронного программирования, конкурентности и параллелизма.
+Подробности о синтаксисе `async def` для *функций-обработчиков пути* и немного фона об асинхронном коде, конкурентности и параллелизме.
-## Нет времени?
+## Нет времени? { #in-a-hurry }
-TL;DR:
+TL;DR:
-Допустим, вы используете сторонюю библиотеку, которая требует вызова с ключевым словом `await`:
+Если вы используете сторонние библиотеки, которые нужно вызывать с `await`, например:
```Python
results = await some_library()
```
-В этом случае *функции обработки пути* необходимо объявлять с использованием синтаксиса `async def`:
+Тогда объявляйте *функции-обработчиков пути* с `async def`, например:
```Python hl_lines="2"
@app.get('/')
@@ -21,15 +21,15 @@ async def read_results():
return results
```
-!!! note
- `await` можно использовать только внутри функций, объявленных с использованием `async def`.
+/// note | Примечание
+
+`await` можно использовать только внутри функций, объявленных с `async def`.
+
+///
---
-Если вы обращаетесь к сторонней библиотеке, которая с чем-то взаимодействует
-(с базой данных, API, файловой системой и т. д.), и не имеет поддержки синтаксиса `await`
-(что относится сейчас к большинству библиотек для работы с базами данных), то
-объявляйте *функции обработки пути* обычным образом с помощью `def`, например:
+Если вы используете стороннюю библиотеку, которая взаимодействует с чем-то (база данных, API, файловая система и т.д.) и не поддерживает использование `await` (сейчас это относится к большинству библиотек для БД), тогда объявляйте *функции-обработчиков пути* как обычно, просто с `def`, например:
```Python hl_lines="2"
@app.get('/')
@@ -40,310 +40,283 @@ def results():
---
-Если вашему приложению (странным образом) не нужно ни с чем взаимодействовать и, соответственно,
-ожидать ответа, используйте `async def`.
+Если вашему приложению (по какой-то причине) не нужно ни с чем взаимодействовать и ждать ответа, используйте `async def`, даже если внутри не нужен `await`.
---
-Если вы не уверены, используйте обычный синтаксис `def`.
+Если вы просто не уверены, используйте обычный `def`.
---
-**Примечание**: при необходимости можно смешивать `def` и `async def` в *функциях обработки пути*
-и использовать в каждом случае наиболее подходящий синтаксис. А FastAPI сделает с этим всё, что нужно.
+**Примечание**: вы можете смешивать `def` и `async def` в *функциях-обработчиков пути* столько, сколько нужно, и объявлять каждую так, как лучше для вашего случая. FastAPI сделает с ними всё как надо.
-В любом из описанных случаев FastAPI работает асинхронно и очень быстро.
+В любом из случаев выше FastAPI всё равно работает асинхронно и очень быстро.
-Однако придерживаясь указанных советов, можно получить дополнительную оптимизацию производительности.
+Но следуя этим шагам, он сможет выполнить некоторые оптимизации производительности.
-## Технические подробности
+## Технические подробности { #technical-details }
-Современные версии Python поддерживают разработку так называемого **"асинхронного кода"** посредством написания **"сопрограмм"** с использованием синтаксиса **`async` и `await`**.
+Современные версии Python поддерживают **«асинхронный код»** с помощью **«сопрограмм»** (coroutines) и синтаксиса **`async` и `await`**.
-Ниже разберём эту фразу по частям:
+Разберём эту фразу по частям в разделах ниже:
* **Асинхронный код**
* **`async` и `await`**
* **Сопрограммы**
-## Асинхронный код
+## Асинхронный код { #asynchronous-code }
+
+Асинхронный код значит, что в языке 💬 есть способ сказать компьютеру/программе 🤖, что в некоторый момент кода ему 🤖 придётся подождать, пока *что-то ещё* где-то в другом месте завершится. Назовём это *что-то ещё* «медленный файл» 📝.
+
+И пока мы ждём завершения работы с «медленным файлом» 📝, компьютер может заняться другой работой.
+
+Затем компьютер/программа 🤖 будет возвращаться каждый раз, когда появится возможность (пока снова где-то идёт ожидание), или когда 🤖 завершит всю текущую работу. И он 🤖 проверит, не завершилась ли какая-либо из задач, которых он ждал, и сделает то, что нужно.
+
+Далее он 🤖 возьмёт первую завершившуюся задачу (скажем, наш «медленный файл» 📝) и продолжит делать с ней то, что требуется.
-Асинхронный код означает, что в языке 💬 есть возможность сообщить машине / программе 🤖,
-что в определённой точке кода ей 🤖 нужно будет ожидать завершения выполнения *чего-то ещё* в другом месте. Допустим это *что-то ещё* называется "медленный файл" 📝.
+Это «ожидание чего-то ещё» обычно относится к операциям I/O, которые относительно «медленные» (по сравнению со скоростью процессора и оперативной памяти), например ожидание:
-И пока мы ждём завершения работы с "медленным файлом" 📝, компьютер может переключиться для выполнения других задач.
+* отправки данных клиентом по сети
+* получения клиентом данных, отправленных вашей программой по сети
+* чтения системой содержимого файла на диске и передачи этих данных вашей программе
+* записи на диск содержимого, которое ваша программа передала системе
+* операции удалённого API
+* завершения операции базы данных
+* возврата результатов запроса к базе данных
+* и т.д.
-Но при каждой возможности компьютер / программа 🤖 будет возвращаться обратно. Например, если он 🤖 опять окажется в режиме ожидания, или когда закончит всю работу. В этом случае компьютер 🤖 проверяет, не завершена ли какая-нибудь из текущих задач.
+Поскольку основное время выполнения уходит на ожидание операций I/O, их называют операциями, «ограниченными вводом-выводом» (I/O bound).
-Потом он 🤖 берёт первую выполненную задачу (допустим, наш "медленный файл" 📝) и продолжает работу, производя с ней необходимые действия.
+Это называется «асинхронным», потому что компьютеру/программе не нужно «синхронизироваться» с медленной задачей, простаивая и выжидая точный момент её завершения, чтобы забрать результат и продолжить работу.
-Вышеупомянутое "что-то ещё", завершения которого приходится ожидать, обычно относится к достаточно "медленным" операциям I/O (по сравнению со скоростью работы процессора и оперативной памяти), например:
+Вместо этого, в «асинхронной» системе, уже завершившаяся задача может немного подождать (несколько микросекунд) в очереди, пока компьютер/программа завершит то, чем занимался, и затем вернётся, чтобы забрать результаты и продолжить работу с ними.
-* отправка данных от клиента по сети
-* получение клиентом данных, отправленных вашей программой по сети
-* чтение системой содержимого файла с диска и передача этих данных программе
-* запись на диск данных, которые программа передала системе
-* обращение к удалённому API
-* ожидание завершения операции с базой данных
-* получение результатов запроса к базе данных
-* и т. д.
+Для «синхронного» (в противоположность «асинхронному») исполнения часто используют термин «последовательный», потому что компьютер/программа выполняет все шаги по порядку, прежде чем переключиться на другую задачу, даже если эти шаги включают ожидание.
-Поскольку в основном время тратится на ожидание выполнения операций I/O,
-их обычно называют операциями, ограниченными скоростью ввода-вывода.
+### Конкурентность и бургеры { #concurrency-and-burgers }
-Код называют "асинхронным", потому что компьютеру / программе не требуется "синхронизироваться" с медленной задачей и,
-будучи в простое, ожидать момента её завершения, с тем чтобы забрать результат и продолжить работу.
+Та идея **асинхронного** кода, описанная выше, иногда также называется **«конкурентностью»**. Она отличается от **«параллелизма»**.
-Вместо этого в "асинхронной" системе завершённая задача может немного подождать (буквально несколько микросекунд),
-пока компьютер / программа занимается другими важными вещами, с тем чтобы потом вернуться,
-забрать результаты выполнения и начать их обрабатывать.
+И **конкурентность**, и **параллелизм** относятся к «разным вещам, происходящим примерно одновременно».
-"Синхронное" исполнение (в противовес "асинхронному") также называют "последовательным",
-потому что компьютер / программа последовательно выполняет все требуемые шаги перед тем, как перейти к следующей задаче,
-даже если в процессе приходится ждать.
+Но различия между *конкурентностью* и *параллелизмом* довольно существенные.
-### Конкурентность и бургеры
+Чтобы их увидеть, представьте следующую историю про бургеры:
-Тот **асинхронный** код, о котором идёт речь выше, иногда называют **"конкурентностью"**. Она отличается от **"параллелизма"**.
+### Конкурентные бургеры { #concurrent-burgers }
-Да, **конкурентность** и **параллелизм** подразумевают, что разные вещи происходят примерно в одно время.
+Вы идёте со своей возлюбленной за фастфудом, вы стоите в очереди, пока кассир принимает заказы у людей перед вами. 😍
-Но внутреннее устройство **конкурентности** и **параллелизма** довольно разное.
+
-Чтобы это понять, представьте такую картину:
+Наконец ваша очередь: вы заказываете 2 очень «навороченных» бургера — для вашей возлюбленной и для себя. 🍔🍔
-### Конкурентные бургеры
+
-
+Кассир говорит что-то повару на кухне, чтобы они знали, что нужно приготовить ваши бургеры (хотя сейчас они готовят бургеры для предыдущих клиентов).
-Вы идёте со своей возлюбленной 😍 в фастфуд 🍔 и становитесь в очередь, в это время кассир 💁 принимает заказы у посетителей перед вами.
+
-Когда наконец подходит очередь, вы заказываете парочку самых вкусных и навороченных бургеров 🍔, один для своей возлюбленной 😍, а другой себе.
+Вы платите. 💸
-Отдаёте деньги 💸.
+Кассир выдаёт вам номер вашей очереди.
-Кассир 💁 что-то говорит поварам на кухне 👨🍳, теперь они знают, какие бургеры нужно будет приготовить 🍔
-(но пока они заняты бургерами предыдущих клиентов).
+
-Кассир 💁 отдаёт вам чек с номером заказа.
+Пока вы ждёте, вы вместе со своей возлюбленной идёте и выбираете столик, садитесь и долго болтаете (ваши бургеры очень «навороченные», поэтому им нужно время на приготовление).
-В ожидании еды вы идёте со своей возлюбленной 😍 выбрать столик, садитесь и довольно продолжительное время общаетесь 😍
-(поскольку ваши бургеры самые навороченные, готовятся они не так быстро ✨🍔✨).
+Сидя за столиком со своей возлюбленной в ожидании бургеров, вы можете провести это время, восхищаясь тем, какая она классная, милая и умная ✨😍✨.
-Сидя за столиком с возлюбленной 😍 в ожидании бургеров 🍔, вы отлично проводите время,
-восхищаясь её великолепием, красотой и умом ✨😍✨.
+
-Всё ещё ожидая заказ и болтая со своей возлюбленной 😍, время от времени вы проверяете,
-какой номер горит над прилавком, и не подошла ли уже ваша очередь.
+Пока вы ждёте и разговариваете, время от времени вы поглядываете на номер на табло, чтобы понять, не подошла ли уже ваша очередь.
-И вот наконец настаёт этот момент, и вы идёте к стойке, чтобы забрать бургеры 🍔 и вернуться за столик.
+И вот в какой-то момент ваша очередь наступает. Вы подходите к стойке, забираете свои бургеры и возвращаетесь к столику.
-Вы со своей возлюбленной 😍 едите бургеры 🍔 и отлично проводите время ✨.
+
+
+Вы со своей возлюбленной едите бургеры и отлично проводите время. ✨
+
+
+
+/// info | Информация
+
+Прекрасные иллюстрации от [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨
+
+///
---
-А теперь представьте, что в этой небольшой истории вы компьютер / программа 🤖.
+Представьте, что в этой истории вы — компьютер/программа 🤖.
-В очереди вы просто глазеете по сторонам 😴, ждёте и ничего особо "продуктивного" не делаете.
-Но очередь движется довольно быстро, поскольку кассир 💁 только принимает заказы (а не занимается приготовлением еды), так что ничего страшного.
+Пока вы стоите в очереди, вы просто бездействуете 😴, ждёте своей очереди и не делаете ничего особо «продуктивного». Но очередь движется быстро, потому что кассир только принимает заказы (а не готовит их), так что это нормально.
-Когда подходит очередь вы наконец предпринимаете "продуктивные" действия 🤓: просматриваете меню, выбираете в нём что-то, узнаёте, что хочет ваша возлюбленная 😍, собираетесь оплатить 💸, смотрите, какую достали карту, проверяете, чтобы с вас списали верную сумму, и что в заказе всё верно и т. д.
+Когда приходит ваша очередь, вы выполняете действительно «продуктивную» работу: просматриваете меню, решаете, чего хотите, учитываете выбор своей возлюбленной, платите, проверяете, что дали правильную купюру/карту, что сумма списана корректно, что в заказе верные позиции и т.д.
-И хотя вы всё ещё не получили бургеры 🍔, ваша работа с кассиром 💁 ставится "на паузу" ⏸,
-поскольку теперь нужно ждать 🕙, когда заказ приготовят.
+Но затем, хотя у вас ещё нет бургеров, ваша «работа» с кассиром поставлена «на паузу» ⏸, потому что нужно подождать 🕙, пока бургеры будут готовы.
-Но отойдя с номерком от прилавка, вы садитесь за столик и можете переключить 🔀 внимание
-на свою возлюбленную 😍 и "работать" ⏯ 🤓 уже над этим. И вот вы снова очень
-"продуктивны" 🤓, мило болтаете вдвоём и всё такое 😍.
+Но, отойдя от стойки и сев за столик с номерком, вы можете переключить 🔀 внимание на свою возлюбленную и «поработать» ⏯ 🤓 над этим. Снова очень «продуктивно» — флирт с вашей возлюбленной 😍.
-В какой-то момент кассир 💁 поместит на табло ваш номер, подразумевая, что бургеры готовы 🍔, но вы не станете подскакивать как умалишённый, лишь только увидев на экране свою очередь. Вы уверены, что ваши бургеры 🍔 никто не утащит, ведь у вас свой номерок, а у других свой.
+Потом кассир 💁 «говорит»: «Я закончил делать бургеры», — выводя ваш номер на табло, но вы не подпрыгиваете как сумасшедший в ту же секунду, как только номер сменился на ваш. Вы знаете, что ваши бургеры никто не украдёт, потому что у вас есть номер вашей очереди, а у других — их.
-Поэтому вы подождёте, пока возлюбленная 😍 закончит рассказывать историю (закончите текущую работу ⏯ / задачу в обработке 🤓),
-и мило улыбнувшись, скажете, что идёте забирать заказ ⏸.
+Поэтому вы дожидаетесь, пока ваша возлюбленная закончит историю (завершится текущая работа ⏯ / выполняемая задача 🤓), мягко улыбаетесь и говорите, что идёте за бургерами ⏸.
-И вот вы подходите к стойке 🔀, к первоначальной задаче, которая уже завершена ⏯, берёте бургеры 🍔, говорите спасибо и относите заказ за столик. На этом заканчивается этап / задача взаимодействия с кассой ⏹.
-В свою очередь порождается задача "поедание бургеров" 🔀 ⏯, но предыдущая ("получение бургеров") завершена ⏹.
+Затем вы идёте к стойке 🔀, к исходной задаче, которая теперь завершена ⏯, забираете бургеры, благодарите и несёте их к столику. На этом шаг/задача взаимодействия со стойкой завершён ⏹. Это, в свою очередь, создаёт новую задачу — «есть бургеры» 🔀 ⏯, но предыдущая «получить бургеры» — завершена ⏹.
-### Параллельные бургеры
+### Параллельные бургеры { #parallel-burgers }
-Теперь представим, что вместо бургерной "Конкурентные бургеры" вы решили сходить в "Параллельные бургеры".
+Теперь представим, что это не «Конкурентные бургеры», а «Параллельные бургеры».
-И вот вы идёте со своей возлюбленной 😍 отведать параллельного фастфуда 🍔.
+Вы идёте со своей возлюбленной за параллельным фастфудом.
-Вы становитесь в очередь пока несколько (пусть будет 8) кассиров, которые по совместительству ещё и повары 👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳, принимают заказы у посетителей перед вами.
+Вы стоите в очереди, пока несколько (скажем, 8) кассиров, которые одновременно являются поварами, принимают заказы у людей перед вами.
-При этом клиенты не отходят от стойки и ждут 🕙 получения еды, поскольку каждый
-из 8 кассиров идёт на кухню готовить бургеры 🍔, а только потом принимает следующий заказ.
+Все перед вами ждут, пока их бургеры будут готовы, не отходя от стойки, потому что каждый из 8 кассиров сразу идёт готовить бургер перед тем, как принять следующий заказ.
-Наконец настаёт ваша очередь, и вы просите два самых навороченных бургера 🍔, один для дамы сердца 😍, а другой себе.
+
-Ни о чём не жалея, расплачиваетесь 💸.
+Наконец ваша очередь: вы заказываете 2 очень «навороченных» бургера — для вашей возлюбленной и для себя.
-И кассир уходит на кухню 👨🍳.
+Вы платите 💸.
-Вам приходится ждать перед стойкой 🕙, чтобы никто по случайности не забрал ваши бургеры 🍔, ведь никаких номерков у вас нет.
+
-Поскольку вы с возлюбленной 😍 хотите получить заказ вовремя 🕙, и следите за тем, чтобы никто не вклинился в очередь,
-у вас не получается уделять должного внимание своей даме сердца 😞.
+Кассир уходит на кухню.
-Это "синхронная" работа, вы "синхронизированы" с кассиром/поваром 👨🍳. Приходится ждать 🕙 у стойки,
-когда кассир/повар 👨🍳 закончит делать бургеры 🍔 и вручит вам заказ, иначе его случайно может забрать кто-то другой.
+Вы ждёте, стоя у стойки 🕙, чтобы никто не забрал ваши бургеры раньше вас, так как никаких номерков нет.
-Наконец кассир/повар 👨🍳 возвращается с бургерами 🍔 после невыносимо долгого ожидания 🕙 за стойкой.
+
-Вы скорее забираете заказ 🍔 и идёте с возлюбленной 😍 за столик.
+Так как вы со своей возлюбленной заняты тем, чтобы никто не встал перед вами и не забрал ваши бургеры, как только они появятся, вы не можете уделить внимание своей возлюбленной. 😞
-Там вы просто едите эти бургеры, и на этом всё 🍔 ⏹.
+Это «синхронная» работа, вы «синхронизированы» с кассиром/поваром 👨🍳. Вам нужно ждать 🕙 и находиться там в точный момент, когда кассир/повар 👨🍳 закончит бургеры и вручит их вам, иначе их может забрать кто-то другой.
-Вам не особо удалось пообщаться, потому что большую часть времени 🕙 пришлось провести у кассы 😞.
+
----
+Затем ваш кассир/повар 👨🍳 наконец возвращается с вашими бургерами, после долгого ожидания 🕙 у стойки.
-В описанном сценарии вы компьютер / программа 🤖 с двумя исполнителями (вы и ваша возлюбленная 😍),
-на протяжении долгого времени 🕙 вы оба уделяете всё внимание ⏯ задаче "ждать на кассе".
+
-В этом ресторане быстрого питания 8 исполнителей (кассиров/поваров) 👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳.
-Хотя в бургерной конкурентного типа было всего два (один кассир и один повар) 💁 👨🍳.
+Вы берёте бургеры и идёте со своей возлюбленной к столику.
-Несмотря на обилие работников, опыт в итоге получился не из лучших 😞.
+Вы просто их съедаете — и всё. ⏹
+
+
+
+Разговоров и флирта было немного, потому что большую часть времени вы ждали 🕙 у стойки. 😞
+
+/// info | Информация
+
+Прекрасные иллюстрации от [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨
+
+///
---
-Так бы выглядел аналог истории про бургерную 🍔 в "параллельном" мире.
+В этом сценарии «параллельных бургеров» вы — компьютер/программа 🤖 с двумя процессорами (вы и ваша возлюбленная), оба ждут 🕙 и уделяют внимание ⏯ тому, чтобы «ждать у стойки» 🕙 долгое время.
-Вот более реалистичный пример. Представьте себе банк.
+В ресторане 8 процессоров (кассиров/поваров). Тогда как в «конкурентных бургерах» могло быть только 2 (один кассир и один повар).
-До недавних пор в большинстве банков было несколько кассиров 👨💼👨💼👨💼👨💼 и длинные очереди 🕙🕙🕙🕙🕙🕙🕙🕙.
+И всё же финальный опыт — не самый лучший. 😞
-Каждый кассир обслуживал одного клиента, потом следующего 👨💼⏯.
+---
-Нужно было долгое время 🕙 стоять перед окошком вместе со всеми, иначе пропустишь свою очередь.
+Это была параллельная версия истории про бургеры. 🍔
-Сомневаюсь, что у вас бы возникло желание прийти с возлюбленной 😍 в банк 🏦 оплачивать налоги.
+Для более «жизненного» примера представьте банк.
-### Выводы о бургерах
+До недавнего времени в большинстве банков было несколько кассиров 👨💼👨💼👨💼👨💼 и длинная очередь 🕙🕙🕙🕙🕙🕙🕙🕙.
-В нашей истории про поход в фастфуд за бургерами приходится много ждать 🕙,
-поэтому имеет смысл организовать конкурентную систему ⏸🔀⏯.
+Все кассиры делают всю работу с одним клиентом за другим 👨💼⏯.
-И то же самое с большинством веб-приложений.
+И вам приходится долго 🕙 стоять в очереди, иначе вы потеряете свою очередь.
-Пользователей очень много, но ваш сервер всё равно вынужден ждать 🕙 запросы по их слабому интернет-соединению.
+Вы вряд ли захотите взять свою возлюбленную 😍 с собой, чтобы заняться делами в банке 🏦.
-Потом снова ждать 🕙, пока вернётся ответ.
+### Вывод про бургеры { #burger-conclusion }
-
-Это ожидание 🕙 измеряется микросекундами, но если всё сложить, то набегает довольно много времени.
+В этом сценарии «фастфуда с вашей возлюбленной», так как много ожидания 🕙, гораздо логичнее иметь конкурентную систему ⏸🔀⏯.
-Вот почему есть смысл использовать асинхронное ⏸🔀⏯ программирование при построении веб-API.
+Так обстоит дело и с большинством веб-приложений.
-Большинство популярных фреймворков (включая Flask и Django) создавались
-до появления в Python новых возможностей асинхронного программирования. Поэтому
-их можно разворачивать с поддержкой параллельного исполнения или асинхронного
-программирования старого типа, которое не настолько эффективно.
+Очень много пользователей, но ваш сервер ждёт 🕙, пока их не самое хорошее соединение отправит их запросы.
-При том, что основная спецификация асинхронного взаимодействия Python с веб-сервером
-(ASGI)
-была разработана командой Django для внедрения поддержки веб-сокетов.
+А затем снова ждёт 🕙, пока отправятся ответы.
-Именно асинхронность сделала NodeJS таким популярным (несмотря на то, что он не параллельный),
-и в этом преимущество Go как языка программирования.
+Это «ожидание» 🕙 измеряется микросекундами, но если всё сложить, то в сумме получается много ожидания.
-И тот же уровень производительности даёт **FastAPI**.
+Вот почему асинхронный ⏸🔀⏯ код очень уместен для веб-API.
-Поскольку можно использовать преимущества параллелизма и асинхронности вместе,
-вы получаете производительность лучше, чем у большинства протестированных NodeJS фреймворков
-и на уровне с Go, который является компилируемым языком близким к C (всё благодаря Starlette).
+Именно такая асинхронность сделала NodeJS популярным (хотя NodeJS — не параллельный), и это сильная сторона Go как языка программирования.
-### Получается, конкурентность лучше параллелизма?
+Того же уровня производительности вы получаете с **FastAPI**.
-Нет! Мораль истории совсем не в этом.
+А так как можно одновременно использовать параллелизм и асинхронность, вы получаете производительность выше, чем у большинства протестированных фреймворков на NodeJS и на уровне Go, который — компилируемый язык, ближе к C [(всё благодаря Starlette)](https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=query&l=zijmkf-1).
-Конкурентность отличается от параллелизма. Она лучше в **конкретных** случаях, где много времени приходится на ожидание.
-Вот почему она зачастую лучше параллелизма при разработке веб-приложений. Но это не значит, что конкурентность лучше в любых сценариях.
+### Конкурентность лучше параллелизма? { #is-concurrency-better-than-parallelism }
-Давайте посмотрим с другой стороны, представьте такую картину:
+Нет! Мораль истории не в этом.
-> Вам нужно убраться в большом грязном доме.
+Конкурентность отличается от параллелизма. И она лучше в **конкретных** сценариях, где много ожидания. Поэтому при разработке веб-приложений она обычно намного лучше параллелизма. Но не во всём.
+
+Чтобы уравновесить это, представьте такую короткую историю:
+
+> Вам нужно убрать большой грязный дом.
*Да, это вся история*.
---
-Тут не нужно нигде ждать 🕙, просто есть куча работы в разных частях дома.
+Здесь нигде нет ожидания 🕙, просто очень много работы в разных местах дома.
-Можно организовать очередь как в примере с бургерами, сначала гостиная, потом кухня,
-но это ни на что не повлияет, поскольку вы нигде не ждёте 🕙, а просто трёте да моете.
+Можно организовать «очереди» как в примере с бургерами — сначала гостиная, потом кухня, — но так как вы ничего не ждёте 🕙, а просто убираете и убираете, очереди ни на что не повлияют.
-И понадобится одинаковое количество времени с очередью (конкурентностью) и без неё,
-и работы будет сделано тоже одинаковое количество.
+На завершение уйдёт одинаковое время — с очередями (конкурентностью) и без них — и объём выполненной работы будет одинаковым.
-Однако в случае, если бы вы могли привести 8 бывших кассиров/поваров, а ныне уборщиков 👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳,
-и каждый из них (вместе с вами) взялся бы за свой участок дома,
-с такой помощью вы бы закончили намного быстрее, делая всю работу **параллельно**.
+Но в этом случае, если бы вы могли привести 8 бывших кассиров/поваров, а теперь — уборщиков, и каждый из них (плюс вы) взял бы свою зону дома для уборки, вы могли бы сделать всю работу **параллельно**, с дополнительной помощью, и завершить гораздо быстрее.
-В описанном сценарии каждый уборщик (включая вас) был бы исполнителем, занятым на своём участке работы.
+В этом сценарии каждый уборщик (включая вас) был бы процессором, выполняющим свою часть работы.
-И поскольку большую часть времени выполнения занимает реальная работа (а не ожидание),
-а работу в компьютере делает ЦП,
-такие задачи называют ограниченными производительностью процессора.
+И так как основное время выполнения уходит на реальную работу (а не ожидание), а работу в компьютере выполняет CPU, такие задачи называют «ограниченными процессором» (CPU bound).
---
-Ограничение по процессору проявляется в операциях, где требуется выполнять сложные математические вычисления.
+Типичные примеры CPU-bound операций — те, которые требуют сложной математической обработки.
Например:
-* Обработка **звука** или **изображений**.
-* **Компьютерное зрение**: изображение состоит из миллионов пикселей, в каждом пикселе 3 составляющих цвета,
-обработка обычно требует проведения расчётов по всем пикселям сразу.
-* **Машинное обучение**: здесь обычно требуется умножение "матриц" и "векторов".
-Представьте гигантскую таблицу с числами в Экселе, и все их надо одновременно перемножить.
-* **Глубокое обучение**: это область *машинного обучения*, поэтому сюда подходит то же описание.
-Просто у вас будет не одна таблица в Экселе, а множество. В ряде случаев используется
-специальный процессор для создания и / или использования построенных таким образом моделей.
+* Обработка **аудио** или **изображений**.
+* **Компьютерное зрение**: изображение состоит из миллионов пикселей, каждый пиксель имеет 3 значения/цвета; обычно требуется вычислить что-то для всех этих пикселей одновременно.
+* **Машинное обучение**: обычно требует множества умножений «матриц» и «векторов». Представьте огромную таблицу с числами и умножение всех этих чисел «одновременно».
+* **Глубокое обучение**: это подполе Машинного обучения, так что всё вышесказанное применимо. Просто это не одна таблица чисел, а их огромный набор, и во многих случаях вы используете специальный процессор, чтобы строить и/или использовать такие модели.
-### Конкурентность + параллелизм: Веб + машинное обучение
+### Конкурентность + параллелизм: Веб + Машинное обучение { #concurrency-parallelism-web-machine-learning }
-**FastAPI** предоставляет возможности конкуретного программирования,
-которое очень распространено в веб-разработке (именно этим славится NodeJS).
+С **FastAPI** вы можете использовать преимущества конкурентности, что очень распространено в веб-разработке (это та же основная «фишка» NodeJS).
-Кроме того вы сможете использовать все преимущества параллелизма и
-многопроцессорности (когда несколько процессов работают параллельно),
-если рабочая нагрузка предполагает **ограничение по процессору**,
-как, например, в системах машинного обучения.
+Но вы также можете использовать выгоды параллелизма и многопроцессности (когда несколько процессов работают параллельно) для рабочих нагрузок, **ограниченных процессором** (CPU bound), как в системах Машинного обучения.
-Необходимо также отметить, что Python является главным языком в области
-**дата-сайенс**,
-машинного обучения и, особенно, глубокого обучения. Всё это делает FastAPI
-отличным вариантом (среди многих других) для разработки веб-API и приложений
-в области дата-сайенс / машинного обучения.
+Плюс к этому простой факт, что Python — основной язык для **Data Science**, Машинного обучения и особенно Глубокого обучения, делает FastAPI очень хорошим выбором для веб-API и приложений в области Data Science / Машинного обучения (среди многих других).
-Как добиться такого параллелизма в эксплуатации описано в разделе [Развёртывание](deployment/index.md){.internal-link target=_blank}.
+Как добиться такого параллелизма в продакшн, см. раздел [Развёртывание](deployment/index.md).
-## `async` и `await`
+## `async` и `await` { #async-and-await }
-В современных версиях Python разработка асинхронного кода реализована очень интуитивно.
-Он выглядит как обычный "последовательный" код и самостоятельно выполняет "ожидание", когда это необходимо.
+В современных версиях Python есть очень интуитивный способ определять асинхронный код. Это делает его похожим на обычный «последовательный» код, а «ожидание» выполняется за вас в нужные моменты.
-Если некая операция требует ожидания перед тем, как вернуть результат, и
-поддерживает современные возможности Python, код можно написать следующим образом:
+Когда есть операция, которой нужно подождать перед тем, как вернуть результат, и она поддерживает эти новые возможности Python, вы можете написать так:
```Python
burgers = await get_burgers(2)
```
-Главное здесь слово `await`. Оно сообщает интерпретатору, что необходимо дождаться ⏸
-пока `get_burgers(2)` закончит свои дела 🕙, и только после этого сохранить результат в `burgers`.
-Зная это, Python может пока переключиться на выполнение других задач 🔀 ⏯
-(например получение следующего запроса).
+Ключ здесь — `await`. Он говорит Python, что нужно подождать ⏸, пока `get_burgers(2)` закончит своё дело 🕙, прежде чем сохранять результат в `burgers`. Благодаря этому Python будет знать, что за это время можно заняться чем-то ещё 🔀 ⏯ (например, принять другой запрос).
-Чтобы ключевое слово `await` сработало, оно должно находиться внутри функции,
-которая поддерживает асинхронность. Для этого вам просто нужно объявить её как `async def`:
+Чтобы `await` работал, он должен находиться внутри функции, которая поддерживает такую асинхронность. Для этого просто объявите её с `async def`:
```Python hl_lines="1"
async def get_burgers(number: int):
- # Готовим бургеры по специальному асинхронному рецепту
+ # Сделать что-то асинхронное, чтобы приготовить бургеры
return burgers
```
@@ -352,26 +325,22 @@ async def get_burgers(number: int):
```Python hl_lines="2"
# Это не асинхронный код
def get_sequential_burgers(number: int):
- # Готовим бургеры последовательно по шагам
+ # Сделать что-то последовательное, чтобы приготовить бургеры
return burgers
```
-Объявление `async def` указывает интерпретатору, что внутри этой функции
-следует ожидать выражений `await`, и что можно поставить выполнение такой функции на "паузу" ⏸ и
-переключиться на другие задачи 🔀, с тем чтобы вернуться сюда позже.
+С `async def` Python знает, что внутри этой функции нужно учитывать выражения `await` и что выполнение такой функции можно «приостанавливать» ⏸ и идти делать что-то ещё 🔀, чтобы потом вернуться.
-Если вы хотите вызвать функцию с `async def`, вам нужно "ожидать" её.
-Поэтому такое не сработает:
+Когда вы хотите вызвать функцию, объявленную с `async def`, нужно её «ожидать». Поэтому вот так не сработает:
```Python
-# Это не заработает, поскольку get_burgers объявлена с использованием async def
+# Это не сработает, потому что get_burgers определена с: async def
burgers = get_burgers(2)
```
---
-Если сторонняя библиотека требует вызывать её с ключевым словом `await`,
-необходимо писать *функции обработки пути* с использованием `async def`, например:
+Итак, если вы используете библиотеку, которую можно вызывать с `await`, вам нужно создать *функцию-обработчик пути*, которая её использует, с `async def`, например:
```Python hl_lines="2-3"
@app.get('/burgers')
@@ -380,126 +349,96 @@ async def read_burgers():
return burgers
```
-### Технические подробности
+### Более технические подробности { #more-technical-details }
+
+Вы могли заметить, что `await` можно использовать только внутри функций, определённых с `async def`.
+
+Но при этом функции, определённые с `async def`, нужно «ожидать». Значит, функции с `async def` тоже можно вызывать только из функций, определённых с `async def`.
+
+Так что же с «яйцом и курицей» — как вызвать первую `async` функцию?
-Как вы могли заметить, `await` может применяться только в функциях, объявленных с использованием `async def`.
+Если вы работаете с **FastAPI**, вам не о чем беспокоиться, потому что этой «первой» функцией будет ваша *функция-обработчик пути*, а FastAPI знает, как сделать всё правильно.
-
-Но выполнение такой функции необходимо "ожидать" с помощью `await`.
-Это означает, что её можно вызвать только из другой функции, которая тоже объявлена с `async def`.
+Но если вы хотите использовать `async` / `await` без FastAPI, вы тоже можете это сделать.
-Но как же тогда появилась первая курица? В смысле... как нам вызвать первую асинхронную функцию?
+### Пишите свой асинхронный код { #write-your-own-async-code }
-При работе с **FastAPI** просто не думайте об этом, потому что "первой" функцией является ваша *функция обработки пути*,
-и дальше с этим разберётся FastAPI.
+Starlette (и **FastAPI**) основаны на [AnyIO](https://anyio.readthedocs.io/en/stable/), что делает их совместимыми и со стандартной библиотекой Python [asyncio](https://docs.python.org/3/library/asyncio-task.html), и с [Trio](https://trio.readthedocs.io/en/stable/).
-Кроме того, если хотите, вы можете использовать синтаксис `async` / `await` и без FastAPI.
+В частности, вы можете напрямую использовать [AnyIO](https://anyio.readthedocs.io/en/stable/) для продвинутых сценариев конкурентности, где в вашем коде нужны более сложные паттерны.
-### Пишите свой асинхронный код
+И даже если вы не используете FastAPI, вы можете писать свои асинхронные приложения с [AnyIO](https://anyio.readthedocs.io/en/stable/), чтобы они были максимально совместимыми и получали его преимущества (например, *структурную конкурентность*).
-Starlette (и **FastAPI**) основаны на AnyIO, что делает их совместимыми как со стандартной библиотекой asyncio в Python, так и с Trio.
+Я создал ещё одну библиотеку поверх AnyIO, тонкий слой, чтобы немного улучшить аннотации типов и получить более качественное **автозавершение**, **ошибки прямо в редакторе** и т.д. Там также есть дружелюбное введение и руководство, чтобы помочь вам **понять** и писать **свой собственный асинхронный код**: [Asyncer](https://asyncer.tiangolo.com/). Она особенно полезна, если вам нужно **комбинировать асинхронный код с обычным** (блокирующим/синхронным) кодом.
-В частности, вы можете напрямую использовать AnyIO в тех проектах, где требуется более сложная логика работы с конкурентностью.
+### Другие формы асинхронного кода { #other-forms-of-asynchronous-code }
-Даже если вы не используете FastAPI, вы можете писать асинхронные приложения с помощью AnyIO, чтобы они были максимально совместимыми и получали его преимущества (например *структурную конкурентность*).
+Такой стиль использования `async` и `await` относительно новый в языке.
-### Другие виды асинхронного программирования
+Но он сильно упрощает работу с асинхронным кодом.
-Стиль написания кода с `async` и `await` появился в языке Python относительно недавно.
+Такой же (или почти такой же) синтаксис недавно появился в современных версиях JavaScript (в браузере и NodeJS).
-Но он сильно облегчает работу с асинхронным кодом.
+До этого работа с асинхронным кодом была заметно сложнее и труднее для понимания.
-Ровно такой же синтаксис (ну или почти такой же) недавно был включён в современные версии JavaScript (в браузере и NodeJS).
+В предыдущих версиях Python можно было использовать потоки или [Gevent](https://www.gevent.org/). Но такой код гораздо сложнее понимать, отлаживать и держать в голове.
-До этого поддержка асинхронного кода была реализована намного сложнее, и его было труднее воспринимать.
+В прежних версиях NodeJS/браузерного JavaScript вы бы использовали «callbacks» (обратные вызовы), что приводит к «callback hell» (ад обратных вызовов).
-В предыдущих версиях Python для этого использовались потоки или Gevent. Но такой код намного сложнее понимать, отлаживать и мысленно представлять.
+## Сопрограммы { #coroutines }
-Что касается JavaScript (в браузере и NodeJS), раньше там использовали для этой цели
-"обратные вызовы". Что выливалось в
-ад обратных вызовов.
+**Сопрограмма** (coroutine) — это просто «навороченное» слово для того, что возвращает функция `async def`. Python знает, что это похоже на функцию: её можно запустить, она когда-нибудь завершится, но её выполнение может приостанавливаться ⏸ внутри, когда встречается `await`.
-## Сопрограммы
+Часто всю функциональность использования асинхронного кода с `async` и `await` кратко называют «сопрограммами». Это сопоставимо с ключевой особенностью Go — «goroutines».
-**Корути́на** (или же сопрограмма) — это крутое словечко для именования той сущности,
-которую возвращает функция `async def`. Python знает, что её можно запустить, как и обычную функцию,
-но кроме того сопрограмму можно поставить на паузу ⏸ в том месте, где встретится слово `await`.
+## Заключение { #conclusion }
-Всю функциональность асинхронного программирования с использованием `async` и `await`
-часто обобщают словом "корутины". Они аналогичны "горутинам", ключевой особенности
-языка Go.
+Вернёмся к той же фразе:
-## Заключение
+> Современные версии Python поддерживают **«асинхронный код»** с помощью **«сопрограмм»** (coroutines) и синтаксиса **`async` и `await`**.
-В самом начале была такая фраза:
+Теперь это должно звучать понятнее. ✨
-> Современные версии Python поддерживают разработку так называемого
-**"асинхронного кода"** посредством написания **"сопрограмм"** с использованием
-синтаксиса **`async` и `await`**.
+Именно это «движет» FastAPI (через Starlette) и обеспечивает столь впечатляющую производительность.
-Теперь всё должно звучать понятнее. ✨
+## Очень технические подробности { #very-technical-details }
-На этом основана работа FastAPI (посредством Starlette), и именно это
-обеспечивает его высокую производительность.
+/// warning | Предупреждение
-## Очень технические подробности
+Скорее всего, этот раздел можно пропустить.
-!!! warning
- Этот раздел читать не обязательно.
+Здесь — очень технические подробности о том, как **FastAPI** работает «под капотом».
- Здесь приводятся подробности внутреннего устройства **FastAPI**.
+Если у вас есть достаточно технических знаний (сопрограммы, потоки, блокировки и т.д.) и вам интересно, как FastAPI обрабатывает `async def` по сравнению с обычным `def`, — вперёд.
- Но если вы обладаете техническими знаниями (корутины, потоки, блокировка и т. д.)
- и вам интересно, как FastAPI обрабатывает `async def` в отличие от обычных `def`,
- читайте дальше.
+///
-### Функции обработки пути
+### Функции-обработчики пути { #path-operation-functions }
-Когда вы объявляете *функцию обработки пути* обычным образом с ключевым словом `def`
-вместо `async def`, FastAPI ожидает её выполнения, запустив функцию во внешнем
-пуле потоков, а не напрямую (это бы заблокировало сервер).
+Когда вы объявляете *функцию-обработчик пути* обычным `def` вместо `async def`, она запускается во внешнем пуле потоков, который затем «ожидается», вместо прямого вызова (прямой вызов заблокировал бы сервер).
-Если ранее вы использовали другой асинхронный фреймворк, который работает иначе,
-и привыкли объявлять простые вычислительные *функции* через `def` ради
-незначительного прироста скорости (порядка 100 наносекунд), обратите внимание,
-что с **FastAPI** вы получите противоположный эффект. В таком случае больше подходит
-`async def`, если только *функция обработки пути* не использует код, приводящий
-к блокировке I/O.
-
+Если вы пришли из другого async-фреймворка, который работает иначе, и привыкли объявлять тривиальные *функции-обработчики пути*, выполняющие только вычисления, через простой `def` ради крошечной выгоды в производительности (около 100 наносекунд), обратите внимание: в **FastAPI** эффект будет противоположным. В таких случаях лучше использовать `async def`, если только ваши *функции-обработчики пути* не используют код, выполняющий блокирующий I/O.
-
-Но в любом случае велика вероятность, что **FastAPI** [окажется быстрее](/#performance){.internal-link target=_blank}
-другого фреймворка (или хотя бы на уровне с ним).
+Тем не менее, в обоих случаях велика вероятность, что **FastAPI** [всё равно будет быстрее](index.md#performance) (или как минимум сопоставим) с вашим предыдущим фреймворком.
-### Зависимости
+### Зависимости { #dependencies }
-То же относится к зависимостям. Если это обычная функция `def`, а не `async def`,
-она запускается во внешнем пуле потоков.
+То же относится к [зависимостям](tutorial/dependencies/index.md). Если зависимость — это обычная функция `def`, а не `async def`, она запускается во внешнем пуле потоков.
-### Подзависимости
+### Подзависимости { #sub-dependencies }
-Вы можете объявить множество ссылающихся друг на друга зависимостей и подзависимостей
-(в виде параметров при определении функции). Какие-то будут созданы с помощью `async def`,
-другие обычным образом через `def`, и такая схема вполне работоспособна. Функции,
-объявленные с помощью `def` будут запускаться на внешнем потоке (из пула),
-а не с помощью `await`.
+У вас может быть несколько зависимостей и [подзависимостей](tutorial/dependencies/sub-dependencies.md), которые требуют друг друга (в виде параметров определений функций): часть из них может быть объявлена с `async def`, а часть — обычным `def`. Всё будет работать, а те, что объявлены обычным `def`, будут вызываться во внешнем потоке (из пула), а не «ожидаться».
-### Другие служебные функции
+### Другие служебные функции { #other-utility-functions }
-Любые другие служебные функции, которые вы вызываете напрямую, можно объявлять
-с использованием `def` или `async def`. FastAPI не будет влиять на то, как вы
-их запускаете.
+Любые другие служебные функции, которые вы вызываете напрямую, можно объявлять обычным `def` или `async def`, и FastAPI не будет влиять на то, как вы их вызываете.
-Этим они отличаются от функций, которые FastAPI вызывает самостоятельно:
-*функции обработки пути* и зависимости.
+В отличие от функций, которые FastAPI вызывает за вас: *функции-обработчики пути* и зависимости.
-Если служебная функция объявлена с помощью `def`, она будет вызвана напрямую
-(как вы и написали в коде), а не в отдельном потоке. Если же она объявлена с
-помощью `async def`, её вызов должен осуществляться с ожиданием через `await`.
+Если служебная функция — обычная функция с `def`, она будет вызвана напрямую (как вы и пишете в коде), не в пуле потоков; если функция объявлена с `async def`, тогда при её вызове в вашем коде вы должны использовать `await`.
---
-
-Ещё раз повторим, что все эти технические подробности полезны, только если вы специально их искали.
+Снова: это очень технические подробности, полезные, вероятно, только если вы целенаправленно их ищете.
-В противном случае просто ознакомьтесь с основными принципами в разделе выше: Нет времени?.
+Иначе вам достаточно руководствоваться рекомендациями из раздела выше: Нет времени?.
diff --git a/docs/ru/docs/benchmarks.md b/docs/ru/docs/benchmarks.md
index 259dca8e67d59..671baba76ce78 100644
--- a/docs/ru/docs/benchmarks.md
+++ b/docs/ru/docs/benchmarks.md
@@ -1,37 +1,34 @@
-# Замеры производительности
+# Бенчмарки (тесты производительности) { #benchmarks }
-Независимые тесты производительности приложений от TechEmpower показывают, что **FastAPI** под управлением Uvicorn один из самых быстрых Python-фреймворков и уступает только Starlette и Uvicorn (которые используются в FastAPI). (*)
+Независимые бенчмарки TechEmpower показывают, что приложения **FastAPI** под управлением Uvicorn — [одни из самых быстрых Python‑фреймворков](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7), уступающие только Starlette и самому Uvicorn (используются внутри FastAPI).
-Но при просмотре и сравнении замеров производительности следует иметь в виду нижеописанное.
+Но при просмотре бенчмарков и сравнений следует иметь в виду следующее.
-## Замеры производительности и скорости
+## Бенчмарки и скорость { #benchmarks-and-speed }
-В подобных тестах часто можно увидеть, что инструменты разного типа сравнивают друг с другом, как аналогичные.
+При проверке бенчмарков часто можно увидеть, что инструменты разных типов сравнивают как эквивалентные.
-В частности, сравнивают вместе Uvicorn, Starlette и FastAPI (среди многих других инструментов).
+В частности, часто сравнивают вместе Uvicorn, Starlette и FastAPI (среди многих других инструментов).
-Чем проще проблема, которую решает инструмент, тем выше его производительность. И большинство тестов не проверяют дополнительные функции, предоставляемые инструментом.
+Чем проще задача, которую решает инструмент, тем выше его производительность. И большинство бенчмарков не тестируют дополнительные возможности, предоставляемые инструментом.
-Иерархия инструментов имеет следующий вид:
+Иерархия выглядит так:
* **Uvicorn**: ASGI-сервер
- * **Starlette** (использует Uvicorn): веб-микрофреймворк
- * **FastAPI** (использует Starlette): API-микрофреймворк с дополнительными функциями для создания API, с валидацией данных и т.д.
+ * **Starlette**: (использует Uvicorn) веб-микрофреймворк
+ * **FastAPI**: (использует Starlette) API-микрофреймворк с рядом дополнительных возможностей для создания API, включая валидацию данных и т.п.
* **Uvicorn**:
- * Будет иметь наилучшую производительность, так как не имеет большого количества дополнительного кода, кроме самого сервера.
- * Вы не будете писать приложение на Uvicorn напрямую. Это означало бы, что Ваш код должен включать как минимум весь
- код, предоставляемый Starlette (или **FastAPI**). И если Вы так сделаете, то в конечном итоге Ваше приложение будет иметь те же накладные расходы, что и при использовании фреймворка, минимизирующего код Вашего приложения и Ваши ошибки.
- * Uvicorn подлежит сравнению с Daphne, Hypercorn, uWSGI и другими веб-серверами.
-
+ * Будет иметь наилучшую производительность, так как помимо самого сервера у него немного дополнительного кода.
+ * Вы не будете писать приложение непосредственно на Uvicorn. Это означало бы, что Ваш код должен включать как минимум весь код, предоставляемый Starlette (или **FastAPI**). И если Вы так сделаете, то в конечном итоге Ваше приложение будет иметь те же накладные расходы, что и при использовании фреймворка, минимизирующего код Вашего приложения и Ваши ошибки.
+ * Если Вы сравниваете Uvicorn, сравнивайте его с Daphne, Hypercorn, uWSGI и т.д. — серверами приложений.
* **Starlette**:
- * Будет уступать Uvicorn по производительности. Фактически Starlette управляется Uvicorn и из-за выполнения большего количества кода он не может быть быстрее, чем Uvicorn.
- * Зато он предоставляет Вам инструменты для создания простых веб-приложений с обработкой маршрутов URL и т.д.
- * Starlette следует сравнивать с Sanic, Flask, Django и другими веб-фреймворками (или микрофреймворками).
-
+ * Будет на следующем месте по производительности после Uvicorn. Фактически Starlette запускается под управлением Uvicorn, поэтому он может быть только «медленнее» Uvicorn из‑за выполнения большего объёма кода.
+ * Зато он предоставляет Вам инструменты для создания простых веб‑приложений с маршрутизацией по путям и т.п.
+ * Если Вы сравниваете Starlette, сравнивайте его с Sanic, Flask, Django и т.д. — веб‑фреймворками (или микрофреймворками).
* **FastAPI**:
- * Так же как Starlette использует Uvicorn и не может быть быстрее него, **FastAPI** использует Starlette, то есть он не может быть быстрее Starlette.
- * FastAPI предоставляет больше возможностей поверх Starlette, которые наверняка Вам понадобятся при создании API, такие как проверка данных и сериализация. В довесок Вы ещё и получаете автоматическую документацию (автоматическая документация даже не увеличивает накладные расходы при работе приложения, так как она создается при запуске).
- * Если Вы не используете FastAPI, а используете Starlette напрямую (или другой инструмент вроде Sanic, Flask, Responder и т.д.), Вам пришлось бы самостоятельно реализовать валидацию и сериализацию данных. То есть, в итоге, Ваше приложение имело бы такие же накладные расходы, как если бы оно было создано с использованием FastAPI. И во многих случаях валидация и сериализация данных представляют собой самый большой объём кода, написанного в приложениях.
- * Таким образом, используя FastAPI Вы потратите меньше времени на разработку, уменьшите количество ошибок, строк кода и, вероятно, получите ту же производительность (или лучше), как и если бы не использовали его (поскольку Вам пришлось бы реализовать все его возможности в своем коде).
- * FastAPI должно сравнивать с фреймворками веб-приложений (или наборами инструментов), которые обеспечивают валидацию и сериализацию данных, а также предоставляют автоматическую документацию, такими как Flask-apispec, NestJS, Molten и им подобные.
+ * Точно так же, как Starlette использует Uvicorn и не может быть быстрее него, **FastAPI** использует Starlette, поэтому не может быть быстрее его.
+ * FastAPI предоставляет больше возможностей поверх Starlette — те, которые почти всегда нужны при создании API, такие как валидация и сериализация данных. В довесок Вы ещё и получаете автоматическую документацию (автоматическая документация даже не увеличивает накладные расходы при работе приложения, так как она создаётся при запуске).
+ * Если бы Вы не использовали FastAPI, а использовали Starlette напрямую (или другой инструмент вроде Sanic, Flask, Responder и т.д.), Вам пришлось бы самостоятельно реализовать валидацию и сериализацию данных. То есть, в итоге, Ваше приложение имело бы такие же накладные расходы, как если бы оно было создано с использованием FastAPI. И во многих случаях валидация и сериализация данных представляют собой самый большой объём кода, написанного в приложениях.
+ * Таким образом, используя FastAPI, Вы экономите время разработки, уменьшаете количество ошибок, строк кода и, вероятно, получите ту же производительность (или лучше), как и если бы не использовали его (поскольку Вам пришлось бы реализовать все его возможности в своём коде).
+ * Если Вы сравниваете FastAPI, сравнивайте его с фреймворком веб‑приложений (или набором инструментов), который обеспечивает валидацию данных, сериализацию и документацию, такими как Flask-apispec, NestJS, Molten и им подобные. Фреймворки с интегрированной автоматической валидацией данных, сериализацией и документацией.
diff --git a/docs/ru/docs/contributing.md b/docs/ru/docs/contributing.md
deleted file mode 100644
index f9b8912e55361..0000000000000
--- a/docs/ru/docs/contributing.md
+++ /dev/null
@@ -1,469 +0,0 @@
-# Участие в разработке фреймворка
-
-Возможно, для начала Вам стоит ознакомиться с основными способами [помочь FastAPI или получить помощь](help-fastapi.md){.internal-link target=_blank}.
-
-## Разработка
-
-Если Вы уже склонировали репозиторий и знаете, что Вам нужно более глубокое погружение в код фреймворка, то здесь представлены некоторые инструкции по настройке виртуального окружения.
-
-### Виртуальное окружение с помощью `venv`
-
-Находясь в нужной директории, Вы можете создать виртуальное окружение при помощи Python модуля `venv`.
-
-
---
-Теперь, когда нам известна разница между **процессом** и **программой**, давайте продолжим обсуждение развёртывания.
+Теперь, когда мы понимаем разницу между **процессом** и **программой**, продолжим разговор о развёртываниях.
-## Настройки запуска приложения
+## Запуск при старте { #running-on-startup }
-В большинстве случаев когда Вы создаёте веб-приложение, то желаете, чтоб оно **работало постоянно** и непрерывно, предоставляя клиентам доступ в любое время. Хотя иногда у Вас могут быть причины, чтоб оно запускалось только при определённых условиях.
+В большинстве случаев, создавая веб‑API, вы хотите, чтобы он **работал постоянно**, без перерывов, чтобы клиенты всегда могли к нему обратиться. Разве что у вас есть особые причины запускать его только при определённых условиях, но обычно вы хотите, чтобы он был постоянно запущен и **доступен**.
-### Удалённый сервер
+### На удалённом сервере { #in-a-remote-server }
-Когда Вы настраиваете удалённый сервер (облачный сервер, виртуальную машину и т.п.), самое простое, что можно сделать, запустить Uvicorn (или его аналог) вручную, как Вы делаете при локальной разработке.
+Когда вы настраиваете удалённый сервер (облачный сервер, виртуальную машину и т.п.), самый простой вариант — вручную использовать `fastapi run` (он использует Uvicorn) или что‑то похожее, как вы делаете при локальной разработке.
-Это рабочий способ и он полезен **во время разработки**.
+Это будет работать и полезно **во время разработки**.
-Но если Вы потеряете соединение с сервером, то не сможете отслеживать - работает ли всё ещё **запущенный Вами процесс**.
+Но если соединение с сервером прервётся, **запущенный процесс**, скорее всего, завершится.
-И если сервер перезагрузится (например, после обновления или каких-то действий облачного провайдера), Вы скорее всего **этого не заметите**, чтобы снова запустить процесс вручную. Вследствие этого Ваш API останется мёртвым. 😱
+А если сервер перезагрузится (например, после обновлений или миграций у облачного провайдера), вы, вероятно, **даже не заметите этого**. Из‑за этого вы не узнаете, что нужно вручную перезапустить процесс — и ваш API просто будет «мёртв». 😱
-### Автоматический запуск программ
+### Автоматический запуск при старте { #run-automatically-on-startup }
-Вероятно Вы пожелаете, чтоб Ваша серверная программа (такая как Uvicorn) стартовала автоматически при включении сервера, без **человеческого вмешательства** и всегда могла управлять Вашим API (так как Uvicorn запускает приложение FastAPI).
+Как правило, вы захотите, чтобы серверная программа (например, Uvicorn) запускалась автоматически при старте сервера и без **участия человека**, чтобы всегда был процесс, запущенный с вашим API (например, Uvicorn, запускающий ваше приложение FastAPI).
-### Отдельная программа
+### Отдельная программа { #separate-program }
-Для этого у обычно используют отдельную программу, которая следит за тем, чтобы Ваши приложения запускались при включении сервера. Такой подход гарантирует, что другие компоненты или приложения также будут запущены, например, база данных
+Чтобы этого добиться, обычно используют **отдельную программу**, которая гарантирует запуск вашего приложения при старте. Во многих случаях она также запускает и другие компоненты/приложения, например базу данных.
-### Примеры инструментов, управляющих запуском программ
+### Примеры инструментов для запуска при старте { #example-tools-to-run-at-startup }
-Вот несколько примеров, которые могут справиться с такой задачей:
+Примеры инструментов, которые могут с этим справиться:
* Docker
* Kubernetes
* Docker Compose
-* Docker в режиме Swarm
+* Docker в режиме Swarm (Swarm Mode)
* Systemd
* Supervisor
-* Использование услуг облачного провайдера
+* Обработка внутри облачного провайдера как часть его услуг
* Прочие...
-Я покажу Вам некоторые примеры их использования в следующих главах.
+Более конкретные примеры будут в следующих главах.
-## Перезапуск
+## Перезапуски { #restarts }
-Вы, вероятно, также пожелаете, чтоб Ваше приложение **перезапускалось**, если в нём произошёл сбой.
+Подобно тому как вы обеспечиваете запуск приложения при старте, вы, вероятно, захотите обеспечить его **перезапуск** после сбоев.
-### Мы ошибаемся
+### Мы ошибаемся { #we-make-mistakes }
-Все люди совершают **ошибки**. Программное обеспечение почти *всегда* содержит **баги** спрятавшиеся в разных местах. 🐛
+Мы, люди, постоянно совершаем **ошибки**. В программном обеспечении почти всегда есть **баги**, скрытые в разных местах. 🐛
-И мы, будучи разработчиками, продолжаем улучшать код, когда обнаруживаем в нём баги или добавляем новый функционал (возможно, добавляя при этом баги 😅).
+И мы, как разработчики, продолжаем улучшать код — находим баги и добавляем новые возможности (иногда добавляя новые баги 😅).
-### Небольшие ошибки обрабатываются автоматически
+### Небольшие ошибки обрабатываются автоматически { #small-errors-automatically-handled }
-Когда Вы создаёте свои API на основе FastAPI и допускаете в коде ошибку, то FastAPI обычно остановит её распространение внутри одного запроса, при обработке которого она возникла. 🛡
+Создавая веб‑API с FastAPI, если в нашем коде возникает ошибка, FastAPI обычно «локализует» её в пределах одного запроса, который эту ошибку вызвал. 🛡
-Клиент получит ошибку **500 Internal Server Error** в ответ на свой запрос, но приложение не сломается и будет продолжать работать с последующими запросами.
+Клиент получит **500 Internal Server Error** для этого запроса, но приложение продолжит работать для последующих запросов, а не «упадёт» целиком.
-### Большие ошибки - Падение приложений
+### Большие ошибки — падения { #bigger-errors-crashes }
-Тем не менее, может случиться так, что ошибка вызовет **сбой всего приложения** или даже сбой в Uvicorn, а то и в самом Python. 💥
+Тем не менее возможны случаи, когда код **роняет всё приложение**, приводя к сбою Uvicorn и Python. 💥
-Но мы всё ещё хотим, чтобы приложение **продолжало работать** несмотря на эту единственную ошибку, обрабатывая, как минимум, запросы к *операциям пути* не имеющим ошибок.
+И вы, скорее всего, не захотите, чтобы приложение оставалось «мёртвым» из‑за ошибки в одном месте — вы захотите, чтобы оно **продолжало работать** хотя бы для *операций пути*, которые не сломаны.
-### Перезапуск после падения
+### Перезапуск после падения { #restart-after-crash }
-Для случаев, когда ошибки приводят к сбою в запущенном **процессе**, Вам понадобится добавить компонент, который **перезапустит** процесс хотя бы пару раз...
+В случаях действительно серьёзных ошибок, которые роняют работающий **процесс**, вам понадобится внешний компонент, отвечающий за **перезапуск** процесса, как минимум пару раз...
-!!! tip "Заметка"
- ... Если приложение падает сразу же после запуска, вероятно бесполезно его бесконечно перезапускать. Но полагаю, Вы заметите такое поведение во время разработки или, по крайней мере, сразу после развёртывания.
+/// tip | Совет
- Так что давайте сосредоточимся на конкретных случаях, когда приложение может полностью выйти из строя, но всё ещё есть смысл его запустить заново.
+...Хотя если приложение **падает сразу же**, вероятно, нет смысла перезапускать его бесконечно. Но такие случаи вы, скорее всего, заметите во время разработки или как минимум сразу после развёртывания.
-Возможно Вы захотите, чтоб был некий **внешний компонент**, ответственный за перезапуск Вашего приложения даже если уже не работает Uvicorn или Python. То есть ничего из того, что написано в Вашем коде внутри приложения, не может быть выполнено в принципе.
+Давайте сосредоточимся на основных сценариях, когда в каких‑то конкретных ситуациях **в будущем** приложение может падать целиком, и при этом имеет смысл его перезапускать.
-### Примеры инструментов для автоматического перезапуска
+///
-В большинстве случаев инструменты **запускающие программы при старте сервера** умеют **перезапускать** эти программы.
+Скорее всего, вы захотите, чтобы перезапуском вашего приложения занимался **внешний компонент**, потому что к тому моменту Uvicorn и Python уже упали, и внутри того же кода вашего приложения сделать уже ничего нельзя.
-В качестве примера можно взять те же:
+### Примеры инструментов для автоматического перезапуска { #example-tools-to-restart-automatically }
+
+В большинстве случаев тот же инструмент, который **запускает программу при старте**, умеет обрабатывать и автоматические **перезапуски**.
+
+Например, это может быть:
* Docker
* Kubernetes
* Docker Compose
-* Docker в режиме Swarm
+* Docker в режиме Swarm (Swarm Mode)
* Systemd
* Supervisor
-* Использование услуг облачного провайдера
+* Обработка внутри облачного провайдера как часть его услуг
* Прочие...
-## Запуск нескольких экземпляров приложения (Репликация) - Процессы и память
+## Репликация — процессы и память { #replication-processes-and-memory }
+
+В приложении FastAPI, используя серверную программу (например, команду `fastapi`, которая запускает Uvicorn), запуск в **одном процессе** уже позволяет обслуживать нескольких клиентов одновременно.
+
+Но во многих случаях вы захотите одновременно запустить несколько процессов‑воркеров.
-Приложение FastAPI, управляемое серверной программой (такой как Uvicorn), запускается как **один процесс** и может обслуживать множество клиентов одновременно.
+### Несколько процессов — Воркеры { #multiple-processes-workers }
-Но часто Вам может понадобиться несколько одновременно работающих одинаковых процессов.
+Если клиентов больше, чем способен обслужить один процесс (например, если виртуальная машина не слишком мощная), и на сервере есть **несколько ядер CPU**, вы можете запустить **несколько процессов** одного и того же приложения параллельно и распределять запросы между ними.
-### Множество процессов - Воркеры (Workers)
+Когда вы запускаете **несколько процессов** одной и той же программы API, их обычно называют **воркерами**.
-Если количество Ваших клиентов больше, чем может обслужить один процесс (допустим, что виртуальная машина не слишком мощная), но при этом Вам доступно **несколько ядер процессора**, то Вы можете запустить **несколько процессов** одного и того же приложения параллельно и распределить запросы между этими процессами.
+### Процессы‑воркеры и порты { #worker-processes-and-ports }
-**Несколько запущенных процессов** одной и той же API-программы часто называют **воркерами**.
+Помните из раздела [Об HTTPS](https.md), что на сервере только один процесс может слушать конкретную комбинацию порта и IP‑адреса?
-### Процессы и порты́
+Это по‑прежнему так.
-Помните ли Вы, как на странице [Об HTTPS](./https.md){.internal-link target=_blank} мы обсуждали, что на сервере только один процесс может слушать одну комбинацию IP-адреса и порта?
+Поэтому, чтобы одновременно работало **несколько процессов**, должен быть **один процесс, слушающий порт**, который затем каким‑то образом передаёт коммуникацию каждому воркер‑процессу.
-С тех пор ничего не изменилось.
+### Память на процесс { #memory-per-process }
-Соответственно, чтобы иметь возможность работать с **несколькими процессами** одновременно, должен быть **один процесс, прослушивающий порт** и затем каким-либо образом передающий данные каждому рабочему процессу.
+Когда программа загружает что‑то в память (например, модель машинного обучения в переменную или содержимое большого файла в переменную), всё это **потребляет часть памяти (RAM)** сервера.
-### У каждого процесса своя память
+И разные процессы обычно **не делят память**. Это значит, что у каждого процесса свои переменные и своя память. Если ваш код потребляет много памяти, то **каждый процесс** будет потреблять сопоставимый объём памяти.
-Работающая программа загружает в память данные, необходимые для её работы, например, переменные содержащие модели машинного обучения или большие файлы. Каждая переменная **потребляет некоторое количество оперативной памяти (RAM)** сервера.
+### Память сервера { #server-memory }
-Обычно процессы **не делятся памятью друг с другом**. Сие означает, что каждый работающий процесс имеет свои данные, переменные и свой кусок памяти. И если для выполнения Вашего кода процессу нужно много памяти, то **каждый такой же процесс** запущенный дополнительно, потребует такого же количества памяти.
+Например, если ваш код загружает модель Машинного обучения размером **1 ГБ**, то при запуске одного процесса с вашим API он будет использовать как минимум 1 ГБ RAM. А если вы запустите **4 процесса** (4 воркера), каждый процесс будет использовать 1 ГБ RAM. Всего ваш API будет потреблять **4 ГБ RAM**.
-### Память сервера
+И если у вашего удалённого сервера или виртуальной машины только 3 ГБ RAM, попытка загрузить более 4 ГБ вызовет проблемы. 🚨
-Допустим, что Ваш код загружает модель машинного обучения **размером 1 ГБ**. Когда Вы запустите своё API как один процесс, он займёт в оперативной памяти не менее 1 ГБ. А если Вы запустите **4 таких же процесса** (4 воркера), то каждый из них займёт 1 ГБ оперативной памяти. В результате Вашему API потребуется **4 ГБ оперативной памяти (RAM)**.
+### Несколько процессов — пример { #multiple-processes-an-example }
-И если Ваш удалённый сервер или виртуальная машина располагает только 3 ГБ памяти, то попытка загрузить в неё 4 ГБ данных вызовет проблемы. 🚨
+В этом примере есть **процесс‑менеджер**, который запускает и контролирует два **процесса‑воркера**.
-### Множество процессов - Пример
+Процесс‑менеджер, вероятно, будет тем, кто слушает **порт** на IP. И он будет передавать всю коммуникацию воркер‑процессам.
-В этом примере **менеджер процессов** запустит и будет управлять двумя **воркерами**.
+Эти воркеры будут запускать ваше приложение, выполнять основные вычисления для получения **HTTP‑запроса** и возврата **HTTP‑ответа**, и загружать всё, что вы кладёте в переменные, в RAM.
-Менеджер процессов будет слушать определённый **сокет** (IP:порт) и передавать данные работающим процессам.
+@@ -24,45 +24,47 @@ Я всячески избегал создания нового фреймворка в течение нескольких лет. Сначала я пытался собрать все нужные возможности, которые ныне есть в **FastAPI**, используя множество различных фреймворков, плагинов и инструментов. -Но в какой-то момент не осталось другого выбора, кроме как создать что-то, что предоставляло бы все эти возможности сразу. Взять самые лучшие идеи из предыдущих инструментов и, используя введённые в Python подсказки типов (которых не было до версии 3.6), объединить их. +Но в какой-то момент не осталось другого выбора, кроме как создать что-то, что предоставляло бы все эти возможности сразу. Взять самые лучшие идеи из предыдущих инструментов и, используя введённые в Python аннотации типов (которых не было до версии 3.6), объединить их.-## Исследования +## Исследования { #investigation } -Благодаря опыту использования существующих альтернатив, мы с коллегами изучили их основные идеи и скомбинировали собранные знания наилучшим образом. +Используя все существовавшие ранее альтернативы, я получил возможность у каждой из них чему-то научиться, позаимствовать идеи и объединить их наилучшим образом для себя и для команд разработчиков, с которыми я работал. -Например, стало ясно, что необходимо брать за основу стандартные подсказки типов Python, а самым лучшим подходом является использование уже существующих стандартов. +Например, стало ясно, что необходимо брать за основу стандартные аннотации типов Python. + +Также наилучшим подходом является использование уже существующих стандартов. Итак, прежде чем приступить к написанию **FastAPI**, я потратил несколько месяцев на изучение OpenAPI, JSON Schema, OAuth2, и т.п. для понимания их взаимосвязей, совпадений и различий. -## Дизайн +## Проектирование { #design } Затем я потратил некоторое время на придумывание "API" разработчика, который я хотел иметь как пользователь (как разработчик, использующий FastAPI). -Я проверил несколько идей на самых популярных редакторах кода среди Python-разработчиков: PyCharm, VS Code, Jedi. +Я проверил несколько идей на самых популярных редакторах кода: PyCharm, VS Code, редакторы на базе Jedi. -Данные по редакторам я взял из опроса Python-разработчиков, который охватываает около 80% пользователей. +Согласно последнему [опросу Python-разработчиков](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools), который охватывает около 80% пользователей. Это означает, что **FastAPI** был специально проверен на редакторах, используемых 80% Python-разработчиками. И поскольку большинство других редакторов, как правило, работают аналогичным образом, все его преимущества должны работать практически для всех редакторов. -Таким образом, я смог найти наилучшие способы сократить дублирование кода, обеспечить повсеместное автодополнение, проверку типов и ошибок и т.д. +Таким образом, я смог найти наилучшие способы сократить дублирование кода, обеспечить повсеместное автозавершение, проверку типов и ошибок и т.д. -И все это, чтобы все пользователи могли получать наилучший опыт разработки. +И все это, чтобы все разработчики могли получать наилучший опыт разработки. -## Зависимости +## Зависимости { #requirements } -Протестировав несколько вариантов, я решил, что в качестве основы буду использовать **Pydantic** и его преимущества. +Протестировав несколько вариантов, я решил, что в качестве основы буду использовать [**Pydantic**](https://docs.pydantic.dev/) и его преимущества. -По моим предложениям был изменён код этого фреймворка, чтобы сделать его полностью совместимым с JSON Schema, поддержать различные способы определения ограничений и улучшить помощь редакторов (проверки типов, автозаполнение). +По моим предложениям был изменён код этого фреймворка, чтобы сделать его полностью совместимым с JSON Schema, поддержать различные способы определения ограничений и улучшить поддержку в редакторах кода (проверки типов, автозавершение) на основе тестов в нескольких редакторах. -В то же время, я принимал участие в разработке **Starlette**, ещё один из основных компонентов FastAPI. +Во время разработки я также внес вклад в [**Starlette**](https://www.starlette.dev/), другую ключевую зависимость. -## Разработка +## Разработка { #development } К тому времени, когда я начал создавать **FastAPI**, большинство необходимых деталей уже существовало, дизайн был определён, зависимости и прочие инструменты были готовы, а знания о стандартах и спецификациях были четкими и свежими. -## Будущее +## Будущее { #future } Сейчас уже ясно, что **FastAPI** со своими идеями стал полезен многим людям. @@ -74,4 +76,4 @@ У **FastAPI** великое будущее. -И [ваш вклад в это](help-fastapi.md){.internal-link target=_blank} - очень ценнен. +И [ваша помощь](help-fastapi.md) очень ценится. diff --git a/docs/ru/docs/how-to/authentication-error-status-code.md b/docs/ru/docs/how-to/authentication-error-status-code.md new file mode 100644 index 0000000000000..acbc18f336539 --- /dev/null +++ b/docs/ru/docs/how-to/authentication-error-status-code.md @@ -0,0 +1,17 @@ +# Использование старых статус-кодов ошибок аутентификации 403 { #use-old-403-authentication-error-status-codes } + +До версии FastAPI `0.122.0`, когда встроенные утилиты безопасности возвращали ошибку клиенту после неудачной аутентификации, они использовали HTTP статус-код `403 Forbidden`. + +Начиная с версии FastAPI `0.122.0`, используется более подходящий HTTP статус-код `401 Unauthorized`, и в ответе возвращается имеющий смысл HTTP-заголовок `WWW-Authenticate` в соответствии со спецификациями HTTP, [RFC 7235](https://datatracker.ietf.org/doc/html/rfc7235#section-3.1), [RFC 9110](https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized). + +Но если по какой-то причине ваши клиенты зависят от старого поведения, вы можете вернуть его, переопределив метод `make_not_authenticated_error` в ваших Security-классах. + +Например, вы можете создать подкласс `HTTPBearer`, который будет возвращать ошибку `403 Forbidden` вместо стандартной `401 Unauthorized`: + +{* ../../docs_src/authentication_error_status_code/tutorial001_an_py310.py hl[9:13] *} + +/// tip | Совет + +Обратите внимание, что функция возвращает экземпляр исключения, не вызывает его. Выброс выполняется остальным внутренним кодом. + +/// diff --git a/docs/ru/docs/how-to/conditional-openapi.md b/docs/ru/docs/how-to/conditional-openapi.md new file mode 100644 index 0000000000000..5fece06c14058 --- /dev/null +++ b/docs/ru/docs/how-to/conditional-openapi.md @@ -0,0 +1,56 @@ +# Условный OpenAPI { #conditional-openapi } + +При необходимости вы можете использовать настройки и переменные окружения, чтобы условно настраивать OpenAPI в зависимости от окружения и даже полностью его отключать. + +## О безопасности, API и документации { #about-security-apis-and-docs } + +Скрытие пользовательских интерфейсов документации в продакшн не должно быть способом защиты вашего API. + +Это не добавляет дополнительной безопасности вашему API, операции пути (обработчики пути) всё равно будут доступны по своим путям. + +Если в вашем коде есть уязвимость, она всё равно останется. + +Сокрытие документации лишь усложняет понимание того, как взаимодействовать с вашим API, и может усложнить его отладку в продакшн. Это можно считать просто разновидностью [безопасности через сокрытие](https://en.wikipedia.org/wiki/Security_through_obscurity). + +Если вы хотите обезопасить свой API, есть несколько более эффективных вещей, которые можно сделать, например: + +* Убедитесь, что у вас чётко определены Pydantic-модели для тел запросов и ответов. +* Настройте необходимые разрешения и роли с помощью зависимостей. +* Никогда не храните пароли в открытом виде, только хэши паролей. +* Реализуйте и используйте известные криптографические инструменты, например pwdlib и JWT-токены, и т.д. +* Добавьте более тонкое управление доступом с помощью OAuth2 scopes (областей) там, где это необходимо. +* ...и т.п. + +Тем не менее, у вас может быть очень специфичный случай использования, когда действительно нужно отключить документацию API для некоторых окружений (например, в продакшн) или в зависимости от настроек из переменных окружения. + +## Условный OpenAPI из настроек и переменных окружения { #conditional-openapi-from-settings-and-env-vars } + +Вы можете легко использовать те же настройки Pydantic, чтобы настроить сгенерированный OpenAPI и интерфейсы документации. + +Например: + +{* ../../docs_src/conditional_openapi/tutorial001_py310.py hl[6,11] *} + +Здесь мы объявляем настройку `openapi_url` с тем же значением по умолчанию — `"/openapi.json"`. + +Затем используем её при создании приложения FastAPI. + +Далее вы можете отключить OpenAPI (включая интерфейсы документации), установив переменную окружения `OPENAPI_URL` в пустую строку, например: + +
+
+Но вы можете отключить её, установив `syntaxHighlight` в `False`:
+
+{* ../../docs_src/configure_swagger_ui/tutorial001_py310.py hl[3] *}
+
+…и после этого Swagger UI больше не будет показывать подсветку синтаксиса:
+
+
+
+## Изменить тему { #change-the-theme }
+
+Аналогично вы можете задать тему подсветки синтаксиса с ключом "syntaxHighlight.theme" (обратите внимание, что посередине стоит точка):
+
+{* ../../docs_src/configure_swagger_ui/tutorial002_py310.py hl[3] *}
+
+Эта настройка изменит цветовую тему подсветки синтаксиса:
+
+
+
+## Изменить параметры Swagger UI по умолчанию { #change-default-swagger-ui-parameters }
+
+FastAPI включает некоторые параметры конфигурации по умолчанию, подходящие для большинства случаев.
+
+Это включает следующие настройки по умолчанию:
+
+{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}
+
+Вы можете переопределить любую из них, указав другое значение в аргументе `swagger_ui_parameters`.
+
+Например, чтобы отключить `deepLinking`, можно передать такие настройки в `swagger_ui_parameters`:
+
+{* ../../docs_src/configure_swagger_ui/tutorial003_py310.py hl[3] *}
+
+## Другие параметры Swagger UI { #other-swagger-ui-parameters }
+
+Чтобы увидеть все остальные возможные настройки, прочитайте официальную [документацию по параметрам Swagger UI](https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/).
+
+## Настройки только для JavaScript { #javascript-only-settings }
+
+Swagger UI также допускает другие настройки, которые являются **чисто JavaScript-объектами** (например, JavaScript-функциями).
+
+FastAPI также включает следующие настройки `presets` (только для JavaScript):
+
+```JavaScript
+presets: [
+ SwaggerUIBundle.presets.apis,
+ SwaggerUIBundle.SwaggerUIStandalonePreset
+]
+```
+
+Это объекты **JavaScript**, а не строки, поэтому напрямую передать их из Python-кода нельзя.
+
+Если вам нужны такие настройки только для JavaScript, используйте один из методов выше. Переопределите *операцию пути* Swagger UI и вручную напишите любой необходимый JavaScript.
diff --git a/docs/ru/docs/how-to/custom-docs-ui-assets.md b/docs/ru/docs/how-to/custom-docs-ui-assets.md
new file mode 100644
index 0000000000000..b8398cdb08608
--- /dev/null
+++ b/docs/ru/docs/how-to/custom-docs-ui-assets.md
@@ -0,0 +1,185 @@
+# Свои статические ресурсы UI документации (самостоятельный хостинг) { #custom-docs-ui-static-assets-self-hosting }
+
+Документация API использует **Swagger UI** и **ReDoc**, и для каждого из них нужны некоторые файлы JavaScript и CSS.
+
+По умолчанию эти файлы отдаются с CDN.
+
+Но это можно настроить: вы можете указать конкретный CDN или отдавать файлы самостоятельно.
+
+## Пользовательский CDN для JavaScript и CSS { #custom-cdn-for-javascript-and-css }
+
+Допустим, вы хотите использовать другой CDN, например `https://unpkg.com/`.
+
+Это может быть полезно, если, например, вы живёте в стране, где некоторые URL ограничены.
+
+### Отключить автоматическую документацию { #disable-the-automatic-docs }
+
+Первый шаг — отключить автоматическую документацию, так как по умолчанию она использует стандартный CDN.
+
+Чтобы отключить её, установите их URL в значение `None` при создании вашего приложения `FastAPI`:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[8] *}
+
+### Подключить пользовательскую документацию { #include-the-custom-docs }
+
+Теперь вы можете создать *операции пути* для пользовательской документации.
+
+Вы можете переиспользовать внутренние функции FastAPI для создания HTML-страниц документации и передать им необходимые аргументы:
+
+* `openapi_url`: URL, по которому HTML-страница документации сможет получить схему OpenAPI для вашего API. Здесь можно использовать атрибут `app.openapi_url`.
+* `title`: заголовок вашего API.
+* `oauth2_redirect_url`: здесь можно использовать `app.swagger_ui_oauth2_redirect_url`, чтобы оставить значение по умолчанию.
+* `swagger_js_url`: URL, по которому HTML для документации Swagger UI сможет получить файл **JavaScript**. Это URL вашего пользовательского CDN.
+* `swagger_css_url`: URL, по которому HTML для документации Swagger UI сможет получить файл **CSS**. Это URL вашего пользовательского CDN.
+
+Аналогично и для ReDoc...
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[2:6,11:19,22:24,27:33] *}
+
+/// tip | Совет
+
+*Операция пути* для `swagger_ui_redirect` — это вспомогательный эндпоинт на случай, когда вы используете OAuth2.
+
+Если вы интегрируете свой API с провайдером OAuth2, вы сможете аутентифицироваться и вернуться к документации API с полученными учётными данными, а затем взаимодействовать с ним, используя реальную аутентификацию OAuth2.
+
+Swagger UI сделает это за вас «за кулисами», но для этого ему нужен этот вспомогательный «redirect» эндпоинт.
+
+///
+
+### Создайте *операцию пути*, чтобы проверить { #create-a-path-operation-to-test-it }
+
+Чтобы убедиться, что всё работает, создайте *операцию пути*:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[36:38] *}
+
+### Тестирование { #test-it }
+
+Теперь вы должны иметь возможность открыть свою документацию по адресу [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) и перезагрузить страницу — «ассеты» (статические файлы) будут загружаться с нового CDN.
+
+## Самостоятельный хостинг JavaScript и CSS для документации { #self-hosting-javascript-and-css-for-docs }
+
+Самостоятельный хостинг JavaScript и CSS может быть полезен, если, например, вам нужно, чтобы приложение продолжало работать в офлайне, без доступа к открытому Интернету, или в локальной сети.
+
+Здесь вы увидите, как отдавать эти файлы самостоятельно, в том же приложении FastAPI, и настроить документацию на их использование.
+
+### Структура файлов проекта { #project-file-structure }
+
+Допустим, структура файлов вашего проекта выглядит так:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+```
+
+Теперь создайте директорию для хранения этих статических файлов.
+
+Новая структура файлов может выглядеть так:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static/
+```
+
+### Скачайте файлы { #download-the-files }
+
+Скачайте статические файлы, необходимые для документации, и поместите их в директорию `static/`.
+
+Скорее всего, вы можете кликнуть правой кнопкой на каждой ссылке и выбрать что-то вроде «Сохранить ссылку как...».
+
+**Swagger UI** использует файлы:
+
+* [`swagger-ui-bundle.js`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js)
+* [`swagger-ui.css`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css)
+
+А **ReDoc** использует файл:
+
+* [`redoc.standalone.js`](https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js)
+
+После этого структура файлов может выглядеть так:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static
+ ├── redoc.standalone.js
+ ├── swagger-ui-bundle.js
+ └── swagger-ui.css
+```
+
+### Предоставьте доступ к статическим файлам { #serve-the-static-files }
+
+* Импортируйте `StaticFiles`.
+* Смонтируйте экземпляр `StaticFiles()` в определённый путь.
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[7,11] *}
+
+### Протестируйте статические файлы { #test-the-static-files }
+
+Запустите своё приложение и откройте [http://127.0.0.1:8000/static/redoc.standalone.js](http://127.0.0.1:8000/static/redoc.standalone.js).
+
+Вы должны увидеть очень длинный JavaScript-файл для **ReDoc**.
+
+Он может начинаться примерно так:
+
+```JavaScript
+/*! For license information please see redoc.standalone.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")):
+...
+```
+
+Это подтверждает, что ваше приложение умеет отдавать статические файлы и что вы поместили файлы документации в нужное место.
+
+Теперь можно настроить приложение так, чтобы документация использовала эти статические файлы.
+
+### Отключить автоматическую документацию для статических файлов { #disable-the-automatic-docs-for-static-files }
+
+Так же, как и при использовании пользовательского CDN, первым шагом будет отключение автоматической документации, так как по умолчанию она использует CDN.
+
+Чтобы отключить её, установите их URL в значение `None` при создании вашего приложения `FastAPI`:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[9] *}
+
+### Подключить пользовательскую документацию со статическими файлами { #include-the-custom-docs-for-static-files }
+
+Аналогично пользовательскому CDN, теперь вы можете создать *операции пути* для собственной документации.
+
+Снова можно переиспользовать внутренние функции FastAPI для создания HTML-страниц документации и передать им необходимые аргументы:
+
+* `openapi_url`: URL, по которому HTML-страница документации сможет получить схему OpenAPI для вашего API. Здесь можно использовать атрибут `app.openapi_url`.
+* `title`: заголовок вашего API.
+* `oauth2_redirect_url`: здесь можно использовать `app.swagger_ui_oauth2_redirect_url`, чтобы оставить значение по умолчанию.
+* `swagger_js_url`: URL, по которому HTML для документации Swagger UI сможет получить файл **JavaScript**. **Это тот файл, который теперь отдаёт ваше собственное приложение**.
+* `swagger_css_url`: URL, по которому HTML для документации Swagger UI сможет получить файл **CSS**. **Это тот файл, который теперь отдаёт ваше собственное приложение**.
+
+Аналогично и для ReDoc...
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[2:6,14:22,25:27,30:36] *}
+
+/// tip | Совет
+
+*Операция пути* для `swagger_ui_redirect` — это вспомогательный эндпоинт на случай, когда вы используете OAuth2.
+
+Если вы интегрируете свой API с провайдером OAuth2, вы сможете аутентифицироваться и вернуться к документации API с полученными учётными данными, а затем взаимодействовать с ним, используя реальную аутентификацию OAuth2.
+
+Swagger UI сделает это за вас «за кулисами», но для этого ему нужен этот вспомогательный «redirect» эндпоинт.
+
+///
+
+### Создайте *операцию пути* для теста статических файлов { #create-a-path-operation-to-test-static-files }
+
+Чтобы убедиться, что всё работает, создайте *операцию пути*:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[39:41] *}
+
+### Тестирование UI со статическими файлами { #test-static-files-ui }
+
+Теперь вы можете отключить Wi‑Fi, открыть свою документацию по адресу [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) и перезагрузить страницу.
+
+Даже без Интернета вы сможете видеть документацию к своему API и взаимодействовать с ним.
diff --git a/docs/ru/docs/how-to/custom-request-and-route.md b/docs/ru/docs/how-to/custom-request-and-route.md
new file mode 100644
index 0000000000000..1e3a608562577
--- /dev/null
+++ b/docs/ru/docs/how-to/custom-request-and-route.md
@@ -0,0 +1,109 @@
+# Пользовательские классы Request и APIRoute { #custom-request-and-apiroute-class }
+
+В некоторых случаях может понадобиться переопределить логику, используемую классами `Request` и `APIRoute`.
+
+В частности, это может быть хорошей альтернативой логике в middleware.
+
+Например, если вы хотите прочитать или изменить тело запроса до того, как оно будет обработано вашим приложением.
+
+/// danger | Опасность
+
+Это «продвинутая» возможность.
+
+Если вы только начинаете работать с **FastAPI**, возможно, стоит пропустить этот раздел.
+
+///
+
+## Сценарии использования { #use-cases }
+
+Некоторые сценарии:
+
+* Преобразование тел запросов, не в формате JSON, в JSON (например, [`msgpack`](https://msgpack.org/index.html)).
+* Распаковка тел запросов, сжатых с помощью gzip.
+* Автоматическое логирование всех тел запросов.
+
+## Обработка пользовательского кодирования тела запроса { #handling-custom-request-body-encodings }
+
+Посмотрим как использовать пользовательский подкласс `Request` для распаковки gzip-запросов.
+
+И подкласс `APIRoute`, чтобы использовать этот пользовательский класс запроса.
+
+### Создать пользовательский класс `GzipRequest` { #create-a-custom-gziprequest-class }
+
+/// tip | Совет
+
+Это учебный пример, демонстрирующий принцип работы. Если вам нужна поддержка Gzip, вы можете использовать готовый [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware).
+
+///
+
+Сначала создадим класс `GzipRequest`, который переопределит метод `Request.body()` и распакует тело запроса при наличии соответствующего HTTP-заголовка.
+
+Если в заголовке нет `gzip`, он не будет пытаться распаковывать тело.
+
+Таким образом, один и тот же класс маршрута сможет обрабатывать как gzip-сжатые, так и несжатые запросы.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[9:16] *}
+
+### Создать пользовательский класс `GzipRoute` { #create-a-custom-gziproute-class }
+
+Далее создадим пользовательский подкласс `fastapi.routing.APIRoute`, который будет использовать `GzipRequest`.
+
+На этот раз он переопределит метод `APIRoute.get_route_handler()`.
+
+Этот метод возвращает функцию. Именно эта функция получает HTTP-запрос и возвращает HTTP-ответ.
+
+Здесь мы используем её, чтобы создать `GzipRequest` из исходного HTTP-запроса.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[19:27] *}
+
+/// note | Технические детали
+
+У `Request` есть атрибут `request.scope` — это просто Python-`dict`, содержащий метаданные, связанные с HTTP-запросом.
+
+У `Request` также есть `request.receive` — функция для «получения» тела запроса.
+
+И `dict` `scope`, и функция `receive` являются частью спецификации ASGI.
+
+Именно этих двух компонентов — `scope` и `receive` — достаточно, чтобы создать новый экземпляр `Request`.
+
+Чтобы узнать больше о `Request`, см. [документацию Starlette о запросах](https://www.starlette.dev/requests/).
+
+///
+
+Единственное, что делает по-другому функция, возвращённая `GzipRequest.get_route_handler`, — преобразует `Request` в `GzipRequest`.
+
+Благодаря этому наш `GzipRequest` позаботится о распаковке данных (при необходимости) до передачи их в наши *операции пути*.
+
+Дальше вся логика обработки остаётся прежней.
+
+Но благодаря изменениям в `GzipRequest.body` тело запроса будет автоматически распаковано при необходимости, когда оно будет загружено **FastAPI**.
+
+## Доступ к телу запроса в обработчике исключений { #accessing-the-request-body-in-an-exception-handler }
+
+/// tip | Совет
+
+Для решения этой задачи, вероятно, намного проще использовать `body` в пользовательском обработчике `RequestValidationError` ([Обработка ошибок](../tutorial/handling-errors.md#use-the-requestvalidationerror-body)).
+
+Но этот пример всё равно актуален и показывает, как взаимодействовать с внутренними компонентами.
+
+///
+
+Тем же подходом можно воспользоваться, чтобы получить доступ к телу запроса в обработчике исключений.
+
+Нужно лишь обработать запрос внутри блока `try`/`except`:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[14,16] *}
+
+Если произойдёт исключение, экземпляр `Request` всё ещё будет в области видимости, поэтому мы сможем прочитать тело запроса и использовать его при обработке ошибки:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[17:19] *}
+
+## Пользовательский класс `APIRoute` в роутере { #custom-apiroute-class-in-a-router }
+
+Вы также можете задать параметр `route_class` у `APIRouter`:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[26] *}
+
+В этом примере *операции пути*, объявленные в `router`, будут использовать пользовательский класс `TimedRoute` и получат дополнительный HTTP-заголовок `X-Response-Time` в ответе с временем, затраченным на формирование ответа:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[13:20] *}
diff --git a/docs/ru/docs/how-to/extending-openapi.md b/docs/ru/docs/how-to/extending-openapi.md
new file mode 100644
index 0000000000000..c1e369f5e5ec8
--- /dev/null
+++ b/docs/ru/docs/how-to/extending-openapi.md
@@ -0,0 +1,80 @@
+# Расширение OpenAPI { #extending-openapi }
+
+Иногда может понадобиться изменить сгенерированную схему OpenAPI.
+
+В этом разделе показано, как это сделать.
+
+## Обычный процесс { #the-normal-process }
+
+Обычный (по умолчанию) процесс выглядит так.
+
+Приложение `FastAPI` (экземпляр) имеет метод `.openapi()`, который должен возвращать схему OpenAPI.
+
+В процессе создания объекта приложения регистрируется *операция пути* (обработчик пути) для `/openapi.json` (или для того, что указано в вашем `openapi_url`).
+
+Она просто возвращает JSON-ответ с результатом вызова метода приложения `.openapi()`.
+
+По умолчанию метод `.openapi()` проверяет свойство `.openapi_schema`: если в нём уже есть данные, возвращает их.
+
+Если нет — генерирует схему с помощью вспомогательной функции `fastapi.openapi.utils.get_openapi`.
+
+Функция `get_openapi()` принимает параметры:
+
+* `title`: Заголовок OpenAPI, отображается в документации.
+* `version`: Версия вашего API, например `2.5.0`.
+* `openapi_version`: Версия используемой спецификации OpenAPI. По умолчанию — последняя: `3.1.0`.
+* `summary`: Краткое описание API.
+* `description`: Описание вашего API; может включать Markdown и будет отображаться в документации.
+* `routes`: Список маршрутов — это каждая зарегистрированная *операция пути*. Берутся из `app.routes`.
+
+/// info | Информация
+
+Параметр `summary` доступен в OpenAPI 3.1.0 и выше, поддерживается FastAPI версии 0.99.0 и выше.
+
+///
+
+## Переопределение значений по умолчанию { #overriding-the-defaults }
+
+Используя информацию выше, вы можете той же вспомогательной функцией сгенерировать схему OpenAPI и переопределить любые нужные части.
+
+Например, добавим [расширение OpenAPI ReDoc для включения собственного логотипа](https://github.com/Rebilly/ReDoc/blob/master/docs/redoc-vendor-extensions.md#x-logo).
+
+### Обычный **FastAPI** { #normal-fastapi }
+
+Сначала напишите приложение **FastAPI** как обычно:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[1,4,7:9] *}
+
+### Сгенерируйте схему OpenAPI { #generate-the-openapi-schema }
+
+Затем используйте ту же вспомогательную функцию для генерации схемы OpenAPI внутри функции `custom_openapi()`:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[2,15:21] *}
+
+### Измените схему OpenAPI { #modify-the-openapi-schema }
+
+Теперь можно добавить расширение ReDoc, добавив кастомный `x-logo` в «объект» `info` в схеме OpenAPI:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[22:24] *}
+
+### Кэшируйте схему OpenAPI { #cache-the-openapi-schema }
+
+Вы можете использовать свойство `.openapi_schema` как «кэш» для хранения сгенерированной схемы.
+
+Так приложению не придётся генерировать схему каждый раз, когда пользователь открывает документацию API.
+
+Она будет создана один раз, а затем тот же кэшированный вариант будет использоваться для последующих запросов.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[13:14,25:26] *}
+
+### Переопределите метод { #override-the-method }
+
+Теперь вы можете заменить метод `.openapi()` на вашу новую функцию.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[29] *}
+
+### Проверьте { #check-it }
+
+Перейдите на [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) — вы увидите, что используется ваш кастомный логотип (в этом примере — логотип **FastAPI**):
+
+
diff --git a/docs/ru/docs/how-to/general.md b/docs/ru/docs/how-to/general.md
new file mode 100644
index 0000000000000..886105eec459c
--- /dev/null
+++ b/docs/ru/docs/how-to/general.md
@@ -0,0 +1,43 @@
+# Общее — Как сделать — Рецепты { #general-how-to-recipes }
+
+Здесь несколько указателей на другие места в документации для общих или частых вопросов.
+
+## Фильтрация данных — Безопасность { #filter-data-security }
+
+Чтобы убедиться, что вы не возвращаете больше данных, чем следует, прочитайте документацию: [Руководство — Модель ответа — Возвращаемый тип](../tutorial/response-model.md).
+
+## Оптимизация производительности ответа — Модель ответа — Возвращаемый тип { #optimize-response-performance-response-model-return-type }
+
+Чтобы оптимизировать производительность при возврате JSON-данных, используйте возвращаемый тип или модель ответа; таким образом Pydantic выполнит сериализацию в JSON на стороне Rust, без прохождения через Python. Подробнее читайте в документации: [Руководство — Модель ответа — Возвращаемый тип](../tutorial/response-model.md).
+
+## Теги в документации — OpenAPI { #documentation-tags-openapi }
+
+Чтобы добавить теги к вашим *операциям пути* и группировать их в интерфейсе документации, прочитайте документацию: [Руководство — Конфигурации операций пути — Теги](../tutorial/path-operation-configuration.md#tags).
+
+## Краткое описание и описание в документации — OpenAPI { #documentation-summary-and-description-openapi }
+
+Чтобы добавить краткое описание и описание к вашим *операциям пути* и отобразить их в интерфейсе документации, прочитайте документацию: [Руководство — Конфигурации операций пути — Краткое описание и описание](../tutorial/path-operation-configuration.md#summary-and-description).
+
+## Описание ответа в документации — OpenAPI { #documentation-response-description-openapi }
+
+Чтобы задать описание ответа, отображаемое в интерфейсе документации, прочитайте документацию: [Руководство — Конфигурации операций пути — Описание ответа](../tutorial/path-operation-configuration.md#response-description).
+
+## Документация — пометить операцию пути устаревшей — OpenAPI { #documentation-deprecate-a-path-operation-openapi }
+
+Чтобы пометить *операцию пути* как устаревшую и показать это в интерфейсе документации, прочитайте документацию: [Руководство — Конфигурации операций пути — Пометить операцию пути устаревшей](../tutorial/path-operation-configuration.md#deprecate-a-path-operation).
+
+## Преобразование любых данных к формату, совместимому с JSON { #convert-any-data-to-json-compatible }
+
+Чтобы преобразовать любые данные к формату, совместимому с JSON, прочитайте документацию: [Руководство — JSON-совместимый кодировщик](../tutorial/encoder.md).
+
+## Метаданные OpenAPI — Документация { #openapi-metadata-docs }
+
+Чтобы добавить метаданные в вашу схему OpenAPI, включая лицензию, версию, контакты и т.д., прочитайте документацию: [Руководство — Метаданные и URL документации](../tutorial/metadata.md).
+
+## Пользовательский URL OpenAPI { #openapi-custom-url }
+
+Чтобы настроить URL OpenAPI (или удалить его), прочитайте документацию: [Руководство — Метаданные и URL документации](../tutorial/metadata.md#openapi-url).
+
+## URL документации OpenAPI { #openapi-docs-urls }
+
+Чтобы изменить URL, используемые для автоматически сгенерированных пользовательских интерфейсов документации, прочитайте документацию: [Руководство — Метаданные и URL документации](../tutorial/metadata.md#docs-urls).
diff --git a/docs/ru/docs/how-to/graphql.md b/docs/ru/docs/how-to/graphql.md
new file mode 100644
index 0000000000000..1829a211c1548
--- /dev/null
+++ b/docs/ru/docs/how-to/graphql.md
@@ -0,0 +1,60 @@
+# GraphQL { #graphql }
+
+Так как **FastAPI** основан на стандарте **ASGI**, очень легко интегрировать любую библиотеку **GraphQL**, также совместимую с ASGI.
+
+Вы можете комбинировать обычные *операции пути* FastAPI с GraphQL в одном приложении.
+
+/// tip | Совет
+
+**GraphQL** решает некоторые очень специфические задачи.
+
+У него есть как **преимущества**, так и **недостатки** по сравнению с обычными **веб-API**.
+
+Убедитесь, что **выгоды** для вашего случая использования перевешивают **недостатки**. 🤓
+
+///
+
+## Библиотеки GraphQL { #graphql-libraries }
+
+Ниже приведены некоторые библиотеки **GraphQL** с поддержкой **ASGI**. Их можно использовать с **FastAPI**:
+
+* [Strawberry](https://strawberry.rocks/) 🍓
+ * С [документацией для FastAPI](https://strawberry.rocks/docs/integrations/fastapi)
+* [Ariadne](https://ariadnegraphql.org/)
+ * С [документацией для FastAPI](https://ariadnegraphql.org/docs/fastapi-integration)
+* [Tartiflette](https://tartiflette.io/)
+ * С [Tartiflette ASGI](https://tartiflette.github.io/tartiflette-asgi/) для интеграции с ASGI
+* [Graphene](https://graphene-python.org/)
+ * С [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3)
+
+## GraphQL со Strawberry { #graphql-with-strawberry }
+
+Если вам нужно или хочется работать с **GraphQL**, [**Strawberry**](https://strawberry.rocks/) — **рекомендуемая** библиотека, так как её дизайн ближе всего к дизайну **FastAPI**, всё основано на **аннотациях типов**.
+
+В зависимости от вашего сценария использования вы можете предпочесть другую библиотеку, но если бы вы спросили меня, я, скорее всего, предложил бы попробовать **Strawberry**.
+
+Вот небольшой пример того, как можно интегрировать Strawberry с FastAPI:
+
+{* ../../docs_src/graphql_/tutorial001_py310.py hl[3,22,25] *}
+
+Подробнее о Strawberry можно узнать в [документации Strawberry](https://strawberry.rocks/).
+
+А также в документации по [интеграции Strawberry с FastAPI](https://strawberry.rocks/docs/integrations/fastapi).
+
+## Устаревший `GraphQLApp` из Starlette { #older-graphqlapp-from-starlette }
+
+В предыдущих версиях Starlette был класс `GraphQLApp` для интеграции с [Graphene](https://graphene-python.org/).
+
+Он был объявлен устаревшим в Starlette, но если у вас есть код, который его использовал, вы можете легко **мигрировать** на [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3), который решает ту же задачу и имеет **почти идентичный интерфейс**.
+
+/// tip | Совет
+
+Если вам нужен GraphQL, я всё же рекомендую посмотреть [Strawberry](https://strawberry.rocks/), так как он основан на аннотациях типов, а не на пользовательских классах и типах.
+
+///
+
+## Подробнее { #learn-more }
+
+Подробнее о **GraphQL** вы можете узнать в [официальной документации GraphQL](https://graphql.org/).
+
+Также можно почитать больше о каждой из указанных выше библиотек по приведённым ссылкам.
diff --git a/docs/ru/docs/how-to/index.md b/docs/ru/docs/how-to/index.md
new file mode 100644
index 0000000000000..23d95ba04c717
--- /dev/null
+++ b/docs/ru/docs/how-to/index.md
@@ -0,0 +1,13 @@
+# Как сделать — Рецепты { #how-to-recipes }
+
+Здесь вы найдете разные рецепты и руководства «как сделать» по **различным темам**.
+
+Большинство из этих идей более-менее **независимы**, и в большинстве случаев вам стоит изучать их только если они напрямую относятся к **вашему проекту**.
+
+Если что-то кажется интересным и полезным для вашего проекта, смело изучайте; в противном случае, вероятно, можно просто пропустить.
+
+/// tip | Совет
+
+Если вы хотите **изучить FastAPI** структурированно (рекомендуется), вместо этого читайте [Учебник - Руководство пользователя](../tutorial/index.md) по главам.
+
+///
diff --git a/docs/ru/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/ru/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
new file mode 100644
index 0000000000000..46b4071da89a2
--- /dev/null
+++ b/docs/ru/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -0,0 +1,135 @@
+# Миграция с Pydantic v1 на Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 }
+
+Если у вас старое приложение FastAPI, возможно, вы используете Pydantic версии 1.
+
+FastAPI версии 0.100.0 поддерживал либо Pydantic v1, либо v2. Он использовал ту версию, которая была установлена.
+
+FastAPI версии 0.119.0 добавил частичную поддержку Pydantic v1 изнутри Pydantic v2 (как `pydantic.v1`), чтобы упростить миграцию на v2.
+
+FastAPI 0.126.0 убрал поддержку Pydantic v1, при этом ещё некоторое время продолжал поддерживать `pydantic.v1`.
+
+/// warning | Предупреждение
+
+Команда Pydantic прекратила поддержку Pydantic v1 для последних версий Python, начиная с **Python 3.14**.
+
+Это включает `pydantic.v1`, который больше не поддерживается в Python 3.14 и выше.
+
+Если вы хотите использовать последние возможности Python, вам нужно убедиться, что вы используете Pydantic v2.
+
+///
+
+Если у вас старое приложение FastAPI с Pydantic v1, здесь я покажу, как мигрировать на Pydantic v2, и **возможности FastAPI 0.119.0**, которые помогут выполнить постепенную миграцию.
+
+## Официальное руководство { #official-guide }
+
+У Pydantic есть официальное [руководство по миграции](https://docs.pydantic.dev/latest/migration/) с v1 на v2.
+
+Там также описано, что изменилось, как валидации стали более корректными и строгими, возможные нюансы и т.д.
+
+Прочитайте его, чтобы лучше понять, что изменилось.
+
+## Тесты { #tests }
+
+Убедитесь, что у вас есть [тесты](../tutorial/testing.md) для вашего приложения и что вы запускаете их в системе непрерывной интеграции (CI).
+
+Так вы сможете выполнить обновление и убедиться, что всё работает как ожидается.
+
+## `bump-pydantic` { #bump-pydantic }
+
+Во многих случаях, когда вы используете обычные Pydantic‑модели без пользовательских настроек, вы сможете автоматизировать большую часть процесса миграции с Pydantic v1 на Pydantic v2.
+
+Вы можете использовать [`bump-pydantic`](https://github.com/pydantic/bump-pydantic) от той же команды Pydantic.
+
+Этот инструмент поможет автоматически изменить большую часть кода, который нужно изменить.
+
+После этого вы можете запустить тесты и проверить, что всё работает. Если да — на этом всё. 😎
+
+## Pydantic v1 в v2 { #pydantic-v1-in-v2 }
+
+Pydantic v2 включает всё из Pydantic v1 как подмодуль `pydantic.v1`. Но это больше не поддерживается в версиях Python выше 3.13.
+
+Это означает, что вы можете установить последнюю версию Pydantic v2 и импортировать и использовать старые компоненты Pydantic v1 из этого подмодуля так, как если бы у вас был установлен старый Pydantic v1.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}
+
+### Поддержка FastAPI для Pydantic v1 внутри v2 { #fastapi-support-for-pydantic-v1-in-v2 }
+
+Начиная с FastAPI 0.119.0, есть также частичная поддержка Pydantic v1 изнутри Pydantic v2, чтобы упростить миграцию на v2.
+
+Таким образом, вы можете обновить Pydantic до последней версии 2 и сменить импорты на подмодуль `pydantic.v1` — во многих случаях всё просто заработает.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py hl[2,5,15] *}
+
+/// warning | Предупреждение
+
+Имейте в виду, что так как команда Pydantic больше не поддерживает Pydantic v1 в последних версиях Python, начиная с Python 3.14, использование `pydantic.v1` также не поддерживается в Python 3.14 и выше.
+
+///
+
+### Pydantic v1 и v2 в одном приложении { #pydantic-v1-and-v2-on-the-same-app }
+
+В Pydantic **не поддерживается** ситуация, когда в одной модели Pydantic v2 используются поля, определённые как модели Pydantic v1, и наоборот.
+
+```mermaid
+graph TB
+ subgraph "❌ Not Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+…но в одном и том же приложении вы можете иметь отдельные модели на Pydantic v1 и v2.
+
+```mermaid
+graph TB
+ subgraph "✅ Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+В некоторых случаях можно использовать и модели Pydantic v1, и v2 в одной и той же **операции пути** (обработчике пути) вашего приложения FastAPI:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}
+
+В примере выше модель входных данных — это модель Pydantic v1, а модель выходных данных (указанная в `response_model=ItemV2`) — это модель Pydantic v2.
+
+### Параметры Pydantic v1 { #pydantic-v1-parameters }
+
+Если вам нужно использовать некоторые специфичные для FastAPI инструменты для параметров, такие как `Body`, `Query`, `Form` и т.п., с моделями Pydantic v1, вы можете импортировать их из `fastapi.temp_pydantic_v1_params`, пока завершаете миграцию на Pydantic v2:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py hl[4,18] *}
+
+### Мигрируйте по шагам { #migrate-in-steps }
+
+/// tip | Совет
+
+Сначала попробуйте `bump-pydantic`: если тесты проходят и всё работает, вы справились одной командой. ✨
+
+///
+
+Если `bump-pydantic` не подходит для вашего случая, вы можете использовать поддержку одновременной работы моделей Pydantic v1 и v2 в одном приложении, чтобы мигрировать на Pydantic v2 постепенно.
+
+Сначала вы можете обновить Pydantic до последней 2-й версии и изменить импорты так, чтобы все ваши модели использовали `pydantic.v1`.
+
+Затем вы можете начать мигрировать ваши модели с Pydantic v1 на v2 группами, поэтапно. 🚶
diff --git a/docs/ru/docs/how-to/separate-openapi-schemas.md b/docs/ru/docs/how-to/separate-openapi-schemas.md
new file mode 100644
index 0000000000000..8f6c83e7ec270
--- /dev/null
+++ b/docs/ru/docs/how-to/separate-openapi-schemas.md
@@ -0,0 +1,102 @@
+# Разделять схемы OpenAPI для входа и выхода или нет { #separate-openapi-schemas-for-input-and-output-or-not }
+
+При использовании **Pydantic v2** сгенерированный OpenAPI становится чуть более точным и **корректным**, чем раньше. 😎
+
+На самом деле, в некоторых случаях в OpenAPI будет даже **две JSON-схемы** для одной и той же Pydantic‑модели: для входа и для выхода — в зависимости от наличия **значений по умолчанию**.
+
+Посмотрим, как это работает, и как это изменить при необходимости.
+
+## Pydantic‑модели для входа и выхода { #pydantic-models-for-input-and-output }
+
+Предположим, у вас есть Pydantic‑модель со значениями по умолчанию, как здесь:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *}
+
+### Модель для входа { #model-for-input }
+
+Если использовать эту модель как входную, как здесь:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *}
+
+…то поле `description` **не будет обязательным**, потому что у него значение по умолчанию `None`.
+
+### Входная модель в документации { #input-model-in-docs }
+
+В документации это видно: у поля `description` нет **красной звёздочки** — оно не отмечено как обязательное:
+
+
+
+
+
+
+- Готовый к внедрению высокопроизводительный фреймворк, простой в изучении и разработке. + Фреймворк FastAPI: высокая производительность, прост в изучении, позволяет быстро писать код, готов к продакшн
-
-
+
+
-
-
+
+
-
-
+
+
-
-
+
+
-FastAPI стоит на плечах гигантов:
+## **Typer**, FastAPI для CLI { #typer-the-fastapi-of-clis }
-* Starlette для части связанной с вебом.
-* Pydantic для части связанной с данными.
+uvicorn main:app --reload...fastapi dev...email_validator - для проверки электронной почты.
+* [`email-validator`](https://github.com/JoshData/python-email-validator) — для проверки адресов электронной почты.
Используется Starlette:
-* HTTPX - Обязательно, если вы хотите использовать `TestClient`.
-* jinja2 - Обязательно, если вы хотите использовать конфигурацию шаблона по умолчанию.
-* python-multipart - Обязательно, если вы хотите поддерживать форму "парсинга" с помощью `request.form()`.
-* itsdangerous - Обязательно, для поддержки `SessionMiddleware`.
-* pyyaml - Обязательно, для поддержки `SchemaGenerator` Starlette (возможно, вам это не нужно с FastAPI).
-* ujson - Обязательно, если вы хотите использовать `UJSONResponse`.
+* [`httpx`](https://www.python-httpx.org) — обязателен, если вы хотите использовать `TestClient`.
+* [`jinja2`](https://jinja.palletsprojects.com) — обязателен, если вы хотите использовать конфигурацию шаблонов по умолчанию.
+* [`python-multipart`](https://github.com/Kludex/python-multipart) - обязателен, если вы хотите поддерживать «парсинг» форм через `request.form()`.
+
+Используется FastAPI:
+
+* [`uvicorn`](https://www.uvicorn.dev) — сервер, который загружает и «отдаёт» ваше приложение. Включает `uvicorn[standard]`, содержащий некоторые зависимости (например, `uvloop`), нужные для высокой производительности.
+* `fastapi-cli[standard]` — чтобы предоставить команду `fastapi`.
+ * Включает `fastapi-cloud-cli`, который позволяет развернуть ваше приложение FastAPI в [FastAPI Cloud](https://fastapicloud.com).
+
+### Без зависимостей `standard` { #without-standard-dependencies }
+
+Если вы не хотите включать опциональные зависимости `standard`, можно установить `pip install fastapi` вместо `pip install "fastapi[standard]"`.
+
+### Без `fastapi-cloud-cli` { #without-fastapi-cloud-cli }
+
+Если вы хотите установить FastAPI со стандартными зависимостями, но без `fastapi-cloud-cli`, установите `pip install "fastapi[standard-no-fastapi-cloud-cli]"`.
+
+### Дополнительные опциональные зависимости { #additional-optional-dependencies }
+
+Есть дополнительные зависимости, которые вы можете установить.
+
+Дополнительные опциональные зависимости Pydantic:
-Используется FastAPI / Starlette:
+* [`pydantic-settings`](https://docs.pydantic.dev/latest/usage/pydantic_settings/) — для управления настройками.
+* [`pydantic-extra-types`](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/) — дополнительные типы для использования с Pydantic.
-* uvicorn - сервер, который загружает и обслуживает ваше приложение.
-* orjson - Обязательно, если вы хотите использовать `ORJSONResponse`.
+Дополнительные опциональные зависимости FastAPI:
-Вы можете установить все это с помощью `pip install "fastapi[all]"`.
+* [`orjson`](https://github.com/ijl/orjson) — обязателен, если вы хотите использовать `ORJSONResponse`.
+* [`ujson`](https://github.com/esnme/ultrajson) — обязателен, если вы хотите использовать `UJSONResponse`.
-## Лицензия
+## Лицензия { #license }
Этот проект распространяется на условиях лицензии MIT.
diff --git a/docs/ru/docs/learn/index.md b/docs/ru/docs/learn/index.md
new file mode 100644
index 0000000000000..50fbd773865d4
--- /dev/null
+++ b/docs/ru/docs/learn/index.md
@@ -0,0 +1,5 @@
+# Обучение { #learn }
+
+Здесь представлены вводные разделы и учебные пособия для изучения **FastAPI**.
+
+Вы можете считать это **книгой**, **курсом**, **официальным** и рекомендуемым способом изучения FastAPI. 😎
diff --git a/docs/ru/docs/project-generation.md b/docs/ru/docs/project-generation.md
index 76253d6f2f0f9..7a46b210d6ed5 100644
--- a/docs/ru/docs/project-generation.md
+++ b/docs/ru/docs/project-generation.md
@@ -1,84 +1,28 @@
-# Генераторы проектов - Шаблоны
-
-Чтобы начать работу быстрее, Вы можете использовать "генераторы проектов", в которые включены множество начальных настроек для функций безопасности, баз данных и некоторые эндпоинты API.
-
-В генераторе проектов всегда будут предустановлены какие-то настройки, которые Вам следует обновить и подогнать под свои нужды, но это может быть хорошей отправной точкой для Вашего проекта.
-
-## Full Stack FastAPI PostgreSQL
-
-GitHub: https://github.com/tiangolo/full-stack-fastapi-postgresql
-
-### Full Stack FastAPI PostgreSQL - Особенности
-
-* Полностью интегрирован с **Docker** (основан на Docker).
-* Развёртывается в режиме Docker Swarm.
-* Интегрирован с **Docker Compose** и оптимизирован для локальной разработки.
-* **Готовый к реальной работе** веб-сервер Python использующий Uvicorn и Gunicorn.
-* Бэкенд построен на фреймворке **FastAPI**:
- * **Быстрый**: Высокопроизводительный, на уровне **NodeJS** и **Go** (благодаря Starlette и Pydantic).
- * **Интуитивно понятный**: Отличная поддержка редактора. Автодополнение кода везде. Меньше времени на отладку.
- * **Простой**: Разработан так, чтоб быть простым в использовании и изучении. Меньше времени на чтение документации.
- * **Лаконичный**: Минимизировано повторение кода. Каждый объявленный параметр определяет несколько функций.
- * **Надёжный**: Получите готовый к работе код. С автоматической интерактивной документацией.
- * **Стандартизированный**: Основан на открытых стандартах API (OpenAPI и JSON Schema) и полностью совместим с ними.
- * **Множество других возможностей** включая автоматическую проверку и сериализацию данных, интерактивную документацию, аутентификацию с помощью OAuth2 JWT-токенов и т.д.
-* **Безопасное хранение паролей**, которые хэшируются по умолчанию.
-* Аутентификация посредством **JWT-токенов**.
-* Модели **SQLAlchemy** (независящие от расширений Flask, а значит могут быть непосредственно использованы процессами Celery).
-* Базовая модель пользователя (измените или удалите её по необходимости).
-* **Alembic** для организации миграций.
-* **CORS** (Совместное использование ресурсов из разных источников).
-* **Celery**, процессы которого могут выборочно импортировать и использовать модели и код из остальной части бэкенда.
-* Тесты, на основе **Pytest**, интегрированные в Docker, чтобы Вы могли полностью проверить Ваше API, независимо от базы данных. Так как тесты запускаются в Docker, для них может создаваться новое хранилище данных каждый раз (Вы можете, по своему желанию, использовать ElasticSearch, MongoDB, CouchDB или другую СУБД, только лишь для проверки - будет ли Ваше API работать с этим хранилищем).
-* Простая интеграция Python с **Jupyter Kernels** для разработки удалённо или в Docker с расширениями похожими на Atom Hydrogen или Visual Studio Code Jupyter.
-* Фронтенд построен на фреймворке **Vue**:
- * Сгенерирован с помощью Vue CLI.
- * Поддерживает **аутентификацию с помощью JWT-токенов**.
- * Страница логина.
- * Перенаправление на страницу главной панели мониторинга после логина.
- * Главная страница мониторинга с возможностью создания и изменения пользователей.
- * Пользователь может изменять свои данные.
- * **Vuex**.
- * **Vue-router**.
- * **Vuetify** для конструирования красивых компонентов страниц.
- * **TypeScript**.
- * Сервер Docker основан на **Nginx** (настроен для удобной работы с Vue-router).
- * Многоступенчатая сборка Docker, то есть Вам не нужно сохранять или коммитить скомпилированный код.
- * Тесты фронтенда запускаются во время сборки (можно отключить).
- * Сделан настолько модульно, насколько возможно, поэтому работает "из коробки", но Вы можете повторно сгенерировать фронтенд с помощью Vue CLI или создать то, что Вам нужно и повторно использовать то, что захотите.
-* **PGAdmin** для СУБД PostgreSQL, которые легко можно заменить на PHPMyAdmin и MySQL.
-* **Flower** для отслеживания работы Celery.
-* Балансировка нагрузки между фронтендом и бэкендом с помощью **Traefik**, а значит, Вы можете расположить их на одном домене, разделив url-пути, так как они обслуживаются разными контейнерами.
-* Интеграция с Traefik включает автоматическую генерацию сертификатов Let's Encrypt для поддержки протокола **HTTPS**.
-* GitLab **CI** (непрерывная интеграция), которая включает тестирование фронтенда и бэкенда.
-
-## Full Stack FastAPI Couchbase
-
-GitHub: https://github.com/tiangolo/full-stack-fastapi-couchbase
-
-⚠️ **ПРЕДУПРЕЖДЕНИЕ** ⚠️
-
-Если Вы начинаете новый проект, ознакомьтесь с представленными здесь альтернативами.
-
-Например, генератор проектов Full Stack FastAPI PostgreSQL может быть более подходящей альтернативой, так как он активно поддерживается и используется. И он включает в себя все новые возможности и улучшения.
-
-Но никто не запрещает Вам использовать генератор с СУБД Couchbase, возможно, он всё ещё работает нормально. Или у Вас уже есть проект, созданный с помощью этого генератора ранее, и Вы, вероятно, уже обновили его в соответствии со своими потребностями.
-
-Вы можете прочитать о нём больше в документации соответствующего репозитория.
-
-## Full Stack FastAPI MongoDB
-
-...может быть когда-нибудь появится, в зависимости от наличия у меня свободного времени и прочих факторов. 😅 🎉
-
-## Модели машинного обучения на основе spaCy и FastAPI
-
-GitHub: https://github.com/microsoft/cookiecutter-spacy-fastapi
-
-### Модели машинного обучения на основе spaCy и FastAPI - Особенности
-
-* Интеграция с моделями **spaCy** NER.
-* Встроенный формат запросов к **когнитивному поиску Azure**.
-* **Готовый к реальной работе** веб-сервер Python использующий Uvicorn и Gunicorn.
-* Встроенное развёртывание на основе **Azure DevOps** Kubernetes (AKS) CI/CD.
-* **Многоязычность**. Лёгкий выбор одного из встроенных в spaCy языков во время настройки проекта.
-* **Легко подключить** модели из других фреймворков (Pytorch, Tensorflow) не ограничиваясь spaCy.
+# Шаблон Full Stack FastAPI { #full-stack-fastapi-template }
+
+Шаблоны, хотя обычно поставляются с определённой конфигурацией, спроектированы так, чтобы быть гибкими и настраиваемыми. Это позволяет вам изменять их и адаптировать под требования вашего проекта, что делает их отличной отправной точкой. 🏁
+
+Вы можете использовать этот шаблон для старта: в нём уже сделана значительная часть начальной настройки, безопасность, база данных и несколько эндпоинтов API.
+
+Репозиторий GitHub: [Full Stack FastAPI Template](https://github.com/tiangolo/full-stack-fastapi-template)
+
+## Шаблон Full Stack FastAPI — Технологический стек и возможности { #full-stack-fastapi-template-technology-stack-and-features }
+
+- ⚡ [**FastAPI**](https://fastapi.tiangolo.com/ru) для бэкенд‑API на Python.
+ - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) для взаимодействия с SQL‑базой данных на Python (ORM).
+ - 🔍 [Pydantic](https://docs.pydantic.dev), используется FastAPI, для валидации данных и управления настройками.
+ - 💾 [PostgreSQL](https://www.postgresql.org) в качестве SQL‑базы данных.
+- 🚀 [React](https://react.dev) для фронтенда.
+ - 💃 Используются TypeScript, хуки, Vite и другие части современного фронтенд‑стека.
+ - 🎨 [Tailwind CSS](https://tailwindcss.com) и [shadcn/ui](https://ui.shadcn.com) для компонентов фронтенда.
+ - 🤖 Автоматически сгенерированный фронтенд‑клиент.
+ - 🧪 [Playwright](https://playwright.dev) для End‑to‑End тестирования.
+ - 🦇 Поддержка тёмной темы.
+- 🐋 [Docker Compose](https://www.docker.com) для разработки и продакшн.
+- 🔒 Безопасное хэширование паролей по умолчанию.
+- 🔑 Аутентификация по JWT‑токенам.
+- 📫 Восстановление пароля по электронной почте.
+- ✅ Тесты с [Pytest](https://pytest.org).
+- 📞 [Traefik](https://traefik.io) в роли обратного прокси / балансировщика нагрузки.
+- 🚢 Инструкции по развёртыванию с использованием Docker Compose, включая настройку фронтенд‑прокси Traefik для автоматического получения сертификатов HTTPS.
+- 🏭 CI (continuous integration) и CD (continuous deployment) на основе GitHub Actions.
diff --git a/docs/ru/docs/python-types.md b/docs/ru/docs/python-types.md
index 7523083c88319..61219704c0dd4 100644
--- a/docs/ru/docs/python-types.md
+++ b/docs/ru/docs/python-types.md
@@ -1,27 +1,28 @@
-# Введение в аннотации типов Python
+# Введение в типы Python { #python-types-intro }
-Python имеет поддержку необязательных аннотаций типов.
+Python поддерживает необязательные «подсказки типов» (их также называют «аннотациями типов»).
-**Аннотации типов** являются специальным синтаксисом, который позволяет определять тип переменной.
+Эти **«подсказки типов»** или аннотации — это специальный синтаксис, позволяющий объявлять тип переменной.
-Объявление типов для переменных позволяет улучшить поддержку вашего кода редакторами и различными инструментами.
+Объявляя типы для ваших переменных, редакторы кода и инструменты смогут лучше вас поддерживать.
-Это просто **краткое руководство / напоминание** об аннотациях типов в Python. Оно охватывает только минимум, необходимый для их использования с **FastAPI**... что на самом деле очень мало.
+Это всего лишь **краткое руководство / напоминание** о подсказках типов в Python. Оно охватывает только минимум, необходимый для их использования с **FastAPI**... что на самом деле очень мало.
-**FastAPI** целиком основан на аннотациях типов, у них много выгод и преимуществ.
+**FastAPI** целиком основан на этих подсказках типов — они дают ему множество преимуществ и выгод.
Но даже если вы никогда не используете **FastAPI**, вам будет полезно немного узнать о них.
-!!! note
- Если вы являетесь экспертом в Python и уже знаете всё об аннотациях типов, переходите к следующему разделу.
+/// note | Примечание
-## Мотивация
+Если вы являетесь экспертом в Python и уже знаете всё о подсказках типов, переходите к следующей главе.
+
+///
+
+## Мотивация { #motivation }
Давайте начнем с простого примера:
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001_py310.py *}
Вызов этой программы выводит:
@@ -32,14 +33,12 @@ John Doe
Функция делает следующее:
* Принимает `first_name` и `last_name`.
-* Преобразует первую букву содержимого каждой переменной в верхний регистр с `title()`.
-* Соединяет их через пробел.
+* Преобразует первую букву каждого значения в верхний регистр с помощью `title()`.
+* Соединяет их пробелом посередине.
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}
-### Отредактируем пример
+### Отредактируем пример { #edit-it }
Это очень простая программа.
@@ -47,23 +46,23 @@ John Doe
В какой-то момент вы бы начали определение функции, у вас были бы готовы параметры...
-Но затем вы должны вызвать «тот метод, который преобразует первую букву в верхний регистр».
+Но затем нужно вызвать «тот метод, который делает первую букву заглавной».
-Было это `upper`? Или `uppercase`? `first_uppercase`? `capitalize`?
+Это был `upper`? Или `uppercase`? `first_uppercase`? `capitalize`?
-Тогда вы попробуете с давним другом программиста: автодополнением редактора.
+Тогда вы пробуете старого друга программиста — автозавершение редактора кода.
-Вы вводите первый параметр функции, `first_name`, затем точку (`.`), а затем нажимаете `Ctrl+Space`, чтобы запустить дополнение.
+Вы вводите первый параметр функции, `first_name`, затем точку (`.`) и нажимаете `Ctrl+Space`, чтобы вызвать автозавершение.
-Но, к сожалению, ничего полезного не выходит:
+Но, к сожалению, ничего полезного не находится:
-### Добавим типы
+### Добавим типы { #add-types }
-Давайте изменим одну строчку в предыдущей версии.
+Давайте изменим одну строку из предыдущей версии.
-Мы изменим именно этот фрагмент, параметры функции, с:
+Мы поменяем ровно этот фрагмент — параметры функции — с:
```Python
first_name, last_name
@@ -75,15 +74,13 @@ John Doe
first_name: str, last_name: str
```
-Вот и все.
+Вот и всё.
-Это аннотации типов:
+Это и есть «подсказки типов»:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
-Это не то же самое, что объявление значений по умолчанию, например:
+Это не то же самое, что объявление значений по умолчанию, как, например:
```Python
first_name="john", last_name="doe"
@@ -91,224 +88,261 @@ John Doe
Это другая вещь.
-Мы используем двоеточия (`:`), а не равно (`=`).
+Здесь мы используем двоеточия (`:`), а не знак равенства (`=`).
-И добавление аннотаций типов обычно не меняет происходящего по сравнению с тем, что произошло бы без неё.
+И добавление подсказок типов обычно не меняет поведение программы по сравнению с вариантом без них.
-Но теперь представьте, что вы снова находитесь в процессе создания этой функции, но уже с аннотациями типов.
+Но теперь представьте, что вы снова посередине написания этой функции, только уже с подсказками типов.
-В тот же момент вы пытаетесь запустить автодополнение с помощью `Ctrl+Space` и вы видите:
+В тот же момент вы пробуете вызвать автозавершение с помощью `Ctrl+Space` — и видите:
-При этом вы можете просматривать варианты, пока не найдёте подходящий:
+С этим вы можете прокручивать варианты, пока не найдёте тот самый:
-## Больше мотивации
+## Больше мотивации { #more-motivation }
-Проверьте эту функцию, она уже имеет аннотации типов:
+Посмотрите на эту функцию — у неё уже есть подсказки типов:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
-Поскольку редактор знает типы переменных, вы получаете не только дополнение, но и проверки ошибок:
+Так как редактор кода знает типы переменных, вы получаете не только автозавершение, но и проверки ошибок:
-Теперь вы знаете, что вам нужно исправить, преобразовав `age` в строку с `str(age)`:
+Теперь вы знаете, что нужно исправить — преобразовать `age` в строку с помощью `str(age)`:
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
-## Объявление типов
+## Объявление типов { #declaring-types }
-Вы только что видели основное место для объявления подсказок типов. В качестве параметров функции.
+Вы только что увидели основное место, где объявляют подсказки типов — параметры функции.
-Это также основное место, где вы можете использовать их с **FastAPI**.
+Это также основное место, где вы будете использовать их с **FastAPI**.
-### Простые типы
+### Простые типы { #simple-types }
-Вы можете объявить все стандартные типы Python, а не только `str`.
+Вы можете объявлять все стандартные типы Python, не только `str`.
-Вы можете использовать, к примеру:
+Можно использовать, например:
* `int`
* `float`
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
-```
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
-### Generic-типы с параметрами типов
+### Модуль `typing` { #typing-module }
-Существуют некоторые структуры данных, которые могут содержать другие значения, например, `dict`, `list`, `set` и `tuple`. И внутренние значения тоже могут иметь свой тип.
+Для некоторых дополнительных сценариев может понадобиться импортировать что-то из стандартного модуля `typing`. Например, когда вы хотите объявить, что что-то имеет «любой тип», можно использовать `Any` из `typing`:
-Чтобы объявить эти типы и внутренние типы, вы можете использовать стандартный Python-модуль `typing`.
+```python
+from typing import Any
-Он существует специально для поддержки подсказок этих типов.
-#### `List`
+def some_function(data: Any):
+ print(data)
+```
-Например, давайте определим переменную как `list`, состоящий из `str`.
+### Generic-типы { #generic-types }
-Импортируйте `List` из `typing` (с заглавной `L`):
+Некоторые типы могут принимать «параметры типов» в квадратных скобках, чтобы определить их внутренние типы. Например, «список строк» объявляется как `list[str]`.
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+Такие типы, которые принимают параметры типов, называются **Generic-типами** или **Generics**.
+
+Вы можете использовать те же встроенные типы как generics (с квадратными скобками и типами внутри):
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
+
+#### List { #list }
+
+Например, давайте определим переменную как `list` из `str`.
Объявите переменную с тем же синтаксисом двоеточия (`:`).
-В качестве типа укажите `List`.
+В качестве типа укажите `list`.
-Поскольку список является типом, содержащим некоторые внутренние типы, вы помещаете их в квадратные скобки:
+Так как список — это тип, содержащий внутренние типы, укажите их в квадратных скобках:
-```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
+
+/// info | Информация
-!!! tip
- Эти внутренние типы в квадратных скобках называются «параметрами типов».
+Эти внутренние типы в квадратных скобках называются «параметрами типов».
- В этом случае `str` является параметром типа, передаваемым в `List`.
+В данном случае `str` — это параметр типа, передаваемый в `list`.
-Это означает: "переменная `items` является `list`, и каждый из элементов этого списка является `str`".
+///
-Если вы будете так поступать, редактор может оказывать поддержку даже при обработке элементов списка:
+Это означает: «переменная `items` — это `list`, и каждый элемент этого списка — `str`».
+
+Таким образом, ваш редактор кода сможет помогать даже при обработке элементов списка:
-Без типов добиться этого практически невозможно.
+Без типов добиться этого почти невозможно.
-Обратите внимание, что переменная `item` является одним из элементов списка `items`.
+Обратите внимание, что переменная `item` — один из элементов списка `items`.
-И все же редактор знает, что это `str`, и поддерживает это.
+И всё же редактор кода знает, что это `str`, и даёт соответствующую поддержку.
-#### `Tuple` и `Set`
+#### Tuple и Set { #tuple-and-set }
-Вы бы сделали то же самое, чтобы объявить `tuple` и `set`:
+Аналогично вы бы объявили `tuple` и `set`:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
-```
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
Это означает:
-* Переменная `items_t` является `tuple` с 3 элементами: `int`, другим `int` и `str`.
-* Переменная `items_s` является `set` и каждый элемент имеет тип `bytes`.
+* Переменная `items_t` — это `tuple` из 3 элементов: `int`, ещё один `int` и `str`.
+* Переменная `items_s` — это `set`, и каждый элемент имеет тип `bytes`.
-#### `Dict`
+#### Dict { #dict }
-Чтобы определить `dict`, вы передаёте 2 параметра типов, разделённых запятыми.
+Чтобы определить `dict`, вы передаёте 2 параметра типов, разделённые запятой.
-Первый параметр типа предназначен для ключей `dict`.
+Первый параметр типа — для ключей `dict`.
-Второй параметр типа предназначен для значений `dict`:
+Второй параметр типа — для значений `dict`:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
-```
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
Это означает:
-* Переменная `prices` является `dict`:
- * Ключи этого `dict` имеют тип `str` (скажем, название каждого элемента).
+* Переменная `prices` — это `dict`:
+ * Ключи этого `dict` имеют тип `str` (скажем, название каждой позиции).
* Значения этого `dict` имеют тип `float` (скажем, цена каждой позиции).
-#### `Optional`
+#### Union { #union }
-Вы также можете использовать `Optional`, чтобы объявить, что переменная имеет тип, например, `str`, но это является «необязательным», что означает, что она также может быть `None`:
+Вы можете объявить, что переменная может быть **одним из нескольких типов**, например, `int` или `str`.
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+Чтобы это определить, используйте вертикальную черту (`|`) для разделения обоих типов.
+
+Это называется «объединение» (union), потому что переменная может быть чем угодно из объединения этих двух множеств типов.
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
```
-Использование `Optional[str]` вместо просто `str` позволит редактору помочь вам в обнаружении ошибок, в которых вы могли бы предположить, что значение всегда является `str`, хотя на самом деле это может быть и `None`.
+Это означает, что `item` может быть `int` или `str`.
-#### Generic-типы
+#### Возможно `None` { #possibly-none }
-Эти типы принимают параметры в квадратных скобках:
+Вы можете объявить, что значение может иметь определённый тип, например `str`, но также может быть и `None`.
-* `List`
-* `Tuple`
-* `Set`
-* `Dict`
-* `Optional`
-* ...и др.
+//// tab | Python 3.10+
-называются **Generic-типами** или **Generics**.
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
-### Классы как типы
+////
-Вы также можете объявить класс как тип переменной.
+Использование `str | None` вместо просто `str` позволит редактору кода помочь вам обнаружить ошибки, когда вы предполагаете, что значение всегда `str`, хотя на самом деле оно может быть и `None`.
-Допустим, у вас есть класс `Person` с полем `name`:
+### Классы как типы { #classes-as-types }
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+Вы также можете объявлять класс как тип переменной.
+
+Допустим, у вас есть класс `Person` с именем:
+
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
Тогда вы можете объявить переменную типа `Person`:
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
-И снова вы получаете полную поддержку редактора:
+И снова вы получите полную поддержку редактора кода:
-## Pydantic-модели
+Обратите внимание, что это означает: «`one_person` — это **экземпляр** класса `Person`».
+
+Это не означает: «`one_person` — это **класс** с именем `Person`».
-Pydantic является Python-библиотекой для выполнения валидации данных.
+## Pydantic-модели { #pydantic-models }
+
+[Pydantic](https://docs.pydantic.dev/) — это библиотека Python для валидации данных.
Вы объявляете «форму» данных как классы с атрибутами.
-И каждый атрибут имеет тип.
+И у каждого атрибута есть тип.
-Затем вы создаете экземпляр этого класса с некоторыми значениями, и он проверяет значения, преобразует их в соответствующий тип (если все верно) и предоставляет вам объект со всеми данными.
+Затем вы создаёте экземпляр этого класса с некоторыми значениями — он провалидирует значения, преобразует их к соответствующему типу (если это применимо) и вернёт вам объект со всеми данными.
-И вы получаете полную поддержку редактора для этого итогового объекта.
+И вы получите полную поддержку редактора кода для этого результирующего объекта.
-Взято из официальной документации Pydantic:
+Пример из официальной документации Pydantic:
-```Python
-{!../../../docs_src/python_types/tutorial011.py!}
-```
+{* ../../docs_src/python_types/tutorial011_py310.py *}
+
+/// info | Информация
-!!! info
- Чтобы узнать больше о Pydantic, читайте его документацию.
+Чтобы узнать больше о [Pydantic, ознакомьтесь с его документацией](https://docs.pydantic.dev/).
+
+///
**FastAPI** целиком основан на Pydantic.
-Вы увидите намного больше всего этого на практике в [Руководстве пользователя](tutorial/index.md){.internal-link target=_blank}.
+Вы увидите намного больше всего этого на практике в [Учебник - Руководство пользователя](tutorial/index.md).
+
+## Подсказки типов с аннотациями метаданных { #type-hints-with-metadata-annotations }
+
+В Python также есть возможность добавлять **дополнительные метаданные** к подсказкам типов с помощью `Annotated`.
-## Аннотации типов в **FastAPI**
+Вы можете импортировать `Annotated` из `typing`.
-**FastAPI** получает преимущества аннотаций типов для выполнения определённых задач.
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
-С **FastAPI** вы объявляете параметры с аннотациями типов и получаете:
+Сам Python ничего не делает с `Annotated`. А для редакторов кода и других инструментов тип по-прежнему `str`.
-* **Поддержку редактора**.
+Но вы можете использовать это место в `Annotated`, чтобы передать **FastAPI** дополнительные метаданные о том, как вы хотите, чтобы ваше приложение себя вело.
+
+Важно помнить, что **первый параметр типа**, который вы передаёте в `Annotated`, — это **фактический тип**. Всё остальное — просто метаданные для других инструментов.
+
+Пока вам достаточно знать, что `Annotated` существует и это — стандартный Python. 😎
+
+Позже вы увидите, насколько это **мощно**.
+
+/// tip | Совет
+
+Тот факт, что это **стандартный Python**, означает, что вы по-прежнему получите **лучший возможный разработческий опыт** в вашем редакторе кода, с инструментами для анализа и рефакторинга кода и т.д. ✨
+
+А ещё ваш код будет очень совместим со множеством других инструментов и библиотек Python. 🚀
+
+///
+
+## Аннотации типов в **FastAPI** { #type-hints-in-fastapi }
+
+**FastAPI** использует эти подсказки типов для выполнения нескольких задач.
+
+С **FastAPI** вы объявляете параметры с подсказками типов и получаете:
+
+* **Поддержку редактора кода**.
* **Проверки типов**.
-...и **FastAPI** использует тот же механизм для:
+...и **FastAPI** использует эти же объявления для:
-* **Определения требований**: из параметров пути запроса, параметров запроса, заголовков, зависимостей и т.д.
-* **Преобразования данных**: от запроса к нужному типу.
-* **Валидации данных**: исходя из каждого запроса:
- * Генерации **автоматических ошибок**, возвращаемых клиенту, когда данные не являются корректными.
+* **Определения требований**: из path-параметров пути запроса, query-параметров, HTTP-заголовков, тел запросов, зависимостей и т.д.
+* **Преобразования данных**: из HTTP-запроса к требуемому типу.
+* **Валидации данных**: приходящих с каждого HTTP-запроса:
+ * Генерации **автоматических ошибок**, возвращаемых клиенту, когда данные некорректны.
* **Документирования** API с использованием OpenAPI:
- * который затем используется пользовательскими интерфейсами автоматической интерактивной документации.
+ * что затем используется пользовательскими интерфейсами автоматической интерактивной документации.
+
+Всё это может звучать абстрактно. Не волнуйтесь. Вы увидите всё это в действии в [Учебник - Руководство пользователя](tutorial/index.md).
+
+Важно то, что, используя стандартные типы Python в одном месте (вместо добавления дополнительных классов, декораторов и т.д.), **FastAPI** сделает за вас большую часть работы.
-Всё это может показаться абстрактным. Не волнуйтесь. Вы увидите всё это в действии в [Руководстве пользователя](tutorial/index.md){.internal-link target=_blank}.
+/// info | Информация
-Важно то, что при использовании стандартных типов Python в одном месте (вместо добавления дополнительных классов, декораторов и т.д.) **FastAPI** сделает за вас большую часть работы.
+Если вы уже прошли всё руководство и вернулись, чтобы узнать больше о типах, хорошим ресурсом будет [«шпаргалка» от `mypy`](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html).
-!!! info
- Если вы уже прошли всё руководство и вернулись, чтобы узнать больше о типах, хорошим ресурсом является «шпаргалка» от `mypy`.
+///
diff --git a/docs/ru/docs/resources/index.md b/docs/ru/docs/resources/index.md
new file mode 100644
index 0000000000000..faf80f7f495c3
--- /dev/null
+++ b/docs/ru/docs/resources/index.md
@@ -0,0 +1,3 @@
+# Ресурсы { #resources }
+
+Дополнительные ресурсы, внешние ссылки и многое другое. ✈️
diff --git a/docs/ru/docs/translation-banner.md b/docs/ru/docs/translation-banner.md
new file mode 100644
index 0000000000000..78ebd676c50dc
--- /dev/null
+++ b/docs/ru/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 Перевод выполнен с помощью ИИ и людей
+
+Этот перевод был сделан ИИ под руководством людей. 🤝
+
+В нем могут быть ошибки из-за неправильного понимания оригинального смысла или неестественности и т. д. 🤖
+
+Вы можете улучшить этот перевод, [помогая нам лучше направлять ИИ LLM](https://fastapi.tiangolo.com/ru/contributing/#translations).
+
+[Английская версия](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md
index 81efda786ad8c..22827b69f3e9e 100644
--- a/docs/ru/docs/tutorial/background-tasks.md
+++ b/docs/ru/docs/tutorial/background-tasks.md
@@ -1,102 +1,84 @@
-# Фоновые задачи
+# Фоновые задачи { #background-tasks }
-Вы можете создавать фоновые задачи, которые будут выполнятся *после* возвращения ответа сервером.
+Вы можете создавать фоновые задачи, которые будут выполняться после возврата ответа.
-Это может быть полезно для функций, которые должны выполниться после получения запроса, но ожидание их выполнения необязательно для пользователя.
+Это полезно для операций, которые должны произойти после HTTP-запроса, но клиенту не обязательно ждать их завершения, чтобы получить ответ.
-К примеру:
+Например:
-* Отправка писем на почту после выполнения каких-либо действий:
- * Т.к. соединение с почтовым сервером и отправка письма идут достаточно "долго" (несколько секунд), вы можете отправить ответ пользователю, а отправку письма выполнить в фоне.
+* Уведомления по электронной почте, отправляемые после выполнения действия:
+ * Так как подключение к почтовому серверу и отправка письма обычно «медленные» (несколько секунд), вы можете сразу вернуть ответ, а отправку уведомления выполнить в фоне.
* Обработка данных:
- * К примеру, если вы получаете файл, который должен пройти через медленный процесс, вы можете отправить ответ "Accepted" (HTTP 202) и отправить работу с файлом в фон.
+ * Например, если вы получаете файл, который должен пройти через медленный процесс, вы можете вернуть ответ «Accepted» (HTTP 202) и обработать файл в фоне.
-## Использование класса `BackgroundTasks`
+## Использование `BackgroundTasks` { #using-backgroundtasks }
-Сначала импортируйте `BackgroundTasks`, потом добавьте в функцию параметр с типом `BackgroundTasks`:
+Сначала импортируйте `BackgroundTasks` и объявите параметр в вашей функции‑обработчике пути с типом `BackgroundTasks`:
-```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
-**FastAPI** создаст объект класса `BackgroundTasks` для вас и запишет его в параметр.
+**FastAPI** создаст объект типа `BackgroundTasks` для вас и передаст его через этот параметр.
-## Создание функции для фоновой задачи
+## Создание функции для фоновой задачи { #create-a-task-function }
-Создайте функцию, которую хотите запустить в фоне.
+Создайте функцию, которую нужно запустить как фоновую задачу.
-Это совершенно обычная функция, которая может принимать параметры.
+Это обычная функция, которая может принимать параметры.
-Она может быть как асинхронной `async def`, так и обычной `def` функцией, **FastAPI** знает, как правильно ее выполнить.
+Это может быть как `async def`, так и обычная функция `def`, **FastAPI** знает, как корректно её выполнить.
-В нашем примере фоновая задача будет вести запись в файл (симулируя отправку письма).
+В этом случае функция задачи будет записывать данные в файл (имитируя отправку письма).
-Так как операция записи не использует `async` и `await`, мы определим ее как обычную `def`:
+Так как операция записи не использует `async` и `await`, мы определим функцию как обычную `def`:
-```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
-## Добавление фоновой задачи
+## Добавление фоновой задачи { #add-the-background-task }
-Внутри функции вызовите метод `.add_task()` у объекта *background tasks* и передайте ему функцию, которую хотите выполнить в фоне:
+Внутри вашей функции‑обработчика пути передайте функцию задачи объекту фоновых задач методом `.add_task()`:
-```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
`.add_task()` принимает следующие аргументы:
-* Функцию, которая будет выполнена в фоне (`write_notification`). Обратите внимание, что передается объект функции, без скобок.
-* Любое упорядоченное количество аргументов, которые принимает функция (`email`).
-* Любое количество именованных аргументов, которые принимает функция (`message="some notification"`).
+* Функцию задачи, которую нужно выполнить в фоне (`write_notification`).
+* Последовательность позиционных аргументов, которые должны быть переданы функции задачи, в порядке (`email`).
+* Любые именованные аргументы, которые должны быть переданы функции задачи (`message="some notification"`).
-## Встраивание зависимостей
+## Встраивание зависимостей { #dependency-injection }
-Класс `BackgroundTasks` также работает с системой встраивания зависимостей, вы можете определить `BackgroundTasks` на разных уровнях: как параметр функции, как завимость, как подзависимость и так далее.
+Использование `BackgroundTasks` также работает с системой встраивания зависимостей, вы можете объявить параметр типа `BackgroundTasks` на нескольких уровнях: в функции‑обработчике пути, в зависимости (dependable), в подзависимости и т.д.
-**FastAPI** знает, что нужно сделать в каждом случае и как переиспользовать тот же объект `BackgroundTasks`, так чтобы все фоновые задачи собрались и запустились вместе в фоне:
+**FastAPI** знает, что делать в каждом случае и как переиспользовать один и тот же объект, так чтобы все фоновые задачи были объединены и затем выполнены в фоне:
-=== "Python 3.10+"
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
+В этом примере сообщения будут записаны в файл `log.txt` после отправки ответа.
-=== "Python 3.6+"
+Если в запросе была строка запроса (query), она будет записана в лог фоновой задачей.
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
+Затем другая фоновая задача, созданная в функции‑обработчике пути, запишет сообщение, используя path‑параметр `email`.
-В этом примере сообщения будут записаны в `log.txt` *после* того, как ответ сервера был отправлен.
+## Технические детали { #technical-details }
-Если бы в запросе была очередь `q`, она бы первой записалась в `log.txt` фоновой задачей (потому что вызывается в зависимости `get_query`).
+Класс `BackgroundTasks` приходит напрямую из [`starlette.background`](https://www.starlette.dev/background/).
-После другая фоновая задача, которая была сгенерирована в функции, запишет сообщение из параметра `email`.
+Он импортируется/включается прямо в FastAPI, чтобы вы могли импортировать его из `fastapi` и избежать случайного импорта альтернативного `BackgroundTask` (без `s` на конце) из `starlette.background`.
-## Технические детали
+Используя только `BackgroundTasks` (а не `BackgroundTask`), его можно применять как параметр функции‑обработчика пути, и **FastAPI** сделает остальное за вас, как при использовании объекта `Request` напрямую.
-Класс `BackgroundTasks` основан на `starlette.background`.
+По‑прежнему можно использовать один `BackgroundTask` в FastAPI, но тогда вам нужно создать объект в своём коде и вернуть Starlette `Response`, включающий его.
-Он интегрирован в FastAPI, так что вы можете импортировать его прямо из `fastapi` и избежать случайного импорта `BackgroundTask` (без `s` на конце) из `starlette.background`.
+Подробнее см. в [официальной документации Starlette по фоновым задачам](https://www.starlette.dev/background/).
-При использовании `BackgroundTasks` (а не `BackgroundTask`), вам достаточно только определить параметр функции с типом `BackgroundTasks` и **FastAPI** сделает все за вас, также как при использовании объекта `Request`.
+## Предостережение { #caveat }
-Вы все равно можете использовать `BackgroundTask` из `starlette` в FastAPI, но вам придется самостоятельно создавать объект фоновой задачи и вручную обработать `Response` внутри него.
+Если вам нужно выполнять тяжелые вычисления в фоне, и при этом они не обязательно должны запускаться тем же процессом (например, вам не нужно делиться памятью, переменными и т.п.), вам могут подойти более мощные инструменты, такие как [Celery](https://docs.celeryq.dev).
-Вы можете подробнее изучить его в Официальной документации Starlette для BackgroundTasks.
+Они обычно требуют более сложной конфигурации, менеджера очереди сообщений/заданий (например, RabbitMQ или Redis), но позволяют запускать фоновые задачи в нескольких процессах и, что особенно важно, на нескольких серверах.
-## Предостережение
+Но если вам нужен доступ к переменным и объектам из того же приложения **FastAPI**, или нужно выполнять небольшие фоновые задачи (например, отправку email‑уведомления), вы можете просто использовать `BackgroundTasks`.
-Если вам нужно выполнить тяжелые вычисления в фоне, которым необязательно быть запущенными в одном процессе с приложением **FastAPI** (к примеру, вам не нужны обрабатываемые переменные или вы не хотите делиться памятью процесса и т.д.), вы можете использовать более серьезные инструменты, такие как Celery.
+## Резюме { #recap }
-Их тяжелее настраивать, также им нужен брокер сообщений наподобие RabbitMQ или Redis, но зато они позволяют вам запускать фоновые задачи в нескольких процессах и даже на нескольких серверах.
-
-Для примера, посмотрите [Project Generators](../project-generation.md){.internal-link target=_blank}, там есть проект с уже настроенным Celery.
-
-Но если вам нужен доступ к общим переменным и объектам вашего **FastAPI** приложения или вам нужно выполнять простые фоновые задачи (наподобие отправки письма из примера) вы можете просто использовать `BackgroundTasks`.
-
-## Резюме
-
-Для создания фоновых задач вам необходимо импортировать `BackgroundTasks` и добавить его в функцию, как параметр с типом `BackgroundTasks`.
+Импортируйте и используйте `BackgroundTasks` с параметрами в функциях‑обработчиках пути и зависимостях, чтобы добавлять фоновые задачи.
diff --git a/docs/ru/docs/tutorial/bigger-applications.md b/docs/ru/docs/tutorial/bigger-applications.md
new file mode 100644
index 0000000000000..972313559ae2e
--- /dev/null
+++ b/docs/ru/docs/tutorial/bigger-applications.md
@@ -0,0 +1,535 @@
+# Большие приложения — несколько файлов { #bigger-applications-multiple-files }
+
+При построении приложения или веб-API нам редко удается поместить всё в один файл.
+
+**FastAPI** предоставляет удобный инструментарий, который позволяет нам структурировать приложение, сохраняя при этом всю необходимую гибкость.
+
+/// info | Примечание
+
+Если вы раньше использовали Flask, то это аналог шаблонов Flask (Flask's Blueprints).
+
+///
+
+## Пример структуры приложения { #an-example-file-structure }
+
+Давайте предположим, что наше приложение имеет следующую структуру:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ ├── dependencies.py
+│ └── routers
+│ │ ├── __init__.py
+│ │ ├── items.py
+│ │ └── users.py
+│ └── internal
+│ ├── __init__.py
+│ └── admin.py
+```
+
+/// tip | Подсказка
+
+Есть несколько файлов `__init__.py`: по одному в каждом каталоге или подкаталоге.
+
+Это как раз то, что позволяет импортировать код из одного файла в другой.
+
+Например, в файле `app/main.py` может быть следующая строка:
+
+```
+from app.routers import items
+```
+
+///
+
+* Всё помещается в каталоге `app`. В нём также находится пустой файл `app/__init__.py`. Таким образом, `app` является "Python-пакетом" (коллекцией "Python-модулей"): `app`.
+* Он содержит файл `app/main.py`. Данный файл является частью Python-пакета (т.е. находится внутри каталога, содержащего файл `__init__.py`), и, соответственно, он является модулем этого пакета: `app.main`.
+* Он также содержит файл `app/dependencies.py`, который также, как и `app/main.py`, является модулем: `app.dependencies`.
+* Здесь также находится подкаталог `app/routers/`, содержащий `__init__.py`. Он является Python-подпакетом: `app.routers`.
+* Файл `app/routers/items.py` находится внутри пакета `app/routers/`. Таким образом, он является подмодулем: `app.routers.items`.
+* Точно так же `app/routers/users.py` является ещё одним подмодулем: `app.routers.users`.
+* Подкаталог `app/internal/`, содержащий файл `__init__.py`, является ещё одним Python-подпакетом: `app.internal`.
+* А файл `app/internal/admin.py` является ещё одним подмодулем: `app.internal.admin`.
+
+
+
+## Подключение одного и того же маршрутизатора несколько раз с разными `prefix` { #include-the-same-router-multiple-times-with-different-prefix }
+
+Вы можете использовать `.include_router()` несколько раз с *одним и тем же* маршрутизатором, используя разные префиксы.
+
+Это может быть полезно, например, чтобы предоставить доступ к одному и тому же API с разными префиксами, например `/api/v1` и `/api/latest`.
+
+Это продвинутое использование, которое вам может и не понадобиться, но оно есть на случай, если понадобится.
+
+## Подключение `APIRouter` в другой `APIRouter` { #include-an-apirouter-in-another }
+
+Точно так же, как вы можете подключить `APIRouter` к приложению `FastAPI`, вы можете подключить `APIRouter` к другому `APIRouter`, используя:
+
+```Python
+router.include_router(other_router)
+```
+
+Убедитесь, что вы сделали это до подключения `router` к приложению `FastAPI`, чтобы *операции пути* из `other_router` также были подключены.
diff --git a/docs/ru/docs/tutorial/body-fields.md b/docs/ru/docs/tutorial/body-fields.md
index 2dc6c1e260a13..cf6cf480a4156 100644
--- a/docs/ru/docs/tutorial/body-fields.md
+++ b/docs/ru/docs/tutorial/body-fields.md
@@ -1,68 +1,59 @@
-# Body - Поля
+# Body - Поля { #body-fields }
Таким же способом, как вы объявляете дополнительную валидацию и метаданные в параметрах *функции обработки пути* с помощью функций `Query`, `Path` и `Body`, вы можете объявлять валидацию и метаданные внутри Pydantic моделей, используя функцию `Field` из Pydantic.
-## Импорт `Field`
+## Импорт `Field` { #import-field }
Сначала вы должны импортировать его:
-=== "Python 3.10+"
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+/// warning | Внимание
-=== "Python 3.6+"
+Обратите внимание, что функция `Field` импортируется непосредственно из `pydantic`, а не из `fastapi`, как все остальные функции (`Query`, `Path`, `Body` и т.д.).
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+///
-!!! warning "Внимание"
- Обратите внимание, что функция `Field` импортируется непосредственно из `pydantic`, а не из `fastapi`, как все остальные функции (`Query`, `Path`, `Body` и т.д.).
-
-## Объявление атрибутов модели
+## Объявление атрибутов модели { #declare-model-attributes }
Вы можете использовать функцию `Field` с атрибутами модели:
-=== "Python 3.10+"
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+Функция `Field` работает так же, как `Query`, `Path` и `Body`, у неё такие же параметры и т.д.
-=== "Python 3.6+"
+/// note | Технические детали
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+На самом деле, `Query`, `Path` и другие функции, которые вы увидите в дальнейшем, создают объекты подклассов общего класса `Param`, который сам по себе является подклассом `FieldInfo` из Pydantic.
-Функция `Field` работает так же, как `Query`, `Path` и `Body`, у неё такие же параметры и т.д.
+И `Field` (из Pydantic) также возвращает экземпляр `FieldInfo`.
-!!! note "Технические детали"
- На самом деле, `Query`, `Path` и другие функции, которые вы увидите в дальнейшем, создают объекты подклассов общего класса `Param`, который сам по себе является подклассом `FieldInfo` из Pydantic.
+`Body` также напрямую возвращает объекты подкласса `FieldInfo`. И есть и другие, с которыми вы познакомитесь позже, которые являются подклассами класса `Body`.
- И `Field` (из Pydantic), и `Body`, оба возвращают объекты подкласса `FieldInfo`.
+Помните, что когда вы импортируете `Query`, `Path` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы.
- У класса `Body` есть и другие подклассы, с которыми вы ознакомитесь позже.
+///
- Помните, что когда вы импортируете `Query`, `Path` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы.
+/// tip | Подсказка
-!!! tip "Подсказка"
- Обратите внимание, что каждый атрибут модели с типом, значением по умолчанию и `Field` имеет ту же структуру, что и параметр *функции обработки пути* с `Field` вместо `Path`, `Query` и `Body`.
+Обратите внимание, что каждый атрибут модели с типом, значением по умолчанию и `Field` имеет ту же структуру, что и параметр *функции обработки пути* с `Field` вместо `Path`, `Query` и `Body`.
-## Добавление дополнительной информации
+///
+
+## Добавление дополнительной информации { #add-extra-information }
Вы можете объявлять дополнительную информацию в `Field`, `Query`, `Body` и т.п. Она будет включена в сгенерированную JSON схему.
-Вы узнаете больше о добавлении дополнительной информации позже в документации, когда будете изучать, как задавать примеры принимаемых данных.
+Вы узнаете больше о добавлении дополнительной информации позже в документации, когда будете изучать, как задавать примеры.
+
+/// warning | Внимание
+Дополнительные ключи, переданные в функцию `Field`, также будут присутствовать в сгенерированной OpenAPI схеме вашего приложения.
+Поскольку эти ключи не являются обязательной частью спецификации OpenAPI, некоторые инструменты OpenAPI, например, [валидатор OpenAPI](https://validator.swagger.io/), могут не работать с вашей сгенерированной схемой.
-!!! warning "Внимание"
- Дополнительные ключи, переданные в функцию `Field`, также будут присутствовать в сгенерированной OpenAPI схеме вашего приложения.
- Поскольку эти ключи не являются обязательной частью спецификации OpenAPI, некоторые инструменты OpenAPI, например, [валидатор OpenAPI](https://validator.swagger.io/), могут не работать с вашей сгенерированной схемой.
+///
-## Резюме
+## Резюме { #recap }
Вы можете использовать функцию `Field` из Pydantic, чтобы задавать дополнительную валидацию и метаданные для атрибутов модели.
diff --git a/docs/ru/docs/tutorial/body-multiple-params.md b/docs/ru/docs/tutorial/body-multiple-params.md
index a20457092b34b..ddd9c6fdd9bb5 100644
--- a/docs/ru/docs/tutorial/body-multiple-params.md
+++ b/docs/ru/docs/tutorial/body-multiple-params.md
@@ -1,55 +1,24 @@
-# Body - Множество параметров
+# Body - Множество параметров { #body-multiple-parameters }
-Теперь, когда мы увидели, как использовать `Path` и `Query` параметры, давайте рассмотрим более продвинутые примеры обьявления тела запроса.
+Теперь, когда мы увидели, как использовать `Path` и `Query` параметры, давайте рассмотрим более продвинутые примеры объявления тела запроса.
-## Обьединение `Path`, `Query` и параметров тела запроса
+## Объединение `Path`, `Query` и параметров тела запроса { #mix-path-query-and-body-parameters }
Во-первых, конечно, вы можете объединять параметры `Path`, `Query` и объявления тела запроса в своих функциях обработки, **FastAPI** автоматически определит, что с ними нужно делать.
Вы также можете объявить параметры тела запроса как необязательные, установив значение по умолчанию, равное `None`:
-=== "Python 3.10+"
+{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
- ```
+/// note | Заметка
-=== "Python 3.9+"
+Заметьте, что в данном случае параметр `item`, который будет взят из тела запроса, необязателен. Так как было установлено значение `None` по умолчанию.
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
- ```
+///
-=== "Python 3.6+"
+## Несколько параметров тела запроса { #multiple-body-parameters }
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! Заметка
- Рекомендуется использовать `Annotated` версию, если это возможно.
-
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! Заметка
- Рекомендуется использовать версию с `Annotated`, если это возможно.
-
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
-
-!!! Заметка
- Заметьте, что в данном случае параметр `item`, который будет взят из тела запроса, необязателен. Так как было установлено значение `None` по умолчанию.
-
-## Несколько параметров тела запроса
-
-В предыдущем примере, *операции пути* ожидали тело запроса в формате JSON-тело с параметрами, соответствующими атрибутам `Item`, например:
+В предыдущем примере, *операции пути* ожидали тело запроса в формате JSON, с параметрами, соответствующими атрибутам `Item`, например:
```JSON
{
@@ -62,19 +31,9 @@
Но вы также можете объявить множество параметров тела запроса, например `item` и `user`:
-=== "Python 3.10+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}
-В этом случае **FastAPI** заметит, что в функции есть более одного параметра тела (два параметра, которые являются моделями Pydantic).
+В этом случае **FastAPI** заметит, что в функции есть более одного параметра тела (два параметра, которые являются Pydantic-моделями).
Таким образом, имена параметров будут использоваться в качестве ключей (имён полей) в теле запроса, и будет ожидаться запрос следующего формата:
@@ -93,59 +52,27 @@
}
```
-!!! Внимание
- Обратите внимание, что хотя параметр `item` был объявлен таким же способом, как и раньше, теперь предпологается, что он находится внутри тела с ключом `item`.
+/// note | Заметка
+Обратите внимание, что хотя параметр `item` был объявлен таким же способом, как и раньше, теперь предполагается, что он находится внутри тела с ключом `item`.
-**FastAPI** сделает автоматические преобразование из запроса, так что параметр `item` получит своё конкретное содержимое, и то же самое происходит с пользователем `user`.
+///
+
+**FastAPI** сделает автоматическое преобразование из запроса, так что параметр `item` получит своё конкретное содержимое, и то же самое происходит с пользователем `user`.
Произойдёт проверка составных данных, и создание документации в схеме OpenAPI и автоматических документах.
-## Отдельные значения в теле запроса
+## Отдельные значения в теле запроса { #singular-values-in-body }
Точно так же, как `Query` и `Path` используются для определения дополнительных данных для query и path параметров, **FastAPI** предоставляет аналогичный инструмент - `Body`.
Например, расширяя предыдущую модель, вы можете решить, что вам нужен еще один ключ `importance` в том же теле запроса, помимо параметров `item` и `user`.
-Если вы объявите его без указания, какой именно объект (Path, Query, Body и .т.п.) ожидаете, то, поскольку это является простым типом данных, **FastAPI** будет считать, что это query-параметр.
+Если вы объявите его без указания, какой именно объект (Path, Query, Body и т.п.) ожидаете, то, поскольку это является простым типом данных, **FastAPI** будет считать, что это query-параметр.
Но вы можете указать **FastAPI** обрабатывать его, как ещё один ключ тела запроса, используя `Body`:
-=== "Python 3.10+"
-
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! Заметка
- Рекомендуется использовать `Annotated` версию, если это возможно.
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! Заметка
- Рекомендуется использовать `Annotated` версию, если это возможно.
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
В этом случае, **FastAPI** будет ожидать тело запроса в формате:
@@ -167,66 +94,29 @@
И всё будет работать так же - преобразование типов данных, валидация, документирование и т.д.
-## Множество body и query параметров
+## Множество body и query параметров { #multiple-body-params-and-query }
Конечно, вы также можете объявлять query-параметры в любое время, дополнительно к любым body-параметрам.
Поскольку по умолчанию, отдельные значения интерпретируются как query-параметры, вам не нужно явно добавлять `Query`, вы можете просто сделать так:
-```Python
-q: Union[str, None] = None
-```
-
-Или в Python 3.10 и выше:
-
```Python
q: str | None = None
```
Например:
-=== "Python 3.10+"
-
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="28"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! Заметка
- Рекомендуется использовать `Annotated` версию, если это возможно.
-
- ```Python hl_lines="25"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
-=== "Python 3.6+ non-Annotated"
+/// info | Информация
- !!! Заметка
- Рекомендуется использовать `Annotated` версию, если это возможно.
+`Body` также имеет все те же дополнительные параметры валидации и метаданных, как у `Query`, `Path` и других, которые вы увидите позже.
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+///
-!!! Информация
- `Body` также имеет все те же дополнительные параметры валидации и метаданных, как у `Query`,`Path` и других, которые вы увидите позже.
+## Вложить один body-параметр { #embed-a-single-body-parameter }
-## Добавление одного body-параметра
-
-Предположим, у вас есть только один body-параметр `item` из Pydantic модели `Item`.
+Предположим, у вас есть только один body-параметр `item` из Pydantic-модели `Item`.
По умолчанию, **FastAPI** ожидает получить тело запроса напрямую.
@@ -238,41 +128,7 @@ item: Item = Body(embed=True)
так же, как в этом примере:
-=== "Python 3.10+"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! Заметка
- Рекомендуется использовать `Annotated` версию, если это возможно.
-
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! Заметка
- Рекомендуется использовать `Annotated` версию, если это возможно.
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}
В этом случае **FastAPI** будет ожидать тело запроса в формате:
@@ -298,9 +154,9 @@ item: Item = Body(embed=True)
}
```
-## Резюме
+## Резюме { #recap }
-Вы можете добавлять несколько body-параметров вашей *функции операции пути*, несмотря даже на то, что запрос может содержать только одно тело.
+Вы можете добавлять несколько body-параметров вашей *функции-обработчика пути*, несмотря даже на то, что запрос может содержать только одно тело.
Но **FastAPI** справится с этим, предоставит правильные данные в вашей функции, а также сделает валидацию и документацию правильной схемы *операции пути*.
diff --git a/docs/ru/docs/tutorial/body-nested-models.md b/docs/ru/docs/tutorial/body-nested-models.md
index 6435e316f4254..fab025dbc9698 100644
--- a/docs/ru/docs/tutorial/body-nested-models.md
+++ b/docs/ru/docs/tutorial/body-nested-models.md
@@ -1,109 +1,44 @@
-# Body - Вложенные модели
+# Body - Вложенные модели { #body-nested-models }
-С помощью **FastAPI**, вы можете определять, валидировать, документировать и использовать модели произвольной вложенности (благодаря библиотеке Pydantic).
+С помощью **FastAPI** вы можете определять, валидировать, документировать и использовать модели произвольной глубины вложенности (благодаря Pydantic).
-## Определение полей содержащих списки
+## Поля-списки { #list-fields }
-Вы можете определять атрибут как подтип. Например, тип `list` в Python:
+Вы можете определить атрибут как подтип. Например, Python-тип `list`:
-=== "Python 3.10+"
+{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
- ```
+Это приведёт к тому, что `tags` будет списком, несмотря на то, что тип его элементов не объявлен.
-=== "Python 3.6+"
+## Поля-списки с параметром типа { #list-fields-with-type-parameter }
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial001.py!}
- ```
+В Python есть специальный способ объявлять списки с внутренними типами, или «параметрами типа»:
-Это приведёт к тому, что обьект `tags` преобразуется в список, несмотря на то что тип его элементов не объявлен.
+### Объявите `list` с параметром типа { #declare-a-list-with-a-type-parameter }
-## Определение полей содержащих список с определением типов его элементов
-
-Однако в Python есть способ объявления списков с указанием типов для вложенных элементов:
-
-### Импортируйте `List` из модуля typing
-
-В Python 3.9 и выше вы можете использовать стандартный тип `list` для объявления аннотаций типов, как мы увидим ниже. 💡
-
-Но в версиях Python до 3.9 (начиная с 3.6) сначала вам необходимо импортировать `List` из стандартного модуля `typing` в Python:
-
-```Python hl_lines="1"
-{!> ../../../docs_src/body_nested_models/tutorial002.py!}
-```
-
-### Объявление `list` с указанием типов для вложенных элементов
-
-Объявление типов для элементов (внутренних типов) вложенных в такие типы как `list`, `dict`, `tuple`:
-
-* Если у вас Python версии ниже чем 3.9, импортируйте их аналог из модуля `typing`
-* Передайте внутренний(ие) тип(ы) как "параметры типа", используя квадратные скобки: `[` и `]`
-
-В Python версии 3.9 это будет выглядеть так:
+Для объявления типов, у которых есть параметры типа (внутренние типы), таких как `list`, `dict`, `tuple`, передайте внутренний(ие) тип(ы) как «параметры типа», используя квадратные скобки: `[` и `]`
```Python
my_list: list[str]
```
-В версиях Python до 3.9 это будет выглядеть так:
-
-```Python
-from typing import List
-
-my_list: List[str]
-```
-
Это всё стандартный синтаксис Python для объявления типов.
Используйте этот же стандартный синтаксис для атрибутов модели с внутренними типами.
-Таким образом, в нашем примере мы можем явно указать тип данных для поля `tags` как "список строк":
-
-=== "Python 3.10+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002.py!}
- ```
+Таким образом, в нашем примере мы можем явно указать тип данных для поля `tags` как «список строк»:
-## Типы множеств
+{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}
-Но затем мы подумали и поняли, что теги не должны повторяться и, вероятно, они должны быть уникальными строками.
+## Типы множеств { #set-types }
-И в Python есть специальный тип данных для множеств уникальных элементов - `set`.
+Но затем мы подумали и поняли, что теги не должны повторяться, вероятно, это должны быть уникальные строки.
-Тогда мы может обьявить поле `tags` как множество строк:
+И в Python есть специальный тип данных для множеств уникальных элементов — `set`.
-=== "Python 3.10+"
+Тогда мы можем объявить поле `tags` как множество строк:
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="1 14"
- {!> ../../../docs_src/body_nested_models/tutorial003.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}
С помощью этого, даже если вы получите запрос с повторяющимися данными, они будут преобразованы в множество уникальных элементов.
@@ -111,59 +46,27 @@ my_list: List[str]
И они также будут соответствующим образом аннотированы / задокументированы.
-## Вложенные Модели
+## Вложенные модели { #nested-models }
У каждого атрибута Pydantic-модели есть тип.
-Но этот тип может сам быть другой моделью Pydantic.
+Но этот тип сам может быть другой моделью Pydantic.
-Таким образом вы можете объявлять глубоко вложенные JSON "объекты" с определёнными именами атрибутов, типами и валидацией.
+Таким образом, вы можете объявлять глубоко вложенные JSON «объекты» с определёнными именами атрибутов, типами и валидацией.
Всё это может быть произвольно вложенным.
-### Определение подмодели
+### Определение подмодели { #define-a-submodel }
Например, мы можем определить модель `Image`:
-=== "Python 3.10+"
-
- ```Python hl_lines="7-9"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}
-=== "Python 3.6+"
-
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
-
-### Использование вложенной модели в качестве типа
+### Использование подмодели как типа { #use-the-submodel-as-a-type }
Также мы можем использовать эту модель как тип атрибута:
-=== "Python 3.10+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}
Это означает, что **FastAPI** будет ожидать тело запроса, аналогичное этому:
@@ -183,62 +86,30 @@ my_list: List[str]
Ещё раз: сделав такое объявление, с помощью **FastAPI** вы получите:
-* Поддержку редакторов IDE (автодополнение и т.д), даже для вложенных моделей
+* Поддержку редактора кода (автозавершение и т.д.), даже для вложенных моделей
* Преобразование данных
* Валидацию данных
* Автоматическую документацию
-## Особые типы и валидация
-
-Помимо обычных простых типов, таких как `str`, `int`, `float`, и т.д. Вы можете использовать более сложные базовые типы, которые наследуются от типа `str`.
-
-Чтобы увидеть все варианты, которые у вас есть, ознакомьтесь с документацией по необычным типам Pydantic. Вы увидите некоторые примеры в следующей главе.
-
-Например, так как в модели `Image` у нас есть поле `url`, то мы можем объявить его как тип `HttpUrl` из модуля Pydantic вместо типа `str`:
-
-=== "Python 3.10+"
-
- ```Python hl_lines="2 8"
- {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
- ```
+## Особые типы и валидация { #special-types-and-validation }
-=== "Python 3.6+"
+Помимо обычных простых типов, таких как `str`, `int`, `float` и т.д., вы можете использовать более сложные простые типы, которые наследуются от `str`.
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005.py!}
- ```
+Чтобы увидеть все варианты, которые у вас есть, ознакомьтесь с [обзором типов Pydantic](https://docs.pydantic.dev/latest/concepts/types/). Вы увидите некоторые примеры в следующей главе.
-Строка будет проверена на соответствие допустимому URL-адресу и задокументирована в JSON схему / OpenAPI.
+Например, так как в модели `Image` у нас есть поле `url`, то мы можем объявить его как тип `HttpUrl` из Pydantic вместо типа `str`:
-## Атрибуты, содержащие списки подмоделей
+{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}
-Вы также можете использовать модели Pydantic в качестве типов вложенных в `list`, `set` и т.д:
+Строка будет проверена на соответствие допустимому URL-адресу и задокументирована в JSON Schema / OpenAPI как таковая.
-=== "Python 3.10+"
+## Атрибуты, содержащие списки подмоделей { #attributes-with-lists-of-submodels }
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
- ```
+Вы также можете использовать модели Pydantic в качестве подтипов для `list`, `set` и т.д.:
-=== "Python 3.9+"
+{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006.py!}
- ```
-
-Такая реализация будет ожидать (конвертировать, валидировать, документировать и т.д) JSON-содержимое в следующем формате:
+Такая реализация будет ожидать (конвертировать, валидировать, документировать и т.д.) JSON-содержимое в следующем формате:
```JSON hl_lines="11"
{
@@ -264,43 +135,27 @@ my_list: List[str]
}
```
-!!! info "Информация"
- Заметьте, что теперь у ключа `images` есть список объектов изображений.
-
-## Глубоко вложенные модели
-
-Вы можете определять модели с произвольным уровнем вложенности:
-
-=== "Python 3.10+"
+/// info | Информация
- ```Python hl_lines="7 12 18 21 25"
- {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
- ```
+Заметьте, что теперь у ключа `images` есть список объектов изображений.
-=== "Python 3.9+"
+///
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
- ```
+## Глубоко вложенные модели { #deeply-nested-models }
-=== "Python 3.6+"
+Вы можете определять модели с произвольным уровнем вложенности:
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}
-!!! info "Информация"
- Заметьте, что у объекта `Offer` есть список объектов `Item`, которые, в свою очередь, могут содержать необязательный список объектов `Image`
+/// info | Информация
-## Тела с чистыми списками элементов
+Заметьте, что у объекта `Offer` есть список объектов `Item`, которые, в свою очередь, могут содержать необязательный список объектов `Image`
-Если верхний уровень значения тела JSON-объекта представляет собой JSON `array` (в Python - `list`), вы можете объявить тип в параметре функции, так же, как в моделях Pydantic:
+///
-```Python
-images: List[Image]
-```
+## Тела с чистыми списками элементов { #bodies-of-pure-lists }
-в Python 3.9 и выше:
+Если верхний уровень значения тела JSON-объекта представляет собой JSON `array` (в Python — `list`), вы можете объявить тип в параметре функции, так же как в моделях Pydantic:
```Python
images: list[Image]
@@ -308,74 +163,57 @@ images: list[Image]
например так:
-=== "Python 3.9+"
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
-=== "Python 3.6+"
+## Поддержка редактора кода везде { #editor-support-everywhere }
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_nested_models/tutorial008.py!}
- ```
-
-## Универсальная поддержка редактора
-
-И вы получаете поддержку редактора везде.
+И вы получаете поддержку редактора кода везде.
Даже для элементов внутри списков:
-Вы не могли бы получить такую поддержку редактора, если бы работали напрямую с `dict`, а не с моделями Pydantic.
+Вы не могли бы получить такую поддержку редактора кода, если бы работали напрямую с `dict`, а не с моделями Pydantic.
Но вы также не должны беспокоиться об этом, входящие словари автоматически конвертируются, а ваш вывод также автоматически преобразуется в формат JSON.
-## Тела запросов с произвольными словарями (`dict` )
+## Тела запросов с произвольными словарями (`dict`) { #bodies-of-arbitrary-dicts }
-Вы также можете объявить тело запроса как `dict` с ключами определенного типа и значениями другого типа данных.
+Вы также можете объявить тело запроса как `dict` с ключами определённого типа и значениями другого типа.
Без необходимости знать заранее, какие значения являются допустимыми для имён полей/атрибутов (как это было бы в случае с моделями Pydantic).
-Это было бы полезно, если вы хотите получить ключи, которые вы еще не знаете.
+Это было бы полезно, если вы хотите получить ключи, которые вы ещё не знаете.
---
-Другой полезный случай - когда вы хотите чтобы ключи были другого типа данных, например, `int`.
+Другой полезный случай — когда вы хотите, чтобы ключи были другого типа данных, например, `int`.
Именно это мы сейчас и увидим здесь.
-В этом случае вы принимаете `dict`, пока у него есть ключи типа `int` со значениями типа `float`:
-
-=== "Python 3.9+"
+В этом случае вы принимаете любой `dict`, пока у него есть ключи типа `int` со значениями типа `float`:
- ```Python hl_lines="7"
- {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
-=== "Python 3.6+"
+/// tip | Совет
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
- ```
+Имейте в виду, что JSON поддерживает только ключи типа `str`.
-!!! tip "Совет"
- Имейте в виду, что JSON поддерживает только ключи типа `str`.
+Но Pydantic обеспечивает автоматическое преобразование данных.
- Но Pydantic обеспечивает автоматическое преобразование данных.
+Это значит, что даже если клиенты вашего API могут отправлять только строки в качестве ключей, при условии, что эти строки содержат целые числа, Pydantic автоматически преобразует и валидирует эти данные.
- Это значит, что даже если пользователи вашего API могут отправлять только строки в качестве ключей, при условии, что эти строки содержат целые числа, Pydantic автоматический преобразует и валидирует эти данные.
+А `dict`, который вы получите как `weights`, действительно будет иметь ключи типа `int` и значения типа `float`.
- А `dict`, с именем `weights`, который вы получите в качестве ответа Pydantic, действительно будет иметь ключи типа `int` и значения типа `float`.
+///
-## Резюме
+## Резюме { #recap }
С помощью **FastAPI** вы получаете максимальную гибкость, предоставляемую моделями Pydantic, сохраняя при этом простоту, краткость и элегантность вашего кода.
И дополнительно вы получаете:
-* Поддержку редактора (автодополнение доступно везде!)
+* Поддержку редактора кода (автозавершение доступно везде!)
* Преобразование данных (также известно как парсинг / сериализация)
* Валидацию данных
* Документацию схемы данных
diff --git a/docs/ru/docs/tutorial/body-updates.md b/docs/ru/docs/tutorial/body-updates.md
new file mode 100644
index 0000000000000..7d970a7a93afd
--- /dev/null
+++ b/docs/ru/docs/tutorial/body-updates.md
@@ -0,0 +1,100 @@
+# Тело запроса - Обновления { #body-updates }
+
+## Обновление с заменой при помощи `PUT` { #update-replacing-with-put }
+
+Чтобы обновить элемент, вы можете использовать операцию [HTTP `PUT`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT).
+
+Вы можете использовать `jsonable_encoder`, чтобы преобразовать входные данные в данные, которые можно сохранить как JSON (например, в NoSQL-базе данных). Например, преобразование `datetime` в `str`.
+
+{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}
+
+`PUT` используется для получения данных, которые должны заменить существующие данные.
+
+### Предупреждение о замене { #warning-about-replacing }
+
+Это означает, что если вы хотите обновить элемент `bar`, используя `PUT` с телом, содержащим:
+
+```Python
+{
+ "name": "Barz",
+ "price": 3,
+ "description": None,
+}
+```
+
+поскольку оно не включает уже сохраненный атрибут `"tax": 20.2`, входная модель примет значение по умолчанию `"tax": 10.5`.
+
+И данные будут сохранены с этим «новым» `tax`, равным `10.5`.
+
+## Частичное обновление с помощью `PATCH` { #partial-updates-with-patch }
+
+Также можно использовать операцию [HTTP `PATCH`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) для частичного обновления данных.
+
+Это означает, что можно передавать только те данные, которые необходимо обновить, оставляя остальные нетронутыми.
+
+/// note | Примечание
+
+`PATCH` менее распространен и известен, чем `PUT`.
+
+А многие команды используют только `PUT`, даже для частичного обновления.
+
+Вы можете **свободно** использовать их как угодно, **FastAPI** не накладывает никаких ограничений.
+
+Но в данном руководстве более или менее понятно, как они должны использоваться.
+
+///
+
+### Использование параметра `exclude_unset` в Pydantic { #using-pydantics-exclude-unset-parameter }
+
+Если вы хотите получать частичные обновления, очень полезно использовать параметр `exclude_unset` в `.model_dump()` модели Pydantic.
+
+Например, `item.model_dump(exclude_unset=True)`.
+
+В результате будет сгенерирован `dict`, содержащий только те данные, которые были заданы при создании модели `item`, без учета значений по умолчанию.
+
+Затем вы можете использовать это для создания `dict` только с теми данными, которые были установлены (отправлены в запросе), опуская значения по умолчанию:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}
+
+### Использование параметра `update` в Pydantic { #using-pydantics-update-parameter }
+
+Теперь можно создать копию существующей модели, используя `.model_copy()`, и передать параметр `update` с `dict`, содержащим данные для обновления.
+
+Например, `stored_item_model.model_copy(update=update_data)`:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}
+
+### Кратко о частичном обновлении { #partial-updates-recap }
+
+В целом, для применения частичных обновлений необходимо:
+
+* (Опционально) использовать `PATCH` вместо `PUT`.
+* Извлечь сохранённые данные.
+* Поместить эти данные в Pydantic-модель.
+* Сгенерировать `dict` без значений по умолчанию из входной модели (с использованием `exclude_unset`).
+ * Таким образом, можно обновлять только те значения, которые действительно установлены пользователем, вместо того чтобы переопределять уже сохраненные значения значениями по умолчанию из вашей модели.
+* Создать копию хранимой модели, обновив ее атрибуты полученными частичными обновлениями (с помощью параметра `update`).
+* Преобразовать скопированную модель в то, что может быть сохранено в вашей БД (например, с помощью `jsonable_encoder`).
+ * Это сравнимо с повторным использованием метода модели `.model_dump()`, но при этом происходит проверка (и преобразование) значений в типы данных, которые могут быть преобразованы в JSON, например, `datetime` в `str`.
+* Сохранить данные в своей БД.
+* Вернуть обновленную модель.
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *}
+
+/// tip | Подсказка
+
+На самом деле эту же технику можно использовать и для операции HTTP `PUT`.
+
+Но в приведенном примере используется `PATCH`, поскольку он был создан именно для таких случаев использования.
+
+///
+
+/// note | Примечание
+
+Обратите внимание, что входная модель по-прежнему валидируется.
+
+Таким образом, если вы хотите получать частичные обновления, в которых могут быть опущены все атрибуты, вам необходимо иметь модель, в которой все атрибуты помечены как необязательные (со значениями по умолчанию или `None`).
+
+Чтобы отличить модели со всеми необязательными значениями для обновления и модели с обязательными значениями для создания, можно воспользоваться идеями, описанными в [Дополнительные модели](extra-models.md).
+
+///
diff --git a/docs/ru/docs/tutorial/body.md b/docs/ru/docs/tutorial/body.md
index c03d40c3fb34e..8a67c8f51e0bd 100644
--- a/docs/ru/docs/tutorial/body.md
+++ b/docs/ru/docs/tutorial/body.md
@@ -1,41 +1,41 @@
-# Тело запроса
+# Тело запроса { #request-body }
-Когда вам необходимо отправить данные из клиента (допустим, браузера) в ваш API, вы отправляете их как **тело запроса**.
+Когда вам необходимо отправить данные из клиента (например, браузера) в ваш API, вы отправляете их как **тело запроса**.
-Тело **запроса** --- это данные, отправляемые клиентом в ваш API. Тело **ответа** --- это данные, которые ваш API отправляет клиенту.
+Тело **запроса** — это данные, отправляемые клиентом в ваш API. Тело **ответа** — это данные, которые ваш API отправляет клиенту.
-Ваш API почти всегда отправляет тело **ответа**. Но клиентам не обязательно всегда отправлять тело **запроса**.
+Ваш API почти всегда должен отправлять тело **ответа**. Но клиентам не обязательно всегда отправлять **тело запроса**: иногда они запрашивают только путь, возможно с некоторыми параметрами запроса, но без тела.
-Чтобы объявить тело **запроса**, необходимо использовать модели Pydantic, со всей их мощью и преимуществами.
+Чтобы объявить тело **запроса**, используйте модели [Pydantic](https://docs.pydantic.dev/), со всей их мощью и преимуществами.
-!!! info "Информация"
- Чтобы отправить данные, необходимо использовать один из методов: `POST` (обычно), `PUT`, `DELETE` или `PATCH`.
+/// info | Информация
- Отправка тела с запросом `GET` имеет неопределенное поведение в спецификациях, тем не менее, оно поддерживается FastAPI только для очень сложных/экстремальных случаев использования.
+Чтобы отправить данные, используйте один из методов: `POST` (чаще всего), `PUT`, `DELETE` или `PATCH`.
- Поскольку это не рекомендуется, интерактивная документация со Swagger UI не будет отображать информацию для тела при использовании метода GET, а промежуточные прокси-серверы могут не поддерживать такой вариант запроса.
+Отправка тела с запросом `GET` имеет неопределённое поведение в спецификациях, тем не менее это поддерживается FastAPI, но только для очень сложных/крайних случаев использования.
-## Импортирование `BaseModel` из Pydantic
+Поскольку это не рекомендуется, интерактивная документация со Swagger UI не будет отображать информацию для тела при использовании `GET`, а промежуточные прокси-серверы могут не поддерживать такой вариант запроса.
-Первое, что вам необходимо сделать, это импортировать `BaseModel` из пакета `pydantic`:
+///
-```Python hl_lines="4"
-{!../../../docs_src/body/tutorial001.py!}
-```
+## Импортируйте `BaseModel` из Pydantic { #import-pydantics-basemodel }
-## Создание вашей собственной модели
+Первое, что нужно сделать, — импортировать `BaseModel` из пакета `pydantic`:
-После этого вы описываете вашу модель данных как класс, наследующий от `BaseModel`.
+{* ../../docs_src/body/tutorial001_py310.py hl[2] *}
-Используйте аннотации типов Python для всех атрибутов:
+## Создайте модель данных { #create-your-data-model }
-```Python hl_lines="7-11"
-{!../../../docs_src/body/tutorial001.py!}
-```
+Затем опишите свою модель данных как класс, наследующийся от `BaseModel`.
+
+Используйте стандартные типы Python для всех атрибутов:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}
-Также как и при описании параметров запроса, когда атрибут модели имеет значение по умолчанию, он является необязательным. Иначе он обязателен. Используйте `None`, чтобы сделать его необязательным без использования конкретных значений по умолчанию.
-Например, модель выше описывает вот такой JSON "объект" (или словарь Python):
+Так же, как при объявлении параметров запроса: когда атрибут модели имеет значение по умолчанию, он не обязателен. Иначе он обязателен. Используйте `None`, чтобы сделать его просто необязательным.
+
+Например, модель выше описывает такой JSON "`object`" (или Python `dict`):
```JSON
{
@@ -46,7 +46,7 @@
}
```
-...поскольку `description` и `tax` являются необязательными (с `None` в качестве значения по умолчанию), вот такой JSON "объект" также подходит:
+...так как `description` и `tax` являются необязательными (со значением по умолчанию `None`), такой JSON "`object`" тоже будет корректным:
```JSON
{
@@ -55,111 +55,112 @@
}
```
-## Объявление как параметра функции
+## Объявите её как параметр { #declare-it-as-a-parameter }
-Чтобы добавить параметр к вашему *обработчику*, объявите его также, как вы объявляли параметры пути или параметры запроса:
+Чтобы добавить её в вашу *операцию пути*, объявите её так же, как вы объявляли параметры пути и параметры запроса:
-```Python hl_lines="18"
-{!../../../docs_src/body/tutorial001.py!}
-```
+{* ../../docs_src/body/tutorial001_py310.py hl[16] *}
-...и укажите созданную модель в качестве типа параметра, `Item`.
+...и укажите тип параметра как созданную вами модель, `Item`.
-## Результаты
+## Результаты { #results }
-Всего лишь с помощью аннотации типов Python, **FastAPI**:
+Всего лишь с этой аннотацией типов Python **FastAPI**:
-* Читает тело запроса как JSON.
-* Приводит к соответствующим типам (если есть необходимость).
-* Проверяет корректность данных.
- * Если данные некорректны, будет возращена читаемая и понятная ошибка, показывающая что именно и в каком месте некорректно в данных.
-* Складывает полученные данные в параметр `item`.
- * Поскольку внутри функции вы объявили его с типом `Item`, то теперь у вас есть поддержка со стороны редактора (автодополнение и т.п.) для всех атрибутов и их типов.
-* Генерирует декларативное описание модели в виде JSON Schema, так что вы можете его использовать где угодно, если это имеет значение для вашего проекта.
-* Эти схемы являются частью сгенерированной схемы OpenAPI и используются для автоматического документирования UI.
+* Считает тело запроса как JSON.
+* Приведёт данные к соответствующим типам (если потребуется).
+* Проведёт валидацию данных.
+ * Если данные некорректны, вернёт понятную и наглядную ошибку, указывающую, где именно и что было некорректно.
+* Передаст полученные данные в параметр `item`.
+ * Поскольку внутри функции вы объявили его с типом `Item`, у вас будет поддержка со стороны редактора кода (автозавершение и т.п.) для всех атрибутов и их типов.
+* Сгенерирует определения [JSON Schema](https://json-schema.org) для вашей модели; вы можете использовать их и в других местах, если это имеет смысл для вашего проекта.
+* Эти схемы будут частью сгенерированной схемы OpenAPI и будут использоваться автоматической документацией UIs.
-## Автоматическое документирование
+## Автоматическая документация { #automatic-docs }
-Схема JSON ваших моделей будет частью сгенерированной схемы OpenAPI и будет отображена в интерактивной документации API:
+JSON Schema ваших моделей будет частью сгенерированной схемы OpenAPI и будет отображаться в интерактивной документации API:
-Также она будет указана в документации по API внутри каждой *операции пути*, в которой используются:
+А также они будут использоваться в документации API внутри каждой *операции пути*, где это требуется:
-## Поддержка редактора
+## Поддержка редактора кода { #editor-support }
-В вашем редакторе внутри вашей функции у вас будут подсказки по типам и автодополнение (это не будет работать, если вы получаете словарь вместо модели Pydantic):
+В вашем редакторе кода внутри функции вы получите подсказки по типам и автозавершение повсюду (этого бы не было, если бы вы получали `dict` вместо модели Pydantic):
-Также вы будете получать ошибки в случае несоответствия типов:
+Также вы получите проверку ошибок при некорректных операциях с типами:
-Это не случайно, весь фреймворк построен вокруг такого дизайна.
+Это не случайность — весь фреймворк построен вокруг такого дизайна.
-И это все тщательно протестировано еще на этапе разработки дизайна, до реализации, чтобы это работало со всеми редакторами.
+И это было тщательно протестировано ещё на этапе проектирования, до реализации, чтобы убедиться, что всё будет работать со всеми редакторами.
-Для поддержки этого даже были внесены некоторые изменения в сам Pydantic.
+В сам Pydantic даже были внесены некоторые изменения для поддержки этого.
-На всех предыдущих скриншотах используется Visual Studio Code.
+Предыдущие скриншоты сделаны в [Visual Studio Code](https://code.visualstudio.com).
-Но у вас будет такая же поддержка и с PyCharm, и вообще с любым редактором Python:
+Но вы получите такую же поддержку редактора кода в [PyCharm](https://www.jetbrains.com/pycharm/) и большинстве других редакторов Python:
-!!! tip "Подсказка"
- Если вы используете PyCharm в качестве редактора, то вам стоит попробовать плагин Pydantic PyCharm Plugin.
+/// tip | Совет
+
+Если вы используете [PyCharm](https://www.jetbrains.com/pycharm/) в качестве редактора кода, вы можете использовать плагин [Pydantic PyCharm Plugin](https://github.com/koxudaxi/pydantic-pycharm-plugin/).
+
+Он улучшает поддержку моделей Pydantic в редакторе кода, включая:
- Он улучшает поддержку редактором моделей Pydantic в части:
+* автозавершение
+* проверки типов
+* рефакторинг
+* поиск
+* инспекции
- * автодополнения,
- * проверки типов,
- * рефакторинга,
- * поиска,
- * инспектирования.
+///
-## Использование модели
+## Использование модели { #use-the-model }
Внутри функции вам доступны все атрибуты объекта модели напрямую:
-```Python hl_lines="21"
-{!../../../docs_src/body/tutorial002.py!}
-```
+{* ../../docs_src/body/tutorial002_py310.py *}
-## Тело запроса + параметры пути
+## Тело запроса + параметры пути { #request-body-path-parameters }
-Вы можете одновременно объявлять параметры пути и тело запроса.
+Вы можете одновременно объявить параметры пути и тело запроса.
-**FastAPI** распознает, какие параметры функции соответствуют параметрам пути и должны быть **получены из пути**, а какие параметры функции, объявленные как модели Pydantic, должны быть **получены из тела запроса**.
+**FastAPI** распознает, что параметры функции, соответствующие параметрам пути, должны быть **получены из пути**, а параметры функции, объявленные как модели Pydantic, должны быть **получены из тела запроса**.
-```Python hl_lines="17-18"
-{!../../../docs_src/body/tutorial003.py!}
-```
+{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}
-## Тело запроса + параметры пути + параметры запроса
-Вы также можете одновременно объявить параметры для **пути**, **запроса** и **тела запроса**.
+## Тело запроса + параметры пути + параметры запроса { #request-body-path-query-parameters }
-**FastAPI** распознает каждый из них и возьмет данные из правильного источника.
+Вы также можете одновременно объявить параметры **тела**, **пути** и **запроса**.
-```Python hl_lines="18"
-{!../../../docs_src/body/tutorial004.py!}
-```
+**FastAPI** распознает каждый из них и возьмёт данные из правильного источника.
+
+{* ../../docs_src/body/tutorial004_py310.py hl[16] *}
+
+Параметры функции будут распознаны следующим образом:
+
+* Если параметр также объявлен в **пути**, он будет использоваться как path-параметр.
+* Если параметр имеет **скалярный тип** (например, `int`, `float`, `str`, `bool` и т.п.), он будет интерпретирован как параметр **запроса**.
+* Если параметр объявлен как тип **модели Pydantic**, он будет интерпретирован как **тело** запроса.
+
+/// note | Заметка
-Параметры функции распознаются следующим образом:
+FastAPI понимает, что значение `q` не является обязательным из-за значения по умолчанию `= None`.
-* Если параметр также указан в **пути**, то он будет использоваться как параметр пути.
-* Если аннотация типа параметра содержит **примитивный тип** (`int`, `float`, `str`, `bool` и т.п.), он будет интерпретирован как параметр **запроса**.
-* Если аннотация типа параметра представляет собой **модель Pydantic**, он будет интерпретирован как параметр **тела запроса**.
+Аннотация типов `str | None` не используется FastAPI для определения обязательности; он узнает, что параметр не обязателен, потому что у него есть значение по умолчанию `= None`.
-!!! note "Заметка"
- FastAPI понимает, что значение параметра `q` не является обязательным, потому что имеет значение по умолчанию `= None`.
+Но добавление аннотаций типов позволит вашему редактору кода лучше вас поддерживать и обнаруживать ошибки.
- Аннотация `Optional` в `Optional[str]` не используется FastAPI, но помогает вашему редактору лучше понимать ваш код и обнаруживать ошибки.
+///
-## Без Pydantic
+## Без Pydantic { #without-pydantic }
-Если вы не хотите использовать модели Pydantic, вы все еще можете использовать параметры **тела запроса**. Читайте в документации раздел [Тело - Несколько параметров: Единичные значения в теле](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}.
+Если вы не хотите использовать модели Pydantic, вы также можете использовать параметры **Body**. См. раздел документации [Тело запроса - Несколько параметров: Единичные значения в теле](body-multiple-params.md#singular-values-in-body).
diff --git a/docs/ru/docs/tutorial/cookie-param-models.md b/docs/ru/docs/tutorial/cookie-param-models.md
new file mode 100644
index 0000000000000..9b34cf0300638
--- /dev/null
+++ b/docs/ru/docs/tutorial/cookie-param-models.md
@@ -0,0 +1,76 @@
+# Модели параметров cookie { #cookie-parameter-models }
+
+Если у вас есть группа **cookies**, которые связаны между собой, вы можете создать **Pydantic-модель** для их объявления. 🍪
+
+Это позволит вам **переиспользовать модель** в **разных местах**, а также объявить проверки и метаданные сразу для всех параметров. 😎
+
+/// note | Заметка
+
+Этот функционал доступен с версии `0.115.0`. 🤓
+
+///
+
+/// tip | Совет
+
+Такой же подход применяется для `Query`, `Cookie`, и `Header`. 😎
+
+///
+
+## Pydantic-модель для cookies { #cookies-with-a-pydantic-model }
+
+Объявите параметры **cookie**, которые вам нужны, в **Pydantic-модели**, а затем объявите параметр как `Cookie`:
+
+{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}
+
+**FastAPI** **извлечёт** данные для **каждого поля** из **cookies**, полученных в запросе, и выдаст вам объявленную Pydantic-модель.
+
+## Проверка сгенерированной документации { #check-the-docs }
+
+Вы можете посмотреть объявленные cookies в графическом интерфейсе Документации по пути `/docs`:
+
+
+
+
+## Сокращение { #shortcut }
+
+Но вы видите, что здесь мы имеем некоторое повторение кода, дважды написав `CommonQueryParams`:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | Подсказка
+
+Рекомендуется использовать версию с `Annotated`, если возможно.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+**FastAPI** предоставляет сокращение для таких случаев, когда зависимость — это *конкретный* класс, который **FastAPI** будет «вызывать» для создания экземпляра этого класса.
+
+Для этих конкретных случаев вы можете сделать следующее.
+
+Вместо того чтобы писать:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | Подсказка
+
+Рекомендуется использовать версию с `Annotated`, если возможно.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+...следует написать:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | Подсказка
+
+Рекомендуется использовать версию с `Annotated`, если возможно.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
+
+Вы объявляете зависимость как тип параметра и используете `Depends()` без какого-либо параметра, вместо того чтобы *снова* писать полный класс внутри `Depends(CommonQueryParams)`.
+
+Аналогичный пример будет выглядеть следующим образом:
+
+{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *}
+
+...и **FastAPI** будет знать, что делать.
+
+/// tip | Подсказка
+
+Если это покажется вам более запутанным, чем полезным, не обращайте внимания — это вам не *нужно*.
+
+Это просто сокращение. Потому что **FastAPI** заботится о том, чтобы помочь вам свести к минимуму повторение кода.
+
+///
diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
new file mode 100644
index 0000000000000..b4b7ce6314b7a
--- /dev/null
+++ b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -0,0 +1,69 @@
+# Зависимости в декораторах операции пути { #dependencies-in-path-operation-decorators }
+
+В некоторых случаях, возвращаемое значение зависимости не используется внутри *функции операции пути*.
+
+Или же зависимость не возвращает никакого значения.
+
+Но вам всё-таки нужно, чтобы она выполнилась.
+
+Для таких ситуаций, вместо объявления *функции операции пути* с параметром `Depends`, вы можете добавить список зависимостей `dependencies` в *декоратор операции пути*.
+
+## Добавление `dependencies` (зависимостей) в *декоратор операции пути* { #add-dependencies-to-the-path-operation-decorator }
+
+*Декоратор операции пути* получает необязательный аргумент `dependencies`.
+
+Это должен быть `list` состоящий из `Depends()`:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
+
+Зависимости из dependencies выполнятся так же, как и обычные зависимости. Но их значения (если они были) не будут переданы в *функцию операции пути*.
+
+/// tip | Подсказка
+
+Некоторые редакторы кода определяют неиспользуемые параметры функций и подсвечивают их как ошибку.
+
+Использование `dependencies` в *декораторе операции пути* гарантирует выполнение зависимостей, избегая при этом предупреждений редактора кода и других инструментов.
+
+Это также должно помочь предотвратить путаницу у начинающих разработчиков, которые видят неиспользуемые параметры в коде и могут подумать что в них нет необходимости.
+
+///
+
+/// info | Примечание
+
+В этом примере мы используем выдуманные пользовательские HTTP-заголовки `X-Key` и `X-Token`.
+
+Но в реальных проектах, при внедрении системы безопасности, вы получите больше пользы используя интегрированные [средства защиты (следующая глава)](../security/index.md).
+
+///
+
+## Ошибки в зависимостях и возвращаемые значения { #dependencies-errors-and-return-values }
+
+Вы можете использовать те же *функции* зависимостей, что и обычно.
+
+### Требования к зависимостям { #dependency-requirements }
+
+Они могут объявлять требования к запросу (например HTTP-заголовки) или другие подзависимости:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
+
+### Вызов исключений { #raise-exceptions }
+
+Зависимости из dependencies могут вызывать исключения с помощью `raise`, как и обычные зависимости:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
+
+### Возвращаемые значения { #return-values }
+
+И они могут возвращать значения или нет, эти значения использоваться не будут.
+
+Таким образом, вы можете переиспользовать обычную зависимость (возвращающую значение), которую вы уже используете где-то в другом месте, и хотя значение не будет использоваться, зависимость будет выполнена:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
+
+## Зависимости для группы *операций путей* { #dependencies-for-a-group-of-path-operations }
+
+Позже, читая о том как структурировать большие приложения ([Большие приложения — несколько файлов](../../tutorial/bigger-applications.md)), возможно, многофайловые, вы узнаете как объявить единый параметр `dependencies` для всей группы *операций путей*.
+
+## Глобальные Зависимости { #global-dependencies }
+
+Далее мы увидим, как можно добавить dependencies для всего `FastAPI` приложения, так чтобы они применялись к каждой *операции пути*.
diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md
new file mode 100644
index 0000000000000..04c2c2da42e77
--- /dev/null
+++ b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -0,0 +1,289 @@
+# Зависимости с yield { #dependencies-with-yield }
+
+FastAPI поддерживает зависимости, которые выполняют некоторые дополнительные шаги после завершения.
+
+Для этого используйте `yield` вместо `return`, а дополнительные шаги (код) напишите после него.
+
+/// tip | Подсказка
+
+Убедитесь, что используете `yield` только один раз на одну зависимость.
+
+///
+
+/// note | Технические детали
+
+Любая функция, с которой можно корректно использовать:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) или
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+будет корректной для использования в качестве зависимости **FastAPI**.
+
+На самом деле, FastAPI использует эти два декоратора внутренне.
+
+///
+
+## Зависимость базы данных с помощью `yield` { #a-database-dependency-with-yield }
+
+Например, с его помощью можно создать сессию работы с базой данных и закрыть её после завершения.
+
+Перед созданием ответа будет выполнен только код до и включая оператор `yield`:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
+
+Значение, полученное из `yield`, внедряется в *операции пути* и другие зависимости:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
+
+Код, следующий за оператором `yield`, выполняется после ответа:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
+
+/// tip | Подсказка
+
+Можно использовать как `async`, так и обычные функции.
+
+**FastAPI** корректно обработает каждый вариант, так же как и с обычными зависимостями.
+
+///
+
+## Зависимость с `yield` и `try` { #a-dependency-with-yield-and-try }
+
+Если использовать блок `try` в зависимости с `yield`, то вы получите любое исключение, которое было выброшено при использовании зависимости.
+
+Например, если какой-то код в какой-то момент в середине, в другой зависимости или в *операции пути*, сделал "откат" транзакции базы данных или создал любую другую ошибку, то вы получите это исключение в своей зависимости.
+
+Таким образом, можно искать конкретное исключение внутри зависимости с помощью `except SomeException`.
+
+Точно так же можно использовать `finally`, чтобы убедиться, что обязательные шаги при выходе выполнены независимо от того, было ли исключение или нет.
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
+
+## Подзависимости с `yield` { #sub-dependencies-with-yield }
+
+Вы можете иметь подзависимости и "деревья" подзависимостей любого размера и формы, и любая из них или все они могут использовать `yield`.
+
+**FastAPI** проследит за тем, чтобы «код выхода» в каждой зависимости с `yield` выполнялся в правильном порядке.
+
+Например, `dependency_c` может зависеть от `dependency_b`, а `dependency_b` — от `dependency_a`:
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
+
+И все они могут использовать `yield`.
+
+В этом случае `dependency_c` для выполнения своего кода выхода нуждается в том, чтобы значение из `dependency_b` (здесь `dep_b`) всё ещё было доступно.
+
+И, в свою очередь, `dependency_b` нуждается в том, чтобы значение из `dependency_a` (здесь `dep_a`) было доступно для её кода выхода.
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
+
+Точно так же можно иметь часть зависимостей с `yield`, часть — с `return`, и какие-то из них могут зависеть друг от друга.
+
+Либо у вас может быть одна зависимость, которая требует несколько других зависимостей с `yield` и т.д.
+
+Комбинации зависимостей могут быть какими угодно.
+
+**FastAPI** проследит за тем, чтобы всё выполнялось в правильном порядке.
+
+/// note | Технические детали
+
+Это работает благодаря [менеджерам контекста](https://docs.python.org/3/library/contextlib.html) в Python.
+
+**FastAPI** использует их внутренне для достижения этого.
+
+///
+
+## Зависимости с `yield` и `HTTPException` { #dependencies-with-yield-and-httpexception }
+
+Вы видели, что можно использовать зависимости с `yield` и иметь блоки `try`, которые пытаются выполнить некоторый код, а затем запускают код выхода в `finally`.
+
+Также вы можете использовать `except`, чтобы поймать вызванное исключение и что-то с ним сделать.
+
+Например, вы можете вызвать другое исключение, например `HTTPException`.
+
+/// tip | Подсказка
+
+Это довольно продвинутая техника, и в большинстве случаев она вам не понадобится, так как вы можете вызывать исключения (включая `HTTPException`) в остальном коде вашего приложения, например, в *функции-обработчике пути*.
+
+Но если понадобится — возможность есть. 🤓
+
+///
+
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
+
+Если вы хотите перехватывать исключения и формировать на их основе пользовательский ответ, создайте [Пользовательский обработчик исключений](../handling-errors.md#install-custom-exception-handlers).
+
+## Зависимости с `yield` и `except` { #dependencies-with-yield-and-except }
+
+Если вы ловите исключение с помощью `except` в зависимости с `yield` и не вызываете его снова (или не вызываете новое исключение), FastAPI не сможет заметить, что было исключение — так же, как это происходит в обычном Python:
+
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
+
+В этом случае клиент получит *HTTP 500 Internal Server Error*, как и должно быть, поскольку мы не вызываем `HTTPException` или что-то подобное, но на сервере **не будет никаких логов** или других указаний на то, какая была ошибка. 😱
+
+### Всегда делайте `raise` в зависимостях с `yield` и `except` { #always-raise-in-dependencies-with-yield-and-except }
+
+Если вы ловите исключение в зависимости с `yield`, то, если вы не вызываете другой `HTTPException` или что-то подобное, вам следует повторно вызвать исходное исключение.
+
+Вы можете повторно вызвать то же самое исключение с помощью `raise`:
+
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
+
+Теперь клиент получит тот же *HTTP 500 Internal Server Error*, но на сервере в логах будет наше пользовательское `InternalError`. 😎
+
+## Выполнение зависимостей с `yield` { #execution-of-dependencies-with-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,operation: Can raise exceptions, including HTTPException
+ client ->> dep: Start request
+ Note over dep: Run code up to yield
+ opt raise Exception
+ dep -->> handler: Raise Exception
+ handler -->> client: HTTP error response
+ end
+ dep ->> operation: Run dependency, e.g. DB session
+ opt raise
+ operation -->> dep: Raise Exception (e.g. HTTPException)
+ opt handle
+ dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception
+ end
+ handler -->> client: HTTP error response
+ 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 -->> tasks: Handle exceptions in the background task code
+ end
+```
+
+/// info | Дополнительная информация
+
+Клиенту будет отправлен только **один ответ**. Это может быть один из ответов об ошибке или ответ от *операции пути*.
+
+После отправки одного из этих ответов никакой другой ответ отправить нельзя.
+
+///
+
+/// tip | Подсказка
+
+Если вы вызовете какое-либо исключение в коде из *функции-обработчика пути*, оно будет передано зависимостям с `yield`, включая `HTTPException`. В большинстве случаев вы захотите повторно вызвать то же самое исключение или новое из зависимости с `yield`, чтобы убедиться, что оно корректно обработано.
+
+///
+
+## Ранний выход и `scope` { #early-exit-and-scope }
+
+Обычно «код выхода» зависимостей с `yield` выполняется **после того, как ответ** отправлен клиенту.
+
+Но если вы знаете, что не будете использовать зависимость после возврата из *функции-обработчика пути*, вы можете использовать `Depends(scope="function")`, чтобы сообщить FastAPI, что он должен закрыть зависимость после возврата из *функции-обработчика пути*, но **до того**, как **ответ будет отправлен**.
+
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
+
+`Depends()` принимает параметр `scope`, который может быть:
+
+* `"function"`: начать зависимость до *функции-обработчика пути*, которая обрабатывает запрос, завершить зависимость после окончания *функции-обработчика пути*, но **до того**, как ответ будет отправлен обратно клиенту. То есть функция зависимости будет выполнена **вокруг** *функции-обработчика пути*.
+* `"request"`: начать зависимость до *функции-обработчика пути*, которая обрабатывает запрос (как и при использовании `"function"`), но завершить **после** того, как ответ будет отправлен обратно клиенту. То есть функция зависимости будет выполнена **вокруг** цикла запроса (**request**) и ответа.
+
+Если не указано и в зависимости есть `yield`, по умолчанию будет `scope` со значением `"request"`.
+
+### `scope` для подзависимостей { #scope-for-sub-dependencies }
+
+Когда вы объявляете зависимость с `scope="request"` (значение по умолчанию), любая подзависимость также должна иметь `scope` равный `"request"`.
+
+Но зависимость со `scope` равным `"function"` может иметь зависимости со `scope` `"function"` и со `scope` `"request"`.
+
+Это потому, что любая зависимость должна иметь возможность выполнить свой код выхода раньше подзависимостей, так как ей может понадобиться использовать их во время своего кода выхода.
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant dep_req as Зависимость scope="request"
+participant dep_func as Зависимость scope="function"
+participant operation as Функция-обработчик пути
+
+ client ->> dep_req: Запрос
+ Note over dep_req: Выполнить код до yield
+ dep_req ->> dep_func: Передать значение
+ Note over dep_func: Выполнить код до yield
+ dep_func ->> operation: Выполнить функцию-обработчик пути
+ operation ->> dep_func: Выход из функции-обработчика пути
+ Note over dep_func: Выполнить код после yield
+ Note over dep_func: ✅ Зависимость закрыта
+ dep_func ->> client: Отправить ответ клиенту
+ Note over client: Ответ отправлен
+ Note over dep_req: Выполнить код после yield
+ Note over dep_req: ✅ Зависимость закрыта
+```
+
+## Зависимости с `yield`, `HTTPException`, `except` и фоновыми задачами { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+Зависимости с `yield` со временем эволюционировали, чтобы покрыть разные сценарии и исправить некоторые проблемы.
+
+Если вы хотите посмотреть, что менялось в разных версиях FastAPI, вы можете прочитать об этом подробнее в продвинутом руководстве: [Продвинутые зависимости — зависимости с `yield`, `HTTPException`, `except` и фоновыми задачами](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks).
+## Контекстные менеджеры { #context-managers }
+
+### Что такое «контекстные менеджеры» { #what-are-context-managers }
+
+«Контекстные менеджеры» — это любые объекты Python, которые можно использовать в операторе `with`.
+
+Например, [можно использовать `with` для чтения файла](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files):
+
+```Python
+with open("./somefile.txt") as f:
+ contents = f.read()
+ print(contents)
+```
+
+Под капотом вызов `open("./somefile.txt")` создаёт объект, называемый «контекстным менеджером».
+
+Когда блок `with` завершается, он обязательно закрывает файл, даже если были исключения.
+
+Когда вы создаёте зависимость с `yield`, **FastAPI** внутренне создаёт для неё менеджер контекста и сочетает его с некоторыми другими связанными инструментами.
+
+### Использование менеджеров контекста в зависимостях с `yield` { #using-context-managers-in-dependencies-with-yield }
+
+/// warning | Внимание
+
+Это, более или менее, «продвинутая» идея.
+
+Если вы только начинаете работать с **FastAPI**, то лучше пока пропустить этот пункт.
+
+///
+
+В Python можно создавать менеджеры контекста, [создав класс с двумя методами: `__enter__()` и `__exit__()`](https://docs.python.org/3/reference/datamodel.html#context-managers).
+
+Их также можно использовать внутри зависимостей **FastAPI** с `yield`, применяя операторы
+`with` или `async with` внутри функции зависимости:
+
+{* ../../docs_src/dependencies/tutorial010_py310.py hl[1:9,13] *}
+
+/// tip | Подсказка
+
+Другой способ создания менеджера контекста — с помощью:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) или
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+оформив ими функцию с одним `yield`.
+
+Именно это **FastAPI** использует внутренне для зависимостей с `yield`.
+
+Но использовать эти декораторы для зависимостей FastAPI не обязательно (и не стоит).
+
+FastAPI сделает это за вас на внутреннем уровне.
+
+///
diff --git a/docs/ru/docs/tutorial/dependencies/global-dependencies.md b/docs/ru/docs/tutorial/dependencies/global-dependencies.md
index 870d42cf54bb3..1563d3e8fe43f 100644
--- a/docs/ru/docs/tutorial/dependencies/global-dependencies.md
+++ b/docs/ru/docs/tutorial/dependencies/global-dependencies.md
@@ -1,34 +1,15 @@
-# Глобальные зависимости
+# Глобальные зависимости { #global-dependencies }
Для некоторых типов приложений может потребоваться добавить зависимости ко всему приложению.
-Подобно тому, как вы можете [добавлять зависимости через параметр `dependencies` в *декораторах операций пути*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, вы можете добавлять зависимости сразу ко всему `FastAPI` приложению.
+Подобно тому, как вы можете [добавлять `dependencies` (зависимости) в *декораторах операций пути*](dependencies-in-path-operation-decorators.md), вы можете добавлять зависимости сразу ко всему `FastAPI` приложению.
В этом случае они будут применяться ко всем *операциям пути* в приложении:
-=== "Python 3.9+"
+{* ../../docs_src/dependencies/tutorial012_an_py310.py hl[17] *}
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!}
- ```
+Все способы [добавления `dependencies` (зависимостей) в *декораторах операций пути*](dependencies-in-path-operation-decorators.md) по-прежнему применимы, но в данном случае зависимости применяются ко всем *операциям пути* приложения.
-=== "Python 3.6+"
+## Зависимости для групп *операций пути* { #dependencies-for-groups-of-path-operations }
- ```Python hl_lines="16"
- {!> ../../../docs_src/dependencies/tutorial012_an.py!}
- ```
-
-=== "Python 3.6 non-Annotated"
-
- !!! tip "Подсказка"
- Рекомендуется использовать 'Annotated' версию, если это возможно.
-
- ```Python hl_lines="15"
- {!> ../../../docs_src/dependencies/tutorial012.py!}
- ```
-
-Все способы [добавления зависимостей в *декораторах операций пути*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} по-прежнему применимы, но в данном случае зависимости применяются ко всем *операциям пути* приложения.
-
-## Зависимости для групп *операций пути*
-
-Позднее, читая о том, как структурировать более крупные [приложения, содержащие много файлов](../../tutorial/bigger-applications.md){.internal-link target=_blank}, вы узнаете, как объявить один параметр dependencies для целой группы *операций пути*.
+Позднее, читая о том, как структурировать более крупные приложения ([Более крупные приложения - несколько файлов](../../tutorial/bigger-applications.md)), возможно, состоящие из нескольких файлов, вы узнаете, как объявить один параметр `dependencies` для целой группы *операций пути*.
diff --git a/docs/ru/docs/tutorial/dependencies/index.md b/docs/ru/docs/tutorial/dependencies/index.md
new file mode 100644
index 0000000000000..4aed035541810
--- /dev/null
+++ b/docs/ru/docs/tutorial/dependencies/index.md
@@ -0,0 +1,250 @@
+# Зависимости { #dependencies }
+
+**FastAPI** имеет очень мощную, но интуитивную систему **Инъекция зависимостей**.
+
+Она спроектирована так, чтобы быть очень простой в использовании и облегчать любому разработчику интеграцию других компонентов с **FastAPI**.
+
+## Что такое инъекция зависимостей («Dependency Injection») { #what-is-dependency-injection }
+
+В программировании **«Dependency Injection»** означает, что у вашего кода (в данном случае у ваших *функций обработки пути*) есть способ объявить вещи, которые требуются для его работы и использования: «зависимости».
+
+И затем эта система (в нашем случае **FastAPI**) позаботится о том, чтобы сделать всё необходимое для предоставления вашему коду этих зависимостей (сделать «инъекцию» зависимостей).
+
+Это очень полезно, когда вам нужно:
+
+* Обеспечить общую логику (один и тот же алгоритм снова и снова).
+* Разделять соединения с базой данных.
+* Обеспечить безопасность, аутентификацию, требования к ролям и т.п.
+* И многое другое...
+
+Всё это при минимизации повторения кода.
+
+## Первые шаги { #first-steps }
+
+Давайте рассмотрим очень простой пример. Он настолько простой, что пока не очень полезен.
+
+Но так мы сможем сосредоточиться на том, как работает система **Dependency Injection**.
+
+### Создайте зависимость, или «dependable» (от чего что-то зависит) { #create-a-dependency-or-dependable }
+
+Сначала сосредоточимся на зависимости.
+
+Это просто функция, которая может принимать те же параметры, что и *функция обработки пути*:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}
+
+И всё.
+
+**2 строки.**
+
+И она имеет ту же форму и структуру, что и все ваши *функции обработки пути*.
+
+Можно думать о ней как о *функции обработки пути* без «декоратора» (без `@app.get("/some-path")`).
+
+И она может возвращать что угодно.
+
+В этом случае эта зависимость ожидает:
+
+* Необязательный query-параметр `q` типа `str`.
+* Необязательный query-параметр `skip` типа `int`, по умолчанию `0`.
+* Необязательный query-параметр `limit` типа `int`, по умолчанию `100`.
+
+А затем просто возвращает `dict`, содержащий эти значения.
+
+/// info | Информация
+
+FastAPI добавил поддержку `Annotated` (и начал рекомендовать его использование) в версии 0.95.0.
+
+Если у вас более старая версия, вы получите ошибки при попытке использовать `Annotated`.
+
+Убедитесь, что вы [обновили версию FastAPI](../../deployment/versions.md#upgrading-the-fastapi-versions) как минимум до 0.95.1, прежде чем использовать `Annotated`.
+
+///
+
+### Импорт `Depends` { #import-depends }
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}
+
+### Объявите зависимость в «зависимом» { #declare-the-dependency-in-the-dependant }
+
+Точно так же, как вы используете `Body`, `Query` и т.д. с параметрами вашей *функции обработки пути*, используйте `Depends` с новым параметром:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}
+
+Хотя вы используете `Depends` в параметрах вашей функции так же, как `Body`, `Query` и т.д., `Depends` работает немного иначе.
+
+В `Depends` вы передаёте только один параметр.
+
+Этот параметр должен быть чем-то вроде функции.
+
+Вы **не вызываете её** напрямую (не добавляйте круглые скобки в конце), просто передаёте её как параметр в `Depends()`.
+
+И эта функция принимает параметры так же, как *функции обработки пути*.
+
+/// tip | Подсказка
+
+В следующей главе вы увидите, какие ещё «вещи», помимо функций, можно использовать в качестве зависимостей.
+
+///
+
+Каждый раз, когда приходит новый запрос, **FastAPI** позаботится о:
+
+* Вызове вашей зависимости («dependable») с корректными параметрами.
+* Получении результата из вашей функции.
+* Присваивании этого результата параметру в вашей *функции обработки пути*.
+
+```mermaid
+graph TB
+
+common_parameters(["common_parameters"])
+read_items["/items/"]
+read_users["/users/"]
+
+common_parameters --> read_items
+common_parameters --> read_users
+```
+
+Таким образом, вы пишете общий код один раз, а **FastAPI** позаботится о его вызове для ваших *операций пути*.
+
+/// check | Проверка
+
+Обратите внимание, что вам не нужно создавать специальный класс и передавать его куда-то в **FastAPI**, чтобы «зарегистрировать» его или что-то подобное.
+
+Вы просто передаёте его в `Depends`, и **FastAPI** знает, что делать дальше.
+
+///
+
+## Использование зависимости с `Annotated` в нескольких местах { #share-annotated-dependencies }
+
+В приведённых выше примерах есть небольшое **повторение кода**.
+
+Когда вам нужно использовать зависимость `common_parameters()`, вы должны написать весь параметр с аннотацией типа и `Depends()`:
+
+```Python
+commons: Annotated[dict, Depends(common_parameters)]
+```
+
+Но поскольку мы используем `Annotated`, мы можем сохранить это значение `Annotated` в переменную и использовать его в нескольких местах:
+
+{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}
+
+/// tip | Подсказка
+
+Это стандартный Python, это называется «type alias», и это не особенность **FastAPI**.
+
+Но поскольку **FastAPI** основан на стандартах Python, включая `Annotated`, вы можете использовать этот трюк в своём коде. 😎
+
+///
+
+Зависимости продолжат работать как ожидалось, и **лучшая часть** в том, что **информация о типах будет сохранена**, а значит, ваш редактор кода продолжит предоставлять **автозавершение**, **встроенные ошибки** и т.д. То же относится и к другим инструментам, таким как `mypy`.
+
+Это особенно полезно, когда вы используете это в **большой кодовой базе**, где вы используете **одни и те же зависимости** снова и снова во **многих *операциях пути***.
+
+## Использовать `async` или не `async` { #to-async-or-not-to-async }
+
+Поскольку зависимости также вызываются **FastAPI** (как и ваши *функции обработки пути*), применяются те же правила при определении ваших функций.
+
+Вы можете использовать `async def` или обычное `def`.
+
+И вы можете объявлять зависимости с `async def` внутри обычных *функций обработки пути* `def`, или зависимости `def` внутри *функций обработки пути* `async def` и т.д.
+
+Это не важно. **FastAPI** знает, что делать.
+
+/// note | Примечание
+
+Если вы не уверены, посмотрите раздел [Async: «Нет времени?»](../../async.md#in-a-hurry) о `async` и `await` в документации.
+
+///
+
+## Интеграция с OpenAPI { #integrated-with-openapi }
+
+Все объявления запросов, проверки и требования ваших зависимостей (и подзависимостей) будут интегрированы в ту же схему OpenAPI.
+
+Поэтому в интерактивной документации будет вся информация и из этих зависимостей:
+
+
+
+## Простое использование { #simple-usage }
+
+Если посмотреть, *функции обработки пути* объявляются для использования всякий раз, когда *путь* и *операция* совпадают, и тогда **FastAPI** заботится о вызове функции с корректными параметрами, извлекая данные из запроса.
+
+На самом деле все (или большинство) веб-фреймворков работают таким же образом.
+
+Вы никогда не вызываете эти функции напрямую. Их вызывает ваш фреймворк (в нашем случае **FastAPI**).
+
+С системой **Dependency Injection** вы также можете сообщить **FastAPI**, что ваша *функция обработки пути* «зависит» от чего-то, что должно быть выполнено перед вашей *функцией обработки пути*, и **FastAPI** позаботится о его выполнении и «инъекции» результатов.
+
+Другие распространённые термины для описания той же идеи «dependency injection»:
+
+* ресурсы
+* провайдеры
+* сервисы
+* внедряемые зависимости
+* компоненты
+
+## Плагины **FastAPI** { #fastapi-plug-ins }
+
+Интеграции и «плагины» могут быть построены с использованием системы **Dependency Injection**. Но на самом деле **нет необходимости создавать «плагины»**, так как, используя зависимости, можно объявить бесконечное количество интеграций и взаимодействий, которые становятся доступными вашим *функциям обработки пути*.
+
+И зависимости можно создавать очень простым и интуитивным способом, который позволяет просто импортировать нужные пакеты Python и интегрировать их с вашими API-функциями в пару строк кода, *буквально*.
+
+Вы увидите примеры этого в следующих главах о реляционных и NoSQL базах данных, безопасности и т.д.
+
+## Совместимость с **FastAPI** { #fastapi-compatibility }
+
+Простота системы **Dependency Injection** делает **FastAPI** совместимым с:
+
+* всеми реляционными базами данных
+* NoSQL базами данных
+* внешними пакетами
+* внешними API
+* системами аутентификации и авторизации
+* системами мониторинга использования API
+* системами инъекции данных в ответы
+* и т.д.
+
+## Просто и мощно { #simple-and-powerful }
+
+Хотя иерархическая система dependency injection очень проста для определения и использования, она по-прежнему очень мощная.
+
+Вы можете определять зависимости, которые, в свою очередь, могут иметь собственные зависимости.
+
+В итоге строится иерархическое дерево зависимостей, и система **Dependency Injection** берёт на себя решение всех этих зависимостей (и их подзависимостей) и предоставляет (инъектирует) результаты на каждом шаге.
+
+Например, у вас есть 4 API-эндпоинта (*операции пути*):
+
+* `/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** { #integrated-with-openapi_1 }
+
+Все эти зависимости, объявляя свои требования, также добавляют параметры, проверки и т.д. к вашим *операциям пути*.
+
+**FastAPI** позаботится о добавлении всего этого в схему OpenAPI, чтобы это отображалось в системах интерактивной документации.
diff --git a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md
new file mode 100644
index 0000000000000..3c71defd89c43
--- /dev/null
+++ b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md
@@ -0,0 +1,105 @@
+# Подзависимости { #sub-dependencies }
+
+Вы можете создавать зависимости, которые имеют **подзависимости**.
+
+Их **вложенность** может быть любой глубины.
+
+**FastAPI** сам займётся их управлением.
+
+## Первая зависимость { #first-dependency-dependable }
+
+Можно создать первую зависимость следующим образом:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}
+
+Она объявляет необязательный параметр запроса `q` как строку, а затем возвращает его.
+
+Это довольно просто (хотя и не очень полезно), но поможет нам сосредоточиться на том, как работают подзависимости.
+
+## Вторая зависимость, «зависимость» и «зависимая» { #second-dependency-dependable-and-dependant }
+
+Затем можно создать еще одну функцию зависимости, которая одновременно объявляет свою собственную зависимость (таким образом, она тоже является «зависимой»):
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}
+
+Остановимся на объявленных параметрах:
+
+* Несмотря на то, что эта функция сама является зависимостью, она также является зависимой от чего-то другого.
+ * Она зависит от `query_extractor` и присваивает возвращаемое ей значение параметру `q`.
+* Она также объявляет необязательный куки-параметр `last_query` в виде строки.
+ * Если пользователь не указал параметр `q` в запросе, то мы используем последний использованный запрос, который мы ранее сохранили в куки-параметре `last_query`.
+
+## Использование зависимости { #use-the-dependency }
+
+Затем мы можем использовать зависимость вместе с:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}
+
+/// info | Дополнительная информация
+
+Обратите внимание, что мы объявляем только одну зависимость в *функции операции пути* - `query_or_cookie_extractor`.
+
+Но **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
+```
+
+## Использование одной и той же зависимости несколько раз { #using-the-same-dependency-multiple-times }
+
+Если одна из ваших зависимостей объявлена несколько раз для одной и той же *функции операции пути*, например, несколько зависимостей имеют общую подзависимость, **FastAPI** будет знать, что вызывать эту подзависимость нужно только один раз за запрос.
+
+При этом возвращаемое значение будет сохранено в «кэш» и будет передано всем "зависимым" функциям, которые нуждаются в нем внутри этого конкретного запроса, вместо того, чтобы вызывать зависимость несколько раз для одного и того же запроса.
+
+В расширенном сценарии, когда вы знаете, что вам нужно, чтобы зависимость вызывалась на каждом шаге (возможно, несколько раз) в одном и том же запросе, вместо использования "кэшированного" значения, вы можете установить параметр `use_cache=False` при использовании `Depends`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | Подсказка
+
+Предпочтительнее использовать версию с аннотацией, если это возможно.
+
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+## Резюме { #recap }
+
+Помимо всех этих умных слов, используемых здесь, система внедрения зависимостей довольно проста.
+
+Это просто функции, которые выглядят так же, как *функции операций путей*.
+
+Но, тем не менее, эта система очень мощная и позволяет вам объявлять вложенные графы (деревья) зависимостей сколь угодно глубоко.
+
+/// tip | Подсказка
+
+Все это может показаться не столь полезным на этих простых примерах.
+
+Но вы увидите как это пригодится в главах посвященных безопасности.
+
+И вы также увидите, сколько кода это вам сэкономит.
+
+///
diff --git a/docs/ru/docs/tutorial/encoder.md b/docs/ru/docs/tutorial/encoder.md
new file mode 100644
index 0000000000000..f68b401cb42ed
--- /dev/null
+++ b/docs/ru/docs/tutorial/encoder.md
@@ -0,0 +1,35 @@
+# JSON-совместимый кодировщик { #json-compatible-encoder }
+
+В некоторых случаях может потребоваться преобразование типа данных (например, Pydantic-модели) в тип, совместимый с JSON (например, `dict`, `list` и т.д.).
+
+Например, если необходимо хранить его в базе данных.
+
+Для этого **FastAPI** предоставляет функцию `jsonable_encoder()`.
+
+## Использование `jsonable_encoder` { #using-the-jsonable-encoder }
+
+Представим, что у вас есть база данных `fake_db`, которая принимает только JSON-совместимые данные.
+
+Например, она не принимает объекты `datetime`, так как они не совместимы с JSON.
+
+В таком случае объект `datetime` следует преобразовать в `str`, содержащую данные в [формате ISO](https://en.wikipedia.org/wiki/ISO_8601).
+
+Точно так же эта база данных не может принять Pydantic-модель (объект с атрибутами), а только `dict`.
+
+Для этого можно использовать функцию `jsonable_encoder`.
+
+Она принимает объект, например, Pydantic-модель, и возвращает его версию, совместимую с JSON:
+
+{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *}
+
+В данном примере она преобразует Pydantic-модель в `dict`, а `datetime` - в `str`.
+
+Результатом её вызова является объект, который может быть закодирован с помощью функции из стандартной библиотеки Python – [`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps).
+
+Функция не возвращает большой `str`, содержащий данные в формате JSON (в виде строки). Она возвращает стандартную структуру данных Python (например, `dict`) со значениями и подзначениями, которые совместимы с JSON.
+
+/// note | Примечание
+
+`jsonable_encoder` фактически используется **FastAPI** внутри системы для преобразования данных. Однако он полезен и во многих других сценариях.
+
+///
diff --git a/docs/ru/docs/tutorial/extra-data-types.md b/docs/ru/docs/tutorial/extra-data-types.md
index efcbcb38a2390..062c1957423f9 100644
--- a/docs/ru/docs/tutorial/extra-data-types.md
+++ b/docs/ru/docs/tutorial/extra-data-types.md
@@ -1,4 +1,4 @@
-# Дополнительные типы данных
+# Дополнительные типы данных { #extra-data-types }
До сих пор вы использовали простые типы данных, такие как:
@@ -9,15 +9,15 @@
Но вы также можете использовать и более сложные типы.
-При этом у вас останутся те же возможности , что и до сих пор:
+При этом у вас останутся те же возможности, что и до сих пор:
-* Отличная поддержка редактора.
+* Отличная поддержка редактора кода.
* Преобразование данных из входящих запросов.
* Преобразование данных для ответа.
* Валидация данных.
* Автоматическая аннотация и документация.
-## Другие типы данных
+## Другие типы данных { #other-data-types }
Ниже перечислены некоторые из дополнительных типов данных, которые вы можете использовать:
@@ -36,7 +36,7 @@
* `datetime.timedelta`:
* Встроенный в Python `datetime.timedelta`.
* В запросах и ответах будет представлен в виде общего количества секунд типа `float`.
- * Pydantic также позволяет представить его как "Кодировку разницы во времени ISO 8601", см. документацию для получения дополнительной информации.
+ * Pydantic также позволяет представить его как "Кодировку разницы во времени ISO 8601", [см. документацию для получения дополнительной информации](https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers).
* `frozenset`:
* В запросах и ответах обрабатывается так же, как и `set`:
* В запросах будет прочитан список, исключены дубликаты и преобразован в `set`.
@@ -49,34 +49,14 @@
* `Decimal`:
* Встроенный в Python `Decimal`.
* В запросах и ответах обрабатывается так же, как и `float`.
-* Вы можете проверить все допустимые типы данных pydantic здесь: Типы данных Pydantic.
+* Вы можете проверить все допустимые типы данных Pydantic здесь: [Типы данных Pydantic](https://docs.pydantic.dev/latest/usage/types/types/).
-## Пример
+## Пример { #example }
Вот пример *операции пути* с параметрами, который демонстрирует некоторые из вышеперечисленных типов.
-=== "Python 3.6 и выше"
-
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
-
-=== "Python 3.10 и выше"
-
- ```Python hl_lines="1 2 11-15"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *}
Обратите внимание, что параметры внутри функции имеют свой естественный тип данных, и вы, например, можете выполнять обычные манипуляции с датами, такие как:
-=== "Python 3.6 и выше"
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
-
-=== "Python 3.10 и выше"
-
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *}
diff --git a/docs/ru/docs/tutorial/extra-models.md b/docs/ru/docs/tutorial/extra-models.md
index a346f7432c7f1..becb76bc3fb88 100644
--- a/docs/ru/docs/tutorial/extra-models.md
+++ b/docs/ru/docs/tutorial/extra-models.md
@@ -1,4 +1,4 @@
-# Дополнительные модели
+# Дополнительные модели { #extra-models }
В продолжение прошлого примера будет уже обычным делом иметь несколько связанных между собой моделей.
@@ -8,34 +8,27 @@
* **Модель для вывода** не должна содержать пароль.
* **Модель для базы данных**, возможно, должна содержать хэшированный пароль.
-!!! danger "Внимание"
- Никогда не храните пароли пользователей в чистом виде. Всегда храните "безопасный хэш", который вы затем сможете проверить.
+/// danger | Внимание
- Если вам это не знакомо, вы можете узнать про "хэш пароля" в [главах о безопасности](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}.
+Никогда не храните пароли пользователей в чистом виде. Всегда храните "безопасный хэш", который вы затем сможете проверить.
-## Множественные модели
+Если вам это не знакомо, вы можете узнать про "хэш пароля" в [главах о безопасности](security/simple-oauth2.md#password-hashing).
-Ниже изложена основная идея того, как могут выглядеть эти модели с полями для паролей, а также описаны места, где они используются:
-
-=== "Python 3.10+"
+///
- ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
- {!> ../../../docs_src/extra_models/tutorial001_py310.py!}
- ```
+## Множественные модели { #multiple-models }
-=== "Python 3.6+"
+Ниже изложена основная идея того, как могут выглядеть эти модели с полями для паролей, а также описаны места, где они используются:
- ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
- {!> ../../../docs_src/extra_models/tutorial001.py!}
- ```
+{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}
-### Про `**user_in.dict()`
+### Про `**user_in.model_dump()` { #about-user-in-model-dump }
-#### `.dict()` из Pydantic
+#### `.model_dump()` из Pydantic { #pydantics-model-dump }
-`user_in` - это Pydantic-модель класса `UserIn`.
+`user_in` — это Pydantic-модель класса `UserIn`.
-У Pydantic-моделей есть метод `.dict()`, который возвращает `dict` с данными модели.
+У Pydantic-моделей есть метод `.model_dump()`, который возвращает `dict` с данными модели.
Поэтому, если мы создадим Pydantic-объект `user_in` таким способом:
@@ -46,10 +39,10 @@ user_in = UserIn(username="john", password="secret", email="john.doe@example.com
и затем вызовем:
```Python
-user_dict = user_in.dict()
+user_dict = user_in.model_dump()
```
-то теперь у нас есть `dict` с данными модели в переменной `user_dict` (это `dict` вместо объекта Pydantic-модели).
+то теперь у нас есть `dict` с данными в переменной `user_dict` (это `dict` вместо объекта Pydantic-модели).
И если мы вызовем:
@@ -57,7 +50,7 @@ user_dict = user_in.dict()
print(user_dict)
```
-мы можем получить `dict` с такими данными:
+мы получим Python `dict` с:
```Python
{
@@ -68,9 +61,9 @@ print(user_dict)
}
```
-#### Распаковка `dict`
+#### Распаковка `dict` { #unpacking-a-dict }
-Если мы возьмём `dict` наподобие `user_dict` и передадим его в функцию (или класс), используя `**user_dict`, Python распакует его. Он передаст ключи и значения `user_dict` напрямую как аргументы типа ключ-значение.
+Если мы возьмём `dict` наподобие `user_dict` и передадим его в функцию (или класс), используя `**user_dict`, Python его "распакует". Он передаст ключи и значения `user_dict` напрямую как аргументы типа ключ-значение.
Поэтому, продолжая описанный выше пример с `user_dict`, написание такого кода:
@@ -78,7 +71,7 @@ print(user_dict)
UserInDB(**user_dict)
```
-Будет работать так же, как примерно такой код:
+будет эквивалентно:
```Python
UserInDB(
@@ -89,7 +82,7 @@ UserInDB(
)
```
-Или, если для большей точности мы напрямую используем `user_dict` с любым потенциальным содержимым, то этот пример будет выглядеть так:
+Или, более точно, если использовать `user_dict` напрямую, с любым содержимым, которое он может иметь в будущем:
```Python
UserInDB(
@@ -100,34 +93,34 @@ UserInDB(
)
```
-#### Pydantic-модель из содержимого другой модели
+#### Pydantic-модель из содержимого другой { #a-pydantic-model-from-the-contents-of-another }
-Как в примере выше мы получили `user_dict` из `user_in.dict()`, этот код:
+Как в примере выше мы получили `user_dict` из `user_in.model_dump()`, этот код:
```Python
-user_dict = user_in.dict()
+user_dict = user_in.model_dump()
UserInDB(**user_dict)
```
будет равнозначен такому:
```Python
-UserInDB(**user_in.dict())
+UserInDB(**user_in.model_dump())
```
-...потому что `user_in.dict()` - это `dict`, и затем мы указываем, чтобы Python его "распаковал", когда передаём его в `UserInDB` и ставим перед ним `**`.
+...потому что `user_in.model_dump()` — это `dict`, и затем мы указываем, чтобы Python его "распаковал", когда передаём его в `UserInDB` с префиксом `**`.
Таким образом мы получаем Pydantic-модель на основе данных из другой Pydantic-модели.
-#### Распаковка `dict` и дополнительные именованные аргументы
+#### Распаковка `dict` и дополнительные именованные аргументы { #unpacking-a-dict-and-extra-keywords }
И затем, если мы добавим дополнительный именованный аргумент `hashed_password=hashed_password` как здесь:
```Python
-UserInDB(**user_in.dict(), hashed_password=hashed_password)
+UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
```
-... то мы получим что-то подобное:
+...то в итоге получится что-то подобное:
```Python
UserInDB(
@@ -139,12 +132,15 @@ UserInDB(
)
```
-!!! warning "Предупреждение"
- Цель использованных в примере вспомогательных функций - не более чем демонстрация возможных операций с данными, но, конечно, они не обеспечивают настоящую безопасность.
+/// warning | Предупреждение
+
+Вспомогательные дополнительные функции `fake_password_hasher` и `fake_save_user` используются только для демонстрации возможного потока данных и, конечно, не обеспечивают настоящую безопасность.
-## Сократите дублирование
+///
-Сокращение дублирования кода - это одна из главных идей **FastAPI**.
+## Сократите дублирование { #reduce-duplication }
+
+Сокращение дублирования кода — это одна из главных идей **FastAPI**.
Поскольку дублирование кода повышает риск появления багов, проблем с безопасностью, проблем десинхронизации кода (когда вы обновляете код в одном месте, но не обновляете в другом), и т.д.
@@ -158,42 +154,25 @@ UserInDB(
В этом случае мы можем определить только различия между моделями (с `password` в чистом виде, с `hashed_password` и без пароля):
-=== "Python 3.10+"
-
- ```Python hl_lines="7 13-14 17-18 21-22"
- {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="9 15-16 19-20 23-24"
- {!> ../../../docs_src/extra_models/tutorial002.py!}
- ```
+{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}
-## `Union` или `anyOf`
+## `Union` или `anyOf` { #union-or-anyof }
-Вы можете определить ответ как `Union` из двух типов. Это означает, что ответ должен соответствовать одному из них.
+Вы можете объявить HTTP-ответ как `Union` из двух или более типов. Это означает, что HTTP-ответ может быть любым из них.
Он будет определён в OpenAPI как `anyOf`.
-Для этого используйте стандартные аннотации типов в Python `typing.Union`:
+Для этого используйте стандартную аннотацию типов в Python [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union):
-!!! note "Примечание"
- При объявлении `Union`, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`.
+/// note | Примечание
-=== "Python 3.10+"
+При объявлении [`Union`](https://docs.pydantic.dev/latest/concepts/types/#unions) сначала указывайте наиболее специфичный тип, затем менее специфичный. В примере ниже более специфичный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`.
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003_py310.py!}
- ```
+///
-=== "Python 3.6+"
+{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003.py!}
- ```
-
-### `Union` в Python 3.10
+### `Union` в Python 3.10 { #union-in-python-3-10 }
В этом примере мы передаём `Union[PlaneItem, CarItem]` в качестве значения аргумента `response_model`.
@@ -205,48 +184,28 @@ UserInDB(
some_variable: PlaneItem | CarItem
```
-Но если мы помещаем его в `response_model=PlaneItem | CarItem` мы получим ошибку, потому что Python попытается произвести **некорректную операцию** между `PlaneItem` и `CarItem` вместо того, чтобы интерпретировать это как аннотацию типа.
-
-## Список моделей
-
-Таким же образом вы можете определять ответы как списки объектов.
-
-Для этого используйте `typing.List` из стандартной библиотеки Python (или просто `list` в Python 3.9 и выше):
+Но если мы поместим это в присваивание `response_model=PlaneItem | CarItem`, мы получим ошибку, потому что Python попытается произвести **некорректную операцию** между `PlaneItem` и `CarItem` вместо того, чтобы интерпретировать это как аннотацию типа.
-=== "Python 3.9+"
+## Список моделей { #list-of-models }
- ```Python hl_lines="18"
- {!> ../../../docs_src/extra_models/tutorial004_py39.py!}
- ```
+Таким же образом вы можете объявлять HTTP-ответы, возвращающие списки объектов.
-=== "Python 3.6+"
+Для этого используйте стандартный `list` в Python:
- ```Python hl_lines="1 20"
- {!> ../../../docs_src/extra_models/tutorial004.py!}
- ```
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
-## Ответ с произвольным `dict`
+## Ответ с произвольным `dict` { #response-with-arbitrary-dict }
-Вы также можете определить ответ, используя произвольный одноуровневый `dict` и определяя только типы ключей и значений без использования Pydantic-моделей.
+Вы также можете объявить HTTP-ответ, используя обычный произвольный `dict`, объявив только тип ключей и значений, без использования Pydantic-модели.
Это полезно, если вы заранее не знаете корректных названий полей/атрибутов (которые будут нужны при использовании Pydantic-модели).
-В этом случае вы можете использовать `typing.Dict` (или просто `dict` в Python 3.9 и выше):
-
-=== "Python 3.9+"
-
- ```Python hl_lines="6"
- {!> ../../../docs_src/extra_models/tutorial005_py39.py!}
- ```
-
-=== "Python 3.6+"
+В этом случае вы можете использовать `dict`:
- ```Python hl_lines="1 8"
- {!> ../../../docs_src/extra_models/tutorial005.py!}
- ```
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
-## Резюме
+## Резюме { #recap }
-Используйте несколько Pydantic-моделей и свободно применяйте наследование для каждой из них.
+Используйте несколько Pydantic-моделей и свободно применяйте наследование для каждого случая.
-Вам не обязательно иметь единственную модель данных для каждой сущности, если эта сущность должна иметь возможность быть в разных "состояниях". Как в случае с "сущностью" пользователя, у которого есть состояния с полями `password`, `password_hash` и без пароля.
+Вам не обязательно иметь единственную модель данных для каждой сущности, если эта сущность должна иметь возможность быть в разных "состояниях". Как в случае с "сущностью" пользователя, у которого есть состояние, включающее `password`, `password_hash` и отсутствие пароля.
diff --git a/docs/ru/docs/tutorial/first-steps.md b/docs/ru/docs/tutorial/first-steps.md
index b46f235bc7bc0..7216d4cb799dd 100644
--- a/docs/ru/docs/tutorial/first-steps.md
+++ b/docs/ru/docs/tutorial/first-steps.md
@@ -1,105 +1,122 @@
-# Первые шаги
+# Первые шаги { #first-steps }
-Самый простой FastAPI файл может выглядеть так:
+Самый простой файл FastAPI может выглядеть так:
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
-Скопируйте в файл `main.py`.
+Скопируйте это в файл `main.py`.
Запустите сервер в режиме реального времени:
get операции
-* путь `/`
-* использующих get операцию
+/// info | Информация о `@decorator`
-!!! info "`@decorator` Дополнительная информация"
- Синтаксис `@something` в Python называется "декоратор".
+Синтаксис `@something` в Python называется «декоратор».
- Вы помещаете его над функцией. Как красивую декоративную шляпу (думаю, что оттуда и происходит этот термин).
+Его размещают над функцией. Как красивая декоративная шляпа (кажется, отсюда и пошёл термин).
- "Декоратор" принимает функцию ниже и выполняет с ней какое-то действие.
+«Декоратор» берёт функцию ниже и делает с ней что-то.
- В нашем случае, этот декоратор сообщает **FastAPI**, что функция ниже соответствует **пути** `/` и **операции** `get`.
+В нашем случае этот декоратор сообщает **FastAPI**, что функция ниже соответствует **пути** `/` с **операцией** `get`.
- Это и есть "**декоратор операции пути**".
+Это и есть «декоратор операции пути».
-Можно также использовать операции:
+///
+
+Можно также использовать другие операции:
* `@app.post()`
* `@app.put()`
@@ -274,60 +349,81 @@ https://example.com/items/foo
* `@app.patch()`
* `@app.trace()`
-!!! tip "Подсказка"
- Вы можете использовать каждую операцию (HTTP-метод) по своему усмотрению.
+/// tip | Подсказка
+
+Вы можете использовать каждый метод (HTTP-операцию) так, как считаете нужным.
- **FastAPI** не навязывает определенного значения для каждого метода.
+**FastAPI** не навязывает какого-либо конкретного смысла.
- Информация здесь представлена как рекомендация, а не требование.
+Эта информация дана как рекомендация, а не требование.
- Например, при использовании GraphQL обычно все действия выполняются только с помощью POST операций.
+Например, при использовании GraphQL обычно все действия выполняются только с помощью POST-операций.
-### Шаг 4: определите **функцию операции пути**
+///
-Вот "**функция операции пути**":
+### Шаг 4: определите **функцию операции пути** { #step-4-define-the-path-operation-function }
+
+Вот наша «функция операции пути»:
* **путь**: `/`.
* **операция**: `get`.
-* **функция**: функция ниже "декоратора" (ниже `@app.get("/")`).
+* **функция**: функция ниже «декоратора» (ниже `@app.get("/")`).
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
-Это обычная Python функция.
+Это функция на Python.
-**FastAPI** будет вызывать её каждый раз при получении `GET` запроса к URL "`/`".
+**FastAPI** будет вызывать её каждый раз, когда получает запрос к URL «`/`» с операцией `GET`.
-В данном случае это асинхронная функция.
+В данном случае это асинхронная (`async`) функция.
---
-Вы также можете определить ее как обычную функцию вместо `async def`:
+Вы также можете определить её как обычную функцию вместо `async def`:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
-!!! note "Технические детали"
- Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
+/// note | Примечание
-### Шаг 5: верните результат
+Если вы не знаете, в чём разница, посмотрите [Асинхронность: *"Нет времени?"*](../async.md#in-a-hurry).
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+///
+
+### Шаг 5: верните содержимое { #step-5-return-the-content }
+
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
Вы можете вернуть `dict`, `list`, отдельные значения `str`, `int` и т.д.
-Также можно вернуть модели Pydantic (рассмотрим это позже).
+Также можно вернуть модели Pydantic (подробнее об этом позже).
+
+Многие другие объекты и модели будут автоматически преобразованы в JSON (включая ORM и т.п.). Попробуйте использовать те, что вам привычнее, с высокой вероятностью они уже поддерживаются.
+
+### Шаг 6: разверните приложение { #step-6-deploy-it }
+
+Разверните приложение в **[FastAPI Cloud](https://fastapicloud.com)** одной командой: `fastapi deploy`. 🎉
+
+#### О FastAPI Cloud { #about-fastapi-cloud }
+
+**[FastAPI Cloud](https://fastapicloud.com)** создан тем же автором и командой, что и **FastAPI**.
+
+Он упрощает процесс **создания образа**, **развертывания** и **доступа** к API с минимальными усилиями.
+
+Он переносит тот же **опыт разработчика** при создании приложений с FastAPI на их **развертывание** в облаке. 🎉
+
+FastAPI Cloud — основной спонсор и источник финансирования для open-source проектов «FastAPI и друзья». ✨
+
+#### Развертывание у других облачных провайдеров { #deploy-to-other-cloud-providers }
+
+FastAPI — open-source и основан на стандартах. Вы можете развернуть приложения FastAPI у любого облачного провайдера по вашему выбору.
-Многие объекты и модели будут автоматически преобразованы в JSON (включая ORM). Пробуйте использовать другие объекты, которые предпочтительней для Вас, вероятно, они уже поддерживаются.
+Следуйте руководствам вашего облачного провайдера, чтобы развернуть приложения FastAPI у них. 🤓
-## Резюме
+## Резюме { #recap }
-* Импортируем `FastAPI`.
-* Создаём экземпляр `app`.
-* Пишем **декоратор операции пути** (такой как `@app.get("/")`).
-* Пишем **функцию операции пути** (`def root(): ...`).
-* Запускаем сервер в режиме разработки (`uvicorn main:app --reload`).
+* Импортируйте `FastAPI`.
+* Создайте экземпляр `app`.
+* Напишите **декоратор операции пути**, например `@app.get("/")`.
+* Определите **функцию операции пути**; например, `def root(): ...`.
+* Запустите сервер разработки командой `fastapi dev`.
+* При желании разверните приложение командой `fastapi deploy`.
diff --git a/docs/ru/docs/tutorial/handling-errors.md b/docs/ru/docs/tutorial/handling-errors.md
new file mode 100644
index 0000000000000..fde188f09f79b
--- /dev/null
+++ b/docs/ru/docs/tutorial/handling-errors.md
@@ -0,0 +1,244 @@
+# Обработка ошибок { #handling-errors }
+
+Существует множество ситуаций, когда необходимо сообщить об ошибке клиенту, использующему ваш API.
+
+Таким клиентом может быть браузер с фронтендом, чужой код, IoT-устройство и т.д.
+
+Возможно, вам придется сообщить клиенту о следующем:
+
+* Клиент не имеет достаточных привилегий для выполнения данной операции.
+* Клиент не имеет доступа к данному ресурсу.
+* Элемент, к которому клиент пытался получить доступ, не существует.
+* и т.д.
+
+В таких случаях обычно возвращают **HTTP статус-код** в диапазоне **400** (от 400 до 499).
+
+Они похожи на двухсотые HTTP статус-коды (от 200 до 299), которые означают, что запрос обработан успешно.
+
+Четырёхсотые статус-коды означают, что ошибка произошла по вине клиента.
+
+Помните ли ошибки **"404 Not Found "** (и шутки) ?
+
+## Использование `HTTPException` { #use-httpexception }
+
+Для возврата клиенту HTTP-ответов с ошибками используется `HTTPException`.
+
+### Импортируйте `HTTPException` { #import-httpexception }
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
+
+### Вызовите `HTTPException` в своем коде { #raise-an-httpexception-in-your-code }
+
+`HTTPException` - это обычное исключение Python с дополнительными данными, актуальными для API.
+
+Поскольку это исключение Python, то его не `возвращают`, а `вызывают`.
+
+Это также означает, что если вы находитесь внутри функции, которая вызывается внутри вашей *функции операции пути*, и вы поднимаете `HTTPException` внутри этой функции, то она не будет выполнять остальной код в *функции операции пути*, а сразу завершит запрос и отправит HTTP-ошибку из `HTTPException` клиенту.
+
+О том, насколько выгоднее `вызывать` исключение, чем `возвращать` значение, будет рассказано в разделе, посвященном зависимостям и безопасности.
+
+В данном примере, когда клиент запрашивает элемент по несуществующему ID, возникает исключение со статус-кодом `404`:
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
+
+### Возвращаемый ответ { #the-resulting-response }
+
+Если клиент запросит `http://example.com/items/foo` (`item_id` `"foo"`), то он получит статус-код 200 и ответ в формате JSON:
+
+```JSON
+{
+ "item": "The Foo Wrestlers"
+}
+```
+
+Но если клиент запросит `http://example.com/items/bar` (несуществующий `item_id` `"bar"`), то он получит статус-код 404 (ошибка "не найдено") и JSON-ответ в виде:
+
+```JSON
+{
+ "detail": "Item not found"
+}
+```
+
+/// tip | Подсказка
+
+При вызове `HTTPException` в качестве параметра `detail` можно передавать любое значение, которое может быть преобразовано в JSON, а не только `str`.
+
+Вы можете передать `dict`, `list` и т.д.
+
+Они автоматически обрабатываются **FastAPI** и преобразуются в JSON.
+
+///
+
+## Добавление пользовательских заголовков { #add-custom-headers }
+
+В некоторых ситуациях полезно иметь возможность добавлять пользовательские HTTP-заголовки к ошибке HTTP. Например, для некоторых типов безопасности.
+
+Скорее всего, вам не потребуется использовать его непосредственно в коде.
+
+Но в случае, если это необходимо для продвинутого сценария, можно добавить пользовательские заголовки:
+
+{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
+
+## Установка пользовательских обработчиков исключений { #install-custom-exception-handlers }
+
+Вы можете добавить пользовательские обработчики исключений с помощью [тех же утилит обработки исключений из Starlette](https://www.starlette.dev/exceptions/).
+
+Допустим, у вас есть пользовательское исключение `UnicornException`, которое вы (или используемая вами библиотека) можете `вызвать`.
+
+И вы хотите обрабатывать это исключение глобально с помощью FastAPI.
+
+Можно добавить собственный обработчик исключений с помощью `@app.exception_handler()`:
+
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
+
+Здесь, если запросить `/unicorns/yolo`, то *операция пути* вызовет `UnicornException`.
+
+Но оно будет обработано `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** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. То же самое касается и `Request`.
+
+///
+
+## Переопределение стандартных обработчиков исключений { #override-the-default-exception-handlers }
+
+**FastAPI** имеет некоторые обработчики исключений по умолчанию.
+
+Эти обработчики отвечают за возврат стандартных JSON-ответов при `вызове` `HTTPException` и при наличии в запросе недопустимых данных.
+
+Вы можете переопределить эти обработчики исключений на свои собственные.
+
+### Переопределение обработчика исключений проверки запроса { #override-request-validation-exceptions }
+
+Когда запрос содержит недопустимые данные, **FastAPI** внутренне вызывает ошибку `RequestValidationError`.
+
+А также включает в себя обработчик исключений по умолчанию.
+
+Чтобы переопределить его, импортируйте `RequestValidationError` и используйте его с `@app.exception_handler(RequestValidationError)` для создания обработчика исключений.
+
+Обработчик исключения получит объект `Request` и исключение.
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
+
+Теперь, если перейти к `/items/foo`, то вместо стандартной JSON-ошибки с:
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ]
+}
+```
+
+вы получите текстовую версию:
+
+```
+Validation errors:
+Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer
+```
+
+### Переопределите обработчик ошибок `HTTPException` { #override-the-httpexception-error-handler }
+
+Аналогичным образом можно переопределить обработчик `HTTPException`.
+
+Например, для этих ошибок можно вернуть обычный текстовый ответ вместо JSON:
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
+
+/// note | Технические детали
+
+Можно также использовать `from starlette.responses import PlainTextResponse`.
+
+**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette.
+
+///
+
+/// warning | Внимание
+
+Имейте в виду, что `RequestValidationError` содержит информацию об имени файла и строке, где произошла ошибка валидации, чтобы вы могли при желании отобразить её в логах с релевантными данными.
+
+Но это означает, что если вы просто преобразуете её в строку и вернёте эту информацию напрямую, вы можете допустить небольшую утечку информации о своей системе, поэтому здесь код извлекает и показывает каждую ошибку отдельно.
+
+///
+
+### Используйте тело `RequestValidationError` { #use-the-requestvalidationerror-body }
+
+Ошибка `RequestValidationError` содержит полученное `тело` с недопустимыми данными.
+
+Вы можете использовать его при разработке приложения для регистрации тела и его отладки, возврата пользователю и т.д.
+
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
+
+Теперь попробуйте отправить недействительный элемент, например:
+
+```JSON
+{
+ "title": "towel",
+ "size": "XL"
+}
+```
+
+Вы получите ответ о том, что данные недействительны, содержащий следующее тело:
+
+```JSON hl_lines="12-15"
+{
+ "detail": [
+ {
+ "loc": [
+ "body",
+ "size"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ],
+ "body": {
+ "title": "towel",
+ "size": "XL"
+ }
+}
+```
+
+#### `HTTPException` в FastAPI или в Starlette { #fastapis-httpexception-vs-starlettes-httpexception }
+
+**FastAPI** имеет собственный `HTTPException`.
+
+Класс ошибок **FastAPI** `HTTPException` наследует от класса ошибок Starlette `HTTPException`.
+
+Единственное отличие состоит в том, что `HTTPException` в **FastAPI** принимает любые данные, пригодные для преобразования в JSON, в поле `detail`, тогда как `HTTPException` в Starlette принимает для него только строки.
+
+Таким образом, вы можете продолжать вызывать `HTTPException` от **FastAPI** как обычно в своем коде.
+
+Но когда вы регистрируете обработчик исключений, вы должны зарегистрировать его для `HTTPException` от Starlette.
+
+Таким образом, если какая-либо часть внутреннего кодa Starlette, расширение или плагин Starlette вызовет исключение Starlette `HTTPException`, ваш обработчик сможет перехватить и обработать его.
+
+В данном примере, чтобы иметь возможность использовать оба `HTTPException` в одном коде, исключения Starlette переименованы в `StarletteHTTPException`:
+
+```Python
+from starlette.exceptions import HTTPException as StarletteHTTPException
+```
+
+### Переиспользование обработчиков исключений **FastAPI** { #reuse-fastapis-exception-handlers }
+
+Если вы хотите использовать исключение вместе с теми же обработчиками исключений по умолчанию из **FastAPI**, вы можете импортировать и повторно использовать обработчики исключений по умолчанию из `fastapi.exception_handlers`:
+
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
+
+В этом примере вы просто `выводите в терминал` ошибку с очень выразительным сообщением, но идея вам понятна. Вы можете использовать исключение, а затем просто повторно использовать стандартные обработчики исключений.
diff --git a/docs/ru/docs/tutorial/header-param-models.md b/docs/ru/docs/tutorial/header-param-models.md
new file mode 100644
index 0000000000000..fc1fb06d6e37a
--- /dev/null
+++ b/docs/ru/docs/tutorial/header-param-models.md
@@ -0,0 +1,72 @@
+# Модели Header-параметров { #header-parameter-models }
+
+Если у вас есть группа связанных **header-параметров**, то вы можете объединить их в одну **Pydantic-модель**.
+
+Это позволит вам **переиспользовать модель** в **разных местах**, а также задать валидацию и метаданные сразу для всех параметров. 😎
+
+/// note | Заметка
+
+Этот функционал доступен в FastAPI начиная с версии `0.115.0`. 🤓
+
+///
+
+## Header-параметры в виде Pydantic-модели { #header-parameters-with-a-pydantic-model }
+
+Объявите нужные **header-параметры** в **Pydantic-модели** и затем аннотируйте параметр как `Header`:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI** **извлечёт** данные для **каждого поля** из **заголовков** запроса и выдаст заданную вами Pydantic-модель.
+
+## Проверьте документацию { #check-the-docs }
+
+Вы можете посмотреть нужные header-параметры в графическом интерфейсе сгенерированной документации по пути `/docs`:
+
+
+contact| Параметр | Тип | Описание |
|---|---|---|
name | str | Идентификационное имя контактного лица/организации. |
url | str | URL указывающий на контактную информацию. ДОЛЖЕН быть в формате URL. |
email | str | Email адрес контактного лица/организации. ДОЛЖЕН быть в формате email адреса. |
license_info| Параметр | Тип | Описание |
|---|---|---|
name | str | ОБЯЗАТЕЛЬНО (если установлен параметр license_info). Название лицензии, используемой для API |
url | str | URL, указывающий на лицензию, используемую для API. ДОЛЖЕН быть в формате URL. |
license_info| Параметр | Тип | Описание |
|---|---|---|
name | str | ОБЯЗАТЕЛЬНО (если установлен параметр license_info). Название лицензии, используемой для API. |
identifier | str | Выражение лицензии [SPDX](https://spdx.org/licenses/) для API. Поле identifier взаимоисключающее с полем url. Доступно начиная с OpenAPI 3.1.0, FastAPI 0.99.0. |
url | str | URL, указывающий на лицензию, используемую для API. ДОЛЖЕН быть в формате URL. |
-## Метаданные для тегов
+## Идентификатор лицензии { #license-identifier }
+
+Начиная с OpenAPI 3.1.0 и FastAPI 0.99.0, вы также можете задать `license_info` с помощью `identifier` вместо `url`.
+
+К примеру:
+
+{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}
+
+## Метаданные для тегов { #metadata-for-tags }
Вы также можете добавить дополнительные метаданные для различных тегов, используемых для группировки ваших операций пути с помощью параметра `openapi_tags`.
@@ -42,44 +52,47 @@
* `description`: `str`-значение с кратким описанием для внешней документации.
* `url` (**обязательно**): `str`-значение с URL-адресом для внешней документации.
-### Создание метаданных для тегов
+### Создание метаданных для тегов { #create-metadata-for-tags }
Давайте попробуем сделать это на примере с тегами для `users` и `items`.
Создайте метаданные для ваших тегов и передайте их в параметре `openapi_tags`:
-```Python hl_lines="3-16 18"
-{!../../../docs_src/metadata/tutorial004.py!}
-```
+{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}
Помните, что вы можете использовать Markdown внутри описания, к примеру "login" будет отображен жирным шрифтом (**login**) и "fancy" будет отображаться курсивом (_fancy_).
-!!! tip "Подсказка"
- Вам необязательно добавлять метаданные для всех используемых тегов
+/// tip | Подсказка
+
+Вам необязательно добавлять метаданные для всех используемых тегов
+
+///
+
+### Используйте собственные теги { #use-your-tags }
-### Используйте собственные теги
Используйте параметр `tags` с вашими *операциями пути* (и `APIRouter`ами), чтобы присвоить им различные теги:
-```Python hl_lines="21 26"
-{!../../../docs_src/metadata/tutorial004.py!}
-```
+{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}
+
+/// info | Дополнительная информация
+
+Узнайте больше о тегах в [Конфигурации операции пути](path-operation-configuration.md#tags).
-!!! info "Дополнительная информация"
- Узнайте больше о тегах в [Конфигурации операции пути](../path-operation-configuration/#tags){.internal-link target=_blank}.
+///
-### Проверьте документацию
+### Проверьте документацию { #check-the-docs }
Теперь, если вы проверите документацию, вы увидите всю дополнительную информацию:
-### Порядок расположения тегов
+### Порядок расположения тегов { #order-of-tags }
-Порядок расположения словарей метаданных для каждого тега определяет также порядок, отображаемый в документах UI
+Порядок расположения словарей метаданных для каждого тега определяет также порядок, отображаемый в UI документации.
К примеру, несмотря на то, что `users` будут идти после `items` в алфавитном порядке, они отображаются раньше, потому что мы добавляем свои метаданные в качестве первого словаря в списке.
-## URL-адреса OpenAPI
+## URL-адрес OpenAPI { #openapi-url }
По умолчанию схема OpenAPI отображена по адресу `/openapi.json`.
@@ -87,15 +100,13 @@
К примеру, чтобы задать её отображение по адресу `/api/v1/openapi.json`:
-```Python hl_lines="3"
-{!../../../docs_src/metadata/tutorial002.py!}
-```
+{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}
-Если вы хотите отключить схему OpenAPI полностью, вы можете задать `openapi_url=None`, это также отключит пользовательские интерфейсы документации, которые его использует.
+Если вы хотите отключить схему OpenAPI полностью, вы можете задать `openapi_url=None`, это также отключит пользовательские интерфейсы документации, которые её используют.
-## URL-адреса документации
+## URL-адреса документации { #docs-urls }
-Вы можете изменить конфигурацию двух пользовательских интерфейсов документации, среди которых
+Вы можете изменить конфигурацию двух пользовательских интерфейсов документации, которые включены:
* **Swagger UI**: отображаемый по адресу `/docs`.
* Вы можете задать его URL с помощью параметра `docs_url`.
@@ -106,6 +117,4 @@
К примеру, чтобы задать отображение Swagger UI по адресу `/documentation` и отключить ReDoc:
-```Python hl_lines="3"
-{!../../../docs_src/metadata/tutorial003.py!}
-```
+{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}
diff --git a/docs/ru/docs/tutorial/middleware.md b/docs/ru/docs/tutorial/middleware.md
new file mode 100644
index 0000000000000..81140051f2ff8
--- /dev/null
+++ b/docs/ru/docs/tutorial/middleware.md
@@ -0,0 +1,95 @@
+# Middleware (Промежуточный слой) { #middleware }
+
+Вы можете добавить middleware (промежуточный слой) в **FastAPI** приложение.
+
+"Middleware" - это функция, которая выполняется с каждым **запросом** до его обработки какой-либо конкретной *операцией пути*. А также с каждым **ответом** перед его возвращением.
+
+* Она принимает каждый поступающий **запрос**.
+* Может что-то сделать с этим **запросом** или выполнить любой нужный код.
+* Затем передает **запрос** для последующей обработки (какой-либо *операцией пути*).
+* Получает **ответ** (от *операции пути*).
+* Может что-то сделать с этим **ответом** или выполнить любой нужный код.
+* И возвращает **ответ**.
+
+/// note | Технические детали
+
+Если у вас есть зависимости с `yield`, то код выхода (код после `yield`) будет выполняться *после* middleware.
+
+Если были какие‑либо фоновые задачи (рассматриваются в разделе [Фоновые задачи](background-tasks.md), вы увидите это позже), они будут запущены *после* всех middleware.
+
+///
+
+## Создание middleware { #create-a-middleware }
+
+Для создания middleware используйте декоратор `@app.middleware("http")` поверх функции.
+
+Функция middleware получает:
+
+* `request`.
+* Функцию `call_next`, которая получает `request` в качестве параметра.
+ * Эта функция передаёт `request` соответствующей *операции пути*.
+ * Затем она возвращает `response`, сгенерированный соответствующей *операцией пути*.
+* Также имеется возможность видоизменить `response` перед тем как его вернуть.
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}
+
+/// tip | Совет
+
+Имейте в виду, что можно добавлять проприетарные HTTP-заголовки [с префиксом `X-`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers).
+
+Но если вы хотите, чтобы клиент в браузере мог видеть ваши пользовательские заголовки, необходимо добавить их в настройки CORS ([CORS (Cross-Origin Resource Sharing)](cors.md)), используя параметр `expose_headers`, описанный в [документации по CORS Starlette](https://www.starlette.dev/middleware/#corsmiddleware).
+
+///
+
+/// note | Технические детали
+
+Вы также можете использовать `from starlette.requests import Request`.
+
+**FastAPI** предоставляет такой доступ для удобства разработчиков. Но, на самом деле, это `Request` из Starlette.
+
+///
+
+### До и после `response` { #before-and-after-the-response }
+
+Вы можете добавить код, использующий `request`, до передачи его какой-либо *операции пути*.
+
+А также после формирования `response`, до того, как вы его вернёте.
+
+Например, вы можете добавить собственный заголовок `X-Process-Time`, содержащий время в секундах, необходимое для обработки запроса и генерации ответа:
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}
+
+/// tip | Совет
+
+Мы используем [`time.perf_counter()`](https://docs.python.org/3/library/time.html#time.perf_counter) вместо `time.time()` для обеспечения большей точности в таких случаях. 🤓
+
+///
+
+## Порядок выполнения нескольких middleware { #multiple-middleware-execution-order }
+
+Когда вы добавляете несколько middleware с помощью декоратора `@app.middleware()` или метода `app.add_middleware()`, каждое новое middleware оборачивает приложение, формируя стек. Последнее добавленное middleware — самое внешнее (*outermost*), а первое — самое внутреннее (*innermost*).
+
+На пути обработки запроса сначала выполняется самое внешнее middleware.
+
+На пути формирования ответа оно выполняется последним.
+
+Например:
+
+```Python
+app.add_middleware(MiddlewareA)
+app.add_middleware(MiddlewareB)
+```
+
+Это приводит к следующему порядку выполнения:
+
+* **Запрос**: MiddlewareB → MiddlewareA → маршрут
+
+* **Ответ**: маршрут → MiddlewareA → MiddlewareB
+
+Такое стековое поведение обеспечивает предсказуемый и управляемый порядок выполнения middleware.
+
+## Другие middleware { #other-middlewares }
+
+О других middleware вы можете узнать больше в разделе [Расширенное руководство пользователя: Продвинутое middleware](../advanced/middleware.md).
+
+В следующем разделе вы можете прочитать, как настроить CORS с помощью middleware.
diff --git a/docs/ru/docs/tutorial/path-operation-configuration.md b/docs/ru/docs/tutorial/path-operation-configuration.md
index 013903add1cc0..965f2a1ba2f2f 100644
--- a/docs/ru/docs/tutorial/path-operation-configuration.md
+++ b/docs/ru/docs/tutorial/path-operation-configuration.md
@@ -1,70 +1,44 @@
-# Конфигурация операций пути
+# Конфигурация операций пути { #path-operation-configuration }
Существует несколько параметров, которые вы можете передать вашему *декоратору операций пути* для его настройки.
-!!! warning "Внимание"
- Помните, что эти параметры передаются непосредственно *декоратору операций пути*, а не вашей *функции-обработчику операций пути*.
+/// warning | Внимание
-## Коды состояния
+Помните, что эти параметры передаются непосредственно *декоратору операций пути*, а не вашей *функции-обработчику пути*.
-Вы можете определить (HTTP) `status_code`, который будет использован в ответах вашей *операции пути*.
-
-Вы можете передать только `int`-значение кода, например `404`.
+///
-Но если вы не помните, для чего нужен каждый числовой код, вы можете использовать сокращенные константы в параметре `status`:
+## Статус-код ответа { #response-status-code }
-=== "Python 3.10+"
+Вы можете определить (HTTP) `status_code`, который будет использован в ответах вашей *операции пути*.
- ```Python hl_lines="1 15"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!}
- ```
+Вы можете передать только `int`-значение кода, например `404`.
-=== "Python 3.9+"
+Но если вы не помните, для чего нужен каждый числовой код, вы можете использовать сокращенные константы в `status`:
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *}
-=== "Python 3.6+"
+Этот статус-код будет использован в ответе и будет добавлен в схему OpenAPI.
- ```Python hl_lines="3 17"
- {!> ../../../docs_src/path_operation_configuration/tutorial001.py!}
- ```
+/// note | Технические детали
-Этот код состояния будет использован в ответе и будет добавлен в схему OpenAPI.
+Вы также можете использовать `from starlette import status`.
-!!! note "Технические детали"
- Вы также можете использовать `from starlette import status`.
+**FastAPI** предоставляет тот же `starlette.status` под псевдонимом `fastapi.status` для удобства разработчика. Но его источник - это непосредственно Starlette.
- **FastAPI** предоставляет тот же `starlette.status` под псевдонимом `fastapi.status` для удобства разработчика. Но его источник - это непосредственно Starlette.
+///
-## Теги
+## Теги { #tags }
Вы можете добавлять теги к вашим *операциям пути*, добавив параметр `tags` с `list` заполненным `str`-значениями (обычно в нём только одна строка):
-=== "Python 3.10+"
-
- ```Python hl_lines="15 20 25"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="17 22 27"
- {!> ../../../docs_src/path_operation_configuration/tutorial002.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *}
Они будут добавлены в схему OpenAPI и будут использованы в автоматической документации интерфейса:
-### Теги с перечислениями
+### Теги с перечислениями { #tags-with-enums }
Если у вас большое приложение, вы можете прийти к необходимости добавить **несколько тегов**, и возможно, вы захотите убедиться в том, что всегда используете **один и тот же тег** для связанных *операций пути*.
@@ -72,99 +46,53 @@
**FastAPI** поддерживает это так же, как и в случае с обычными строками:
-```Python hl_lines="1 8-10 13 18"
-{!../../../docs_src/path_operation_configuration/tutorial002b.py!}
-```
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
-## Краткое и развёрнутое содержание
+## Краткое и развёрнутое содержание { #summary-and-description }
Вы можете добавить параметры `summary` и `description`:
-=== "Python 3.10+"
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *}
-=== "Python 3.9+"
+## Описание из строк документации { #description-from-docstring }
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!}
- ```
+Так как описания обычно длинные и содержат много строк, вы можете объявить описание *операции пути* в строке документации функции, и **FastAPI** прочитает её оттуда.
-=== "Python 3.6+"
+Вы можете использовать [Markdown](https://en.wikipedia.org/wiki/Markdown) в строке документации, и он будет интерпретирован и отображён корректно (с учетом отступа в строке документации).
- ```Python hl_lines="20-21"
- {!> ../../../docs_src/path_operation_configuration/tutorial003.py!}
- ```
-
-## Описание из строк документации
-
-Так как описания обычно длинные и содержат много строк, вы можете объявить описание *операции пути* в функции строки документации и **FastAPI** прочитает её отсюда.
-
-Вы можете использовать Markdown в строке документации, и он будет интерпретирован и отображён корректно (с учетом отступа в строке документации).
-
-=== "Python 3.10+"
-
- ```Python hl_lines="17-25"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="19-27"
- {!> ../../../docs_src/path_operation_configuration/tutorial004.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}
Он будет использован в интерактивной документации:
-## Описание ответа
+## Описание ответа { #response-description }
Вы можете указать описание ответа с помощью параметра `response_description`:
-=== "Python 3.10+"
-
- ```Python hl_lines="19"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!}
- ```
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
-=== "Python 3.9+"
+/// info | Дополнительная информация
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!}
- ```
+Помните, что `response_description` относится конкретно к ответу, а `description` относится к *операции пути* в целом.
-=== "Python 3.6+"
+///
- ```Python hl_lines="21"
- {!> ../../../docs_src/path_operation_configuration/tutorial005.py!}
- ```
+/// check | Проверка
-!!! info "Дополнительная информация"
- Помните, что `response_description` относится конкретно к ответу, а `description` относится к *операции пути* в целом.
+OpenAPI указывает, что каждой *операции пути* необходимо описание ответа.
-!!! check "Технические детали"
- OpenAPI указывает, что каждой *операции пути* необходимо описание ответа.
+Если вдруг вы не укажете его, то **FastAPI** автоматически сгенерирует это описание с текстом "Successful response".
- Если вдруг вы не укажете его, то **FastAPI** автоматически сгенерирует это описание с текстом "Successful response".
+///
-## Обозначение *операции пути* как устаревшей
+## Обозначение *операции пути* как устаревшей { #deprecate-a-path-operation }
-Если вам необходимо пометить *операцию пути* как устаревшую, при этом не удаляя её, передайте параметр `deprecated`:
+Если вам необходимо пометить *операцию пути* как устаревшую, при этом не удаляя её, передайте параметр `deprecated`:
-```Python hl_lines="16"
-{!../../../docs_src/path_operation_configuration/tutorial006.py!}
-```
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
Он будет четко помечен как устаревший в интерактивной документации:
@@ -174,6 +102,6 @@
-## Резюме
+## Резюме { #recap }
Вы можете легко конфигурировать и добавлять метаданные в ваши *операции пути*, передавая параметры *декораторам операций пути*.
diff --git a/docs/ru/docs/tutorial/path-params-numeric-validations.md b/docs/ru/docs/tutorial/path-params-numeric-validations.md
index 0d034ef343897..34eeb80cb2f64 100644
--- a/docs/ru/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/ru/docs/tutorial/path-params-numeric-validations.md
@@ -1,113 +1,50 @@
-# Path-параметры и валидация числовых данных
+# Path-параметры и валидация числовых данных { #path-parameters-and-numeric-validations }
Так же, как с помощью `Query` вы можете добавлять валидацию и метаданные для query-параметров, так и с помощью `Path` вы можете добавлять такую же валидацию и метаданные для path-параметров.
-## Импорт Path
+## Импорт `Path` { #import-path }
Сначала импортируйте `Path` из `fastapi`, а также импортируйте `Annotated`:
-=== "Python 3.10+"
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+/// info | Информация
-=== "Python 3.9+"
+Поддержка `Annotated` была добавлена в FastAPI начиная с версии 0.95.0 (и с этой версии рекомендуется использовать этот подход).
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+Если вы используете более старую версию, вы столкнётесь с ошибками при попытке использовать `Annotated`.
-=== "Python 3.6+"
+Убедитесь, что вы [обновили версию FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions) как минимум до 0.95.1 перед тем, как использовать `Annotated`.
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+///
-=== "Python 3.10+ без Annotated"
-
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+ без Annotated"
-
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
-
-!!! info "Информация"
- Поддержка `Annotated` была добавлена в FastAPI начиная с версии 0.95.0 (и с этой версии рекомендуется использовать этот подход).
-
- Если вы используете более старую версию, вы столкнётесь с ошибками при попытке использовать `Annotated`.
-
- Убедитесь, что вы [обновили версию FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} как минимум до 0.95.1 перед тем, как использовать `Annotated`.
-
-## Определите метаданные
+## Определите метаданные { #declare-metadata }
Вы можете указать все те же параметры, что и для `Query`.
Например, чтобы указать значение метаданных `title` для path-параметра `item_id`, вы можете написать:
-=== "Python 3.10+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *}
-=== "Python 3.6+"
+/// note | Примечание
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+Path-параметр всегда является обязательным, поскольку он должен быть частью пути. Даже если вы объявите его как `None` или зададите значение по умолчанию, это ни на что не повлияет — параметр всё равно будет обязательным.
-=== "Python 3.10+ без Annotated"
+///
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+## Задайте нужный вам порядок параметров { #order-the-parameters-as-you-need }
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+/// tip | Подсказка
-=== "Python 3.6+ без Annotated"
+Это не имеет большого значения, если вы используете `Annotated`.
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
-
-!!! note "Примечание"
- Path-параметр всегда является обязательным, поскольку он составляет часть пути.
-
- Поэтому следует объявить его с помощью `...`, чтобы обозначить, что этот параметр обязательный.
-
- Тем не менее, даже если вы объявите его как `None` или установите для него значение по умолчанию, это ни на что не повлияет и параметр останется обязательным.
-
-## Задайте нужный вам порядок параметров
-
-!!! tip "Подсказка"
- Это не имеет большого значения, если вы используете `Annotated`.
+///
Допустим, вы хотите объявить query-параметр `q` как обязательный параметр типа `str`.
И если вам больше ничего не нужно указывать для этого параметра, то нет необходимости использовать `Query`.
-Но вам по-прежнему нужно использовать `Path` для path-параметра `item_id`. И если по какой-либо причине вы не хотите использовать `Annotated`, то могут возникнуть небольшие сложности.
+Но вам по-прежнему нужно использовать `Path` для path-параметра `item_id`. И по какой-либо причине вы не хотите использовать `Annotated`.
Если вы поместите параметр со значением по умолчанию перед другим параметром, у которого нет значения по умолчанию, то Python укажет на ошибку.
@@ -117,33 +54,19 @@
Поэтому вы можете определить функцию так:
-=== "Python 3.6 без Annotated"
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+Но имейте в виду, что если вы используете `Annotated`, вы не столкнётесь с этой проблемой, так как вы не используете значения по умолчанию параметров функции для `Query()` или `Path()`.
- ```Python hl_lines="7"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
- ```
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
-Но имейте в виду, что если вы используете `Annotated`, вы не столкнётесь с этой проблемой, так как вы не используете `Query()` или `Path()` в качестве значения по умолчанию для параметра функции.
+## Задайте нужный вам порядок параметров, полезные приёмы { #order-the-parameters-as-you-need-tricks }
-=== "Python 3.9+"
+/// tip | Подсказка
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!}
- ```
+Это не имеет большого значения, если вы используете `Annotated`.
-=== "Python 3.6+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!}
- ```
-
-## Задайте нужный вам порядок параметров, полезные приёмы
-
-!!! tip "Подсказка"
- Это не имеет большого значения, если вы используете `Annotated`.
+///
Здесь описан **небольшой приём**, который может оказаться удобным, хотя часто он вам не понадобится.
@@ -158,117 +81,48 @@
Передайте `*` в качестве первого параметра функции.
-Python не будет ничего делать с `*`, но он будет знать, что все следующие параметры являются именованными аргументами (парами ключ-значение), также известными как kwargs, даже если у них нет значений по умолчанию.
-
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
-```
-
-### Лучше с `Annotated`
+Python не будет ничего делать с `*`, но он будет знать, что все следующие параметры являются именованными аргументами (парами ключ-значение), также известными как kwargs, даже если у них нет значений по умолчанию.
-Имейте в виду, что если вы используете `Annotated`, то, поскольку вы не используете значений по умолчанию для параметров функции, то у вас не возникнет подобной проблемы и вам не придётся использовать `*`.
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
-=== "Python 3.9+"
+### Лучше с `Annotated` { #better-with-annotated }
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!}
- ```
+Имейте в виду, что если вы используете `Annotated`, то, поскольку вы не используете значений по умолчанию для параметров функции, у вас не возникнет подобной проблемы и вам, вероятно, не придётся использовать `*`.
-=== "Python 3.6+"
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!}
- ```
-
-## Валидация числовых данных: больше или равно
+## Валидация числовых данных: больше или равно { #number-validations-greater-than-or-equal }
С помощью `Query` и `Path` (и других классов, которые мы разберём позже) вы можете добавлять ограничения для числовых данных.
-В этом примере при указании `ge=1`, параметр `item_id` должен быть больше или равен `1` ("`g`reater than or `e`qual").
-
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!}
- ```
-
-=== "Python 3.6+ без Annotated"
+В этом примере при указании `ge=1`, параметр `item_id` должен быть целым числом "`g`reater than or `e`qual" — больше или равно `1`.
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!}
- ```
-
-## Валидация числовых данных: больше и меньше или равно
+## Валидация числовых данных: больше и меньше или равно { #number-validations-greater-than-and-less-than-or-equal }
То же самое применимо к:
* `gt`: больше (`g`reater `t`han)
* `le`: меньше или равно (`l`ess than or `e`qual)
-=== "Python 3.9+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!}
- ```
-
-=== "Python 3.6+ без Annotated"
-
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
- ```Python hl_lines="9"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!}
- ```
-
-## Валидация числовых данных: числа с плавающей точкой, больше и меньше
+## Валидация числовых данных: числа с плавающей точкой, больше и меньше { #number-validations-floats-greater-than-and-less-than }
Валидация также применима к значениям типа `float`.
-В этом случае становится важной возможность добавить ограничение gt, вместо ge, поскольку в таком случае вы можете, например, создать ограничение, чтобы значение было больше `0`, даже если оно меньше `1`.
+В этом случае становится важной возможность добавить ограничение gt, вместо ge, поскольку в таком случае вы можете, например, создать ограничение, чтобы значение было больше `0`, даже если оно меньше `1`.
Таким образом, `0.5` будет корректным значением. А `0.0` или `0` — нет.
-То же самое справедливо и для lt.
-
-=== "Python 3.9+"
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!}
- ```
-
-=== "Python 3.6+ без Annotated"
+То же самое справедливо и для lt.
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!}
- ```
+## Резюме { #recap }
-## Резюме
-
-С помощью `Query`, `Path` (и других классов, которые мы пока не затронули) вы можете добавлять метаданные и строковую валидацию тем же способом, как и в главе [Query-параметры и валидация строк](query-params-str-validations.md){.internal-link target=_blank}.
+С помощью `Query`, `Path` (и других классов, которые мы пока не затронули) вы можете добавлять метаданные и строковую валидацию тем же способом, как и в главе [Query-параметры и валидация строк](query-params-str-validations.md).
А также вы можете добавить валидацию числовых данных:
@@ -277,16 +131,22 @@ Python не будет ничего делать с `*`, но он будет з
* `lt`: меньше (`l`ess `t`han)
* `le`: меньше или равно (`l`ess than or `e`qual)
-!!! info "Информация"
- `Query`, `Path` и другие классы, которые мы разберём позже, являются наследниками общего класса `Param`.
+/// info | Информация
+
+`Query`, `Path` и другие классы, которые вы разберёте позже, являются наследниками общего класса `Param`.
+
+Все они используют те же параметры для дополнительной валидации и метаданных, которые вы видели ранее.
+
+///
+
+/// note | Технические детали
- Все они используют те же параметры для дополнительной валидации и метаданных, которые вы видели ранее.
+`Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов.
-!!! note "Технические детали"
- `Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов.
+Объект `Query`, который вы импортируете, является функцией. И при вызове она возвращает экземпляр одноимённого класса `Query`.
- Объект `Query`, который вы импортируете, является функцией. И при вызове она возвращает экземпляр одноимённого класса `Query`.
+Использование функций (вместо использования классов напрямую) нужно для того, чтобы ваш редактор не подсвечивал ошибки, связанные с их типами.
- Использование функций (вместо использования классов напрямую) нужно для того, чтобы ваш редактор не подсвечивал ошибки, связанные с их типами.
+Таким образом вы можете использовать привычный вам редактор и инструменты разработки, не добавляя дополнительных конфигураций для игнорирования подобных ошибок.
- Таким образом вы можете использовать привычный вам редактор и инструменты разработки, не добавляя дополнительных конфигураций для игнорирования подобных ошибок.
+///
diff --git a/docs/ru/docs/tutorial/path-params.md b/docs/ru/docs/tutorial/path-params.md
index 55b498ef0acd2..79343a1588ed5 100644
--- a/docs/ru/docs/tutorial/path-params.md
+++ b/docs/ru/docs/tutorial/path-params.md
@@ -1,105 +1,114 @@
-# Path-параметры
+# Path-параметры { #path-parameters }
Вы можете определить "параметры" или "переменные" пути, используя синтаксис форматированных строк Python:
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
Значение параметра пути `item_id` будет передано в функцию в качестве аргумента `item_id`.
-Если запустите этот пример и перейдёте по адресу: http://127.0.0.1:8000/items/foo, то увидите ответ:
+Если запустите этот пример и перейдёте по адресу: [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo), то увидите ответ:
```JSON
{"item_id":"foo"}
```
-## Параметры пути с типами
+## Параметры пути с типами { #path-parameters-with-types }
-Вы можете объявить тип параметра пути в функции, используя стандартные аннотации типов Python.
+Вы можете объявить тип параметра пути в функции, используя стандартные аннотации типов Python:
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
+{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}
Здесь, `item_id` объявлен типом `int`.
-!!! check "Заметка"
- Это обеспечит поддержку редактора внутри функции (проверка ошибок, автодополнение и т.п.).
+/// check | Заметка
+
+Это обеспечит поддержку редактора кода внутри функции (проверка ошибок, автозавершение и т.п.).
+
+///
-## Преобразование данных
+## Преобразование данных { #data-conversion }
-Если запустите этот пример и перейдёте по адресу: http://127.0.0.1:8000/items/3, то увидите ответ:
+Если запустите этот пример и перейдёте по адресу: [http://127.0.0.1:8000/items/3](http://127.0.0.1:8000/items/3), то увидите ответ:
```JSON
{"item_id":3}
```
-!!! check "Заметка"
- Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`.
+/// check | Заметка
- Используя определения типов, **FastAPI** выполняет автоматический "парсинг" запросов.
+Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`.
-## Проверка данных
+Используя такое объявление типов, **FastAPI** выполняет автоматический HTTP-запрос "парсинг".
-Если откроете браузер по адресу http://127.0.0.1:8000/items/foo, то увидите интересную HTTP-ошибку:
+///
+
+## Валидация данных { #data-validation }
+
+Если откроете браузер по адресу [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo), то увидите интересную HTTP-ошибку:
```JSON
{
- "detail": [
- {
- "loc": [
- "path",
- "item_id"
- ],
- "msg": "value is not a valid integer",
- "type": "type_error.integer"
- }
- ]
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo"
+ }
+ ]
}
```
-из-за того, что параметр пути `item_id` имеет значение `"foo"`, которое не является типом `int`.
+из-за того, что параметр пути `item_id` имеет значение `"foo"`, которое не является типом `int`.
+
+Та же ошибка возникнет, если вместо `int` передать `float`, например: [http://127.0.0.1:8000/items/4.2](http://127.0.0.1:8000/items/4.2)
-Та же ошибка возникнет, если вместо `int` передать `float` , например: http://127.0.0.1:8000/items/4.2
+/// check | Заметка
-!!! check "Заметка"
- **FastAPI** обеспечивает проверку типов, используя всё те же определения типов.
+**FastAPI** обеспечивает валидацию данных, используя всё те же определения типов.
- Обратите внимание, что в тексте ошибки явно указано место не прошедшее проверку.
+Обратите внимание, что в тексте ошибки явно указано место, не прошедшее проверку.
- Это очень полезно при разработке и отладке кода, который взаимодействует с API.
+Это очень полезно при разработке и отладке кода, который взаимодействует с API.
-## Документация
+///
-И теперь, когда откроете браузер по адресу: http://127.0.0.1:8000/docs, то увидите вот такую автоматически сгенерированную документацию API:
+## Документация { #documentation }
+
+И теперь, когда откроете браузер по адресу: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs), то увидите вот такую автоматически сгенерированную документацию API:
-!!! check "Заметка"
- Ещё раз, просто используя определения типов, **FastAPI** обеспечивает автоматическую интерактивную документацию (с интеграцией Swagger UI).
+/// check | Заметка
+
+Ещё раз, просто используя определения типов, **FastAPI** обеспечивает автоматическую интерактивную документацию (с интеграцией Swagger UI).
+
+Обратите внимание, что параметр пути объявлен целочисленным.
- Обратите внимание, что параметр пути объявлен целочисленным.
+///
-## Преимущества стандартизации, альтернативная документация
+## Преимущества стандартизации, альтернативная документация { #standards-based-benefits-alternative-documentation }
-Поскольку сгенерированная схема соответствует стандарту OpenAPI, её можно использовать со множеством совместимых инструментов.
+Поскольку сгенерированная схема соответствует стандарту [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md), её можно использовать со множеством совместимых инструментов.
-Именно поэтому, FastAPI сам предоставляет альтернативную документацию API (используя ReDoc), которую можно получить по адресу: http://127.0.0.1:8000/redoc.
+Именно поэтому, **FastAPI** сам предоставляет альтернативную документацию API (используя ReDoc), которую можно получить по адресу: [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc).
По той же причине, есть множество совместимых инструментов, включая инструменты генерации кода для многих языков.
-## Pydantic
+## Pydantic { #pydantic }
-Вся проверка данных выполняется под капотом с помощью Pydantic. Поэтому вы можете быть уверены в качестве обработки данных.
+Вся проверка данных выполняется под капотом с помощью [Pydantic](https://docs.pydantic.dev/), поэтому вы получаете все его преимущества. И вы можете быть уверены, что находитесь в надёжных руках.
Вы можете использовать в аннотациях как простые типы данных, вроде `str`, `float`, `bool`, так и более сложные типы.
Некоторые из них рассматриваются в следующих главах данного руководства.
-## Порядок имеет значение
+## Порядок имеет значение { #order-matters }
При создании *операций пути* можно столкнуться с ситуацией, когда путь является фиксированным.
@@ -109,26 +118,21 @@
Поскольку *операции пути* выполняются в порядке их объявления, необходимо, чтобы путь для `/users/me` был объявлен раньше, чем путь для `/users/{user_id}`:
-
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
-```
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
Иначе путь для `/users/{user_id}` также будет соответствовать `/users/me`, "подразумевая", что он получает параметр `user_id` со значением `"me"`.
Аналогично, вы не можете переопределить операцию с путем:
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003b.py!}
-```
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
Первый будет выполняться всегда, так как путь совпадает первым.
-## Предопределенные значения
+## Предопределенные значения { #predefined-values }
-Что если нам нужно заранее определить допустимые *параметры пути*, которые *операция пути* может принимать? В таком случае можно использовать стандартное перечисление `Enum` Python.
+Что если нам нужно заранее определить допустимые *параметры пути*, которые *операция пути* может принимать? В таком случае можно использовать стандартное перечисление `Enum` Python.
-### Создание класса `Enum`
+### Создание класса `Enum` { #create-an-enum-class }
Импортируйте `Enum` и создайте подкласс, который наследуется от `str` и `Enum`.
@@ -136,63 +140,56 @@
Затем создайте атрибуты класса с фиксированными допустимыми значениями:
-```Python hl_lines="1 6-9"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
+
+/// tip | Подсказка
-!!! info "Дополнительная информация"
- Перечисления (enum) доступны в Python начиная с версии 3.4.
+Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия моделей Машинного обучения.
-!!! tip "Подсказка"
- Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия моделей машинного обучения.
+///
-### Определение *параметра пути*
+### Определение *параметра пути* { #declare-a-path-parameter }
Определите *параметр пути*, используя в аннотации типа класс перечисления (`ModelName`), созданный ранее:
-```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
-### Проверьте документацию
+### Проверьте документацию { #check-the-docs }
Поскольку доступные значения *параметра пути* определены заранее, интерактивная документация может наглядно их отображать:
-### Работа с *перечислениями* в Python
+### Работа с *перечислениями* в Python { #working-with-python-enumerations }
Значение *параметра пути* будет *элементом перечисления*.
-#### Сравнение *элементов перечисления*
+#### Сравнение *элементов перечисления* { #compare-enumeration-members }
Вы можете сравнить это значение с *элементом перечисления* класса `ModelName`:
-```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}
-#### Получение *значения перечисления*
+#### Получение *значения перечисления* { #get-the-enumeration-value }
Можно получить фактическое значение (в данном случае - `str`) с помощью `model_name.value` или в общем случае `your_enum_member.value`:
-```Python hl_lines="20"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}
+
+/// tip | Подсказка
-!!! tip "Подсказка"
- Значение `"lenet"` также можно получить с помощью `ModelName.lenet.value`.
+Значение `"lenet"` также можно получить с помощью `ModelName.lenet.value`.
-#### Возврат *элементов перечисления*
+///
+
+#### Возврат *элементов перечисления* { #return-enumeration-members }
Из *операции пути* можно вернуть *элементы перечисления*, даже вложенные в тело JSON (например в `dict`).
Они будут преобразованы в соответствующие значения (в данном случае - строки) перед их возвратом клиенту:
-```Python hl_lines="18 21 23"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
-Вы отправите клиенту такой JSON-ответ:
+{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}
+На стороне клиента вы получите такой JSON-ответ:
```JSON
{
@@ -201,7 +198,7 @@
}
```
-## Path-параметры, содержащие пути
+## Path-параметры, содержащие пути { #path-parameters-containing-paths }
Предположим, что есть *операция пути* с путем `/files/{file_path}`.
@@ -209,7 +206,7 @@
Тогда URL для этого файла будет такой: `/files/home/johndoe/myfile.txt`.
-### Поддержка OpenAPI
+### Поддержка OpenAPI { #openapi-support }
OpenAPI не поддерживает способов объявления *параметра пути*, содержащего внутри *путь*, так как это может привести к сценариям, которые сложно определять и тестировать.
@@ -217,7 +214,7 @@ OpenAPI не поддерживает способов объявления *п
Документация по-прежнему будет работать, хотя и не добавит никакой информации о том, что параметр должен содержать путь.
-### Конвертер пути
+### Конвертер пути { #path-convertor }
Благодаря одной из опций Starlette, можете объявить *параметр пути*, содержащий *путь*, используя URL вроде:
@@ -229,22 +226,24 @@ OpenAPI не поддерживает способов объявления *п
Можете использовать так:
-```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
-```
+{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}
+
+/// tip | Подсказка
+
+Возможно, вам понадобится, чтобы параметр содержал `/home/johndoe/myfile.txt` с ведущим слэшем (`/`).
+
+В этом случае URL будет таким: `/files//home/johndoe/myfile.txt`, с двойным слэшем (`//`) между `files` и `home`.
-!!! tip "Подсказка"
- Возможно, вам понадобится, чтобы параметр содержал `/home/johndoe/myfile.txt` с ведущим слэшем (`/`).
+///
- В этом случае URL будет таким: `/files//home/johndoe/myfile.txt`, с двойным слэшем (`//`) между `files` и `home`.
+## Резюме { #recap }
-## Резюме
Используя **FastAPI** вместе со стандартными объявлениями типов Python (короткими и интуитивно понятными), вы получаете:
-* Поддержку редактора (проверку ошибок, автозаполнение и т.п.)
-* "Парсинг" данных
+* Поддержку редактора кода (проверку ошибок, автозавершение и т.п.)
+* "Парсинг" данных
* Валидацию данных
-* Автоматическую документацию API с указанием типов параметров.
+* Аннотации API и автоматическую документацию
И объявлять типы достаточно один раз.
diff --git a/docs/ru/docs/tutorial/query-param-models.md b/docs/ru/docs/tutorial/query-param-models.md
new file mode 100644
index 0000000000000..7f29740acc25f
--- /dev/null
+++ b/docs/ru/docs/tutorial/query-param-models.md
@@ -0,0 +1,68 @@
+# Модели Query-Параметров { #query-parameter-models }
+
+Если у вас есть группа связанных **query-параметров**, то вы можете объединить их в одну **Pydantic-модель**.
+
+Это позволит вам **переиспользовать модель** в **разных местах**, устанавливать валидаторы и метаданные, в том числе для сразу всех параметров, в одном месте. 😎
+
+/// note | Заметка
+
+Это поддерживается начиная с версии FastAPI `0.115.0`. 🤓
+
+///
+
+## Pydantic-Модель для Query-Параметров { #query-parameters-with-a-pydantic-model }
+
+Объявите нужные **query-параметры** в **Pydantic-модели**, а после аннотируйте параметр как `Query`:
+
+{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}
+
+**FastAPI извлечёт** данные соответствующие **каждому полю модели** из **query-параметров** запроса и выдаст вам объявленную Pydantic-модель заполненную ими.
+
+## Проверьте Сгенерированную Документацию { #check-the-docs }
+
+Вы можете посмотреть query-параметры в графическом интерфейсе сгенерированной документации по пути `/docs`:
+
+
+
-
-### Query-параметр со множеством значений по умолчанию
-
-Вы также можете указать тип `list` со списком значений по умолчанию на случай, если вам их не предоставят:
-
-=== "Python 3.9+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!}
- ```
+///
-=== "Python 3.6+"
+Интерактивная документация API обновится соответствующим образом и позволит передавать несколько значений:
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!}
- ```
-
-=== "Python 3.9+ без Annotated"
-
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!}
- ```
+
-=== "Python 3.6+ без Annotated"
+### Query-параметр - список / несколько значений со значением по умолчанию { #query-parameter-list-multiple-values-with-defaults }
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+Можно также определить значение по умолчанию как `list`, если ничего не передано:
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial012.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
-Если вы перейдёте по ссылке:
+Если вы перейдёте по адресу:
```
http://localhost:8000/items/
```
-значение по умолчанию для `q` будет: `["foo", "bar"]` и ответом для вас будет:
+значение по умолчанию для `q` будет: `["foo", "bar"]`, и ответом будет:
```JSON
{
@@ -637,126 +287,45 @@ http://localhost:8000/items/
}
```
-#### Использование `list`
-
-Вы также можете использовать `list` напрямую вместо `List[str]` (или `list[str]` в Python 3.9+):
-
-=== "Python 3.9+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!}
- ```
-
-=== "Python 3.6+ без Annotated"
-
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial013.py!}
- ```
-
-!!! note "Технические детали"
- Запомните, что в таком случае, FastAPI не будет проверять содержимое списка.
-
- Например, для List[int] список будет провалидирован (и задокументирован) на содержание только целочисленных элементов. Но для простого `list` такой проверки не будет.
+#### Просто `list` { #using-just-list }
-## Больше метаданных
+Можно использовать `list` напрямую вместо `list[str]`:
-Вы можете добавить больше информации об query-параметре.
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
-Указанная информация будет включена в генерируемую OpenAPI документацию и использована в пользовательском интерфейсе и внешних инструментах.
+/// note | Примечание
-!!! note "Технические детали"
- Имейте в виду, что разные инструменты могут иметь разные уровни поддержки OpenAPI.
+Имейте в виду, что в этом случае FastAPI не будет проверять содержимое списка.
- Некоторые из них могут не отображать (на данный момент) всю заявленную дополнительную информацию, хотя в большинстве случаев отсутствующая функция уже запланирована к разработке.
+Например, `list[int]` проверит (и задокументирует), что элементы списка — целые числа. А просто `list` — нет.
-Вы можете указать название query-параметра, используя параметр `title`:
+///
-=== "Python 3.10+"
+## Больше метаданных { #declare-more-metadata }
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!}
- ```
+Можно добавить больше информации о параметре.
-=== "Python 3.9+"
+Эта информация будет включена в сгенерированную OpenAPI-схему и использована интерфейсами документации и внешними инструментами.
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!}
- ```
+/// note | Примечание
-=== "Python 3.6+"
+Помните, что разные инструменты могут иметь разный уровень поддержки OpenAPI.
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!}
- ```
+Некоторые из них пока могут не показывать всю дополнительную информацию, хотя в большинстве случаев недостающая возможность уже запланирована к разработке.
-=== "Python 3.10+ без Annotated"
+///
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+Можно задать `title`:
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *}
-=== "Python 3.6+ без Annotated"
+И `description`:
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *}
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial007.py!}
- ```
+## Псевдонимы параметров { #alias-parameters }
-Добавить описание, используя параметр `description`:
-
-=== "Python 3.10+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="15"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!}
- ```
-
-=== "Python 3.10+ без Annotated"
-
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!}
- ```
-
-=== "Python 3.6+ без Annotated"
-
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/query_params_str_validations/tutorial008.py!}
- ```
-
-## Псевдонимы параметров
-
-Представьте, что вы хотите использовать query-параметр с названием `item-query`.
+Представьте, что вы хотите, чтобы параметр назывался `item-query`.
Например:
@@ -764,156 +333,117 @@ http://localhost:8000/items/
http://127.0.0.1:8000/items/?item-query=foobaritems
```
-Но `item-query` является невалидным именем переменной в Python.
-
-Наиболее похожее валидное имя `item_query`.
+Но `item-query` — недопустимое имя переменной в Python.
-Но вам всё равно необходим `item-query`...
+Ближайший вариант — `item_query`.
-Тогда вы можете объявить `псевдоним`, и этот псевдоним будет использоваться для поиска значения параметра запроса:
+Но вам всё равно нужно именно `item-query`...
-=== "Python 3.10+"
+Тогда можно объявить `alias`, и этот псевдоним будет использован для поиска значения параметра:
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *}
-=== "Python 3.9+"
+## Маркировка параметров как устаревших { #deprecating-parameters }
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!}
- ```
+Предположим, этот параметр вам больше не нравится.
-=== "Python 3.6+"
+Его нужно оставить на какое‑то время, так как клиенты его используют, но вы хотите, чтобы в документации он явно отображался как устаревший.
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!}
- ```
+Тогда передайте параметр `deprecated=True` в `Query`:
-=== "Python 3.10+ без Annotated"
+{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *}
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+В документации это будет показано так:
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!}
- ```
-
-=== "Python 3.6+ без Annotated"
+
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+## Исключить параметры из OpenAPI { #exclude-parameters-from-openapi }
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params_str_validations/tutorial009.py!}
- ```
+Чтобы исключить query-параметр из генерируемой OpenAPI-схемы (и, следовательно, из систем автоматической документации), укажите у `Query` параметр `include_in_schema=False`:
-## Устаревшие параметры
+{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *}
-Предположим, вы больше не хотите использовать какой-либо параметр.
+## Кастомная валидация { #custom-validation }
-Вы решили оставить его, потому что клиенты всё ещё им пользуются. Но вы хотите отобразить это в документации как устаревший функционал.
+Бывают случаи, когда нужна **кастомная валидация**, которую нельзя выразить параметрами выше.
-Тогда для `Query` укажите параметр `deprecated=True`:
+В таких случаях можно использовать **кастомную функцию-валидатор**, которая применяется после обычной валидации (например, после проверки, что значение — это `str`).
-=== "Python 3.10+"
+Этого можно добиться, используя [`AfterValidator` Pydantic](https://docs.pydantic.dev/latest/concepts/validators/#field-after-validator) внутри `Annotated`.
- ```Python hl_lines="19"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!}
- ```
+/// tip | Совет
-=== "Python 3.9+"
+В Pydantic также есть [`BeforeValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-before-validator) и другие. 🤓
- ```Python hl_lines="19"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!}
- ```
+///
-=== "Python 3.6+"
+Например, эта кастомная проверка убеждается, что ID элемента начинается с `isbn-` для номера книги ISBN или с `imdb-` для ID URL фильма на IMDB:
- ```Python hl_lines="20"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
-=== "Python 3.10+ без Annotated"
+/// info | Дополнительная информация
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+Это доступно в Pydantic версии 2 и выше. 😎
- ```Python hl_lines="17"
- {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!}
- ```
+///
-=== "Python 3.6+ без Annotated"
+/// tip | Совет
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+Если вам нужна валидация, требующая общения с каким‑либо **внешним компонентом** — базой данных или другим API — вместо этого используйте **Зависимости FastAPI**, вы познакомитесь с ними позже.
- ```Python hl_lines="18"
- {!> ../../../docs_src/query_params_str_validations/tutorial010.py!}
- ```
+Эти кастомные валидаторы предназначены для проверок, которые можно выполнить, имея **только** те же **данные**, что пришли в запросе.
-В документации это будет отображено следующим образом:
+///
-
+### Понимание этого кода { #understand-that-code }
-## Исключить из OpenAPI
+Важный момент — это использовать **`AfterValidator` с функцией внутри `Annotated`**. Смело пропускайте эту часть. 🤸
-Чтобы исключить query-параметр из генерируемой OpenAPI схемы (а также из системы автоматической генерации документации), укажите в `Query` параметр `include_in_schema=False`:
+---
-=== "Python 3.10+"
+Но если вам любопытен именно этот пример и всё ещё интересно, вот немного подробностей.
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!}
- ```
+#### Строка и `value.startswith()` { #string-with-value-startswith }
-=== "Python 3.9+"
+Заметили? Метод строки `value.startswith()` может принимать кортеж — тогда будет проверено каждое значение из кортежа:
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *}
-=== "Python 3.6+"
+#### Случайный элемент { #a-random-item }
- ```Python hl_lines="11"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!}
- ```
+С помощью `data.items()` мы получаем итерируемый объект с кортежами, содержащими ключ и значение для каждого элемента словаря.
-=== "Python 3.10+ без Annotated"
+Мы превращаем этот итерируемый объект в обычный `list` через `list(data.items())`.
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+Затем с `random.choice()` можно получить **случайное значение** из списка — то есть кортеж вида `(id, name)`. Это будет что‑то вроде `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")`.
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!}
- ```
+После этого мы **присваиваем эти два значения** кортежа переменным `id` и `name`.
-=== "Python 3.6+ без Annotated"
+Так что, если пользователь не передал ID элемента, он всё равно получит случайную рекомендацию.
- !!! tip "Подсказка"
- Рекомендуется использовать версию с `Annotated` если возможно.
+...и всё это в **одной простой строке**. 🤯 Разве не прекрасен Python? 🐍
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params_str_validations/tutorial014.py!}
- ```
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *}
-## Резюме
+## Резюме { #recap }
-Вы можете объявлять дополнительные правила валидации и метаданные для ваших параметров запроса.
+Вы можете объявлять дополнительные проверки и метаданные для параметров.
-Общие метаданные:
+Общие метаданные и настройки:
* `alias`
* `title`
* `description`
* `deprecated`
-* `include_in_schema`
-Специфичные правила валидации для строк:
+Проверки, специфичные для строк:
* `min_length`
* `max_length`
-* `regex`
+* `pattern`
+
+Кастомные проверки с использованием `AfterValidator`.
-В рассмотренных примерах показано объявление правил валидации для строковых значений `str`.
+В этих примерах вы видели, как объявлять проверки для значений типа `str`.
-В следующих главах вы увидете, как объявлять правила валидации для других типов (например, чисел).
+Смотрите следующие главы, чтобы узнать, как объявлять проверки для других типов, например чисел.
diff --git a/docs/ru/docs/tutorial/query-params.md b/docs/ru/docs/tutorial/query-params.md
index 68333ec56604c..99f2a98aeb9fd 100644
--- a/docs/ru/docs/tutorial/query-params.md
+++ b/docs/ru/docs/tutorial/query-params.md
@@ -1,10 +1,8 @@
-# Query-параметры
+# Query-параметры { #query-parameters }
-Когда вы объявляете параметры функции, которые не являются параметрами пути, они автоматически интерпретируются как "query"-параметры.
+Когда вы объявляете параметры функции, которые не являются параметрами пути, они автоматически интерпретируются как "query"-параметры.
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial001.py!}
-```
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
Query-параметры представляют из себя набор пар ключ-значение, которые идут после знака `?` в URL-адресе, разделенные символами `&`.
@@ -21,16 +19,16 @@ http://127.0.0.1:8000/items/?skip=0&limit=10
Будучи частью URL-адреса, они "по умолчанию" являются строками.
-Но когда вы объявляете их с использованием аннотаций (в примере выше, как `int`), они конвертируются в указанный тип данных и проходят проверку на соответствие ему.
+Но когда вы объявляете их с использованием типов Python (в примере выше, как `int`), они конвертируются в указанный тип данных и проходят проверку на соответствие ему.
Все те же правила, которые применяются к path-параметрам, также применяются и query-параметрам:
* Поддержка от редактора кода (очевидно)
-* "Парсинг" данных
+* "Парсинг" данных
* Проверка на соответствие данных (Валидация)
* Автоматическая документация
-## Значения по умолчанию
+## Значения по умолчанию { #defaults }
Поскольку query-параметры не являются фиксированной частью пути, они могут быть не обязательными и иметь значения по умолчанию.
@@ -59,42 +57,25 @@ http://127.0.0.1:8000/items/?skip=20
* `skip=20`: потому что вы установили это в URL-адресе
* `limit=10`: т.к это было значение по умолчанию
-## Необязательные параметры
+## Необязательные параметры { #optional-parameters }
Аналогично, вы можете объявлять необязательные query-параметры, установив их значение по умолчанию, равное `None`:
-=== "Python 3.10+"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial002_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial002.py!}
- ```
+{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *}
В этом случае, параметр `q` будет не обязательным и будет иметь значение `None` по умолчанию.
-!!! Важно
- Также обратите внимание, что **FastAPI** достаточно умён чтобы заметить, что параметр `item_id` является path-параметром, а `q` нет, поэтому, это параметр запроса.
+/// check | Важно
-## Преобразование типа параметра запроса
+Также обратите внимание, что **FastAPI** достаточно умён чтобы заметить, что параметр `item_id` является path-параметром, а `q` нет, поэтому, это параметр запроса.
-Вы также можете объявлять параметры с типом `bool`, которые будут преобразованы соответственно:
+///
-=== "Python 3.10+"
+## Преобразование типа параметра запроса { #query-parameter-type-conversion }
- ```Python hl_lines="7"
- {!> ../../../docs_src/query_params/tutorial003_py310.py!}
- ```
-
-=== "Python 3.6+"
+Вы также можете объявлять параметры с типом `bool`, которые будут преобразованы соответственно:
- ```Python hl_lines="9"
- {!> ../../../docs_src/query_params/tutorial003.py!}
- ```
+{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *}
В этом случае, если вы сделаете запрос:
@@ -128,38 +109,25 @@ http://127.0.0.1:8000/items/foo?short=yes
или в любом другом варианте написания (в верхнем регистре, с заглавной буквой, и т.п), внутри вашей функции параметр `short` будет иметь значение `True` типа данных `bool` . В противном случае - `False`.
+## Смешивание query-параметров и path-параметров { #multiple-path-and-query-parameters }
-## Смешивание query-параметров и path-параметров
-
-Вы можете объявлять несколько query-параметров и path-параметров одновременно,**FastAPI** сам разберётся, что чем является.
+Вы можете объявлять несколько query-параметров и path-параметров одновременно, **FastAPI** сам разберётся, что чем является.
И вы не обязаны объявлять их в каком-либо определенном порядке.
Они будут обнаружены по именам:
-=== "Python 3.10+"
-
- ```Python hl_lines="6 8"
- {!> ../../../docs_src/query_params/tutorial004_py310.py!}
- ```
+{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *}
-=== "Python 3.6+"
+## Обязательные query-параметры { #required-query-parameters }
- ```Python hl_lines="8 10"
- {!> ../../../docs_src/query_params/tutorial004.py!}
- ```
-
-## Обязательные query-параметры
-
-Когда вы объявляете значение по умолчанию для параметра, который не является path-параметром (в этом разделе, мы пока что познакомились только с path-параметрами), то это значение не является обязательным.
+Когда вы объявляете значение по умолчанию для параметра, который не является path-параметром (в этом разделе мы пока что рассмотрели только query-параметры), то он не является обязательным.
Если вы не хотите задавать конкретное значение, но хотите сделать параметр необязательным, вы можете установить значение по умолчанию равным `None`.
Но если вы хотите сделать query-параметр обязательным, вы можете просто не указывать значение по умолчанию:
-```Python hl_lines="6-7"
-{!../../../docs_src/query_params/tutorial005.py!}
-```
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
Здесь параметр запроса `needy` является обязательным параметром с типом данных `str`.
@@ -173,16 +141,17 @@ http://127.0.0.1:8000/items/foo-item
```JSON
{
- "detail": [
- {
- "loc": [
- "query",
- "needy"
- ],
- "msg": "field required",
- "type": "value_error.missing"
- }
- ]
+ "detail": [
+ {
+ "type": "missing",
+ "loc": [
+ "query",
+ "needy"
+ ],
+ "msg": "Field required",
+ "input": null
+ }
+ ]
}
```
@@ -201,19 +170,9 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
}
```
-Конечно, вы можете определить некоторые параметры как обязательные, некоторые - со значением по умполчанию, а некоторые - полностью необязательные:
-
-=== "Python 3.10+"
+Конечно, вы можете определить некоторые параметры как обязательные, некоторые — со значением по умолчанию, а некоторые — полностью необязательные:
- ```Python hl_lines="8"
- {!> ../../../docs_src/query_params/tutorial006_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/query_params/tutorial006.py!}
- ```
+{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *}
В этом примере, у нас есть 3 параметра запроса:
@@ -221,5 +180,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
* `skip`, типа `int` и со значением по умолчанию `0`.
* `limit`, необязательный `int`.
-!!! подсказка
- Вы можете использовать класс `Enum` также, как ранее применяли его с [Path-параметрами](path-params.md#predefined-values){.internal-link target=_blank}.
+/// tip | Подсказка
+
+Вы можете использовать класс `Enum` также, как ранее применяли его с [Path-параметрами](path-params.md#predefined-values).
+
+///
diff --git a/docs/ru/docs/tutorial/request-files.md b/docs/ru/docs/tutorial/request-files.md
new file mode 100644
index 0000000000000..e8500adbac784
--- /dev/null
+++ b/docs/ru/docs/tutorial/request-files.md
@@ -0,0 +1,177 @@
+# Загрузка файлов { #request-files }
+
+Используя класс `File`, мы можем позволить клиентам загружать файлы.
+
+/// info | Дополнительная информация
+
+Чтобы получать загруженные файлы, сначала установите [`python-multipart`](https://github.com/Kludex/python-multipart).
+
+Убедитесь, что вы создали [виртуальное окружение](../virtual-environments.md), активировали его, а затем установили пакет, например:
+
+```console
+$ pip install python-multipart
+```
+
+Это связано с тем, что загружаемые файлы передаются как "данные формы".
+
+///
+
+## Импорт `File` { #import-file }
+
+Импортируйте `File` и `UploadFile` из модуля `fastapi`:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
+
+## Определите параметры `File` { #define-file-parameters }
+
+Создайте параметры `File` так же, как вы это делаете для `Body` или `Form`:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
+
+/// info | Дополнительная информация
+
+`File` - это класс, который наследуется непосредственно от `Form`.
+
+Но помните, что когда вы импортируете `Query`, `Path`, `File` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы.
+
+///
+
+/// tip | Подсказка
+
+Для объявления тела файла необходимо использовать `File`, поскольку в противном случае параметры будут интерпретироваться как параметры запроса или параметры тела (JSON).
+
+///
+
+Файлы будут загружены как данные формы.
+
+Если вы объявите тип параметра у *функции операции пути* как `bytes`, то **FastAPI** прочитает файл за вас, и вы получите его содержимое в виде `bytes`.
+
+Следует иметь в виду, что все содержимое будет храниться в памяти. Это хорошо подходит для небольших файлов.
+
+Однако возможны случаи, когда использование `UploadFile` может оказаться полезным.
+
+## Параметры файла с `UploadFile` { #file-parameters-with-uploadfile }
+
+Определите параметр файла с типом `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
+
+Использование `UploadFile` имеет ряд преимуществ перед `bytes`:
+
+* Использовать `File()` в значении параметра по умолчанию не обязательно.
+* При этом используется "буферный" файл:
+ * Файл, хранящийся в памяти до максимального предела размера, после преодоления которого он будет храниться на диске.
+* Это означает, что он будет хорошо работать с большими файлами, такими как изображения, видео, большие бинарные файлы и т.д., не потребляя при этом всю память.
+* Из загруженного файла можно получить метаданные.
+* Он реализует [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) `async` интерфейс.
+* Он предоставляет реальный объект Python [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile), который вы можете передать непосредственно другим библиотекам, которые ожидают файл в качестве объекта.
+
+### `UploadFile` { #uploadfile }
+
+`UploadFile` имеет следующие атрибуты:
+
+* `filename`: Строка `str` с исходным именем файла, который был загружен (например, `myimage.jpg`).
+* `content_type`: Строка `str` с типом содержимого (MIME type / media type) (например, `image/jpeg`).
+* `file`: [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) (a [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) объект). Это фактический файл Python, который можно передавать непосредственно другим функциям или библиотекам, ожидающим файл в качестве объекта.
+
+`UploadFile` имеет следующие методы `async`. Все они вызывают соответствующие файловые методы (используя внутренний `SpooledTemporaryFile`).
+
+* `write(data)`: Записать данные `data` (`str` или `bytes`) в файл.
+* `read(size)`: Прочитать количество `size` (`int`) байт/символов из файла.
+* `seek(offset)`: Перейти к байту на позиции `offset` (`int`) в файле.
+ * Например, `await myfile.seek(0)` перейдет к началу файла.
+ * Это особенно удобно, если вы один раз выполнили команду `await myfile.read()`, а затем вам нужно прочитать содержимое файла еще раз.
+* `close()`: Закрыть файл.
+
+Поскольку все эти методы являются `async` методами, вам следует использовать "await" вместе с ними.
+
+Например, внутри `async` *функции операции пути* можно получить содержимое с помощью:
+
+```Python
+contents = await myfile.read()
+```
+
+Если вы находитесь внутри обычной `def` *функции операции пути*, можно получить прямой доступ к файлу `UploadFile.file`, например:
+
+```Python
+contents = myfile.file.read()
+```
+
+
+/// note | Технические детали `async`
+
+При использовании методов `async` **FastAPI** запускает файловые методы в пуле потоков и ожидает их.
+
+///
+
+/// note | Технические детали Starlette
+
+**FastAPI** наследует `UploadFile` непосредственно из **Starlette**, но добавляет некоторые детали для совместимости с **Pydantic** и другими частями FastAPI.
+
+///
+
+## Что такое «данные формы» { #what-is-form-data }
+
+Способ, которым HTML-формы (``) отправляют данные на сервер, обычно использует "специальную" кодировку для этих данных, отличную от JSON.
+
+**FastAPI** позаботится о том, чтобы считать эти данные из нужного места, а не из JSON.
+
+/// note | Технические детали
+
+Данные из форм обычно кодируются с использованием "media type" `application/x-www-form-urlencoded` когда он не включает файлы.
+
+Но когда форма включает файлы, она кодируется как `multipart/form-data`. Если вы используете `File`, **FastAPI** будет знать, что ему нужно получить файлы из нужной части тела.
+
+Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке [MDN web docs for `POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST).
+
+///
+
+/// warning | Внимание
+
+В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`.
+
+Это не является ограничением **FastAPI**, это часть протокола HTTP.
+
+///
+
+## Необязательная загрузка файлов { #optional-file-upload }
+
+Вы можете сделать загрузку файла необязательной, используя стандартные аннотации типов и установив значение по умолчанию `None`:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## `UploadFile` с дополнительными метаданными { #uploadfile-with-additional-metadata }
+
+Вы также можете использовать `File()` вместе с `UploadFile`, например, для установки дополнительных метаданных:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
+
+## Загрузка нескольких файлов { #multiple-file-uploads }
+
+Можно одновременно загружать несколько файлов.
+
+Они будут связаны с одним и тем же "полем формы", отправляемым с помощью данных формы.
+
+Для этого необходимо объявить список `bytes` или `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
+
+Вы получите, как и было объявлено, список `list` из `bytes` или `UploadFile`.
+
+/// note | Технические детали
+
+Можно также использовать `from starlette.responses import HTMLResponse`.
+
+**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette.
+
+///
+
+### Загрузка нескольких файлов с дополнительными метаданными { #multiple-file-uploads-with-additional-metadata }
+
+Так же, как и раньше, вы можете использовать `File()` для задания дополнительных параметров, даже для `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
+
+## Резюме { #recap }
+
+Используйте `File`, `bytes` и `UploadFile` для работы с файлами, которые будут загружаться и передаваться в виде данных формы.
diff --git a/docs/ru/docs/tutorial/request-form-models.md b/docs/ru/docs/tutorial/request-form-models.md
new file mode 100644
index 0000000000000..c7f37c2baf549
--- /dev/null
+++ b/docs/ru/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Модели форм { #form-models }
+
+Вы можете использовать **Pydantic-модели** для объявления **полей формы** в FastAPI.
+
+/// info | Дополнительная информация
+
+Чтобы использовать формы, сначала установите [`python-multipart`](https://github.com/Kludex/python-multipart).
+
+Убедитесь, что вы создали и активировали [виртуальное окружение](../virtual-environments.md), а затем установите пакет, например:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | Заметка
+
+Этот функционал доступен начиная с версии FastAPI `0.113.0`. 🤓
+
+///
+
+## Pydantic-модели для форм { #pydantic-models-for-forms }
+
+Вам просто нужно объявить **Pydantic-модель** с полями, которые вы хотите получить как **поля формы**, а затем объявить параметр как `Form`:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
+
+**FastAPI** **извлечёт** данные для **каждого поля** из **данных формы** в запросе и выдаст вам объявленную Pydantic-модель.
+
+## Проверьте документацию { #check-the-docs }
+
+Вы можете проверить это в интерфейсе документации по адресу `/docs`:
+
+
+
-И также обе модели будут использованы в интерактивной документации API:
+И обе модели будут использоваться в интерактивной документации API:
-## Другие аннотации типов
+## Другие аннотации возвращаемых типов { #other-return-type-annotations }
-Бывают случаи, когда вы возвращаете что-то, что не является валидным типом для Pydantic и вы указываете аннотацию ответа функции только для того, чтобы работала поддержка различных инструментов (редактор кода, mypy и др.).
+Бывают случаи, когда вы возвращаете что-то, что не является валидным полем Pydantic, и аннотируете это в функции только ради поддержки инструментов (редактор кода, mypy и т.д.).
-### Возвращаем Response
+### Возврат Response напрямую { #return-a-response-directly }
-Самый частый сценарий использования - это [возвращать Response напрямую, как описано в расширенной документации](../advanced/response-directly.md){.internal-link target=_blank}.
+Самый распространённый случай — [возвращать Response напрямую, как описано далее в разделах документации для продвинутых](../advanced/response-directly.md).
-```Python hl_lines="8 10-11"
-{!> ../../../docs_src/response_model/tutorial003_02.py!}
-```
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
-Это поддерживается FastAPI по-умолчанию, т.к. аннотация проставлена в классе (или подклассе) `Response`.
+Этот простой случай обрабатывается FastAPI автоматически, потому что аннотация возвращаемого типа — это класс (или подкласс) `Response`.
-И ваши помощники разработки также будут счастливы, т.к. оба класса `RedirectResponse` и `JSONResponse` являются подклассами `Response`. Таким образом мы получаем корректную аннотацию типа.
+И инструменты тоже будут довольны, потому что и `RedirectResponse`, и `JSONResponse` являются подклассами `Response`, так что аннотация типа корректна.
-### Подкласс Response в аннотации типа
+### Аннотировать подкласс Response { #annotate-a-response-subclass }
-Вы также можете указать подкласс `Response` в аннотации типа:
+Вы также можете использовать подкласс `Response` в аннотации типа:
-```Python hl_lines="8-9"
-{!> ../../../docs_src/response_model/tutorial003_03.py!}
-```
-
-Это сработает, потому что `RedirectResponse` является подклассом `Response` и FastAPI автоматически обработает этот простейший случай.
-
-### Некорректные аннотации типов
-
-Но когда вы возвращаете какой-либо другой произвольный объект, который не является допустимым типом Pydantic (например, объект из базы данных), и вы аннотируете его подобным образом для функции, FastAPI попытается создать из этого типа модель Pydantic и потерпит неудачу.
-
-То же самое произошло бы, если бы у вас было что-то вроде Union различных типов и один или несколько из них не являлись бы допустимыми типами для Pydantic. Например, такой вариант приведет к ошибке 💥:
-
-=== "Python 3.10+"
-
- ```Python hl_lines="8"
- {!> ../../../docs_src/response_model/tutorial003_04_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="10"
- {!> ../../../docs_src/response_model/tutorial003_04.py!}
- ```
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
-...такой код вызовет ошибку, потому что в аннотации указан неподдерживаемый Pydantic тип. А также этот тип не является классом или подклассом `Response`.
+Это тоже сработает, так как `RedirectResponse` — подкласс `Response`, и FastAPI автоматически обработает этот простой случай.
-### Возможно ли отключить генерацию модели ответа?
+### Некорректные аннотации возвращаемых типов { #invalid-return-type-annotations }
-Продолжим рассматривать предыдущий пример. Допустим, что вы хотите отказаться от автоматической валидации ответа, документации, фильтрации и т.д.
+Но когда вы возвращаете произвольный объект, не являющийся валидным типом Pydantic (например, объект базы данных), и аннотируете его таким образом в функции, FastAPI попытается создать модель ответа Pydantic из этой аннотации типа и потерпит неудачу.
-Но в то же время, хотите сохранить аннотацию возвращаемого типа для функции, чтобы обеспечить работу помощников и анализаторов типов (например, mypy).
+То же произойдёт, если у вас будет что-то вроде объединение разных типов, где один или несколько не являются валидными типами Pydantic, например, это приведёт к ошибке 💥:
-В таком случае, вы можете отключить генерацию модели ответа, указав `response_model=None`:
+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
-=== "Python 3.10+"
+...это не сработает, потому что аннотация типа не является типом Pydantic и это не единственный класс `Response` или его подкласс, а объединение (`union`) из `Response` и `dict`.
- ```Python hl_lines="7"
- {!> ../../../docs_src/response_model/tutorial003_05_py310.py!}
- ```
+### Отключить модель ответа { #disable-response-model }
-=== "Python 3.6+"
+Продолжая пример выше, вы можете не хотеть использовать стандартные валидацию данных, документирование, фильтрацию и т.п., выполняемые FastAPI.
- ```Python hl_lines="9"
- {!> ../../../docs_src/response_model/tutorial003_05.py!}
- ```
+Но при этом вы можете хотеть сохранить аннотацию возвращаемого типа в функции, чтобы пользоваться поддержкой инструментов вроде редакторов кода и инструментов проверки типов (например, mypy).
-Тогда FastAPI не станет генерировать модель ответа и вы сможете сохранить такую аннотацию типа, которая вам требуется, никак не влияя на работу FastAPI. 🤓
+В этом случае вы можете отключить генерацию модели ответа, установив `response_model=None`:
-## Параметры модели ответа
+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}
-Модель ответа может иметь значения по умолчанию, например:
+Так FastAPI пропустит генерацию модели ответа, и вы сможете использовать любые аннотации возвращаемых типов, которые вам нужны, без влияния на ваше приложение FastAPI. 🤓
-=== "Python 3.10+"
+## Параметры кодирования модели ответа { #response-model-encoding-parameters }
- ```Python hl_lines="9 11-12"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
+У вашей модели ответа могут быть значения по умолчанию, например:
-=== "Python 3.9+"
+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
+* `description: Union[str, None] = None` (или `str | None = None` в Python 3.10) имеет значение по умолчанию `None`.
+* `tax: float = 10.5` имеет значение по умолчанию `10.5`.
+* `tags: List[str] = []` имеет значение по умолчанию пустого списка: `[]`.
-=== "Python 3.6+"
+но вы можете захотеть опустить их в результате, если они фактически не были сохранены.
- ```Python hl_lines="11 13-14"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
+Например, если у вас есть модели с множеством необязательных атрибутов в NoSQL-базе данных, но вы не хотите отправлять очень длинные JSON-ответы, заполненные значениями по умолчанию.
-* `description: Union[str, None] = None` (или `str | None = None` в Python 3.10), где `None` является значением по умолчанию.
-* `tax: float = 10.5`, где `10.5` является значением по умолчанию.
-* `tags: List[str] = []`, где пустой список `[]` является значением по умолчанию.
+### Используйте параметр `response_model_exclude_unset` { #use-the-response-model-exclude-unset-parameter }
-но вы, возможно, хотели бы исключить их из ответа, если данные поля не были заданы явно.
+Вы можете установить у *декоратора операции пути* параметр `response_model_exclude_unset=True`:
-Например, у вас есть модель с множеством необязательных полей в NoSQL базе данных, но вы не хотите отправлять в качестве ответа очень длинный JSON с множеством значений по умолчанию.
+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}
-### Используйте параметр `response_model_exclude_unset`
+и эти значения по умолчанию не будут включены в ответ — только те значения, которые действительно были установлены.
-Установите для *декоратора операции пути* параметр `response_model_exclude_unset=True`:
-
-=== "Python 3.10+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial004_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial004.py!}
- ```
-
-и тогда значения по умолчанию не будут включены в ответ. В нем будут только те поля, значения которых фактически были установлены.
-
-Итак, если вы отправите запрос на данную *операцию пути* для элемента, с ID = `Foo` - ответ (с исключенными значениями по-умолчанию) будет таким:
+Итак, если вы отправите запрос к этой *операции пути* для элемента с ID `foo`, ответ (без значений по умолчанию) будет таким:
```JSON
{
@@ -376,20 +251,20 @@ FastAPI совместно с Pydantic выполнит некоторую ма
}
```
-!!! info "Информация"
- "Под капотом" FastAPI использует метод `.dict()` у объектов моделей Pydantic с параметром `exclude_unset`, чтобы достичь такого эффекта.
+/// info | Информация
+
+Вы также можете использовать:
-!!! info "Информация"
- Вы также можете использовать:
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+как описано в [документации Pydantic](https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict) для `exclude_defaults` и `exclude_none`.
- как описано в документации Pydantic для параметров `exclude_defaults` и `exclude_none`.
+///
-#### Если значение поля отличается от значения по-умолчанию
+#### Данные со значениями для полей, имеющих значения по умолчанию { #data-with-values-for-fields-with-defaults }
-Если для некоторых полей модели, имеющих значения по-умолчанию, значения были явно установлены - как для элемента с ID = `Bar`, ответ будет таким:
+Но если в ваших данных есть значения для полей модели, для которых указаны значения по умолчанию, как у элемента с ID `bar`:
```Python hl_lines="3 5"
{
@@ -400,11 +275,11 @@ FastAPI совместно с Pydantic выполнит некоторую ма
}
```
-они не будут исключены из ответа.
+они будут включены в ответ.
-#### Если значение поля совпадает с его значением по умолчанию
+#### Данные с такими же значениями, как значения по умолчанию { #data-with-the-same-values-as-the-defaults }
-Если данные содержат те же значения, которые являются для этих полей по умолчанию, но были установлены явно - как для элемента с ID = `baz`, ответ будет таким:
+Если данные имеют те же значения, что и значения по умолчанию, как у элемента с ID `baz`:
```Python hl_lines="3 5-6"
{
@@ -416,65 +291,54 @@ FastAPI совместно с Pydantic выполнит некоторую ма
}
```
-FastAPI достаточно умен (на самом деле, это заслуга Pydantic), чтобы понять, что, хотя `description`, `tax` и `tags` хранят такие же данные, какие должны быть по умолчанию - для них эти значения были установлены явно (а не получены из значений по умолчанию).
+FastAPI достаточно умен (на самом деле, это Pydantic), чтобы понять, что хотя `description`, `tax` и `tags` совпадают со значениями по умолчанию, они были установлены явно (а не взяты из значений по умолчанию).
-И поэтому, они также будут включены в JSON ответа.
+Поэтому они тоже будут включены в JSON-ответ.
-!!! tip "Подсказка"
- Значением по умолчанию может быть что угодно, не только `None`.
+/// tip | Совет
- Им может быть и список (`[]`), значение 10.5 типа `float`, и т.п.
+Обратите внимание, что значения по умолчанию могут быть любыми, не только `None`.
-### `response_model_include` и `response_model_exclude`
+Это может быть список (`[]`), число с плавающей точкой `10.5` и т.д.
-Вы также можете использовать параметры *декоратора операции пути*, такие, как `response_model_include` и `response_model_exclude`.
+///
-Они принимают аргументы типа `set`, состоящий из строк (`str`) с названиями атрибутов, которые либо требуется включить в ответ (при этом исключив все остальные), либо наоборот исключить (оставив в ответе все остальные поля).
+### `response_model_include` и `response_model_exclude` { #response-model-include-and-response-model-exclude }
-Это можно использовать как быстрый способ исключить данные из ответа, не создавая отдельную модель Pydantic.
+Вы также можете использовать параметры *декоратора операции пути* `response_model_include` и `response_model_exclude`.
-!!! tip "Подсказка"
- Но по-прежнему рекомендуется следовать изложенным выше советам и использовать несколько моделей вместо данных параметров.
+Они принимают `set` из `str` с именами атрибутов, которые нужно включить (исключив остальные) или исключить (оставив остальные).
- Потому как JSON схема OpenAPI, генерируемая вашим приложением (а также документация) все еще будет содержать все поля, даже если вы использовали `response_model_include` или `response_model_exclude` и исключили некоторые атрибуты.
+Это можно использовать как быстрый способ, если у вас только одна Pydantic-модель и вы хотите убрать часть данных из ответа.
- То же самое применимо к параметру `response_model_by_alias`.
+/// tip | Совет
-=== "Python 3.10+"
+Но всё же рекомендуется использовать подходы выше — несколько классов — вместо этих параметров.
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial005_py310.py!}
- ```
+Потому что JSON Schema, генерируемая в OpenAPI вашего приложения (и документации), всё равно будет соответствовать полной модели, даже если вы используете `response_model_include` или `response_model_exclude`, чтобы опустить некоторые атрибуты.
-=== "Python 3.6+"
+То же относится к `response_model_by_alias`, который работает аналогично.
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial005.py!}
- ```
+///
-!!! tip "Подсказка"
- При помощи кода `{"name","description"}` создается объект множества (`set`) с двумя строковыми значениями.
+{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}
- Того же самого можно достичь используя `set(["name", "description"])`.
+/// tip | Совет
-#### Что если использовать `list` вместо `set`?
+Синтаксис `{"name", "description"}` создаёт `set` с этими двумя значениями.
-Если вы забыли про `set` и использовали структуру `list` или `tuple`, FastAPI автоматически преобразует этот объект в `set`, чтобы обеспечить корректную работу:
+Это эквивалентно `set(["name", "description"])`.
-=== "Python 3.10+"
+///
- ```Python hl_lines="29 35"
- {!> ../../../docs_src/response_model/tutorial006_py310.py!}
- ```
+#### Использование `list` вместо `set` { #using-lists-instead-of-sets }
-=== "Python 3.6+"
+Если вы забыли использовать `set` и применили `list` или `tuple` вместо него, FastAPI всё равно преобразует это в `set`, и всё будет работать корректно:
- ```Python hl_lines="31 37"
- {!> ../../../docs_src/response_model/tutorial006.py!}
- ```
+{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}
-## Резюме
+## Резюме { #recap }
-Используйте параметр `response_model` у *декоратора операции пути* для того, чтобы задать модель ответа и в большей степени для того, чтобы быть уверенным, что приватная информация будет отфильтрована.
+Используйте параметр `response_model` у *декоратора операции пути*, чтобы задавать модели ответа, и особенно — чтобы приватные данные отфильтровывались.
-А также используйте `response_model_exclude_unset`, чтобы возвращать только те значения, которые были заданы явно.
+Используйте `response_model_exclude_unset`, чтобы возвращать только те значения, которые были установлены явно.
diff --git a/docs/ru/docs/tutorial/response-status-code.md b/docs/ru/docs/tutorial/response-status-code.md
index b2f9b7704817f..f3144a33ab4f3 100644
--- a/docs/ru/docs/tutorial/response-status-code.md
+++ b/docs/ru/docs/tutorial/response-status-code.md
@@ -1,6 +1,6 @@
-# HTTP коды статуса ответа
+# Статус-код ответа { #response-status-code }
-Вы можете задать HTTP код статуса ответа с помощью параметра `status_code` подобно тому, как вы определяете схему ответа в любой из *операций пути*:
+Подобно тому, как вы можете задать модель/схему ответа, вы можете объявить HTTP статус-код, используемый для ответа, с помощью параметра `status_code` в любой из *операций пути*:
* `@app.get()`
* `@app.post()`
@@ -8,62 +8,73 @@
* `@app.delete()`
* и других.
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
-!!! note "Примечание"
- Обратите внимание, что `status_code` является атрибутом метода-декоратора (`get`, `post` и т.д.), а не *функции-обработчика пути* в отличие от всех остальных параметров и тела запроса.
+/// note | Примечание
-Параметр `status_code` принимает число, обозначающее HTTP код статуса ответа.
+Обратите внимание, что `status_code` — это параметр метода-декоратора (`get`, `post` и т.д.), а не вашей *функции-обработчика пути*, в отличие от всех остальных параметров и тела запроса.
-!!! info "Информация"
- В качестве значения параметра `status_code` также может использоваться `IntEnum`, например, из библиотеки `http.HTTPStatus` в Python.
+///
+
+Параметр `status_code` принимает число, обозначающее HTTP статус-код.
+
+/// info | Информация
+
+В качестве значения параметра `status_code` также может использоваться `IntEnum`, например, из библиотеки [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus) в Python.
+
+///
Это позволит:
* Возвращать указанный код статуса в ответе.
-* Документировать его как код статуса ответа в OpenAPI схеме (а значит, и в пользовательском интерфейсе):
+* Документировать его как код статуса ответа в OpenAPI схеме (а значит, и в пользовательских интерфейсах):
-!!! note "Примечание"
- Некоторые коды статуса ответа (см. следующий раздел) указывают на то, что ответ не имеет тела.
+/// note | Примечание
+
+Некоторые коды статуса ответа (см. следующий раздел) указывают на то, что ответ не имеет тела.
+
+FastAPI знает об этом и создаст документацию OpenAPI, в которой будет указано, что тело ответа отсутствует.
- FastAPI знает об этом и создаст документацию OpenAPI, в которой будет указано, что тело ответа отсутствует.
+///
-## Об HTTP кодах статуса ответа
+## Об HTTP статус-кодах { #about-http-status-codes }
-!!! note "Примечание"
- Если вы уже знаете, что представляют собой HTTP коды статуса ответа, можете перейти к следующему разделу.
+/// note | Примечание
+
+Если вы уже знаете, что представляют собой HTTP статус-коды, можете перейти к следующему разделу.
+
+///
В протоколе HTTP числовой код состояния из 3 цифр отправляется как часть ответа.
У кодов статуса есть названия, чтобы упростить их распознавание, но важны именно числовые значения.
-Кратко о значениях кодов:
+Кратко:
-* `1XX` – статус-коды информационного типа. Они редко используются разработчиками напрямую. Ответы с этими кодами не могут иметь тела.
-* **`2XX`** – статус-коды, сообщающие об успешной обработке запроса. Они используются чаще всего.
+* `100 - 199` – статус-коды информационного типа. Они редко используются разработчиками напрямую. Ответы с этими кодами не могут иметь тела.
+* **`200 - 299`** – статус-коды, сообщающие об успешной обработке запроса. Они используются чаще всего.
* `200` – это код статуса ответа по умолчанию, который означает, что все прошло "OK".
* Другим примером может быть статус `201`, "Created". Он обычно используется после создания новой записи в базе данных.
- * Особый случай – `204`, "No Content". Этот статус ответа используется, когда нет содержимого для возврата клиенту, и поэтому ответ не должен иметь тела.
-* **`3XX`** – статус-коды, сообщающие о перенаправлениях. Ответы с этими кодами статуса могут иметь или не иметь тело, за исключением ответов со статусом `304`, "Not Modified", у которых не должно быть тела.
-* **`4XX`** – статус-коды, сообщающие о клиентской ошибке. Это ещё одна наиболее часто используемая категория.
+ * Особый случай – `204`, "No Content". Этот статус ответа используется, когда нет содержимого для возврата клиенту, и поэтому ответ не должен иметь тела.
+* **`300 - 399`** – статус-коды, сообщающие о перенаправлениях. Ответы с этими кодами статуса могут иметь или не иметь тело, за исключением ответов со статусом `304`, "Not Modified", у которых не должно быть тела.
+* **`400 - 499`** – статус-коды, сообщающие о клиентской ошибке. Это ещё одна наиболее часто используемая категория.
* Пример – код `404` для статуса "Not Found".
* Для общих ошибок со стороны клиента можно просто использовать код `400`.
-* `5XX` – статус-коды, сообщающие о серверной ошибке. Они почти никогда не используются разработчиками напрямую. Когда что-то идет не так в какой-то части кода вашего приложения или на сервере, он автоматически вернёт один из 5XX кодов.
+* `500 - 599` – статус-коды, сообщающие о серверной ошибке. Они почти никогда не используются разработчиками напрямую. Когда что-то идет не так в какой-то части кода вашего приложения или на сервере, он автоматически вернёт один из этих кодов статуса.
+
+/// tip | Подсказка
-!!! tip "Подсказка"
- Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с документацией MDN об HTTP кодах статуса ответа.
+Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с [MDN документацией об HTTP статус-кодах](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status).
-## Краткие обозначения для запоминания названий кодов
+///
+
+## Краткие обозначения для запоминания названий кодов { #shortcut-to-remember-the-names }
Рассмотрим предыдущий пример еще раз:
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
`201` – это код статуса "Создано".
@@ -71,19 +82,20 @@
Для удобства вы можете использовать переменные из `fastapi.status`.
-```Python hl_lines="1 6"
-{!../../../docs_src/response_status_code/tutorial002.py!}
-```
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
-Они содержат те же числовые значения, но позволяют использовать подсказки редактора для выбора кода статуса:
+Они содержат те же числовые значения, но позволяют использовать автозавершение редактора кода для выбора кода статуса:
-!!! note "Технические детали"
- Вы также можете использовать `from starlette import status` вместо `from fastapi import status`.
+/// note | Технические детали
+
+Вы также можете использовать `from starlette import status`.
+
+**FastAPI** позволяет использовать как `starlette.status`, так и `fastapi.status` исключительно для удобства разработчиков. Но поставляется fastapi.status непосредственно из Starlette.
- **FastAPI** позволяет использовать как `starlette.status`, так и `fastapi.status` исключительно для удобства разработчиков. Но поставляется fastapi.status непосредственно из Starlette.
+///
-## Изменение кода статуса по умолчанию
+## Изменение кода статуса по умолчанию { #changing-the-default }
-Позже, в [Руководстве для продвинутых пользователей](../advanced/response-change-status-code.md){.internal-link target=_blank}, вы узнаете, как возвращать HTTP коды статуса, отличные от используемого здесь кода статуса по умолчанию.
+Позже, в [Руководстве для продвинутых пользователей](../advanced/response-change-status-code.md), вы узнаете, как возвращать HTTP статус-код, отличный от значения по умолчанию, которое вы объявляете здесь.
diff --git a/docs/ru/docs/tutorial/schema-extra-example.md b/docs/ru/docs/tutorial/schema-extra-example.md
index a0363b9ba7a68..ee2f5b99135dd 100644
--- a/docs/ru/docs/tutorial/schema-extra-example.md
+++ b/docs/ru/docs/tutorial/schema-extra-example.md
@@ -1,56 +1,48 @@
-# Объявление примера запроса данных
+# Объявление примеров данных запроса { #declare-request-example-data }
Вы можете объявлять примеры данных, которые ваше приложение может получать.
-Вот несколько способов, как это можно сделать.
+Вот несколько способов, как это сделать.
-## Pydantic `schema_extra`
+## Дополнительные данные JSON Schema в моделях Pydantic { #extra-json-schema-data-in-pydantic-models }
-Вы можете объявить ключ `example` для модели Pydantic, используя класс `Config` и переменную `schema_extra`, как описано в Pydantic документации: Настройка схемы:
+Вы можете объявить `examples` для модели Pydantic, которые будут добавлены в сгенерированную JSON Schema.
-=== "Python 3.10+"
+{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}
- ```Python hl_lines="13-21"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
- ```
+Эта дополнительная информация будет добавлена как есть в выходную **JSON Schema** этой модели и будет использоваться в документации API.
-=== "Python 3.6+"
+Вы можете использовать атрибут `model_config`, который принимает `dict`, как описано в [Документация Pydantic: Конфигурация](https://docs.pydantic.dev/latest/api/config/).
- ```Python hl_lines="15-23"
- {!> ../../../docs_src/schema_extra_example/tutorial001.py!}
- ```
+Вы можете задать `"json_schema_extra"` с `dict`, содержащим любые дополнительные данные, которые вы хотите видеть в сгенерированной JSON Schema, включая `examples`.
-Эта дополнительная информация будет включена в **JSON Schema** выходных данных для этой модели, и она будет использоваться в документации к API.
+/// tip | Подсказка
-!!! tip Подсказка
- Вы можете использовать тот же метод для расширения JSON-схемы и добавления своей собственной дополнительной информации.
+Вы можете использовать тот же приём, чтобы расширить JSON Schema и добавить свою собственную дополнительную информацию.
- Например, вы можете использовать это для добавления дополнительной информации для пользовательского интерфейса в вашем веб-приложении и т.д.
+Например, вы можете использовать это, чтобы добавить метаданные для фронтенд‑пользовательского интерфейса и т.д.
-## Дополнительные аргументы поля `Field`
+///
-При использовании `Field()` с моделями Pydantic, вы также можете объявлять дополнительную информацию для **JSON Schema**, передавая любые другие произвольные аргументы в функцию.
+/// info | Информация
-Вы можете использовать это, чтобы добавить аргумент `example` для каждого поля:
+OpenAPI 3.1.0 (используется начиная с FastAPI 0.99.0) добавил поддержку `examples`, который является частью стандарта **JSON Schema**.
-=== "Python 3.10+"
+До этого поддерживалось только ключевое слово `example` с одним примером. Оно всё ещё поддерживается в OpenAPI 3.1.0, но помечено как устаревшее и не является частью стандарта JSON Schema. Поэтому рекомендуется мигрировать `example` на `examples`. 🤓
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
- ```
+Подробнее — в конце этой страницы.
-=== "Python 3.6+"
+///
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
+## Дополнительные аргументы `Field` { #field-additional-arguments }
-!!! warning Внимание
- Имейте в виду, что эти дополнительные переданные аргументы не добавляют никакой валидации, только дополнительную информацию для документации.
+При использовании `Field()` с моделями Pydantic вы также можете объявлять дополнительные `examples`:
-## Использование `example` и `examples` в OpenAPI
+{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}
-При использовании любой из этих функций:
+## `examples` в JSON Schema — OpenAPI { #examples-in-json-schema-openapi }
+
+При использовании любой из функций:
* `Path()`
* `Query()`
@@ -60,130 +52,151 @@
* `Form()`
* `File()`
-вы также можете добавить аргумент, содержащий `example` или группу `examples` с дополнительной информацией, которая будет добавлена в **OpenAPI**.
+вы также можете объявить набор `examples` с дополнительной информацией, которая будет добавлена в их **JSON Schema** внутри **OpenAPI**.
+
+### `Body` с `examples` { #body-with-examples }
-### Параметр `Body` с аргументом `example`
+Здесь мы передаём `examples`, содержащий один пример данных, ожидаемых в `Body()`:
-Здесь мы передаём аргумент `example`, как пример данных ожидаемых в параметре `Body()`:
+{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *}
-=== "Python 3.10+"
+### Пример в UI документации { #example-in-the-docs-ui }
- ```Python hl_lines="22-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
- ```
+С любым из перечисленных выше методов это будет выглядеть так в `/docs`:
-=== "Python 3.9+"
+
- ```Python hl_lines="22-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
- ```
+### `Body` с несколькими `examples` { #body-with-multiple-examples }
-=== "Python 3.6+"
+Конечно, вы можете передать и несколько `examples`:
- ```Python hl_lines="23-28"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
- ```
+{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *}
-=== "Python 3.10+ non-Annotated"
+Когда вы делаете это, примеры становятся частью внутренней **JSON Schema** для данных тела запроса.
- !!! tip Заметка
- Рекомендуется использовать версию с `Annotated`, если это возможно.
+Тем не менее, на момент написания этого Swagger UI, инструмент, отвечающий за отображение UI документации, не поддерживает показ нескольких примеров для данных в **JSON Schema**. Но ниже есть обходной путь.
- ```Python hl_lines="18-23"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
+### Специфические для OpenAPI `examples` { #openapi-specific-examples }
-=== "Python 3.6+ non-Annotated"
+Ещё до того как **JSON Schema** поддержала `examples`, в OpenAPI была поддержка другого поля, также называемого `examples`.
- !!! tip Заметка
- Рекомендуется использовать версию с `Annotated`, если это возможно.
+Эти **специфические для OpenAPI** `examples` находятся в другой секции спецификации OpenAPI. Они находятся в **подробностях для каждой операции пути (обработчика пути)**, а не внутри каждого объекта Schema.
- ```Python hl_lines="20-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
- ```
+И Swagger UI уже какое‑то время поддерживает именно это поле `examples`. Поэтому вы можете использовать его, чтобы **отобразить** разные **примеры в UI документации**.
-### Аргумент "example" в UI документации
+Структура этого специфичного для OpenAPI поля `examples` — это `dict` с **несколькими примерами** (вместо `list`), каждый с дополнительной информацией, которая также будет добавлена в **OpenAPI**.
-С любым из вышеуказанных методов это будет выглядеть так в `/docs`:
+Это не помещается внутрь каждого объекта Schema в OpenAPI, это находится снаружи, непосредственно на уровне самой *операции пути*.
-
+### Использование параметра `openapi_examples` { #using-the-openapi-examples-parameter }
-### `Body` с аргументом `examples`
+Вы можете объявлять специфические для OpenAPI `examples` в FastAPI с помощью параметра `openapi_examples` для:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
-В качестве альтернативы одному аргументу `example`, вы можете передавать `examples` используя тип данных `dict` с **несколькими примерами**, каждый из которых содержит дополнительную информацию, которая также будет добавлена в **OpenAPI**.
+Ключи `dict` идентифицируют каждый пример, а каждое значение — это ещё один `dict`.
-Ключи `dict` указывают на каждый пример, а значения для каждого из них - на еще один тип `dict` с дополнительной информацией.
+Каждый конкретный пример `dict` в `examples` может содержать:
-Каждый конкретный пример типа `dict` в аргументе `examples` может содержать:
+* `summary`: Краткое описание примера.
+* `description`: Подробное описание, которое может содержать текст в Markdown.
+* `value`: Это фактический пример, который отображается, например, `dict`.
+* `externalValue`: альтернатива `value`, URL, указывающий на пример. Хотя это может поддерживаться не так многими инструментами, как `value`.
-* `summary`: Краткое описание для примера.
-* `description`: Полное описание, которое может содержать текст в формате Markdown.
-* `value`: Это конкретный пример, который отображается, например, в виде типа `dict`.
-* `externalValue`: альтернатива параметру `value`, URL-адрес, указывающий на пример. Хотя это может не поддерживаться таким же количеством инструментов разработки и тестирования API, как параметр `value`.
+Использовать это можно так:
-=== "Python 3.10+"
+{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *}
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!}
- ```
+### OpenAPI-примеры в UI документации { #openapi-examples-in-the-docs-ui }
-=== "Python 3.9+"
+С `openapi_examples`, добавленным в `Body()`, страница `/docs` будет выглядеть так:
- ```Python hl_lines="23-49"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!}
- ```
+
-=== "Python 3.6+"
+## Технические детали { #technical-details }
- ```Python hl_lines="24-50"
- {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!}
- ```
+/// tip | Подсказка
-=== "Python 3.10+ non-Annotated"
+Если вы уже используете **FastAPI** версии **0.99.0 или выше**, вы, вероятно, можете **пропустить** эти подробности.
- !!! tip Заметка
- Рекомендуется использовать версию с `Annotated`, если это возможно.
+Они более актуальны для старых версий, до того как стала доступна OpenAPI 3.1.0.
- ```Python hl_lines="19-45"
- {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
- ```
+Считайте это кратким **уроком истории** про OpenAPI и JSON Schema. 🤓
-=== "Python 3.6+ non-Annotated"
+///
- !!! tip Заметка
- Рекомендуется использовать версию с `Annotated`, если это возможно.
+/// warning | Внимание
- ```Python hl_lines="21-47"
- {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
- ```
+Далее идут очень технические подробности о стандартах **JSON Schema** и **OpenAPI**.
-### Аргумент "examples" в UI документации
+Если идеи выше уже работают для вас, этого может быть достаточно, и, вероятно, вам не нужны эти детали — смело пропускайте их.
-С аргументом `examples`, добавленным в `Body()`, страница документации `/docs` будет выглядеть так:
+///
-
+До OpenAPI 3.1.0 OpenAPI использовала более старую и модифицированную версию **JSON Schema**.
-## Технические Детали
+В JSON Schema не было `examples`, поэтому OpenAPI добавила собственное поле `example` в свою модифицированную версию.
-!!! warning Внимание
- Эти технические детали относятся к стандартам **JSON Schema** и **OpenAPI**.
+OpenAPI также добавила поля `example` и `examples` в другие части спецификации:
- Если предложенные выше идеи уже работают для вас, возможно этого будет достаточно и эти детали вам не потребуются, можете спокойно их пропустить.
+* [`Parameter Object` (в спецификации)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object), которое использовалось в FastAPI:
+ * `Path()`
+ * `Query()`
+ * `Header()`
+ * `Cookie()`
+* [`Request Body Object`, в поле `content`, в `Media Type Object` (в спецификации)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object), которое использовалось в FastAPI:
+ * `Body()`
+ * `File()`
+ * `Form()`
-Когда вы добавляете пример внутрь модели Pydantic, используя `schema_extra` или `Field(example="something")`, этот пример добавляется в **JSON Schema** для данной модели Pydantic.
+/// info | Информация
+
+Этот старый специфичный для OpenAPI параметр `examples` теперь называется `openapi_examples`, начиная с FastAPI `0.103.0`.
+
+///
+
+### Поле `examples` в JSON Schema { #json-schemas-examples-field }
+
+Позже в новой версии спецификации JSON Schema было добавлено поле [`examples`](https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.9.5).
+
+А затем новый OpenAPI 3.1.0 был основан на последней версии (JSON Schema 2020-12), которая включала это новое поле `examples`.
+
+И теперь это новое поле `examples` имеет приоритет над старым одиночным (и кастомным) полем `example`, которое теперь устарело.
+
+Это новое поле `examples` в JSON Schema — это **просто `list`** примеров, а не dict с дополнительными метаданными, как в других местах OpenAPI (описанных выше).
+
+/// info | Информация
+
+Даже после того как OpenAPI 3.1.0 была выпущена с этой новой, более простой интеграцией с JSON Schema, какое‑то время Swagger UI, инструмент, предоставляющий автоматическую документацию, не поддерживал OpenAPI 3.1.0 (поддержка появилась начиная с версии 5.0.0 🎉).
+
+Из‑за этого версии FastAPI до 0.99.0 всё ещё использовали версии OpenAPI ниже 3.1.0.
+
+///
+
+### `examples` в Pydantic и FastAPI { #pydantic-and-fastapi-examples }
+
+Когда вы добавляете `examples` внутри модели Pydantic, используя `schema_extra` или `Field(examples=["something"])`, этот пример добавляется в **JSON Schema** для этой модели Pydantic.
И эта **JSON Schema** модели Pydantic включается в **OpenAPI** вашего API, а затем используется в UI документации.
-Поля `example` как такового не существует в стандартах **JSON Schema**. В последних версиях JSON-схемы определено поле `examples`, но OpenAPI 3.0.3 основан на более старой версии JSON-схемы, которая не имела поля `examples`.
+В версиях FastAPI до 0.99.0 (0.99.0 и выше используют новый OpenAPI 3.1.0), когда вы использовали `example` или `examples` с любыми другими утилитами (`Query()`, `Body()`, и т.д.), эти примеры не добавлялись в JSON Schema, описывающую эти данные (даже в собственную версию JSON Schema OpenAPI), они добавлялись непосредственно в объявление *операции пути* в OpenAPI (вне частей OpenAPI, использующих JSON Schema).
+
+Но теперь, когда FastAPI 0.99.0 и выше используют OpenAPI 3.1.0, который использует JSON Schema 2020-12, а также Swagger UI 5.0.0 и выше, всё стало более последовательным, и примеры включаются в JSON Schema.
-Таким образом, OpenAPI 3.0.3 определяет своё собственное поле `example` для модифицированной версии **JSON Schema**, которую он использует чтобы достичь той же цели (однако это именно поле `example`, а не `examples`), и именно это используется API в UI документации (с интеграцией Swagger UI).
+### Swagger UI и специфичные для OpenAPI `examples` { #swagger-ui-and-openapi-specific-examples }
-Итак, хотя поле `example` не является частью JSON-схемы, оно является частью настраиваемой версии JSON-схемы в OpenAPI, и именно это поле будет использоваться в UI документации.
+Теперь, поскольку Swagger UI не поддерживал несколько примеров JSON Schema (по состоянию на 2023-08-26), у пользователей не было способа показать несколько примеров в документации.
-Однако, когда вы используете поле `example` или `examples` с любой другой функцией (`Query()`, `Body()`, и т.д.), эти примеры не добавляются в JSON-схему, которая описывает эти данные (даже в собственную версию JSON-схемы OpenAPI), они добавляются непосредственно в объявление *операции пути* в OpenAPI (вне частей OpenAPI, которые используют JSON-схему).
+Чтобы решить это, FastAPI `0.103.0` **добавил поддержку** объявления того же старого, **специфичного для OpenAPI**, поля `examples` с новым параметром `openapi_examples`. 🤓
-Для функций `Path()`, `Query()`, `Header()`, и `Cookie()`, аргументы `example` или `examples` добавляются в определение OpenAPI, к объекту `Parameter Object` (в спецификации).
+### Итог { #summary }
-И для функций `Body()`, `File()` и `Form()` аргументы `example` или `examples` аналогично добавляются в определение OpenAPI, к объекту `Request Body Object`, в поле `content` в объекте `Media Type Object` (в спецификации).
+Раньше я говорил, что не очень люблю историю... а теперь вот рассказываю «уроки технической истории». 😅
-С другой стороны, существует более новая версия OpenAPI: **3.1.0**, недавно выпущенная. Она основана на последней версии JSON-схемы и большинство модификаций из OpenAPI JSON-схемы удалены в обмен на новые возможности из последней версии JSON-схемы, так что все эти мелкие отличия устранены. Тем не менее, Swagger UI в настоящее время не поддерживает OpenAPI 3.1.0, поэтому пока лучше продолжать использовать вышеупомянутые методы.
+Коротко: **обновитесь до FastAPI 0.99.0 или выше** — так всё будет значительно **проще, последовательнее и интуитивнее**, и вам не придётся знать все эти исторические подробности. 😎
diff --git a/docs/ru/docs/tutorial/security/first-steps.md b/docs/ru/docs/tutorial/security/first-steps.md
new file mode 100644
index 0000000000000..c55e832f40b7a
--- /dev/null
+++ b/docs/ru/docs/tutorial/security/first-steps.md
@@ -0,0 +1,203 @@
+# Безопасность — первые шаги { #security-first-steps }
+
+Представим, что у вас есть **бэкенд** API на некотором домене.
+
+И у вас есть **фронтенд** на другом домене или на другом пути того же домена (или в мобильном приложении).
+
+И вы хотите, чтобы фронтенд мог аутентифицироваться на бэкенде, используя **имя пользователя** и **пароль**.
+
+Мы можем использовать **OAuth2**, чтобы построить это с **FastAPI**.
+
+Но давайте сэкономим вам время на чтение всей длинной спецификации в поисках тех небольших фрагментов информации, которые вам нужны.
+
+Воспользуемся инструментами, предоставленными **FastAPI**, чтобы работать с безопасностью.
+
+## Как это выглядит { #how-it-looks }
+
+Сначала просто воспользуемся кодом и посмотрим, как он работает, а затем вернемся и разберемся, что происходит.
+
+## Создание `main.py` { #create-main-py }
+
+Скопируйте пример в файл `main.py`:
+
+{* ../../docs_src/security/tutorial001_an_py310.py *}
+
+## Запуск { #run-it }
+
+/// info | Дополнительная информация
+
+Пакет [`python-multipart`](https://github.com/Kludex/python-multipart) автоматически устанавливается вместе с **FastAPI**, если вы запускаете команду `pip install "fastapi[standard]"`.
+
+Однако, если вы используете команду `pip install fastapi`, пакет `python-multipart` по умолчанию не включается.
+
+Чтобы установить его вручную, убедитесь, что вы создали [виртуальное окружение](../../virtual-environments.md), активировали его и затем установили пакет:
+
+```console
+$ pip install python-multipart
+```
+
+Это связано с тем, что **OAuth2** использует «данные формы» для отправки `username` и `password`.
+
+///
+
+Запустите пример командой:
+
+
+
+/// check | Кнопка авторизации!
+
+У вас уже появилась новая кнопка «Authorize».
+
+А у вашей *операции пути* в правом верхнем углу есть маленький замочек, на который можно нажать.
+
+///
+
+Если нажать на нее, появится небольшая форма авторизации, в которую нужно ввести `username` и `password` (и другие необязательные поля):
+
+
+
+/// note | Примечание
+
+Неважно, что вы введете в форму — пока это не будет работать. Но мы скоро до этого дойдем.
+
+///
+
+Конечно, это не фронтенд для конечных пользователей, но это отличный автоматический инструмент для интерактивного документирования всего вашего API.
+
+Им может пользоваться команда фронтенда (которой можете быть и вы сами).
+
+Им могут пользоваться сторонние приложения и системы.
+
+И им также можете пользоваться вы сами, чтобы отлаживать, проверять и тестировать то же самое приложение.
+
+## «`password` flow» (аутентификация по паролю) { #the-password-flow }
+
+Теперь давайте немного вернемся и разберемся, что это все такое.
+
+«`password` flow» — это один из способов («flows»), определенных в OAuth2, для обеспечения безопасности и аутентификации.
+
+OAuth2 был спроектирован так, чтобы бэкенд или API были независимы от сервера, который аутентифицирует пользователя.
+
+Но в нашем случае одно и то же приложение **FastAPI** будет работать и с API, и с аутентификацией.
+
+Итак, рассмотрим это с упрощенной точки зрения:
+
+* Пользователь вводит на фронтенде `username` и `password` и нажимает `Enter`.
+* Фронтенд (работающий в браузере пользователя) отправляет эти `username` и `password` на конкретный URL в нашем API (объявленный с `tokenUrl="token"`).
+* API проверяет этот `username` и `password` и отвечает «токеном» (мы еще ничего из этого не реализовали).
+ * «Токен» — это просто строка с некоторым содержимым, которое мы сможем позже использовать для проверки этого пользователя.
+ * Обычно у токена установлен срок действия: он истекает через некоторое время.
+ * Поэтому пользователю придется снова войти в систему в какой‑то момент.
+ * И если токен украдут, риск меньше: это не постоянный ключ, который будет работать вечно (в большинстве случаев).
+* Фронтенд временно где‑то хранит этот токен.
+* Пользователь кликает во фронтенде, чтобы перейти в другой раздел веб‑приложения.
+* Фронтенду нужно получить дополнительные данные из API.
+ * Но для этого для конкретной конечной точки нужна аутентификация.
+ * Поэтому, чтобы аутентифицироваться в нашем API, он отправляет HTTP-заголовок `Authorization` со значением `Bearer ` плюс сам токен.
+ * Если токен содержит `foobar`, то содержимое заголовка `Authorization` будет: `Bearer foobar`.
+
+## Класс `OAuth2PasswordBearer` в **FastAPI** { #fastapis-oauth2passwordbearer }
+
+**FastAPI** предоставляет несколько средств на разных уровнях абстракции для реализации этих функций безопасности.
+
+В этом примере мы будем использовать **OAuth2**, с потоком **Password**, используя токен **Bearer**. Для этого мы используем класс `OAuth2PasswordBearer`.
+
+/// info | Дополнительная информация
+
+Токен «bearer» — не единственный вариант.
+
+Но для нашего случая он — лучший.
+
+И он может быть лучшим для большинства случаев использования, если только вы не являетесь экспертом по OAuth2 и точно знаете, почему другой вариант лучше подходит под ваши нужды.
+
+В этом случае **FastAPI** также предоставляет инструменты, чтобы его реализовать.
+
+///
+
+При создании экземпляра класса `OAuth2PasswordBearer` мы передаем параметр `tokenUrl`. Этот параметр содержит URL, который клиент (фронтенд, работающий в браузере пользователя) будет использовать для отправки `username` и `password`, чтобы получить токен.
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
+
+/// tip | Подсказка
+
+Здесь `tokenUrl="token"` ссылается на относительный URL `token`, который мы еще не создали. Поскольку это относительный URL, он эквивалентен `./token`.
+
+Поскольку мы используем относительный URL, если ваш API расположен по адресу `https://example.com/`, то он будет ссылаться на `https://example.com/token`. А если ваш API расположен по адресу `https://example.com/api/v1/`, то он будет ссылаться на `https://example.com/api/v1/token`.
+
+Использование относительного URL важно для того, чтобы ваше приложение продолжало работать даже в таком продвинутом случае, как [За прокси-сервером](../../advanced/behind-a-proxy.md).
+
+///
+
+Этот параметр не создает конечную точку / *операцию пути*, а объявляет, что URL `/token` — это тот, который клиент должен использовать для получения токена. Эта информация используется в OpenAPI, а затем в интерактивных системах документации по API.
+
+Скоро мы также создадим и саму операцию пути.
+
+/// info | Дополнительная информация
+
+Если вы очень строгий «питонист», вам может не понравиться стиль имени параметра `tokenUrl` вместо `token_url`.
+
+Это потому, что используется то же имя, что и в спецификации OpenAPI. Так, если вам нужно разобраться подробнее в какой‑то из этих схем безопасности, вы можете просто скопировать и вставить это имя, чтобы найти больше информации.
+
+///
+
+Переменная `oauth2_scheme` — это экземпляр `OAuth2PasswordBearer`, но она также «вызываемая».
+
+Ее можно вызвать так:
+
+```Python
+oauth2_scheme(some, parameters)
+```
+
+Поэтому ее можно использовать вместе с `Depends`.
+
+### Использование { #use-it }
+
+Теперь вы можете передать `oauth2_scheme` как зависимость с `Depends`.
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+Эта зависимость предоставит `str`, который будет присвоен параметру `token` *функции-обработчика пути*.
+
+**FastAPI** будет знать, что может использовать эту зависимость для определения «схемы безопасности» в схеме OpenAPI (и в автоматической документации по API).
+
+/// info | Технические детали
+
+**FastAPI** будет знать, что может использовать класс `OAuth2PasswordBearer` (объявленный в зависимости) для определения схемы безопасности в OpenAPI, потому что он наследуется от `fastapi.security.oauth2.OAuth2`, который, в свою очередь, наследуется от `fastapi.security.base.SecurityBase`.
+
+Все утилиты безопасности, интегрируемые с OpenAPI (и автоматической документацией по API), наследуются от `SecurityBase`, — так **FastAPI** понимает, как интегрировать их в OpenAPI.
+
+///
+
+## Что он делает { #what-it-does }
+
+Он будет искать в запросе заголовок `Authorization`, проверять, что его значение — это `Bearer ` плюс некоторый токен, и вернет токен как `str`.
+
+Если заголовок `Authorization` отсутствует или его значение не содержит токен `Bearer `, он сразу ответит ошибкой со статус-кодом 401 (`UNAUTHORIZED`).
+
+Вам даже не нужно проверять наличие токена, чтобы вернуть ошибку. Вы можете быть уверены: если ваша функция была выполнена, в этом токене будет `str`.
+
+Это уже можно попробовать в интерактивной документации:
+
+
+
+Мы пока не проверяем валидность токена, но для начала это уже неплохо.
+
+## Резюме { #recap }
+
+Таким образом, всего за 3–4 дополнительные строки у вас уже есть некая примитивная форма защиты.
diff --git a/docs/ru/docs/tutorial/security/get-current-user.md b/docs/ru/docs/tutorial/security/get-current-user.md
new file mode 100644
index 0000000000000..8388b672c7366
--- /dev/null
+++ b/docs/ru/docs/tutorial/security/get-current-user.md
@@ -0,0 +1,105 @@
+# Получить текущего пользователя { #get-current-user }
+
+В предыдущей главе система безопасности (основанная на системе внедрения зависимостей) передавала *функции-обработчику пути* `token` типа `str`:
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+Но это всё ещё не слишком полезно.
+
+Сделаем так, чтобы она возвращала текущего пользователя.
+
+## Создать модель пользователя { #create-a-user-model }
+
+Сначала создадим Pydantic-модель пользователя.
+
+Точно так же, как мы используем Pydantic для объявления тел запросов, мы можем использовать его где угодно:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *}
+
+## Создать зависимость `get_current_user` { #create-a-get-current-user-dependency }
+
+Давайте создадим зависимость `get_current_user`.
+
+Помните, что у зависимостей могут быть подзависимости?
+
+`get_current_user` будет иметь зависимость от того же `oauth2_scheme`, который мы создали ранее.
+
+Аналогично тому, как мы делали ранее прямо в *операции пути*, новая зависимость `get_current_user` получит `token` типа `str` от подзависимости `oauth2_scheme`:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *}
+
+## Получить пользователя { #get-the-user }
+
+`get_current_user` будет использовать созданную нами (ненастоящую) служебную функцию, которая принимает токен типа `str` и возвращает нашу Pydantic-модель `User`:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *}
+
+## Внедрить текущего пользователя { #inject-the-current-user }
+
+Теперь мы можем использовать тот же `Depends` с нашей `get_current_user` в *операции пути*:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *}
+
+Обратите внимание, что мы объявляем тип `current_user` как Pydantic-модель `User`.
+
+Это поможет внутри функции с автозавершением и проверками типов.
+
+/// tip | Подсказка
+
+Возможно, вы помните, что тела запросов также объявляются с помощью Pydantic-моделей.
+
+Здесь **FastAPI** не запутается, потому что вы используете `Depends`.
+
+///
+
+/// check | Заметка
+
+То, как устроена эта система зависимостей, позволяет иметь разные зависимости, которые возвращают модель `User`.
+
+Мы не ограничены наличием только одной зависимости, которая может возвращать такой тип данных.
+
+///
+
+## Другие модели { #other-models }
+
+Теперь вы можете получать текущего пользователя напрямую в *функциях-обработчиках пути* и работать с механизмами безопасности на уровне **внедрения зависимостей**, используя `Depends`.
+
+И вы можете использовать любую модель или данные для требований безопасности (в данном случае Pydantic-модель `User`).
+
+Но вы не ограничены использованием какой-то конкретной модели данных, класса или типа.
+
+Хотите, чтобы в модели были `id` и `email`, но не было `username`? Пожалуйста. Можно использовать те же инструменты.
+
+Хотите просто `str`? Или просто `dict`? Или напрямую экземпляр класса модели базы данных? Всё работает одинаково.
+
+У вас вообще нет пользователей, которые входят в приложение, а есть роботы, боты или другие системы, у которых есть только токен доступа? Снова — всё работает так же.
+
+Просто используйте любую модель, любой класс, любую базу данных, которые нужны вашему приложению. Система внедрения зависимостей **FastAPI** поможет вам в этом.
+
+## Размер кода { #code-size }
+
+Этот пример может показаться многословным. Имейте в виду, что в одном файле мы смешиваем безопасность, модели данных, служебные функции и *операции пути*.
+
+Но вот ключевой момент.
+
+Всё, что касается безопасности и внедрения зависимостей, пишется один раз.
+
+И вы можете сделать это настолько сложным, насколько захотите. И всё равно это будет написано только один раз, в одном месте. Со всей гибкостью.
+
+При этом у вас могут быть тысячи эндпоинтов (*операций пути*), использующих одну и ту же систему безопасности.
+
+И все они (или любая их часть по вашему желанию) могут воспользоваться преимуществами повторного использования этих зависимостей или любых других зависимостей, которые вы создадите.
+
+И все эти тысячи *операций пути* могут состоять всего из 3 строк:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *}
+
+## Резюме { #recap }
+
+Теперь вы можете получать текущего пользователя прямо в своей *функции-обработчике пути*.
+
+Мы уже на полпути.
+
+Нужно лишь добавить *операцию пути*, чтобы пользователь/клиент мог отправить `username` и `password`.
+
+Это будет дальше.
diff --git a/docs/ru/docs/tutorial/security/index.md b/docs/ru/docs/tutorial/security/index.md
index d5fe4e76f8940..bd8da824b3157 100644
--- a/docs/ru/docs/tutorial/security/index.md
+++ b/docs/ru/docs/tutorial/security/index.md
@@ -1,101 +1,106 @@
-# Настройка авторизации
+# Безопасность { #security }
Существует множество способов обеспечения безопасности, аутентификации и авторизации.
-Обычно эта тема является достаточно сложной и трудной.
+Обычно эта тема является достаточно сложной и «трудной».
-Во многих фреймворках и системах только работа с определением доступов к приложению и аутентификацией требует значительных затрат усилий и написания множества кода (во многих случаях его объём может составлять более 50% от всего написанного кода).
+Во многих фреймворках и системах только работа с безопасностью и аутентификацией требует значительных затрат усилий и написания множества кода (во многих случаях его объём может составлять 50% или более от всего написанного кода).
-**FastAPI** предоставляет несколько инструментов, которые помогут вам настроить **Авторизацию** легко, быстро, стандартным способом, без необходимости изучать все её тонкости.
+**FastAPI** предоставляет несколько инструментов, которые помогут вам работать с **безопасностью** легко, быстро, стандартным способом, без необходимости изучать и разбираться во всех спецификациях по безопасности.
-Но сначала давайте рассмотрим некоторые небольшие концепции.
+Но сначала давайте рассмотрим несколько небольших концепций.
-## Куда-то торопишься?
+## Нет времени? { #in-a-hurry }
-Если вам не нужна информация о каких-либо из следующих терминов и вам просто нужно добавить защиту с аутентификацией на основе логина и пароля *прямо сейчас*, переходите к следующим главам.
+Если вам не важны какие-либо из этих терминов и вам просто нужно добавить защиту с аутентификацией на основе имени пользователя и пароля прямо сейчас, переходите к следующим главам.
-## OAuth2
+## OAuth2 { #oauth2 }
-OAuth2 - это протокол, который определяет несколько способов обработки аутентификации и авторизации.
+OAuth2 - это спецификация, которая определяет несколько способов обработки аутентификации и авторизации.
-Он довольно обширен и охватывает несколько сложных вариантов использования.
+Это довольно обширная спецификация, охватывающая несколько сложных вариантов использования.
-OAuth2 включает в себя способы аутентификации с использованием "третьей стороны".
+Она включает способы аутентификации с использованием «третьей стороны».
-Это то, что используют под собой все кнопки "вход с помощью Facebook, Google, Twitter, GitHub" на страницах авторизации.
+Именно это используется во всех системах с кнопками «войти с помощью Facebook, Google, X (Twitter), GitHub».
-### OAuth 1
+### OAuth 1 { #oauth-1 }
-Ранее использовался протокол OAuth 1, который сильно отличается от OAuth2 и является более сложным, поскольку он включал прямые описания того, как шифровать сообщение.
+Ранее использовался OAuth 1, который сильно отличается от OAuth2 и является более сложным, поскольку он включал прямые спецификации того, как шифровать обмен данными.
В настоящее время он не очень популярен и не используется.
-OAuth2 не указывает, как шифровать сообщение, он ожидает, что ваше приложение будет обслуживаться по протоколу HTTPS.
+OAuth2 не указывает, как шифровать обмен данными, он ожидает, что ваше приложение будет обслуживаться по протоколу HTTPS.
-!!! tip "Подсказка"
- В разделе **Развертывание** вы увидите [как настроить протокол HTTPS бесплатно, используя Traefik и Let's Encrypt.](https://fastapi.tiangolo.com/ru/deployment/https/)
+/// tip | Подсказка
+В разделе о **развертывании** вы увидите, как настроить HTTPS бесплатно, используя Traefik и Let's Encrypt.
-## OpenID Connect
+///
-OpenID Connect - это еще один протокол, основанный на **OAuth2**.
+## OpenID Connect { #openid-connect }
-Он просто расширяет OAuth2, уточняя некоторые вещи, не имеющие однозначного определения в OAuth2, в попытке сделать его более совместимым.
+OpenID Connect — это ещё одна спецификация, основанная на **OAuth2**.
-Например, для входа в Google используется OpenID Connect (который под собой использует OAuth2).
+Она просто расширяет OAuth2, уточняя некоторые вещи, которые относительно неоднозначны в OAuth2, стараясь сделать его более совместимым.
+
+Например, для входа в Google используется OpenID Connect (который под капотом использует OAuth2).
Но вход в Facebook не поддерживает OpenID Connect. У него есть собственная вариация OAuth2.
-### OpenID (не "OpenID Connect")
+### OpenID (не «OpenID Connect») { #openid-not-openid-connect }
-Также ранее использовался стандарт "OpenID", который пытался решить ту же проблему, что и **OpenID Connect**, но не был основан на OAuth2.
+Также ранее использовалась спецификация «OpenID», которая пыталась решить ту же задачу, что и **OpenID Connect**, но не была основана на OAuth2.
Таким образом, это была полноценная дополнительная система.
В настоящее время не очень популярен и не используется.
-## OpenAPI
+## OpenAPI { #openapi }
OpenAPI (ранее известный как Swagger) - это открытая спецификация для создания API (в настоящее время является частью Linux Foundation).
**FastAPI** основан на **OpenAPI**.
-Это то, что делает возможным наличие множества автоматических интерактивных интерфейсов документирования, сгенерированного кода и т.д.
+Это то, что делает возможными несколько автоматических интерактивных интерфейсов документации, генерацию кода и т.д.
-В OpenAPI есть способ использовать несколько "схем" безопасности.
+В OpenAPI есть способ определить несколько «схем» безопасности.
-Таким образом, вы можете воспользоваться преимуществами Всех этих стандартных инструментов, включая интерактивные системы документирования.
+Используя их, вы можете воспользоваться преимуществами всех этих инструментов, основанных на стандартах, включая интерактивные системы документирования.
-OpenAPI может использовать следующие схемы авторизации:
+OpenAPI определяет следующие схемы безопасности:
-* `apiKey`: уникальный идентификатор для приложения, который может быть получен из:
- * Параметров запроса.
- * Заголовка.
- * Cookies.
-* `http`: стандартные системы аутентификации по протоколу HTTP, включая:
- * `bearer`: заголовок `Authorization` со значением `Bearer {уникальный токен}`. Это унаследовано от OAuth2.
- * Базовая аутентификация по протоколу HTTP.
+* `apiKey`: специфичный для приложения ключ, который может поступать из:
+ * параметра запроса.
+ * HTTP-заголовка.
+ * cookie.
+* `http`: стандартные системы аутентификации по HTTP, включая:
+ * `bearer`: HTTP-заголовок `Authorization` со значением `Bearer ` плюс токен. Это унаследовано от OAuth2.
+ * Базовая аутентификация по HTTP.
* HTTP Digest и т.д.
-* `oauth2`: все способы обеспечения безопасности OAuth2 называемые "потоки" (англ. "flows").
- * Некоторые из этих "потоков" подходят для реализации аутентификации через сторонний сервис использующий OAuth 2.0 (например, Google, Facebook, Twitter, GitHub и т.д.):
+* `oauth2`: все способы OAuth2 для обеспечения безопасности (называются «потоками»).
+ * Несколько из этих «потоков» подходят для построения провайдера аутентификации OAuth 2.0 (например, Google, Facebook, X (Twitter), GitHub и т.д.):
* `implicit`
* `clientCredentials`
* `authorizationCode`
- * Но есть один конкретный "поток", который может быть идеально использован для обработки аутентификации непосредственно в том же приложении:
- * `password`: в некоторых следующих главах будут рассмотрены примеры этого.
-* `openIdConnect`: способ определить, как автоматически обнаруживать данные аутентификации OAuth2.
- * Это автоматическое обнаружение определено в спецификации OpenID Connect.
+ * Но есть один конкретный «поток», который можно идеально использовать для обработки аутентификации непосредственно в этом же приложении:
+ * `password`: в некоторых следующих главах будут приведены примеры.
+* `openIdConnect`: имеет способ определить, как автоматически обнаруживать данные аутентификации OAuth2.
+ * Именно это автоматическое обнаружение определено в спецификации OpenID Connect.
+
+
+/// tip | Подсказка
+Интеграция сторонних провайдеров аутентификации/авторизации, таких как Google, Facebook, X (Twitter), GitHub и т.д., также возможна и относительно проста.
-!!! tip "Подсказка"
- Интеграция сторонних сервисов для аутентификации/авторизации таких как Google, Facebook, Twitter, GitHub и т.д. осуществляется достаточно легко.
+Самой сложной задачей является создание такого провайдера аутентификации/авторизации, но **FastAPI** предоставляет вам инструменты, позволяющие легко это сделать, выполняя при этом всю тяжёлую работу за вас.
- Самой сложной проблемой является создание такого провайдера аутентификации/авторизации, но **FastAPI** предоставляет вам инструменты, позволяющие легко это сделать, выполняя при этом всю тяжелую работу за вас.
+///
-## Преимущества **FastAPI**
+## Инструменты **FastAPI** { #fastapi-utilities }
-Fast API предоставляет несколько инструментов для каждой из этих схем безопасности в модуле `fastapi.security`, которые упрощают использование этих механизмов безопасности.
+FastAPI предоставляет несколько инструментов для каждой из этих схем безопасности в модуле `fastapi.security`, которые упрощают использование этих механизмов безопасности.
-В следующих главах вы увидите, как обезопасить свой API, используя инструменты, предоставляемые **FastAPI**.
+В следующих главах вы увидите, как добавить безопасность в ваш API, используя инструменты, предоставляемые **FastAPI**.
-И вы также увидите, как он автоматически интегрируется в систему интерактивной документации.
+И вы также увидите, как это автоматически интегрируется в систему интерактивной документации.
diff --git a/docs/ru/docs/tutorial/security/oauth2-jwt.md b/docs/ru/docs/tutorial/security/oauth2-jwt.md
new file mode 100644
index 0000000000000..e3729dfc83f92
--- /dev/null
+++ b/docs/ru/docs/tutorial/security/oauth2-jwt.md
@@ -0,0 +1,277 @@
+# OAuth2 с паролем (и хешированием), Bearer с JWT-токенами { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
+
+Теперь, когда у нас определен процесс обеспечения безопасности, давайте сделаем приложение действительно безопасным, используя токены JWT и безопасное хеширование паролей.
+
+Этот код можно реально использовать в своем приложении, сохранять хэши паролей в базе данных и т.д.
+
+Мы продолжим разбираться, начиная с того места, на котором остановились в предыдущей главе, и расширим его.
+
+## Про JWT { #about-jwt }
+
+JWT означает "JSON Web Tokens".
+
+Это стандарт для кодирования JSON-объекта в виде длинной строки без пробелов. Выглядит это следующим образом:
+
+```
+eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
+```
+
+Он не зашифрован, поэтому любой человек может восстановить информацию из его содержимого.
+
+Но он подписан. Следовательно, когда вы получаете токен, который вы эмитировали (выдавали), вы можете убедиться, что это именно вы его эмитировали.
+
+Таким образом, можно создать токен со сроком действия, скажем, 1 неделя. А когда пользователь вернется на следующий день с тем же токеном, вы будете знать, что он все еще авторизован в вашей системе.
+
+Через неделю срок действия токена истечет, пользователь не будет авторизован и ему придется заново входить в систему, чтобы получить новый токен. А если пользователь (или третье лицо) попытается модифицировать токен, чтобы изменить срок действия, вы сможете это обнаружить, поскольку подписи не будут совпадать.
+
+Если вы хотите поиграть с JWT-токенами и посмотреть, как они работают, посмотрите [https://jwt.io](https://jwt.io/).
+
+## Установка `PyJWT` { #install-pyjwt }
+
+Нам необходимо установить `pyjwt` для генерации и проверки JWT-токенов на языке Python.
+
+Убедитесь, что вы создали [виртуальное окружение](../../virtual-environments.md), активируйте его, а затем установите `pyjwt`:
+
+
+
+Пройдите авторизацию так же, как делали раньше.
+
+Используя учетные данные пользователя:
+
+Username: `johndoe`
+Password: `secret`
+
+/// check | Проверка
+
+Обратите внимание, что нигде в коде не используется открытый текст пароля "`secret`", мы используем только его хэшированную версию.
+
+///
+
+
+
+Вызвав эндпоинт `/users/me/`, вы получите ответ в виде:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false
+}
+```
+
+
+
+Если открыть инструменты разработчика, то можно увидеть, что передаваемые данные включают только токен, пароль передается только в первом запросе для аутентификации пользователя и получения токена доступа, но не в последующих:
+
+
+
+/// note | Техническая информация
+
+Обратите внимание на HTTP-заголовок `Authorization`, значение которого начинается с `Bearer `.
+
+///
+
+## Продвинутое использование `scopes` { #advanced-usage-with-scopes }
+
+В OAuth2 существует понятие "диапазоны" ("`scopes`").
+
+С их помощью можно добавить определенный набор разрешений к JWT-токену.
+
+Затем вы можете передать этот токен непосредственно пользователю или третьей стороне для взаимодействия с вашим API с определенным набором ограничений.
+
+О том, как их использовать и как они интегрированы в **FastAPI**, читайте далее в **Расширенном руководстве пользователя**.
+
+## Резюме { #recap }
+
+С учетом того, что вы видели до сих пор, вы можете создать безопасное приложение **FastAPI**, используя такие стандарты, как OAuth2 и JWT.
+
+Практически в любом фреймворке работа с безопасностью довольно быстро превращается в сложную тему.
+
+Многие пакеты, сильно упрощающие эту задачу, вынуждены идти на многочисленные компромиссы с моделью данных, с базой данных и с доступным функционалом. Некоторые из этих пакетов, которые пытаются уж слишком все упростить, имеют даже "дыры" в системе безопасности.
+
+---
+
+**FastAPI** не делает уступок ни одной базе данных, модели данных или инструментарию.
+
+Он предоставляет вам полную свободу действий, позволяя выбирать то, что лучше всего подходит для вашего проекта.
+
+Вы можете напрямую использовать многие хорошо поддерживаемые и широко распространенные пакеты, такие как `pwdlib` и `PyJWT`, поскольку **FastAPI** не требует сложных механизмов для интеграции внешних пакетов.
+
+Напротив, он предоставляет инструменты, позволяющие максимально упростить этот процесс без ущерба для гибкости, надежности и безопасности.
+
+При этом вы можете использовать и реализовывать безопасные стандартные протоколы, такие как OAuth2, относительно простым способом.
+
+В **Расширенном руководстве пользователя** вы можете узнать больше о том, как использовать "диапазоны" ("`scopes`") OAuth2 для создания более точно настроенной системы разрешений в соответствии с теми же стандартами. OAuth2 с диапазонами — это механизм, используемый многими крупными провайдерами сервиса аутентификации, такими как Facebook, Google, GitHub, Microsoft, X (Twitter) и др., для авторизации сторонних приложений на взаимодействие с их API от имени их пользователей.
diff --git a/docs/ru/docs/tutorial/security/simple-oauth2.md b/docs/ru/docs/tutorial/security/simple-oauth2.md
new file mode 100644
index 0000000000000..4ef5109e4f614
--- /dev/null
+++ b/docs/ru/docs/tutorial/security/simple-oauth2.md
@@ -0,0 +1,273 @@
+# Простая авторизация OAuth2 с паролем и «Bearer» { #simple-oauth2-with-password-and-bearer }
+
+Теперь, отталкиваясь от предыдущей главы, добавим недостающие части, чтобы получить полный поток безопасности.
+
+## Получение `username` и `password` { #get-the-username-and-password }
+
+Для получения `username` и `password` мы будем использовать утилиты безопасности **FastAPI**.
+
+OAuth2 определяет, что при использовании "password flow" (аутентификация по паролю - именно его мы используем) клиент/пользователь должен передавать поля `username` и `password` в полях формы.
+
+В спецификации сказано, что поля должны быть названы именно так. Поэтому `user-name` или `email` работать не будут.
+
+Но не волнуйтесь, вы можете показать это конечным пользователям во фронтенде в том виде, в котором хотите.
+
+А ваши модели баз данных могут использовать любые другие имена.
+
+Но для логин-операции пути нам нужно использовать именно эти имена, чтобы быть совместимыми со спецификацией (и иметь возможность, например, использовать встроенную систему документации API).
+
+В спецификации также указано, что `username` и `password` должны передаваться в виде данных формы (так что никакого JSON здесь нет).
+
+### `scope` { #scope }
+
+В спецификации также говорится, что клиент может передать еще одно поле формы — `scope`.
+
+Имя поля формы — `scope` (в единственном числе), но на самом деле это длинная строка, состоящая из отдельных "scopes", разделенных пробелами.
+
+Каждый "scope" — это просто строка (без пробелов).
+
+Обычно они используются для указания уровней доступа, например:
+
+* `users:read` или `users:write` — распространенные примеры.
+* `instagram_basic` используется Facebook / Instagram.
+* `https://www.googleapis.com/auth/drive` используется Google.
+
+/// info | Дополнительная информация
+В OAuth2 "scope" — это просто строка, которая указывает требуемое конкретное разрешение.
+
+Не имеет значения, содержит ли она другие символы, например `:`, или является ли это URL.
+
+Эти детали зависят от реализации.
+
+Для OAuth2 это просто строки.
+///
+
+## Код для получения `username` и `password` { #code-to-get-the-username-and-password }
+
+Теперь воспользуемся утилитами, предоставляемыми **FastAPI**, чтобы обработать это.
+
+### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform }
+
+Сначала импортируйте `OAuth2PasswordRequestForm` и затем используйте её как зависимость с `Depends` в операции пути для `/token`:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}
+
+`OAuth2PasswordRequestForm` — это зависимость-класс, которая объявляет тело формы со следующими полями:
+
+* `username`.
+* `password`.
+* Необязательное поле `scope` в виде большой строки, состоящей из строк, разделенных пробелами.
+* Необязательное поле `grant_type`.
+
+/// tip | Подсказка
+По спецификации OAuth2 поле `grant_type` обязательно и содержит фиксированное значение `password`, но `OAuth2PasswordRequestForm` это не проверяет строго.
+
+Если вам нужно это строгое требование, используйте `OAuth2PasswordRequestFormStrict` вместо `OAuth2PasswordRequestForm`.
+///
+
+* Необязательное поле `client_id` (в нашем примере оно не нужно).
+* Необязательное поле `client_secret` (в нашем примере оно не нужно).
+
+/// info | Дополнительная информация
+`OAuth2PasswordRequestForm` — это не специальный класс для **FastAPI**, как `OAuth2PasswordBearer`.
+
+`OAuth2PasswordBearer` сообщает **FastAPI**, что это схема безопасности. Поэтому она добавляется в OpenAPI соответствующим образом.
+
+А `OAuth2PasswordRequestForm` — это просто зависимость-класс, которую вы могли бы написать сами, или вы могли бы объявить параметры `Form` напрямую.
+
+Но так как это распространённый вариант использования, он предоставлен **FastAPI** напрямую, чтобы упростить задачу.
+///
+
+### Использование данных формы { #use-the-form-data }
+
+/// tip | Подсказка
+У экземпляра зависимости `OAuth2PasswordRequestForm` не будет атрибута `scope` с длинной строкой, разделенной пробелами. Вместо этого будет атрибут `scopes` со списком отдельных строк — по одной для каждого переданного scope.
+
+В данном примере мы не используем `scopes`, но если вам это необходимо, функциональность есть.
+///
+
+Теперь получим данные о пользователе из (ненастоящей) базы данных, используя `username` из поля формы.
+
+Если такого пользователя нет, то мы возвращаем ошибку "Incorrect username or password" (неверное имя пользователя или пароль).
+
+Для ошибки используем исключение `HTTPException`:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}
+
+### Проверка пароля { #check-the-password }
+
+На данный момент у нас есть данные о пользователе из нашей базы данных, но мы еще не проверили пароль.
+
+Давайте сначала поместим эти данные в Pydantic-модель `UserInDB`.
+
+Никогда нельзя сохранять пароли в открытом виде, поэтому мы будем использовать (пока что ненастоящую) систему хеширования паролей.
+
+Если пароли не совпадают, мы возвращаем ту же ошибку.
+
+#### Хеширование паролей { #password-hashing }
+
+"Хеширование" означает: преобразование некоторого содержимого (в данном случае пароля) в последовательность байтов (просто строку), которая выглядит как тарабарщина.
+
+Каждый раз, когда вы передаете точно такое же содержимое (точно такой же пароль), вы получаете точно такую же тарабарщину.
+
+Но преобразовать тарабарщину обратно в пароль невозможно.
+
+##### Зачем использовать хеширование паролей { #why-use-password-hashing }
+
+Если вашу базу данных украдут, у злоумышленника не будет паролей пользователей в открытом виде, только хэши.
+
+Таким образом, он не сможет попробовать использовать эти же пароли в другой системе (поскольку многие пользователи используют один и тот же пароль повсеместно, это было бы опасно).
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}
+
+#### Про `**user_dict` { #about-user-dict }
+
+`UserInDB(**user_dict)` означает:
+
+*Передать ключи и значения `user_dict` непосредственно как аргументы ключ-значение, эквивалентно:*
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ disabled = user_dict["disabled"],
+ hashed_password = user_dict["hashed_password"],
+)
+```
+
+/// info | Дополнительная информация
+Более полное объяснение `**user_dict` можно найти в [документации к **Дополнительным моделям**](../extra-models.md#about-user-in-dict).
+///
+
+## Возврат токена { #return-the-token }
+
+Ответ операции пути `/token` должен быть объектом JSON.
+
+В нём должен быть `token_type`. В нашем случае, поскольку мы используем токены типа "Bearer", тип токена должен быть `bearer`.
+
+И в нём должен быть `access_token` — строка, содержащая наш токен доступа.
+
+В этом простом примере мы намеренно поступим небезопасно и вернём тот же `username` в качестве токена.
+
+/// tip | Подсказка
+В следующей главе вы увидите реальную защищённую реализацию с хешированием паролей и токенами JWT.
+
+Но пока давайте сосредоточимся на необходимых нам деталях.
+///
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}
+
+/// tip | Подсказка
+Согласно спецификации, вы должны возвращать JSON с `access_token` и `token_type`, как в данном примере.
+
+Это то, что вы должны сделать сами в своём коде и убедиться, что вы используете именно эти JSON-ключи.
+
+Это практически единственное, о чём нужно не забыть, чтобы соответствовать спецификациям.
+
+Остальное за вас сделает **FastAPI**.
+///
+
+## Обновление зависимостей { #update-the-dependencies }
+
+Теперь мы обновим наши зависимости.
+
+Мы хотим получить `current_user` только если этот пользователь активен.
+
+Поэтому мы создаём дополнительную зависимость `get_current_active_user`, которая, в свою очередь, использует в качестве зависимости `get_current_user`.
+
+Обе эти зависимости просто вернут HTTP-ошибку, если пользователь не существует или неактивен.
+
+Таким образом, в нашей операции пути мы получим пользователя только в том случае, если он существует, корректно аутентифицирован и активен:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}
+
+/// info | Дополнительная информация
+Дополнительный HTTP-заголовок `WWW-Authenticate` со значением `Bearer`, который мы здесь возвращаем, также является частью спецификации.
+
+Любой HTTP статус-код 401 "UNAUTHORIZED" должен также возвращать заголовок `WWW-Authenticate`.
+
+В случае с bearer-токенами (наш случай) значение этого заголовка должно быть `Bearer`.
+
+Фактически, этот дополнительный заголовок можно опустить, и всё будет работать.
+
+Но он приведён здесь для соответствия спецификациям.
+
+Кроме того, могут существовать инструменты, которые ожидают его и могут использовать, и это может быть полезно для вас или ваших пользователей — сейчас или в будущем.
+
+В этом и заключается преимущество стандартов...
+///
+
+## Посмотрим, как это работает { #see-it-in-action }
+
+Откройте интерактивную документацию: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).
+
+### Аутентификация { #authenticate }
+
+Нажмите кнопку "Authorize".
+
+Используйте учётные данные:
+
+Пользователь: `johndoe`
+
+Пароль: `secret`
+
+
+
+После аутентификации вы увидите следующее:
+
+
+
+### Получение собственных пользовательских данных { #get-your-own-user-data }
+
+Теперь используйте операцию `GET` с путём `/users/me`.
+
+Вы получите свои пользовательские данные, например:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false,
+ "hashed_password": "fakehashedsecret"
+}
+```
+
+
+
+Если щёлкнуть на значке замка и выйти из системы, а затем попробовать выполнить ту же операцию ещё раз, будет выдана ошибка HTTP 401:
+
+```JSON
+{
+ "detail": "Not authenticated"
+}
+```
+
+### Неактивный пользователь { #inactive-user }
+
+Теперь попробуйте с неактивным пользователем, аутентифицируйтесь с:
+
+Пользователь: `alice`
+
+Пароль: `secret2`
+
+И попробуйте использовать операцию `GET` с путём `/users/me`.
+
+Вы получите ошибку "Inactive user", как здесь:
+
+```JSON
+{
+ "detail": "Inactive user"
+}
+```
+
+## Резюме { #recap }
+
+Теперь у вас есть инструменты для реализации полноценной системы безопасности на основе `username` и `password` для вашего API.
+
+Используя эти средства, можно сделать систему безопасности совместимой с любой базой данных и с любой пользовательской или моделью данных.
+
+Единственная деталь, которой не хватает, — система пока ещё не "защищена" по-настоящему.
+
+В следующей главе вы увидите, как использовать библиотеку безопасного хеширования паролей и токены JWT.
diff --git a/docs/ru/docs/tutorial/server-sent-events.md b/docs/ru/docs/tutorial/server-sent-events.md
new file mode 100644
index 0000000000000..be6bd23665dfe
--- /dev/null
+++ b/docs/ru/docs/tutorial/server-sent-events.md
@@ -0,0 +1,120 @@
+# События, отправляемые сервером (SSE) { #server-sent-events-sse }
+
+Вы можете передавать данные потоком клиенту, используя Server-Sent Events (SSE).
+
+Это похоже на [Стриминг JSON Lines](stream-json-lines.md), но использует формат `text/event-stream`, который нативно поддерживается браузерами через [`EventSource` API](https://developer.mozilla.org/en-US/docs/Web/API/EventSource).
+
+/// info | Информация
+
+Добавлено в FastAPI 0.135.0.
+
+///
+
+## Что такое Server-Sent Events? { #what-are-server-sent-events }
+
+SSE — это стандарт для потоковой передачи данных с сервера на клиента по HTTP.
+
+Каждое событие — это небольшой текстовый блок с «полями», такими как `data`, `event`, `id` и `retry`, разделёнными пустыми строками.
+
+Это выглядит так:
+
+```
+data: {"name": "Portal Gun", "price": 999.99}
+
+data: {"name": "Plumbus", "price": 32.99}
+
+```
+
+SSE часто используют для стриминга ответов ИИ в чатах, живых уведомлений, логов и наблюдаемости, а также в других случаях, когда сервер «проталкивает» обновления клиенту.
+
+/// tip | Совет
+
+Если вам нужно стримить бинарные данные, например видео или аудио, посмотрите расширенное руководство: [Stream Data](../advanced/stream-data.md).
+
+///
+
+## Стриминг SSE с FastAPI { #stream-sse-with-fastapi }
+
+Чтобы стримить SSE с FastAPI, используйте `yield` в своей функции-обработчике пути и укажите `response_class=EventSourceResponse`.
+
+Импортируйте `EventSourceResponse` из `fastapi.sse`:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[4,22] *}
+
+Каждый возвращаемый через `yield` элемент кодируется как JSON и отправляется в поле `data:` события SSE.
+
+Если вы объявите тип возврата как `AsyncIterable[Item]`, FastAPI будет использовать его, чтобы выполнить **валидацию**, добавить **документацию** и **сериализовать** данные с помощью Pydantic.
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[10:12,23] *}
+
+/// tip | Совет
+
+Так как Pydantic будет сериализовать это на стороне **Rust**, вы получите значительно более высокую **производительность**, чем если не объявите тип возврата.
+
+///
+
+### Несинхронные функции-обработчики пути { #non-async-path-operation-functions }
+
+Вы также можете использовать обычные функции `def` (без `async`) и применять `yield` тем же образом.
+
+FastAPI проследит, чтобы выполнение прошло корректно и не блокировало цикл событий.
+
+Так как в этом случае функция не async, правильным типом возврата будет `Iterable[Item]`:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[28:31] hl[29] *}
+
+### Без объявленного типа возврата { #no-return-type }
+
+Вы также можете опустить тип возврата. FastAPI использует [`jsonable_encoder`](./encoder.md) для преобразования данных и их отправки.
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[34:37] hl[35] *}
+
+## `ServerSentEvent` { #serversentevent }
+
+Если вам нужно задать поля SSE, такие как `event`, `id`, `retry` или `comment`, вы можете возвращать через `yield` объекты `ServerSentEvent` вместо обычных данных.
+
+Импортируйте `ServerSentEvent` из `fastapi.sse`:
+
+{* ../../docs_src/server_sent_events/tutorial002_py310.py hl[4,26] *}
+
+Поле `data` всегда кодируется как JSON. Вы можете передавать любое значение, сериализуемое в JSON, включая Pydantic-модели.
+
+## Необработанные данные { #raw-data }
+
+Если нужно отправлять данные без JSON-кодирования, используйте `raw_data` вместо `data`.
+
+Это полезно для отправки заранее отформатированного текста, строк логов или специальных значений «сентинель», например `[DONE]`.
+
+{* ../../docs_src/server_sent_events/tutorial003_py310.py hl[17] *}
+
+/// note | Примечание
+
+`data` и `raw_data` взаимно исключают друг друга. В каждом `ServerSentEvent` можно задать только одно из них.
+
+///
+
+## Возобновление с `Last-Event-ID` { #resuming-with-last-event-id }
+
+Когда браузер переподключается после обрыва соединения, он отправляет последний полученный `id` в HTTP-заголовке `Last-Event-ID`.
+
+Вы можете прочитать его как параметр заголовка и использовать, чтобы возобновить поток с того места, где клиент остановился:
+
+{* ../../docs_src/server_sent_events/tutorial004_py310.py hl[25,27,31] *}
+
+## SSE с POST { #sse-with-post }
+
+SSE работает с любым HTTP-методом, не только с `GET`.
+
+Это полезно для таких протоколов, как [MCP](https://modelcontextprotocol.io), которые стримят SSE по `POST`:
+
+{* ../../docs_src/server_sent_events/tutorial005_py310.py hl[14] *}
+
+## Технические детали { #technical-details }
+
+FastAPI из коробки реализует некоторые лучшие практики для SSE.
+
+- Отправлять комментарий «ping» для поддержания соединения («keep alive») каждые 15 секунд, когда нет сообщений, чтобы предотвратить закрытие соединения некоторыми прокси, как рекомендовано в [HTML specification: Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes).
+- Устанавливать заголовок `Cache-Control: no-cache`, чтобы предотвратить кэширование потока.
+- Устанавливать специальный заголовок `X-Accel-Buffering: no`, чтобы предотвратить буферизацию в некоторых прокси, например Nginx.
+
+Вам не нужно ничего настраивать, это работает из коробки. 🤓
diff --git a/docs/ru/docs/tutorial/sql-databases.md b/docs/ru/docs/tutorial/sql-databases.md
new file mode 100644
index 0000000000000..ae863733879e0
--- /dev/null
+++ b/docs/ru/docs/tutorial/sql-databases.md
@@ -0,0 +1,357 @@
+# SQL (реляционные) базы данных { #sql-relational-databases }
+
+**FastAPI** не требует использовать SQL (реляционную) базу данных. Но вы можете использовать любую базу данных, которую хотите.
+
+Здесь мы рассмотрим пример с использованием [SQLModel](https://sqlmodel.tiangolo.com/).
+
+**SQLModel** построен поверх [SQLAlchemy](https://www.sqlalchemy.org/) и Pydantic. Его создал тот же автор, что и **FastAPI**, чтобы он идеально подходил для приложений FastAPI, которым нужны **SQL базы данных**.
+
+/// tip | Подсказка
+
+Вы можете использовать любую другую библиотеку для работы с SQL или NoSQL базами данных (иногда их называют "ORMs"), FastAPI ничего не навязывает. 😎
+
+///
+
+Так как SQLModel основан на SQLAlchemy, вы можете легко использовать **любую поддерживаемую** SQLAlchemy базу данных (а значит, и поддерживаемую SQLModel), например:
+
+* PostgreSQL
+* MySQL
+* SQLite
+* Oracle
+* Microsoft SQL Server, и т.д.
+
+В этом примере мы будем использовать **SQLite**, потому что она использует один файл и имеет встроенную поддержку в Python. Так что вы можете скопировать этот пример и запустить его как есть.
+
+Позже, для продакшн-приложения, возможно, вы захотите использовать серверную базу данных, например **PostgreSQL**.
+
+/// tip | Подсказка
+
+Существует официальный генератор проектов на **FastAPI** и **PostgreSQL**, включающий frontend и другие инструменты: [https://github.com/fastapi/full-stack-fastapi-template](https://github.com/fastapi/full-stack-fastapi-template)
+
+///
+
+Это очень простое и короткое руководство. Если вы хотите узнать больше о базах данных в целом, об SQL или о более продвинутых возможностях, обратитесь к [документации SQLModel](https://sqlmodel.tiangolo.com/).
+
+## Установка `SQLModel` { #install-sqlmodel }
+
+Сначала убедитесь, что вы создали [виртуальное окружение](../virtual-environments.md), активировали его и затем установили `sqlmodel`:
+
+
+
+lt
+* XWT
+* PSGI
+
+### abbr tam bir ifade ve bir açıklama verir { #the-abbr-gives-a-full-phrase-and-an-explanation }
+
+* MDN
+* I/O.
+
+////
+
+//// tab | Bilgi
+
+"abbr" öğelerinin "title" attribute'ları belirli talimatlara göre çevrilir.
+
+Çeviriler, LLM'nin kaldırmaması gereken kendi "abbr" öğelerini ekleyebilir. Örneğin İngilizce kelimeleri açıklamak için.
+
+`scripts/translate.py` içindeki genel prompt'ta `### HTML abbr elements` bölümüne bakın.
+
+////
+
+## HTML "dfn" öğeleri { #html-dfn-elements }
+
+* küme
+* Derin Öğrenme
+
+## Başlıklar { #headings }
+
+//// tab | Test
+
+### Bir web uygulaması geliştirin - bir öğretici { #develop-a-webapp-a-tutorial }
+
+Merhaba.
+
+### Type hint'ler ve -annotation'lar { #type-hints-and-annotations }
+
+Tekrar merhaba.
+
+### Super- ve subclass'lar { #super-and-subclasses }
+
+Tekrar merhaba.
+
+////
+
+//// tab | Bilgi
+
+Başlıklarla ilgili tek katı kural, LLM'nin süslü parantezler içindeki hash kısmını değiştirmemesidir; böylece link'ler bozulmaz.
+
+`scripts/translate.py` içindeki genel prompt'ta `### Headings` bölümüne bakın.
+
+Dile özel bazı talimatlar için örneğin `docs/de/llm-prompt.md` içindeki `### Headings` bölümüne bakın.
+
+////
+
+## Dokümanlarda kullanılan terimler { #terms-used-in-the-docs }
+
+//// tab | Test
+
+* siz
+* sizin
+
+* örn.
+* vb.
+
+* `foo` bir `int` olarak
+* `bar` bir `str` olarak
+* `baz` bir `list` olarak
+
+* Tutorial - Kullanıcı kılavuzu
+* İleri Düzey Kullanıcı Kılavuzu
+* SQLModel dokümanları
+* API dokümanları
+* otomatik dokümanlar
+
+* Veri Bilimi
+* Deep Learning
+* Machine Learning
+* Dependency Injection
+* HTTP Basic authentication
+* HTTP Digest
+* ISO formatı
+* JSON Schema standardı
+* JSON schema
+* schema tanımı
+* Password Flow
+* Mobil
+
+* deprecated
+* designed
+* invalid
+* on the fly
+* standard
+* default
+* case-sensitive
+* case-insensitive
+
+* uygulamayı serve etmek
+* sayfayı serve etmek
+
+* app
+* application
+
+* request
+* response
+* error response
+
+* path operation
+* path operation decorator
+* path operation function
+
+* body
+* request body
+* response body
+* JSON body
+* form body
+* file body
+* function body
+
+* parameter
+* body parameter
+* path parameter
+* query parameter
+* cookie parameter
+* header parameter
+* form parameter
+* function parameter
+
+* event
+* startup event
+* server'ın startup'ı
+* shutdown event
+* lifespan event
+
+* handler
+* event handler
+* exception handler
+* handle etmek
+
+* model
+* Pydantic model
+* data model
+* database model
+* form model
+* model object
+
+* class
+* base class
+* parent class
+* subclass
+* child class
+* sibling class
+* class method
+
+* header
+* headers
+* authorization header
+* `Authorization` header
+* forwarded header
+
+* dependency injection system
+* dependency
+* dependable
+* dependant
+
+* I/O bound
+* CPU bound
+* concurrency
+* parallelism
+* multiprocessing
+
+* env var
+* environment variable
+* `PATH`
+* `PATH` variable
+
+* authentication
+* authentication provider
+* authorization
+* authorization form
+* authorization provider
+* kullanıcı authenticate olur
+* sistem kullanıcıyı authenticate eder
+
+* CLI
+* command line interface
+
+* server
+* client
+
+* cloud provider
+* cloud service
+
+* geliştirme
+* geliştirme aşamaları
+
+* dict
+* dictionary
+* enumeration
+* enum
+* enum member
+
+* encoder
+* decoder
+* encode etmek
+* decode etmek
+
+* exception
+* raise etmek
+
+* expression
+* statement
+
+* frontend
+* backend
+
+* GitHub discussion
+* GitHub issue
+
+* performance
+* performance optimization
+
+* return type
+* return value
+
+* security
+* security scheme
+
+* task
+* background task
+* task function
+
+* template
+* template engine
+
+* type annotation
+* type hint
+
+* server worker
+* Uvicorn worker
+* Gunicorn Worker
+* worker process
+* worker class
+* workload
+
+* deployment
+* deploy etmek
+
+* SDK
+* software development kit
+
+* `APIRouter`
+* `requirements.txt`
+* Bearer Token
+* breaking change
+* bug
+* button
+* callable
+* code
+* commit
+* context manager
+* coroutine
+* database session
+* disk
+* domain
+* engine
+* fake X
+* HTTP GET method
+* item
+* library
+* lifespan
+* lock
+* middleware
+* mobile application
+* module
+* mounting
+* network
+* origin
+* override
+* payload
+* processor
+* property
+* proxy
+* pull request
+* query
+* RAM
+* remote machine
+* status code
+* string
+* tag
+* web framework
+* wildcard
+* return etmek
+* validate etmek
+
+////
+
+//// tab | Bilgi
+
+Bu, dokümanlarda görülen (çoğunlukla) teknik terimlerin eksiksiz ve normatif olmayan bir listesidir. Prompt tasarlayan kişi için, LLM'nin hangi terimlerde desteğe ihtiyaç duyduğunu anlamada yardımcı olabilir. Örneğin iyi bir çeviriyi sürekli daha zayıf bir çeviriye geri alıyorsa. Ya da sizin dilinizde bir terimi çekimlemekte (conjugating/declinating) zorlanıyorsa.
+
+Örneğin `docs/de/llm-prompt.md` içindeki `### List of English terms and their preferred German translations` bölümüne bakın.
+
+////
diff --git a/docs/tr/docs/about/index.md b/docs/tr/docs/about/index.md
new file mode 100644
index 0000000000000..a638fb0cf8c65
--- /dev/null
+++ b/docs/tr/docs/about/index.md
@@ -0,0 +1,3 @@
+# Hakkında { #about }
+
+FastAPI, tasarımı, ilham kaynağı ve daha fazlası hakkında. 🤓
diff --git a/docs/tr/docs/advanced/additional-responses.md b/docs/tr/docs/advanced/additional-responses.md
new file mode 100644
index 0000000000000..92999b2871ae5
--- /dev/null
+++ b/docs/tr/docs/advanced/additional-responses.md
@@ -0,0 +1,247 @@
+# OpenAPI'de Ek Response'lar { #additional-responses-in-openapi }
+
+/// warning | Uyarı
+
+Bu konu oldukça ileri seviye bir konudur.
+
+**FastAPI**'ye yeni başlıyorsanız buna ihtiyaç duymayabilirsiniz.
+
+///
+
+Ek status code'lar, media type'lar, açıklamalar vb. ile ek response'lar tanımlayabilirsiniz.
+
+Bu ek response'lar OpenAPI şemasına dahil edilir; dolayısıyla API dokümanlarında da görünürler.
+
+Ancak bu ek response'lar için, status code'unuzu ve içeriğinizi vererek `JSONResponse` gibi bir `Response`'u doğrudan döndürdüğünüzden emin olmanız gerekir.
+
+## `model` ile Ek Response { #additional-response-with-model }
+
+*Path operation decorator*'larınıza `responses` adlı bir parametre geçebilirsiniz.
+
+Bu parametre bir `dict` alır: anahtarlar her response için status code'lardır (`200` gibi), değerler ise her birine ait bilgileri içeren başka `dict`'lerdir.
+
+Bu response `dict`'lerinin her birinde, `response_model`'e benzer şekilde bir Pydantic model içeren `model` anahtarı olabilir.
+
+**FastAPI** bu modeli alır, JSON Schema'sını üretir ve OpenAPI'de doğru yere ekler.
+
+Örneğin, `404` status code'u ve `Message` Pydantic model'i ile başka bir response tanımlamak için şunu yazabilirsiniz:
+
+{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}
+
+/// note | Not
+
+`JSONResponse`'u doğrudan döndürmeniz gerektiğini unutmayın.
+
+///
+
+/// info | Bilgi
+
+`model` anahtarı OpenAPI'nin bir parçası değildir.
+
+**FastAPI** buradaki Pydantic model'i alır, JSON Schema'yı üretir ve doğru yere yerleştirir.
+
+Doğru yer şurasıdır:
+
+* Değeri başka bir JSON nesnesi (`dict`) olan `content` anahtarının içinde:
+ * Media type anahtarı (örn. `application/json`) bulunur; bunun değeri başka bir JSON nesnesidir ve onun içinde:
+ * Değeri model'den gelen JSON Schema olan `schema` anahtarı vardır; doğru yer burasıdır.
+ * **FastAPI** bunu doğrudan gömmek yerine OpenAPI'deki başka bir yerde bulunan global JSON Schema'lara bir referans ekler. Böylece diğer uygulamalar ve client'lar bu JSON Schema'ları doğrudan kullanabilir, daha iyi code generation araçları sağlayabilir, vb.
+
+///
+
+Bu *path operation* için OpenAPI'de üretilen response'lar şöyle olur:
+
+```JSON hl_lines="3-12"
+{
+ "responses": {
+ "404": {
+ "description": "Additional Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Message"
+ }
+ }
+ }
+ },
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+Schema'lar OpenAPI şemasının içinde başka bir yere referanslanır:
+
+```JSON hl_lines="4-16"
+{
+ "components": {
+ "schemas": {
+ "Message": {
+ "title": "Message",
+ "required": [
+ "message"
+ ],
+ "type": "object",
+ "properties": {
+ "message": {
+ "title": "Message",
+ "type": "string"
+ }
+ }
+ },
+ "Item": {
+ "title": "Item",
+ "required": [
+ "id",
+ "value"
+ ],
+ "type": "object",
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
+ },
+ "value": {
+ "title": "Value",
+ "type": "string"
+ }
+ }
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": [
+ "loc",
+ "msg",
+ "type"
+ ],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string"
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string"
+ }
+ }
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+## Ana Response İçin Ek Media Type'lar { #additional-media-types-for-the-main-response }
+
+Aynı `responses` parametresini, aynı ana response için farklı media type'lar eklemek amacıyla da kullanabilirsiniz.
+
+Örneğin, `image/png` için ek bir media type ekleyerek, *path operation*'ınızın bir JSON nesnesi (media type `application/json`) ya da bir PNG görseli döndürebildiğini belirtebilirsiniz:
+
+{* ../../docs_src/additional_responses/tutorial002_py310.py hl[17:22,26] *}
+
+/// note | Not
+
+Görseli `FileResponse` kullanarak doğrudan döndürmeniz gerektiğine dikkat edin.
+
+///
+
+/// info | Bilgi
+
+`responses` parametrenizde açıkça farklı bir media type belirtmediğiniz sürece FastAPI, response'un ana response class'ı ile aynı media type'a sahip olduğunu varsayar (varsayılan `application/json`).
+
+Ancak media type'ı `None` olan özel bir response class belirttiyseniz, FastAPI ilişkili bir model'i olan tüm ek response'lar için `application/json` kullanır.
+
+///
+
+## Bilgileri Birleştirme { #combining-information }
+
+`response_model`, `status_code` ve `responses` parametreleri dahil olmak üzere, response bilgilerini birden fazla yerden birleştirebilirsiniz.
+
+Varsayılan `200` status code'unu (ya da gerekiyorsa özel bir tane) kullanarak bir `response_model` tanımlayabilir, ardından aynı response için ek bilgileri `responses` içinde, doğrudan OpenAPI şemasına ekleyebilirsiniz.
+
+**FastAPI**, `responses` içindeki ek bilgileri korur ve model'inizin JSON Schema'sı ile birleştirir.
+
+Örneğin, Pydantic model kullanan ve özel bir `description` içeren `404` status code'lu bir response tanımlayabilirsiniz.
+
+Ayrıca `response_model`'inizi kullanan, ancak özel bir `example` içeren `200` status code'lu bir response da tanımlayabilirsiniz:
+
+{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}
+
+Bunların hepsi OpenAPI'nize birleştirilerek dahil edilir ve API dokümanlarında gösterilir:
+
+
+
+## Ön Tanımlı Response'ları Özel Olanlarla Birleştirme { #combine-predefined-responses-and-custom-ones }
+
+Birçok *path operation* için geçerli olacak bazı ön tanımlı response'larınız olabilir; ancak bunları her *path operation*'ın ihtiyaç duyduğu özel response'larla birleştirmek isteyebilirsiniz.
+
+Bu durumlarda, Python'daki bir `dict`'i `**dict_to_unpack` ile "unpacking" tekniğini kullanabilirsiniz:
+
+```Python
+old_dict = {
+ "old key": "old value",
+ "second old key": "second old value",
+}
+new_dict = {**old_dict, "new key": "new value"}
+```
+
+Burada `new_dict`, `old_dict` içindeki tüm key-value çiftlerini ve buna ek olarak yeni key-value çiftini içerir:
+
+```Python
+{
+ "old key": "old value",
+ "second old key": "second old value",
+ "new key": "new value",
+}
+```
+
+Bu tekniği, *path operation*'larınızda bazı ön tanımlı response'ları yeniden kullanmak ve bunları ek özel response'larla birleştirmek için kullanabilirsiniz.
+
+Örneğin:
+
+{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}
+
+## OpenAPI Response'ları Hakkında Daha Fazla Bilgi { #more-information-about-openapi-responses }
+
+Response'ların içine tam olarak neleri dahil edebileceğinizi görmek için OpenAPI spesifikasyonundaki şu bölümlere bakabilirsiniz:
+
+* [OpenAPI Responses Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responses-object), `Response Object`'i içerir.
+* [OpenAPI Response Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#response-object), buradaki her şeyi `responses` parametreniz içinde, her bir response'un içine doğrudan ekleyebilirsiniz. Buna `description`, `headers`, `content` (bunun içinde farklı media type'lar ve JSON Schema'lar tanımlarsınız) ve `links` dahildir.
diff --git a/docs/tr/docs/advanced/additional-status-codes.md b/docs/tr/docs/advanced/additional-status-codes.md
new file mode 100644
index 0000000000000..6db570aef78f6
--- /dev/null
+++ b/docs/tr/docs/advanced/additional-status-codes.md
@@ -0,0 +1,41 @@
+# Ek Status Code'ları { #additional-status-codes }
+
+Varsayılan olarak **FastAPI**, response'ları bir `JSONResponse` kullanarak döndürür; *path operation*'ınızdan döndürdüğünüz içeriği bu `JSONResponse`'un içine yerleştirir.
+
+Varsayılan status code'u veya *path operation* içinde sizin belirlediğiniz status code'u kullanır.
+
+## Ek status code'ları { #additional-status-codes_1 }
+
+Ana status code'a ek olarak başka status code'lar da döndürmek istiyorsanız, `JSONResponse` gibi bir `Response`'u doğrudan döndürerek bunu yapabilirsiniz ve ek status code'u doğrudan orada ayarlarsınız.
+
+Örneğin, item'ları güncellemeye izin veren bir *path operation*'ınız olduğunu düşünelim; başarılı olduğunda 200 "OK" HTTP status code'unu döndürüyor olsun.
+
+Ancak yeni item'ları da kabul etmesini istiyorsunuz. Ve item daha önce yoksa, onu oluşturup 201 "Created" HTTP status code'unu döndürsün.
+
+Bunu yapmak için `JSONResponse` import edin ve içeriğinizi doğrudan onunla döndürün; istediğiniz `status_code`'u da ayarlayın:
+
+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
+
+/// warning | Uyarı
+
+Yukarıdaki örnekte olduğu gibi bir `Response`'u doğrudan döndürdüğünüzde, response aynen olduğu gibi döndürülür.
+
+Bir model ile serialize edilmez, vb.
+
+İçinde olmasını istediğiniz veriyi taşıdığından emin olun ve değerlerin geçerli JSON olduğundan emin olun (eğer `JSONResponse` kullanıyorsanız).
+
+///
+
+/// note | Teknik Detaylar
+
+`from starlette.responses import JSONResponse` da kullanabilirsiniz.
+
+**FastAPI**, geliştirici olarak size kolaylık olsun diye `starlette.responses` içindekileri `fastapi.responses` altında da sunar. Ancak mevcut response'ların çoğu doğrudan Starlette'ten gelir. `status` için de aynı durum geçerlidir.
+
+///
+
+## OpenAPI ve API docs { #openapi-and-api-docs }
+
+Ek status code'ları ve response'ları doğrudan döndürürseniz, FastAPI sizin ne döndüreceğinizi önceden bilemeyeceği için bunlar OpenAPI şemasına (API docs) dahil edilmez.
+
+Ancak bunu kodunuzda şu şekilde dokümante edebilirsiniz: [Ek Response'lar](additional-responses.md).
diff --git a/docs/tr/docs/advanced/advanced-dependencies.md b/docs/tr/docs/advanced/advanced-dependencies.md
new file mode 100644
index 0000000000000..24453f68954ef
--- /dev/null
+++ b/docs/tr/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,163 @@
+# Gelişmiş Dependency'ler { #advanced-dependencies }
+
+## Parametreli dependency'ler { #parameterized-dependencies }
+
+Şimdiye kadar gördüğümüz tüm dependency'ler sabit bir function ya da class idi.
+
+Ancak, birçok farklı function veya class tanımlamak zorunda kalmadan, dependency üzerinde bazı parametreler ayarlamak isteyebileceğiniz durumlar olabilir.
+
+Örneğin, query parametresi `q`'nun belirli bir sabit içeriği barındırıp barındırmadığını kontrol eden bir dependency istediğimizi düşünelim.
+
+Ama bu sabit içeriği parametreleştirebilmek istiyoruz.
+
+## "Callable" bir instance { #a-callable-instance }
+
+Python'da bir class'ın instance'ını "callable" yapmanın bir yolu vardır.
+
+Class'ın kendisini değil (zaten callable'dır), o class'ın bir instance'ını.
+
+Bunu yapmak için `__call__` adında bir method tanımlarız:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}
+
+Bu durumda, ek parametreleri ve alt-dependency'leri kontrol etmek için **FastAPI**'nin kullanacağı şey bu `__call__` olacaktır; ayrıca daha sonra *path operation function* içindeki parametreye bir değer geçmek için çağrılacak olan da budur.
+
+## Instance'ı parametreleştirme { #parameterize-the-instance }
+
+Ve şimdi, dependency'yi "parametreleştirmek" için kullanacağımız instance parametrelerini tanımlamak üzere `__init__` kullanabiliriz:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}
+
+Bu durumda **FastAPI**, `__init__` ile asla uğraşmaz veya onu önemsemez; onu doğrudan kendi kodumuzda kullanırız.
+
+## Bir instance oluşturma { #create-an-instance }
+
+Bu class'tan bir instance'ı şöyle oluşturabiliriz:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}
+
+Böylece dependency'mizi "parametreleştirmiş" oluruz; artık içinde `"bar"` vardır ve bu değer `checker.fixed_content` attribute'u olarak durur.
+
+## Instance'ı dependency olarak kullanma { #use-the-instance-as-a-dependency }
+
+Sonra `Depends(FixedContentQueryChecker)` yerine `Depends(checker)` içinde bu `checker`'ı kullanabiliriz. Çünkü dependency, class'ın kendisi değil, `checker` instance'ıdır.
+
+Ve dependency çözülürken **FastAPI** bu `checker`'ı şöyle çağırır:
+
+```Python
+checker(q="somequery")
+```
+
+...ve bunun döndürdüğü her şeyi, *path operation function* içinde `fixed_content_included` parametresine dependency değeri olarak geçirir:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}
+
+/// tip | İpucu
+
+Bunların tamamı biraz yapay görünebilir. Ayrıca bunun nasıl faydalı olduğu da henüz çok net olmayabilir.
+
+Bu örnekler bilerek basit tutuldu; ama mekanizmanın nasıl çalıştığını gösteriyor.
+
+Security bölümlerinde, aynı şekilde implement edilmiş yardımcı function'lar bulunuyor.
+
+Buradaki her şeyi anladıysanız, security için kullanılan bu yardımcı araçların arka planda nasıl çalıştığını da zaten biliyorsunuz demektir.
+
+///
+
+## `yield`, `HTTPException`, `except` ve Background Tasks ile Dependency'ler { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+/// warning | Uyarı
+
+Büyük ihtimalle bu teknik detaylara ihtiyacınız yok.
+
+Bu detaylar, özellikle 0.121.0'dan eski bir FastAPI uygulamanız varsa ve `yield` kullanan dependency'lerle ilgili sorunlar yaşıyorsanız faydalıdır.
+
+///
+
+`yield` kullanan dependency'ler; farklı kullanım senaryolarını kapsamak ve bazı sorunları düzeltmek için zaman içinde evrildi. Aşağıda nelerin değiştiğinin bir özeti var.
+
+### `yield` ve `scope` ile dependency'ler { #dependencies-with-yield-and-scope }
+
+0.121.0 sürümünde FastAPI, `Depends(scope="function")` desteğini ekledi.
+
+`Depends(scope="function")` kullanıldığında, `yield` sonrasındaki çıkış kodu, *path operation function* biter bitmez, response client'a geri gönderilmeden önce çalıştırılır.
+
+`Depends(scope="request")` (varsayılan) kullanıldığında ise `yield` sonrasındaki çıkış kodu, response gönderildikten sonra çalıştırılır.
+
+Daha fazlasını [`yield` ile Dependency'ler - Erken çıkış ve `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope) dokümantasyonunda okuyabilirsiniz.
+
+### `yield` ve `StreamingResponse` ile dependency'ler, Teknik Detaylar { #dependencies-with-yield-and-streamingresponse-technical-details }
+
+FastAPI 0.118.0 öncesinde, `yield` kullanan bir dependency kullanırsanız, *path operation function* döndükten sonra ama response gönderilmeden hemen önce `yield` sonrasındaki çıkış kodu çalıştırılırdı.
+
+Amaç, response'un ağ üzerinden taşınmasını beklerken gereğinden uzun süre resource tutmaktan kaçınmaktı.
+
+Bu değişiklik aynı zamanda şunu da ifade ediyordu: `StreamingResponse` döndürürseniz, `yield` kullanan dependency'nin çıkış kodu zaten çalışmış olurdu.
+
+Örneğin, `yield` kullanan bir dependency içinde bir veritabanı session'ınız varsa, `StreamingResponse` veri stream ederken bu session'ı kullanamazdı; çünkü `yield` sonrasındaki çıkış kodunda session zaten kapatılmış olurdu.
+
+Bu davranış 0.118.0'da geri alındı ve `yield` sonrasındaki çıkış kodunun, response gönderildikten sonra çalıştırılması sağlandı.
+
+/// info | Bilgi
+
+Aşağıda göreceğiniz gibi, bu davranış 0.106.0 sürümünden önceki davranışa oldukça benzer; ancak köşe durumlar için çeşitli iyileştirmeler ve bug fix'ler içerir.
+
+///
+
+#### Erken Çıkış Kodu için Kullanım Senaryoları { #use-cases-with-early-exit-code }
+
+Bazı özel koşullardaki kullanım senaryoları, response gönderilmeden önce `yield` kullanan dependency'lerin çıkış kodunun çalıştırıldığı eski davranıştan fayda görebilir.
+
+Örneğin, `yield` kullanan bir dependency içinde yalnızca bir kullanıcıyı doğrulamak için veritabanı session'ı kullanan bir kodunuz olduğunu düşünün; ama bu session *path operation function* içinde bir daha hiç kullanılmıyor, yalnızca dependency içinde kullanılıyor **ve** response'un gönderilmesi uzun sürüyor. Mesela veriyi yavaş gönderen bir `StreamingResponse` var, ama herhangi bir nedenle veritabanını kullanmıyor.
+
+Bu durumda veritabanı session'ı, response tamamen gönderilene kadar elde tutulur. Ancak session kullanılmıyorsa, bunu elde tutmak gerekli değildir.
+
+Şöyle görünebilir:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
+
+`Session`'ın otomatik kapatılması olan çıkış kodu şurada:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
+
+...yavaş veri gönderen response'un gönderimi bittikten sonra çalıştırılır:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
+
+Ama `generate_stream()` veritabanı session'ını kullanmadığı için, response gönderilirken session'ı açık tutmak aslında gerekli değildir.
+
+SQLModel (veya SQLAlchemy) kullanarak bu spesifik senaryoya sahipseniz, session'a artık ihtiyacınız kalmadıktan sonra session'ı açıkça kapatabilirsiniz:
+
+{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}
+
+Böylece session veritabanı bağlantısını serbest bırakır ve diğer request'ler bunu kullanabilir.
+
+`yield` kullanan bir dependency'den erken çıkış gerektiren farklı bir kullanım senaryonuz varsa, lütfen kullanım senaryonuzla birlikte ve `yield` kullanan dependency'ler için erken kapatmadan neden fayda göreceğinizi açıklayarak bir [GitHub Discussion Sorusu](https://github.com/fastapi/fastapi/discussions/new?category=questions) oluşturun.
+
+`yield` kullanan dependency'lerde erken kapatma için ikna edici kullanım senaryoları varsa, erken kapatmayı seçmeli (opt-in) hale getiren yeni bir yöntem eklemeyi düşünebilirim.
+
+### `yield` ve `except` ile dependency'ler, Teknik Detaylar { #dependencies-with-yield-and-except-technical-details }
+
+FastAPI 0.110.0 öncesinde, `yield` kullanan bir dependency kullanır, sonra o dependency içinde `except` ile bir exception yakalar ve exception'ı tekrar raise etmezseniz; exception otomatik olarak herhangi bir exception handler'a veya internal server error handler'a raise/forward edilirdi.
+
+Bu davranış 0.110.0 sürümünde değiştirildi. Amaç, handler olmayan (internal server errors) forward edilmiş exception'ların yönetilmemesinden kaynaklanan bellek tüketimini düzeltmek ve bunu normal Python kodunun davranışıyla tutarlı hale getirmekti.
+
+### Background Tasks ve `yield` ile dependency'ler, Teknik Detaylar { #background-tasks-and-dependencies-with-yield-technical-details }
+
+FastAPI 0.106.0 öncesinde, `yield` sonrasında exception raise etmek mümkün değildi; çünkü `yield` kullanan dependency'lerdeki çıkış kodu response gönderildikten *sonra* çalıştırılıyordu. Bu nedenle [Exception Handler'ları](../tutorial/handling-errors.md#install-custom-exception-handlers) zaten çalışmış olurdu.
+
+Bu tasarımın ana sebeplerinden biri, background task'lerin içinde dependency'lerin "yield ettiği" aynı objeleri kullanmaya izin vermekti; çünkü çıkış kodu, background task'ler bittikten sonra çalıştırılıyordu.
+
+Bu davranış FastAPI 0.106.0'da, response'un ağ üzerinde taşınmasını beklerken resource tutmamak amacıyla değiştirildi.
+
+/// tip | İpucu
+
+Ek olarak, bir background task normalde ayrı ele alınması gereken bağımsız bir mantık setidir ve kendi resource'larına sahip olmalıdır (ör. kendi veritabanı bağlantısı).
+
+Bu şekilde muhtemelen daha temiz bir kod elde edersiniz.
+
+///
+
+Bu davranışa güvenerek kod yazdıysanız, artık background task'ler için resource'ları background task'in içinde oluşturmalı ve içeride yalnızca `yield` kullanan dependency'lerin resource'larına bağlı olmayan verileri kullanmalısınız.
+
+Örneğin, aynı veritabanı session'ını kullanmak yerine background task içinde yeni bir veritabanı session'ı oluşturur ve veritabanındaki objeleri bu yeni session ile alırsınız. Ardından, background task function'ına veritabanından gelen objeyi parametre olarak geçirmek yerine, o objenin ID'sini geçirir ve objeyi background task function'ı içinde yeniden elde edersiniz.
diff --git a/docs/tr/docs/advanced/advanced-python-types.md b/docs/tr/docs/advanced/advanced-python-types.md
new file mode 100644
index 0000000000000..91fe1d5e0947b
--- /dev/null
+++ b/docs/tr/docs/advanced/advanced-python-types.md
@@ -0,0 +1,61 @@
+# Gelişmiş Python Tipleri { #advanced-python-types }
+
+Python tipleriyle çalışırken işinize yarayabilecek bazı ek fikirler.
+
+## `Union` veya `Optional` Kullanımı { #using-union-or-optional }
+
+Kodunuz herhangi bir nedenle `|` kullanamıyorsa — örneğin bir tip açıklamasında (type annotation) değil de `response_model=` gibi bir yerdeyse — dikey çizgi (`|`) yerine `typing` içindeki `Union`'ı kullanabilirsiniz.
+
+Örneğin, bir şeyin `str` ya da `None` olabileceğini şöyle belirtebilirsiniz:
+
+```python
+from typing import Union
+
+
+def say_hi(name: Union[str, None]):
+ print(f"Hi {name}!")
+```
+
+`typing`, bir şeyin `None` olabileceğini belirtmek için `Optional` ile bir kısayol da sunar.
+
+Benim oldukça öznel bakış açıma göre küçük bir ipucu:
+
+- 🚨 `Optional[SomeType]` kullanmaktan kaçının
+- Bunun yerine ✨ **`Union[SomeType, None]` kullanın** ✨.
+
+İkisi de eşdeğer ve temelde aynıdır; ancak "**optional**" kelimesi değerin isteğe bağlı olduğunu ima eder. Oysa aslında " `None` olabilir" demektir; değer isteğe bağlı olmasa ve hâlâ zorunlu olsa bile.
+
+Bence `Union[SomeType, None]` ne demek istediğini daha açık anlatır.
+
+Burada mesele sadece kelimeler ve isimler. Ancak bu kelimeler sizin ve ekip arkadaşlarınızın koda bakışını etkileyebilir.
+
+Örnek olarak şu fonksiyona bakalım:
+
+```python
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+ print(f"Hey {name}!")
+```
+
+`name` parametresi `Optional[str]` olarak tanımlıdır; ancak isteğe bağlı değildir, parametre olmadan fonksiyonu çağıramazsınız:
+
+```Python
+say_hi() # Ah hayır, bu hata fırlatır! 😱
+```
+
+`name` parametresi varsayılan bir değeri olmadığı için hâlâ zorunludur (yani *optional* değildir). Yine de `name`, değer olarak `None` kabul eder:
+
+```Python
+say_hi(name=None) # Bu çalışır, None geçerlidir 🎉
+```
+
+İyi haber şu ki, çoğu durumda tip birliklerini (union) tanımlamak için doğrudan `|` kullanabilirsiniz:
+
+```python
+def say_hi(name: str | None):
+ print(f"Hey {name}!")
+```
+
+Dolayısıyla, normalde `Optional` ve `Union` gibi isimler için endişelenmenize gerek yok. 😎
diff --git a/docs/tr/docs/advanced/async-tests.md b/docs/tr/docs/advanced/async-tests.md
new file mode 100644
index 0000000000000..99951a899e149
--- /dev/null
+++ b/docs/tr/docs/advanced/async-tests.md
@@ -0,0 +1,99 @@
+# Async Testler { #async-tests }
+
+Sağlanan `TestClient` ile **FastAPI** uygulamalarınızı nasıl test edeceğinizi zaten gördünüz. Şimdiye kadar yalnızca senkron testler yazdık, yani `async` fonksiyonlar kullanmadan.
+
+Testlerinizde asenkron fonksiyonlar kullanabilmek faydalı olabilir; örneğin veritabanınızı asenkron olarak sorguluyorsanız. Diyelim ki FastAPI uygulamanıza request gönderilmesini test etmek ve ardından async bir veritabanı kütüphanesi kullanırken backend'in doğru veriyi veritabanına başarıyla yazdığını doğrulamak istiyorsunuz.
+
+Bunu nasıl çalıştırabileceğimize bir bakalım.
+
+## pytest.mark.anyio { #pytest-mark-anyio }
+
+Testlerimizde asenkron fonksiyonlar çağırmak istiyorsak, test fonksiyonlarımızın da asenkron olması gerekir. AnyIO bunun için güzel bir plugin sağlar; böylece bazı test fonksiyonlarının asenkron olarak çağrılacağını belirtebiliriz.
+
+## HTTPX { #httpx }
+
+**FastAPI** uygulamanız `async def` yerine normal `def` fonksiyonları kullanıyor olsa bile, altta yatan yapı hâlâ bir `async` uygulamadır.
+
+`TestClient`, standart pytest kullanarak normal `def` test fonksiyonlarınızın içinden asenkron FastAPI uygulamasını çağırmak için içeride bazı “sihirli” işlemler yapar. Ancak bu sihir, onu asenkron fonksiyonların içinde kullandığımızda artık çalışmaz. Testlerimizi asenkron çalıştırdığımızda, test fonksiyonlarımızın içinde `TestClient` kullanamayız.
+
+`TestClient`, [HTTPX](https://www.python-httpx.org) tabanlıdır ve neyse ki API'yi test etmek için HTTPX'i doğrudan kullanabiliriz.
+
+## Örnek { #example }
+
+Basit bir örnek için, [Daha Büyük Uygulamalar](../tutorial/bigger-applications.md) ve [Test Etme](../tutorial/testing.md) bölümlerinde anlatılana benzer bir dosya yapısı düşünelim:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+`main.py` dosyası şöyle olur:
+
+{* ../../docs_src/async_tests/app_a_py310/main.py *}
+
+`test_main.py` dosyasında `main.py` için testler yer alır, artık şöyle görünebilir:
+
+{* ../../docs_src/async_tests/app_a_py310/test_main.py *}
+
+## Çalıştırma { #run-it }
+
+Testlerinizi her zamanki gibi şu şekilde çalıştırabilirsiniz:
+
+
+
+Ancak docs UI'yi proxy üzerinden, `9999` portuyla, `/api/v1/docs` altında "resmi" URL'den açarsak doğru çalışır! 🎉
+
+Şuradan kontrol edebilirsiniz: [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs):
+
+
+
+Tam istediğimiz gibi. ✔️
+
+Bunun nedeni, FastAPI'nin OpenAPI içinde varsayılan `server`'ı, `root_path` tarafından verilen URL ile oluşturmak için bu `root_path`'i kullanmasıdır.
+
+## Ek `server`'lar { #additional-servers }
+
+/// warning | Uyarı
+
+Bu daha ileri seviye bir kullanım senaryosudur. İsterseniz atlayabilirsiniz.
+
+///
+
+Varsayılan olarak **FastAPI**, OpenAPI şemasında `root_path` için bir `server` oluşturur.
+
+Ancak başka alternatif `servers` da sağlayabilirsiniz; örneğin *aynı* docs UI'nin hem staging hem de production ortamıyla etkileşime girmesini istiyorsanız.
+
+Özel bir `servers` listesi verirseniz ve bir `root_path` varsa (çünkü API'niz proxy arkasındadır), **FastAPI** bu `root_path` ile bir "server"ı listenin başına ekler.
+
+Örneğin:
+
+{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}
+
+Şöyle bir OpenAPI şeması üretir:
+
+```JSON hl_lines="5-7"
+{
+ "openapi": "3.1.0",
+ // Burada daha fazla şey var
+ "servers": [
+ {
+ "url": "/api/v1"
+ },
+ {
+ "url": "https://stag.example.com",
+ "description": "Staging environment"
+ },
+ {
+ "url": "https://prod.example.com",
+ "description": "Production environment"
+ }
+ ],
+ "paths": {
+ // Burada daha fazla şey var
+ }
+}
+```
+
+/// tip | İpucu
+
+`url` değeri `/api/v1` olan, `root_path`'ten alınmış otomatik üretilen server'a dikkat edin.
+
+///
+
+Docs UI'de, [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs) adresinde şöyle görünür:
+
+
+
+/// tip | İpucu
+
+Docs UI, seçtiğiniz server ile etkileşime girer.
+
+///
+
+/// note | Teknik Detaylar
+
+OpenAPI spesifikasyonunda `servers` özelliği opsiyoneldir.
+
+`servers` parametresini belirtmezseniz ve `root_path` `/` ile aynıysa, üretilen OpenAPI şemasında `servers` özelliği varsayılan olarak tamamen çıkarılır; bu da `url` değeri `/` olan tek bir server ile eşdeğerdir.
+
+///
+
+### `root_path`'ten Otomatik `server` Eklenmesini Kapatma { #disable-automatic-server-from-root-path }
+
+**FastAPI**'nin `root_path` kullanarak otomatik bir server eklemesini istemiyorsanız, `root_path_in_servers=False` parametresini kullanabilirsiniz:
+
+{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}
+
+Böylece OpenAPI şemasına dahil etmez.
+
+## Bir Sub-Application Mount Etme { #mounting-a-sub-application }
+
+Bir sub-application'ı ([Sub Applications - Mounts](sub-applications.md) bölümünde anlatıldığı gibi) mount etmeniz gerekiyorsa ve aynı zamanda `root_path` ile bir proxy kullanıyorsanız, bunu beklendiği gibi normal şekilde yapabilirsiniz.
+
+FastAPI içeride `root_path`'i akıllıca kullanır; dolayısıyla doğrudan çalışır. ✨
diff --git a/docs/tr/docs/advanced/custom-response.md b/docs/tr/docs/advanced/custom-response.md
new file mode 100644
index 0000000000000..73ac29b1617e0
--- /dev/null
+++ b/docs/tr/docs/advanced/custom-response.md
@@ -0,0 +1,272 @@
+# Özel Response - HTML, Stream, File ve Diğerleri { #custom-response-html-stream-file-others }
+
+Varsayılan olarak **FastAPI**, JSON response'lar döndürür.
+
+Bunu, [Doğrudan bir Response döndür](response-directly.md) bölümünde gördüğünüz gibi doğrudan bir `Response` döndürerek geçersiz kılabilirsiniz.
+
+Ancak doğrudan bir `Response` döndürürseniz (veya `JSONResponse` gibi herhangi bir alt sınıfını), veri otomatik olarak dönüştürülmez (bir `response_model` tanımlamış olsanız bile) ve dokümantasyon da otomatik üretilmez (örneğin, üretilen OpenAPI’nin parçası olarak HTTP header `Content-Type` içindeki ilgili "media type" dahil edilmez).
+
+Bununla birlikte, *path operation decorator* içinde `response_class` parametresini kullanarak hangi `Response`’un (örn. herhangi bir `Response` alt sınıfı) kullanılacağını da ilan edebilirsiniz.
+
+*path operation function*’ınızdan döndürdüğünüz içerik, o `Response`’un içine yerleştirilir.
+
+/// note | Not
+
+Media type’ı olmayan bir response class kullanırsanız, FastAPI response’unuzun content içermediğini varsayar; bu yüzden ürettiği OpenAPI dokümanında response formatını dokümante etmez.
+
+///
+
+## JSON Response'lar { #json-responses }
+
+Varsayılan olarak FastAPI JSON response'lar döndürür.
+
+Bir [Response Model](../tutorial/response-model.md) tanımlarsanız, FastAPI veriyi Pydantic kullanarak JSON’a serialize eder.
+
+Bir response modeli tanımlamazsanız, FastAPI [JSON Compatible Encoder](../tutorial/encoder.md) bölümünde açıklanan `jsonable_encoder`’ı kullanır ve sonucu bir `JSONResponse` içine koyar.
+
+`JSONResponse` örneğinde olduğu gibi JSON media type’ına (`application/json`) sahip bir `response_class` tanımlarsanız, döndürdüğünüz veri; *path operation decorator* içinde tanımladığınız herhangi bir Pydantic `response_model` ile otomatik olarak dönüştürülür (ve filtrelenir). Ancak veri Pydantic ile JSON bytes’a serialize edilmez; bunun yerine `jsonable_encoder` ile dönüştürülür ve ardından Python’un standart JSON kütüphanesini kullanarak bytes’a serialize edecek olan `JSONResponse` class’ına iletilir.
+
+### JSON Performansı { #json-performance }
+
+Kısaca, en yüksek performansı istiyorsanız bir [Response Model](../tutorial/response-model.md) kullanın ve *path operation decorator* içinde `response_class` tanımlamayın.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py ln[15:17] hl[16] *}
+
+## HTML Response { #html-response }
+
+**FastAPI**’den doğrudan HTML içeren bir response döndürmek için `HTMLResponse` kullanın.
+
+* `HTMLResponse` import edin.
+* *path operation decorator*’ınızın `response_class` parametresi olarak `HTMLResponse` verin.
+
+{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}
+
+/// info | Bilgi
+
+`response_class` parametresi, response’un "media type"’ını tanımlamak için de kullanılır.
+
+Bu durumda HTTP header `Content-Type`, `text/html` olarak ayarlanır.
+
+Ve OpenAPI’de de bu şekilde dokümante edilir.
+
+///
+
+### Bir `Response` Döndür { #return-a-response }
+
+[Doğrudan bir Response döndür](response-directly.md) bölümünde görüldüğü gibi, *path operation* içinde doğrudan bir response döndürerek response’u override edebilirsiniz.
+
+Yukarıdaki örneğin aynısı, bu sefer bir `HTMLResponse` döndürerek, şöyle görünebilir:
+
+{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}
+
+/// warning | Uyarı
+
+*path operation function*’ınızın doğrudan döndürdüğü bir `Response`, OpenAPI’de dokümante edilmez (örneğin `Content-Type` dokümante edilmez) ve otomatik interaktif dokümanlarda görünmez.
+
+///
+
+/// info | Bilgi
+
+Elbette gerçek `Content-Type` header’ı, status code vb. değerler, döndürdüğünüz `Response` objesinden gelir.
+
+///
+
+### OpenAPI’de Dokümante Et ve `Response`’u Override Et { #document-in-openapi-and-override-response }
+
+Response’u fonksiyonun içinden override etmek ama aynı zamanda OpenAPI’de "media type"’ı dokümante etmek istiyorsanız, `response_class` parametresini kullanıp ayrıca bir `Response` objesi döndürebilirsiniz.
+
+Bu durumda `response_class` sadece OpenAPI *path operation*’ını dokümante etmek için kullanılır; sizin `Response`’unuz ise olduğu gibi kullanılır.
+
+#### Doğrudan bir `HTMLResponse` Döndür { #return-an-htmlresponse-directly }
+
+Örneğin şöyle bir şey olabilir:
+
+{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}
+
+Bu örnekte `generate_html_response()` fonksiyonu, HTML’i bir `str` olarak döndürmek yerine zaten bir `Response` üretip döndürmektedir.
+
+`generate_html_response()` çağrısının sonucunu döndürerek, varsayılan **FastAPI** davranışını override edecek bir `Response` döndürmüş olursunuz.
+
+Ama `response_class` içinde `HTMLResponse` da verdiğiniz için **FastAPI**, bunu OpenAPI’de ve interaktif dokümanlarda `text/html` ile HTML olarak nasıl dokümante edeceğini bilir:
+
+
+
+## Mevcut Response'lar { #available-responses }
+
+Mevcut response'lardan bazıları aşağıdadır.
+
+Unutmayın: `Response` ile başka herhangi bir şeyi döndürebilir, hatta özel bir alt sınıf da oluşturabilirsiniz.
+
+/// note | Teknik Detaylar
+
+`from starlette.responses import HTMLResponse` da kullanabilirsiniz.
+
+**FastAPI**, geliştirici için kolaylık olsun diye `starlette.responses` içindekileri `fastapi.responses` olarak da sağlar. Ancak mevcut response'ların çoğu doğrudan Starlette’ten gelir.
+
+///
+
+### `Response` { #response }
+
+Ana `Response` class’ıdır; diğer tüm response'lar bundan türetilir.
+
+Bunu doğrudan döndürebilirsiniz.
+
+Şu parametreleri kabul eder:
+
+* `content` - Bir `str` veya `bytes`.
+* `status_code` - Bir `int` HTTP status code.
+* `headers` - String’lerden oluşan bir `dict`.
+* `media_type` - Media type’ı veren bir `str`. Örn. `"text/html"`.
+
+FastAPI (aslında Starlette) otomatik olarak bir Content-Length header’ı ekler. Ayrıca `media_type`’a göre bir Content-Type header’ı ekler ve text türleri için sona bir charset ekler.
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+### `HTMLResponse` { #htmlresponse }
+
+Yukarıda okuduğunuz gibi, bir miktar text veya bytes alır ve HTML response döndürür.
+
+### `PlainTextResponse` { #plaintextresponse }
+
+Bir miktar text veya bytes alır ve düz metin response döndürür.
+
+{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}
+
+### `JSONResponse` { #jsonresponse }
+
+Bir miktar veri alır ve `application/json` olarak encode edilmiş bir response döndürür.
+
+Yukarıda okuduğunuz gibi, **FastAPI**’de varsayılan response budur.
+
+/// note | Teknik Detaylar
+
+Ancak bir response modeli veya dönüş tipi (return type) tanımlarsanız, veri doğrudan JSON’a serialize edilir ve JSON için doğru media type’a sahip bir response, `JSONResponse` class’ı kullanılmadan doğrudan döndürülür.
+
+Bu, en iyi performansı elde etmenin ideal yoludur.
+
+///
+
+### `RedirectResponse` { #redirectresponse }
+
+HTTP redirect döndürür. Varsayılan olarak 307 status code (Temporary Redirect) kullanır.
+
+`RedirectResponse`’u doğrudan döndürebilirsiniz:
+
+{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}
+
+---
+
+Veya `response_class` parametresi içinde kullanabilirsiniz:
+
+{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}
+
+Bunu yaparsanız, *path operation* function’ınızdan doğrudan URL döndürebilirsiniz.
+
+Bu durumda kullanılan `status_code`, `RedirectResponse` için varsayılan olan `307` olur.
+
+---
+
+Ayrıca `status_code` parametresini `response_class` parametresiyle birlikte kullanabilirsiniz:
+
+{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}
+
+### `StreamingResponse` { #streamingresponse }
+
+Bir async generator veya normal generator/iterator (içinde `yield` olan bir fonksiyon) alır ve response body’yi stream eder.
+
+{* ../../docs_src/custom_response/tutorial007_py310.py hl[3,16] *}
+
+/// note | Teknik Detaylar
+
+Bir `async` görev, yalnızca bir `await` noktasına geldiğinde iptal edilebilir. Eğer hiç `await` yoksa, generator (içinde `yield` olan fonksiyon) düzgün şekilde iptal edilemez ve iptal istendikten sonra bile çalışmaya devam edebilir.
+
+Bu küçük örneğin `await` ifadesine ihtiyacı olmadığı için, event loop’un iptali ele alabilmesi adına `await anyio.sleep(0)` ekliyoruz.
+
+Büyük veya sonsuz akışlarda bu daha da önemlidir.
+
+///
+
+/// tip | İpucu
+
+Doğrudan bir `StreamingResponse` döndürmek yerine, muhtemelen [Veri Stream Etme](./stream-data.md) bölümündeki tarzı takip etmelisiniz; çok daha kullanışlıdır ve iptali arka planda sizin için halleder.
+
+JSON Lines stream ediyorsanız, [JSON Lines Stream Etme](../tutorial/stream-json-lines.md) kılavuzunu izleyin.
+
+///
+
+### `FileResponse` { #fileresponse }
+
+Asenkron olarak bir dosyayı response olarak stream eder.
+
+Diğer response türlerine göre instantiate ederken farklı argümanlar alır:
+
+* `path` - Stream edilecek dosyanın dosya path'i.
+* `headers` - Eklenecek özel header’lar; dictionary olarak.
+* `media_type` - Media type’ı veren string. Ayarlanmazsa, dosya adı veya path kullanılarak media type tahmin edilir.
+* `filename` - Ayarlanırsa response içindeki `Content-Disposition`’a dahil edilir.
+
+File response'ları uygun `Content-Length`, `Last-Modified` ve `ETag` header’larını içerir.
+
+{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}
+
+`response_class` parametresini de kullanabilirsiniz:
+
+{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}
+
+Bu durumda *path operation* function’ınızdan doğrudan dosya path'ini döndürebilirsiniz.
+
+## Özel response class { #custom-response-class }
+
+`Response`’dan türeterek kendi özel response class’ınızı oluşturabilir ve kullanabilirsiniz.
+
+Örneğin, bazı ayarlarla [`orjson`](https://github.com/ijl/orjson) kullanmak istediğinizi varsayalım.
+
+Diyelim ki girintili ve biçimlendirilmiş JSON döndürmek istiyorsunuz; bunun için orjson seçeneği `orjson.OPT_INDENT_2`’yi kullanmak istiyorsunuz.
+
+Bir `CustomORJSONResponse` oluşturabilirsiniz. Burada yapmanız gereken temel şey, content’i `bytes` olarak döndüren bir `Response.render(content)` metodu yazmaktır:
+
+{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}
+
+Artık şunu döndürmek yerine:
+
+```json
+{"message": "Hello World"}
+```
+
+...bu response şunu döndürür:
+
+```json
+{
+ "message": "Hello World"
+}
+```
+
+Elbette JSON’u formatlamaktan çok daha iyi şekillerde bundan faydalanabilirsiniz. 😉
+
+### `orjson` mı Response Model mi { #orjson-or-response-model }
+
+Aradığınız şey performans ise, büyük olasılıkla bir `orjson` response’tan ziyade bir [Response Model](../tutorial/response-model.md) kullanmak daha iyi olacaktır.
+
+Bir response modeliyle FastAPI, veriyi JSON’a serialize etmek için Pydantic’i kullanır; böylece diğer durumlarda olacağı gibi `jsonable_encoder` ile ara dönüşümlere gerek kalmaz.
+
+Ve kaputun altında, Pydantic JSON’a serialize etmek için `orjson` ile aynı Rust tabanlı mekanizmaları kullanır; bu nedenle bir response modeliyle zaten en iyi performansı elde edersiniz.
+
+## Varsayılan response class { #default-response-class }
+
+Bir **FastAPI** class instance’ı veya bir `APIRouter` oluştururken, varsayılan olarak hangi response class’ının kullanılacağını belirtebilirsiniz.
+
+Bunu tanımlayan parametre `default_response_class`’tır.
+
+Aşağıdaki örnekte **FastAPI**, tüm *path operations* için varsayılan olarak JSON yerine `HTMLResponse` kullanır.
+
+{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}
+
+/// tip | İpucu
+
+Daha önce olduğu gibi, *path operations* içinde `response_class`’ı yine override edebilirsiniz.
+
+///
+
+## Ek dokümantasyon { #additional-documentation }
+
+OpenAPI’de media type’ı ve daha birçok detayı `responses` kullanarak da tanımlayabilirsiniz: [OpenAPI’de Ek Response'lar](additional-responses.md).
diff --git a/docs/tr/docs/advanced/dataclasses.md b/docs/tr/docs/advanced/dataclasses.md
new file mode 100644
index 0000000000000..998ccea8a2e28
--- /dev/null
+++ b/docs/tr/docs/advanced/dataclasses.md
@@ -0,0 +1,95 @@
+# Dataclass Kullanımı { #using-dataclasses }
+
+FastAPI, **Pydantic** üzerine inşa edilmiştir ve request/response tanımlamak için Pydantic model'lerini nasıl kullanacağınızı gösteriyordum.
+
+Ancak FastAPI, [`dataclasses`](https://docs.python.org/3/library/dataclasses.html) kullanmayı da aynı şekilde destekler:
+
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
+
+Bu destek hâlâ **Pydantic** sayesinde vardır; çünkü Pydantic, [`dataclasses` için dahili destek](https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel) sunar.
+
+Yani yukarıdaki kod Pydantic'i doğrudan kullanmasa bile, FastAPI bu standart dataclass'ları Pydantic'in kendi dataclass biçimine dönüştürmek için Pydantic'i kullanmaktadır.
+
+Ve elbette aynı özellikleri destekler:
+
+* veri doğrulama (data validation)
+* veri serileştirme (data serialization)
+* veri dokümantasyonu (data documentation), vb.
+
+Bu, Pydantic model'lerinde olduğu gibi çalışır. Aslında arka planda da aynı şekilde, Pydantic kullanılarak yapılır.
+
+/// info | Bilgi
+
+Dataclass'ların, Pydantic model'lerinin yapabildiği her şeyi yapamadığını unutmayın.
+
+Bu yüzden yine de Pydantic model'lerini kullanmanız gerekebilir.
+
+Ancak elinizde zaten bir sürü dataclass varsa, bunları FastAPI ile bir web API'yi beslemek için kullanmak güzel bir numaradır. 🤓
+
+///
+
+## `response_model` İçinde Dataclass'lar { #dataclasses-in-response-model }
+
+`response_model` parametresinde `dataclasses` da kullanabilirsiniz:
+
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
+
+Dataclass otomatik olarak bir Pydantic dataclass'ına dönüştürülür.
+
+Bu sayede şeması API docs kullanıcı arayüzünde görünür:
+
+
+
+## İç İçe Veri Yapılarında Dataclass'lar { #dataclasses-in-nested-data-structures }
+
+İç içe veri yapıları oluşturmak için `dataclasses` ile diğer type annotation'ları da birleştirebilirsiniz.
+
+Bazı durumlarda yine de Pydantic'in `dataclasses` sürümünü kullanmanız gerekebilir. Örneğin, otomatik oluşturulan API dokümantasyonunda hata alıyorsanız.
+
+Bu durumda standart `dataclasses` yerine, drop-in replacement olan `pydantic.dataclasses` kullanabilirsiniz:
+
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+
+1. `field` hâlâ standart `dataclasses` içinden import edilir.
+
+2. `pydantic.dataclasses`, `dataclasses` için bir drop-in replacement'tır.
+
+3. `Author` dataclass'ı, `Item` dataclass'larından oluşan bir liste içerir.
+
+4. `Author` dataclass'ı, `response_model` parametresi olarak kullanılır.
+
+5. Request body olarak dataclass'larla birlikte diğer standart type annotation'ları da kullanabilirsiniz.
+
+ Bu örnekte, `Item` dataclass'larından oluşan bir listedir.
+
+6. Burada `items` içeren bir dictionary döndürüyoruz; `items` bir dataclass listesi.
+
+ FastAPI, veriyi JSON'a serileştirmeyi yine başarır.
+
+7. Burada `response_model`, `Author` dataclass'larından oluşan bir listenin type annotation'ını kullanıyor.
+
+ Yine `dataclasses` ile standart type annotation'ları birleştirebilirsiniz.
+
+8. Bu *path operation function*, `async def` yerine normal `def` kullanıyor.
+
+ Her zaman olduğu gibi, FastAPI'de ihtiyaca göre `def` ve `async def`’i birlikte kullanabilirsiniz.
+
+ Hangisini ne zaman kullanmanız gerektiğine dair hızlı bir hatırlatma isterseniz, [`async` ve `await`](../async.md#in-a-hurry) dokümanındaki _"In a hurry?"_ bölümüne bakın.
+
+9. Bu *path operation function* dataclass döndürmüyor (isterse döndürebilir), onun yerine dahili verilerle bir dictionary listesi döndürüyor.
+
+ FastAPI, response'u dönüştürmek için (dataclass'ları içeren) `response_model` parametresini kullanacaktır.
+
+Karmaşık veri yapıları oluşturmak için `dataclasses` ile diğer type annotation'ları pek çok farklı kombinasyonda birleştirebilirsiniz.
+
+Daha spesifik ayrıntılar için yukarıdaki kod içi annotation ipuçlarına bakın.
+
+## Daha Fazla Öğrenin { #learn-more }
+
+`dataclasses`'ı diğer Pydantic model'leriyle de birleştirebilir, onlardan kalıtım alabilir, kendi model'lerinize dahil edebilirsiniz, vb.
+
+Daha fazlası için [Pydantic'in dataclasses dokümantasyonuna](https://docs.pydantic.dev/latest/concepts/dataclasses/) bakın.
+
+## Sürüm { #version }
+
+Bu özellik FastAPI `0.67.0` sürümünden beri mevcuttur. 🔖
diff --git a/docs/tr/docs/advanced/events.md b/docs/tr/docs/advanced/events.md
new file mode 100644
index 0000000000000..c66342213d394
--- /dev/null
+++ b/docs/tr/docs/advanced/events.md
@@ -0,0 +1,165 @@
+# Lifespan Olayları { #lifespan-events }
+
+Uygulama **başlamadan** önce çalıştırılması gereken mantığı (kodu) tanımlayabilirsiniz. Bu, bu kodun **bir kez**, uygulama **request almaya başlamadan önce** çalıştırılacağı anlamına gelir.
+
+Benzer şekilde, uygulama **kapanırken** çalıştırılması gereken mantığı (kodu) da tanımlayabilirsiniz. Bu durumda bu kod, muhtemelen **çok sayıda request** işlendi **sonra**, **bir kez** çalıştırılır.
+
+Bu kod, uygulama request almaya **başlamadan** önce ve request’leri işlemeyi **bitirdikten** hemen sonra çalıştığı için, uygulamanın tüm **lifespan**’ını (birazdan "lifespan" kelimesi önemli olacak 😉) kapsar.
+
+Bu yaklaşım, tüm uygulama boyunca kullanacağınız ve request’ler arasında **paylaşılan** **resource**’ları kurmak ve/veya sonrasında bunları **temizlemek** için çok faydalıdır. Örneğin bir veritabanı connection pool’u ya da paylaşılan bir machine learning modelini yüklemek gibi.
+
+## Kullanım Senaryosu { #use-case }
+
+Önce bir **kullanım senaryosu** örneğiyle başlayalım, sonra bunu bununla nasıl çözeceğimize bakalım.
+
+Request’leri işlemek için kullanmak istediğiniz bazı **machine learning modelleriniz** olduğunu hayal edelim. 🤖
+
+Aynı modeller request’ler arasında paylaşılır; yani request başına bir model, kullanıcı başına bir model vb. gibi değil.
+
+Modeli yüklemenin, diskten çok fazla **data** okunması gerektiği için **oldukça uzun sürebildiğini** düşünelim. Dolayısıyla bunu her request için yapmak istemezsiniz.
+
+Modeli modülün/dosyanın en üst seviyesinde yükleyebilirdiniz; ancak bu, basit bir otomatik test çalıştırdığınızda bile **modelin yükleneceği** anlamına gelir. Böyle olunca test, kodun bağımsız bir kısmını çalıştırabilmek için önce modelin yüklenmesini beklemek zorunda kalır ve **yavaş** olur.
+
+Burada çözeceğimiz şey bu: modeli request’ler işlenmeden önce yükleyelim, ama kod yüklenirken değil; yalnızca uygulama request almaya başlamadan hemen önce.
+
+## Lifespan { #lifespan }
+
+Bu *startup* ve *shutdown* mantığını, `FastAPI` uygulamasının `lifespan` parametresi ve bir "context manager" kullanarak tanımlayabilirsiniz (bunun ne olduğunu birazdan göstereceğim).
+
+Önce bir örnekle başlayıp sonra ayrıntılarına bakalım.
+
+Aşağıdaki gibi `yield` kullanan async bir `lifespan()` fonksiyonu oluşturuyoruz:
+
+{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}
+
+Burada, `yield` öncesinde (sahte) model fonksiyonunu machine learning modellerini içeren dictionary’e koyarak, modeli yükleme gibi maliyetli bir *startup* işlemini simüle ediyoruz. Bu kod, *startup* sırasında, uygulama **request almaya başlamadan önce** çalıştırılır.
+
+Ardından `yield`’den hemen sonra modeli bellekten kaldırıyoruz (unload). Bu kod, uygulama **request’leri işlemeyi bitirdikten sonra**, *shutdown*’dan hemen önce çalıştırılır. Örneğin memory veya GPU gibi resource’ları serbest bırakabilir.
+
+/// tip | İpucu
+
+`shutdown`, uygulamayı **durdurduğunuzda** gerçekleşir.
+
+Belki yeni bir sürüm başlatmanız gerekiyordur, ya da çalıştırmaktan sıkılmışsınızdır. 🤷
+
+///
+
+### Lifespan fonksiyonu { #lifespan-function }
+
+Dikkat edilmesi gereken ilk şey, `yield` içeren async bir fonksiyon tanımlıyor olmamız. Bu, `yield` kullanan Dependencies’e oldukça benzer.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}
+
+Fonksiyonun `yield`’den önceki kısmı, uygulama başlamadan **önce** çalışır.
+
+`yield`’den sonraki kısım ise, uygulama işini bitirdikten **sonra** çalışır.
+
+### Async Context Manager { #async-context-manager }
+
+Bakarsanız, fonksiyon `@asynccontextmanager` ile dekore edilmiş.
+
+Bu da fonksiyonu "**async context manager**" denen şeye dönüştürür.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}
+
+Python’da **context manager**, `with` ifadesi içinde kullanabildiğiniz bir yapıdır. Örneğin `open()` bir context manager olarak kullanılabilir:
+
+```Python
+with open("file.txt") as file:
+ file.read()
+```
+
+Python’ın güncel sürümlerinde bir de **async context manager** vardır. Bunu `async with` ile kullanırsınız:
+
+```Python
+async with lifespan(app):
+ await do_stuff()
+```
+
+Yukarıdaki gibi bir context manager veya async context manager oluşturduğunuzda, yaptığı şey şudur: `with` bloğuna girmeden önce `yield`’den önceki kodu çalıştırır, `with` bloğundan çıktıktan sonra da `yield`’den sonraki kodu çalıştırır.
+
+Yukarıdaki kod örneğimizde bunu doğrudan kullanmıyoruz; bunun yerine FastAPI’ye veriyoruz ki o kullansın.
+
+`FastAPI` uygulamasının `lifespan` parametresi bir **async context manager** alır; dolayısıyla oluşturduğumuz yeni `lifespan` async context manager’ını buraya geçebiliriz.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[22] *}
+
+## Alternatif Events (kullanımdan kaldırıldı) { #alternative-events-deprecated }
+
+/// warning | Uyarı
+
+*startup* ve *shutdown* işlemlerini yönetmenin önerilen yolu, yukarıda anlatıldığı gibi `FastAPI` uygulamasının `lifespan` parametresini kullanmaktır. Bir `lifespan` parametresi sağlarsanız, `startup` ve `shutdown` event handler’ları artık çağrılmaz. Ya tamamen `lifespan` ya da tamamen events; ikisi birden değil.
+
+Muhtemelen bu bölümü atlayabilirsiniz.
+
+///
+
+*startup* ve *shutdown* sırasında çalıştırılacak bu mantığı tanımlamanın alternatif bir yolu daha vardır.
+
+Uygulama başlamadan önce veya uygulama kapanırken çalıştırılması gereken event handler’ları (fonksiyonları) tanımlayabilirsiniz.
+
+Bu fonksiyonlar `async def` ile veya normal `def` ile tanımlanabilir.
+
+### `startup` eventi { #startup-event }
+
+Uygulama başlamadan önce çalıştırılacak bir fonksiyon eklemek için, `"startup"` event’i ile tanımlayın:
+
+{* ../../docs_src/events/tutorial001_py310.py hl[8] *}
+
+Bu durumda `startup` event handler fonksiyonu, "database" öğesini (sadece bir `dict`) bazı değerlerle başlatır.
+
+Birden fazla event handler fonksiyonu ekleyebilirsiniz.
+
+Ve tüm `startup` event handler’ları tamamlanmadan uygulamanız request almaya başlamaz.
+
+### `shutdown` eventi { #shutdown-event }
+
+Uygulama kapanırken çalıştırılacak bir fonksiyon eklemek için, `"shutdown"` event’i ile tanımlayın:
+
+{* ../../docs_src/events/tutorial002_py310.py hl[6] *}
+
+Burada `shutdown` event handler fonksiyonu, `log.txt` dosyasına `"Application shutdown"` satırını yazar.
+
+/// info | Bilgi
+
+`open()` fonksiyonunda `mode="a"` "append" anlamına gelir; yani satır, önceki içeriği silmeden dosyada ne varsa onun sonuna eklenir.
+
+///
+
+/// tip | İpucu
+
+Dikkat edin, bu örnekte bir dosyayla etkileşen standart Python `open()` fonksiyonunu kullanıyoruz.
+
+Dolayısıyla disk’e yazılmasını beklemeyi gerektiren I/O (input/output) söz konusu.
+
+Ancak `open()` `async` ve `await` kullanmaz.
+
+Bu yüzden event handler fonksiyonunu `async def` yerine standart `def` ile tanımlarız.
+
+///
+
+### `startup` ve `shutdown` birlikte { #startup-and-shutdown-together }
+
+*startup* ve *shutdown* mantığınızın birbiriyle bağlantılı olma ihtimali yüksektir; bir şeyi başlatıp sonra bitirmek, bir resource edinip sonra serbest bırakmak vb. isteyebilirsiniz.
+
+Bunu, ortak mantık veya değişken paylaşmayan ayrı fonksiyonlarda yapmak daha zordur; çünkü değerleri global değişkenlerde tutmanız veya benzer numaralar yapmanız gerekir.
+
+Bu nedenle artık bunun yerine, yukarıda açıklandığı gibi `lifespan` kullanmanız önerilmektedir.
+
+## Teknik Detaylar { #technical-details }
+
+Meraklı nerd’ler için küçük bir teknik detay. 🤓
+
+Altta, ASGI teknik spesifikasyonunda bu, [Lifespan Protokolü](https://asgi.readthedocs.io/en/latest/specs/lifespan.html)’nün bir parçasıdır ve `startup` ile `shutdown` adında event’ler tanımlar.
+
+/// info | Bilgi
+
+Starlette `lifespan` handler’ları hakkında daha fazlasını [Starlette Lifespan dokümanları](https://www.starlette.dev/lifespan/) içinde okuyabilirsiniz.
+
+Ayrıca kodunuzun başka bölgelerinde de kullanılabilecek lifespan state’i nasıl yöneteceğinizi de kapsar.
+
+///
+
+## Alt Uygulamalar { #sub-applications }
+
+🚨 Unutmayın: Bu lifespan event’leri (`startup` ve `shutdown`) yalnızca ana uygulama için çalıştırılır; [Alt Uygulamalar - Mounts](sub-applications.md) için çalıştırılmaz.
diff --git a/docs/tr/docs/advanced/generate-clients.md b/docs/tr/docs/advanced/generate-clients.md
new file mode 100644
index 0000000000000..94d0074041360
--- /dev/null
+++ b/docs/tr/docs/advanced/generate-clients.md
@@ -0,0 +1,208 @@
+# SDK Üretme { #generating-sdks }
+
+**FastAPI**, **OpenAPI** spesifikasyonunu temel aldığı için API'leri birçok aracın anlayabildiği standart bir formatta tanımlanabilir.
+
+Bu sayede güncel **dokümantasyon**, birden fazla dilde istemci kütüphaneleri (**SDKs**) ve kodunuzla senkron kalan **test** veya **otomasyon iş akışları** üretmek kolaylaşır.
+
+Bu rehberde, FastAPI backend'iniz için bir **TypeScript SDK** üretmeyi öğreneceksiniz.
+
+## Açık Kaynak SDK Üreteçleri { #open-source-sdk-generators }
+
+Esnek bir seçenek olan [OpenAPI Generator](https://openapi-generator.tech/), **birçok programlama dilini** destekler ve OpenAPI spesifikasyonunuzdan SDK üretebilir.
+
+**TypeScript client**'lar için [Hey API](https://heyapi.dev/), TypeScript ekosistemi için özel olarak tasarlanmış, optimize bir deneyim sunan bir çözümdür.
+
+Daha fazla SDK üretecini [OpenAPI.Tools](https://openapi.tools/#sdk) üzerinde keşfedebilirsiniz.
+
+/// tip | İpucu
+
+FastAPI otomatik olarak **OpenAPI 3.1** spesifikasyonları üretir; bu yüzden kullanacağınız aracın bu sürümü desteklemesi gerekir.
+
+///
+
+## FastAPI Sponsorlarından SDK Üreteçleri { #sdk-generators-from-fastapi-sponsors }
+
+Bu bölüm, FastAPI'yi sponsorlayan şirketlerin sunduğu **yatırım destekli** ve **şirket destekli** çözümleri öne çıkarır. Bu ürünler, yüksek kaliteli üretilen SDK'ların üzerine **ek özellikler** ve **entegrasyonlar** sağlar.
+
+✨ [**FastAPI'ye sponsor olarak**](../help-fastapi.md#sponsor-the-author) ✨ bu şirketler, framework'ün ve **ekosisteminin** sağlıklı ve **sürdürülebilir** kalmasına yardımcı olur.
+
+Sponsor olmaları aynı zamanda FastAPI **topluluğuna** (size) güçlü bir bağlılığı da gösterir; yalnızca **iyi bir hizmet** sunmayı değil, aynı zamanda **güçlü ve gelişen bir framework** olan FastAPI'yi desteklemeyi de önemsediklerini gösterir. 🙇
+
+Örneğin şunları deneyebilirsiniz:
+
+* [Speakeasy](https://speakeasy.com/editor?utm_source=fastapi+repo&utm_medium=github+sponsorship)
+* [Stainless](https://www.stainless.com/?utm_source=fastapi&utm_medium=referral)
+* [liblab](https://developers.liblab.com/tutorials/sdk-for-fastapi?utm_source=fastapi)
+
+Bu çözümlerin bazıları açık kaynak olabilir veya ücretsiz katman sunabilir; yani finansal bir taahhüt olmadan deneyebilirsiniz. Başka ticari SDK üreteçleri de vardır ve internette bulunabilir. 🤓
+
+## TypeScript SDK Oluşturma { #create-a-typescript-sdk }
+
+Basit bir FastAPI uygulamasıyla başlayalım:
+
+{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}
+
+*Path operation*'ların, request payload ve response payload için kullandıkları modelleri `Item` ve `ResponseMessage` modelleriyle tanımladıklarına dikkat edin.
+
+### API Dokümanları { #api-docs }
+
+`/docs` adresine giderseniz, request'lerde gönderilecek ve response'larda alınacak veriler için **schema**'ları içerdiğini görürsünüz:
+
+
+
+Bu schema'ları görebilirsiniz, çünkü uygulamada modellerle birlikte tanımlandılar.
+
+Bu bilgi uygulamanın **OpenAPI schema**'sında bulunur ve sonrasında API dokümanlarında gösterilir.
+
+OpenAPI'ye dahil edilen, modellerden gelen bu bilginin aynısı **client code üretmek** için kullanılabilir.
+
+### Hey API { #hey-api }
+
+Modelleri olan bir FastAPI uygulamamız olduğunda, Hey API ile bir TypeScript client üretebiliriz. Bunu yapmanın en hızlı yolu npx kullanmaktır.
+
+```sh
+npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
+```
+
+Bu komut `./src/client` içine bir TypeScript SDK üretecektir.
+
+Web sitelerinde [`@hey-api/openapi-ts` kurulumunu](https://heyapi.dev/openapi-ts/get-started) öğrenebilir ve [üretilen çıktıyı](https://heyapi.dev/openapi-ts/output) inceleyebilirsiniz.
+
+### SDK'yı Kullanma { #using-the-sdk }
+
+Artık client code'u import edip kullanabilirsiniz. Şuna benzer görünebilir; method'lar için otomatik tamamlama aldığınıza dikkat edin:
+
+
+
+Ayrıca gönderilecek payload için de otomatik tamamlama alırsınız:
+
+
+
+/// tip | İpucu
+
+`name` ve `price` için otomatik tamamlamaya dikkat edin; bunlar FastAPI uygulamasında, `Item` modelinde tanımlanmıştı.
+
+///
+
+Gönderdiğiniz veriler için satır içi hatalar (inline errors) da alırsınız:
+
+
+
+Response objesi de otomatik tamamlama sunacaktır:
+
+
+
+## Tag'lerle FastAPI Uygulaması { #fastapi-app-with-tags }
+
+Birçok durumda FastAPI uygulamanız daha büyük olacaktır ve farklı *path operation* gruplarını ayırmak için muhtemelen tag'leri kullanacaksınız.
+
+Örneğin **items** için bir bölüm, **users** için başka bir bölüm olabilir ve bunları tag'lerle ayırabilirsiniz:
+
+{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}
+
+### Tag'lerle TypeScript Client Üretme { #generate-a-typescript-client-with-tags }
+
+Tag'leri kullanan bir FastAPI uygulaması için client ürettiğinizde, genelde client code da tag'lere göre ayrılır.
+
+Bu sayede client code tarafında her şey doğru şekilde sıralanır ve gruplandırılır:
+
+
+
+Bu örnekte şunlar var:
+
+* `ItemsService`
+* `UsersService`
+
+### Client Method İsimleri { #client-method-names }
+
+Şu an üretilen `createItemItemsPost` gibi method isimleri çok temiz görünmüyor:
+
+```TypeScript
+ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
+```
+
+...çünkü client üreteci, her *path operation* için OpenAPI'nin dahili **operation ID** değerini kullanır.
+
+OpenAPI, her operation ID'nin tüm *path operation*'lar arasında benzersiz olmasını ister. Bu yüzden FastAPI; operation ID'yi benzersiz tutabilmek için **function adı**, **path** ve **HTTP method/operation** bilgilerini birleştirerek üretir.
+
+Ancak bunu bir sonraki adımda nasıl iyileştirebileceğinizi göstereceğim. 🤓
+
+## Özel Operation ID'ler ve Daha İyi Method İsimleri { #custom-operation-ids-and-better-method-names }
+
+Bu operation ID'lerin **üretilme** şeklini **değiştirerek**, client'larda daha basit **method isimleri** elde edebilirsiniz.
+
+Bu durumda, her operation ID'nin **benzersiz** olduğundan başka bir şekilde emin olmanız gerekir.
+
+Örneğin, her *path operation*'ın bir tag'i olmasını sağlayabilir ve operation ID'yi **tag** ve *path operation* **adı**na (function adı) göre üretebilirsiniz.
+
+### Benzersiz ID Üreten Özel Fonksiyon { #custom-generate-unique-id-function }
+
+FastAPI, her *path operation* için bir **unique ID** kullanır. Bu ID, **operation ID** için ve ayrıca request/response'lar için gerekebilecek özel model isimleri için de kullanılır.
+
+Bu fonksiyonu özelleştirebilirsiniz. Bir `APIRoute` alır ve string döndürür.
+
+Örneğin burada ilk tag'i (muhtemelen tek tag'iniz olur) ve *path operation* adını (function adı) kullanıyor.
+
+Sonrasında bu özel fonksiyonu `generate_unique_id_function` parametresiyle **FastAPI**'ye geçebilirsiniz:
+
+{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}
+
+### Özel Operation ID'lerle TypeScript Client Üretme { #generate-a-typescript-client-with-custom-operation-ids }
+
+Artık client'ı tekrar üretirseniz, geliştirilmiş method isimlerini göreceksiniz:
+
+
+
+Gördüğünüz gibi method isimleri artık önce tag'i, sonra function adını içeriyor; URL path'i ve HTTP operation bilgisini artık taşımıyor.
+
+### Client Üretecine Vermeden Önce OpenAPI Spesifikasyonunu Ön İşlemek { #preprocess-the-openapi-specification-for-the-client-generator }
+
+Üretilen kodda hâlâ bazı **tekrarlanan bilgiler** var.
+
+Bu method'un **items** ile ilişkili olduğunu zaten biliyoruz; çünkü bu kelime `ItemsService` içinde var (tag'den geliyor). Ama method adında da tag adı önek olarak duruyor. 😕
+
+OpenAPI genelinde muhtemelen bunu korumak isteriz; çünkü operation ID'lerin **benzersiz** olmasını sağlar.
+
+Ancak üretilen client için, client'ları üretmeden hemen önce OpenAPI operation ID'lerini **değiştirip**, method isimlerini daha hoş ve **temiz** hale getirebiliriz.
+
+OpenAPI JSON'u `openapi.json` diye bir dosyaya indirip, şu tarz bir script ile **öndeki tag'i kaldırabiliriz**:
+
+{* ../../docs_src/generate_clients/tutorial004_py310.py *}
+
+//// tab | Node.js
+
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
+```
+
+////
+
+Bununla operation ID'ler `items-get_items` gibi değerlerden sadece `get_items` olacak şekilde yeniden adlandırılır; böylece client üreteci daha basit method isimleri üretebilir.
+
+### Ön İşlenmiş OpenAPI ile TypeScript Client Üretme { #generate-a-typescript-client-with-the-preprocessed-openapi }
+
+Sonuç artık bir `openapi.json` dosyasında olduğuna göre, input konumunu güncellemeniz gerekir:
+
+```sh
+npx @hey-api/openapi-ts -i ./openapi.json -o src/client
+```
+
+Yeni client'ı ürettikten sonra, tüm **otomatik tamamlama**, **satır içi hatalar**, vb. ile birlikte **temiz method isimleri** elde edersiniz:
+
+
+
+## Faydalar { #benefits }
+
+Otomatik üretilen client'ları kullanınca şu alanlarda **otomatik tamamlama** elde edersiniz:
+
+* Method'lar.
+* Body'deki request payload'ları, query parametreleri, vb.
+* Response payload'ları.
+
+Ayrıca her şey için **satır içi hatalar** (inline errors) da olur.
+
+Backend kodunu her güncellediğinizde ve frontend'i **yeniden ürettiğinizde**, yeni *path operation*'lar method olarak eklenir, eskileri kaldırılır ve diğer değişiklikler de üretilen koda yansır. 🤓
+
+Bu, bir şey değiştiğinde client code'a otomatik olarak **yansıyacağı** anlamına gelir. Ayrıca client'ı **build** ettiğinizde, kullanılan verilerde bir **uyuşmazlık** (mismatch) varsa hata alırsınız.
+
+Böylece üretimde son kullanıcılara hata yansımasını beklemek ve sonra sorunun nerede olduğunu debug etmeye çalışmak yerine, geliştirme sürecinin çok erken aşamalarında **birçok hatayı tespit edersiniz**. ✨
diff --git a/docs/tr/docs/advanced/index.md b/docs/tr/docs/advanced/index.md
new file mode 100644
index 0000000000000..154a5501d6bb9
--- /dev/null
+++ b/docs/tr/docs/advanced/index.md
@@ -0,0 +1,21 @@
+# Gelişmiş Kullanıcı Rehberi { #advanced-user-guide }
+
+## Ek Özellikler { #additional-features }
+
+Ana [Tutorial - User Guide](../tutorial/index.md) sayfası, **FastAPI**'nin tüm temel özelliklerini tanımanız için yeterli olmalıdır.
+
+Sonraki bölümlerde diğer seçenekleri, konfigürasyonları ve ek özellikleri göreceksiniz.
+
+/// tip | İpucu
+
+Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**.
+
+Ve kullanım amacınıza bağlı olarak, çözüm bunlardan birinde olabilir.
+
+///
+
+## Önce Tutorial'ı Okuyun { #read-the-tutorial-first }
+
+Ana [Tutorial - User Guide](../tutorial/index.md) sayfasındaki bilgilerle **FastAPI**'nin çoğu özelliğini yine de kullanabilirsiniz.
+
+Ve sonraki bölümler, onu zaten okuduğunuzu ve bu temel fikirleri bildiğinizi varsayar.
diff --git a/docs/tr/docs/advanced/json-base64-bytes.md b/docs/tr/docs/advanced/json-base64-bytes.md
new file mode 100644
index 0000000000000..68e1cba7aa668
--- /dev/null
+++ b/docs/tr/docs/advanced/json-base64-bytes.md
@@ -0,0 +1,63 @@
+# JSON'da Bytes'i Base64 Olarak Kullanma { #json-with-bytes-as-base64 }
+
+Uygulamanız JSON veri alıp gönderiyorsa ve bunun içine ikili (binary) veri eklemeniz gerekiyorsa, veriyi base64 olarak encode edebilirsiniz.
+
+## Base64 ve Dosyalar { #base64-vs-files }
+
+İkili veriyi JSON içinde encode etmek yerine, yükleme için [Request Files](../tutorial/request-files.md) ve gönderim için [Custom Response - FileResponse](./custom-response.md#fileresponse--fileresponse-) kullanıp kullanamayacağınıza önce bir bakın.
+
+JSON sadece UTF-8 ile encode edilmiş string'ler içerebilir, dolayısıyla ham bytes içeremez.
+
+Base64 ikili veriyi string olarak encode edebilir, ancak bunu yapmak için orijinal ikili veriden daha fazla karakter kullanır; bu yüzden genellikle normal dosyalardan daha verimsiz olur.
+
+Base64'ü sadece gerçekten JSON içine ikili veri koymanız gerekiyorsa ve bunun için dosya kullanamıyorsanız tercih edin.
+
+## Pydantic `bytes` { #pydantic-bytes }
+
+`bytes` alanları olan bir Pydantic model tanımlayabilir, ardından model config'inde `val_json_bytes` kullanarak giriş JSON verisini base64 ile doğrulamasını (validate) söyleyebilirsiniz; bu doğrulamanın bir parçası olarak base64 string'i bytes'a decode eder.
+
+{* ../../docs_src/json_base64_bytes/tutorial001_py310.py ln[1:9,29:35] hl[9] *}
+
+`/docs`'a bakarsanız, `data` alanının base64 ile encode edilmiş bytes beklediğini görürsünüz:
+
+
+
diff --git a/docs/tr/docs/advanced/openapi-webhooks.md b/docs/tr/docs/advanced/openapi-webhooks.md
new file mode 100644
index 0000000000000..a9f21662cacbe
--- /dev/null
+++ b/docs/tr/docs/advanced/openapi-webhooks.md
@@ -0,0 +1,55 @@
+# OpenAPI Webhook'lar { #openapi-webhooks }
+
+Bazı durumlarda, API'nizi kullanan **kullanıcılara** uygulamanızın *onların* uygulamasını (request göndererek) bazı verilerle çağırabileceğini; genellikle bir tür **event** hakkında **bildirim** yapmak için kullanacağını söylemek istersiniz.
+
+Bu da şunu ifade eder: Kullanıcılarınızın API'nize request göndermesi şeklindeki normal akış yerine, request'i **sizin API'niz** (veya uygulamanız) **onların sistemine** (onların API'sine, onların uygulamasına) **gönderebilir**.
+
+Buna genellikle **webhook** denir.
+
+## Webhook adımları { #webhooks-steps }
+
+Süreç genellikle şöyledir: Kodunuzda göndereceğiniz mesajın ne olduğunu, yani request'in **body**'sini **siz tanımlarsınız**.
+
+Ayrıca uygulamanızın bu request'leri veya event'leri hangi **anlarda** göndereceğini de bir şekilde tanımlarsınız.
+
+Ve **kullanıcılarınız** da bir şekilde (örneğin bir web dashboard üzerinden) uygulamanızın bu request'leri göndermesi gereken **URL**'yi tanımlar.
+
+Webhook'lar için URL'lerin nasıl kaydedileceğine dair tüm **mantık** ve bu request'leri gerçekten gönderen kod tamamen size bağlıdır. Bunu **kendi kodunuzda** istediğiniz gibi yazarsınız.
+
+## **FastAPI** ve OpenAPI ile webhook'ları dokümante etmek { #documenting-webhooks-with-fastapi-and-openapi }
+
+**FastAPI** ile OpenAPI kullanarak bu webhook'ların adlarını, uygulamanızın gönderebileceği HTTP operation türlerini (örn. `POST`, `PUT`, vb.) ve uygulamanızın göndereceği request **body**'lerini tanımlayabilirsiniz.
+
+Bu, kullanıcılarınızın **webhook** request'lerinizi alacak şekilde **API'lerini implement etmesini** çok daha kolaylaştırabilir; hatta kendi API kodlarının bir kısmını otomatik üretebilirler.
+
+/// info | Bilgi
+
+Webhook'lar OpenAPI 3.1.0 ve üzeri sürümlerde mevcuttur; FastAPI `0.99.0` ve üzeri tarafından desteklenir.
+
+///
+
+## Webhook'ları olan bir uygulama { #an-app-with-webhooks }
+
+Bir **FastAPI** uygulaması oluşturduğunuzda, *webhook*'ları tanımlamak için kullanabileceğiniz bir `webhooks` attribute'u vardır; *path operation* tanımlar gibi, örneğin `@app.webhooks.post()` ile.
+
+{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}
+
+Tanımladığınız webhook'lar **OpenAPI** şemasında ve otomatik **docs UI**'da yer alır.
+
+/// info | Bilgi
+
+`app.webhooks` nesnesi aslında sadece bir `APIRouter`'dır; uygulamanızı birden fazla dosya ile yapılandırırken kullanacağınız türün aynısıdır.
+
+///
+
+Dikkat edin: Webhook'larda aslında bir *path* (ör. `/items/`) deklare etmiyorsunuz; oraya verdiğiniz metin sadece webhook'un bir **identifier**'ıdır (event'in adı). Örneğin `@app.webhooks.post("new-subscription")` içinde webhook adı `new-subscription`'dır.
+
+Bunun nedeni, webhook request'ini almak istedikleri gerçek **URL path**'i **kullanıcılarınızın** başka bir şekilde (örn. bir web dashboard üzerinden) tanımlamasının beklenmesidir.
+
+### Dokümanları kontrol edin { #check-the-docs }
+
+Şimdi uygulamanızı başlatıp [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) adresine gidin.
+
+Dokümanlarınızda normal *path operation*'ları ve artık bazı **webhook**'ları da göreceksiniz:
+
+
diff --git a/docs/tr/docs/advanced/path-operation-advanced-configuration.md b/docs/tr/docs/advanced/path-operation-advanced-configuration.md
new file mode 100644
index 0000000000000..00ce765884416
--- /dev/null
+++ b/docs/tr/docs/advanced/path-operation-advanced-configuration.md
@@ -0,0 +1,172 @@
+# Path Operation İleri Düzey Yapılandırma { #path-operation-advanced-configuration }
+
+## OpenAPI operationId { #openapi-operationid }
+
+/// warning | Uyarı
+
+OpenAPI konusunda "uzman" değilseniz, muhtemelen buna ihtiyacınız yok.
+
+///
+
+*path operation*’ınızda kullanılacak OpenAPI `operationId` değerini `operation_id` parametresiyle ayarlayabilirsiniz.
+
+Bunun her operation için benzersiz olduğundan emin olmanız gerekir.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
+
+### operationId olarak *path operation function* adını kullanma { #using-the-path-operation-function-name-as-the-operationid }
+
+API’lerinizin function adlarını `operationId` olarak kullanmak istiyorsanız, hepsini dolaşıp her *path operation*’ın `operation_id` değerini `APIRoute.name` ile override edebilirsiniz.
+
+Bunu, tüm *path operation*’ları ekledikten sonra yapmalısınız.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *}
+
+/// tip | İpucu
+
+`app.openapi()` fonksiyonunu manuel olarak çağırıyorsanız, bunu yapmadan önce `operationId`’leri güncellemelisiniz.
+
+///
+
+/// warning | Uyarı
+
+Bunu yaparsanız, her bir *path operation function*’ın adının benzersiz olduğundan emin olmanız gerekir.
+
+Farklı modüllerde (Python dosyalarında) olsalar bile.
+
+///
+
+## OpenAPI’den Hariç Tutma { #exclude-from-openapi }
+
+Bir *path operation*’ı üretilen OpenAPI şemasından (dolayısıyla otomatik dokümantasyon sistemlerinden) hariç tutmak için `include_in_schema` parametresini kullanın ve `False` yapın:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}
+
+## Docstring’den İleri Düzey Açıklama { #advanced-description-from-docstring }
+
+OpenAPI için, bir *path operation function*’ın docstring’inden kullanılacak satırları sınırlandırabilirsiniz.
+
+Bir `\f` (escape edilmiş "form feed" karakteri) eklerseniz, **FastAPI** OpenAPI için kullanılan çıktıyı bu noktada **keser**.
+
+Dokümantasyonda görünmez, ancak diğer araçlar (Sphinx gibi) geri kalan kısmı kullanabilir.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}
+
+## Ek Responses { #additional-responses }
+
+Muhtemelen bir *path operation* için `response_model` ve `status_code` tanımlamayı görmüşsünüzdür.
+
+Bu, bir *path operation*’ın ana response’u ile ilgili metadata’yı tanımlar.
+
+Ek response’ları; modelleri, status code’ları vb. ile birlikte ayrıca da tanımlayabilirsiniz.
+
+Dokümantasyonda bununla ilgili ayrı bir bölüm var; [OpenAPI’de Ek Responses](additional-responses.md) sayfasından okuyabilirsiniz.
+
+## OpenAPI Extra { #openapi-extra }
+
+Uygulamanızda bir *path operation* tanımladığınızda, **FastAPI** OpenAPI şemasına dahil edilmek üzere o *path operation* ile ilgili metadata’yı otomatik olarak üretir.
+
+/// note | Teknik Detaylar
+
+OpenAPI spesifikasyonunda buna [Operation Nesnesi](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object) denir.
+
+///
+
+Bu, *path operation* hakkında tüm bilgileri içerir ve otomatik dokümantasyonu üretmek için kullanılır.
+
+`tags`, `parameters`, `requestBody`, `responses` vb. alanları içerir.
+
+Bu *path operation*’a özel OpenAPI şeması normalde **FastAPI** tarafından otomatik üretilir; ancak siz bunu genişletebilirsiniz.
+
+/// tip | İpucu
+
+Bu, düşük seviyeli bir genişletme noktasıdır.
+
+Yalnızca ek response’lar tanımlamanız gerekiyorsa, bunu yapmanın daha pratik yolu [OpenAPI’de Ek Responses](additional-responses.md) kullanmaktır.
+
+///
+
+Bir *path operation* için OpenAPI şemasını `openapi_extra` parametresiyle genişletebilirsiniz.
+
+### OpenAPI Extensions { #openapi-extensions }
+
+Örneğin bu `openapi_extra`, [OpenAPI Uzantıları](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) tanımlamak için faydalı olabilir:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py310.py hl[6] *}
+
+Otomatik API dokümanlarını açtığınızda, extension’ınız ilgili *path operation*’ın en altında görünür.
+
+
+
+Ayrıca ortaya çıkan OpenAPI’yi (API’nizde `/openapi.json`) görüntülerseniz, extension’ınızı ilgili *path operation*’ın bir parçası olarak orada da görürsünüz:
+
+```JSON hl_lines="22"
+{
+ "openapi": "3.1.0",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0"
+ },
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ }
+ },
+ "x-aperture-labs-portal": "blue"
+ }
+ }
+ }
+}
+```
+
+### Özel OpenAPI *path operation* şeması { #custom-openapi-path-operation-schema }
+
+`openapi_extra` içindeki dictionary, *path operation* için otomatik üretilen OpenAPI şemasıyla derinlemesine (deep) birleştirilir.
+
+Böylece otomatik üretilen şemaya ek veri ekleyebilirsiniz.
+
+Örneğin, Pydantic ile FastAPI’nin otomatik özelliklerini kullanmadan request’i kendi kodunuzla okuyup doğrulamaya karar verebilirsiniz; ancak yine de OpenAPI şemasında request’i tanımlamak isteyebilirsiniz.
+
+Bunu `openapi_extra` ile yapabilirsiniz:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py310.py hl[19:36, 39:40] *}
+
+Bu örnekte herhangi bir Pydantic model tanımlamadık. Hatta request body JSON olarak ayrıştırılmıyor; doğrudan `bytes` olarak okunuyor ve `magic_data_reader()` fonksiyonu bunu bir şekilde parse etmekten sorumlu oluyor.
+
+Buna rağmen, request body için beklenen şemayı tanımlayabiliriz.
+
+### Özel OpenAPI content type { #custom-openapi-content-type }
+
+Aynı yöntemi kullanarak, Pydantic model ile JSON Schema’yı tanımlayıp bunu *path operation* için özel OpenAPI şeması bölümüne dahil edebilirsiniz.
+
+Ve bunu, request içindeki veri tipi JSON olmasa bile yapabilirsiniz.
+
+Örneğin bu uygulamada, FastAPI’nin Pydantic modellerinden JSON Schema çıkarmaya yönelik entegre işlevselliğini ve JSON için otomatik doğrulamayı kullanmıyoruz. Hatta request content type’ını JSON değil, YAML olarak tanımlıyoruz:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[15:20, 22] *}
+
+Buna rağmen, varsayılan entegre işlevselliği kullanmasak da, YAML olarak almak istediğimiz veri için JSON Schema’yı manuel üretmek üzere bir Pydantic model kullanmaya devam ediyoruz.
+
+Ardından request’i doğrudan kullanıp body’yi `bytes` olarak çıkarıyoruz. Bu da FastAPI’nin request payload’ını JSON olarak parse etmeye çalışmayacağı anlamına gelir.
+
+Sonrasında kodumuzda bu YAML içeriğini doğrudan parse ediyor, ardından YAML içeriğini doğrulamak için yine aynı Pydantic modeli kullanıyoruz:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *}
+
+/// tip | İpucu
+
+Burada aynı Pydantic modeli tekrar kullanıyoruz.
+
+Aynı şekilde, başka bir yöntemle de doğrulama yapabilirdik.
+
+///
diff --git a/docs/tr/docs/advanced/response-change-status-code.md b/docs/tr/docs/advanced/response-change-status-code.md
new file mode 100644
index 0000000000000..f15ed77f504a4
--- /dev/null
+++ b/docs/tr/docs/advanced/response-change-status-code.md
@@ -0,0 +1,31 @@
+# Response - Status Code Değiştirme { #response-change-status-code }
+
+Muhtemelen daha önce varsayılan bir [Response Status Code](../tutorial/response-status-code.md) ayarlayabileceğinizi okumuşsunuzdur.
+
+Ancak bazı durumlarda, varsayılandan farklı bir status code döndürmeniz gerekir.
+
+## Kullanım senaryosu { #use-case }
+
+Örneğin, varsayılan olarak "OK" `200` HTTP status code'u döndürmek istediğinizi düşünün.
+
+Ama veri mevcut değilse onu oluşturmak ve "CREATED" `201` HTTP status code'u döndürmek istiyorsunuz.
+
+Aynı zamanda, döndürdüğünüz veriyi bir `response_model` ile filtreleyip dönüştürebilmeyi de sürdürmek istiyorsunuz.
+
+Bu tür durumlarda bir `Response` parametresi kullanabilirsiniz.
+
+## Bir `Response` parametresi kullanın { #use-a-response-parameter }
+
+*Path operation function* içinde `Response` tipinde bir parametre tanımlayabilirsiniz (cookie ve header'lar için yapabildiğiniz gibi).
+
+Ardından bu *geçici (temporal)* `Response` nesnesi üzerinde `status_code` değerini ayarlayabilirsiniz.
+
+{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}
+
+Sonrasında, normalde yaptığınız gibi ihtiyacınız olan herhangi bir nesneyi döndürebilirsiniz (`dict`, bir veritabanı modeli, vb.).
+
+Ve eğer bir `response_model` tanımladıysanız, döndürdüğünüz nesneyi filtrelemek ve dönüştürmek için yine kullanılacaktır.
+
+**FastAPI**, status code'u (ayrıca cookie ve header'ları) bu *geçici (temporal)* response'tan alır ve `response_model` ile filtrelenmiş, sizin döndürdüğünüz değeri içeren nihai response'a yerleştirir.
+
+Ayrıca `Response` parametresini dependency'lerde de tanımlayıp status code'u orada ayarlayabilirsiniz. Ancak unutmayın, en son ayarlanan değer geçerli olur.
diff --git a/docs/tr/docs/advanced/response-cookies.md b/docs/tr/docs/advanced/response-cookies.md
new file mode 100644
index 0000000000000..3d3b978bcf1da
--- /dev/null
+++ b/docs/tr/docs/advanced/response-cookies.md
@@ -0,0 +1,51 @@
+# Response Cookie'leri { #response-cookies }
+
+## Bir `Response` parametresi kullanın { #use-a-response-parameter }
+
+*Path operation function* içinde `Response` tipinde bir parametre tanımlayabilirsiniz.
+
+Ardından bu *geçici* response nesnesi üzerinde cookie'leri set edebilirsiniz.
+
+{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}
+
+Sonrasında normalde yaptığınız gibi ihtiyaç duyduğunuz herhangi bir nesneyi döndürebilirsiniz (bir `dict`, bir veritabanı modeli vb.).
+
+Ayrıca bir `response_model` tanımladıysanız, döndürdüğünüz nesneyi filtrelemek ve dönüştürmek için yine kullanılacaktır.
+
+**FastAPI**, bu *geçici* response'u cookie'leri (ayrıca header'ları ve status code'u) çıkarmak için kullanır ve bunları, döndürdüğünüz değeri içeren nihai response'a ekler. Döndürdüğünüz değer, varsa `response_model` ile filtrelenmiş olur.
+
+`Response` parametresini dependency'lerde de tanımlayıp, onların içinde cookie (ve header) set edebilirsiniz.
+
+## Doğrudan bir `Response` döndürün { #return-a-response-directly }
+
+Kodunuzda doğrudan bir `Response` döndürürken de cookie oluşturabilirsiniz.
+
+Bunu yapmak için, [Doğrudan Response Döndürme](response-directly.md) bölümünde anlatıldığı gibi bir response oluşturabilirsiniz.
+
+Sonra bunun içinde Cookie'leri set edin ve response'u döndürün:
+
+{* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *}
+
+/// tip
+
+`Response` parametresini kullanmak yerine doğrudan bir response döndürürseniz, FastAPI onu olduğu gibi (doğrudan) döndürür.
+
+Bu yüzden, verinizin doğru tipte olduğundan emin olmanız gerekir. Örneğin `JSONResponse` döndürüyorsanız, verinin JSON ile uyumlu olması gerekir.
+
+Ayrıca `response_model` tarafından filtrelenmesi gereken bir veriyi göndermediğinizden de emin olun.
+
+///
+
+### Daha fazla bilgi { #more-info }
+
+/// note | Teknik Detaylar
+
+`from starlette.responses import Response` veya `from starlette.responses import JSONResponse` da kullanabilirsiniz.
+
+**FastAPI**, geliştirici olarak size kolaylık olması için `fastapi.responses` içinde `starlette.responses` ile aynı response sınıflarını sunar. Ancak mevcut response'ların büyük kısmı doğrudan Starlette'ten gelir.
+
+Ve `Response`, header ve cookie set etmek için sık kullanıldığından, **FastAPI** bunu `fastapi.Response` olarak da sağlar.
+
+///
+
+Mevcut tüm parametreleri ve seçenekleri görmek için [Starlette dokümantasyonu](https://www.starlette.dev/responses/#set-cookie)'na bakın.
diff --git a/docs/tr/docs/advanced/response-directly.md b/docs/tr/docs/advanced/response-directly.md
new file mode 100644
index 0000000000000..8db51e3513049
--- /dev/null
+++ b/docs/tr/docs/advanced/response-directly.md
@@ -0,0 +1,83 @@
+# Doğrudan Bir Response Döndürme { #return-a-response-directly }
+
+**FastAPI** ile bir *path operation* oluşturduğunuzda, normalde ondan herhangi bir veri döndürebilirsiniz: bir `dict`, bir `list`, bir Pydantic model, bir veritabanı modeli vb.
+
+Bir [Response Model](../tutorial/response-model.md) deklare ederseniz, FastAPI veriyi Pydantic kullanarak JSON'a serialize etmek için bunu kullanır.
+
+Bir response model deklare etmezseniz, FastAPI [JSON Uyumlu Encoder](../tutorial/encoder.md)'da anlatılan `jsonable_encoder`'ı kullanır ve bunu bir `JSONResponse` içine koyar.
+
+Ayrıca doğrudan bir `JSONResponse` oluşturup döndürebilirsiniz.
+
+/// tip | İpucu
+
+[Response Model](../tutorial/response-model.md) kullanmak, doğrudan `JSONResponse` döndürmeye kıyasla genellikle çok daha iyi performans sağlar; çünkü veriyi Pydantic ile, Rust tarafında serialize eder.
+
+///
+
+## Bir `Response` Döndürme { #return-a-response }
+
+Aslında herhangi bir `Response` veya onun herhangi bir alt sınıfını döndürebilirsiniz.
+
+/// info | Bilgi
+
+`JSONResponse` zaten `Response`'un bir alt sınıfıdır.
+
+///
+
+Bir `Response` döndürdüğünüzde, **FastAPI** bunu olduğu gibi doğrudan iletir.
+
+Pydantic model'leriyle herhangi bir veri dönüşümü yapmaz, içeriği başka bir tipe çevirmez vb.
+
+Bu size ciddi bir esneklik sağlar. Herhangi bir veri türü döndürebilir, herhangi bir veri deklarasyonunu veya validasyonunu override edebilirsiniz.
+
+Bu aynı zamanda size ciddi bir sorumluluk yükler. Döndürdüğünüz verinin doğru, doğru formatta, serialize edilebilir vb. olduğundan emin olmanız gerekir.
+
+## Bir `Response` İçinde `jsonable_encoder` Kullanma { #using-the-jsonable-encoder-in-a-response }
+
+**FastAPI**, sizin döndürdüğünüz `Response` üzerinde hiçbir değişiklik yapmadığı için, içeriğinin gönderilmeye hazır olduğundan emin olmanız gerekir.
+
+Örneğin, bir Pydantic model'i, önce JSON-uyumlu tiplere çevrilmeden (`datetime`, `UUID` vb.) doğrudan bir `JSONResponse` içine koyamazsınız. Önce tüm veri tipleri JSON-uyumlu hale gelecek şekilde `dict`'e çevrilmesi gerekir.
+
+Bu gibi durumlarda, response'a vermeden önce verinizi dönüştürmek için `jsonable_encoder` kullanabilirsiniz:
+
+{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}
+
+/// note | Teknik Detaylar
+
+`from starlette.responses import JSONResponse` da kullanabilirsiniz.
+
+**FastAPI**, geliştirici olarak size kolaylık olması için `starlette.responses` içeriğini `fastapi.responses` üzerinden de sunar. Ancak mevcut response'ların çoğu doğrudan Starlette'tan gelir.
+
+///
+
+## Özel Bir `Response` Döndürme { #returning-a-custom-response }
+
+Yukarıdaki örnek ihtiyaç duyduğunuz tüm parçaları gösteriyor, ancak henüz çok kullanışlı değil. Çünkü `item`'ı zaten doğrudan döndürebilirdiniz ve **FastAPI** varsayılan olarak onu sizin için bir `JSONResponse` içine koyup `dict`'e çevirirdi vb.
+
+Şimdi bunu kullanarak nasıl özel bir response döndürebileceğinize bakalım.
+
+Diyelim ki [XML](https://en.wikipedia.org/wiki/XML) response döndürmek istiyorsunuz.
+
+XML içeriğinizi bir string içine koyabilir, onu bir `Response` içine yerleştirip döndürebilirsiniz:
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+## Bir Response Model Nasıl Çalışır { #how-a-response-model-works }
+
+Bir path operation içinde [Response Model - Dönüş Tipi](../tutorial/response-model.md) deklare ettiğinizde, **FastAPI** veriyi Pydantic kullanarak JSON'a serialize etmek için bunu kullanır.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+Bu işlem Rust tarafında gerçekleştiği için, sıradan Python ve `JSONResponse` sınıfıyla yapılmasına kıyasla performans çok daha iyi olacaktır.
+
+Bir `response_model` veya dönüş tipi kullandığınızda, FastAPI veriyi dönüştürmek için (daha yavaş olacağı için) `jsonable_encoder`'ı ya da `JSONResponse` sınıfını kullanmaz.
+
+Bunun yerine, response model'i (veya dönüş tipini) kullanarak Pydantic ile üretilen JSON baytlarını alır ve doğrudan JSON için doğru medya tipiyle (`application/json`) bir `Response` döndürür.
+
+## Notlar { #notes }
+
+Bir `Response`'u doğrudan döndürdüğünüzde, verisi otomatik olarak validate edilmez, dönüştürülmez (serialize edilmez) veya dokümante edilmez.
+
+Ancak yine de [OpenAPI'de Ek Response'lar](additional-responses.md) bölümünde anlatıldığı şekilde dokümante edebilirsiniz.
+
+İlerleyen bölümlerde, otomatik veri dönüşümü, dokümantasyon vb. özellikleri korurken bu özel `Response`'ları nasıl kullanıp declare edebileceğinizi göreceksiniz.
diff --git a/docs/tr/docs/advanced/response-headers.md b/docs/tr/docs/advanced/response-headers.md
new file mode 100644
index 0000000000000..d61e24da35ded
--- /dev/null
+++ b/docs/tr/docs/advanced/response-headers.md
@@ -0,0 +1,41 @@
+# Response Header'ları { #response-headers }
+
+## Bir `Response` parametresi kullanın { #use-a-response-parameter }
+
+*Path operation function* içinde (cookie'lerde yapabildiğiniz gibi) tipi `Response` olan bir parametre tanımlayabilirsiniz.
+
+Sonra da bu *geçici* response nesnesi üzerinde header'ları ayarlayabilirsiniz.
+
+{* ../../docs_src/response_headers/tutorial002_py310.py hl[1, 7:8] *}
+
+Ardından normalde yaptığınız gibi ihtiyacınız olan herhangi bir nesneyi döndürebilirsiniz (bir `dict`, bir veritabanı modeli vb.).
+
+Eğer bir `response_model` tanımladıysanız, döndürdüğünüz nesneyi filtrelemek ve dönüştürmek için yine kullanılacaktır.
+
+**FastAPI**, header'ları (aynı şekilde cookie'leri ve status code'u) bu *geçici* response'dan alır ve döndürdüğünüz değeri (varsa bir `response_model` ile filtrelenmiş hâliyle) içeren nihai response'a ekler.
+
+`Response` parametresini dependency'lerde de tanımlayıp, onların içinde header (ve cookie) ayarlayabilirsiniz.
+
+## Doğrudan bir `Response` döndürün { #return-a-response-directly }
+
+Doğrudan bir `Response` döndürdüğünüzde de header ekleyebilirsiniz.
+
+[Bir Response'u Doğrudan Döndürün](response-directly.md) bölümünde anlatıldığı gibi bir response oluşturun ve header'ları ek bir parametre olarak geçin:
+
+{* ../../docs_src/response_headers/tutorial001_py310.py hl[10:12] *}
+
+/// note | Teknik Detaylar
+
+`from starlette.responses import Response` veya `from starlette.responses import JSONResponse` da kullanabilirsiniz.
+
+**FastAPI**, geliştirici olarak size kolaylık olsun diye `starlette.responses` içeriğini `fastapi.responses` olarak da sunar. Ancak mevcut response'ların çoğu doğrudan Starlette'ten gelir.
+
+Ayrıca `Response` header ve cookie ayarlamak için sık kullanıldığından, **FastAPI** bunu `fastapi.Response` altında da sağlar.
+
+///
+
+## Özel Header'lar { #custom-headers }
+
+Özel/proprietary header'ların [`X-` prefix'i kullanılarak](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) eklenebileceğini unutmayın.
+
+Ancak tarayıcıdaki bir client'ın görebilmesini istediğiniz özel header'larınız varsa, bunları CORS ayarlarınıza eklemeniz gerekir ([CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md) bölümünde daha fazla bilgi), bunun için [Starlette'in CORS dokümanında](https://www.starlette.dev/middleware/#corsmiddleware) açıklanan `expose_headers` parametresini kullanın.
diff --git a/docs/tr/docs/advanced/security/http-basic-auth.md b/docs/tr/docs/advanced/security/http-basic-auth.md
new file mode 100644
index 0000000000000..e94f769a39834
--- /dev/null
+++ b/docs/tr/docs/advanced/security/http-basic-auth.md
@@ -0,0 +1,107 @@
+# HTTP Basic Auth { #http-basic-auth }
+
+En basit senaryolarda HTTP Basic Auth kullanabilirsiniz.
+
+HTTP Basic Auth’ta uygulama, içinde kullanıcı adı ve şifre bulunan bir header bekler.
+
+Eğer bunu almazsa HTTP 401 "Unauthorized" hatası döndürür.
+
+Ayrıca değeri `Basic` olan ve isteğe bağlı `realm` parametresi içerebilen `WWW-Authenticate` header’ını da döndürür.
+
+Bu da tarayıcıya, kullanıcı adı ve şifre için entegre giriş penceresini göstermesini söyler.
+
+Ardından kullanıcı adı ve şifreyi yazdığınızda tarayıcı bunları otomatik olarak header içinde gönderir.
+
+## Basit HTTP Basic Auth { #simple-http-basic-auth }
+
+* `HTTPBasic` ve `HTTPBasicCredentials` import edin.
+* `HTTPBasic` kullanarak bir "`security` scheme" oluşturun.
+* *path operation*’ınızda bir dependency ile bu `security`’yi kullanın.
+* Bu, `HTTPBasicCredentials` tipinde bir nesne döndürür:
+ * İçinde gönderilen `username` ve `password` bulunur.
+
+{* ../../docs_src/security/tutorial006_an_py310.py hl[4,8,12] *}
+
+URL’yi ilk kez açmaya çalıştığınızda (veya dokümanlardaki "Execute" butonuna tıkladığınızda) tarayıcı sizden kullanıcı adınızı ve şifrenizi ister:
+
+
+
+## Kullanıcı adını kontrol edin { #check-the-username }
+
+Daha kapsamlı bir örneğe bakalım.
+
+Kullanıcı adı ve şifrenin doğru olup olmadığını kontrol etmek için bir dependency kullanın.
+
+Bunun için kullanıcı adı ve şifreyi kontrol ederken Python standart modülü olan [`secrets`](https://docs.python.org/3/library/secrets.html)'i kullanın.
+
+`secrets.compare_digest()`; `bytes` ya da yalnızca ASCII karakterleri (İngilizce’deki karakterler) içeren bir `str` almalıdır. Bu da `Sebastián` içindeki `á` gibi karakterlerle çalışmayacağı anlamına gelir.
+
+Bunu yönetmek için önce `username` ve `password` değerlerini UTF-8 ile encode ederek `bytes`’a dönüştürürüz.
+
+Sonra `secrets.compare_digest()` kullanarak `credentials.username`’in `"stanleyjobson"` ve `credentials.password`’ün `"swordfish"` olduğundan emin olabiliriz.
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[1,12:24] *}
+
+Bu, kabaca şuna benzer olurdu:
+
+```Python
+if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
+ # Bir hata döndür
+ ...
+```
+
+Ancak `secrets.compare_digest()` kullanarak, "timing attacks" denilen bir saldırı türüne karşı güvenli olursunuz.
+
+### Timing Attacks { #timing-attacks }
+
+Peki "timing attack" nedir?
+
+Bazı saldırganların kullanıcı adı ve şifreyi tahmin etmeye çalıştığını düşünelim.
+
+Ve `johndoe` kullanıcı adı ve `love123` şifresi ile bir request gönderiyorlar.
+
+Uygulamanızdaki Python kodu o zaman kabaca şuna denk olur:
+
+```Python
+if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Ancak Python, `johndoe` içindeki ilk `j` ile `stanleyjobson` içindeki ilk `s`’i karşılaştırdığı anda `False` döndürür; çünkü iki string’in aynı olmadığını zaten anlar ve "kalan harfleri karşılaştırmak için daha fazla hesaplama yapmaya gerek yok" diye düşünür. Uygulamanız da "Incorrect username or password" der.
+
+Sonra saldırganlar bu sefer `stanleyjobsox` kullanıcı adı ve `love123` şifresi ile dener.
+
+Uygulama kodunuz da şuna benzer bir şey yapar:
+
+```Python
+if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Bu kez Python, iki string’in aynı olmadığını fark etmeden önce hem `stanleyjobsox` hem de `stanleyjobson` içinde `stanleyjobso` kısmının tamamını karşılaştırmak zorunda kalır. Bu nedenle "Incorrect username or password" yanıtını vermesi birkaç mikro saniye daha uzun sürer.
+
+#### Yanıt süresi saldırganlara yardımcı olur { #the-time-to-answer-helps-the-attackers }
+
+Bu noktada saldırganlar, server’ın "Incorrect username or password" response’unu göndermesinin birkaç mikro saniye daha uzun sürdüğünü fark ederek _bir şeyleri_ doğru yaptıklarını anlar; yani başlangıçtaki bazı harfler doğrudur.
+
+Sonra tekrar denerken, bunun `johndoe`’dan ziyade `stanleyjobsox`’a daha yakın bir şey olması gerektiğini bilerek devam edebilirler.
+
+#### "Profesyonel" bir saldırı { #a-professional-attack }
+
+Elbette saldırganlar bunu elle tek tek denemez; bunu yapan bir program yazarlar. Muhtemelen saniyede binlerce ya da milyonlarca test yaparlar ve her seferinde yalnızca bir doğru harf daha elde ederler.
+
+Böylece birkaç dakika ya da birkaç saat içinde doğru kullanıcı adı ve şifreyi, yanıt süresini kullanarak ve uygulamamızın "yardımıyla" tahmin etmiş olurlar.
+
+#### `secrets.compare_digest()` ile düzeltin { #fix-it-with-secrets-compare-digest }
+
+Ancak bizim kodumuzda `secrets.compare_digest()` kullanıyoruz.
+
+Kısacası, `stanleyjobsox` ile `stanleyjobson`’u karşılaştırmak için geçen süre, `johndoe` ile `stanleyjobson`’u karşılaştırmak için geçen süreyle aynı olur. Şifre için de aynı şekilde.
+
+Bu sayede uygulama kodunuzda `secrets.compare_digest()` kullanarak bu güvenlik saldırıları ailesine karşı güvenli olursunuz.
+
+### Hatayı döndürün { #return-the-error }
+
+Credential’ların hatalı olduğunu tespit ettikten sonra, 401 status code ile (credential verilmediğinde dönenle aynı) bir `HTTPException` döndürün ve tarayıcının giriş penceresini yeniden göstermesi için `WWW-Authenticate` header’ını ekleyin:
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[26:30] *}
diff --git a/docs/tr/docs/advanced/security/index.md b/docs/tr/docs/advanced/security/index.md
new file mode 100644
index 0000000000000..a8ffbb69d1a65
--- /dev/null
+++ b/docs/tr/docs/advanced/security/index.md
@@ -0,0 +1,19 @@
+# Gelişmiş Güvenlik { #advanced-security }
+
+## Ek Özellikler { #additional-features }
+
+[Öğretici - Kullanıcı Kılavuzu: Güvenlik](../../tutorial/security/index.md) sayfasında ele alınanların dışında güvenlikle ilgili bazı ek özellikler vardır.
+
+/// tip | İpucu
+
+Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**.
+
+Ve kullanım durumunuza göre, çözüm bu bölümlerden birinde olabilir.
+
+///
+
+## Önce Öğreticiyi Okuyun { #read-the-tutorial-first }
+
+Sonraki bölümler, ana [Öğretici - Kullanıcı Kılavuzu: Güvenlik](../../tutorial/security/index.md) sayfasını zaten okuduğunuzu varsayar.
+
+Hepsi aynı kavramlara dayanır, ancak bazı ek işlevselliklere izin verir.
diff --git a/docs/tr/docs/advanced/security/oauth2-scopes.md b/docs/tr/docs/advanced/security/oauth2-scopes.md
new file mode 100644
index 0000000000000..6ac6ea6c1ef92
--- /dev/null
+++ b/docs/tr/docs/advanced/security/oauth2-scopes.md
@@ -0,0 +1,274 @@
+# OAuth2 scope'ları { #oauth2-scopes }
+
+OAuth2 scope'larını **FastAPI** ile doğrudan kullanabilirsiniz; sorunsuz çalışacak şekilde entegre edilmiştir.
+
+Bu sayede OAuth2 standardını takip eden, daha ince taneli bir izin sistemini OpenAPI uygulamanıza (ve API dokümanlarınıza) entegre edebilirsiniz.
+
+Scope'lu OAuth2; Facebook, Google, GitHub, Microsoft, X (Twitter) vb. birçok büyük kimlik doğrulama sağlayıcısının kullandığı mekanizmadır. Kullanıcı ve uygulamalara belirli izinler vermek için bunu kullanırlar.
+
+Facebook, Google, GitHub, Microsoft, X (Twitter) ile "giriş yaptığınızda", o uygulama scope'lu OAuth2 kullanıyor demektir.
+
+Bu bölümde, **FastAPI** uygulamanızda aynı scope'lu OAuth2 ile authentication ve authorization'ı nasıl yöneteceğinizi göreceksiniz.
+
+/// warning | Uyarı
+
+Bu bölüm az çok ileri seviye sayılır. Yeni başlıyorsanız atlayabilirsiniz.
+
+OAuth2 scope'larına mutlaka ihtiyacınız yok; authentication ve authorization'ı istediğiniz şekilde ele alabilirsiniz.
+
+Ancak scope'lu OAuth2, API'nize (OpenAPI ile) ve API dokümanlarınıza güzel biçimde entegre edilebilir.
+
+Buna rağmen, bu scope'ları (veya başka herhangi bir security/authorization gereksinimini) kodunuzda ihtiyaç duyduğunuz şekilde yine siz zorunlu kılarsınız.
+
+Birçok durumda scope'lu OAuth2 gereğinden fazla (overkill) olabilir.
+
+Ama ihtiyacınız olduğunu biliyorsanız ya da merak ediyorsanız okumaya devam edin.
+
+///
+
+## OAuth2 scope'ları ve OpenAPI { #oauth2-scopes-and-openapi }
+
+OAuth2 spesifikasyonu, "scope"ları boşluklarla ayrılmış string'lerden oluşan bir liste olarak tanımlar.
+
+Bu string'lerin her birinin içeriği herhangi bir formatta olabilir, ancak boşluk içermemelidir.
+
+Bu scope'lar "izinleri" temsil eder.
+
+OpenAPI'de (ör. API dokümanlarında) "security scheme" tanımlayabilirsiniz.
+
+Bu security scheme'lerden biri OAuth2 kullanıyorsa, scope'ları da tanımlayıp kullanabilirsiniz.
+
+Her bir "scope" sadece bir string'dir (boşluksuz).
+
+Genellikle belirli güvenlik izinlerini tanımlamak için kullanılır, örneğin:
+
+* `users:read` veya `users:write` sık görülen örneklerdir.
+* `instagram_basic` Facebook / Instagram tarafından kullanılır.
+* `https://www.googleapis.com/auth/drive` Google tarafından kullanılır.
+
+/// info | Bilgi
+
+OAuth2'de "scope", gereken belirli bir izni bildiren bir string'den ibarettir.
+
+`:` gibi başka karakterler içermesi ya da bir URL olması önemli değildir.
+
+Bu detaylar implementasyon'a bağlıdır.
+
+OAuth2 için bunlar sadece string'dir.
+
+///
+
+## Genel görünüm { #global-view }
+
+Önce, ana **Tutorial - User Guide** içindeki [Password (ve hashing) ile OAuth2, JWT token'lı Bearer](../../tutorial/security/oauth2-jwt.md) örneklerinden, OAuth2 scope'larına geçince hangi kısımların değiştiğine hızlıca bakalım:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}
+
+Şimdi bu değişiklikleri adım adım inceleyelim.
+
+## OAuth2 Security scheme { #oauth2-security-scheme }
+
+İlk değişiklik, artık OAuth2 security scheme'ini iki adet kullanılabilir scope ile tanımlamamız: `me` ve `items`.
+
+`scopes` parametresi; her scope'un key, açıklamasının ise value olduğu bir `dict` alır:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *}
+
+Bu scope'ları tanımladığımız için, login/authorize yaptığınızda API dokümanlarında görünecekler.
+
+Ve hangi scope'lara erişim vermek istediğinizi seçebileceksiniz: `me` ve `items`.
+
+Bu, Facebook/Google/GitHub vb. ile giriş yaparken izin verdiğinizde kullanılan mekanizmanın aynısıdır:
+
+
+
+## Scope'lu JWT token { #jwt-token-with-scopes }
+
+Şimdi token *path operation*'ını, istenen scope'ları döndürecek şekilde değiştirin.
+
+Hâlâ aynı `OAuth2PasswordRequestForm` kullanılıyor. Bu form, request'te aldığı her scope için `str`'lerden oluşan bir `list` içeren `scopes` özelliğine sahiptir.
+
+Ve scope'ları JWT token'ın bir parçası olarak döndürüyoruz.
+
+/// danger | Uyarı
+
+Basitlik için burada, gelen scope'ları doğrudan token'a ekliyoruz.
+
+Ama uygulamanızda güvenlik açısından, yalnızca kullanıcının gerçekten sahip olabileceği scope'ları (veya sizin önceden tanımladıklarınızı) eklediğinizden emin olmalısınız.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}
+
+## *Path operation*'larda ve dependency'lerde scope tanımlama { #declare-scopes-in-path-operations-and-dependencies }
+
+Artık `/users/me/items/` için olan *path operation*'ın `items` scope'unu gerektirdiğini tanımlıyoruz.
+
+Bunun için `fastapi` içinden `Security` import edip kullanıyoruz.
+
+Dependency'leri (`Depends` gibi) tanımlamak için `Security` kullanabilirsiniz; fakat `Security`, ayrıca string'lerden oluşan bir scope listesi alan `scopes` parametresini de alır.
+
+Bu durumda `Security`'ye dependency fonksiyonu olarak `get_current_active_user` veriyoruz (`Depends` ile yaptığımız gibi).
+
+Ama ayrıca bir `list` olarak scope'ları da veriyoruz; burada tek bir scope var: `items` (daha fazla da olabilir).
+
+Ve `get_current_active_user` dependency fonksiyonu, sadece `Depends` ile değil `Security` ile de alt-dependency'ler tanımlayabilir. Kendi alt-dependency fonksiyonunu (`get_current_user`) ve daha fazla scope gereksinimini tanımlar.
+
+Bu örnekte `me` scope'unu gerektiriyor (birden fazla scope da isteyebilirdi).
+
+/// note | Not
+
+Farklı yerlerde farklı scope'lar eklemek zorunda değilsiniz.
+
+Burada, **FastAPI**'nin farklı seviyelerde tanımlanan scope'ları nasıl ele aldığını göstermek için böyle yapıyoruz.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}
+
+/// info | Teknik Detaylar
+
+`Security` aslında `Depends`'in bir alt sınıfıdır ve sadece birazdan göreceğimiz bir ek parametreye sahiptir.
+
+Ancak `Depends` yerine `Security` kullanınca **FastAPI**, security scope'larının tanımlanabileceğini bilir, bunları içeride kullanır ve API'yi OpenAPI ile dokümante eder.
+
+Fakat `fastapi` içinden `Query`, `Path`, `Depends`, `Security` vb. import ettiğiniz şeyler, aslında özel sınıflar döndüren fonksiyonlardır.
+
+///
+
+## `SecurityScopes` kullanımı { #use-securityscopes }
+
+Şimdi `get_current_user` dependency'sini güncelleyelim.
+
+Bu fonksiyon, yukarıdaki dependency'ler tarafından kullanılıyor.
+
+Burada, daha önce oluşturduğumuz aynı OAuth2 scheme'i dependency olarak tanımlıyoruz: `oauth2_scheme`.
+
+Bu dependency fonksiyonunun kendi içinde bir scope gereksinimi olmadığı için, `oauth2_scheme` ile `Depends` kullanabiliriz; security scope'larını belirtmemiz gerekmiyorsa `Security` kullanmak zorunda değiliz.
+
+Ayrıca `fastapi.security` içinden import edilen, `SecurityScopes` tipinde özel bir parametre tanımlıyoruz.
+
+Bu `SecurityScopes` sınıfı, `Request`'e benzer (`Request`, request nesnesini doğrudan almak için kullanılmıştı).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}
+
+## `scopes`'ları kullanma { #use-the-scopes }
+
+`security_scopes` parametresi `SecurityScopes` tipinde olacaktır.
+
+Bu nesnenin `scopes` adlı bir özelliği vardır; bu liste, kendisinin ve bunu alt-dependency olarak kullanan tüm dependency'lerin gerektirdiği tüm scope'ları içerir. Yani tüm "dependant"lar... kafa karıştırıcı gelebilir; aşağıda tekrar açıklanıyor.
+
+`security_scopes` nesnesi (`SecurityScopes` sınıfından) ayrıca, bu scope'ları boşluklarla ayrılmış tek bir string olarak veren `scope_str` attribute'una sahiptir (bunu kullanacağız).
+
+Sonrasında birkaç farklı noktada tekrar kullanabileceğimiz (`raise` edebileceğimiz) bir `HTTPException` oluşturuyoruz.
+
+Bu exception içinde, gerekiyorsa, gerekli scope'ları boşlukla ayrılmış bir string olarak (`scope_str` ile) ekliyoruz. Bu scope'ları içeren string'i `WWW-Authenticate` header'ına koyuyoruz (spesifikasyonun bir parçası).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}
+
+## `username` ve veri şeklinin doğrulanması { #verify-the-username-and-data-shape }
+
+Bir `username` aldığımızı doğruluyoruz ve scope'ları çıkarıyoruz.
+
+Ardından bu veriyi Pydantic model'i ile doğruluyoruz (`ValidationError` exception'ını yakalayarak). JWT token'ı okurken veya Pydantic ile veriyi doğrularken bir hata olursa, daha önce oluşturduğumuz `HTTPException`'ı fırlatıyoruz.
+
+Bunun için Pydantic model'i `TokenData`'yı, `scopes` adlı yeni bir özellik ekleyerek güncelliyoruz.
+
+Veriyi Pydantic ile doğrulayarak örneğin scope'ların tam olarak `str`'lerden oluşan bir `list` olduğunu ve `username`'in bir `str` olduğunu garanti edebiliriz.
+
+Aksi halde, örneğin bir `dict` veya başka bir şey gelebilir; bu da daha sonra uygulamanın bir yerinde kırılmaya yol açıp güvenlik riski oluşturabilir.
+
+Ayrıca bu `username` ile bir kullanıcı olduğunu doğruluyoruz; yoksa yine aynı exception'ı fırlatıyoruz.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}
+
+## `scopes`'ların doğrulanması { #verify-the-scopes }
+
+Şimdi bu dependency'nin ve tüm dependant'ların ( *path operation*'lar dahil) gerektirdiği tüm scope'ların, alınan token'da sağlanan scope'lar içinde olup olmadığını doğruluyoruz; değilse `HTTPException` fırlatıyoruz.
+
+Bunun için, tüm bu scope'ları `str` olarak içeren bir `list` olan `security_scopes.scopes` kullanılır.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}
+
+## Dependency ağacı ve scope'lar { #dependency-tree-and-scopes }
+
+Bu dependency ağacını ve scope'ları tekrar gözden geçirelim.
+
+`get_current_active_user` dependency'si, alt-dependency olarak `get_current_user`'ı kullandığı için, `get_current_active_user` üzerinde tanımlanan `"me"` scope'u, `get_current_user`'a geçirilen `security_scopes.scopes` içindeki gerekli scope listesine dahil edilir.
+
+*Path operation*'ın kendisi de `"items"` scope'unu tanımlar; bu da `get_current_user`'a geçirilen `security_scopes.scopes` listesinde yer alır.
+
+Dependency'lerin ve scope'ların hiyerarşisi şöyle görünür:
+
+* *Path operation* `read_own_items` şunlara sahiptir:
+ * Dependency ile gerekli scope'lar `["items"]`:
+ * `get_current_active_user`:
+ * `get_current_active_user` dependency fonksiyonu şunlara sahiptir:
+ * Dependency ile gerekli scope'lar `["me"]`:
+ * `get_current_user`:
+ * `get_current_user` dependency fonksiyonu şunlara sahiptir:
+ * Kendisinin gerektirdiği scope yok.
+ * `oauth2_scheme` kullanan bir dependency.
+ * `SecurityScopes` tipinde bir `security_scopes` parametresi:
+ * Bu `security_scopes` parametresinin `scopes` adlı bir özelliği vardır ve yukarıda tanımlanan tüm scope'ları içeren bir `list` taşır, yani:
+ * *Path operation* `read_own_items` için `security_scopes.scopes` `["me", "items"]` içerir.
+ * *Path operation* `read_users_me` için `security_scopes.scopes` `["me"]` içerir; çünkü bu scope `get_current_active_user` dependency'sinde tanımlanmıştır.
+ * *Path operation* `read_system_status` için `security_scopes.scopes` `[]` (boş) olur; çünkü herhangi bir `Security` ile `scopes` tanımlamamıştır ve dependency'si olan `get_current_user` da `scopes` tanımlamaz.
+
+/// tip | İpucu
+
+Buradaki önemli ve "sihirli" nokta şu: `get_current_user`, her *path operation* için kontrol etmesi gereken farklı bir `scopes` listesi alır.
+
+Bu, belirli bir *path operation* için dependency ağacındaki her *path operation* ve her dependency üzerinde tanımlanan `scopes`'lara bağlıdır.
+
+///
+
+## `SecurityScopes` hakkında daha fazla detay { #more-details-about-securityscopes }
+
+`SecurityScopes`'u herhangi bir noktada ve birden fazla yerde kullanabilirsiniz; mutlaka "kök" dependency'de olmak zorunda değildir.
+
+Her zaman, **o spesifik** *path operation* ve **o spesifik** dependency ağacı için, mevcut `Security` dependency'lerinde ve tüm dependant'larda tanımlanan security scope'larını içerir.
+
+`SecurityScopes`, dependant'ların tanımladığı tüm scope'ları barındırdığı için, gereken scope'ların token'da olup olmadığını merkezi bir dependency fonksiyonunda doğrulayıp, farklı *path operation*'larda farklı scope gereksinimleri tanımlayabilirsiniz.
+
+Bu kontroller her *path operation* için bağımsız yapılır.
+
+## Deneyin { #check-it }
+
+API dokümanlarını açarsanız, authenticate olup hangi scope'ları authorize etmek istediğinizi seçebilirsiniz.
+
+
+
+Hiç scope seçmezseniz "authenticated" olursunuz; ancak `/users/me/` veya `/users/me/items/`'e erişmeye çalıştığınızda, yeterli izniniz olmadığını söyleyen bir hata alırsınız. Yine de `/status/`'a erişebilirsiniz.
+
+`me` scope'unu seçip `items` scope'unu seçmezseniz `/users/me/`'a erişebilirsiniz ama `/users/me/items/`'e erişemezsiniz.
+
+Bu, bir üçüncü taraf uygulamanın, bir kullanıcı tarafından sağlanan token ile bu *path operation*'lardan birine erişmeye çalıştığında; kullanıcının uygulamaya kaç izin verdiğine bağlı olarak yaşayacağı durumdur.
+
+## Üçüncü taraf entegrasyonları hakkında { #about-third-party-integrations }
+
+Bu örnekte OAuth2 "password" flow'unu kullanıyoruz.
+
+Bu, kendi uygulamamıza giriş yaptığımız durumlar için uygundur; muhtemelen kendi frontend'imiz vardır.
+
+Çünkü `username` ve `password` alacağını bildiğimiz frontend'i biz kontrol ediyoruz, dolayısıyla güvenebiliriz.
+
+Ancak başkalarının bağlanacağı bir OAuth2 uygulaması geliştiriyorsanız (yani Facebook, Google, GitHub vb. gibi bir authentication provider muadili geliştiriyorsanız) diğer flow'lardan birini kullanmalısınız.
+
+En yaygını implicit flow'dur.
+
+En güvenlisi code flow'dur; ancak daha fazla adım gerektirdiği için implementasyonu daha karmaşıktır. Daha karmaşık olduğundan, birçok sağlayıcı implicit flow'yu önermeye yönelir.
+
+/// note | Not
+
+Her authentication provider'ın flow'ları markasının bir parçası yapmak için farklı şekilde adlandırması yaygındır.
+
+Ama sonuçta aynı OAuth2 standardını implement ediyorlar.
+
+///
+
+**FastAPI**, bu OAuth2 authentication flow'larının tamamı için `fastapi.security.oauth2` içinde yardımcı araçlar sunar.
+
+## Decorator `dependencies` içinde `Security` { #security-in-decorator-dependencies }
+
+Decorator'ın `dependencies` parametresinde bir `list` `Depends` tanımlayabildiğiniz gibi ( [Path operation decorator'larında Dependencies](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md) bölümünde açıklandığı üzere), burada `scopes` ile birlikte `Security` de kullanabilirsiniz.
diff --git a/docs/tr/docs/advanced/settings.md b/docs/tr/docs/advanced/settings.md
new file mode 100644
index 0000000000000..a39e28a9231bd
--- /dev/null
+++ b/docs/tr/docs/advanced/settings.md
@@ -0,0 +1,302 @@
+# Ayarlar ve Ortam Değişkenleri { #settings-and-environment-variables }
+
+Birçok durumda uygulamanızın bazı harici ayarlara veya konfigürasyonlara ihtiyacı olabilir; örneğin secret key'ler, veritabanı kimlik bilgileri, e-posta servisleri için kimlik bilgileri vb.
+
+Bu ayarların çoğu değişkendir (değişebilir); örneğin veritabanı URL'leri. Ayrıca birçoğu hassas olabilir; örneğin secret'lar.
+
+Bu nedenle bunları, uygulama tarafından okunan environment variable'lar ile sağlamak yaygındır.
+
+/// tip | İpucu
+
+Environment variable'ları anlamak için [Ortam Değişkenleri](../environment-variables.md) dokümanını okuyabilirsiniz.
+
+///
+
+## Tipler ve doğrulama { #types-and-validation }
+
+Bu environment variable'lar yalnızca metin (string) taşıyabilir; çünkü Python'ın dışındadırlar ve diğer programlarla ve sistemin geri kalanıyla uyumlu olmaları gerekir (hatta Linux, Windows, macOS gibi farklı işletim sistemleriyle de).
+
+Bu da, Python içinde bir environment variable'dan okunan herhangi bir değerin `str` olacağı anlamına gelir; farklı bir tipe dönüştürme veya herhangi bir doğrulama işlemi kod içinde yapılmalıdır.
+
+## Pydantic `Settings` { #pydantic-settings }
+
+Neyse ki Pydantic, environment variable'lardan gelen bu ayarları yönetmek için [Pydantic: Settings yönetimi](https://docs.pydantic.dev/latest/concepts/pydantic_settings/) ile çok iyi bir yardımcı araç sunar.
+
+### `pydantic-settings`'i kurun { #install-pydantic-settings }
+
+Önce, [Sanal ortam](../virtual-environments.md) oluşturduğunuzdan, aktive ettiğinizden emin olun ve ardından `pydantic-settings` paketini kurun:
+
+
+
+Sonra alt uygulamanın dokümanlarını [http://127.0.0.1:8000/subapi/docs](http://127.0.0.1:8000/subapi/docs) adresinden açın.
+
+Alt uygulama için otomatik API dokümanlarını göreceksiniz; yalnızca onun kendi _path operation_’larını içerir ve hepsi doğru alt-path öneki `/subapi` altında yer alır:
+
+
+
+İki arayüzden herhangi biriyle etkileşime girmeyi denerseniz doğru şekilde çalıştıklarını görürsünüz; çünkü tarayıcı her bir uygulama ya da alt uygulama ile ayrı ayrı iletişim kurabilir.
+
+### Teknik Detaylar: `root_path` { #technical-details-root-path }
+
+Yukarıda anlatıldığı gibi bir alt uygulamayı mount ettiğinizde FastAPI, ASGI spesifikasyonundaki `root_path` adlı bir mekanizmayı kullanarak alt uygulamaya mount path’ini iletmeyi otomatik olarak yönetir.
+
+Bu sayede alt uygulama, dokümantasyon arayüzü için o path önekini kullanması gerektiğini bilir.
+
+Ayrıca alt uygulamanın kendi mount edilmiş alt uygulamaları da olabilir; FastAPI tüm bu `root_path`’leri otomatik olarak yönettiği için her şey doğru şekilde çalışır.
+
+`root_path` hakkında daha fazlasını ve bunu açıkça nasıl kullanacağınızı [Proxy Arkasında](behind-a-proxy.md) bölümünde öğreneceksiniz.
diff --git a/docs/tr/docs/advanced/templates.md b/docs/tr/docs/advanced/templates.md
new file mode 100644
index 0000000000000..443a527efcbdd
--- /dev/null
+++ b/docs/tr/docs/advanced/templates.md
@@ -0,0 +1,126 @@
+# Şablonlar { #templates }
+
+**FastAPI** ile istediğiniz herhangi bir template engine'i kullanabilirsiniz.
+
+Yaygın bir tercih, Flask ve diğer araçların da kullandığı Jinja2'dir.
+
+Bunu kolayca yapılandırmak için, doğrudan **FastAPI** uygulamanızda kullanabileceğiniz yardımcı araçlar vardır (Starlette tarafından sağlanır).
+
+## Bağımlılıkları Yükleme { #install-dependencies }
+
+Bir [sanal ortam](../virtual-environments.md) oluşturduğunuzdan, etkinleştirdiğinizden ve `jinja2`'yi yüklediğinizden emin olun:
+
+
+
+Input kutusuna mesaj yazıp gönderebilirsiniz:
+
+
+
+Ve WebSockets kullanan **FastAPI** uygulamanız yanıt döndürecektir:
+
+
+
+Birçok mesaj gönderebilir (ve alabilirsiniz):
+
+
+
+Ve hepsinde aynı WebSocket bağlantısı kullanılacaktır.
+
+## `Depends` ve Diğerlerini Kullanma { #using-depends-and-others }
+
+WebSocket endpoint'lerinde `fastapi` içinden import edip şunları kullanabilirsiniz:
+
+* `Depends`
+* `Security`
+* `Cookie`
+* `Header`
+* `Path`
+* `Query`
+
+Diğer FastAPI endpoint'leri/*path operations* ile aynı şekilde çalışırlar:
+
+{* ../../docs_src/websockets_/tutorial002_an_py310.py hl[68:69,82] *}
+
+/// info
+
+Bu bir WebSocket olduğu için `HTTPException` raise etmek pek anlamlı değildir; bunun yerine `WebSocketException` raise ederiz.
+
+[Spesifikasyonda tanımlanan geçerli kodlar](https://tools.ietf.org/html/rfc6455#section-7.4.1) arasından bir kapatma kodu kullanabilirsiniz.
+
+///
+
+### Dependency'lerle WebSockets'i Deneyin { #try-the-websockets-with-dependencies }
+
+Uygulamanızı çalıştırın:
+
+
+
+## Bağlantı Kopmalarını ve Birden Fazla Client'ı Yönetme { #handling-disconnections-and-multiple-clients }
+
+Bir WebSocket bağlantısı kapandığında, `await websocket.receive_text()` bir `WebSocketDisconnect` exception'ı raise eder; ardından bunu bu örnekteki gibi yakalayıp (catch) yönetebilirsiniz.
+
+{* ../../docs_src/websockets_/tutorial003_py310.py hl[79:81] *}
+
+Denemek için:
+
+* Uygulamayı birden fazla tarayıcı sekmesiyle açın.
+* Bu sekmelerden mesaj yazın.
+* Sonra sekmelerden birini kapatın.
+
+Bu, `WebSocketDisconnect` exception'ını raise eder ve diğer tüm client'lar şuna benzer bir mesaj alır:
+
+```
+Client #1596980209979 left the chat
+```
+
+/// tip
+
+Yukarıdaki uygulama, birden fazla WebSocket bağlantısına mesajları nasıl yönetip broadcast edeceğinizi göstermek için minimal ve basit bir örnektir.
+
+Ancak her şey memory'de, tek bir list içinde yönetildiği için yalnızca process çalıştığı sürece ve yalnızca tek bir process ile çalışacaktır.
+
+FastAPI ile kolay entegre olan ama Redis, PostgreSQL vb. tarafından desteklenen daha sağlam bir şeye ihtiyacınız varsa [encode/broadcaster](https://github.com/encode/broadcaster)'a göz atın.
+
+///
+
+## Daha Fazla Bilgi { #more-info }
+
+Seçenekler hakkında daha fazlasını öğrenmek için Starlette dokümantasyonunda şunlara bakın:
+
+* [`WebSocket` class'ı](https://www.starlette.dev/websockets/).
+* [Class tabanlı WebSocket yönetimi](https://www.starlette.dev/endpoints/#websocketendpoint).
diff --git a/docs/tr/docs/advanced/wsgi.md b/docs/tr/docs/advanced/wsgi.md
new file mode 100644
index 0000000000000..06a3f2834f694
--- /dev/null
+++ b/docs/tr/docs/advanced/wsgi.md
@@ -0,0 +1,51 @@
+# WSGI'yi Dahil Etme - Flask, Django ve Diğerleri { #including-wsgi-flask-django-others }
+
+WSGI uygulamalarını [Alt Uygulamalar - Mount Etme](sub-applications.md), [Bir Proxy Arkasında](behind-a-proxy.md) bölümlerinde gördüğünüz gibi mount edebilirsiniz.
+
+Bunun için `WSGIMiddleware`'ı kullanabilir ve bunu WSGI uygulamanızı (örneğin Flask, Django vb.) sarmalamak için kullanabilirsiniz.
+
+## `WSGIMiddleware` Kullanımı { #using-wsgimiddleware }
+
+/// info
+
+Bunun için `a2wsgi` kurulmalıdır; örneğin `pip install a2wsgi` ile.
+
+///
+
+`WSGIMiddleware`'ı `a2wsgi` paketinden import etmeniz gerekir.
+
+Ardından WSGI (örn. Flask) uygulamasını middleware ile sarmalayın.
+
+Ve sonra bunu bir path'in altına mount edin.
+
+{* ../../docs_src/wsgi/tutorial001_py310.py hl[1,3,23] *}
+
+/// note
+
+Önceden, `fastapi.middleware.wsgi` içindeki `WSGIMiddleware`'ın kullanılması öneriliyordu, ancak artık kullanımdan kaldırıldı.
+
+Bunun yerine `a2wsgi` paketini kullanmanız önerilir. Kullanım aynıdır.
+
+Sadece `a2wsgi` paketinin kurulu olduğundan emin olun ve `WSGIMiddleware`'ı `a2wsgi` içinden doğru şekilde import edin.
+
+///
+
+## Kontrol Edelim { #check-it }
+
+Artık `/v1/` path'i altındaki her request Flask uygulaması tarafından işlenecektir.
+
+Geri kalanı ise **FastAPI** tarafından işlenecektir.
+
+Eğer uygulamanızı çalıştırıp [http://localhost:8000/v1/](http://localhost:8000/v1/) adresine giderseniz, Flask'tan gelen response'u göreceksiniz:
+
+```txt
+Hello, World from Flask!
+```
+
+Ve eğer [http://localhost:8000/v2](http://localhost:8000/v2) adresine giderseniz, FastAPI'den gelen response'u göreceksiniz:
+
+```JSON
+{
+ "message": "Hello World"
+}
+```
diff --git a/docs/tr/docs/alternatives.md b/docs/tr/docs/alternatives.md
new file mode 100644
index 0000000000000..d2149a3571586
--- /dev/null
+++ b/docs/tr/docs/alternatives.md
@@ -0,0 +1,483 @@
+# Alternatifler, İlham Kaynakları ve Karşılaştırmalar { #alternatives-inspiration-and-comparisons }
+
+**FastAPI**'a nelerin ilham verdiği, alternatiflerle nasıl karşılaştırıldığı ve onlardan neler öğrendiği.
+
+## Giriş { #intro }
+
+Başkalarının daha önceki çalışmaları olmasaydı, **FastAPI** var olmazdı.
+
+Önceden oluşturulan birçok araç, ortaya çıkışına ilham verdi.
+
+Yıllarca yeni bir framework oluşturmaktan kaçındım. Önce **FastAPI**’ın bugün kapsadığı özelliklerin tamamını, birçok farklı framework, eklenti ve araçla çözmeyi denedim.
+
+Ancak bir noktada, geçmişteki araçlardan en iyi fikirleri alıp, mümkün olan en iyi şekilde birleştiren ve daha önce mevcut olmayan dil özelliklerini (Python 3.6+ tip belirteçleri) kullanarak tüm bu özellikleri sağlayan bir şey geliştirmekten başka seçenek kalmadı.
+
+## Daha Önce Geliştirilen Araçlar { #previous-tools }
+
+### [Django](https://www.djangoproject.com/) { #django }
+
+Python ekosistemindeki en popüler ve yaygın olarak güvenilen web framework’üdür. Instagram gibi sistemleri geliştirmede kullanılmıştır.
+
+MySQL veya PostgreSQL gibi ilişkisel veritabanlarıyla nispeten sıkı bağlıdır, bu nedenle Couchbase, MongoDB, Cassandra vb. gibi bir NoSQL veritabanını ana depolama motoru olarak kullanmak pek kolay değildir.
+
+Modern bir ön uç (React, Vue.js, Angular gibi) veya onunla haberleşen diğer sistemler (ör. IoT cihazları) tarafından tüketilen API’lar üretmekten ziyade, arka uçta HTML üretmek için oluşturulmuştur.
+
+### [Django REST Framework](https://www.django-rest-framework.org/) { #django-rest-framework }
+
+Django REST Framework, Django üzerine kurulu esnek bir araç takımı olarak, Web API’lar geliştirmeyi ve Django’nun API kabiliyetlerini artırmayı hedefler.
+
+Mozilla, Red Hat ve Eventbrite gibi birçok şirket tarafından kullanılmaktadır.
+
+**Otomatik API dökümantasyonu**nun ilk örneklerinden biriydi ve bu, “**FastAPI** arayışına” ilham veren ilk fikirlerden biriydi.
+
+/// note | Not
+
+Django REST Framework, **FastAPI**'ın üzerine inşa edildiği Starlette ve Uvicorn'un da yaratıcısı olan Tom Christie tarafından geliştirildi.
+
+///
+
+/// check | **FastAPI**'a ilham olan
+
+Otomatik API dökümantasyonu sağlayan bir web arayüzü sunmak.
+
+///
+
+### [Flask](https://flask.palletsprojects.com) { #flask }
+
+Flask bir “mikroframework”tür, Django’da varsayılan gelen pek çok özelliği (veritabanı entegrasyonları vb.) içermez.
+
+Bu basitlik ve esneklik, NoSQL veritabanlarını ana veri depolama sistemi olarak kullanmak gibi şeyleri mümkün kılar.
+
+Çok basit olduğu için öğrenmesi nispeten sezgiseldir, ancak dökümantasyon bazı noktalarda biraz teknikleşebilir.
+
+Ayrıca veritabanı, kullanıcı yönetimi veya Django’da önceden gelen pek çok özelliğe ihtiyaç duymayan uygulamalar için de yaygın olarak kullanılır. Yine de bu özelliklerin çoğu eklentilerle eklenebilir.
+
+Bileşenlerin ayrık olması ve gerekeni tam olarak kapsayacak şekilde genişletilebilen bir “mikroframework” olması, özellikle korumak istediğim bir özelliktir.
+
+Flask’ın sadeliği göz önüne alındığında, API geliştirmek için iyi bir aday gibi görünüyordu. Sırada, Flask için bir “Django REST Framework” bulmak vardı.
+
+/// check | **FastAPI**'a ilham olan
+
+Gereken araç ve parçaları kolayca eşleştirip birleştirmeyi sağlayan bir mikroframework olmak.
+
+Basit ve kullanımı kolay bir yönlendirme (routing) sistemine sahip olmak.
+
+///
+
+### [Requests](https://requests.readthedocs.io) { #requests }
+
+**FastAPI** aslında **Requests**’in bir alternatifi değildir. Kapsamları çok farklıdır.
+
+Hatta bir FastAPI uygulamasının içinde Requests kullanmak yaygındır.
+
+Yine de FastAPI, Requests’ten epey ilham almıştır.
+
+**Requests** bir kütüphane olarak API’larla (istemci olarak) etkileşime geçmeye yararken, **FastAPI** API’lar (sunucu olarak) geliştirmeye yarar.
+
+Yani daha çok zıt uçlardadırlar ama birbirlerini tamamlarlar.
+
+Requests çok basit ve sezgisel bir tasarıma sahiptir, mantıklı varsayılanlarla kullanımı çok kolaydır. Aynı zamanda çok güçlü ve özelleştirilebilirdir.
+
+Bu yüzden resmi web sitesinde de söylendiği gibi:
+
+> Requests, tüm zamanların en çok indirilen Python paketlerinden biridir
+
+Kullanımı çok basittir. Örneğin bir `GET` isteği yapmak için:
+
+```Python
+response = requests.get("http://example.com/some/url")
+```
+
+Buna karşılık bir FastAPI API *path operation*’ı şöyle olabilir:
+
+```Python hl_lines="1"
+@app.get("/some/url")
+def read_url():
+ return {"message": "Hello World"}
+```
+
+`requests.get(...)` ile `@app.get(...)` arasındaki benzerliklere bakın.
+
+/// check | **FastAPI**'a ilham olan
+
+* Basit ve sezgisel bir API’ya sahip olmak.
+* HTTP metot isimlerini (işlemlerini) doğrudan, anlaşılır ve sezgisel bir şekilde kullanmak.
+* Mantıklı varsayılanlara sahip olmak ama güçlü özelleştirmeler de sunmak.
+
+///
+
+### [Swagger](https://swagger.io/) / [OpenAPI](https://github.com/OAI/OpenAPI-Specification/) { #swagger-openapi }
+
+Django REST Framework’ünden istediğim ana özellik otomatik API dökümantasyonuydu.
+
+Sonra API’ları JSON (veya JSON’un bir uzantısı olan YAML) kullanarak dökümante etmek için Swagger adlı bir standart olduğunu gördüm.
+
+Ve Swagger API’ları için zaten oluşturulmuş bir web arayüzü vardı. Yani bir API için Swagger dökümantasyonu üretebilmek, bu web arayüzünü otomatik kullanabilmek demekti.
+
+Bir noktada Swagger, Linux Foundation’a devredildi ve OpenAPI olarak yeniden adlandırıldı.
+
+Bu yüzden, 2.0 sürümü söz konusu olduğunda “Swagger”, 3+ sürümler için ise “OpenAPI” denmesi yaygındır.
+
+/// check | **FastAPI**'a ilham olan
+
+API spesifikasyonları için özel bir şema yerine açık bir standart benimsemek ve kullanmak.
+
+Ve standartlara dayalı kullanıcı arayüzü araçlarını entegre etmek:
+
+* [Swagger UI](https://github.com/swagger-api/swagger-ui)
+* [ReDoc](https://github.com/Rebilly/ReDoc)
+
+Bu ikisi oldukça popüler ve istikrarlı oldukları için seçildi; hızlı bir aramayla OpenAPI için onlarca alternatif kullanıcı arayüzü bulabilirsiniz (**FastAPI** ile de kullanabilirsiniz).
+
+///
+
+### Flask REST framework’leri { #flask-rest-frameworks }
+
+Birçok Flask REST framework’ü var; ancak zaman ayırıp inceledikten sonra çoğunun artık sürdürülmediğini veya bazı kritik sorunlar nedeniyle uygun olmadıklarını gördüm.
+
+### [Marshmallow](https://marshmallow.readthedocs.io/en/stable/) { #marshmallow }
+
+API sistemlerinin ihtiyaç duyduğu temel özelliklerden biri, koddan (Python) veriyi alıp ağ üzerinden gönderilebilecek bir şeye dönüştürmek, yani veri “dönüşüm”üdür. Örneğin, bir veritabanından gelen verileri içeren bir objeyi JSON objesine dönüştürmek, `datetime` objelerini string’e çevirmek vb.
+
+API’ların ihtiyaç duyduğu bir diğer önemli özellik, veri doğrulamadır; belirli parametreler göz önüne alındığında verinin geçerli olduğundan emin olmak. Örneğin, bir alanın `int` olması ve rastgele bir metin olmaması. Bu özellikle dışarıdan gelen veriler için kullanışlıdır.
+
+Bir veri doğrulama sistemi olmadan, tüm bu kontrolleri kod içinde el ile yapmanız gerekir.
+
+Marshmallow, bu özellikleri sağlamak için inşa edildi. Harika bir kütüphanedir ve geçmişte çok kullandım.
+
+Ancak Python tip belirteçlerinden önce yazılmıştır. Dolayısıyla her şemayı tanımlamak için Marshmallow’un sağladığı belirli yardımcılar ve sınıflar kullanılır.
+
+/// check | **FastAPI**'a ilham olan
+
+Kodla, veri tiplerini ve doğrulamayı otomatik sağlayan “şemalar” tanımlamak.
+
+///
+
+### [Webargs](https://webargs.readthedocs.io/en/latest/) { #webargs }
+
+API’ların ihtiyaç duyduğu bir diğer büyük özellik, gelen isteklerden veriyi ayrıştırmadır.
+
+Webargs, Flask dahil birkaç framework’ün üzerinde bunu sağlamak için geliştirilmiş bir araçtır.
+
+Veri doğrulama için arka planda Marshmallow’u kullanır. Aynı geliştiriciler tarafından yazılmıştır.
+
+**FastAPI**’dan önce benim de çok kullandığım harika bir araçtır.
+
+/// info | Bilgi
+
+Webargs, Marshmallow geliştiricileri tarafından oluşturuldu.
+
+///
+
+/// check | **FastAPI**'a ilham olan
+
+Gelen istek verisini otomatik doğrulamak.
+
+///
+
+### [APISpec](https://apispec.readthedocs.io/en/stable/) { #apispec }
+
+Marshmallow ve Webargs; doğrulama, ayrıştırma ve dönüşümü eklenti olarak sağlar.
+
+Ama dökümantasyon eksikti. Sonra APISpec geliştirildi.
+
+Birçok framework için bir eklentidir (Starlette için de bir eklenti vardır).
+
+Çalışma şekli: Her bir route’u işleyen fonksiyonun docstring’i içine YAML formatında şema tanımı yazarsınız.
+
+Ve OpenAPI şemaları üretir.
+
+Flask, Starlette, Responder vb. için çalışma şekli böyledir.
+
+Ancak yine, Python metni içinde (kocaman bir YAML) mikro bir söz dizimi sorunu ortaya çıkar.
+
+Editör bu konuda pek yardımcı olamaz. Parametreleri veya Marshmallow şemalarını değiştirip docstring’teki YAML’ı güncellemeyi unutursak, üretilen şema geçerliliğini yitirir.
+
+/// info | Bilgi
+
+APISpec, Marshmallow geliştiricileri tarafından oluşturuldu.
+
+///
+
+/// check | **FastAPI**'a ilham olan
+
+API’lar için açık standart olan OpenAPI’ı desteklemek.
+
+///
+
+### [Flask-apispec](https://flask-apispec.readthedocs.io/en/latest/) { #flask-apispec }
+
+Webargs, Marshmallow ve APISpec’i bir araya getiren bir Flask eklentisidir.
+
+Webargs ve Marshmallow’dan aldığı bilgiyi kullanarak, APISpec ile otomatik OpenAPI şemaları üretir.
+
+Harika ama yeterince değer görmeyen bir araçtır. Mevcut birçok Flask eklentisinden çok daha popüler olmalıydı. Muhtemelen dökümantasyonunun fazla kısa ve soyut olmasından kaynaklanıyor olabilir.
+
+Python docstring’leri içine YAML (farklı bir söz dizimi) yazma ihtiyacını ortadan kaldırdı.
+
+**FastAPI**’yı inşa edene kadar, Flask + Flask-apispec + Marshmallow + Webargs kombinasyonu benim favori arka uç stack’imdi.
+
+Bunu kullanmak, birkaç Flask full‑stack üreticisinin ortaya çıkmasına yol açtı. Şu ana kadar benim (ve birkaç harici ekibin) kullandığı ana stack’ler:
+
+* [https://github.com/tiangolo/full-stack](https://github.com/tiangolo/full-stack)
+* [https://github.com/tiangolo/full-stack-flask-couchbase](https://github.com/tiangolo/full-stack-flask-couchbase)
+* [https://github.com/tiangolo/full-stack-flask-couchdb](https://github.com/tiangolo/full-stack-flask-couchdb)
+
+Aynı full‑stack üreticiler, [**FastAPI** Proje Üreticileri](project-generation.md)’nin de temelini oluşturdu.
+
+/// info | Bilgi
+
+Flask-apispec, Marshmallow geliştiricileri tarafından oluşturuldu.
+
+///
+
+/// check | **FastAPI**'a ilham olan
+
+Veri dönüşümü ve doğrulamayı tanımlayan aynı koddan, OpenAPI şemasını otomatik üretmek.
+
+///
+
+### [NestJS](https://nestjs.com/) (ve [Angular](https://angular.io/)) { #nestjs-and-angular }
+
+Bu Python bile değil; NestJS, Angular’dan ilham alan bir JavaScript (TypeScript) NodeJS framework’üdür.
+
+Flask-apispec ile yapılabilene kısmen benzer bir şey başarır.
+
+Angular 2’den esinlenen, entegre bir bağımlılık enjeksiyonu sistemi vardır. “Injectable”ları önceden kaydetmeyi gerektirir (bildiğim diğer bağımlılık enjeksiyonu sistemlerinde olduğu gibi), bu da ayrıntıyı ve kod tekrarını artırır.
+
+Parametreler TypeScript tipleriyle (Python tip belirteçlerine benzer) açıklandığından, editör desteği oldukça iyidir.
+
+Ancak TypeScript tip bilgisi JavaScript’e derlemeden sonra korunmadığından, aynı anda tiplere dayanarak doğrulama, dönüşüm ve dökümantasyon tanımlanamaz. Bu ve bazı tasarım kararları nedeniyle doğrulama, dönüşüm ve otomatik şema üretimi için birçok yere dekoratör eklemek gerekir; proje oldukça ayrıntılı hâle gelir.
+
+İçiçe modelleri çok iyi işleyemez. Yani istek gövdesindeki JSON, içinde başka alanları ve onlar da içiçe JSON objelerini içeriyorsa, doğru şekilde dökümante edilip doğrulanamaz.
+
+/// check | **FastAPI**'a ilham olan
+
+Harika editör desteği için Python tiplerini kullanmak.
+
+Güçlü bir bağımlılık enjeksiyonu sistemine sahip olmak. Kod tekrarını en aza indirmenin bir yolunu bulmak.
+
+///
+
+### [Sanic](https://sanic.readthedocs.io/en/latest/) { #sanic }
+
+`asyncio` tabanlı, son derece hızlı ilk Python framework’lerinden biriydi. Flask’a oldukça benzer olacak şekilde geliştirilmişti.
+
+/// note | Teknik Detaylar
+
+Varsayılan Python `asyncio` döngüsü yerine [`uvloop`](https://github.com/MagicStack/uvloop) kullanır; hızını esasen bu sağlar.
+
+Açık kıyaslamalarda, bugün Uvicorn ve Starlette’in Sanic’ten daha hızlı olduğu görülür; Sanic bu ikisine ilham vermiştir.
+
+///
+
+/// check | **FastAPI**'a ilham olan
+
+Çok yüksek performans elde etmenin bir yolunu bulmak.
+
+Bu yüzden **FastAPI**, en hızlı framework olduğu için (üçüncü parti kıyaslamalara göre) Starlette üzerine kuruludur.
+
+///
+
+### [Falcon](https://falconframework.org/) { #falcon }
+
+Falcon, başka bir yüksek performanslı Python framework’üdür; minimal olacak şekilde tasarlanmış ve Hug gibi diğer framework’lere temel olmuştur.
+
+İki parametre alan fonksiyonlar etrafında tasarlanmıştır: “request” ve “response”. İstekten parçalar “okur”, cevaba parçalar “yazarsınız”. Bu tasarım nedeniyle, fonksiyon parametreleriyle standart Python tip belirteçlerini kullanarak istek parametrelerini ve gövdelerini ilan etmek mümkün değildir.
+
+Dolayısıyla veri doğrulama, dönüşüm ve dökümantasyon kodda yapılmalı; otomatik olmaz. Ya da Hug’da olduğu gibi Falcon’un üzerine bir framework olarak uygulanmalıdır. Falcon’un tasarımından etkilenen ve tek bir request objesi ile response objesini parametre olarak alan diğer framework’lerde de aynı ayrım vardır.
+
+/// check | **FastAPI**'a ilham olan
+
+Harika performans elde etmenin yollarını bulmak.
+
+Hug ile birlikte (Hug, Falcon’a dayanır) **FastAPI**’da fonksiyonlarda opsiyonel bir `response` parametresi ilan edilmesi fikrine ilham vermek. FastAPI’da bu parametre çoğunlukla header, cookie ve alternatif durum kodlarını ayarlamak için kullanılır.
+
+///
+
+### [Molten](https://moltenframework.com/) { #molten }
+
+**FastAPI**’ı geliştirmenin ilk aşamalarında Molten’ı keşfettim. Oldukça benzer fikirleri vardı:
+
+* Python tip belirteçlerine dayanır.
+* Bu tiplere bağlı doğrulama ve dökümantasyon sağlar.
+* Bağımlılık enjeksiyonu sistemi vardır.
+
+Pydantic gibi doğrulama, dönüşüm ve dökümantasyon için üçüncü parti bir kütüphane kullanmaz; kendi içinde sağlar. Bu yüzden bu veri tipi tanımlarını tekrar kullanmak o kadar kolay olmaz.
+
+Biraz daha ayrıntılı yapılandırma ister. Ve ASGI yerine WSGI tabanlı olduğundan, Uvicorn, Starlette ve Sanic gibi araçların yüksek performansından faydalanmaya yönelik tasarlanmamıştır.
+
+Bağımlılık enjeksiyonu sistemi, bağımlılıkların önceden kaydedilmesini ve tiplerine göre çözülmesini gerektirir. Yani belirli bir tipi sağlayan birden fazla “bileşen” tanımlanamaz.
+
+Route’lar, endpoint’i işleyen fonksiyonun üstüne konan dekoratörlerle değil, tek bir yerde, farklı yerlerde tanımlanmış fonksiyonlar kullanılarak ilan edilir. Bu yaklaşım, Flask (ve Starlette) yerine Django’ya daha yakındır; kodda aslında birbirine sıkı bağlı olan şeyleri ayırır.
+
+/// check | **FastAPI**'a ilham olan
+
+Model özelliklerinin “varsayılan” değerlerini kullanarak veri tiplerine ekstra doğrulamalar tanımlamak. Bu, editör desteğini iyileştirir ve Pydantic’te daha önce yoktu.
+
+Bu yaklaşım, Pydantic’te de aynı doğrulama beyan stilinin desteklenmesine ilham verdi (bu işlevselliklerin tamamı artık Pydantic’te mevcut).
+
+///
+
+### [Hug](https://github.com/hugapi/hug) { #hug }
+
+Hug, Python tip belirteçlerini kullanarak API parametre tiplerini ilan etmeyi uygulayan ilk framework’lerden biriydi. Diğer araçlara da ilham veren harika bir fikirdi.
+
+Standart Python tipleri yerine kendi özel tiplerini kullansa da büyük bir adımdı.
+
+JSON ile tüm API’ı beyan eden özel bir şema üreten ilk framework’lerden biriydi.
+
+OpenAPI veya JSON Schema gibi bir standarda dayanmadığı için Swagger UI gibi diğer araçlarla doğrudan entegre edilemezdi. Yine de oldukça yenilikçiydi.
+
+Nadir bir özelliği daha vardı: aynı framework ile hem API’lar hem de CLI’lar oluşturmak mümkündü.
+
+Senkron Python web framework’leri için önceki standart olan WSGI’ye dayandığından, WebSocket vb. şeyleri işleyemez, ancak yine de yüksek performansa sahiptir.
+
+/// info | Bilgi
+
+Hug, Python dosyalarındaki import’ları otomatik sıralayan harika bir araç olan [`isort`](https://github.com/timothycrosley/isort)’un geliştiricisi Timothy Crosley tarafından geliştirildi.
+
+///
+
+/// check | **FastAPI**'a ilham olan fikirler
+
+Hug, APIStar’ın bazı kısımlarına ilham verdi ve APIStar ile birlikte en umut verici bulduğum araçlardandı.
+
+**FastAPI**, parametreleri ilan etmek ve API’ı otomatik tanımlayan bir şema üretmek için Python tip belirteçlerini kullanma fikrini Hug’dan ilhamla benimsedi.
+
+Ayrıca header ve cookie ayarlamak için fonksiyonlarda `response` parametresi ilan etme fikrine de Hug ilham verdi.
+
+///
+
+### [APIStar](https://github.com/encode/apistar) (<= 0.5) { #apistar-0-5 }
+
+**FastAPI**’yi inşa etmeye karar vermeden hemen önce **APIStar** sunucusunu buldum. Aradığım şeylerin neredeyse hepsine sahipti ve harika bir tasarımı vardı.
+
+Python tip belirteçleriyle parametreleri ve istekleri ilan eden bir framework’ün gördüğüm ilk örneklerindendi (NestJS ve Molten’dan önce). Aşağı yukarı Hug ile aynı zamanlarda buldum; ancak APIStar, OpenAPI standardını kullanıyordu.
+
+Farklı yerlerdeki aynı tip belirteçlerine dayanarak otomatik veri doğrulama, veri dönüşümü ve OpenAPI şeması üretimi vardı.
+
+Gövde şema tanımları Pydantic’tekiyle aynı Python tip belirteçlerini kullanmıyordu; biraz daha Marshmallow’a benziyordu. Bu yüzden editör desteği o kadar iyi olmazdı; yine de APIStar mevcut en iyi seçenekti.
+
+O dönem kıyaslamalarda en iyi performansa sahipti (sadece Starlette tarafından geçiliyordu).
+
+Başta otomatik API dökümantasyonu sunan bir web arayüzü yoktu ama Swagger UI ekleyebileceğimi biliyordum.
+
+Bağımlılık enjeksiyonu sistemi vardı. Diğer araçlarda olduğu gibi bileşenlerin önceden kaydedilmesini gerektiriyordu. Yine de harika bir özellikti.
+
+Güvenlik entegrasyonu olmadığından tam bir projede kullanamadım; bu yüzden Flask-apispec tabanlı full‑stack üreticilerle sahip olduğum özelliklerin tamamını ikame edemedim. Bu işlevi ekleyen bir pull request’i yapılacaklar listeme almıştım.
+
+Sonra projenin odağı değişti.
+
+Artık bir API web framework’ü değildi; geliştirici Starlette’e odaklanmak zorundaydı.
+
+Şimdi APIStar, bir web framework’ü değil, OpenAPI spesifikasyonlarını doğrulamak için araçlar takımından ibaret.
+
+/// info | Bilgi
+
+APIStar, aşağıdakilerin de yaratıcısı olan Tom Christie tarafından geliştirildi:
+
+* Django REST Framework
+* **FastAPI**’ın üzerine kurulu Starlette
+* Starlette ve **FastAPI** tarafından kullanılan Uvicorn
+
+///
+
+/// check | **FastAPI**'a ilham olan
+
+Var olmak.
+
+Aynı Python tipleriyle (hem veri doğrulama, dönüşüm ve dökümantasyon) birden çok şeyi ilan etmek ve aynı anda harika editör desteği sağlamak, bence dahiyane bir fikirdi.
+
+Uzun süre benzer bir framework arayıp birçok alternatifi denedikten sonra, APIStar mevcut en iyi seçenekti.
+
+Sonra APIStar bir sunucu olarak var olmaktan çıktı ve Starlette oluşturuldu; böyle bir sistem için daha iyi bir temel oldu. Bu, **FastAPI**’yi inşa etmek için son ilhamdı.
+
+Önceki bu araçlardan edinilen deneyimler üzerine özellikleri, tip sistemi ve diğer kısımları geliştirip artırırken, **FastAPI**’yi APIStar’ın “ruhani varisi” olarak görüyorum.
+
+///
+
+## **FastAPI** Tarafından Kullanılanlar { #used-by-fastapi }
+
+### [Pydantic](https://docs.pydantic.dev/) { #pydantic }
+
+Pydantic, Python tip belirteçlerine dayalı olarak veri doğrulama, dönüşüm ve dökümantasyon (JSON Schema kullanarak) tanımlamak için bir kütüphanedir.
+
+Bu onu aşırı sezgisel kılar.
+
+Marshmallow ile karşılaştırılabilir. Kıyaslamalarda Marshmallow’dan daha hızlıdır. Aynı Python tip belirteçlerine dayandığı için editör desteği harikadır.
+
+/// check | **FastAPI** bunu şurada kullanır
+
+Tüm veri doğrulama, veri dönüşümü ve JSON Schema tabanlı otomatik model dökümantasyonunu halletmekte.
+
+**FastAPI** daha sonra bu JSON Schema verisini alır ve (yaptığı diğer şeylerin yanı sıra) OpenAPI içine yerleştirir.
+
+///
+
+### [Starlette](https://www.starlette.dev/) { #starlette }
+
+Starlette, yüksek performanslı asyncio servisleri oluşturmak için ideal, hafif bir ASGI framework’ü/araç takımıdır.
+
+Çok basit ve sezgiseldir. Kolayca genişletilebilir ve modüler bileşenlere sahip olacak şekilde tasarlanmıştır.
+
+Şunlara sahiptir:
+
+* Cidden etkileyici performans.
+* WebSocket desteği.
+* Süreç içi arka plan görevleri.
+* Başlatma ve kapatma olayları.
+* HTTPX üzerinde geliştirilmiş test istemcisi.
+* CORS, GZip, Statik Dosyalar, Streaming cevaplar.
+* Oturum (Session) ve Cookie desteği.
+* %100 test kapsamı.
+* %100 tip anotasyonlu kod tabanı.
+* Az sayıda zorunlu bağımlılık.
+
+Starlette, şu anda test edilen en hızlı Python framework’üdür. Yalnızca bir framework değil, bir sunucu olan Uvicorn tarafından geçilir.
+
+Starlette, temel web mikroframework işlevselliğinin tamamını sağlar.
+
+Ancak otomatik veri doğrulama, dönüşüm veya dökümantasyon sağlamaz.
+
+**FastAPI**’nin bunun üzerine eklediği ana şeylerden biri, Pydantic kullanarak, bütünüyle Python tip belirteçlerine dayalı bu özelliklerdir. Buna ek olarak bağımlılık enjeksiyonu sistemi, güvenlik yardımcıları, OpenAPI şema üretimi vb. gelir.
+
+/// note | Teknik Detaylar
+
+ASGI, Django çekirdek ekip üyeleri tarafından geliştirilen yeni bir “standart”tır. Hâlâ resmi bir “Python standardı” (PEP) değildir, ancak bu süreç üzerindedirler.
+
+Buna rağmen, şimdiden birçok araç tarafından bir “standart” olarak kullanılmaktadır. Bu, birlikte çalışabilirliği büyük ölçüde artırır; örneğin Uvicorn’u başka bir ASGI sunucusuyla (Daphne veya Hypercorn gibi) değiştirebilir ya da `python-socketio` gibi ASGI uyumlu araçlar ekleyebilirsiniz.
+
+///
+
+/// check | **FastAPI** bunu şurada kullanır
+
+Tüm temel web kısımlarını ele almak; üzerine özellikler eklemek.
+
+`FastAPI` sınıfı, doğrudan `Starlette` sınıfından miras alır.
+
+Dolayısıyla Starlette ile yapabildiğiniz her şeyi, adeta “turbo şarjlı Starlette” olan **FastAPI** ile de doğrudan yapabilirsiniz.
+
+///
+
+### [Uvicorn](https://www.uvicorn.dev/) { #uvicorn }
+
+Uvicorn, uvloop ve httptools üzerinde inşa edilmiş, ışık hızında bir ASGI sunucusudur.
+
+Bir web framework’ü değil, bir sunucudur. Örneğin path’lere göre yönlendirme araçları sağlamaz; bunu Starlette (veya **FastAPI**) gibi bir framework üstte sağlar.
+
+Starlette ve **FastAPI** için önerilen sunucudur.
+
+/// check | **FastAPI** bunu şöyle önerir
+
+**FastAPI** uygulamalarını çalıştırmak için ana web sunucusu.
+
+Komut satırında `--workers` seçeneğini kullanarak asenkron çok süreçli (multi‑process) bir sunucu da elde edebilirsiniz.
+
+Daha fazla detay için [Dağıtım](deployment/index.md) bölümüne bakın.
+
+///
+
+## Kıyaslamalar ve Hız { #benchmarks-and-speed }
+
+Uvicorn, Starlette ve FastAPI arasındaki farkı anlamak ve karşılaştırmak için [Kıyaslamalar](benchmarks.md) bölümüne göz atın.
diff --git a/docs/tr/docs/async.md b/docs/tr/docs/async.md
new file mode 100644
index 0000000000000..5ac792fa43d59
--- /dev/null
+++ b/docs/tr/docs/async.md
@@ -0,0 +1,444 @@
+# Eşzamanlılık ve async / await { #concurrency-and-async-await }
+
+*path operasyon fonksiyonları* için `async def` sözdizimi hakkında detaylar ve asenkron kod, eşzamanlılık (concurrency) ve paralellik üzerine arka plan bilgisi.
+
+## Aceleniz mi var? { #in-a-hurry }
+
+TL;DR:
+
+Eğer `await` ile çağırmanız gerektiğini söyleyen üçüncü taraf kütüphaneler kullanıyorsanız, örneğin:
+
+```Python
+results = await some_library()
+```
+
+O zaman *path operasyon fonksiyonlarınızı* aşağıdaki gibi `async def` ile tanımlayın:
+
+```Python hl_lines="2"
+@app.get('/')
+async def read_results():
+ results = await some_library()
+ return results
+```
+
+/// note | Not
+
+`await` yalnızca `async def` ile oluşturulan fonksiyonların içinde kullanılabilir.
+
+///
+
+---
+
+Eğer bir veritabanı, bir API, dosya sistemi vb. ile iletişim kuran ve `await` desteği olmayan bir üçüncü taraf kütüphane kullanıyorsanız (bu şu anda çoğu veritabanı kütüphanesi için geçerlidir), o zaman *path operasyon fonksiyonlarınızı* normal olarak `def` ile tanımlayın:
+
+```Python hl_lines="2"
+@app.get('/')
+def results():
+ results = some_library()
+ return results
+```
+
+---
+
+Uygulamanız (bir şekilde) başka bir şeyle iletişim kurmak ve onun yanıtını beklemek zorunda değilse, içinde `await` kullanmanız gerekmese bile `async def` kullanın.
+
+---
+
+Emin değilseniz, normal `def` kullanın.
+
+---
+
+Not: *path operasyon fonksiyonlarınızda* `def` ve `async def`'i ihtiyacınız kadar karıştırabilirsiniz, her birini sizin için en iyi seçenekle tanımlayın. FastAPI onlar için doğru olanı yapacaktır.
+
+Yukarıdaki durumların herhangi birinde FastAPI yine de asenkron olarak çalışır ve son derece hızlıdır.
+
+Ancak yukarıdaki adımları izleyerek bazı performans optimizasyonları mümkün olur.
+
+## Teknik Detaylar { #technical-details }
+
+Python’un modern sürümleri, **`async` ve `await`** sözdizimiyle, **"coroutines"** denilen bir yapıyı kullanarak **"asenkron kod"** desteğine sahiptir.
+
+Aşağıdaki bölümlerde bu ifadeyi parça parça ele alalım:
+
+* **Asenkron Kod**
+* **`async` ve `await`**
+* **Coroutine'ler**
+
+## Asenkron Kod { #asynchronous-code }
+
+Asenkron kod, dilin 💬 bilgisayara / programa 🤖 kodun bir noktasında, bir yerde *başka bir şeyin* bitmesini beklemesi gerektiğini söylemesinin bir yoludur. Diyelim ki bu *başka şeye* "slow-file" 📝 diyoruz.
+
+Bu sırada bilgisayar, "slow-file" 📝 biterken gidip başka işler yapabilir.
+
+Sonra bilgisayar / program 🤖, ya tekrar beklediği için ya da o anda elindeki tüm işleri bitirdiğinde fırsat buldukça geri gelir. Ve beklediği görevlerden herhangi biri bittiyse, yapılması gerekenleri yapar.
+
+Ardından, 🤖 ilk biten görevi alır (örneğin bizim "slow-file" 📝) ve onunla yapması gerekenlere devam eder.
+
+Bu "başka bir şeyi beklemek" genelde işlemci ve RAM hızına kıyasla nispeten "yavaş" olan I/O işlemlerine atıfta bulunur, örneğin şunları beklemek gibi:
+
+* istemciden verinin ağ üzerinden gelmesi
+* programınızın gönderdiği verinin ağ üzerinden istemciye ulaşması
+* diskteki bir dosyanın içeriğinin sistem tarafından okunup programınıza verilmesi
+* programınızın sisteme verdiği içeriğin diske yazılması
+* uzak bir API işlemi
+* bir veritabanı işleminin bitmesi
+* bir veritabanı sorgusunun sonuç döndürmesi
+* vb.
+
+Çalışma süresi çoğunlukla I/O işlemlerini beklemekle geçtiğinden, bunlara "I/O bound" işlemler denir.
+
+"Bunun" asenkron" denmesinin sebebi, bilgisayarın / programın yavaş görevle "senkronize" olmak, görev tam bittiği anda orada olup görev sonucunu almak ve işe devam etmek için hiçbir şey yapmadan beklemek zorunda olmamasıdır.
+
+Bunun yerine "asenkron" bir sistem olarak, görev bittiğinde, bilgisayarın / programın o sırada yaptığı işi bitirmesi için biraz (birkaç mikrosaniye) sırada bekleyebilir ve sonra sonuçları almak üzere geri dönüp onlarla çalışmaya devam edebilir.
+
+"Senkron" (asenkronun tersi) için genelde "sıralı" terimi de kullanılır; çünkü bilgisayar / program, farklı bir göreve geçmeden önce tüm adımları sırayla izler, bu adımlar beklemeyi içerse bile.
+
+### Eşzamanlılık ve Burgerler { #concurrency-and-burgers }
+
+Yukarıda anlatılan **asenkron** kod fikrine bazen **"eşzamanlılık"** (concurrency) da denir. **"Paralellik"**ten (parallelism) farklıdır.
+
+**Eşzamanlılık** ve **paralellik**, "aynı anda az çok birden fazla şeyin olması" ile ilgilidir.
+
+Ama *eşzamanlılık* ve *paralellik* arasındaki ayrıntılar oldukça farklıdır.
+
+Farkı görmek için burgerlerle ilgili şu hikayeyi hayal edin:
+
+### Eşzamanlı Burgerler { #concurrent-burgers }
+
+Aşkınla fast food almaya gidiyorsun, kasiyer senden önceki insanların siparişlerini alırken sıraya giriyorsun. 😍
+
+
+
+Sonra sıra size geliyor, sen ve aşkın için 2 çok havalı burger sipariş ediyorsun. 🍔🍔
+
+
+
+Kasiyer, mutfaktaki aşçıya burgerlerini hazırlamaları gerektiğini söylüyor (o an önceki müşterilerin burgerlerini hazırlıyor olsalar bile).
+
+
+
+Ödeme yapıyorsun. 💸
+
+Kasiyer sana sıra numaranı veriyor.
+
+
+
+Beklerken aşkınla bir masa seçip oturuyorsunuz, uzun uzun sohbet ediyorsunuz (burgerler baya havalı ve hazırlanması biraz zaman alıyor).
+
+Masada aşkınla otururken, burgerleri beklerken, o zamanı aşkının ne kadar harika, tatlı ve zeki olduğuna hayran kalarak geçirebilirsin ✨😍✨.
+
+
+
+Bekler ve sohbet ederken, ara ara tezgâhtaki numaraya bakıp sıranın size gelip gelmediğini kontrol ediyorsun.
+
+Bir noktada, nihayet sıra size geliyor. Tezgâha gidiyor, burgerleri alıp masaya dönüyorsun.
+
+
+
+Aşkınla burgerleri yiyip güzel vakit geçiriyorsunuz. ✨
+
+
+
+/// info | Bilgi
+
+Harika çizimler: [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨
+
+///
+
+---
+
+Bu hikâyede bilgisayar / program 🤖 olduğunu hayal et.
+
+Sıradayken sadece boştasın 😴, sıranı bekliyorsun, çok "üretken" bir şey yapmıyorsun. Ama sorun yok, çünkü kasiyer sadece sipariş alıyor (hazırlamıyor), bu yüzden sıra hızlı ilerliyor.
+
+Sıra sana geldiğinde gerçekten "üretken" işler yapıyorsun: menüyü işliyorsun, ne istediğine karar veriyorsun, aşkının seçimini alıyorsun, ödüyorsun, doğru para ya da kartı verdiğini kontrol ediyorsun, doğru ücretlendirildiğini kontrol ediyorsun, sipariş kalemlerinin doğru olduğunu kontrol ediyorsun, vb.
+
+Ama sonra, burgerlerin hâlâ gelmemiş olsa da, kasiyerle olan işin "duraklatılıyor" ⏸, çünkü burgerlerin hazır olmasını 🕙 beklemen gerekiyor.
+
+Fakat tezgâhtan uzaklaşıp masada sıra numaranla oturduğun için, dikkatinizi 🔀 aşkına çevirebilir, onunla "çalışmaya" ⏯ 🤓 odaklanabilirsin. Yani yine çok "üretken" bir şey yapıyorsun, aşkınla flört etmek gibi 😍.
+
+Ardından kasiyer 💁, tezgâh ekranına numaranı koyarak "burgerleri bitirdim" diyor; ama numara seninki olduğunda çılgınca sıçramıyorsun. Sıra numaran sende, herkesin kendi numarası var; kimse burgerlerini çalamaz.
+
+Bu yüzden aşkının hikâyeyi bitirmesini (mevcut işi ⏯ / işlenen görevi 🤓 bitirmesini) bekliyor, nazikçe gülümsüyor ve burgerleri almaya gittiğini söylüyorsun ⏸.
+
+Sonra tezgâha 🔀 gidip artık bitmiş olan ilk göreve ⏯ dönüyor, burgerleri alıyor, teşekkür ediyor ve masaya getiriyorsun. Tezgâhla etkileşimin bu adımı / görevi böylece bitiyor ⏹. Bu da yeni bir görev olan "burgerleri yemek" 🔀 ⏯ görevini oluşturuyor, ama "burgerleri almak" görevi tamamlandı ⏹.
+
+### Paralel Burgerler { #parallel-burgers }
+
+Şimdi bunların "Eşzamanlı Burgerler" değil, "Paralel Burgerler" olduğunu hayal edelim.
+
+Aşkınla paralel fast food almaya gidiyorsun.
+
+Aynı anda aşçı da olan birden fazla (8 diyelim) kasiyerin, senden önceki insanların siparişlerini aldığı bir sırada bekliyorsun.
+
+Senden önceki herkes, tezgâhtan ayrılmadan önce burgerlerinin hazırlanmasını bekliyor; çünkü 8 kasiyerin her biri bir sonraki siparişe geçmeden önce burgeri hemen gidip hazırlıyor.
+
+
+
+Sonunda sıra size geliyor, sen ve aşkın için 2 çok havalı burger siparişi veriyorsun.
+
+Ödüyorsun 💸.
+
+
+
+Kasiyer mutfağa gidiyor.
+
+Tezgâhın önünde ayakta 🕙 bekliyorsun; sıra numarası olmadığından, burgerlerini senden önce kimsenin almaması için orada durman gerekiyor.
+
+
+
+Sen ve aşkın, kimsenin önünüze geçip burgerler gelince almaması için meşgul olduğunuzdan, aşkına dikkatini veremiyorsun. 😞
+
+Bu "senkron" bir iştir; kasiyer/aşçı 👨🍳 ile "senkronize"sin. 🕙 Beklemen ve kasiyer/aşçı 👨🍳 burgerleri bitirip sana verdiği anda tam orada olman gerekir; yoksa bir başkası alabilir.
+
+
+
+Sonra kasiyer/aşçı 👨🍳, uzun süre tezgâhın önünde 🕙 bekledikten sonra nihayet burgerlerinle geri geliyor.
+
+
+
+Burgerleri alıyor ve aşkınla masaya gidiyorsun.
+
+Sadece yiyorsunuz ve iş bitiyor. ⏹
+
+
+
+Vaktin çoğu tezgâhın önünde 🕙 beklemekle geçtiğinden, pek konuşma ya da flört olmadı. 😞
+
+/// info | Bilgi
+
+Harika çizimler: [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨
+
+///
+
+---
+
+Bu paralel burger senaryosunda, ikiniz (sen ve aşkın) iki işlemcili bir bilgisayar / programsınız 🤖; ikiniz de uzun süre tezgâhta "bekleme" işine 🕙 dikkat ⏯ ayırıyorsunuz.
+
+Fast food dükkânında 8 işlemci var (kasiyer/aşçılar). Eşzamanlı burger dükkânında yalnızca 2 kişi olabilir (bir kasiyer ve bir aşçı).
+
+Ama yine de nihai deneyim pek iyi değil. 😞
+
+---
+
+Bu, burgerler için paralel karşılık gelen hikâye olurdu. 🍔
+
+Daha "gerçek hayat" bir örnek için, bir banka hayal edin.
+
+Yakın zamana kadar, bankaların çoğunda birden çok gişe memuru 👨💼👨💼👨💼👨💼 ve uzun bir sıra 🕙🕙🕙🕙🕙🕙🕙🕙 vardı.
+
+Tüm gişe memurları bir müşteriyle tüm işi yapar, sonra sıradakiyle 👨💼⏯.
+
+Ve sıranı kaybetmemek için uzun süre 🕙 kuyrukta beklemen gerekir.
+
+Muhtemelen, bankada 🏦 işlerini hallederken aşkını 😍 yanında götürmek istemezsin.
+
+### Burger Sonucu { #burger-conclusion }
+
+"Fast food burgerleri ve aşkın" senaryosunda, çok fazla bekleme 🕙 olduğundan, eşzamanlı bir sistem ⏸🔀⏯ çok daha mantıklıdır.
+
+Bu, çoğu web uygulaması için de geçerlidir.
+
+Çok fazla kullanıcı vardır; ancak sunucunuz, iyi olmayan bağlantılarından gelen istekleri 🕙 bekler.
+
+Ve sonra yanıtların geri gelmesini yine 🕙 bekler.
+
+Bu "beklemeler" 🕙 mikrosaniyelerle ölçülür; ama hepsi toplandığında sonuçta oldukça fazla bekleme olur.
+
+Bu yüzden web API’leri için asenkron ⏸🔀⏯ kod kullanmak çok mantıklıdır.
+
+Bu tür asenkronluk, NodeJS’i popüler yapan şeydir (NodeJS paralel olmasa bile) ve Go dilinin gücüdür.
+
+Ve **FastAPI** ile elde ettiğiniz performans seviyesi de budur.
+
+Ayrıca, aynı anda hem paralellik hem de asenkronluk kullanabildiğiniz için, test edilen çoğu NodeJS framework’ünden daha yüksek ve C’ye daha yakın derlenen bir dil olan Go ile başa baş performans elde edersiniz [(hepsi Starlette sayesinde)](https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=query&l=zijmkf-1).
+
+### Eşzamanlılık paralellikten daha mı iyi? { #is-concurrency-better-than-parallelism }
+
+Hayır! Hikâyenin özü bu değil.
+
+Eşzamanlılık paralellikten farklıdır. Ve çok fazla bekleme içeren **belirli** senaryolarda daha iyidir. Bu nedenle, genellikle web uygulaması geliştirme için paralellikten çok daha iyidir. Ama her şey için değil.
+
+Bunu dengelemek için, şu kısa hikâyeyi hayal edin:
+
+> Büyük, kirli bir evi temizlemen gerekiyor.
+
+*Evet, tüm hikâye bu kadar*.
+
+---
+
+Hiçbir yerde 🕙 bekleme yok; sadece evin birden fazla yerinde yapılacak çok iş var.
+
+Hamburger örneğindeki gibi dönüşlerle ilerleyebilirsin, önce salon, sonra mutfak; ama hiçbir şey 🕙 beklemediğin için, sadece temizlik yaptığından, dönüşlerin hiçbir etkisi olmaz.
+
+Dönüşlerle ya da dönüşsüz (eşzamanlılık) bitirmek aynı zaman alır ve aynı miktarda iş yapmış olursun.
+
+Ama bu durumda, 8 eski kasiyer/aşçı—yeni temizlikçiyi getirip her birine (artı sana) evin bir bölümünü versen, fazladan yardımla tüm işleri **paralel** yaparak çok daha çabuk bitirebilirdin.
+
+Bu senaryoda, her bir temizlikçi (sen dâhil) birer işlemci olur ve kendi iş payını yapar.
+
+Ve yürütme süresinin çoğu gerçek işten (bekleme yerine) oluştuğu ve bilgisayardaki işi bir CPU yaptığı için, bu sorunlara "CPU bound" denir.
+
+---
+
+CPU’ya bağlı işlemlerin yaygın örnekleri, karmaşık matematiksel işlem gerektiren iş yükleridir.
+
+Örneğin:
+
+* **Ses** veya **görüntü işleme**.
+* **Bilgisayar görüsü**: bir görüntü milyonlarca pikselden oluşur, her pikselin 3 değeri / rengi vardır; işleme genellikle bu pikseller üzerinde aynı anda bir şeyler hesaplamayı gerektirir.
+* **Makine Öğrenimi**: genellikle çok sayıda "matris" ve "vektör" çarpımı gerekir. Sayılar içeren devasa bir elektronik tabloyu ve hepsini aynı anda çarpmayı düşünün.
+* **Derin Öğrenme**: Makine Öğreniminin bir alt alanıdır, dolayısıyla aynısı geçerlidir. Sadece çarpılacak tek bir sayı tablosu değil, kocaman bir sayı kümesi vardır ve çoğu durumda bu modelleri kurmak ve/veya kullanmak için özel işlemciler kullanırsınız.
+
+### Eşzamanlılık + Paralellik: Web + Makine Öğrenimi { #concurrency-parallelism-web-machine-learning }
+
+**FastAPI** ile web geliştirmede çok yaygın olan eşzamanlılıktan (NodeJS’in başlıca cazibesiyle aynı) yararlanabilirsiniz.
+
+Ama ayrıca **CPU’ya bağlı** iş yükleri (Makine Öğrenimi sistemlerindeki gibi) için paralellik ve çoklu işlemden (paralel çalışan birden çok işlem) de yararlanabilirsiniz.
+
+Buna ek olarak Python’un **Veri Bilimi**, Makine Öğrenimi ve özellikle Derin Öğrenme için ana dil olması, FastAPI’yi Veri Bilimi / Makine Öğrenimi web API’leri ve uygulamaları için çok iyi bir seçenek yapar.
+
+Production’da bu paralelliği nasıl sağlayacağınızı görmek için [Deployment](deployment/index.md) bölümüne bakın.
+
+## `async` ve `await` { #async-and-await }
+
+Python’un modern sürümleri, asenkron kodu tanımlamak için oldukça sezgisel bir yol sunar. Bu sayede kod normal "sıralı" kod gibi görünür ve doğru anlarda sizin yerinize "beklemeyi" yapar.
+
+Sonuçları vermeden önce bekleme gerektiren ve bu yeni Python özelliklerini destekleyen bir işlem olduğunda, şöyle kodlayabilirsiniz:
+
+```Python
+burgers = await get_burgers(2)
+```
+
+Buradaki kilit nokta `await`. Python’a, sonuçları `burgers` değişkenine koymadan önce `get_burgers(2)` çalışmasının bitmesini 🕙 beklemesi ⏸ gerektiğini söyler. Böylece Python, bu arada başka bir şey 🔀 ⏯ yapabileceğini bilir (ör. başka bir request almak gibi).
+
+`await`’in çalışabilmesi için, bu asenkronluğu destekleyen bir fonksiyonun içinde olması gerekir. Bunu yapmak için fonksiyonu `async def` ile tanımlayın:
+
+```Python hl_lines="1"
+async def get_burgers(number: int):
+ # Burgerleri yaratmak için bazı asenkron işler yap
+ return burgers
+```
+
+...`def` yerine:
+
+```Python hl_lines="2"
+# Bu asenkron değildir
+def get_sequential_burgers(number: int):
+ # Burgerleri yaratmak için bazı sıralı işler yap
+ return burgers
+```
+
+`async def` ile Python, bu fonksiyonun içinde `await` ifadelerinin olabileceğini bilir ve bu fonksiyonun yürütülmesini "duraklatıp" ⏸ başka bir şey yapabileceğini 🔀, sonra geri dönebileceğini anlar.
+
+`async def` fonksiyonunu çağırmak istediğinizde, onu "await" etmeniz gerekir. Yani şu çalışmaz:
+
+```Python
+# Bu çalışmaz, çünkü get_burgers şöyle tanımlandı: async def
+burgers = get_burgers(2)
+```
+
+---
+
+Dolayısıyla, `await` ile çağrılabileceğini söyleyen bir kütüphane kullanıyorsanız, onu kullanan *path operasyon fonksiyonunu* `async def` ile oluşturmanız gerekir, örneğin:
+
+```Python hl_lines="2-3"
+@app.get('/burgers')
+async def read_burgers():
+ burgers = await get_burgers(2)
+ return burgers
+```
+
+### Daha teknik detaylar { #more-technical-details }
+
+`await`’in yalnızca `async def` ile tanımlanan fonksiyonların içinde kullanılabildiğini fark etmiş olabilirsiniz.
+
+Aynı zamanda, `async def` ile tanımlanan fonksiyonların da "await" edilmesi gerekir. Yani `async def` ile tanımlanan fonksiyonlar yalnızca `async def` ile tanımlanan fonksiyonların içinde çağrılabilir.
+
+Peki, tavuk-yumurta meselesi: ilk `async` fonksiyon nasıl çağrılır?
+
+**FastAPI** ile çalışıyorsanız bunu dert etmenize gerek yok; çünkü o "ilk" fonksiyon sizin *path operasyon fonksiyonunuz* olacaktır ve FastAPI doğru olanı yapmasını bilir.
+
+Ama FastAPI olmadan da `async` / `await` kullanmak isterseniz, bunu da yapabilirsiniz.
+
+### Kendi async kodunuzu yazın { #write-your-own-async-code }
+
+Starlette (ve **FastAPI**) [AnyIO](https://anyio.readthedocs.io/en/stable/) üzerine kuruludur; bu sayede Python standart kütüphanesindeki [asyncio](https://docs.python.org/3/library/asyncio-task.html) ve [Trio](https://trio.readthedocs.io/en/stable/) ile uyumludur.
+
+Özellikle, kendi kodunuzda daha gelişmiş desenler gerektiren ileri seviye eşzamanlılık kullanım senaryoları için doğrudan [AnyIO](https://anyio.readthedocs.io/en/stable/) kullanabilirsiniz.
+
+Hatta FastAPI kullanmıyor olsanız bile, yüksek uyumluluk ve avantajları (ör. *structured concurrency*) için [AnyIO](https://anyio.readthedocs.io/en/stable/) ile kendi async uygulamalarınızı yazabilirsiniz.
+
+AnyIO’nun üzerine, tür açıklamalarını biraz iyileştirmek ve daha iyi **otomatik tamamlama**, **satır içi hatalar** vb. elde etmek için ince bir katman olarak başka bir kütüphane daha oluşturdum. Ayrıca **kendi async kodunuzu** anlamanıza ve yazmanıza yardımcı olacak dostça bir giriş ve eğitim içerir: [Asyncer](https://asyncer.tiangolo.com/). Özellikle **async kodu normal** (bloklayan/senkron) **kodla birleştirmeniz** gerektiğinde faydalı olacaktır.
+
+### Asenkron kodun diğer biçimleri { #other-forms-of-asynchronous-code }
+
+`async` ve `await` kullanma tarzı, dilde nispeten yenidir.
+
+Ama asenkron kodla çalışmayı çok daha kolaylaştırır.
+
+Aynı (ya da neredeyse aynı) sözdizimi yakın zamanda modern JavaScript sürümlerine (Tarayıcı ve NodeJS) de eklendi.
+
+Bundan önce, asenkron kodu ele almak oldukça daha karmaşık ve zordu.
+
+Python’un önceki sürümlerinde thread’ler veya [Gevent](https://www.gevent.org/) kullanabilirdiniz. Ama kodu anlamak, hata ayıklamak ve üzerine düşünmek çok daha zordu.
+
+NodeJS / Tarayıcı JavaScript’in önceki sürümlerinde "callback" kullanırdınız. Bu da "callback cehennemi"ne yol açardı.
+
+## Coroutine'ler { #coroutines }
+
+**Coroutine**, bir `async def` fonksiyonunun döndürdüğü şeye verilen süslü isimdir. Python bunun bir fonksiyona benzer bir şey olduğunu, bir noktada başlayıp biteceğini bilir; ama içinde bir `await` olduğunda dahili olarak duraklatılabileceğini ⏸ de bilir.
+
+`async` ve `await` ile asenkron kod kullanmanın bu işlevselliği çoğu zaman "coroutine" kullanmak olarak özetlenir. Go’nun ana kilit özelliği olan "Goroutines" ile karşılaştırılabilir.
+
+## Sonuç { #conclusion }
+
+Yukarıdaki cümleyi tekrar görelim:
+
+> Python’un modern sürümleri, **`async` ve `await`** sözdizimiyle, **"coroutines"** denilen bir yapıyı kullanarak **"asenkron kod"** desteğine sahiptir.
+
+Artık daha anlamlı gelmeli. ✨
+
+Bunların hepsi, FastAPI’ye (Starlette aracılığıyla) güç verir ve böylesine etkileyici bir performansa sahip olmasını sağlar.
+
+## Çok Teknik Detaylar { #very-technical-details }
+
+/// warning | Uyarı
+
+Büyük ihtimalle burayı atlayabilirsiniz.
+
+Bunlar, **FastAPI**’nin altında nasıl çalıştığına dair oldukça teknik ayrıntılardır.
+
+Coroutine’ler, thread’ler, blocking vb. hakkında teknik bilginiz varsa ve FastAPI’nin `async def` ile normal `def` arasındaki farkı nasıl ele aldığını merak ediyorsanız, devam edin.
+
+///
+
+### Path Operasyon Fonksiyonları { #path-operation-functions }
+
+Bir *path operasyon fonksiyonunu* `async def` yerine normal `def` ile tanımladığınızda, (sunucuyu bloklayacağından) doğrudan çağrılmak yerine, harici bir thread pool’da çalıştırılır ve ardından beklenir.
+
+Yukarıda açıklanan şekilde çalışmayan başka bir async framework’ten geliyorsanız ve ufak bir performans kazancı (yaklaşık 100 nanosaniye) için yalnızca hesaplama yapan basit *path operasyon fonksiyonlarını* düz `def` ile tanımlamaya alışkınsanız, **FastAPI**’de etkinin tam tersi olacağını unutmayın. Bu durumlarda, *path operasyon fonksiyonlarınız* bloklayan I/O yapan kod kullanmadıkça `async def` kullanmak daha iyidir.
+
+Yine de her iki durumda da, **FastAPI**’nin önceki framework’ünüzden [hala daha hızlı](index.md#performance) (ya da en azından karşılaştırılabilir) olması muhtemeldir.
+
+### Bağımlılıklar { #dependencies }
+
+Aynısı [bağımlılıklar](tutorial/dependencies/index.md) için de geçerlidir. Bir bağımlılık `async def` yerine standart bir `def` fonksiyonuysa, harici thread pool’da çalıştırılır.
+
+### Alt-bağımlılıklar { #sub-dependencies }
+
+Birbirini gerektiren birden çok bağımlılık ve [alt-bağımlılık](tutorial/dependencies/sub-dependencies.md) olabilir (fonksiyon tanımlarının parametreleri olarak). Bazıları `async def` ile, bazıları normal `def` ile oluşturulmuş olabilir. Yine de çalışır ve normal `def` ile oluşturulanlar "await" edilmek yerine harici bir thread’de (thread pool’dan) çağrılır.
+
+### Diğer yardımcı fonksiyonlar { #other-utility-functions }
+
+Doğrudan çağırdığınız diğer yardımcı fonksiyonları normal `def` veya `async def` ile tanımlayabilirsiniz ve FastAPI onları çağırma biçiminizi etkilemez.
+
+Bu, FastAPI’nin sizin için çağırdığı fonksiyonların tersidir: *path operasyon fonksiyonları* ve bağımlılıklar.
+
+Yardımcı fonksiyonunuz `def` ile tanımlı normal bir fonksiyonsa, bir thread pool’da değil doğrudan (kodunuzda yazdığınız gibi) çağrılır; fonksiyon `async def` ile tanımlıysa kodunuzda çağırırken onu `await` etmelisiniz.
+
+---
+
+Yine, bunlar muhtemelen özellikle aradığınızda işinize yarayacak çok teknik ayrıntılardır.
+
+Aksi hâlde, yukarıdaki bölümdeki yönergeler yeterlidir: Aceleniz mi var?.
diff --git a/docs/tr/docs/benchmarks.md b/docs/tr/docs/benchmarks.md
index 1ce3c758f1e6a..61a561df8dde6 100644
--- a/docs/tr/docs/benchmarks.md
+++ b/docs/tr/docs/benchmarks.md
@@ -1,34 +1,34 @@
-# Kıyaslamalar
+# Kıyaslamalar { #benchmarks }
-Bağımsız TechEmpower kıyaslamaları gösteriyor ki Uvicorn'la beraber çalışan **FastAPI** uygulamaları Python'un en hızlı frameworklerinden birisi , sadece Starlette ve Uvicorn'dan daha düşük sıralamada (FastAPI bu frameworklerin üzerine kurulu). (*)
+Bağımsız TechEmpower kıyaslamaları, Uvicorn altında çalışan **FastAPI** uygulamalarının [mevcut en hızlı Python frameworklerinden biri](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7) olduğunu, yalnızca Starlette ve Uvicorn'un kendilerinin altında yer aldığını gösteriyor (FastAPI bunları dahili olarak kullanır).
Fakat kıyaslamaları ve karşılaştırmaları incelerken şunları aklınızda bulundurmalısınız.
-## Kıyaslamalar ve hız
+## Kıyaslamalar ve Hız { #benchmarks-and-speed }
-Kıyaslamaları incelediğinizde, farklı özelliklere sahip birçok araçların eşdeğer olarak karşılaştırıldığını görmek yaygındır.
+Kıyaslamalara baktığınızda, farklı türlerdeki birkaç aracın eşdeğermiş gibi karşılaştırıldığını görmek yaygındır.
-Özellikle, Uvicorn, Starlette ve FastAPI'ın birlikte karşılaştırıldığını görmek için (diğer birçok araç arasında).
+Özellikle, (diğer birçok araç arasında) Uvicorn, Starlette ve FastAPI'ın birlikte karşılaştırıldığını görebilirsiniz.
-Araç tarafından çözülen sorun ne kadar basitse, o kadar iyi performans alacaktır. Ve kıyaslamaların çoğu, araç tarafından sağlanan ek özellikleri test etmez.
+Aracın çözdüğü problem ne kadar basitse, elde edeceği performans o kadar iyi olur. Ayrıca kıyaslamaların çoğu, aracın sağladığı ek özellikleri test etmez.
Hiyerarşi şöyledir:
* **Uvicorn**: bir ASGI sunucusu
- * **Starlette**: (Uvicorn'u kullanır) bir web microframeworkü
- * **FastAPI**: (Starlette'i kullanır) data validation vb. ile API'lar oluşturmak için çeşitli ek özelliklere sahip bir API frameworkü
+ * **Starlette**: (Uvicorn'u kullanır) bir web mikroframework'ü
+ * **FastAPI**: (Starlette'i kullanır) veri doğrulama vb. ile API'lar oluşturmak için çeşitli ek özelliklere sahip bir API mikroframework'ü
* **Uvicorn**:
- * Sunucunun kendisi dışında ekstra bir kod içermediği için en iyi performansa sahip olacaktır
- * Direkt olarak Uvicorn'da bir uygulama yazmazsınız. Bu, en azından Starlette tarafından sağlanan tüm kodu (veya **FastAPI**) az çok içermesi gerektiği anlamına gelir. Ve eğer bunu yaptıysanız, son uygulamanız bir framework kullanmak ve uygulama kodlarını ve bugları en aza indirmekle aynı ek yüke sahip olacaktır.
- * Eğer Uvicorn'u karşılaştırıyorsanız, Daphne, Hypercorn, uWSGI, vb. uygulama sunucuları ile karşılaştırın.
+ * Sunucunun kendisi dışında çok fazla ekstra kod içermediği için en iyi performansa sahip olacaktır.
+ * Uvicorn ile doğrudan bir uygulama yazmazsınız. Bu, kodunuzun en azından Starlette'in (veya **FastAPI**'nin) sağladığı kodun aşağı yukarı tamamını içermesi gerektiği anlamına gelir. Bunu yaparsanız, nihai uygulamanız; bir framework kullanmış olmanın ve uygulama kodunu ve bug'ları en aza indirmenin getirdiği ek yükle aynı ek yüke sahip olur.
+ * Uvicorn'u karşılaştırıyorsanız, Daphne, Hypercorn, uWSGI vb. application server'larla karşılaştırın.
* **Starlette**:
- * Uvicorn'dan sonraki en iyi performansa sahip olacak. Aslında, Starlette çalışmak için Uvicorn'u kullanıyor. Dolayısıyla, muhtemelen daha fazla kod çalıştırmak zorunda kaldığında Uvicorn'dan sadece "daha yavaş" olabilir.
- * Ancak routing based on paths ile vb. basit web uygulamaları oluşturmak için araçlar sağlar.
- * Eğer Starlette'i karşılaştırıyorsanız, Sanic, Flask, Django, vb. frameworkler (veya microframeworkler) ile karşılaştırın.
+ * Uvicorn'dan sonra en iyi performansa sahip olacaktır. Aslında Starlette çalışmak için Uvicorn'u kullanır. Bu yüzden muhtemelen yalnızca daha fazla kod çalıştırmak zorunda kaldığı için Uvicorn'dan "daha yavaş" olabilir.
+ * Ancak path tabanlı routing vb. ile basit web uygulamaları oluşturmanız için araçlar sağlar.
+ * Starlette'i karşılaştırıyorsanız, Sanic, Flask, Django vb. web framework'lerle (veya mikroframework'lerle) karşılaştırın.
* **FastAPI**:
- * Starlette'in Uvicorn'u kullandığı ve ondan daha hızlı olamayacağı gibi, **FastAPI** da Starlette'i kullanır, bu yüzden ondan daha hızlı olamaz.
- * FastAPI, Starlette'e ek olarak daha fazla özellik sunar. Data validation ve serialization gibi API'lar oluştururken neredeyse ve her zaman ihtiyaç duyduğunuz özellikler. Ve bunu kullanarak, ücretsiz olarak otomatik dokümantasyon elde edersiniz (otomatik dokümantasyon çalışan uygulamalara ek yük getirmez, başlangıçta oluşturulur).
- * FastAPI'ı kullanmadıysanız ve Starlette'i doğrudan kullandıysanız (veya başka bir araç, Sanic, Flask, Responder, vb.) tüm data validation'ı ve serialization'ı kendiniz sağlamanız gerekir. Dolayısıyla, son uygulamanız FastAPI kullanılarak oluşturulmuş gibi hâlâ aynı ek yüke sahip olacaktır. Çoğu durumda, uygulamalarda yazılan kodun büyük çoğunluğunu data validation ve serialization oluşturur.
- * Dolayısıyla, FastAPI'ı kullanarak geliştirme süresinden, buglardan, kod satırlarından tasarruf edersiniz ve muhtemelen kullanmasaydınız aynı performansı (veya daha iyisini) elde edersiniz. (hepsini kodunuza uygulamak zorunda kalacağınız gibi)
- * Eğer FastAPI'ı karşılaştırıyorsanız, Flask-apispec, NestJS, Molten, vb. gibi data validation, serialization ve dokümantasyon sağlayan bir web uygulaması frameworkü ile (veya araç setiyle) karşılaştırın. Entegre otomatik data validation, serialization ve dokümantasyon içeren frameworkler.
+ * Starlette'in Uvicorn'u kullanıp ondan daha hızlı olamaması gibi, **FastAPI** da Starlette'i kullanır; dolayısıyla ondan daha hızlı olamaz.
+ * FastAPI, Starlette'in üzerine daha fazla özellik sağlar. API'lar oluştururken neredeyse her zaman ihtiyaç duyduğunuz veri doğrulama ve serialization gibi özellikler. Ayrıca bunu kullanarak ücretsiz olarak otomatik dokümantasyon elde edersiniz (otomatik dokümantasyon, çalışan uygulamalara ek yük bile getirmez; startup'ta üretilir).
+ * FastAPI'yi kullanmayıp Starlette'i doğrudan kullansaydınız (veya Sanic, Flask, Responder vb. başka bir aracı), tüm veri doğrulama ve serialization işlemlerini kendiniz uygulamak zorunda kalırdınız. Dolayısıyla nihai uygulamanız, FastAPI kullanılarak inşa edilmiş olsaydı sahip olacağı ek yükle hâlâ aynı ek yüke sahip olurdu. Ve çoğu durumda, uygulamalarda yazılan en büyük kod miktarı veri doğrulama ve serialization kısmıdır.
+ * Bu nedenle FastAPI kullanarak geliştirme süresinden, bug'lardan, kod satırlarından tasarruf edersiniz; ayrıca muhtemelen, onu kullanmasaydınız (tüm bunları kodunuzda kendiniz uygulamak zorunda kalacağınız için) elde edeceğiniz performansın aynısını (veya daha iyisini) elde edersiniz.
+ * FastAPI'yi karşılaştırıyorsanız, Flask-apispec, NestJS, Molten vb. veri doğrulama, serialization ve dokümantasyon sağlayan bir web uygulaması framework'ü (veya araç seti) ile karşılaştırın. Entegre otomatik veri doğrulama, serialization ve dokümantasyona sahip framework'ler.
diff --git a/docs/tr/docs/deployment/cloud.md b/docs/tr/docs/deployment/cloud.md
new file mode 100644
index 0000000000000..b263ecc578a1a
--- /dev/null
+++ b/docs/tr/docs/deployment/cloud.md
@@ -0,0 +1,24 @@
+# Bulut Sağlayıcılar Üzerinde FastAPI Yayınlama { #deploy-fastapi-on-cloud-providers }
+
+FastAPI uygulamanızı yayınlamak için neredeyse **herhangi bir bulut sağlayıcıyı** kullanabilirsiniz.
+
+Çoğu durumda, ana bulut sağlayıcıların FastAPI'yi onlarla birlikte yayınlamak için kılavuzları vardır.
+
+## FastAPI Cloud { #fastapi-cloud }
+
+**[FastAPI Cloud](https://fastapicloud.com)**, **FastAPI**'nin arkasındaki aynı yazar ve ekip tarafından geliştirilmiştir.
+
+Bir API'yi minimum çabayla **oluşturma**, **yayınlama** ve **erişme** sürecini kolaylaştırır.
+
+FastAPI ile uygulama geliştirirken elde edilen aynı **geliştirici deneyimini**, onları buluta **yayınlamaya** da taşır. 🎉
+
+FastAPI Cloud, *FastAPI and friends* açık kaynak projelerinin birincil sponsoru ve finansman sağlayıcısıdır. ✨
+
+## Bulut Sağlayıcılar - Sponsorlar { #cloud-providers-sponsors }
+
+Diğer bazı bulut sağlayıcılar da ✨ [**FastAPI'ye sponsor olur**](../help-fastapi.md#sponsor-the-author) ✨. 🙇
+
+Kılavuzlarını takip etmek ve servislerini denemek için onları da değerlendirmek isteyebilirsiniz:
+
+* [Render](https://docs.render.com/deploy-fastapi?utm_source=deploydoc&utm_medium=referral&utm_campaign=fastapi)
+* [Railway](https://docs.railway.com/guides/fastapi?utm_medium=integration&utm_source=docs&utm_campaign=fastapi)
diff --git a/docs/tr/docs/deployment/concepts.md b/docs/tr/docs/deployment/concepts.md
new file mode 100644
index 0000000000000..211e2ab51bb72
--- /dev/null
+++ b/docs/tr/docs/deployment/concepts.md
@@ -0,0 +1,321 @@
+# Deployment Kavramları { #deployments-concepts }
+
+Bir **FastAPI** uygulamasını (hatta genel olarak herhangi bir web API'yi) deploy ederken, muhtemelen önemseyeceğiniz bazı kavramlar vardır. Bu kavramları kullanarak, **uygulamanızı deploy etmek** için **en uygun** yöntemi bulabilirsiniz.
+
+Önemli kavramlardan bazıları şunlardır:
+
+* Güvenlik - HTTPS
+* Startup'ta çalıştırma
+* Yeniden başlatmalar
+* Replikasyon (çalışan process sayısı)
+* Bellek
+* Başlatmadan önceki adımlar
+
+Bunların **deployment**'ları nasıl etkilediğine bakalım.
+
+Nihai hedef, **API client**'larınıza **güvenli** bir şekilde hizmet verebilmek, **kesintileri** önlemek ve **hesaplama kaynaklarını** (ör. uzak server'lar/sanal makineler) olabildiğince verimli kullanmaktır. 🚀
+
+Burada bu **kavramlar** hakkında biraz daha bilgi vereceğim. Böylece, çok farklı ortamlarda—hatta bugün var olmayan **gelecekteki** ortamlarda bile—API'nizi nasıl deploy edeceğinize karar verirken ihtiyaç duyacağınız **sezgiyi** kazanmış olursunuz.
+
+Bu kavramları dikkate alarak, **kendi API**'leriniz için en iyi deployment yaklaşımını **değerlendirebilir ve tasarlayabilirsiniz**.
+
+Sonraki bölümlerde, FastAPI uygulamalarını deploy etmek için daha **somut tarifler** (recipes) paylaşacağım.
+
+Ama şimdilik, bu önemli **kavramsal fikirleri** inceleyelim. Bu kavramlar diğer tüm web API türleri için de geçerlidir. 💡
+
+## Güvenlik - HTTPS { #security-https }
+
+[HTTPS hakkındaki önceki bölümde](https.md) HTTPS'in API'niz için nasıl şifreleme sağladığını öğrenmiştik.
+
+Ayrıca HTTPS'in genellikle uygulama server'ınızın **dışında** yer alan bir bileşen tarafından sağlandığını, yani bir **TLS Termination Proxy** ile yapıldığını da görmüştük.
+
+Ve **HTTPS sertifikalarını yenilemekten** sorumlu bir şey olmalıdır; bu aynı bileşen olabileceği gibi farklı bir bileşen de olabilir.
+
+### HTTPS için Örnek Araçlar { #example-tools-for-https }
+
+TLS Termination Proxy olarak kullanabileceğiniz bazı araçlar:
+
+* Traefik
+ * Sertifika yenilemelerini otomatik yönetir ✨
+* Caddy
+ * Sertifika yenilemelerini otomatik yönetir ✨
+* Nginx
+ * Sertifika yenilemeleri için Certbot gibi harici bir bileşenle
+* HAProxy
+ * Sertifika yenilemeleri için Certbot gibi harici bir bileşenle
+* Nginx gibi bir Ingress Controller ile Kubernetes
+ * Sertifika yenilemeleri için cert-manager gibi harici bir bileşenle
+* Bir cloud provider tarafından servislerinin parçası olarak içeride yönetilmesi (aşağıyı okuyun 👇)
+
+Bir diğer seçenek de, HTTPS kurulumunu da dahil olmak üzere işin daha büyük kısmını yapan bir **cloud service** kullanmaktır. Bunun bazı kısıtları olabilir veya daha pahalı olabilir vb. Ancak bu durumda TLS Termination Proxy'yi kendiniz kurmak zorunda kalmazsınız.
+
+Sonraki bölümlerde bazı somut örnekler göstereceğim.
+
+---
+
+Sonraki kavramlar, gerçek API'nizi çalıştıran programla (ör. Uvicorn) ilgilidir.
+
+## Program ve Process { #program-and-process }
+
+Çalışan "**process**" hakkında çok konuşacağız. Bu yüzden ne anlama geldiğini ve "**program**" kelimesinden farkının ne olduğunu netleştirmek faydalı.
+
+### Program Nedir { #what-is-a-program }
+
+**Program** kelimesi günlük kullanımda birçok şeyi anlatmak için kullanılır:
+
+* Yazdığınız **code**, yani **Python dosyaları**.
+* İşletim sistemi tarafından **çalıştırılabilen** **dosya**, örn: `python`, `python.exe` veya `uvicorn`.
+* İşletim sistemi üzerinde **çalışır durumdayken** CPU kullanan ve bellekte veri tutan belirli bir program. Buna **process** de denir.
+
+### Process Nedir { #what-is-a-process }
+
+**Process** kelimesi genellikle daha spesifik kullanılır; yalnızca işletim sistemi üzerinde çalışan şeye (yukarıdaki son madde gibi) işaret eder:
+
+* İşletim sistemi üzerinde **çalışır durumda** olan belirli bir program.
+ * Bu; dosyayı ya da code'u değil, işletim sistemi tarafından **çalıştırılan** ve yönetilen şeyi ifade eder.
+* Herhangi bir program, herhangi bir code, **yalnızca çalıştırılırken** bir şey yapabilir. Yani bir **process çalışıyorken**.
+* Process siz tarafından veya işletim sistemi tarafından **sonlandırılabilir** (ya da "killed" edilebilir). O anda çalışması/çalıştırılması durur ve artık **hiçbir şey yapamaz**.
+* Bilgisayarınızda çalışan her uygulamanın arkasında bir process vardır; çalışan her program, her pencere vb. Bilgisayar açıkken normalde **aynı anda** birçok process çalışır.
+* Aynı anda **aynı programın birden fazla process**'i çalışabilir.
+
+İşletim sisteminizdeki "task manager" veya "system monitor" (ya da benzeri araçlar) ile bu process'lerin birçoğunu çalışır halde görebilirsiniz.
+
+Örneğin muhtemelen aynı browser programını (Firefox, Chrome, Edge vb.) çalıştıran birden fazla process göreceksiniz. Genelde her tab için bir process, üstüne bazı ek process'ler çalıştırırlar.
+
+
+
+---
+
+Artık **process** ve **program** arasındaki farkı bildiğimize göre, deployment konusuna devam edelim.
+
+## Startup'ta Çalıştırma { #running-on-startup }
+
+Çoğu durumda bir web API oluşturduğunuzda, client'larınızın her zaman erişebilmesi için API'nizin kesintisiz şekilde **sürekli çalışıyor** olmasını istersiniz. Elbette sadece belirli durumlarda çalışmasını istemenizin özel bir sebebi olabilir; ancak çoğunlukla onu sürekli açık ve **kullanılabilir** halde tutarsınız.
+
+### Uzak Bir Server'da { #in-a-remote-server }
+
+Uzak bir server (cloud server, sanal makine vb.) kurduğunuzda, yapabileceğiniz en basit şey; local geliştirme sırasında yaptığınız gibi, manuel olarak `fastapi run` (Uvicorn'u kullanır) veya benzeri bir komutla çalıştırmaktır.
+
+Bu yöntem çalışır ve **geliştirme sırasında** faydalıdır.
+
+Ancak server'a olan bağlantınız koparsa, **çalışan process** muhtemelen ölür.
+
+Ve server yeniden başlatılırsa (örneğin update'lerden sonra ya da cloud provider'ın migration'larından sonra) bunu muhtemelen **fark etmezsiniz**. Dolayısıyla process'i manuel yeniden başlatmanız gerektiğini de bilmezsiniz. Sonuçta API'niz ölü kalır. 😱
+
+### Startup'ta Otomatik Çalıştırma { #run-automatically-on-startup }
+
+Genellikle server programının (ör. Uvicorn) server açılışında otomatik başlamasını ve herhangi bir **insan müdahalesi** gerektirmeden API'nizi çalıştıran bir process'in sürekli ayakta olmasını istersiniz (ör. FastAPI uygulamanızı çalıştıran Uvicorn).
+
+### Ayrı Bir Program { #separate-program }
+
+Bunu sağlamak için genellikle startup'ta uygulamanızın çalıştığından emin olacak **ayrı bir program** kullanırsınız. Pek çok durumda bu program, örneğin bir veritabanı gibi diğer bileşenlerin/uygulamaların da çalıştığından emin olur.
+
+### Startup'ta Çalıştırmak için Örnek Araçlar { #example-tools-to-run-at-startup }
+
+Bu işi yapabilen araçlara örnekler:
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Docker in Swarm Mode
+* Systemd
+* Supervisor
+* Bir cloud provider tarafından servislerinin parçası olarak içeride yönetilmesi
+* Diğerleri...
+
+Sonraki bölümlerde daha somut örnekler vereceğim.
+
+## Yeniden Başlatmalar { #restarts }
+
+Uygulamanızın startup'ta çalıştığından emin olmaya benzer şekilde, hatalardan sonra **yeniden başlatıldığından** da emin olmak istersiniz.
+
+### Hata Yaparız { #we-make-mistakes }
+
+Biz insanlar sürekli **hata** yaparız. Yazılımın neredeyse *her zaman* farklı yerlerinde gizli **bug**'lar vardır. 🐛
+
+Ve biz geliştiriciler bu bug'ları buldukça ve yeni özellikler ekledikçe code'u iyileştiririz (muhtemelen yeni bug'lar da ekleyerek 😅).
+
+### Küçük Hatalar Otomatik Yönetilir { #small-errors-automatically-handled }
+
+FastAPI ile web API geliştirirken, code'umuzda bir hata olursa FastAPI genellikle bunu hatayı tetikleyen tek request ile sınırlar. 🛡
+
+Client o request için **500 Internal Server Error** alır; ancak uygulama tamamen çöküp durmak yerine sonraki request'ler için çalışmaya devam eder.
+
+### Daha Büyük Hatalar - Çökmeler { #bigger-errors-crashes }
+
+Yine de bazı durumlarda, yazdığımız bir code **tüm uygulamayı çökertip** Uvicorn ve Python'ın crash olmasına neden olabilir. 💥
+
+Böyle bir durumda, tek bir noktadaki hata yüzünden uygulamanın ölü kalmasını istemezsiniz; bozuk olmayan *path operations* en azından çalışmaya devam etsin istersiniz.
+
+### Crash Sonrası Yeniden Başlatma { #restart-after-crash }
+
+Ancak çalışan **process**'i çökerten gerçekten kötü hatalarda, process'i **yeniden başlatmaktan** sorumlu harici bir bileşen istersiniz; en azından birkaç kez...
+
+/// tip | İpucu
+
+...Yine de uygulama **hemen crash oluyorsa**, onu sonsuza kadar yeniden başlatmaya çalışmanın pek anlamı yoktur. Böyle durumları büyük ihtimalle geliştirme sırasında ya da en geç deploy'dan hemen sonra fark edersiniz.
+
+O yüzden ana senaryoya odaklanalım: Gelecekte bazı özel durumlarda tamamen çökebilir ve yine de yeniden başlatmak mantıklıdır.
+
+///
+
+Uygulamanızı yeniden başlatmakla görevli bileşenin **harici bir bileşen** olmasını istersiniz. Çünkü o noktada Uvicorn ve Python ile birlikte aynı uygulama zaten crash olmuştur; aynı app'in içindeki aynı code'un bunu düzeltmek için yapabileceği bir şey kalmaz.
+
+### Otomatik Yeniden Başlatma için Örnek Araçlar { #example-tools-to-restart-automatically }
+
+Çoğu durumda, **startup'ta programı çalıştırmak** için kullanılan aracın aynısı otomatik **restart**'ları yönetmek için de kullanılır.
+
+Örneğin bu şunlarla yönetilebilir:
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Docker in Swarm Mode
+* Systemd
+* Supervisor
+* Bir cloud provider tarafından servislerinin parçası olarak içeride yönetilmesi
+* Diğerleri...
+
+## Replikasyon - Process'ler ve Bellek { #replication-processes-and-memory }
+
+FastAPI uygulamasında, Uvicorn'u çalıştıran `fastapi` komutu gibi bir server programı kullanırken, uygulamayı **tek bir process** içinde bir kez çalıştırmak bile aynı anda birden fazla client'a hizmet verebilir.
+
+Ancak birçok durumda, aynı anda birden fazla worker process çalıştırmak istersiniz.
+
+### Birden Fazla Process - Worker'lar { #multiple-processes-workers }
+
+Tek bir process'in karşılayabileceğinden daha fazla client'ınız varsa (örneğin sanal makine çok büyük değilse) ve server CPU'sunda **birden fazla core** varsa, aynı uygulamayla **birden fazla process** çalıştırıp tüm request'leri bunlara dağıtabilirsiniz.
+
+Aynı API programının **birden fazla process**'ini çalıştırdığınızda, bunlara genellikle **worker** denir.
+
+### Worker Process'ler ve Port'lar { #worker-processes-and-ports }
+
+[HTTPS hakkındaki dokümanda](https.md) bir server'da aynı port ve IP adresi kombinasyonunu yalnızca tek bir process'in dinleyebileceğini hatırlıyor musunuz?
+
+Bu hâlâ geçerli.
+
+Dolayısıyla **aynı anda birden fazla process** çalıştırabilmek için, **port** üzerinde dinleyen **tek bir process** olmalı ve bu process iletişimi bir şekilde worker process'lere aktarmalıdır.
+
+### Process Başına Bellek { #memory-per-process }
+
+Program belleğe bir şeyler yüklediğinde—örneğin bir değişkende bir machine learning modelini veya büyük bir dosyanın içeriğini tutmak gibi—bunların hepsi server'ın **belleğini (RAM)** tüketir.
+
+Ve birden fazla process normalde **belleği paylaşmaz**. Yani her çalışan process'in kendi verileri, değişkenleri ve belleği vardır. Code'unuz çok bellek tüketiyorsa, **her process** buna denk bir miktar bellek tüketir.
+
+### Server Belleği { #server-memory }
+
+Örneğin code'unuz **1 GB** boyutunda bir Machine Learning modelini yüklüyorsa, API'niz tek process ile çalışırken en az 1 GB RAM tüketir. **4 process** (4 worker) başlatırsanız her biri 1 GB RAM tüketir. Yani toplamda API'niz **4 GB RAM** tüketir.
+
+Uzak server'ınız veya sanal makineniz yalnızca 3 GB RAM'e sahipse, 4 GB'tan fazla RAM yüklemeye çalışmak sorun çıkarır. 🚨
+
+### Birden Fazla Process - Bir Örnek { #multiple-processes-an-example }
+
+Bu örnekte, iki adet **Worker Process** başlatıp kontrol eden bir **Manager Process** vardır.
+
+Bu Manager Process büyük ihtimalle IP üzerindeki **port**'u dinleyen süreçtir ve tüm iletişimi worker process'lere aktarır.
+
+Worker process'ler uygulamanızı çalıştıran process'lerdir; bir **request** alıp bir **response** döndürmek için asıl hesaplamaları yaparlar ve sizin RAM'de değişkenlere koyduğunuz her şeyi yüklerler.
+
++ +Başkalarının daha önceki çalışmaları olmasaydı, **FastAPI** var olmazdı. + +Geçmişte oluşturulan pek çok araç **FastAPI**'a ilham kaynağı olmuştur. + +Yıllardır yeni bir framework oluşturmaktan kaçınıyordum. Başlangıçta **FastAPI**'ın çözdüğü sorunları çözebilmek için pek çok farklı framework, eklenti ve araç kullanmayı denedim. + +Ancak bir noktada, geçmişteki diğer araçlardan en iyi fikirleri alarak bütün bu çözümleri kapsayan, ayrıca bütün bunları Python'ın daha önce mevcut olmayan özelliklerini (Python 3.6+ ile gelen tip belirteçleri) kullanarak yapan bir şey üretmekten başka bir seçenek kalmamıştı. + ++ +## Araştırma { #investigation } + +Önceki alternatifleri kullanarak hepsinden bir şeyler öğrenip, fikirler alıp, bunları kendim ve çalıştığım geliştirici ekipler için en iyi şekilde birleştirebilme şansım oldu. + +Mesela, ideal olarak standart Python tip belirteçlerine dayanması gerektiği açıktı. + +Ayrıca, en iyi yaklaşım zaten mevcut olan standartları kullanmaktı. + +Sonuç olarak, **FastAPI**'ı kodlamaya başlamadan önce, birkaç ay boyunca OpenAPI, JSON Schema, OAuth2 ve benzerlerinin tanımlamalarını inceledim. İlişkilerini, örtüştükleri noktaları ve farklılıklarını anlamaya çalıştım. + +## Tasarım { #design } + +Sonrasında, (**FastAPI** kullanan bir geliştirici olarak) sahip olmak istediğim "API"ı tasarlamak için biraz zaman harcadım. + +Çeşitli fikirleri en popüler Python editörlerinde test ettim: PyCharm, VS Code, Jedi tabanlı editörler. + +Bu test, en son [Python Geliştirici Anketi](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools)'ine göre, kullanıcıların yaklaşık %80'inin kullandığı editörleri kapsıyor. + +Bu da demek oluyor ki **FastAPI**, Python geliştiricilerinin %80'inin kullandığı editörlerle test edildi. Ve diğer editörlerin çoğu benzer şekilde çalıştığından, avantajları neredeyse tüm editörlerde çalışacaktır. + +Bu şekilde, kod tekrarını mümkün olduğunca azaltmak, her yerde otomatik tamamlama, tip ve hata kontrollerine sahip olmak için en iyi yolları bulabildim. + +Hepsi, tüm geliştiriciler için en iyi geliştirme deneyimini sağlayacak şekilde. + +## Gereksinimler { #requirements } + +Çeşitli alternatifleri test ettikten sonra, avantajlarından dolayı [**Pydantic**](https://docs.pydantic.dev/)'i kullanmaya karar verdim. + +Sonra, JSON Schema ile tamamen uyumlu olmasını sağlamak, kısıtlama bildirimlerini tanımlamanın farklı yollarını desteklemek ve birkaç editördeki testlere dayanarak editör desteğini (tip kontrolleri, otomatik tamamlama) geliştirmek için katkıda bulundum. + +Geliştirme sırasında, diğer ana gereksinim olan [**Starlette**](https://www.starlette.dev/)'e de katkıda bulundum. + +## Geliştirme { #development } + +**FastAPI**'ı oluşturmaya başladığımda, parçaların çoğu zaten yerindeydi, tasarım tanımlanmıştı, gereksinimler ve araçlar hazırdı, standartlar ve tanımlamalar hakkındaki bilgi net ve tazeydi. + +## Gelecek { #future } + +Şimdiye kadar, **FastAPI**'ın fikirleriyle birçok kişiye faydalı olduğu apaçık ortada. + +Birçok kullanım durumuna daha iyi uyduğu için, önceki alternatiflerin yerine seçiliyor. + +Ben ve ekibim dahil, birçok geliştirici ve ekip projelerinde **FastAPI**'ya bağlı. + +Tabi, geliştirilecek birçok özellik ve iyileştirme mevcut. + +**FastAPI**'ın önünde harika bir gelecek var. + +[Yardımlarınız](help-fastapi.md) çok değerlidir. diff --git a/docs/tr/docs/how-to/authentication-error-status-code.md b/docs/tr/docs/how-to/authentication-error-status-code.md new file mode 100644 index 0000000000000..cd8258da35e47 --- /dev/null +++ b/docs/tr/docs/how-to/authentication-error-status-code.md @@ -0,0 +1,17 @@ +# Eski 403 Kimlik Doğrulama Hata Durum Kodlarını Kullanma { #use-old-403-authentication-error-status-codes } + +FastAPI `0.122.0` sürümünden önce, entegre security yardımcı araçları başarısız bir kimlik doğrulama (authentication) sonrasında client'a bir hata döndüğünde HTTP durum kodu olarak `403 Forbidden` kullanıyordu. + +FastAPI `0.122.0` sürümünden itibaren ise daha uygun olan HTTP durum kodu `401 Unauthorized` kullanılmakta ve HTTP spesifikasyonlarına uygun olarak response içinde anlamlı bir `WWW-Authenticate` header'ı döndürülmektedir, [RFC 7235](https://datatracker.ietf.org/doc/html/rfc7235#section-3.1), [RFC 9110](https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized). + +Ancak herhangi bir nedenle client'larınız eski davranışa bağlıysa, security class'larınızda `make_not_authenticated_error` metodunu override ederek eski davranışa geri dönebilirsiniz. + +Örneğin, varsayılan `401 Unauthorized` hatası yerine `403 Forbidden` hatası döndüren bir `HTTPBearer` alt sınıfı oluşturabilirsiniz: + +{* ../../docs_src/authentication_error_status_code/tutorial001_an_py310.py hl[9:13] *} + +/// tip | İpucu + +Fonksiyonun exception instance'ını döndürdüğüne dikkat edin; exception'ı raise etmiyor. Raise işlemi internal kodun geri kalan kısmında yapılıyor. + +/// diff --git a/docs/tr/docs/how-to/conditional-openapi.md b/docs/tr/docs/how-to/conditional-openapi.md new file mode 100644 index 0000000000000..66504194433dc --- /dev/null +++ b/docs/tr/docs/how-to/conditional-openapi.md @@ -0,0 +1,56 @@ +# Koşullu OpenAPI { #conditional-openapi } + +Gerekirse, ayarlar ve environment variable'ları kullanarak OpenAPI'yi ortama göre koşullu şekilde yapılandırabilir, hatta tamamen devre dışı bırakabilirsiniz. + +## Güvenlik, API'ler ve dokümantasyon hakkında { #about-security-apis-and-docs } + +Production ortamında dokümantasyon arayüzlerini gizlemek, API'nizi korumanın yolu olmamalıdır. + +Bu, API'nize ekstra bir güvenlik katmanı eklemez; path operation'lar bulundukları yerde yine erişilebilir olacaktır. + +Kodunuzda bir güvenlik açığı varsa, o açık yine var olmaya devam eder. + +Dokümantasyonu gizlemek, API'nizle nasıl etkileşime geçileceğini anlamayı zorlaştırır ve production'da debug etmeyi de daha zor hale getirebilir. Bu yaklaşım, basitçe [Security through obscurity](https://en.wikipedia.org/wiki/Security_through_obscurity) olarak değerlendirilebilir. + +API'nizi güvence altına almak istiyorsanız, yapabileceğiniz daha iyi birçok şey var; örneğin: + +* request body'leriniz ve response'larınız için iyi tanımlanmış Pydantic model'larına sahip olduğunuzdan emin olun. +* dependencies kullanarak gerekli izinleri ve rolleri yapılandırın. +* Asla düz metin (plaintext) şifre saklamayın, yalnızca password hash'leri saklayın. +* pwdlib ve JWT token'ları gibi, iyi bilinen kriptografik araçları uygulayın ve kullanın. +* Gerektiğinde OAuth2 scope'ları ile daha ayrıntılı izin kontrolleri ekleyin. +* ...vb. + +Yine de, bazı ortamlarda (örn. production) veya environment variable'lardan gelen konfigürasyonlara bağlı olarak API docs'u gerçekten devre dışı bırakmanız gereken çok spesifik bir use case'iniz olabilir. + +## Ayarlar ve env var'lar ile koşullu OpenAPI { #conditional-openapi-from-settings-and-env-vars } + +Üretilen OpenAPI'yi ve docs UI'larını yapılandırmak için aynı Pydantic settings'i kolayca kullanabilirsiniz. + +Örneğin: + +{* ../../docs_src/conditional_openapi/tutorial001_py310.py hl[6,11] *} + +Burada `openapi_url` ayarını, varsayılanı `"/openapi.json"` olacak şekilde tanımlıyoruz. + +Ardından `FastAPI` app'ini oluştururken bunu kullanıyoruz. + +Sonrasında, environment variable `OPENAPI_URL`'i boş string olarak ayarlayarak OpenAPI'yi (UI docs dahil) devre dışı bırakabilirsiniz; örneğin: + +
+
+Ancak `syntaxHighlight` değerini `False` yaparak devre dışı bırakabilirsiniz:
+
+{* ../../docs_src/configure_swagger_ui/tutorial001_py310.py hl[3] *}
+
+...ve ardından Swagger UI artık syntax highlighting'i göstermeyecektir:
+
+
+
+## Temayı Değiştirin { #change-the-theme }
+
+Aynı şekilde, `"syntaxHighlight.theme"` anahtarıyla (ortasında bir nokta olduğuna dikkat edin) syntax highlighting temasını ayarlayabilirsiniz:
+
+{* ../../docs_src/configure_swagger_ui/tutorial002_py310.py hl[3] *}
+
+Bu yapılandırma, syntax highlighting renk temasını değiştirir:
+
+
+
+## Varsayılan Swagger UI Parametrelerini Değiştirin { #change-default-swagger-ui-parameters }
+
+FastAPI, çoğu kullanım senaryosu için uygun bazı varsayılan yapılandırma parametreleriyle gelir.
+
+Şu varsayılan yapılandırmaları içerir:
+
+{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}
+
+`swagger_ui_parameters` argümanında farklı bir değer vererek bunların herhangi birini ezebilirsiniz (override).
+
+Örneğin `deepLinking`'i devre dışı bırakmak için `swagger_ui_parameters`'a şu ayarları geçebilirsiniz:
+
+{* ../../docs_src/configure_swagger_ui/tutorial003_py310.py hl[3] *}
+
+## Diğer Swagger UI Parametreleri { #other-swagger-ui-parameters }
+
+Kullanabileceğiniz diğer tüm olası yapılandırmaları görmek için, resmi [Swagger UI parametreleri dokümantasyonunu](https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/) okuyun.
+
+## Yalnızca JavaScript Ayarları { #javascript-only-settings }
+
+Swagger UI ayrıca bazı yapılandırmaların **yalnızca JavaScript** nesneleri olmasına izin verir (örneğin JavaScript fonksiyonları).
+
+FastAPI, bu yalnızca JavaScript olan `presets` ayarlarını da içerir:
+
+```JavaScript
+presets: [
+ SwaggerUIBundle.presets.apis,
+ SwaggerUIBundle.SwaggerUIStandalonePreset
+]
+```
+
+Bunlar string değil, **JavaScript** nesneleridir; dolayısıyla bunları Python kodundan doğrudan geçemezsiniz.
+
+Böyle yalnızca JavaScript yapılandırmalarına ihtiyacınız varsa, yukarıdaki yöntemlerden birini kullanabilirsiniz: Swagger UI'nin tüm *path operation*'larını override edin ve ihtiyaç duyduğunuz JavaScript'i elle yazın.
diff --git a/docs/tr/docs/how-to/custom-docs-ui-assets.md b/docs/tr/docs/how-to/custom-docs-ui-assets.md
new file mode 100644
index 0000000000000..2a2a0cfa2d716
--- /dev/null
+++ b/docs/tr/docs/how-to/custom-docs-ui-assets.md
@@ -0,0 +1,185 @@
+# Özel Docs UI Statik Varlıkları (Self-Hosting) { #custom-docs-ui-static-assets-self-hosting }
+
+API dokümanları **Swagger UI** ve **ReDoc** kullanır ve bunların her biri bazı JavaScript ve CSS dosyalarına ihtiyaç duyar.
+
+Varsayılan olarak bu dosyalar bir CDN üzerinden servis edilir.
+
+Ancak bunu özelleştirmek mümkündür; belirli bir CDN ayarlayabilir veya dosyaları kendiniz servis edebilirsiniz.
+
+## JavaScript ve CSS için Özel CDN { #custom-cdn-for-javascript-and-css }
+
+Diyelim ki farklı bir CDN kullanmak istiyorsunuz; örneğin `https://unpkg.com/` kullanmak istiyorsunuz.
+
+Bu, örneğin bazı URL'leri kısıtlayan bir ülkede yaşıyorsanız faydalı olabilir.
+
+### Otomatik dokümanları devre dışı bırakın { #disable-the-automatic-docs }
+
+İlk adım, otomatik dokümanları devre dışı bırakmaktır; çünkü varsayılan olarak bunlar varsayılan CDN'i kullanır.
+
+Bunları devre dışı bırakmak için `FastAPI` uygulamanızı oluştururken URL'lerini `None` olarak ayarlayın:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[8] *}
+
+### Özel dokümanları ekleyin { #include-the-custom-docs }
+
+Şimdi özel dokümanlar için *path operation*'ları oluşturabilirsiniz.
+
+Dokümanlar için HTML sayfalarını üretmek üzere FastAPI'nin dahili fonksiyonlarını yeniden kullanabilir ve gerekli argümanları iletebilirsiniz:
+
+* `openapi_url`: Dokümanların HTML sayfasının API'niz için OpenAPI şemasını alacağı URL. Burada `app.openapi_url` niteliğini kullanabilirsiniz.
+* `title`: API'nizin başlığı.
+* `oauth2_redirect_url`: varsayılanı kullanmak için burada `app.swagger_ui_oauth2_redirect_url` kullanabilirsiniz.
+* `swagger_js_url`: Swagger UI dokümanlarınızın HTML'inin **JavaScript** dosyasını alacağı URL. Bu, özel CDN URL'idir.
+* `swagger_css_url`: Swagger UI dokümanlarınızın HTML'inin **CSS** dosyasını alacağı URL. Bu, özel CDN URL'idir.
+
+ReDoc için de benzer şekilde...
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[2:6,11:19,22:24,27:33] *}
+
+/// tip | İpucu
+
+`swagger_ui_redirect` için olan *path operation*, OAuth2 kullandığınızda yardımcı olması için vardır.
+
+API'nizi bir OAuth2 sağlayıcısıyla entegre ederseniz kimlik doğrulaması yapabilir, aldığınız kimlik bilgileriyle API dokümanlarına geri dönebilir ve gerçek OAuth2 kimlik doğrulamasını kullanarak onunla etkileşime geçebilirsiniz.
+
+Swagger UI bunu arka planda sizin için yönetir, ancak bu "redirect" yardımcısına ihtiyaç duyar.
+
+///
+
+### Test etmek için bir *path operation* oluşturun { #create-a-path-operation-to-test-it }
+
+Şimdi her şeyin çalıştığını test edebilmek için bir *path operation* oluşturun:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[36:38] *}
+
+### Test edin { #test-it }
+
+Artık [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) adresinden dokümanlarınıza gidebilmeli ve sayfayı yenilediğinizde bu varlıkların yeni CDN'den yüklendiğini görebilmelisiniz.
+
+## Dokümanlar için JavaScript ve CSS'i Self-Hosting ile barındırma { #self-hosting-javascript-and-css-for-docs }
+
+JavaScript ve CSS'i self-hosting ile barındırmak, örneğin uygulamanızın İnternet erişimi olmadan (offline), açık İnternet olmadan veya bir lokal ağ içinde bile çalışmaya devam etmesi gerekiyorsa faydalı olabilir.
+
+Burada bu dosyaları aynı FastAPI uygulamasında nasıl kendiniz servis edeceğinizi ve dokümanların bunları kullanacak şekilde nasıl yapılandırılacağını göreceksiniz.
+
+### Proje dosya yapısı { #project-file-structure }
+
+Diyelim ki projenizin dosya yapısı şöyle:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+```
+
+Şimdi bu statik dosyaları saklamak için bir dizin oluşturun.
+
+Yeni dosya yapınız şöyle olabilir:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static/
+```
+
+### Dosyaları indirin { #download-the-files }
+
+Dokümanlar için gereken statik dosyaları indirin ve `static/` dizinine koyun.
+
+Muhtemelen her bir linke sağ tıklayıp "Save link as..." benzeri bir seçenek seçebilirsiniz.
+
+**Swagger UI** şu dosyaları kullanır:
+
+* [`swagger-ui-bundle.js`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js)
+* [`swagger-ui.css`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css)
+
+**ReDoc** ise şu dosyayı kullanır:
+
+* [`redoc.standalone.js`](https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js)
+
+Bundan sonra dosya yapınız şöyle görünebilir:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static
+ ├── redoc.standalone.js
+ ├── swagger-ui-bundle.js
+ └── swagger-ui.css
+```
+
+### Statik dosyaları servis edin { #serve-the-static-files }
+
+* `StaticFiles` içe aktarın.
+* Belirli bir path'te bir `StaticFiles()` instance'ını "mount" edin.
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[7,11] *}
+
+### Statik dosyaları test edin { #test-the-static-files }
+
+Uygulamanızı başlatın ve [http://127.0.0.1:8000/static/redoc.standalone.js](http://127.0.0.1:8000/static/redoc.standalone.js) adresine gidin.
+
+**ReDoc** için çok uzun bir JavaScript dosyası görmelisiniz.
+
+Şuna benzer bir şekilde başlayabilir:
+
+```JavaScript
+/*! For license information please see redoc.standalone.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")):
+...
+```
+
+Bu, uygulamanızdan statik dosyaları servis edebildiğinizi ve dokümanlar için statik dosyaları doğru yere koyduğunuzu doğrular.
+
+Şimdi uygulamayı, dokümanlar için bu statik dosyaları kullanacak şekilde yapılandırabiliriz.
+
+### Statik dosyalar için otomatik dokümanları devre dışı bırakın { #disable-the-automatic-docs-for-static-files }
+
+Özel CDN kullanırken olduğu gibi, ilk adım otomatik dokümanları devre dışı bırakmaktır; çünkü bunlar varsayılan olarak CDN kullanır.
+
+Bunları devre dışı bırakmak için `FastAPI` uygulamanızı oluştururken URL'lerini `None` olarak ayarlayın:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[9] *}
+
+### Statik dosyalar için özel dokümanları ekleyin { #include-the-custom-docs-for-static-files }
+
+Özel CDN'de olduğu gibi, artık özel dokümanlar için *path operation*'ları oluşturabilirsiniz.
+
+Yine FastAPI'nin dahili fonksiyonlarını kullanarak dokümanlar için HTML sayfalarını oluşturabilir ve gerekli argümanları geçebilirsiniz:
+
+* `openapi_url`: Dokümanların HTML sayfasının API'niz için OpenAPI şemasını alacağı URL. Burada `app.openapi_url` niteliğini kullanabilirsiniz.
+* `title`: API'nizin başlığı.
+* `oauth2_redirect_url`: varsayılanı kullanmak için burada `app.swagger_ui_oauth2_redirect_url` kullanabilirsiniz.
+* `swagger_js_url`: Swagger UI dokümanlarınızın HTML'inin **JavaScript** dosyasını alacağı URL. **Artık bunu sizin kendi uygulamanız servis ediyor**.
+* `swagger_css_url`: Swagger UI dokümanlarınızın HTML'inin **CSS** dosyasını alacağı URL. **Artık bunu sizin kendi uygulamanız servis ediyor**.
+
+ReDoc için de benzer şekilde...
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[2:6,14:22,25:27,30:36] *}
+
+/// tip | İpucu
+
+`swagger_ui_redirect` için olan *path operation*, OAuth2 kullandığınızda yardımcı olması için vardır.
+
+API'nizi bir OAuth2 sağlayıcısıyla entegre ederseniz kimlik doğrulaması yapabilir, aldığınız kimlik bilgileriyle API dokümanlarına geri dönebilir ve gerçek OAuth2 kimlik doğrulamasını kullanarak onunla etkileşime geçebilirsiniz.
+
+Swagger UI bunu arka planda sizin için yönetir, ancak bu "redirect" yardımcısına ihtiyaç duyar.
+
+///
+
+### Statik dosyaları test etmek için bir *path operation* oluşturun { #create-a-path-operation-to-test-static-files }
+
+Şimdi her şeyin çalıştığını test edebilmek için bir *path operation* oluşturun:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[39:41] *}
+
+### Statik Dosyalar UI'ını Test Edin { #test-static-files-ui }
+
+Artık WiFi bağlantınızı kesip [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) adresindeki dokümanlarınıza gidebilmeli ve sayfayı yenileyebilmelisiniz.
+
+Ve İnternet olmasa bile API dokümanlarınızı görebilir ve onunla etkileşime geçebilirsiniz.
diff --git a/docs/tr/docs/how-to/custom-request-and-route.md b/docs/tr/docs/how-to/custom-request-and-route.md
new file mode 100644
index 0000000000000..1c17098ae700e
--- /dev/null
+++ b/docs/tr/docs/how-to/custom-request-and-route.md
@@ -0,0 +1,109 @@
+# Özel Request ve APIRoute sınıfı { #custom-request-and-apiroute-class }
+
+Bazı durumlarda, `Request` ve `APIRoute` sınıflarının kullandığı mantığı override etmek isteyebilirsiniz.
+
+Özellikle bu yaklaşım, bir middleware içindeki mantığa iyi bir alternatif olabilir.
+
+Örneğin, request body uygulamanız tarafından işlenmeden önce okumak veya üzerinde değişiklik yapmak istiyorsanız.
+
+/// danger | Uyarı
+
+Bu "ileri seviye" bir özelliktir.
+
+**FastAPI**'ye yeni başlıyorsanız bu bölümü atlamak isteyebilirsiniz.
+
+///
+
+## Kullanım senaryoları { #use-cases }
+
+Bazı kullanım senaryoları:
+
+* JSON olmayan request body'leri JSON'a dönüştürmek (örn. [`msgpack`](https://msgpack.org/index.html)).
+* gzip ile sıkıştırılmış request body'leri açmak (decompress).
+* Tüm request body'lerini otomatik olarak loglamak.
+
+## Özel request body encoding'lerini ele alma { #handling-custom-request-body-encodings }
+
+Gzip request'lerini açmak için özel bir `Request` alt sınıfını nasıl kullanabileceğimize bakalım.
+
+Ayrıca, o özel request sınıfını kullanmak için bir `APIRoute` alt sınıfı da oluşturacağız.
+
+### Özel bir `GzipRequest` sınıfı oluşturun { #create-a-custom-gziprequest-class }
+
+/// tip | İpucu
+
+Bu, nasıl çalıştığını göstermek için hazırlanmış basit bir örnektir; Gzip desteğine ihtiyacınız varsa sağlanan [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware) bileşenini kullanabilirsiniz.
+
+///
+
+Önce, uygun bir header mevcut olduğunda body'yi açmak için `Request.body()` metodunu overwrite edecek bir `GzipRequest` sınıfı oluşturuyoruz.
+
+Header'da `gzip` yoksa body'yi açmayı denemez.
+
+Böylece aynı route sınıfı, gzip ile sıkıştırılmış veya sıkıştırılmamış request'leri handle edebilir.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[9:16] *}
+
+### Özel bir `GzipRoute` sınıfı oluşturun { #create-a-custom-gziproute-class }
+
+Sonra, `GzipRequest`'i kullanacak `fastapi.routing.APIRoute` için özel bir alt sınıf oluşturuyoruz.
+
+Bu kez `APIRoute.get_route_handler()` metodunu overwrite edeceğiz.
+
+Bu metot bir fonksiyon döndürür. Bu fonksiyon da request'i alır ve response döndürür.
+
+Burada bu fonksiyonu, orijinal request'ten bir `GzipRequest` oluşturmak için kullanıyoruz.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[19:27] *}
+
+/// note | Teknik Detaylar
+
+Bir `Request`'in, request ile ilgili metadata'yı içeren bir Python `dict` olan `request.scope` attribute'u vardır.
+
+Bir `Request` ayrıca `request.receive` içerir; bu, request'in body'sini "almak" (receive etmek) için kullanılan bir fonksiyondur.
+
+`scope` `dict`'i ve `receive` fonksiyonu, ASGI spesifikasyonunun parçalarıdır.
+
+Ve bu iki şey, `scope` ve `receive`, yeni bir `Request` instance'ı oluşturmak için gerekenlerdir.
+
+`Request` hakkında daha fazla bilgi için [Starlette'ın Request dokümantasyonu](https://www.starlette.dev/requests/) bölümüne bakın.
+
+///
+
+`GzipRequest.get_route_handler` tarafından döndürülen fonksiyonun farklı yaptığı tek şey, `Request`'i bir `GzipRequest`'e dönüştürmektir.
+
+Bunu yaptığımızda `GzipRequest`, veriyi (gerekliyse) *path operations*'larımıza geçirmeden önce açma (decompress) işini üstlenir.
+
+Bundan sonra tüm işleme mantığı aynıdır.
+
+Ancak `GzipRequest.body` içindeki değişikliklerimiz sayesinde, request body gerektiğinde **FastAPI** tarafından yüklendiğinde otomatik olarak decompress edilir.
+
+## Bir exception handler içinde request body'ye erişme { #accessing-the-request-body-in-an-exception-handler }
+
+/// tip | İpucu
+
+Aynı problemi çözmek için, muhtemelen `RequestValidationError` için özel bir handler içinde `body` kullanmak çok daha kolaydır ([Hataları Ele Alma](../tutorial/handling-errors.md#use-the-requestvalidationerror-body)).
+
+Yine de bu örnek geçerlidir ve dahili bileşenlerle nasıl etkileşime geçileceğini gösterir.
+
+///
+
+Aynı yaklaşımı bir exception handler içinde request body'ye erişmek için de kullanabiliriz.
+
+Tek yapmamız gereken, request'i bir `try`/`except` bloğu içinde handle etmek:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[14,16] *}
+
+Bir exception oluşursa, `Request` instance'ı hâlâ scope içinde olacağı için, hatayı handle ederken request body'yi okuyup kullanabiliriz:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[17:19] *}
+
+## Bir router içinde özel `APIRoute` sınıfı { #custom-apiroute-class-in-a-router }
+
+Bir `APIRouter` için `route_class` parametresini de ayarlayabilirsiniz:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[26] *}
+
+Bu örnekte, `router` altındaki *path operations*'lar özel `TimedRoute` sınıfını kullanır ve response'u üretmek için geçen süreyi içeren ekstra bir `X-Response-Time` header'ı response'ta bulunur:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[13:20] *}
diff --git a/docs/tr/docs/how-to/extending-openapi.md b/docs/tr/docs/how-to/extending-openapi.md
new file mode 100644
index 0000000000000..7fe8649e1f432
--- /dev/null
+++ b/docs/tr/docs/how-to/extending-openapi.md
@@ -0,0 +1,80 @@
+# OpenAPI'yi Genişletme { #extending-openapi }
+
+Oluşturulan OpenAPI şemasını değiştirmeniz gereken bazı durumlar olabilir.
+
+Bu bölümde bunun nasıl yapılacağını göreceksiniz.
+
+## Normal Süreç { #the-normal-process }
+
+Normal (varsayılan) süreç şöyledir.
+
+Bir `FastAPI` uygulamasının (instance) OpenAPI şemasını döndürmesi beklenen bir `.openapi()` metodu vardır.
+
+Uygulama nesnesi oluşturulurken, `/openapi.json` (ya da `openapi_url` için ne ayarladıysanız o) için bir *path operation* kaydedilir.
+
+Bu path operation, uygulamanın `.openapi()` metodunun sonucunu içeren bir JSON response döndürür.
+
+Varsayılan olarak `.openapi()` metodunun yaptığı şey, `.openapi_schema` özelliğinde içerik olup olmadığını kontrol etmek ve varsa onu döndürmektir.
+
+Eğer yoksa, `fastapi.openapi.utils.get_openapi` konumundaki yardımcı (utility) fonksiyonu kullanarak şemayı üretir.
+
+Ve `get_openapi()` fonksiyonu şu parametreleri alır:
+
+* `title`: Dokümanlarda gösterilen OpenAPI başlığı.
+* `version`: API'nizin sürümü, örn. `2.5.0`.
+* `openapi_version`: Kullanılan OpenAPI specification sürümü. Varsayılan olarak en günceli: `3.1.0`.
+* `summary`: API'nin kısa özeti.
+* `description`: API'nizin açıklaması; markdown içerebilir ve dokümanlarda gösterilir.
+* `routes`: route'ların listesi; bunların her biri kayıtlı *path operations*'lardır. `app.routes` içinden alınırlar.
+
+/// info | Bilgi
+
+`summary` parametresi OpenAPI 3.1.0 ve üzeri sürümlerde vardır; FastAPI 0.99.0 ve üzeri tarafından desteklenmektedir.
+
+///
+
+## Varsayılanları Ezme { #overriding-the-defaults }
+
+Yukarıdaki bilgileri kullanarak aynı yardımcı fonksiyonla OpenAPI şemasını üretebilir ve ihtiyacınız olan her parçayı override edebilirsiniz.
+
+Örneğin, [özel bir logo eklemek için ReDoc'un OpenAPI extension'ını](https://github.com/Rebilly/ReDoc/blob/master/docs/redoc-vendor-extensions.md#x-logo) ekleyelim.
+
+### Normal **FastAPI** { #normal-fastapi }
+
+Önce, tüm **FastAPI** uygulamanızı her zamanki gibi yazın:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[1,4,7:9] *}
+
+### OpenAPI Şemasını Üretme { #generate-the-openapi-schema }
+
+Ardından, bir `custom_openapi()` fonksiyonunun içinde aynı yardımcı fonksiyonu kullanarak OpenAPI şemasını üretin:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[2,15:21] *}
+
+### OpenAPI Şemasını Değiştirme { #modify-the-openapi-schema }
+
+Artık OpenAPI şemasındaki `info` "object"'ine özel bir `x-logo` ekleyerek ReDoc extension'ını ekleyebilirsiniz:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[22:24] *}
+
+### OpenAPI Şemasını Cache'leme { #cache-the-openapi-schema }
+
+Ürettiğiniz şemayı saklamak için `.openapi_schema` özelliğini bir "cache" gibi kullanabilirsiniz.
+
+Böylece bir kullanıcı API docs'larınızı her açtığında uygulamanız şemayı tekrar tekrar üretmek zorunda kalmaz.
+
+Şema yalnızca bir kez üretilecektir; sonraki request'ler için de aynı cache'lenmiş şema kullanılacaktır.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[13:14,25:26] *}
+
+### Metodu Override Etme { #override-the-method }
+
+Şimdi `.openapi()` metodunu yeni fonksiyonunuzla değiştirebilirsiniz.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[29] *}
+
+### Kontrol Edin { #check-it }
+
+[http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) adresine gittiğinizde, özel logonuzu kullandığınızı göreceksiniz (bu örnekte **FastAPI**'nin logosu):
+
+
diff --git a/docs/tr/docs/how-to/general.md b/docs/tr/docs/how-to/general.md
new file mode 100644
index 0000000000000..915ec9cc2dc6f
--- /dev/null
+++ b/docs/tr/docs/how-to/general.md
@@ -0,0 +1,43 @@
+# Genel - Nasıl Yapılır - Tarifler { #general-how-to-recipes }
+
+Bu sayfada genel veya sık sorulan sorular için dokümantasyonun diğer bölümlerine çeşitli yönlendirmeler bulunmaktadır.
+
+## Veri Filtreleme - Güvenlik { #filter-data-security }
+
+Döndürmeniz gerekenden daha fazla veri döndürmediğinizden emin olmak için, [Tutorial - Response Model - Return Type](../tutorial/response-model.md) dokümantasyonunu okuyun.
+
+## Response Performansını Optimize Etme - Response Model - Return Type { #optimize-response-performance-response-model-return-type }
+
+JSON veri döndürürken performansı optimize etmek için bir return type veya response model kullanın; böylece Pydantic serileştirmeyi Python'dan geçmeden Rust tarafında gerçekleştirir. Ayrıntılar için [Tutorial - Response Model - Return Type](../tutorial/response-model.md) dokümantasyonunu okuyun.
+
+## Dokümantasyon Etiketleri - OpenAPI { #documentation-tags-openapi }
+
+*path operation*'larınıza etiketler eklemek ve dokümantasyon arayüzünde gruplamak için, [Tutorial - Path Operation Configurations - Tags](../tutorial/path-operation-configuration.md#tags) dokümantasyonunu okuyun.
+
+## Dokümantasyon Özeti ve Açıklaması - OpenAPI { #documentation-summary-and-description-openapi }
+
+*path operation*'larınıza özet ve açıklama eklemek ve bunları dokümantasyon arayüzünde göstermek için, [Tutorial - Path Operation Configurations - Summary and Description](../tutorial/path-operation-configuration.md#summary-and-description) dokümantasyonunu okuyun.
+
+## Dokümantasyon Response Açıklaması - OpenAPI { #documentation-response-description-openapi }
+
+Dokümantasyon arayüzünde gösterilen response açıklamasını tanımlamak için, [Tutorial - Path Operation Configurations - Response description](../tutorial/path-operation-configuration.md#response-description) dokümantasyonunu okuyun.
+
+## Dokümantasyonda Bir *Path Operation*'ı Kullanımdan Kaldırma - OpenAPI { #documentation-deprecate-a-path-operation-openapi }
+
+Bir *path operation*'ı kullanımdan kaldırmak ve bunu dokümantasyon arayüzünde göstermek için, [Tutorial - Path Operation Configurations - Deprecation](../tutorial/path-operation-configuration.md#deprecate-a-path-operation) dokümantasyonunu okuyun.
+
+## Herhangi Bir Veriyi JSON Uyumlu Hale Getirme { #convert-any-data-to-json-compatible }
+
+Herhangi bir veriyi JSON uyumlu hale getirmek için, [Tutorial - JSON Compatible Encoder](../tutorial/encoder.md) dokümantasyonunu okuyun.
+
+## OpenAPI Meta Verileri - Dokümantasyon { #openapi-metadata-docs }
+
+Lisans, sürüm, iletişim vb. dahil olmak üzere OpenAPI şemanıza meta veriler eklemek için, [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md) dokümantasyonunu okuyun.
+
+## OpenAPI Özel URL { #openapi-custom-url }
+
+OpenAPI URL'ini özelleştirmek (veya kaldırmak) için, [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#openapi-url) dokümantasyonunu okuyun.
+
+## OpenAPI Dokümantasyon URL'leri { #openapi-docs-urls }
+
+Otomatik olarak oluşturulan dokümantasyon kullanıcı arayüzlerinde kullanılan URL'leri güncellemek için, [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#docs-urls) dokümantasyonunu okuyun.
diff --git a/docs/tr/docs/how-to/graphql.md b/docs/tr/docs/how-to/graphql.md
new file mode 100644
index 0000000000000..bb32fe392e68e
--- /dev/null
+++ b/docs/tr/docs/how-to/graphql.md
@@ -0,0 +1,60 @@
+# GraphQL { #graphql }
+
+**FastAPI**, **ASGI** standardını temel aldığı için ASGI ile uyumlu herhangi bir **GraphQL** kütüphanesini entegre etmek oldukça kolaydır.
+
+Aynı uygulama içinde normal FastAPI *path operation*'larını GraphQL ile birlikte kullanabilirsiniz.
+
+/// tip | İpucu
+
+**GraphQL** bazı çok özel kullanım senaryolarını çözer.
+
+Yaygın **web API**'lerle karşılaştırıldığında **avantajları** ve **dezavantajları** vardır.
+
+Kendi senaryonuz için **faydaların**, **olumsuz yönleri** telafi edip etmediğini mutlaka değerlendirin. 🤓
+
+///
+
+## GraphQL Kütüphaneleri { #graphql-libraries }
+
+Aşağıda **ASGI** desteği olan bazı **GraphQL** kütüphaneleri var. Bunları **FastAPI** ile kullanabilirsiniz:
+
+* [Strawberry](https://strawberry.rocks/) 🍓
+ * [FastAPI dokümantasyonu](https://strawberry.rocks/docs/integrations/fastapi) ile
+* [Ariadne](https://ariadnegraphql.org/)
+ * [FastAPI dokümantasyonu](https://ariadnegraphql.org/docs/fastapi-integration) ile
+* [Tartiflette](https://tartiflette.io/)
+ * ASGI entegrasyonu sağlamak için [Tartiflette ASGI](https://tartiflette.github.io/tartiflette-asgi/) ile
+* [Graphene](https://graphene-python.org/)
+ * [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3) ile
+
+## Strawberry ile GraphQL { #graphql-with-strawberry }
+
+**GraphQL** ile çalışmanız gerekiyorsa ya da bunu istiyorsanız, [**Strawberry**](https://strawberry.rocks/) önerilen kütüphanedir; çünkü tasarımı **FastAPI**'nin tasarımına en yakındır ve her şey **type annotation**'lar üzerine kuruludur.
+
+Kullanım senaryonuza göre farklı bir kütüphaneyi tercih edebilirsiniz; ancak bana sorarsanız muhtemelen **Strawberry**'yi denemenizi önerirdim.
+
+Strawberry'yi FastAPI ile nasıl entegre edebileceğinize dair küçük bir ön izleme:
+
+{* ../../docs_src/graphql_/tutorial001_py310.py hl[3,22,25] *}
+
+Strawberry hakkında daha fazlasını [Strawberry dokümantasyonunda](https://strawberry.rocks/) öğrenebilirsiniz.
+
+Ayrıca [FastAPI ile Strawberry](https://strawberry.rocks/docs/integrations/fastapi) dokümanlarına da göz atın.
+
+## Starlette'teki Eski `GraphQLApp` { #older-graphqlapp-from-starlette }
+
+Starlette'in önceki sürümlerinde [Graphene](https://graphene-python.org/) ile entegrasyon için bir `GraphQLApp` sınıfı vardı.
+
+Bu sınıf Starlette'te kullanımdan kaldırıldı (deprecated). Ancak bunu kullanan bir kodunuz varsa, aynı kullanım senaryosunu kapsayan ve **neredeyse aynı bir interface** sağlayan [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3)'e kolayca **migrate** edebilirsiniz.
+
+/// tip | İpucu
+
+GraphQL'e ihtiyacınız varsa, custom class ve type'lar yerine type annotation'lara dayandığı için yine de [Strawberry](https://strawberry.rocks/)'yi incelemenizi öneririm.
+
+///
+
+## Daha Fazlasını Öğrenin { #learn-more }
+
+**GraphQL** hakkında daha fazlasını [resmi GraphQL dokümantasyonunda](https://graphql.org/) öğrenebilirsiniz.
+
+Ayrıca yukarıda bahsedilen kütüphanelerin her biri hakkında, kendi bağlantılarından daha fazla bilgi okuyabilirsiniz.
diff --git a/docs/tr/docs/how-to/index.md b/docs/tr/docs/how-to/index.md
new file mode 100644
index 0000000000000..0aa6e180910b3
--- /dev/null
+++ b/docs/tr/docs/how-to/index.md
@@ -0,0 +1,13 @@
+# Nasıl Yapılır - Tarifler { #how-to-recipes }
+
+Burada **çeşitli konular** hakkında farklı tarifler veya "nasıl yapılır" kılavuzları göreceksiniz.
+
+Bu fikirlerin büyük bir kısmı aşağı yukarı **bağımsız** olacaktır ve çoğu durumda bunları yalnızca doğrudan **projenize** uygulanıyorsa incelemeniz yeterli olacaktır.
+
+Projeniz için ilginç ve yararlı görünen bir şey varsa devam edin ve inceleyin; aksi halde muhtemelen bunları atlayabilirsiniz.
+
+/// tip | İpucu
+
+**FastAPI**'yi yapılandırılmış bir şekilde (önerilir) **öğrenmek** istiyorsanız bunun yerine [Öğretici - Kullanıcı Rehberi](../tutorial/index.md)'ni bölüm bölüm okuyun.
+
+///
diff --git a/docs/tr/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/tr/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
new file mode 100644
index 0000000000000..7777139375658
--- /dev/null
+++ b/docs/tr/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -0,0 +1,135 @@
+# Pydantic v1'den Pydantic v2'ye Geçiş { #migrate-from-pydantic-v1-to-pydantic-v2 }
+
+Eski bir FastAPI uygulamanız varsa, Pydantic'in 1. sürümünü kullanıyor olabilirsiniz.
+
+FastAPI 0.100.0 sürümü, Pydantic v1 veya v2 ile çalışmayı destekliyordu. Hangisi kuruluysa onu kullanıyordu.
+
+FastAPI 0.119.0 sürümü, v2'ye geçişi kolaylaştırmak için, Pydantic v2’nin içinden Pydantic v1’e (`pydantic.v1` olarak) kısmi destek ekledi.
+
+FastAPI 0.126.0 sürümü Pydantic v1 desteğini kaldırdı, ancak bir süre daha `pydantic.v1` desteğini sürdürdü.
+
+/// warning | Uyarı
+
+Pydantic ekibi, Python'ın en yeni sürümleri için Pydantic v1 desteğini, **Python 3.14** ile başlayarak sonlandırdı.
+
+Buna `pydantic.v1` de dahildir; Python 3.14 ve üzeri sürümlerde artık desteklenmemektedir.
+
+Python'ın en yeni özelliklerini kullanmak istiyorsanız, Pydantic v2 kullandığınızdan emin olmanız gerekir.
+
+///
+
+Pydantic v1 kullanan eski bir FastAPI uygulamanız varsa, burada onu Pydantic v2'ye nasıl taşıyacağınızı ve kademeli geçişi kolaylaştıran **FastAPI 0.119.0 özelliklerini** göstereceğim.
+
+## Resmi Kılavuz { #official-guide }
+
+Pydantic'in v1'den v2'ye resmi bir [Migration Guide](https://docs.pydantic.dev/latest/migration/)'ı vardır.
+
+Ayrıca nelerin değiştiğini, validasyonların artık nasıl daha doğru ve katı olduğunu, olası dikkat edilmesi gereken noktaları (caveat) vb. de içerir.
+
+Nelerin değiştiğini daha iyi anlamak için okuyabilirsiniz.
+
+## Testler { #tests }
+
+Uygulamanız için [testleriniz](../tutorial/testing.md) olduğundan ve bunları continuous integration (CI) üzerinde çalıştırdığınızdan emin olun.
+
+Bu şekilde yükseltmeyi yapabilir ve her şeyin hâlâ beklendiği gibi çalıştığını doğrulayabilirsiniz.
+
+## `bump-pydantic` { #bump-pydantic }
+
+Birçok durumda, özel özelleştirmeler olmadan standart Pydantic modelleri kullanıyorsanız, Pydantic v1'den Pydantic v2'ye geçiş sürecinin büyük kısmını otomatikleştirebilirsiniz.
+
+Aynı Pydantic ekibinin geliştirdiği [`bump-pydantic`](https://github.com/pydantic/bump-pydantic) aracını kullanabilirsiniz.
+
+Bu araç, değişmesi gereken kodun büyük bir kısmını otomatik olarak dönüştürmenize yardımcı olur.
+
+Bundan sonra testleri çalıştırıp her şeyin çalışıp çalışmadığını kontrol edebilirsiniz. Çalışıyorsa işiniz biter. 😎
+
+## v2 İçinde Pydantic v1 { #pydantic-v1-in-v2 }
+
+Pydantic v2, `pydantic.v1` adlı bir alt modül olarak Pydantic v1'in tamamını içerir. Ancak bu yapı, Python 3.13'ün üzerindeki sürümlerde artık desteklenmemektedir.
+
+Bu da şu anlama gelir: Pydantic v2'nin en güncel sürümünü kurup, bu alt modülden eski Pydantic v1 bileşenlerini import ederek, sanki eski Pydantic v1 kuruluymuş gibi kullanabilirsiniz.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}
+
+### v2 İçinde Pydantic v1 için FastAPI Desteği { #fastapi-support-for-pydantic-v1-in-v2 }
+
+FastAPI 0.119.0'dan itibaren, v2'ye geçişi kolaylaştırmak için Pydantic v2’nin içinden Pydantic v1 kullanımına yönelik kısmi destek de vardır.
+
+Dolayısıyla Pydantic'i en güncel 2 sürümüne yükseltip import'ları `pydantic.v1` alt modülünü kullanacak şekilde değiştirebilirsiniz; çoğu durumda bu doğrudan çalışır.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py hl[2,5,15] *}
+
+/// warning | Uyarı
+
+Pydantic ekibi Python 3.14'ten itibaren yeni Python sürümlerinde Pydantic v1'i artık desteklemediği için, `pydantic.v1` kullanımı da Python 3.14 ve üzeri sürümlerde desteklenmez.
+
+///
+
+### Aynı Uygulamada Pydantic v1 ve v2 { #pydantic-v1-and-v2-on-the-same-app }
+
+Pydantic açısından, alanları (field) Pydantic v1 modelleriyle tanımlanmış bir Pydantic v2 modeli (ya da tersi) kullanmak **desteklenmez**.
+
+```mermaid
+graph TB
+ subgraph "❌ Not Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+...ancak aynı uygulamada Pydantic v1 ve v2 kullanarak **ayrı** modeller tanımlayabilirsiniz.
+
+```mermaid
+graph TB
+ subgraph "✅ Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+Bazı durumlarda, FastAPI uygulamanızda aynı **path operation** içinde hem Pydantic v1 hem de v2 modellerini kullanmak bile mümkündür:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}
+
+Yukarıdaki örnekte input modeli bir Pydantic v1 modelidir; output modeli ( `response_model=ItemV2` ile tanımlanan) ise bir Pydantic v2 modelidir.
+
+### Pydantic v1 Parametreleri { #pydantic-v1-parameters }
+
+Pydantic v1 modelleriyle `Body`, `Query`, `Form` vb. parametreler için FastAPI'ye özgü bazı araçları kullanmanız gerekiyorsa, Pydantic v2'ye geçişi tamamlayana kadar bunları `fastapi.temp_pydantic_v1_params` içinden import edebilirsiniz:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py hl[4,18] *}
+
+### Adım Adım Geçiş { #migrate-in-steps }
+
+/// tip | İpucu
+
+Önce `bump-pydantic` ile deneyin; testleriniz geçerse ve bu yol çalışırsa tek komutla işi bitirmiş olursunuz. ✨
+
+///
+
+`bump-pydantic` sizin senaryonuz için uygun değilse, aynı uygulamada hem Pydantic v1 hem de v2 modellerini birlikte kullanma desteğinden yararlanarak Pydantic v2'ye kademeli şekilde geçebilirsiniz.
+
+Önce Pydantic'i en güncel 2 sürümüne yükseltip tüm modelleriniz için import'ları `pydantic.v1` kullanacak şekilde değiştirebilirsiniz.
+
+Ardından modellerinizi Pydantic v1'den v2'ye gruplar hâlinde, adım adım taşımaya başlayabilirsiniz. 🚶
diff --git a/docs/tr/docs/how-to/separate-openapi-schemas.md b/docs/tr/docs/how-to/separate-openapi-schemas.md
new file mode 100644
index 0000000000000..c26411d292691
--- /dev/null
+++ b/docs/tr/docs/how-to/separate-openapi-schemas.md
@@ -0,0 +1,102 @@
+# Input ve Output için Ayrı OpenAPI Schema'ları (Ya da Değil) { #separate-openapi-schemas-for-input-and-output-or-not }
+
+**Pydantic v2** yayınlandığından beri, üretilen OpenAPI eskisine göre biraz daha net ve **doğru**. 😎
+
+Hatta bazı durumlarda, aynı Pydantic model için OpenAPI içinde input ve output tarafında, **default değerler** olup olmamasına bağlı olarak **iki farklı JSON Schema** bile görebilirsiniz.
+
+Bunun nasıl çalıştığına ve gerekirse nasıl değiştirebileceğinize bir bakalım.
+
+## Input ve Output için Pydantic Modelleri { #pydantic-models-for-input-and-output }
+
+Default değerleri olan bir Pydantic modeliniz olduğunu varsayalım; örneğin şöyle:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *}
+
+### Input için Model { #model-for-input }
+
+Bu modeli şöyle input olarak kullanırsanız:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *}
+
+...`description` alanı **zorunlu olmaz**. Çünkü `None` default değerine sahiptir.
+
+### Dokümanlarda Input Modeli { #input-model-in-docs }
+
+Bunu dokümanlarda da doğrulayabilirsiniz; `description` alanında **kırmızı yıldız** yoktur, yani required olarak işaretlenmemiştir:
+
+
+
+
+
+
+- FastAPI framework, yüksek performanslı, öğrenmesi kolay, geliştirmesi hızlı, kullanıma sunulmaya hazır. + FastAPI framework, yüksek performanslı, öğrenmesi kolay, kodlaması hızlı, production'a hazır
--- -**dokümantasyon**: https://fastapi.tiangolo.com +**Dokümantasyon**: [https://fastapi.tiangolo.com/tr](https://fastapi.tiangolo.com/tr) -**Kaynak kodu**: https://github.com/tiangolo/fastapi +**Kaynak Kod**: [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi) --- -FastAPI, Python 3.6+'nın standart type hintlerine dayanan modern ve hızlı (yüksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'ü. +FastAPI, Python'un standart type hints'lerine dayalı olarak Python ile API'lar oluşturmak için kullanılan modern ve hızlı (yüksek performanslı) bir web framework'üdür. -Ana özellikleri: +Temel özellikleri şunlardır: -* **Hızlı**: çok yüksek performanslı, **NodeJS** ve **Go** ile eşdeğer seviyede performans sağlıyor, (Starlette ve Pydantic sayesinde.) [Python'un en hızlı frameworklerinden bir tanesi.](#performans). -* **Kodlaması hızlı**: Yeni özellikler geliştirmek neredeyse %200 - %300 daha hızlı. * -* **Daha az bug**: Geliştirici (insan) kaynaklı hatalar neredeyse %40 azaltıldı. * -* **Sezgileri güçlü**: Editor (otomatik-tamamlama) desteği harika. Otomatik tamamlama her yerde. Debuglamak ile daha az zaman harcayacaksınız. -* **Kolay**: Öğrenmesi ve kullanması kolay olacak şekilde. Doküman okumak için harcayacağınız süre azaltıldı. -* **Kısa**: Kod tekrarını minimuma indirdik. Fonksiyon parametrelerinin tiplerini belirtmede farklı yollar sunarak karşılaşacağınız bug'ları azalttık. -* **Güçlü**: Otomatik dokümantasyon ile beraber, kullanıma hazır kod yaz. +* **Hızlı**: Çok yüksek performanslı, **NodeJS** ve **Go** ile eşit düzeyde (Starlette ve Pydantic sayesinde). [Mevcut en hızlı Python framework'lerinden biri](#performance). +* **Kodlaması Hızlı**: Özellik geliştirme hızını yaklaşık %200 ile %300 aralığında artırır. * +* **Daha az hata**: İnsan (geliştirici) kaynaklı hataları yaklaşık %40 azaltır. * +* **Sezgisel**: Harika bir editör desteği. Her yerde Tamamlama. Hata ayıklamaya daha az zaman. +* **Kolay**: Kullanımı ve öğrenmesi kolay olacak şekilde tasarlandı. Doküman okumaya daha az zaman. +* **Kısa**: Kod tekrarını minimize eder. Her parametre tanımından birden fazla özellik. Daha az hata. +* **Sağlam**: Production'a hazır kod elde edersiniz. Otomatik etkileşimli dokümantasyon ile birlikte. +* **Standardlara dayalı**: API'lar için açık standartlara dayalıdır (ve tamamen uyumludur); [OpenAPI](https://github.com/OAI/OpenAPI-Specification) (önceden Swagger olarak biliniyordu) ve [JSON Schema](https://json-schema.org/). -* **Standartlar belirli**: Tamamiyle API'ların açık standartlara bağlı ve (tam uyumlululuk içerisinde); OpenAPI (eski adıyla Swagger) ve JSON Schema. +* tahmin, production uygulamalar geliştiren dahili bir geliştirme ekibinin yaptığı testlere dayanmaktadır. -* Bahsi geçen rakamsal ifadeler tamamiyle, geliştirme takımının kendi sundukları ürünü geliştirirken yaptıkları testlere dayanmakta. - -## Sponsors +## Sponsorlar { #sponsors } -{% if sponsors %} +### Keystone Sponsor { #keystone-sponsor } + +{% for sponsor in sponsors.keystone -%} +
-FastAPI iki devin omuzları üstünde duruyor:
+## CLI'ların FastAPI'ı: **Typer** { #typer-the-fastapi-of-clis }
-* Web tarafı için Starlette.
-* Data tarafı için Pydantic.
+async def...async def kullanalım...uvicorn main:app --reload hakkında...fastapi dev komutu hakkında...email_validator - email doğrulaması için.
+### Ek Opsiyonel Bağımlılıklar { #additional-optional-dependencies }
-Starlette tarafında kullanılan:
+Yüklemek isteyebileceğiniz bazı ek bağımlılıklar da vardır.
-* httpx - Eğer `TestClient` kullanmak istiyorsan gerekli.
-* jinja2 - Eğer kendine ait template konfigürasyonu oluşturmak istiyorsan gerekli
-* python-multipart - Form kullanmak istiyorsan gerekli ("dönüşümü").
-* itsdangerous - `SessionMiddleware` desteği için gerekli.
-* pyyaml - `SchemaGenerator` desteği için gerekli (Muhtemelen FastAPI kullanırken ihtiyacınız olmaz).
-* graphene - `GraphQLApp` desteği için gerekli.
-* ujson - `UJSONResponse` kullanmak istiyorsan gerekli.
+Ek opsiyonel Pydantic bağımlılıkları:
-Hem FastAPI hem de Starlette tarafından kullanılan:
+* [`pydantic-settings`](https://docs.pydantic.dev/latest/usage/pydantic_settings/) - ayar yönetimi için.
+* [`pydantic-extra-types`](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/) - Pydantic ile kullanılacak ek type'lar için.
-* uvicorn - oluşturduğumuz uygulamayı bir web sunucusuna servis etmek için gerekli
-* orjson - `ORJSONResponse` kullanmak istiyor isen gerekli.
+Ek opsiyonel FastAPI bağımlılıkları:
-Bunların hepsini `pip install fastapi[all]` ile yükleyebilirsin.
+* [`orjson`](https://github.com/ijl/orjson) - `ORJSONResponse` kullanmak istiyorsanız gereklidir.
+* [`ujson`](https://github.com/esnme/ultrajson) - `UJSONResponse` kullanmak istiyorsanız gereklidir.
-## Lisans
+## Lisans { #license }
-Bu proje, MIT lisansı şartlarına göre lisanslanmıştır.
+Bu proje MIT lisansı şartları altında lisanslanmıştır.
diff --git a/docs/tr/docs/learn/index.md b/docs/tr/docs/learn/index.md
new file mode 100644
index 0000000000000..accf971aa791a
--- /dev/null
+++ b/docs/tr/docs/learn/index.md
@@ -0,0 +1,5 @@
+# Öğren { #learn }
+
+**FastAPI** öğrenmek için giriş bölümleri ve öğreticiler burada yer alıyor.
+
+Burayı, bir **kitap**, bir **kurs**, FastAPI öğrenmenin **resmi** ve önerilen yolu olarak düşünebilirsiniz. 😎
diff --git a/docs/tr/docs/project-generation.md b/docs/tr/docs/project-generation.md
new file mode 100644
index 0000000000000..6c73a942d8823
--- /dev/null
+++ b/docs/tr/docs/project-generation.md
@@ -0,0 +1,28 @@
+# Full Stack FastAPI Şablonu { #full-stack-fastapi-template }
+
+Şablonlar genellikle belirli bir kurulumla gelir, ancak esnek ve özelleştirilebilir olacak şekilde tasarlanırlar. Bu sayede şablonu projenizin gereksinimlerine göre değiştirip uyarlayabilir, çok iyi bir başlangıç noktası olarak kullanabilirsiniz. 🏁
+
+Bu şablonu başlangıç için kullanabilirsiniz; çünkü ilk kurulumun, güvenliğin, veritabanının ve bazı API endpoint'lerinin önemli bir kısmı sizin için zaten hazırlanmıştır.
+
+GitHub Repository: [Full Stack FastAPI Şablonu](https://github.com/tiangolo/full-stack-fastapi-template)
+
+## Full Stack FastAPI Şablonu - Teknoloji Yığını ve Özellikler { #full-stack-fastapi-template-technology-stack-and-features }
+
+- ⚡ Python backend API için [**FastAPI**](https://fastapi.tiangolo.com/tr).
+ - 🧰 Python SQL veritabanı etkileşimleri (ORM) için [SQLModel](https://sqlmodel.tiangolo.com).
+ - 🔍 FastAPI'nin kullandığı; veri doğrulama ve ayarlar yönetimi için [Pydantic](https://docs.pydantic.dev).
+ - 💾 SQL veritabanı olarak [PostgreSQL](https://www.postgresql.org).
+- 🚀 frontend için [React](https://react.dev).
+ - 💃 TypeScript, hooks, Vite ve modern bir frontend stack'inin diğer parçalarını kullanır.
+ - 🎨 frontend component'leri için [Tailwind CSS](https://tailwindcss.com) ve [shadcn/ui](https://ui.shadcn.com).
+ - 🤖 Otomatik üretilen bir frontend client.
+ - 🧪 End-to-End testleri için [Playwright](https://playwright.dev).
+ - 🦇 Dark mode desteği.
+- 🐋 Geliştirme ve production için [Docker Compose](https://www.docker.com).
+- 🔒 Varsayılan olarak güvenli password hashing.
+- 🔑 JWT (JSON Web Token) authentication.
+- 📫 E-posta tabanlı şifre kurtarma.
+- ✅ [Pytest](https://pytest.org) ile testler.
+- 📞 Reverse proxy / load balancer olarak [Traefik](https://traefik.io).
+- 🚢 Docker Compose kullanarak deployment talimatları; otomatik HTTPS sertifikalarını yönetmek için bir frontend Traefik proxy'sini nasıl kuracağınız dahil.
+- 🏭 GitHub Actions tabanlı CI (continuous integration) ve CD (continuous deployment).
diff --git a/docs/tr/docs/python-types.md b/docs/tr/docs/python-types.md
index 3b9ab905079e5..48aab1dcfcc22 100644
--- a/docs/tr/docs/python-types.md
+++ b/docs/tr/docs/python-types.md
@@ -1,75 +1,74 @@
-# Python Veri Tiplerine Giriş
+# Python Tiplerine Giriş { #python-types-intro }
-Python isteğe bağlı olarak "tip belirteçlerini" destekler.
+Python, isteğe bağlı "type hints" (diğer adıyla "type annotations") desteğine sahiptir.
- **"Tip belirteçleri"** bir değişkenin tipinin belirtilmesine olanak sağlayan özel bir sözdizimidir.
+Bu **"type hints"** veya annotations, bir değişkenin tip'ini bildirmeye yarayan özel bir sözdizimidir.
-Değişkenlerin tiplerini belirterek editör ve araçlardan daha fazla destek alabilirsiniz.
+Değişkenleriniz için tip bildirerek, editörler ve araçlar size daha iyi destek sağlayabilir.
-Bu pythonda tip belirteçleri için **hızlı bir başlangıç / bilgi tazeleme** rehberidir . Bu rehber **FastAPI** kullanmak için gereken minimum konuyu kapsar ki bu da çok az bir miktardır.
+Bu, Python type hints hakkında sadece **hızlı bir eğitim / bilgi tazeleme** dokümanıdır. **FastAPI** ile kullanmak için gereken minimum bilgiyi kapsar... ki aslında bu çok azdır.
-**FastAPI' nin** tamamı bu tür tip belirteçleri ile donatılmıştır ve birçok avantaj sağlamaktadır.
+**FastAPI** tamamen bu type hints üzerine kuruludur; bunlar ona birçok avantaj ve fayda sağlar.
-**FastAPI** kullanmayacak olsanız bile tür belirteçleri hakkında bilgi edinmenizde fayda var.
+Ancak hiç **FastAPI** kullanmasanız bile, bunlar hakkında biraz öğrenmeniz size fayda sağlayacaktır.
-!!! not
- Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, sonraki bölüme geçin.
+/// note | Not
-## Motivasyon
+Eğer bir Python uzmanıysanız ve type hints hakkında her şeyi zaten biliyorsanız, sonraki bölüme geçin.
-Basit bir örnek ile başlayalım:
+///
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+## Motivasyon { #motivation }
+
+Basit bir örnekle başlayalım:
+
+{* ../../docs_src/python_types/tutorial001_py310.py *}
-Programın çıktısı:
+Bu programı çalıştırınca şu çıktıyı alırsınız:
```
John Doe
```
-Fonksiyon sırayla şunları yapar:
+Fonksiyon şunları yapar:
* `first_name` ve `last_name` değerlerini alır.
-* `title()` ile değişkenlerin ilk karakterlerini büyütür.
-* Değişkenleri aralarında bir boşlukla beraber Birleştirir.
+* `title()` ile her birinin ilk harfini büyük harfe çevirir.
+* Ortada bir boşluk olacak şekilde Birleştirir.
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}
-### Düzenle
+### Düzenleyelim { #edit-it }
Bu çok basit bir program.
-Ama şimdi sıfırdan yazdığınızı hayal edin.
+Ama şimdi bunu sıfırdan yazdığınızı hayal edin.
-Bir noktada fonksiyonun tanımına başlayacaktınız, parametreleri hazır hale getirdiniz...
+Bir noktada fonksiyon tanımını yazmaya başlamış olacaktınız, parametreler hazır...
-Ama sonra "ilk harfi büyük harfe dönüştüren yöntemi" çağırmanız gerekir.
+Ama sonra "ilk harfi büyük harfe çeviren method"u çağırmanız gerekiyor.
- `upper` mıydı ? Yoksa `uppercase`' mi? `first_uppercase`? `capitalize`?
+`upper` mıydı? `uppercase` miydi? `first_uppercase`? `capitalize`?
-Ardından, programcıların en iyi arkadaşı olan otomatik tamamlama ile denediniz.
+Sonra eski programcı dostuyla denersiniz: editör autocomplete.
-'first_name', ardından bir nokta ('.') yazıp otomatik tamamlamayı tetiklemek için 'Ctrl+Space' tuşlarına bastınız.
+Fonksiyonun ilk parametresi olan `first_name`'i yazarsınız, sonra bir nokta (`.`) ve ardından autocomplete'i tetiklemek için `Ctrl+Space`'e basarsınız.
-Ancak, ne yazık ki, yararlı hiçbir şey elde edemediniz:
+Ama ne yazık ki, işe yarar bir şey göremezsiniz:
-### Tipleri ekle
+### Tipleri ekleyelim { #add-types }
-Önceki sürümden sadece bir satırı değiştirelim.
+Önceki sürümden tek bir satırı değiştirelim.
-Tam olarak bu parçayı, işlevin parametrelerini değiştireceğiz:
+Fonksiyonun parametreleri olan şu parçayı:
```Python
first_name, last_name
```
-ve bu hale getireceğiz:
+şuna çevireceğiz:
```Python
first_name: str, last_name: str
@@ -77,61 +76,55 @@ ve bu hale getireceğiz:
Bu kadar.
-İşte bunlar "tip belirteçleri":
+Bunlar "type hints":
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
-Bu, aşağıdaki gibi varsayılan değerleri bildirmekle aynı şey değildir:
+Bu, aşağıdaki gibi default değerler bildirmekle aynı şey değildir:
```Python
first_name="john", last_name="doe"
```
-Bu tamamen farklı birşey
+Bu farklı bir şey.
-İki nokta üst üste (`:`) kullanıyoruz , eşittir (`=`) değil.
+Eşittir (`=`) değil, iki nokta (`:`) kullanıyoruz.
-Normalde tip belirteçleri eklemek, kod üzerinde olacakları değiştirmez.
+Ve type hints eklemek, normalde onlarsız ne oluyorsa onu değiştirmez.
-Şimdi programı sıfırdan birdaha yazdığınızı hayal edin.
+Ama şimdi, type hints ile o fonksiyonu oluşturmanın ortasında olduğunuzu tekrar hayal edin.
-Aynı noktada, `Ctrl+Space` ile otomatik tamamlamayı tetiklediniz ve şunu görüyorsunuz:
+Aynı noktada, `Ctrl+Space` ile autocomplete'i tetiklemeye çalışırsınız ve şunu görürsünüz:
-Aradığınızı bulana kadar seçenekleri kaydırabilirsiniz:
+Bununla birlikte, seçenekleri görerek kaydırabilirsiniz; ta ki "tanıdık gelen" seçeneği bulana kadar:
-## Daha fazla motivasyon
+## Daha fazla motivasyon { #more-motivation }
-Bu fonksiyon, zaten tür belirteçlerine sahip:
+Şu fonksiyona bakın, zaten type hints içeriyor:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
-Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama değil, hata kontrolleri de sağlar:
+Editör değişkenlerin tiplerini bildiği için, sadece completion değil, aynı zamanda hata kontrolleri de alırsınız:
-Artık `age` değişkenini `str(age)` olarak kullanmanız gerektiğini biliyorsunuz:
+Artık bunu düzeltmeniz gerektiğini, `age`'i `str(age)` ile string'e çevirmeniz gerektiğini biliyorsunuz:
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
-## Tip bildirme
+## Tipleri Bildirmek { #declaring-types }
-Az önce tip belirteçlerinin en çok kullanıldığı yeri gördünüz.
+Type hints bildirmek için ana yeri az önce gördünüz: fonksiyon parametreleri.
- **FastAPI**ile çalışırken tip belirteçlerini en çok kullanacağımız yer yine fonksiyonlardır.
+Bu, **FastAPI** ile kullanırken de onları en çok kullanacağınız yerdir.
-### Basit tipler
+### Basit tipler { #simple-types }
-Yalnızca `str` değil, tüm standart Python tiplerinin bildirebilirsiniz.
+Sadece `str` değil, tüm standart Python tiplerini bildirebilirsiniz.
Örneğin şunları kullanabilirsiniz:
@@ -140,175 +133,216 @@ Yalnızca `str` değil, tüm standart Python tiplerinin bildirebilirsiniz.
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
+
+### `typing` modülü { #typing-module }
+
+Bazı ek kullanım durumları için standart kütüphanedeki `typing` modülünden bazı şeyleri import etmeniz gerekebilir. Örneğin bir şeyin "herhangi bir tip" olabileceğini bildirmek istediğinizde, `typing` içindeki `Any`'yi kullanabilirsiniz:
+
+```python
+from typing import Any
+
+
+def some_function(data: Any):
+ print(data)
```
-### Tip parametreleri ile Generic tipler
+### Generic tipler { #generic-types }
-"dict", "list", "set" ve "tuple" gibi diğer değerleri içerebilen bazı veri yapıları vardır. Ve dahili değerlerinin de tip belirtecleri olabilir.
+Bazı tipler, köşeli parantez içinde "type parameters" alarak iç tiplerini tanımlayabilir; örneğin "string listesi" `list[str]` olarak bildirilir.
-Bu tipleri ve dahili tpileri bildirmek için standart Python modülünü "typing" kullanabilirsiniz.
+Bu şekilde type parameter alabilen tiplere **Generic types** veya **Generics** denir.
-Bu tür tip belirteçlerini desteklemek için özel olarak mevcuttur.
+Aynı builtin tipleri generics olarak kullanabilirsiniz (köşeli parantez ve içinde tiplerle):
-#### `List`
+* `list`
+* `tuple`
+* `set`
+* `dict`
-Örneğin `str` değerlerden oluşan bir `list` tanımlayalım.
+#### List { #list }
-From `typing`, import `List` (büyük harf olan `L` ile):
+Örneğin, `str`'lerden oluşan bir `list` olan bir değişken tanımlayalım.
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+Değişkeni, aynı iki nokta (`:`) sözdizimiyle bildirin.
-Değişkenin tipini yine iki nokta üstüste (`:`) ile belirleyin.
+Tip olarak `list` yazın.
-tip olarak `List` kullanın.
+`list`, bazı iç tipleri barındıran bir tip olduğundan, bunları köşeli parantez içine yazarsınız:
-Liste, bazı dahili tipleri içeren bir tür olduğundan, bunları köşeli parantez içine alırsınız:
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
-```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+/// info | Bilgi
+
+Köşeli parantez içindeki bu iç tiplere "type parameters" denir.
-!!! ipucu
- Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir.
+Bu durumda `str`, `list`'e verilen type parameter'dır.
- Bu durumda `str`, `List`e iletilen tür parametresidir.
+///
-Bunun anlamı şudur: "`items` değişkeni bir `list`tir ve bu listedeki öğelerin her biri bir `str`dir".
+Bu şu demektir: "`items` değişkeni bir `list` ve bu listedeki her bir öğe `str`".
-Bunu yaparak, düzenleyicinizin listedeki öğeleri işlerken bile destek sağlamasını sağlayabilirsiniz:
+Bunu yaparak, editörünüz listeden öğeleri işlerken bile destek sağlayabilir:
-Tip belirteçleri olmadan, bunu başarmak neredeyse imkansızdır.
+Tipler olmadan, bunu başarmak neredeyse imkansızdır.
-`item` değişkeninin `items` listesindeki öğelerden biri olduğuna dikkat edin.
+`item` değişkeninin, `items` listesindeki elemanlardan biri olduğuna dikkat edin.
-Ve yine, editör bunun bir `str` olduğunu biliyor ve bunun için destek sağlıyor.
+Ve yine de editör bunun bir `str` olduğunu bilir ve buna göre destek sağlar.
-#### `Tuple` ve `Set`
+#### Tuple ve Set { #tuple-and-set }
-`Tuple` ve `set`lerin tiplerini bildirmek için de aynısını yapıyoruz:
+`tuple`'ları ve `set`'leri bildirmek için de aynısını yaparsınız:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
-```
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
-Bu şu anlama geliyor:
+Bu şu anlama gelir:
-* `items_t` değişkeni sırasıyla `int`, `int`, ve `str` tiplerinden oluşan bir `tuple` türündedir .
-* `items_s` ise her öğesi `bytes` türünde olan bir `set` örneğidir.
+* `items_t` değişkeni 3 öğeli bir `tuple`'dır: bir `int`, bir başka `int` ve bir `str`.
+* `items_s` değişkeni bir `set`'tir ve her bir öğesi `bytes` tipindedir.
-#### `Dict`
+#### Dict { #dict }
-Bir `dict` tanımlamak için virgülle ayrılmış iki parametre verebilirsiniz.
+Bir `dict` tanımlamak için, virgülle ayrılmış 2 type parameter verirsiniz.
-İlk tip parametresi `dict` değerinin `key` değeri içindir.
+İlk type parameter, `dict`'in key'leri içindir.
-İkinci parametre ise `dict` değerinin `value` değeri içindir:
+İkinci type parameter, `dict`'in value'ları içindir:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
-```
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
Bu şu anlama gelir:
-* `prices` değişkeni `dict` tipindedir:
- * `dict` değişkeninin `key` değeri `str` tipindedir (herbir item'ın "name" değeri).
- * `dict` değişkeninin `value` değeri `float` tipindedir (lherbir item'ın "price" değeri).
+* `prices` değişkeni bir `dict`'tir:
+ * Bu `dict`'in key'leri `str` tipindedir (örneğin her bir öğenin adı).
+ * Bu `dict`'in value'ları `float` tipindedir (örneğin her bir öğenin fiyatı).
+
+#### Union { #union }
-#### `Optional`
+Bir değişkenin **birkaç tipten herhangi biri** olabileceğini bildirebilirsiniz; örneğin bir `int` veya bir `str`.
-`Optional` bir değişkenin `str`gibi bir tipi olabileceğini ama isteğe bağlı olarak tipinin `None` olabileceğini belirtir:
+Bunu tanımlamak için, her iki tipi ayırmak üzere dikey çizgi (`|`) kullanırsınız.
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+Buna "union" denir, çünkü değişken bu iki tip kümesinin birleşimindeki herhangi bir şey olabilir.
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
```
-`str` yerine `Optional[str]` kullanmak editorün bu değerin her zaman `str` tipinde değil bazen `None` tipinde de olabileceğini belirtir ve hataları tespit etmemizde yardımcı olur.
+Bu, `item`'ın `int` veya `str` olabileceği anlamına gelir.
-#### Generic tipler
+#### Muhtemelen `None` { #possibly-none }
-Köşeli parantez içinde tip parametreleri alan bu türler, örneğin:
+Bir değerin `str` gibi bir tipi olabileceğini ama aynı zamanda `None` da olabileceğini bildirebilirsiniz.
-* `List`
-* `Tuple`
-* `Set`
-* `Dict`
-* `Optional`
-* ...and others.
+//// tab | Python 3.10+
-**Generic types** yada **Generics** olarak adlandırılır.
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
-### Tip olarak Sınıflar
+////
-Bir değişkenin tipini bir sınıf ile bildirebilirsiniz.
+Sadece `str` yerine `str | None` kullanmak, aslında değer `None` olabilecekken her zaman `str` olduğunu varsaydığınız hataları editörün yakalamanıza yardımcı olur.
-Diyelim ki `name` değerine sahip `Person` sınıfınız var:
+### Tip olarak sınıflar { #classes-as-types }
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+Bir sınıfı da bir değişkenin tipi olarak bildirebilirsiniz.
-Sonra bir değişkeni 'Person' tipinde tanımlayabilirsiniz:
+Örneğin, adı olan bir `Person` sınıfınız olsun:
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
+
+Sonra bir değişkeni `Person` tipinde olacak şekilde bildirebilirsiniz:
-Ve yine bütün editör desteğini alırsınız:
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
+
+Ve sonra, yine tüm editör desteğini alırsınız:
-## Pydantic modelleri
+Bunun "`one_person`, `Person` sınıfının bir **instance**'ıdır" anlamına geldiğine dikkat edin.
-Pydantic veri doğrulaması yapmak için bir Python kütüphanesidir.
+"`one_person`, `Person` adlı **class**'tır" anlamına gelmez.
-Verilerin "biçimini" niteliklere sahip sınıflar olarak düzenlersiniz.
+## Pydantic modelleri { #pydantic-models }
-Ve her niteliğin bir türü vardır.
+[Pydantic](https://docs.pydantic.dev/), data validation yapmak için bir Python kütüphanesidir.
-Sınıfın bazı değerlerle bir örneğini oluşturursunuz ve değerleri doğrular, bunları uygun türe dönüştürür ve size tüm verileri içeren bir nesne verir.
+Verinin "shape"'ini attribute'lara sahip sınıflar olarak tanımlarsınız.
-Ve ortaya çıkan nesne üzerindeki bütün editör desteğini alırsınız.
+Ve her attribute'un bir tipi vardır.
-Resmi Pydantic dokümanlarından alınmıştır:
+Ardından o sınıfın bir instance'ını bazı değerlerle oluşturursunuz; bu değerleri doğrular, uygun tipe dönüştürür (gerekliyse) ve size tüm veriyi içeren bir nesne verir.
-```Python
-{!../../../docs_src/python_types/tutorial011.py!}
-```
+Ve bu ortaya çıkan nesne ile tüm editör desteğini alırsınız.
+
+Resmî Pydantic dokümanlarından bir örnek:
+
+{* ../../docs_src/python_types/tutorial011_py310.py *}
+
+/// info | Bilgi
+
+Daha fazlasını öğrenmek için [Pydantic'in dokümanlarına bakın](https://docs.pydantic.dev/).
+
+///
+
+**FastAPI** tamamen Pydantic üzerine kuruludur.
+
+Bunların pratikte nasıl çalıştığını [Eğitim - Kullanım Kılavuzu](tutorial/index.md) içinde çok daha fazla göreceksiniz.
+
+## Metadata Annotations ile Type Hints { #type-hints-with-metadata-annotations }
+
+Python'da ayrıca, `Annotated` kullanarak bu type hints içine **ek üstveri** koymayı sağlayan bir özellik de vardır.
+
+`Annotated`'ı `typing` içinden import edebilirsiniz.
+
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
+
+Python'un kendisi bu `Annotated` ile bir şey yapmaz. Editörler ve diğer araçlar için tip hâlâ `str`'dir.
+
+Ama **FastAPI**'ye uygulamanızın nasıl davranmasını istediğinize dair ek metadata sağlamak için `Annotated` içindeki bu alanı kullanabilirsiniz.
+
+Hatırlanması gereken önemli nokta: `Annotated`'a verdiğiniz **ilk *type parameter***, **gerçek tip**tir. Geri kalanı ise diğer araçlar için metadatadır.
+
+Şimdilik, sadece `Annotated`'ın var olduğunu ve bunun standart Python olduğunu bilmeniz yeterli. 😎
+
+İleride bunun ne kadar **güçlü** olabildiğini göreceksiniz.
+
+/// tip | İpucu
+
+Bunun **standart Python** olması, editörünüzde mümkün olan **en iyi developer experience**'ı almaya devam edeceğiniz anlamına gelir; kodu analiz etmek ve refactor etmek için kullandığınız araçlarla da, vb. ✨
+
+Ayrıca kodunuzun pek çok başka Python aracı ve kütüphanesiyle çok uyumlu olacağı anlamına gelir. 🚀
-!!! info
- Daha fazla şey öğrenmek için Pydantic'i takip edin.
+///
-**FastAPI** tamamen Pydantic'e dayanmaktadır.
+## **FastAPI**'de type hints { #type-hints-in-fastapi }
-Daha fazlasini görmek için [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}.
+**FastAPI**, birkaç şey yapmak için bu type hints'ten faydalanır.
-## **FastAPI** tip belirteçleri
+**FastAPI** ile type hints kullanarak parametreleri bildirirsiniz ve şunları elde edersiniz:
-**FastAPI** birkaç şey yapmak için bu tür tip belirteçlerinden faydalanır.
+* **Editör desteği**.
+* **Tip kontrolleri**.
-**FastAPI** ile parametre tiplerini bildirirsiniz ve şunları elde edersiniz:
+...ve **FastAPI** aynı bildirimleri şunlar için de kullanır:
-* **Editor desteği**.
-* **Tip kontrolü**.
+* **Gereksinimleri tanımlamak**: request path parameters, query parameters, headers, bodies, bağımlılıklar (dependencies), vb.
+* **Veriyi dönüştürmek**: request'ten gerekli tipe.
+* **Veriyi doğrulamak**: her request'ten gelen veriyi:
+ * Veri geçersiz olduğunda client'a dönen **otomatik hatalar** üretmek.
+* OpenAPI kullanarak API'yi **dokümante etmek**:
+ * bu, daha sonra otomatik etkileşimli dokümantasyon kullanıcı arayüzleri tarafından kullanılır.
-...ve **FastAPI** aynı belirteçleri şunlar için de kullanıyor:
+Bunların hepsi kulağa soyut gelebilir. Merak etmeyin. Tüm bunları [Eğitim - Kullanım Kılavuzu](tutorial/index.md) içinde çalışırken göreceksiniz.
-* **Gereksinimleri tanımlama**: request path parameters, query parameters, headers, bodies, dependencies, ve benzeri gereksinimlerden
-* **Verileri çevirme**: Gönderilen veri tipinden istenilen veri tipine çevirme.
-* **Verileri doğrulama**: Her gönderilen verinin:
- * doğrulanması ve geçersiz olduğunda **otomatik hata** oluşturma.
-* OpenAPI kullanarak apinizi **Belgeleyin** :
- * bu daha sonra otomatik etkileşimli dokümantasyon kullanıcı arayüzü tarafından kullanılır.
+Önemli olan, standart Python tiplerini tek bir yerde kullanarak (daha fazla sınıf, decorator vb. eklemek yerine), **FastAPI**'nin sizin için işin büyük kısmını yapmasıdır.
-Bütün bunlar kulağa soyut gelebilir. Merak etme. Tüm bunları çalışırken göreceksiniz. [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}.
+/// info | Bilgi
-Önemli olan, standart Python türlerini tek bir yerde kullanarak (daha fazla sınıf, dekoratör vb. eklemek yerine), **FastAPI**'nin bizim için işi yapmasını sağlamak.
+Tüm tutorial'ı zaten bitirdiyseniz ve tipler hakkında daha fazlasını görmek için geri döndüyseniz, iyi bir kaynak: [`mypy`'nin "cheat sheet"i](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html).
-!!! info
- Tüm öğreticiyi zaten okuduysanız ve türler hakkında daha fazla bilgi için geri döndüyseniz, iyi bir kaynak: the "cheat sheet" from `mypy`.
+///
diff --git a/docs/tr/docs/resources/index.md b/docs/tr/docs/resources/index.md
new file mode 100644
index 0000000000000..884052f79c25f
--- /dev/null
+++ b/docs/tr/docs/resources/index.md
@@ -0,0 +1,3 @@
+# Kaynaklar { #resources }
+
+Ek kaynaklar, dış bağlantılar ve daha fazlası. ✈️
diff --git a/docs/tr/docs/translation-banner.md b/docs/tr/docs/translation-banner.md
new file mode 100644
index 0000000000000..7491e61b8df4d
--- /dev/null
+++ b/docs/tr/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 Yapay Zekâ ve İnsanlar Tarafından Çeviri
+
+Bu çeviri, insanlar tarafından yönlendirilen bir yapay zekâ ile oluşturuldu. 🤝
+
+Orijinal anlamın yanlış anlaşılması ya da kulağa doğal gelmeme gibi hatalar içerebilir. 🤖
+
+[Yapay zekâ LLM'ini daha iyi yönlendirmemize yardımcı olarak](https://fastapi.tiangolo.com/tr/contributing/#translations) bu çeviriyi iyileştirebilirsiniz.
+
+[İngilizce sürüm](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/tr/docs/tutorial/background-tasks.md b/docs/tr/docs/tutorial/background-tasks.md
new file mode 100644
index 0000000000000..46e0efb811713
--- /dev/null
+++ b/docs/tr/docs/tutorial/background-tasks.md
@@ -0,0 +1,84 @@
+# Arka Plan Görevleri { #background-tasks }
+
+Response döndürüldükten *sonra* çalıştırılacak arka plan görevleri tanımlayabilirsiniz.
+
+Bu, request’ten sonra yapılması gereken; ancak client’ın response’u almadan önce tamamlanmasını beklemesine gerek olmayan işlemler için kullanışlıdır.
+
+Örneğin:
+
+* Bir işlem gerçekleştirdikten sonra gönderilen email bildirimleri:
+ * Bir email server’a bağlanmak ve email göndermek genellikle "yavaş" olduğundan (birkaç saniye), response’u hemen döndürüp email bildirimini arka planda gönderebilirsiniz.
+* Veri işleme:
+ * Örneğin, yavaş bir süreçten geçmesi gereken bir dosya aldığınızı düşünün; "Accepted" (HTTP 202) response’u döndürüp dosyayı arka planda işleyebilirsiniz.
+
+## `BackgroundTasks` Kullanımı { #using-backgroundtasks }
+
+Önce `BackgroundTasks`’i import edin ve *path operation function*’ınızda `BackgroundTasks` tip bildirimi olan bir parametre tanımlayın:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
+
+**FastAPI**, sizin için `BackgroundTasks` tipinde bir obje oluşturur ve onu ilgili parametre olarak geçirir.
+
+## Bir Görev Fonksiyonu Oluşturun { #create-a-task-function }
+
+Arka plan görevi olarak çalıştırılacak bir fonksiyon oluşturun.
+
+Bu, parametre alabilen standart bir fonksiyondur.
+
+`async def` de olabilir, normal `def` de olabilir; **FastAPI** bunu doğru şekilde nasıl ele alacağını bilir.
+
+Bu örnekte görev fonksiyonu bir dosyaya yazacaktır (email göndermeyi simüle ediyor).
+
+Ve yazma işlemi `async` ve `await` kullanmadığı için fonksiyonu normal `def` ile tanımlarız:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
+
+## Arka Plan Görevini Ekleyin { #add-the-background-task }
+
+*Path operation function*’ınızın içinde, görev fonksiyonunuzu `.add_task()` metodu ile *background tasks* objesine ekleyin:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
+
+`.add_task()` şu argümanları alır:
+
+* Arka planda çalıştırılacak bir görev fonksiyonu (`write_notification`).
+* Görev fonksiyonuna sırayla geçirilecek argümanlar (`email`).
+* Görev fonksiyonuna geçirilecek keyword argümanlar (`message="some notification"`).
+
+## Dependency Injection { #dependency-injection }
+
+`BackgroundTasks` kullanımı dependency injection sistemiyle de çalışır; `BackgroundTasks` tipinde bir parametreyi birden fazla seviyede tanımlayabilirsiniz: bir *path operation function* içinde, bir dependency’de (dependable), bir sub-dependency’de, vb.
+
+**FastAPI** her durumda ne yapılacağını ve aynı objenin nasıl yeniden kullanılacağını bilir; böylece tüm arka plan görevleri birleştirilir ve sonrasında arka planda çalıştırılır:
+
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
+
+Bu örnekte, response gönderildikten *sonra* mesajlar `log.txt` dosyasına yazılacaktır.
+
+Request’te bir query varsa, log’a bir arka plan göreviyle yazılır.
+
+Ardından *path operation function* içinde oluşturulan başka bir arka plan görevi, `email` path parametresini kullanarak bir mesaj yazar.
+
+## Teknik Detaylar { #technical-details }
+
+`BackgroundTasks` sınıfı doğrudan [`starlette.background`](https://www.starlette.dev/background/)’dan gelir.
+
+`fastapi` üzerinden import edebilmeniz ve yanlışlıkla `starlette.background` içindeki alternatif `BackgroundTask`’i (sonunda `s` olmadan) import etmemeniz için FastAPI’nin içine doğrudan import/eklenmiştir.
+
+Sadece `BackgroundTasks` (ve `BackgroundTask` değil) kullanarak, bunu bir *path operation function* parametresi olarak kullanmak ve gerisini **FastAPI**’nin sizin için halletmesini sağlamak mümkündür; tıpkı `Request` objesini doğrudan kullanırken olduğu gibi.
+
+FastAPI’de `BackgroundTask`’i tek başına kullanmak hâlâ mümkündür; ancak bu durumda objeyi kendi kodunuzda oluşturmanız ve onu içeren bir Starlette `Response` döndürmeniz gerekir.
+
+Daha fazla detayı [Starlette’in Background Tasks için resmi dokümantasyonunda](https://www.starlette.dev/background/) görebilirsiniz.
+
+## Dikkat Edilmesi Gerekenler { #caveat }
+
+Yoğun arka plan hesaplamaları yapmanız gerekiyorsa ve bunun aynı process tarafından çalıştırılmasına şart yoksa (örneğin memory, değişkenler vb. paylaşmanız gerekmiyorsa), [Celery](https://docs.celeryq.dev) gibi daha büyük araçları kullanmak size fayda sağlayabilir.
+
+Bunlar genellikle daha karmaşık konfigurasyonlar ve RabbitMQ veya Redis gibi bir mesaj/iş kuyruğu yöneticisi gerektirir; ancak arka plan görevlerini birden fazla process’te ve özellikle birden fazla server’da çalıştırmanıza olanak tanırlar.
+
+Ancak aynı **FastAPI** app’i içindeki değişkenlere ve objelere erişmeniz gerekiyorsa veya küçük arka plan görevleri (email bildirimi göndermek gibi) yapacaksanız, doğrudan `BackgroundTasks` kullanabilirsiniz.
+
+## Özet { #recap }
+
+Arka plan görevleri eklemek için *path operation function*’larda ve dependency’lerde parametre olarak `BackgroundTasks`’i import edip kullanın.
diff --git a/docs/tr/docs/tutorial/bigger-applications.md b/docs/tr/docs/tutorial/bigger-applications.md
new file mode 100644
index 0000000000000..1ecce6018e0fc
--- /dev/null
+++ b/docs/tr/docs/tutorial/bigger-applications.md
@@ -0,0 +1,535 @@
+# Daha Büyük Uygulamalar - Birden Fazla Dosya { #bigger-applications-multiple-files }
+
+Bir uygulama veya web API geliştirirken, her şeyi tek bir dosyaya sığdırabilmek nadirdir.
+
+**FastAPI**, tüm esnekliği korurken uygulamanızı yapılandırmanıza yardımcı olan pratik bir araç sunar.
+
+/// info | Bilgi
+
+Flask'ten geliyorsanız, bu yapı Flask'in Blueprints'ine denk gelir.
+
+///
+
+## Örnek Bir Dosya Yapısı { #an-example-file-structure }
+
+Diyelim ki şöyle bir dosya yapınız var:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ ├── dependencies.py
+│ └── routers
+│ │ ├── __init__.py
+│ │ ├── items.py
+│ │ └── users.py
+│ └── internal
+│ ├── __init__.py
+│ └── admin.py
+```
+
+/// tip | İpucu
+
+Birden fazla `__init__.py` dosyası var: her dizinde veya alt dizinde bir tane.
+
+Bu sayede bir dosyadaki kodu diğerine import edebilirsiniz.
+
+Örneğin `app/main.py` içinde şöyle bir satırınız olabilir:
+
+```
+from app.routers import items
+```
+
+///
+
+* `app` dizini her şeyi içerir. Ayrıca boş bir `app/__init__.py` dosyası olduğu için bir "Python package" (bir "Python module" koleksiyonu) olur: `app`.
+* İçinde bir `app/main.py` dosyası vardır. Bir Python package'in (içinde `__init__.py` dosyası olan bir dizinin) içinde olduğundan, o package'in bir "module"’üdür: `app.main`.
+* Benzer şekilde `app/dependencies.py` dosyası da bir "module"’dür: `app.dependencies`.
+* `app/routers/` adında bir alt dizin vardır ve içinde başka bir `__init__.py` dosyası bulunur; dolayısıyla bu bir "Python subpackage"’dir: `app.routers`.
+* `app/routers/items.py` dosyası `app/routers/` package’i içinde olduğundan bir submodule’dür: `app.routers.items`.
+* `app/routers/users.py` için de aynı şekilde, başka bir submodule’dür: `app.routers.users`.
+* `app/internal/` adında bir alt dizin daha vardır ve içinde başka bir `__init__.py` dosyası bulunur; dolayısıyla bu da bir "Python subpackage"’dir: `app.internal`.
+* Ve `app/internal/admin.py` dosyası başka bir submodule’dür: `app.internal.admin`.
+
+
+
+## Aynı Router'ı Farklı `prefix` ile Birden Fazla Kez Dahil Edin { #include-the-same-router-multiple-times-with-different-prefix }
+
+`.include_router()` ile aynı router’ı farklı prefix’ler kullanarak birden fazla kez de dahil edebilirsiniz.
+
+Örneğin aynı API’yi `/api/v1` ve `/api/latest` gibi farklı prefix’ler altında sunmak için faydalı olabilir.
+
+Bu, muhtemelen ihtiyacınız olmayan ileri seviye bir kullanımdır; ancak gerekirse diye mevcut.
+
+## Bir `APIRouter`’ı Başka Birine Dahil Edin { #include-an-apirouter-in-another }
+
+Bir `APIRouter`’ı `FastAPI` uygulamasına dahil ettiğiniz gibi, bir `APIRouter`’ı başka bir `APIRouter`’a da şu şekilde dahil edebilirsiniz:
+
+```Python
+router.include_router(other_router)
+```
+
+`router`’ı `FastAPI` uygulamasına dahil etmeden önce bunu yaptığınızdan emin olun; böylece `other_router` içindeki *path operation*’lar da dahil edilmiş olur.
diff --git a/docs/tr/docs/tutorial/body-fields.md b/docs/tr/docs/tutorial/body-fields.md
new file mode 100644
index 0000000000000..6a0f3314a15ad
--- /dev/null
+++ b/docs/tr/docs/tutorial/body-fields.md
@@ -0,0 +1,60 @@
+# Body - Alanlar { #body-fields }
+
+`Query`, `Path` ve `Body` ile *path operation function* parametrelerinde ek doğrulama ve metadata tanımlayabildiğiniz gibi, Pydantic modellerinin içinde de Pydantic'in `Field`'ını kullanarak doğrulama ve metadata tanımlayabilirsiniz.
+
+## `Field`'ı import edin { #import-field }
+
+Önce import etmeniz gerekir:
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}
+
+/// warning | Uyarı
+
+`Field`'ın, diğerlerinin (`Query`, `Path`, `Body` vb.) aksine `fastapi`'den değil doğrudan `pydantic`'den import edildiğine dikkat edin.
+
+///
+
+## Model attribute'larını tanımlayın { #declare-model-attributes }
+
+Ardından `Field`'ı model attribute'larıyla birlikte kullanabilirsiniz:
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}
+
+`Field`, `Query`, `Path` ve `Body` ile aynı şekilde çalışır; aynı parametrelerin tamamına sahiptir, vb.
+
+/// note | Teknik Detaylar
+
+Aslında, `Query`, `Path` ve birazdan göreceğiniz diğerleri, ortak bir `Param` sınıfının alt sınıflarından nesneler oluşturur; `Param` sınıfı da Pydantic'in `FieldInfo` sınıfının bir alt sınıfıdır.
+
+Pydantic'in `Field`'ı da `FieldInfo`'nun bir instance'ını döndürür.
+
+`Body` ayrıca doğrudan `FieldInfo`'nun bir alt sınıfından nesneler döndürür. Daha sonra göreceğiniz başka bazıları da `Body` sınıfının alt sınıflarıdır.
+
+`fastapi`'den `Query`, `Path` ve diğerlerini import ettiğinizde, bunların aslında özel sınıflar döndüren fonksiyonlar olduğunu unutmayın.
+
+///
+
+/// tip | İpucu
+
+Type, varsayılan değer ve `Field` ile tanımlanan her model attribute'unun yapısının, *path operation function* parametresiyle aynı olduğuna dikkat edin; sadece `Path`, `Query` ve `Body` yerine `Field` kullanılmıştır.
+
+///
+
+## Ek bilgi ekleyin { #add-extra-information }
+
+`Field`, `Query`, `Body` vb. içinde ek bilgi tanımlayabilirsiniz. Bu bilgiler oluşturulan JSON Schema'ya dahil edilir.
+
+Örnek (examples) tanımlamayı öğrenirken, dokümanların ilerleyen kısımlarında ek bilgi ekleme konusunu daha ayrıntılı göreceksiniz.
+
+/// warning | Uyarı
+
+`Field`'a geçirilen ekstra key'ler, uygulamanız için üretilen OpenAPI schema'sında da yer alır.
+Bu key'ler OpenAPI spesifikasyonunun bir parçası olmak zorunda olmadığından, örneğin [OpenAPI validator](https://validator.swagger.io/) gibi bazı OpenAPI araçları üretilen schema'nızla çalışmayabilir.
+
+///
+
+## Özet { #recap }
+
+Model attribute'ları için ek doğrulamalar ve metadata tanımlamak üzere Pydantic'in `Field`'ını kullanabilirsiniz.
+
+Ayrıca, ek keyword argument'ları kullanarak JSON Schema'ya ekstra metadata da iletebilirsiniz.
diff --git a/docs/tr/docs/tutorial/body-multiple-params.md b/docs/tr/docs/tutorial/body-multiple-params.md
new file mode 100644
index 0000000000000..4cd381b8698e3
--- /dev/null
+++ b/docs/tr/docs/tutorial/body-multiple-params.md
@@ -0,0 +1,169 @@
+# Body - Birden Fazla Parametre { #body-multiple-parameters }
+
+Artık `Path` ve `Query` kullanmayı gördüğümüze göre, request body bildirimlerinin daha ileri kullanım senaryolarına bakalım.
+
+## `Path`, `Query` ve body parametrelerini karıştırma { #mix-path-query-and-body-parameters }
+
+Öncelikle, elbette `Path`, `Query` ve request body parametre bildirimlerini serbestçe karıştırabilirsiniz ve **FastAPI** ne yapacağını bilir.
+
+Ayrıca, varsayılan değeri `None` yaparak body parametrelerini opsiyonel olarak da tanımlayabilirsiniz:
+
+{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
+
+/// note | Not
+
+Bu durumda body'den alınacak `item` opsiyoneldir. Çünkü varsayılan değeri `None` olarak ayarlanmıştır.
+
+///
+
+## Birden fazla body parametresi { #multiple-body-parameters }
+
+Önceki örnekte, *path operation*'lar `Item`'ın özelliklerini içeren bir JSON body beklerdi, örneğin:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+
+Ancak birden fazla body parametresi de tanımlayabilirsiniz; örneğin `item` ve `user`:
+
+{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}
+
+
+Bu durumda **FastAPI**, fonksiyonda birden fazla body parametresi olduğunu fark eder (iki parametre de Pydantic modelidir).
+
+Bunun üzerine, body içinde anahtar (field name) olarak parametre adlarını kullanır ve şu şekilde bir body bekler:
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ }
+}
+```
+
+/// note | Not
+
+`item` daha öncekiyle aynı şekilde tanımlanmış olsa bile, artık body içinde `item` anahtarı altında gelmesi beklenir.
+
+///
+
+**FastAPI**, request'ten otomatik dönüşümü yapar; böylece `item` parametresi kendi içeriğini alır, `user` için de aynı şekilde olur.
+
+Birleşik verinin validasyonunu yapar ve OpenAPI şeması ile otomatik dokümantasyonda da bunu bu şekilde dokümante eder.
+
+## Body içinde tekil değerler { #singular-values-in-body }
+
+Query ve path parametreleri için ek veri tanımlamak üzere `Query` ve `Path` olduğu gibi, **FastAPI** bunların karşılığı olarak `Body` de sağlar.
+
+Örneğin, önceki modeli genişleterek, aynı body içinde `item` ve `user` dışında bir de `importance` anahtarı olmasını isteyebilirsiniz.
+
+Bunu olduğu gibi tanımlarsanız, tekil bir değer olduğu için **FastAPI** bunun bir query parametresi olduğunu varsayar.
+
+Ama `Body` kullanarak, **FastAPI**'ye bunu body içinde başka bir anahtar olarak ele almasını söyleyebilirsiniz:
+
+{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
+
+
+Bu durumda **FastAPI** şu şekilde bir body bekler:
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ },
+ "importance": 5
+}
+```
+
+Yine veri tiplerini dönüştürür, validate eder, dokümante eder, vb.
+
+## Birden fazla body parametresi ve query { #multiple-body-params-and-query }
+
+Elbette ihtiyaç duyduğunuzda, body parametrelerine ek olarak query parametreleri de tanımlayabilirsiniz.
+
+Varsayılan olarak tekil değerler query parametresi olarak yorumlandığı için, ayrıca `Query` eklemeniz gerekmez; şöyle yazmanız yeterlidir:
+
+```Python
+q: str | None = None
+```
+
+Örneğin:
+
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
+
+
+/// info | Bilgi
+
+`Body`, `Query`, `Path` ve daha sonra göreceğiniz diğerleriyle aynı ek validasyon ve metadata parametrelerine de sahiptir.
+
+///
+
+## Tek bir body parametresini gömme { #embed-a-single-body-parameter }
+
+Diyelim ki Pydantic'teki `Item` modelinden gelen yalnızca tek bir `item` body parametreniz var.
+
+Varsayılan olarak **FastAPI**, body'nin doğrudan bu modelin içeriği olmasını bekler.
+
+Ancak, ek body parametreleri tanımladığınızda olduğu gibi, `item` anahtarı olan bir JSON ve onun içinde modelin içeriğini beklemesini istiyorsanız, `Body`'nin özel parametresi olan `embed`'i kullanabilirsiniz:
+
+```Python
+item: Item = Body(embed=True)
+```
+
+yani şöyle:
+
+{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}
+
+
+Bu durumda **FastAPI** şu şekilde bir body bekler:
+
+```JSON hl_lines="2"
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ }
+}
+```
+
+şunun yerine:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+
+## Özet { #recap }
+
+Bir request yalnızca tek bir body içerebilse de, *path operation function*'ınıza birden fazla body parametresi ekleyebilirsiniz.
+
+Ancak **FastAPI** bunu yönetir; fonksiyonunuza doğru veriyi verir ve *path operation* içinde doğru şemayı validate edip dokümante eder.
+
+Ayrıca tekil değerlerin body'nin bir parçası olarak alınmasını da tanımlayabilirsiniz.
+
+Ve yalnızca tek bir parametre tanımlanmış olsa bile, **FastAPI**'ye body'yi bir anahtarın içine gömmesini söyleyebilirsiniz.
diff --git a/docs/tr/docs/tutorial/body-nested-models.md b/docs/tr/docs/tutorial/body-nested-models.md
new file mode 100644
index 0000000000000..4f078e035c1d9
--- /dev/null
+++ b/docs/tr/docs/tutorial/body-nested-models.md
@@ -0,0 +1,220 @@
+# Body - İç İçe Modeller { #body-nested-models }
+
+**FastAPI** ile (Pydantic sayesinde) istediğiniz kadar derin iç içe geçmiş modelleri tanımlayabilir, doğrulayabilir, dokümante edebilir ve kullanabilirsiniz.
+
+## List alanları { #list-fields }
+
+Bir attribute’u bir alt tipe sahip olacak şekilde tanımlayabilirsiniz. Örneğin, bir Python `list`:
+
+{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}
+
+Bu, `tags`’in bir list olmasını sağlar; ancak list’in elemanlarının tipini belirtmez.
+
+## Tip parametresi olan list alanları { #list-fields-with-type-parameter }
+
+Ancak Python’da, iç tipleri olan list’leri (ya da "type parameter" içeren tipleri) tanımlamanın belirli bir yolu vardır:
+
+### Tip parametresiyle bir `list` tanımlayın { #declare-a-list-with-a-type-parameter }
+
+`list`, `dict`, `tuple` gibi type parameter (iç tip) alan tipleri tanımlamak için, iç tipi(leri) köşeli parantezlerle "type parameter" olarak verin: `[` ve `]`
+
+```Python
+my_list: list[str]
+```
+
+Bu, tip tanımları için standart Python sözdizimidir.
+
+İç tipleri olan model attribute’ları için de aynı standart sözdizimini kullanın.
+
+Dolayısıyla örneğimizde, `tags`’i özel olarak bir "string list’i" yapabiliriz:
+
+{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}
+
+## Set tipleri { #set-types }
+
+Sonra bunu düşününce, tag’lerin tekrar etmemesi gerektiğini fark ederiz; büyük ihtimalle benzersiz string’ler olmalıdır.
+
+Python’da benzersiz öğelerden oluşan kümeler için özel bir veri tipi vardır: `set`.
+
+O zaman `tags`’i string’lerden oluşan bir set olarak tanımlayabiliriz:
+
+{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}
+
+Böylece duplicate veri içeren bir request alsanız bile, bu veri benzersiz öğelerden oluşan bir set’e dönüştürülür.
+
+Ve bu veriyi ne zaman output etseniz, kaynakta duplicate olsa bile, benzersiz öğelerden oluşan bir set olarak output edilir.
+
+Ayrıca buna göre annotate / dokümante edilir.
+
+## İç İçe Modeller { #nested-models }
+
+Bir Pydantic modelinin her attribute’unun bir tipi vardır.
+
+Ancak bu tip, kendi başına başka bir Pydantic modeli de olabilir.
+
+Yani belirli attribute adları, tipleri ve validation kurallarıyla derin iç içe JSON "object"leri tanımlayabilirsiniz.
+
+Hem de istediğiniz kadar iç içe.
+
+### Bir alt model tanımlayın { #define-a-submodel }
+
+Örneğin bir `Image` modeli tanımlayabiliriz:
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}
+
+### Alt modeli tip olarak kullanın { #use-the-submodel-as-a-type }
+
+Ardından bunu bir attribute’un tipi olarak kullanabiliriz:
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}
+
+Bu da **FastAPI**’nin aşağıdakine benzer bir body bekleyeceği anlamına gelir:
+
+```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"
+ }
+}
+```
+
+Yine, sadece bu tanımı yaparak **FastAPI** ile şunları elde edersiniz:
+
+* Editör desteği (tamamlama vb.), iç içe modeller için bile
+* Veri dönüştürme
+* Veri doğrulama (validation)
+* Otomatik dokümantasyon
+
+## Özel tipler ve doğrulama { #special-types-and-validation }
+
+`str`, `int`, `float` vb. normal tekil tiplerin yanında, `str`’den türeyen daha karmaşık tekil tipleri de kullanabilirsiniz.
+
+Tüm seçenekleri görmek için [Pydantic Türlerine Genel Bakış](https://docs.pydantic.dev/latest/concepts/types/) sayfasına göz atın. Sonraki bölümde bazı örnekleri göreceksiniz.
+
+Örneğin `Image` modelinde bir `url` alanımız olduğuna göre, bunu `str` yerine Pydantic’in `HttpUrl` tipinden bir instance olacak şekilde tanımlayabiliriz:
+
+{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}
+
+String’in geçerli bir URL olup olmadığı kontrol edilir ve JSON Schema / OpenAPI’de de buna göre dokümante edilir.
+
+## Alt modellerden oluşan list’lere sahip attribute’lar { #attributes-with-lists-of-submodels }
+
+Pydantic modellerini `list`, `set` vb. tiplerin alt tipi olarak da kullanabilirsiniz:
+
+{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}
+
+Bu, aşağıdaki gibi bir JSON body bekler (dönüştürür, doğrular, dokümante eder vb.):
+
+```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 | Bilgi
+
+`images` key’inin artık image object’lerinden oluşan bir list içerdiğine dikkat edin.
+
+///
+
+## Çok derin iç içe modeller { #deeply-nested-models }
+
+İstediğiniz kadar derin iç içe modeller tanımlayabilirsiniz:
+
+{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}
+
+/// info | Bilgi
+
+`Offer`’ın bir `Item` list’i olduğuna, `Item`’ların da opsiyonel bir `Image` list’ine sahip olduğuna dikkat edin.
+
+///
+
+## Sadece list olan body’ler { #bodies-of-pure-lists }
+
+Beklediğiniz JSON body’nin en üst seviye değeri bir JSON `array` (Python’da `list`) ise, tipi Pydantic modellerinde olduğu gibi fonksiyonun parametresinde tanımlayabilirsiniz:
+
+```Python
+images: list[Image]
+```
+
+şu örnekte olduğu gibi:
+
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
+
+## Her yerde editör desteği { #editor-support-everywhere }
+
+Ve her yerde editör desteği alırsınız.
+
+List içindeki öğeler için bile:
+
+
+
+Pydantic modelleri yerine doğrudan `dict` ile çalışsaydınız bu tür bir editör desteğini alamazdınız.
+
+Ancak bunlarla uğraşmanız da gerekmez; gelen dict’ler otomatik olarak dönüştürülür ve output’unuz da otomatik olarak JSON’a çevrilir.
+
+## Rastgele `dict` body’leri { #bodies-of-arbitrary-dicts }
+
+Body’yi, key’leri bir tipte ve value’ları başka bir tipte olan bir `dict` olarak da tanımlayabilirsiniz.
+
+Bu şekilde (Pydantic modellerinde olduğu gibi) geçerli field/attribute adlarının önceden ne olduğunu bilmeniz gerekmez.
+
+Bu, önceden bilmediğiniz key’leri almak istediğiniz durumlarda faydalıdır.
+
+---
+
+Bir diğer faydalı durum da key’lerin başka bir tipte olmasını istediğiniz zamandır (ör. `int`).
+
+Burada göreceğimiz şey de bu.
+
+Bu durumda, `int` key’lere ve `float` value’lara sahip olduğu sürece herhangi bir `dict` kabul edersiniz:
+
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
+
+/// tip | İpucu
+
+JSON key olarak yalnızca `str` destekler, bunu unutmayın.
+
+Ancak Pydantic otomatik veri dönüştürme yapar.
+
+Yani API client’larınız key’leri sadece string olarak gönderebilse bile, bu string’ler saf tamsayı içeriyorsa Pydantic bunları dönüştürür ve doğrular.
+
+Ve `weights` olarak aldığınız `dict`, gerçekte `int` key’lere ve `float` value’lara sahip olur.
+
+///
+
+## Özet { #recap }
+
+**FastAPI** ile Pydantic modellerinin sağladığı en yüksek esnekliği elde ederken, kodunuzu da basit, kısa ve şık tutarsınız.
+
+Üstelik tüm avantajlarla birlikte:
+
+* Editör desteği (her yerde tamamlama!)
+* Veri dönüştürme (diğer adıyla parsing / serialization)
+* Veri doğrulama (validation)
+* Schema dokümantasyonu
+* Otomatik dokümanlar
diff --git a/docs/tr/docs/tutorial/body-updates.md b/docs/tr/docs/tutorial/body-updates.md
new file mode 100644
index 0000000000000..27709440ef3f9
--- /dev/null
+++ b/docs/tr/docs/tutorial/body-updates.md
@@ -0,0 +1,100 @@
+# Body - Güncellemeler { #body-updates }
+
+## `PUT` ile değiştirerek güncelleme { #update-replacing-with-put }
+
+Bir öğeyi güncellemek için [HTTP `PUT`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) operasyonunu kullanabilirsiniz.
+
+Girdi verisini JSON olarak saklanabilecek bir formata (ör. bir NoSQL veritabanı ile) dönüştürmek için `jsonable_encoder` kullanabilirsiniz. Örneğin, `datetime` değerlerini `str`'ye çevirmek gibi.
+
+{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}
+
+`PUT`, mevcut verinin yerine geçmesi gereken veriyi almak için kullanılır.
+
+### Değiştirerek güncelleme uyarısı { #warning-about-replacing }
+
+Bu, `bar` öğesini `PUT` ile, body içinde şu verilerle güncellemek isterseniz:
+
+```Python
+{
+ "name": "Barz",
+ "price": 3,
+ "description": None,
+}
+```
+
+zaten kayıtlı olan `"tax": 20.2` alanını içermediği için, input model `"tax": 10.5` varsayılan değerini kullanacaktır.
+
+Ve veri, bu "yeni" `tax` değeri olan `10.5` ile kaydedilecektir.
+
+## `PATCH` ile kısmi güncellemeler { #partial-updates-with-patch }
+
+Veriyi *kısmen* güncellemek için [HTTP `PATCH`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) operasyonunu da kullanabilirsiniz.
+
+Bu, yalnızca güncellemek istediğiniz veriyi gönderip, geri kalanını olduğu gibi bırakabileceğiniz anlamına gelir.
+
+/// note | Not
+
+`PATCH`, `PUT`'a göre daha az yaygın kullanılır ve daha az bilinir.
+
+Hatta birçok ekip, kısmi güncellemeler için bile yalnızca `PUT` kullanır.
+
+Bunları nasıl isterseniz öyle kullanmakta **özgürsünüz**; **FastAPI** herhangi bir kısıtlama dayatmaz.
+
+Ancak bu kılavuz, aşağı yukarı, bunların nasıl kullanılması amaçlandığını gösterir.
+
+///
+
+### Pydantic'in `exclude_unset` parametresini kullanma { #using-pydantics-exclude-unset-parameter }
+
+Kısmi güncellemeler almak istiyorsanız, Pydantic modelinin `.model_dump()` metodundaki `exclude_unset` parametresini kullanmak çok faydalıdır.
+
+Örneğin: `item.model_dump(exclude_unset=True)`.
+
+Bu, `item` modeli oluşturulurken set edilmiş verileri içeren; varsayılan değerleri hariç tutan bir `dict` üretir.
+
+Sonrasında bunu, yalnızca set edilmiş (request'te gönderilmiş) veriyi içeren; varsayılan değerleri atlayan bir `dict` üretmek için kullanabilirsiniz:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}
+
+### Pydantic'in `update` parametresini kullanma { #using-pydantics-update-parameter }
+
+Artık `.model_copy()` ile mevcut modelin bir kopyasını oluşturup, güncellenecek verileri içeren bir `dict` ile `update` parametresini geçebilirsiniz.
+
+Örneğin: `stored_item_model.model_copy(update=update_data)`:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}
+
+### Kısmi güncellemeler özeti { #partial-updates-recap }
+
+Özetle, kısmi güncelleme uygulamak için şunları yaparsınız:
+
+* (İsteğe bağlı olarak) `PUT` yerine `PATCH` kullanın.
+* Kayıtlı veriyi alın.
+* Bu veriyi bir Pydantic modeline koyun.
+* Input modelinden, varsayılan değerler olmadan bir `dict` üretin (`exclude_unset` kullanarak).
+ * Bu şekilde, modelinizdeki varsayılan değerlerle daha önce saklanmış değerlerin üzerine yazmak yerine, yalnızca kullanıcının gerçekten set ettiği değerleri güncellersiniz.
+* Kayıtlı modelin bir kopyasını oluşturun ve alınan kısmi güncellemeleri kullanarak attribute'larını güncelleyin (`update` parametresini kullanarak).
+* Kopyalanan modeli DB'nizde saklanabilecek bir şeye dönüştürün (ör. `jsonable_encoder` kullanarak).
+ * Bu, modelin `.model_dump()` metodunu yeniden kullanmaya benzer; ancak değerlerin JSON'a dönüştürülebilecek veri tiplerine çevrilmesini garanti eder (ör. `datetime` -> `str`).
+* Veriyi DB'nize kaydedin.
+* Güncellenmiş modeli döndürün.
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *}
+
+/// tip | İpucu
+
+Aynı tekniği HTTP `PUT` operasyonu ile de kullanabilirsiniz.
+
+Ancak buradaki örnek `PATCH` kullanıyor, çünkü bu kullanım senaryoları için tasarlanmıştır.
+
+///
+
+/// note | Not
+
+Input modelin yine de doğrulandığına dikkat edin.
+
+Dolayısıyla, tüm attribute'ların atlanabildiği kısmi güncellemeler almak istiyorsanız, tüm attribute'ları optional olarak işaretlenmiş (varsayılan değerlerle veya `None` ile) bir modele ihtiyacınız vardır.
+
+**Güncelleme** için tüm değerleri optional olan modeller ile **oluşturma** için zorunlu değerlere sahip modelleri ayırmak için, [Extra Models](extra-models.md) bölümünde anlatılan fikirleri kullanabilirsiniz.
+
+///
diff --git a/docs/tr/docs/tutorial/body.md b/docs/tr/docs/tutorial/body.md
new file mode 100644
index 0000000000000..26f51ffecaca6
--- /dev/null
+++ b/docs/tr/docs/tutorial/body.md
@@ -0,0 +1,166 @@
+# Request Body { #request-body }
+
+Bir client'ten (örneğin bir tarayıcıdan) API'nize veri göndermeniz gerektiğinde, bunu **request body** olarak gönderirsiniz.
+
+Bir **request** body, client'in API'nize gönderdiği veridir. Bir **response** body ise API'nizin client'e gönderdiği veridir.
+
+API'niz neredeyse her zaman bir **response** body göndermek zorundadır. Ancak client'lerin her zaman **request body** göndermesi gerekmez; bazen sadece bir path isterler, belki birkaç query parametresiyle birlikte, ama body göndermezler.
+
+Bir **request** body tanımlamak için, tüm gücü ve avantajlarıyla [Pydantic](https://docs.pydantic.dev/) modellerini kullanırsınız.
+
+/// info | Bilgi
+
+Veri göndermek için şunlardan birini kullanmalısınız: `POST` (en yaygını), `PUT`, `DELETE` veya `PATCH`.
+
+`GET` request'i ile body göndermek, spesifikasyonlarda tanımsız bir davranıştır; yine de FastAPI bunu yalnızca çok karmaşık/uç kullanım senaryoları için destekler.
+
+Önerilmediği için Swagger UI ile etkileşimli dokümanlar, `GET` kullanırken body için dokümantasyonu göstermez ve aradaki proxy'ler bunu desteklemeyebilir.
+
+///
+
+## Pydantic'in `BaseModel`'ini import edin { #import-pydantics-basemodel }
+
+Önce, `pydantic` içinden `BaseModel`'i import etmeniz gerekir:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[2] *}
+
+## Veri modelinizi oluşturun { #create-your-data-model }
+
+Sonra veri modelinizi, `BaseModel`'den kalıtım alan bir class olarak tanımlarsınız.
+
+Tüm attribute'lar için standart Python type'larını kullanın:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}
+
+
+Query parametrelerini tanımlarken olduğu gibi, bir model attribute'ü default bir değere sahipse zorunlu değildir. Aksi halde zorunludur. Sadece opsiyonel yapmak için `None` kullanın.
+
+Örneğin, yukarıdaki model şu şekilde bir JSON "`object`" (veya Python `dict`) tanımlar:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "An optional description",
+ "price": 45.2,
+ "tax": 3.5
+}
+```
+
+...`description` ve `tax` opsiyonel olduğu için (default değerleri `None`), şu JSON "`object`" da geçerli olur:
+
+```JSON
+{
+ "name": "Foo",
+ "price": 45.2
+}
+```
+
+## Parametre olarak tanımlayın { #declare-it-as-a-parameter }
+
+Bunu *path operation*'ınıza eklemek için, path ve query parametrelerini tanımladığınız şekilde tanımlayın:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[16] *}
+
+...ve type'ını, oluşturduğunuz model olan `Item` olarak belirtin.
+
+## Sonuçlar { #results }
+
+Sadece bu Python type tanımıyla, **FastAPI** şunları yapar:
+
+* Request'in body'sini JSON olarak okur.
+* İlgili type'lara dönüştürür (gerekirse).
+* Veriyi doğrular (validate eder).
+ * Veri geçersizse, tam olarak nerede ve hangi verinin hatalı olduğunu söyleyen, anlaşılır bir hata döndürür.
+* Aldığı veriyi `item` parametresi içinde size verir.
+ * Fonksiyonda bunun type'ını `Item` olarak tanımladığınız için, tüm attribute'lar ve type'ları için editor desteğini (tamamlama vb.) de alırsınız.
+* Modeliniz için [JSON Schema](https://json-schema.org) tanımları üretir; projeniz için anlamlıysa bunları başka yerlerde de kullanabilirsiniz.
+* Bu şemalar üretilen OpenAPI şemasının bir parçası olur ve otomatik dokümantasyon UIs tarafından kullanılır.
+
+## Otomatik dokümanlar { #automatic-docs }
+
+Modellerinizin JSON Schema'ları, OpenAPI tarafından üretilen şemanın bir parçası olur ve etkileşimli API dokümanlarında gösterilir:
+
+
+
+Ayrıca, ihtiyaç duyan her *path operation* içindeki API dokümanlarında da kullanılır:
+
+
+
+## Editor desteği { #editor-support }
+
+Editor'ünüzde, fonksiyonunuzun içinde her yerde type hint'leri ve tamamlama (completion) alırsınız (Pydantic modeli yerine `dict` alsaydınız bu olmazdı):
+
+
+
+Yanlış type işlemleri için hata kontrolleri de alırsınız:
+
+
+
+Bu bir tesadüf değil; tüm framework bu tasarımın etrafında inşa edildi.
+
+Ayrıca, bunun tüm editor'lerle çalışacağından emin olmak için herhangi bir implementasyon yapılmadan önce tasarım aşamasında kapsamlı şekilde test edildi.
+
+Hatta bunu desteklemek için Pydantic'in kendisinde bile bazı değişiklikler yapıldı.
+
+Önceki ekran görüntüleri [Visual Studio Code](https://code.visualstudio.com) ile alınmıştır.
+
+Ancak [PyCharm](https://www.jetbrains.com/pycharm/) ve diğer Python editor'lerinin çoğunda da aynı editor desteğini alırsınız:
+
+
+
+/// tip | İpucu
+
+Editor olarak [PyCharm](https://www.jetbrains.com/pycharm/) kullanıyorsanız, [Pydantic PyCharm Plugin](https://github.com/koxudaxi/pydantic-pycharm-plugin/) kullanabilirsiniz.
+
+Pydantic modelleri için editor desteğini şu açılardan iyileştirir:
+
+* auto-completion
+* type checks
+* refactoring
+* searching
+* inspections
+
+///
+
+## Modeli kullanın { #use-the-model }
+
+Fonksiyonun içinde model nesnesinin tüm attribute'larına doğrudan erişebilirsiniz:
+
+{* ../../docs_src/body/tutorial002_py310.py *}
+
+## Request body + path parametreleri { #request-body-path-parameters }
+
+Path parametrelerini ve request body'yi aynı anda tanımlayabilirsiniz.
+
+**FastAPI**, path parametreleriyle eşleşen fonksiyon parametrelerinin **path'ten alınması** gerektiğini ve Pydantic model olarak tanımlanan fonksiyon parametrelerinin **request body'den alınması** gerektiğini anlayacaktır.
+
+{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}
+
+
+## Request body + path + query parametreleri { #request-body-path-query-parameters }
+
+**body**, **path** ve **query** parametrelerini aynı anda da tanımlayabilirsiniz.
+
+**FastAPI** bunların her birini tanır ve veriyi doğru yerden alır.
+
+{* ../../docs_src/body/tutorial004_py310.py hl[16] *}
+
+Fonksiyon parametreleri şu şekilde tanınır:
+
+* Parametre, **path** içinde de tanımlıysa path parametresi olarak kullanılır.
+* Parametre **tekil bir type**'taysa (`int`, `float`, `str`, `bool` vb.), **query** parametresi olarak yorumlanır.
+* Parametre bir **Pydantic model** type'ı olarak tanımlandıysa, request **body** olarak yorumlanır.
+
+/// note | Not
+
+FastAPI, `q` değerinin zorunlu olmadığını `= None` default değerinden anlayacaktır.
+
+`str | None`, FastAPI tarafından bu değerin zorunlu olmadığını belirlemek için kullanılmaz; FastAPI bunun zorunlu olmadığını `= None` default değeri olduğu için bilir.
+
+Ancak type annotation'larını eklemek, editor'ünüzün size daha iyi destek vermesini ve hataları yakalamasını sağlar.
+
+///
+
+## Pydantic olmadan { #without-pydantic }
+
+Pydantic modellerini kullanmak istemiyorsanız, **Body** parametrelerini de kullanabilirsiniz. [Body - Multiple Parameters: Singular values in body](body-multiple-params.md#singular-values-in-body) dokümanına bakın.
diff --git a/docs/tr/docs/tutorial/cookie-param-models.md b/docs/tr/docs/tutorial/cookie-param-models.md
new file mode 100644
index 0000000000000..0fa399c6ae126
--- /dev/null
+++ b/docs/tr/docs/tutorial/cookie-param-models.md
@@ -0,0 +1,76 @@
+# Cookie Parametre Modelleri { #cookie-parameter-models }
+
+Birbirleriyle ilişkili bir **cookie** grubunuz varsa, bunları tanımlamak için bir **Pydantic model** oluşturabilirsiniz. 🍪
+
+Bu sayede **model'i yeniden kullanabilir**, **birden fazla yerde** tekrar tekrar kullanabilir ve tüm parametreler için validation ve metadata'yı tek seferde tanımlayabilirsiniz. 😎
+
+/// note | Not
+
+This is supported since FastAPI version `0.115.0`. 🤓
+
+///
+
+/// tip | İpucu
+
+Aynı teknik `Query`, `Cookie` ve `Header` için de geçerlidir. 😎
+
+///
+
+## Pydantic Model ile Cookies { #cookies-with-a-pydantic-model }
+
+İhtiyacınız olan **cookie** parametrelerini bir **Pydantic model** içinde tanımlayın ve ardından parametreyi `Cookie` olarak bildirin:
+
+{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}
+
+**FastAPI**, request ile gelen **cookies** içinden **her bir field** için veriyi **extract** eder ve size tanımladığınız Pydantic model'i verir.
+
+## Dokümanları Kontrol Edin { #check-the-docs }
+
+Tanımlanan cookie'leri `/docs` altındaki docs UI'da görebilirsiniz:
+
+
+
+
+---
+
+PyCharm kullanıyorsanız şunları yapabilirsiniz:
+
+* "Run" menüsünü açın.
+* "Debug..." seçeneğini seçin.
+* Bir context menü açılır.
+* Debug edilecek dosyayı seçin (bu örnekte `main.py`).
+
+Böylece server, **FastAPI** kodunuzla başlar; breakpoint'lerinizde durur vb.
+
+Aşağıdaki gibi görünebilir:
+
+
diff --git a/docs/tr/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/tr/docs/tutorial/dependencies/classes-as-dependencies.md
new file mode 100644
index 0000000000000..989e93b406657
--- /dev/null
+++ b/docs/tr/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -0,0 +1,288 @@
+# Dependency Olarak Class'lar { #classes-as-dependencies }
+
+**Dependency Injection** sistemine daha derinlemesine geçmeden önce, bir önceki örneği geliştirelim.
+
+## Önceki Örnekten Bir `dict` { #a-dict-from-the-previous-example }
+
+Önceki örnekte, dependency'mizden ("dependable") bir `dict` döndürüyorduk:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *}
+
+Ama sonra *path operation function* içindeki `commons` parametresinde bir `dict` alıyoruz.
+
+Ve biliyoruz ki editor'ler `dict`'ler için çok fazla destek (ör. completion) veremez; çünkü key'lerini ve value type'larını bilemezler.
+
+Daha iyisini yapabiliriz...
+
+## Bir Şeyi Dependency Yapan Nedir { #what-makes-a-dependency }
+
+Şimdiye kadar dependency'leri function olarak tanımlanmış şekilde gördünüz.
+
+Ancak dependency tanımlamanın tek yolu bu değil (muhtemelen en yaygını bu olsa da).
+
+Buradaki kritik nokta, bir dependency'nin "callable" olması gerektiğidir.
+
+Python'da "**callable**", Python'ın bir function gibi "çağırabildiği" her şeydir.
+
+Yani elinizde `something` adlı bir nesne varsa (function _olmak zorunda değil_) ve onu şöyle "çağırabiliyorsanız" (çalıştırabiliyorsanız):
+
+```Python
+something()
+```
+
+veya
+
+```Python
+something(some_argument, some_keyword_argument="foo")
+```
+
+o zaman bu bir "callable" demektir.
+
+## Dependency Olarak Class'lar { #classes-as-dependencies_1 }
+
+Python'da bir class'tan instance oluştururken de aynı söz dizimini kullandığınızı fark etmiş olabilirsiniz.
+
+Örneğin:
+
+```Python
+class Cat:
+ def __init__(self, name: str):
+ self.name = name
+
+
+fluffy = Cat(name="Mr Fluffy")
+```
+
+Bu durumda `fluffy`, `Cat` class'ının bir instance'ıdır.
+
+Ve `fluffy` oluşturmak için `Cat`'i "çağırmış" olursunuz.
+
+Dolayısıyla bir Python class'ı da bir **callable**'dır.
+
+O zaman **FastAPI** içinde bir Python class'ını dependency olarak kullanabilirsiniz.
+
+FastAPI'nin aslında kontrol ettiği şey, bunun bir "callable" olması (function, class ya da başka bir şey) ve tanımlı parametreleridir.
+
+Eğer **FastAPI**'de bir dependency olarak bir "callable" verirseniz, FastAPI o "callable" için parametreleri analiz eder ve bunları *path operation function* parametreleriyle aynı şekilde işler. Sub-dependency'ler dahil.
+
+Bu, hiç parametresi olmayan callable'lar için de geçerlidir. Tıpkı hiç parametresi olmayan *path operation function*'larda olduğu gibi.
+
+O zaman yukarıdaki `common_parameters` adlı "dependable" dependency'sini `CommonQueryParams` class'ına çevirebiliriz:
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *}
+
+Class instance'ını oluşturmak için kullanılan `__init__` metoduna dikkat edin:
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *}
+
+...bizim önceki `common_parameters` ile aynı parametrelere sahip:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *}
+
+Bu parametreler, dependency'yi "çözmek" için **FastAPI**'nin kullanacağı şeylerdir.
+
+Her iki durumda da şunlar olacak:
+
+* `str` olan opsiyonel bir `q` query parametresi.
+* Default değeri `0` olan `int` tipinde bir `skip` query parametresi.
+* Default değeri `100` olan `int` tipinde bir `limit` query parametresi.
+
+Her iki durumda da veriler dönüştürülecek, doğrulanacak, OpenAPI şemasında dokümante edilecek, vb.
+
+## Kullanalım { #use-it }
+
+Artık bu class'ı kullanarak dependency'nizi tanımlayabilirsiniz.
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *}
+
+**FastAPI**, `CommonQueryParams` class'ını çağırır. Bu, o class'ın bir "instance"ını oluşturur ve bu instance, sizin function'ınıza `commons` parametresi olarak geçirilir.
+
+## Type Annotation vs `Depends` { #type-annotation-vs-depends }
+
+Yukarıdaki kodda `CommonQueryParams`'ı iki kez yazdığımıza dikkat edin:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ Annotated Olmadan
+
+/// tip | İpucu
+
+Mümkünse `Annotated` sürümünü kullanmayı tercih edin.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+Şuradaki son `CommonQueryParams`:
+
+```Python
+... Depends(CommonQueryParams)
+```
+
+...FastAPI'nin dependency'nin ne olduğunu anlamak için gerçekten kullandığı şeydir.
+
+FastAPI tanımlanan parametreleri buradan çıkarır ve aslında çağıracağı şey de budur.
+
+---
+
+Bu durumda, şuradaki ilk `CommonQueryParams`:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, ...
+```
+
+////
+
+//// tab | Python 3.10+ Annotated Olmadan
+
+/// tip | İpucu
+
+Mümkünse `Annotated` sürümünü kullanmayı tercih edin.
+
+///
+
+```Python
+commons: CommonQueryParams ...
+```
+
+////
+
+...**FastAPI** için özel bir anlam taşımaz. FastAPI bunu veri dönüştürme, doğrulama vb. için kullanmaz (çünkü bunlar için `Depends(CommonQueryParams)` kullanıyor).
+
+Hatta şunu bile yazabilirsiniz:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[Any, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ Annotated Olmadan
+
+/// tip | İpucu
+
+Mümkünse `Annotated` sürümünü kullanmayı tercih edin.
+
+///
+
+```Python
+commons = Depends(CommonQueryParams)
+```
+
+////
+
+...şu örnekte olduğu gibi:
+
+{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *}
+
+Ancak type'ı belirtmeniz önerilir; böylece editor'ünüz `commons` parametresine ne geçirileceğini bilir ve size code completion, type check'leri vb. konularda yardımcı olur:
+
+
+
+## Kısayol { #shortcut }
+
+Ama burada bir miktar kod tekrarımız olduğunu görüyorsunuz; `CommonQueryParams`'ı iki kez yazıyoruz:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ Annotated Olmadan
+
+/// tip | İpucu
+
+Mümkünse `Annotated` sürümünü kullanmayı tercih edin.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+**FastAPI**, bu durumlar için bir kısayol sağlar: dependency'nin *özellikle* FastAPI'nin bir instance oluşturmak için "çağıracağı" bir class olduğu durumlar.
+
+Bu özel durumlarda şunu yapabilirsiniz:
+
+Şunu yazmak yerine:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ Annotated Olmadan
+
+/// tip | İpucu
+
+Mümkünse `Annotated` sürümünü kullanmayı tercih edin.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+...şunu yazarsınız:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
+
+////
+
+//// tab | Python 3.10+ Annotated Olmadan
+
+/// tip | İpucu
+
+Mümkünse `Annotated` sürümünü kullanmayı tercih edin.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
+
+Dependency'yi parametrenin type'ı olarak tanımlarsınız ve `Depends(CommonQueryParams)` içinde class'ı *yeniden* yazmak yerine, parametre vermeden `Depends()` kullanırsınız.
+
+Aynı örnek şu hale gelir:
+
+{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *}
+
+...ve **FastAPI** ne yapması gerektiğini bilir.
+
+/// tip | İpucu
+
+Bu size faydalı olmaktan çok kafa karıştırıcı geliyorsa, kullanmayın; buna *ihtiyacınız* yok.
+
+Bu sadece bir kısayoldur. Çünkü **FastAPI** kod tekrarını en aza indirmenize yardımcı olmayı önemser.
+
+///
diff --git a/docs/tr/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/tr/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
new file mode 100644
index 0000000000000..8764d736fe794
--- /dev/null
+++ b/docs/tr/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -0,0 +1,69 @@
+# Path Operation Decorator'lerinde Dependency'ler { #dependencies-in-path-operation-decorators }
+
+Bazı durumlarda bir dependency'nin döndürdüğü değere *path operation function* içinde gerçekten ihtiyacınız olmaz.
+
+Ya da dependency zaten bir değer döndürmüyordur.
+
+Ancak yine de çalıştırılmasını/çözülmesini istersiniz.
+
+Bu gibi durumlarda, `Depends` ile bir *path operation function* parametresi tanımlamak yerine, *path operation decorator*'üne `dependencies` adında bir `list` ekleyebilirsiniz.
+
+## *Path Operation Decorator*'üne `dependencies` Ekleyin { #add-dependencies-to-the-path-operation-decorator }
+
+*Path operation decorator*, opsiyonel bir `dependencies` argümanı alır.
+
+Bu, `Depends()` öğelerinden oluşan bir `list` olmalıdır:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
+
+Bu dependency'ler normal dependency'lerle aynı şekilde çalıştırılır/çözülür. Ancak (eğer bir değer döndürüyorlarsa) bu değer *path operation function*'ınıza aktarılmaz.
+
+/// tip | İpucu
+
+Bazı editörler, kullanılmayan function parametrelerini kontrol eder ve bunları hata olarak gösterebilir.
+
+Bu `dependencies` yaklaşımıyla, editör/araç hatalarına takılmadan dependency'lerin çalıştırılmasını sağlayabilirsiniz.
+
+Ayrıca kodunuzda kullanılmayan bir parametreyi gören yeni geliştiricilerin bunun gereksiz olduğunu düşünmesi gibi bir kafa karışıklığını da azaltabilir.
+
+///
+
+/// info | Bilgi
+
+Bu örnekte uydurma özel header'lar olan `X-Key` ve `X-Token` kullanıyoruz.
+
+Ancak gerçek senaryolarda, security uygularken, entegre [Security yardımcı araçlarını (bir sonraki bölüm)](../security/index.md) kullanmak size daha fazla fayda sağlar.
+
+///
+
+## Dependency Hataları ve Return Değerleri { #dependencies-errors-and-return-values }
+
+Normalde kullandığınız aynı dependency *function*'larını burada da kullanabilirsiniz.
+
+### Dependency Gereksinimleri { #dependency-requirements }
+
+Request gereksinimleri (header'lar gibi) veya başka alt dependency'ler tanımlayabilirler:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
+
+### Exception Fırlatmak { #raise-exceptions }
+
+Bu dependency'ler, normal dependency'lerde olduğu gibi `raise` ile exception fırlatabilir:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
+
+### Return Değerleri { #return-values }
+
+Ayrıca değer döndürebilirler ya da döndürmeyebilirler; dönen değer kullanılmayacaktır.
+
+Yani başka bir yerde zaten kullandığınız, değer döndüren normal bir dependency'yi tekrar kullanabilirsiniz; değer kullanılmasa bile dependency çalıştırılacaktır:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
+
+## Bir *Path Operation* Grubu İçin Dependency'ler { #dependencies-for-a-group-of-path-operations }
+
+Daha sonra, muhtemelen birden fazla dosya kullanarak daha büyük uygulamaları nasıl yapılandıracağınızı okurken ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md)), bir *path operation* grubu için tek bir `dependencies` parametresini nasıl tanımlayacağınızı öğreneceksiniz.
+
+## Global Dependency'ler { #global-dependencies }
+
+Sırada, dependency'leri tüm `FastAPI` uygulamasına nasıl ekleyeceğimizi göreceğiz; böylece her *path operation* için geçerli olacaklar.
diff --git a/docs/tr/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/tr/docs/tutorial/dependencies/dependencies-with-yield.md
new file mode 100644
index 0000000000000..5ed7660c50119
--- /dev/null
+++ b/docs/tr/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -0,0 +1,288 @@
+# `yield` ile Dependency'ler { #dependencies-with-yield }
+
+FastAPI, işini bitirdikten sonra ek adımlar çalıştıran dependency'leri destekler.
+
+Bunu yapmak için `return` yerine `yield` kullanın ve ek adımları (kodu) `yield` satırından sonra yazın.
+
+/// tip | İpucu
+
+Her dependency için yalnızca bir kez `yield` kullandığınızdan emin olun.
+
+///
+
+/// note | Teknik Detaylar
+
+Şunlarla kullanılabilen herhangi bir fonksiyon:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) veya
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+bir **FastAPI** dependency'si olarak kullanılabilir.
+
+Hatta FastAPI bu iki decorator'ı içeride (internally) kullanır.
+
+///
+
+## `yield` ile Bir Veritabanı Dependency'si { #a-database-dependency-with-yield }
+
+Örneğin bunu, bir veritabanı session'ı oluşturmak ve iş bittikten sonra kapatmak için kullanabilirsiniz.
+
+Response oluşturulmadan önce yalnızca `yield` satırına kadar olan (ve `yield` dahil) kod çalıştırılır:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
+
+`yield` edilen değer, *path operation*'lara ve diğer dependency'lere enjekte edilen (injected) değerdir:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
+
+Response'dan sonra `yield` satırını takip eden kod çalıştırılır:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
+
+/// tip | İpucu
+
+`async` ya da normal fonksiyonlar kullanabilirsiniz.
+
+**FastAPI**, normal dependency'lerde olduğu gibi her ikisinde de doğru şekilde davranır.
+
+///
+
+## `yield` ve `try` ile Bir Dependency { #a-dependency-with-yield-and-try }
+
+`yield` kullanan bir dependency içinde bir `try` bloğu kullanırsanız, dependency kullanılırken fırlatılan (raised) herhangi bir exception'ı alırsınız.
+
+Örneğin, başka bir dependency'de veya bir *path operation* içinde çalışan bir kod, bir veritabanı transaction'ını "rollback" yaptıysa ya da başka bir exception oluşturduysa, o exception dependency'nizde size gelir.
+
+Dolayısıyla `except SomeException` ile dependency içinde o spesifik exception'ı yakalayabilirsiniz.
+
+Aynı şekilde, exception olsun ya da olmasın çıkış (exit) adımlarının çalıştırılmasını garanti etmek için `finally` kullanabilirsiniz.
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
+
+## `yield` ile Alt Dependency'ler { #sub-dependencies-with-yield }
+
+Her boyutta ve şekilde alt dependency'ler ve alt dependency "ağaçları" (trees) oluşturabilirsiniz; bunların herhangi biri veya hepsi `yield` kullanabilir.
+
+**FastAPI**, `yield` kullanan her dependency'deki "exit code"'un doğru sırayla çalıştırılmasını sağlar.
+
+Örneğin, `dependency_c`, `dependency_b`'ye; `dependency_b` de `dependency_a`'ya bağlı olabilir:
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
+
+Ve hepsi `yield` kullanabilir.
+
+Bu durumda `dependency_c`, exit code'unu çalıştırabilmek için `dependency_b`'den gelen değerin (burada `dep_b`) hâlâ erişilebilir olmasına ihtiyaç duyar.
+
+Aynı şekilde `dependency_b` de exit code'u için `dependency_a`'dan gelen değerin (burada `dep_a`) erişilebilir olmasına ihtiyaç duyar.
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
+
+Benzer şekilde, bazı dependency'ler `yield`, bazıları `return` kullanabilir ve bunların bazıları diğerlerine bağlı olabilir.
+
+Ayrıca birden fazla `yield` kullanan dependency gerektiren tek bir dependency'niz de olabilir, vb.
+
+İstediğiniz herhangi bir dependency kombinasyonunu kullanabilirsiniz.
+
+**FastAPI** her şeyin doğru sırada çalışmasını sağlar.
+
+/// note | Teknik Detaylar
+
+Bu, Python'un [Context Managers](https://docs.python.org/3/library/contextlib.html) yapısı sayesinde çalışır.
+
+**FastAPI** bunu sağlamak için içeride onları kullanır.
+
+///
+
+## `yield` ve `HTTPException` ile Dependency'ler { #dependencies-with-yield-and-httpexception }
+
+`yield` kullanan dependency'lerde `try` bloklarıyla bazı kodları çalıştırıp ardından `finally` sonrasında exit code çalıştırabileceğinizi gördünüz.
+
+Ayrıca `except` ile fırlatılan exception'ı yakalayıp onunla bir şey yapabilirsiniz.
+
+Örneğin `HTTPException` gibi farklı bir exception fırlatabilirsiniz.
+
+/// tip | İpucu
+
+Bu biraz ileri seviye bir tekniktir ve çoğu durumda gerçekten ihtiyaç duymazsınız; çünkü exception'ları (`HTTPException` dahil) uygulamanızın geri kalan kodundan, örneğin *path operation function* içinden fırlatabilirsiniz.
+
+Ama ihtiyaç duyarsanız diye burada. 🤓
+
+///
+
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
+
+Exception yakalayıp buna göre özel bir response oluşturmak istiyorsanız bir [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers) oluşturun.
+
+## `yield` ve `except` ile Dependency'ler { #dependencies-with-yield-and-except }
+
+`yield` kullanan bir dependency içinde `except` ile bir exception yakalar ve bunu tekrar fırlatmazsanız (ya da yeni bir exception fırlatmazsanız), FastAPI normal Python'da olduğu gibi bir exception olduğunu fark edemez:
+
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
+
+Bu durumda client, biz `HTTPException` veya benzeri bir şey fırlatmadığımız için olması gerektiği gibi *HTTP 500 Internal Server Error* response'u görür; ancak server **hiç log üretmez** ve hatanın ne olduğuna dair başka bir işaret de olmaz. 😱
+
+### `yield` ve `except` Kullanan Dependency'lerde Her Zaman `raise` Edin { #always-raise-in-dependencies-with-yield-and-except }
+
+`yield` kullanan bir dependency içinde bir exception yakalarsanız, başka bir `HTTPException` veya benzeri bir şey fırlatmıyorsanız, **orijinal exception'ı tekrar raise etmelisiniz**.
+
+Aynı exception'ı `raise` ile tekrar fırlatabilirsiniz:
+
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
+
+Artık client yine aynı *HTTP 500 Internal Server Error* response'unu alır, ama server log'larda bizim özel `InternalError`'ımızı görür. 😎
+
+## `yield` Kullanan Dependency'lerin Çalıştırılması { #execution-of-dependencies-with-yield }
+
+Çalıştırma sırası kabaca aşağıdaki diyagramdaki gibidir. Zaman yukarıdan aşağı akar. Her sütun, etkileşime giren veya kod çalıştıran parçalardan birini temsil eder.
+
+```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,operation: Can raise exceptions, including HTTPException
+ client ->> dep: Start request
+ Note over dep: Run code up to yield
+ opt raise Exception
+ dep -->> handler: Raise Exception
+ handler -->> client: HTTP error response
+ end
+ dep ->> operation: Run dependency, e.g. DB session
+ opt raise
+ operation -->> dep: Raise Exception (e.g. HTTPException)
+ opt handle
+ dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception
+ end
+ handler -->> client: HTTP error response
+ 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 -->> tasks: Handle exceptions in the background task code
+ end
+```
+
+/// info | Bilgi
+
+Client'a yalnızca **tek bir response** gönderilir. Bu, error response'lardan biri olabilir ya da *path operation*'dan dönen response olabilir.
+
+Bu response'lardan biri gönderildikten sonra başka bir response gönderilemez.
+
+///
+
+/// tip | İpucu
+
+*Path operation function* içindeki koddan herhangi bir exception raise ederseniz, `HTTPException` dahil olmak üzere bu exception `yield` kullanan dependency'lere aktarılır. Çoğu durumda, doğru şekilde ele alındığından emin olmak için `yield` kullanan dependency'den aynı exception'ı (veya yeni bir tanesini) yeniden raise etmek istersiniz.
+
+///
+
+## Erken Çıkış ve `scope` { #early-exit-and-scope }
+
+Normalde `yield` kullanan dependency'lerin exit code'u, client'a response gönderildikten **sonra** çalıştırılır.
+
+Ama *path operation function*'dan döndükten sonra dependency'yi kullanmayacağınızı biliyorsanız, `Depends(scope="function")` kullanarak FastAPI'ye dependency'yi *path operation function* döndükten sonra kapatmasını, ancak **response gönderilmeden önce** kapatmasını söyleyebilirsiniz.
+
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
+
+`Depends()` şu değerleri alabilen bir `scope` parametresi alır:
+
+* `"function"`: dependency'yi request'i işleyen *path operation function* çalışmadan önce başlat, *path operation function* bittikten sonra bitir, ancak response client'a geri gönderilmeden **önce** sonlandır. Yani dependency fonksiyonu, *path operation **function***'ın **etrafında** çalıştırılır.
+* `"request"`: dependency'yi request'i işleyen *path operation function* çalışmadan önce başlat (`"function"` kullanımına benzer), ancak response client'a geri gönderildikten **sonra** sonlandır. Yani dependency fonksiyonu, **request** ve response döngüsünün **etrafında** çalıştırılır.
+
+Belirtilmezse ve dependency `yield` kullanıyorsa, varsayılan olarak `scope` `"request"` olur.
+
+### Alt dependency'ler için `scope` { #scope-for-sub-dependencies }
+
+`scope="request"` (varsayılan) ile bir dependency tanımladığınızda, herhangi bir alt dependency'nin `scope` değeri de `"request"` olmalıdır.
+
+Ancak `scope` değeri `"function"` olan bir dependency, hem `"function"` hem de `"request"` scope'una sahip dependency'lere bağlı olabilir.
+
+Bunun nedeni, bir dependency'nin exit code'unu alt dependency'lerden önce çalıştırabilmesi gerekmesidir; çünkü exit code sırasında hâlâ onları kullanması gerekebilir.
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant dep_req as Dep scope="request"
+participant dep_func as Dep scope="function"
+participant operation as Path Operation
+
+ client ->> dep_req: Start request
+ Note over dep_req: Run code up to yield
+ dep_req ->> dep_func: Pass dependency
+ Note over dep_func: Run code up to yield
+ dep_func ->> operation: Run path operation with dependency
+ operation ->> dep_func: Return from path operation
+ Note over dep_func: Run code after yield
+ Note over dep_func: ✅ Dependency closed
+ dep_func ->> client: Send response to client
+ Note over client: Response sent
+ Note over dep_req: Run code after yield
+ Note over dep_req: ✅ Dependency closed
+```
+
+## `yield`, `HTTPException`, `except` ve Background Tasks ile Dependency'ler { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+`yield` kullanan dependency'ler, zaman içinde farklı kullanım senaryolarını kapsamak ve bazı sorunları düzeltmek için gelişti.
+
+FastAPI'nin farklı sürümlerinde nelerin değiştiğini görmek isterseniz, advanced guide'da şu bölümü okuyabilirsiniz: [Advanced Dependencies - Dependencies with `yield`, `HTTPException`, `except` and Background Tasks](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks).
+## Context Managers { #context-managers }
+
+### "Context Managers" Nedir? { #what-are-context-managers }
+
+"Context Managers", `with` ifadesiyle kullanabildiğiniz Python nesneleridir.
+
+Örneğin, [bir dosyayı okumak için `with` kullanabilirsiniz](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files):
+
+```Python
+with open("./somefile.txt") as f:
+ contents = f.read()
+ print(contents)
+```
+
+Temelde `open("./somefile.txt")`, "Context Manager" olarak adlandırılan bir nesne oluşturur.
+
+`with` bloğu bittiğinde, exception olsa bile dosyanın kapatılmasını garanti eder.
+
+`yield` ile bir dependency oluşturduğunuzda, **FastAPI** içeride bunun için bir context manager oluşturur ve bazı ilgili başka araçlarla birleştirir.
+
+### `yield` kullanan dependency'lerde context manager kullanma { #using-context-managers-in-dependencies-with-yield }
+
+/// warning | Uyarı
+
+Bu, az çok "ileri seviye" bir fikirdir.
+
+**FastAPI**'ye yeni başlıyorsanız şimdilik bunu atlamak isteyebilirsiniz.
+
+///
+
+Python'da Context Manager'ları, [iki method'a sahip bir class oluşturarak: `__enter__()` ve `__exit__()`](https://docs.python.org/3/reference/datamodel.html#context-managers) yaratabilirsiniz.
+
+Ayrıca dependency fonksiyonunun içinde `with` veya `async with` ifadeleri kullanarak **FastAPI**'de `yield` kullanan dependency'lerin içinde de kullanabilirsiniz:
+
+{* ../../docs_src/dependencies/tutorial010_py310.py hl[1:9,13] *}
+
+/// tip | İpucu
+
+Bir context manager oluşturmanın başka bir yolu da şunlardır:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) veya
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+Bunları, tek bir `yield` içeren bir fonksiyonu decorate etmek için kullanabilirsiniz.
+
+FastAPI, `yield` kullanan dependency'ler için içeride bunu yapar.
+
+Ancak FastAPI dependency'leri için bu decorator'ları kullanmak zorunda değilsiniz (hatta kullanmamalısınız).
+
+FastAPI bunu sizin yerinize içeride yapar.
+
+///
diff --git a/docs/tr/docs/tutorial/dependencies/global-dependencies.md b/docs/tr/docs/tutorial/dependencies/global-dependencies.md
new file mode 100644
index 0000000000000..110821c2d1cee
--- /dev/null
+++ b/docs/tr/docs/tutorial/dependencies/global-dependencies.md
@@ -0,0 +1,16 @@
+# Global Dependencies { #global-dependencies }
+
+Bazı uygulama türlerinde, tüm uygulama için dependency eklemek isteyebilirsiniz.
+
+[`dependencies`'i *path operation decorator*'larına ekleyebildiğiniz](dependencies-in-path-operation-decorators.md) gibi, `FastAPI` uygulamasına da ekleyebilirsiniz.
+
+Bu durumda, uygulamadaki tüm *path operation*'lara uygulanırlar:
+
+{* ../../docs_src/dependencies/tutorial012_an_py310.py hl[17] *}
+
+
+Ve [*path operation decorator*'larına `dependencies` ekleme](dependencies-in-path-operation-decorators.md) bölümündeki tüm fikirler hâlâ geçerlidir; ancak bu sefer, uygulamadaki tüm *path operation*'lar için geçerli olur.
+
+## *Path operations* grupları için Dependencies { #dependencies-for-groups-of-path-operations }
+
+İleride, daha büyük uygulamaları nasıl yapılandıracağınızı ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md)) okurken, muhtemelen birden fazla dosyayla birlikte, bir *path operations* grubu için tek bir `dependencies` parametresini nasıl tanımlayacağınızı öğreneceksiniz.
diff --git a/docs/tr/docs/tutorial/dependencies/index.md b/docs/tr/docs/tutorial/dependencies/index.md
new file mode 100644
index 0000000000000..6cf626e05ad46
--- /dev/null
+++ b/docs/tr/docs/tutorial/dependencies/index.md
@@ -0,0 +1,250 @@
+# Bağımlılıklar { #dependencies }
+
+**FastAPI**, çok güçlü ama aynı zamanda sezgisel bir **Bağımlılık Enjeksiyonu** sistemine sahiptir.
+
+Kullanımı çok basit olacak şekilde tasarlanmıştır ve herhangi bir geliştiricinin diğer bileşenleri **FastAPI** ile entegre etmesini kolaylaştırır.
+
+## "Dependency Injection" Nedir? { #what-is-dependency-injection }
+
+Programlamada **"Dependency Injection"**, kodunuzun (bu örnekte *path operation function*'larınızın) çalışmak ve kullanmak için ihtiyaç duyduğu şeyleri: "dependencies" (bağımlılıklar) olarak beyan edebilmesi anlamına gelir.
+
+Ardından bu sistem (bu örnekte **FastAPI**), kodunuza gerekli bağımlılıkları sağlamak ("inject" etmek) için gereken her şeyi sizin yerinize halleder.
+
+Bu yaklaşım, şunlara ihtiyaç duyduğunuzda özellikle faydalıdır:
+
+* Paylaşılan bir mantığa sahip olmak (aynı kod mantığını tekrar tekrar kullanmak).
+* Veritabanı bağlantılarını paylaşmak.
+* Güvenlik, authentication, rol gereksinimleri vb. kuralları zorunlu kılmak.
+* Ve daha birçok şey...
+
+Tüm bunları, kod tekrarını minimumda tutarak yaparsınız.
+
+## İlk Adımlar { #first-steps }
+
+Çok basit bir örneğe bakalım. Şimdilik o kadar basit olacak ki pek işe yaramayacak.
+
+Ama bu sayede **Dependency Injection** sisteminin nasıl çalıştığına odaklanabiliriz.
+
+### Bir dependency (bağımlılık) veya "dependable" Oluşturun { #create-a-dependency-or-dependable }
+
+Önce dependency'e odaklanalım.
+
+Bu, bir *path operation function*'ın alabileceği parametrelerin aynısını alabilen basit bir fonksiyondur:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}
+
+Bu kadar.
+
+**2 satır**.
+
+Ve tüm *path operation function*'larınızla aynı şekle ve yapıya sahiptir.
+
+Bunu, "decorator" olmadan (yani `@app.get("/some-path")` olmadan) yazılmış bir *path operation function* gibi düşünebilirsiniz.
+
+Ayrıca istediğiniz herhangi bir şeyi döndürebilir.
+
+Bu örnekte, bu dependency şunları bekler:
+
+* `str` olan, opsiyonel bir query parametresi `q`.
+* `int` olan, opsiyonel bir query parametresi `skip` ve varsayılanı `0`.
+* `int` olan, opsiyonel bir query parametresi `limit` ve varsayılanı `100`.
+
+Sonra da bu değerleri içeren bir `dict` döndürür.
+
+/// info | Bilgi
+
+FastAPI, `Annotated` desteğini 0.95.0 sürümünde ekledi (ve önermeye başladı).
+
+Daha eski bir sürüm kullanıyorsanız `Annotated` kullanmaya çalıştığınızda hata alırsınız.
+
+`Annotated` kullanmadan önce **FastAPI** sürümünü en az 0.95.1'e yükseltmek için [FastAPI sürümünü yükseltin](../../deployment/versions.md#upgrading-the-fastapi-versions).
+
+///
+
+### `Depends`'i Import Edin { #import-depends }
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}
+
+### "Dependant" İçinde Dependency'yi Tanımlayın { #declare-the-dependency-in-the-dependant }
+
+*Path operation function* parametrelerinizde `Body`, `Query` vb. kullandığınız gibi, yeni bir parametreyle `Depends` kullanın:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}
+
+Fonksiyon parametrelerinde `Depends`'i `Body`, `Query` vb. ile aynı şekilde kullansanız da `Depends` biraz farklı çalışır.
+
+`Depends`'e yalnızca tek bir parametre verirsiniz.
+
+Bu parametre, bir fonksiyon gibi bir şey olmalıdır.
+
+Onu doğrudan **çağırmazsınız** (sonuna parantez eklemezsiniz), sadece `Depends()`'e parametre olarak verirsiniz.
+
+Ve bu fonksiyon da, *path operation function*'lar gibi parametre alır.
+
+/// tip | İpucu
+
+Fonksiyonların dışında başka hangi "şeylerin" dependency olarak kullanılabildiğini bir sonraki bölümde göreceksiniz.
+
+///
+
+Yeni bir request geldiğinde, **FastAPI** şunları sizin yerinize yapar:
+
+* Dependency ("dependable") fonksiyonunuzu doğru parametrelerle çağırır.
+* Fonksiyonunuzun sonucunu alır.
+* Bu sonucu *path operation function*'ınızdaki parametreye atar.
+
+```mermaid
+graph TB
+
+common_parameters(["common_parameters"])
+read_items["/items/"]
+read_users["/users/"]
+
+common_parameters --> read_items
+common_parameters --> read_users
+```
+
+Bu şekilde paylaşılan kodu bir kez yazarsınız ve onu *path operation*'larda çağırma işini **FastAPI** halleder.
+
+/// check | Ek bilgi
+
+Dikkat edin: Bunu "register" etmek ya da benzeri bir şey yapmak için özel bir class oluşturup **FastAPI**'ye bir yere geçirmeniz gerekmez.
+
+Sadece `Depends`'e verirsiniz ve gerisini **FastAPI** nasıl yapacağını bilir.
+
+///
+
+## `Annotated` Dependency'lerini Paylaşın { #share-annotated-dependencies }
+
+Yukarıdaki örneklerde, ufak bir **kod tekrarı** olduğunu görüyorsunuz.
+
+`common_parameters()` dependency'sini kullanmanız gerektiğinde, type annotation ve `Depends()` içeren parametrenin tamamını yazmanız gerekir:
+
+```Python
+commons: Annotated[dict, Depends(common_parameters)]
+```
+
+Ancak `Annotated` kullandığımız için bu `Annotated` değerini bir değişkende saklayıp birden fazla yerde kullanabiliriz:
+
+{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}
+
+/// tip | İpucu
+
+Bu aslında standart Python'dır; buna "type alias" denir ve **FastAPI**'ye özel bir şey değildir.
+
+Ama **FastAPI**, `Annotated` dahil Python standartları üzerine kurulu olduğu için bu tekniği kodunuzda kullanabilirsiniz. 😎
+
+///
+
+Dependency'ler beklediğiniz gibi çalışmaya devam eder ve **en güzel kısmı** da şudur: **type bilgisi korunur**. Bu da editörünüzün size **autocompletion**, **inline errors** vb. sağlamaya devam edeceği anlamına gelir. `mypy` gibi diğer araçlar için de aynısı geçerlidir.
+
+Bu özellikle, **büyük bir kod tabanında**, aynı dependency'leri **birçok *path operation*** içinde tekrar tekrar kullandığınızda çok faydalı olacaktır.
+
+## `async` Olsa da Olmasa da { #to-async-or-not-to-async }
+
+Dependency'ler de **FastAPI** tarafından çağrılacağı için (tıpkı *path operation function*'larınız gibi), fonksiyonları tanımlarken aynı kurallar geçerlidir.
+
+`async def` ya da normal `def` kullanabilirsiniz.
+
+Ayrıca normal `def` *path operation function*'ları içinde `async def` dependency tanımlayabilir veya `async def` *path operation function*'ları içinde `def` dependency kullanabilirsiniz vb.
+
+Fark etmez. **FastAPI** ne yapacağını bilir.
+
+/// note | Not
+
+Eğer bilmiyorsanız, dokümanlarda `async` ve `await` için [Async: *"In a hurry?"*](../../async.md#in-a-hurry) bölümüne bakın.
+
+///
+
+## OpenAPI ile Entegre { #integrated-with-openapi }
+
+Dependency'lerinizin (ve alt dependency'lerin) tüm request tanımları, doğrulamaları ve gereksinimleri aynı OpenAPI şemasına entegre edilir.
+
+Bu nedenle interaktif dokümanlar, bu dependency'lerden gelen tüm bilgileri de içerir:
+
+
+
+## Basit Kullanım { #simple-usage }
+
+Şöyle düşünürseniz: *Path operation function*'lar, bir *path* ve *operation* eşleştiğinde kullanılacak şekilde tanımlanır; ardından **FastAPI** fonksiyonu doğru parametrelerle çağırır ve request'ten veriyi çıkarır.
+
+Aslında tüm (veya çoğu) web framework'ü de aynı şekilde çalışır.
+
+Bu fonksiyonları hiçbir zaman doğrudan çağırmazsınız. Onları framework'ünüz (bu örnekte **FastAPI**) çağırır.
+
+Dependency Injection sistemiyle, *path operation function*'ınızın, ondan önce çalıştırılması gereken başka bir şeye de "bağlı" olduğunu **FastAPI**'ye söyleyebilirsiniz; **FastAPI** bunu çalıştırır ve sonuçları "inject" eder.
+
+Aynı "dependency injection" fikri için kullanılan diğer yaygın terimler:
+
+* resources
+* providers
+* services
+* injectables
+* components
+
+## **FastAPI** Plug-in'leri { #fastapi-plug-ins }
+
+Entegrasyonlar ve "plug-in"ler **Dependency Injection** sistemi kullanılarak inşa edilebilir. Ancak aslında **"plug-in" oluşturmanıza gerek yoktur**; çünkü dependency'leri kullanarak *path operation function*'larınıza sunulabilecek sınırsız sayıda entegrasyon ve etkileşim tanımlayabilirsiniz.
+
+Dependency'ler, çok basit ve sezgisel bir şekilde oluşturulabilir. Böylece ihtiyacınız olan Python package'larını import edip, API fonksiyonlarınızla birkaç satır kodla *kelimenin tam anlamıyla* entegre edebilirsiniz.
+
+İlerleyen bölümlerde ilişkisel ve NoSQL veritabanları, güvenlik vb. konularda bunun örneklerini göreceksiniz.
+
+## **FastAPI** Uyumluluğu { #fastapi-compatibility }
+
+Dependency injection sisteminin sadeliği, **FastAPI**'yi şunlarla uyumlu hale getirir:
+
+* tüm ilişkisel veritabanları
+* NoSQL veritabanları
+* harici paketler
+* harici API'ler
+* authentication ve authorization sistemleri
+* API kullanım izleme (monitoring) sistemleri
+* response verisi injection sistemleri
+* vb.
+
+## Basit ve Güçlü { #simple-and-powerful }
+
+Hiyerarşik dependency injection sistemi tanımlamak ve kullanmak çok basit olsa da, hâlâ oldukça güçlüdür.
+
+Kendileri de dependency tanımlayabilen dependency'ler tanımlayabilirsiniz.
+
+Sonuçta hiyerarşik bir dependency ağacı oluşur ve **Dependency Injection** sistemi tüm bu dependency'leri (ve alt dependency'lerini) sizin için çözer ve her adımda sonuçları sağlar ("inject" eder).
+
+Örneğin, 4 API endpoint'iniz (*path operation*) olduğunu varsayalım:
+
+* `/items/public/`
+* `/items/private/`
+* `/users/{user_id}/activate`
+* `/items/pro/`
+
+O zaman her biri için farklı izin gereksinimlerini yalnızca dependency'ler ve alt dependency'lerle ekleyebilirsiniz:
+
+```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** ile Entegre { #integrated-with-openapi_1 }
+
+Bu dependency'lerin tümü, gereksinimlerini beyan ederken aynı zamanda *path operation*'larınıza parametreler, doğrulamalar vb. da ekler.
+
+**FastAPI**, bunların hepsini OpenAPI şemasına eklemekle ilgilenir; böylece interaktif dokümantasyon sistemlerinde gösterilir.
diff --git a/docs/tr/docs/tutorial/dependencies/sub-dependencies.md b/docs/tr/docs/tutorial/dependencies/sub-dependencies.md
new file mode 100644
index 0000000000000..ab196d829ffb7
--- /dev/null
+++ b/docs/tr/docs/tutorial/dependencies/sub-dependencies.md
@@ -0,0 +1,105 @@
+# Alt Bağımlılıklar { #sub-dependencies }
+
+**Alt bağımlılıkları** olan bağımlılıklar oluşturabilirsiniz.
+
+İhtiyacınız olduğu kadar **derine** gidebilirler.
+
+Bunları çözme işini **FastAPI** üstlenir.
+
+## İlk bağımlılık "dependable" { #first-dependency-dependable }
+
+Şöyle bir ilk bağımlılık ("dependable") oluşturabilirsiniz:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}
+
+Burada `q` adında opsiyonel bir query parametresi `str` olarak tanımlanır ve sonra doğrudan geri döndürülür.
+
+Bu oldukça basit (pek faydalı değil), ama alt bağımlılıkların nasıl çalıştığına odaklanmamıza yardımcı olacak.
+
+## İkinci bağımlılık: "dependable" ve "dependant" { #second-dependency-dependable-and-dependant }
+
+Ardından, aynı zamanda kendi içinde bir bağımlılık da tanımlayan başka bir bağımlılık fonksiyonu (bir "dependable") oluşturabilirsiniz (yani o da bir "dependant" olur):
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}
+
+Tanımlanan parametrelere odaklanalım:
+
+* Bu fonksiyonun kendisi bir bağımlılık ("dependable") olmasına rağmen, ayrıca başka bir bağımlılık daha tanımlar (başka bir şeye "depends" olur).
+ * `query_extractor`'a bağlıdır ve ondan dönen değeri `q` parametresine atar.
+* Ayrıca `last_query` adında opsiyonel bir cookie'yi `str` olarak tanımlar.
+ * Kullanıcı herhangi bir query `q` sağlamadıysa, daha önce cookie'ye kaydettiğimiz en son kullanılan query'yi kullanırız.
+
+## Bağımlılığı Kullanma { #use-the-dependency }
+
+Sonra bu bağımlılığı şöyle kullanabiliriz:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}
+
+/// info | Bilgi
+
+Dikkat edin, *path operation function* içinde yalnızca tek bir bağımlılık tanımlıyoruz: `query_or_cookie_extractor`.
+
+Ancak **FastAPI**, `query_or_cookie_extractor`'ı çağırmadan önce `query_extractor`'ı önce çözmesi gerektiğini bilir ve onun sonucunu `query_or_cookie_extractor`'a aktarır.
+
+///
+
+```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
+```
+
+## Aynı Bağımlılığı Birden Fazla Kez Kullanma { #using-the-same-dependency-multiple-times }
+
+Bağımlılıklarınızdan biri aynı *path operation* için birden fazla kez tanımlanırsa (örneğin birden fazla bağımlılığın ortak bir alt bağımlılığı varsa), **FastAPI** o alt bağımlılığı request başına yalnızca bir kez çağıracağını bilir.
+
+Dönen değeri bir "önbellek" içinde saklar ve aynı request içinde buna ihtiyaç duyan tüm "dependant"lara aktarır; böylece aynı request için bağımlılığı tekrar tekrar çağırmaz.
+
+Daha ileri bir senaryoda, "cached" değeri kullanmak yerine aynı request içinde her adımda (muhtemelen birden fazla kez) bağımlılığın çağrılması gerektiğini biliyorsanız, `Depends` kullanırken `use_cache=False` parametresini ayarlayabilirsiniz:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+//// tab | Python 3.10+ Annotated olmayan
+
+/// tip | İpucu
+
+Mümkünse `Annotated` sürümünü tercih edin.
+
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+## Özet { #recap }
+
+Burada kullanılan havalı terimlerin ötesinde, **Dependency Injection** sistemi aslında oldukça basittir.
+
+*Path operation function*'lara benzeyen fonksiyonlardan ibarettir.
+
+Yine de çok güçlüdür ve keyfi derecede derin iç içe geçmiş bağımlılık "graph"ları (ağaçları) tanımlamanıza izin verir.
+
+/// tip | İpucu
+
+Bu basit örneklerle çok faydalı görünmeyebilir.
+
+Ancak **security** ile ilgili bölümlerde bunun ne kadar işe yaradığını göreceksiniz.
+
+Ayrıca size ne kadar kod kazandırdığını da göreceksiniz.
+
+///
diff --git a/docs/tr/docs/tutorial/encoder.md b/docs/tr/docs/tutorial/encoder.md
new file mode 100644
index 0000000000000..9bb9cf542cd53
--- /dev/null
+++ b/docs/tr/docs/tutorial/encoder.md
@@ -0,0 +1,35 @@
+# JSON Uyumlu Encoder { #json-compatible-encoder }
+
+Bazı durumlarda, bir veri tipini (örneğin bir Pydantic model) JSON ile uyumlu bir şeye (örneğin `dict`, `list` vb.) dönüştürmeniz gerekebilir.
+
+Örneğin, bunu bir veritabanında saklamanız gerekiyorsa.
+
+Bunun için **FastAPI**, `jsonable_encoder()` fonksiyonunu sağlar.
+
+## `jsonable_encoder` Kullanımı { #using-the-jsonable-encoder }
+
+Yalnızca JSON ile uyumlu veri kabul eden bir veritabanınız olduğunu düşünelim: `fake_db`.
+
+Örneğin bu veritabanı, JSON ile uyumlu olmadıkları için `datetime` objelerini kabul etmez.
+
+Dolayısıyla bir `datetime` objesinin, [ISO formatında](https://en.wikipedia.org/wiki/ISO_8601) veriyi içeren bir `str`'e dönüştürülmesi gerekir.
+
+Aynı şekilde bu veritabanı bir Pydantic model'i (attribute'lara sahip bir obje) de kabul etmez; yalnızca bir `dict` kabul eder.
+
+Bunun için `jsonable_encoder` kullanabilirsiniz.
+
+Bir Pydantic model gibi bir obje alır ve JSON ile uyumlu bir versiyonunu döndürür:
+
+{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *}
+
+Bu örnekte, Pydantic model'i bir `dict`'e, `datetime`'ı da bir `str`'e dönüştürür.
+
+Bu fonksiyonun çağrılmasıyla elde edilen sonuç, Python standardındaki [`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps) ile encode edilebilecek bir şeydir.
+
+JSON formatında (string olarak) veriyi içeren büyük bir `str` döndürmez. Bunun yerine, tüm değerleri ve alt değerleri JSON ile uyumlu olacak şekilde, Python’un standart bir veri yapısını (örneğin bir `dict`) döndürür.
+
+/// note | Not
+
+`jsonable_encoder`, aslında **FastAPI** tarafından veriyi dönüştürmek için internal olarak kullanılır. Ancak birçok farklı senaryoda da oldukça faydalıdır.
+
+///
diff --git a/docs/tr/docs/tutorial/extra-data-types.md b/docs/tr/docs/tutorial/extra-data-types.md
new file mode 100644
index 0000000000000..93ae034b2c5c3
--- /dev/null
+++ b/docs/tr/docs/tutorial/extra-data-types.md
@@ -0,0 +1,62 @@
+# Ek Veri Tipleri { #extra-data-types }
+
+Şimdiye kadar şunlar gibi yaygın veri tiplerini kullanıyordunuz:
+
+* `int`
+* `float`
+* `str`
+* `bool`
+
+Ancak daha karmaşık veri tiplerini de kullanabilirsiniz.
+
+Ve yine, şimdiye kadar gördüğünüz özelliklerin aynısına sahip olursunuz:
+
+* Harika editör desteği.
+* Gelen request'lerden veri dönüştürme.
+* response verileri için veri dönüştürme.
+* Veri doğrulama.
+* Otomatik annotation ve dokümantasyon.
+
+## Diğer veri tipleri { #other-data-types }
+
+Kullanabileceğiniz ek veri tiplerinden bazıları şunlardır:
+
+* `UUID`:
+ * Birçok veritabanı ve sistemde ID olarak yaygın kullanılan, standart bir "Universally Unique Identifier".
+ * request'lerde ve response'larda `str` olarak temsil edilir.
+* `datetime.datetime`:
+ * Python `datetime.datetime`.
+ * request'lerde ve response'larda ISO 8601 formatında bir `str` olarak temsil edilir, örn: `2008-09-15T15:53:00+05:00`.
+* `datetime.date`:
+ * Python `datetime.date`.
+ * request'lerde ve response'larda ISO 8601 formatında bir `str` olarak temsil edilir, örn: `2008-09-15`.
+* `datetime.time`:
+ * Python `datetime.time`.
+ * request'lerde ve response'larda ISO 8601 formatında bir `str` olarak temsil edilir, örn: `14:23:55.003`.
+* `datetime.timedelta`:
+ * Python `datetime.timedelta`.
+ * request'lerde ve response'larda toplam saniye sayısını ifade eden bir `float` olarak temsil edilir.
+ * Pydantic, bunu ayrıca bir "ISO 8601 time diff encoding" olarak temsil etmeye de izin verir, [daha fazla bilgi için dokümanlara bakın](https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers).
+* `frozenset`:
+ * request'lerde ve response'larda, `set` ile aynı şekilde ele alınır:
+ * request'lerde bir list okunur, tekrarlar kaldırılır ve `set`'e dönüştürülür.
+ * response'larda `set`, `list`'e dönüştürülür.
+ * Üretilen schema, `set` değerlerinin benzersiz olduğunu belirtir (JSON Schema'nın `uniqueItems` özelliğini kullanarak).
+* `bytes`:
+ * Standart Python `bytes`.
+ * request'lerde ve response'larda `str` gibi ele alınır.
+ * Üretilen schema, bunun `binary` "format"ına sahip bir `str` olduğunu belirtir.
+* `Decimal`:
+ * Standart Python `Decimal`.
+ * request'lerde ve response'larda `float` ile aynı şekilde işlenir.
+* Geçerli tüm Pydantic veri tiplerini burada görebilirsiniz: [Pydantic veri tipleri](https://docs.pydantic.dev/latest/usage/types/types/).
+
+## Örnek { #example }
+
+Yukarıdaki tiplerden bazılarını kullanan parametrelere sahip bir örnek *path operation* şöyle:
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *}
+
+Fonksiyonun içindeki parametrelerin doğal veri tiplerinde olduğunu unutmayın; örneğin normal tarih işlemleri yapabilirsiniz:
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *}
diff --git a/docs/tr/docs/tutorial/extra-models.md b/docs/tr/docs/tutorial/extra-models.md
new file mode 100644
index 0000000000000..d25a80aad9703
--- /dev/null
+++ b/docs/tr/docs/tutorial/extra-models.md
@@ -0,0 +1,211 @@
+# Ek Modeller { #extra-models }
+
+Önceki örnekten devam edersek, birbiriyle ilişkili birden fazla modelin olması oldukça yaygındır.
+
+Bu durum özellikle kullanıcı modellerinde sık görülür, çünkü:
+
+* **input modeli** bir `password` içerebilmelidir.
+* **output modeli** `password` içermemelidir.
+* **database modeli** büyük ihtimalle hash'lenmiş bir `password` tutmalıdır.
+
+/// danger | Tehlike
+
+Kullanıcının düz metin (plaintext) `password`'ünü asla saklamayın. Her zaman sonradan doğrulayabileceğiniz "güvenli bir hash" saklayın.
+
+Eğer bilmiyorsanız, "password hash" nedir konusunu [güvenlik bölümlerinde](security/simple-oauth2.md#password-hashing) öğreneceksiniz.
+
+///
+
+## Birden Çok Model { #multiple-models }
+
+`password` alanlarıyla birlikte modellerin genel olarak nasıl görünebileceğine ve nerelerde kullanılacaklarına dair bir fikir:
+
+{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}
+
+### `**user_in.model_dump()` Hakkında { #about-user-in-model-dump }
+
+#### Pydantic'in `.model_dump()` Metodu { #pydantics-model-dump }
+
+`user_in`, `UserIn` sınıfına ait bir Pydantic modelidir.
+
+Pydantic modellerinde, model verilerini içeren bir `dict` döndüren `.model_dump()` metodu bulunur.
+
+Yani, şöyle bir Pydantic nesnesi `user_in` oluşturursak:
+
+```Python
+user_in = UserIn(username="john", password="secret", email="john.doe@example.com")
+```
+
+ve sonra şunu çağırırsak:
+
+```Python
+user_dict = user_in.model_dump()
+```
+
+artık `user_dict` değişkeninde modelin verilerini içeren bir `dict` vardır (Pydantic model nesnesi yerine bir `dict` elde etmiş oluruz).
+
+Ve eğer şunu çağırırsak:
+
+```Python
+print(user_dict)
+```
+
+şöyle bir Python `dict` elde ederiz:
+
+```Python
+{
+ 'username': 'john',
+ 'password': 'secret',
+ 'email': 'john.doe@example.com',
+ 'full_name': None,
+}
+```
+
+#### Bir `dict`'i Unpack Etmek { #unpacking-a-dict }
+
+`user_dict` gibi bir `dict` alıp bunu bir fonksiyona (ya da sınıfa) `**user_dict` ile gönderirsek, Python bunu "unpack" eder. Yani `user_dict` içindeki key ve value'ları doğrudan key-value argümanları olarak geçirir.
+
+Dolayısıyla, yukarıdaki `user_dict` ile devam edersek, şunu yazmak:
+
+```Python
+UserInDB(**user_dict)
+```
+
+şuna eşdeğer bir sonuç üretir:
+
+```Python
+UserInDB(
+ username="john",
+ password="secret",
+ email="john.doe@example.com",
+ full_name=None,
+)
+```
+
+Ya da daha net şekilde, `user_dict`'i doğrudan kullanarak, gelecekte içeriği ne olursa olsun:
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ password = user_dict["password"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+)
+```
+
+#### Bir Pydantic Modelinden Diğerinin İçeriğiyle Pydantic Model Oluşturmak { #a-pydantic-model-from-the-contents-of-another }
+
+Yukarıdaki örnekte `user_dict`'i `user_in.model_dump()` ile elde ettiğimiz için, şu kod:
+
+```Python
+user_dict = user_in.model_dump()
+UserInDB(**user_dict)
+```
+
+şuna eşdeğerdir:
+
+```Python
+UserInDB(**user_in.model_dump())
+```
+
+...çünkü `user_in.model_dump()` bir `dict` döndürür ve biz de bunu `UserInDB`'ye `**` önekiyle vererek Python'ın "unpack" etmesini sağlarız.
+
+Böylece, bir Pydantic modelindeki verilerden başka bir Pydantic model üretmiş oluruz.
+
+#### Bir `dict`'i Unpack Etmek ve Ek Keyword'ler { #unpacking-a-dict-and-extra-keywords }
+
+Sonrasında, aşağıdaki gibi ek keyword argümanı `hashed_password=hashed_password` eklemek:
+
+```Python
+UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
+```
+
+...şuna benzer bir sonuca dönüşür:
+
+```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 | Uyarı
+
+Ek destek fonksiyonları olan `fake_password_hasher` ve `fake_save_user` sadece verinin olası bir akışını göstermek içindir; elbette gerçek bir güvenlik sağlamazlar.
+
+///
+
+## Tekrarı Azaltma { #reduce-duplication }
+
+Kod tekrarını azaltmak, **FastAPI**'nin temel fikirlerinden biridir.
+
+Kod tekrarı; bug, güvenlik problemi, kodun senkron dışına çıkması (bir yeri güncelleyip diğerlerini güncellememek) gibi sorunların olasılığını artırır.
+
+Bu modellerin hepsi verinin büyük bir kısmını paylaşıyor ve attribute adlarını ve type'larını tekrar ediyor.
+
+Daha iyisini yapabiliriz.
+
+Diğer modellerimiz için temel olacak bir `UserBase` modeli tanımlayabiliriz. Sonra da bu modelden türeyen (subclass) modeller oluşturup onun attribute'larını (type deklarasyonları, doğrulama vb.) miras aldırabiliriz.
+
+Tüm veri dönüştürme, doğrulama, dokümantasyon vb. her zamanki gibi çalışmaya devam eder.
+
+Bu sayede modeller arasındaki farkları (plaintext `password` olan, `hashed_password` olan ve `password` olmayan) sadece o farklılıklar olarak tanımlayabiliriz:
+
+{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}
+
+## `Union` veya `anyOf` { #union-or-anyof }
+
+Bir response'u iki ya da daha fazla type'ın `Union`'ı olarak tanımlayabilirsiniz; bu, response'un bunlardan herhangi biri olabileceği anlamına gelir.
+
+OpenAPI'de bu `anyOf` ile tanımlanır.
+
+Bunu yapmak için standart Python type hint'i olan [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union)'ı kullanın:
+
+/// note | Not
+
+Bir [`Union`](https://docs.pydantic.dev/latest/concepts/types/#unions) tanımlarken en spesifik type'ı önce, daha az spesifik olanı sonra ekleyin. Aşağıdaki örnekte daha spesifik olan `PlaneItem`, `Union[PlaneItem, CarItem]` içinde `CarItem`'dan önce gelir.
+
+///
+
+{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}
+
+### Python 3.10'da `Union` { #union-in-python-3-10 }
+
+Bu örnekte `Union[PlaneItem, CarItem]` değerini `response_model` argümanına veriyoruz.
+
+Bunu bir **type annotation** içine koymak yerine bir **argümana değer** olarak geçtiğimiz için, Python 3.10'da bile `Union` kullanmamız gerekiyor.
+
+Eğer bu bir type annotation içinde olsaydı, dikey çizgiyi kullanabilirdik:
+
+```Python
+some_variable: PlaneItem | CarItem
+```
+
+Ancak bunu `response_model=PlaneItem | CarItem` atamasına koyarsak hata alırız; çünkü Python bunu bir type annotation olarak yorumlamak yerine `PlaneItem` ile `CarItem` arasında **geçersiz bir işlem** yapmaya çalışır.
+
+## Model Listesi { #list-of-models }
+
+Aynı şekilde, nesne listesi döndüren response'ları da tanımlayabilirsiniz.
+
+Bunun için standart Python `list`'i kullanın:
+
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
+
+## Rastgele `dict` ile Response { #response-with-arbitrary-dict }
+
+Bir Pydantic modeli kullanmadan, sadece key ve value type'larını belirterek düz, rastgele bir `dict` ile de response tanımlayabilirsiniz.
+
+Bu, geçerli field/attribute adlarını (Pydantic modeli için gerekli olurdu) önceden bilmiyorsanız kullanışlıdır.
+
+Bu durumda `dict` kullanabilirsiniz:
+
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
+
+## Özet { #recap }
+
+Her duruma göre birden fazla Pydantic modeli kullanın ve gerekirse özgürce inheritance uygulayın.
+
+Bir entity'nin farklı "state"lere sahip olması gerekiyorsa, o entity için tek bir veri modeli kullanmak zorunda değilsiniz. Örneğin `password` içeren, `password_hash` içeren ve `password` içermeyen state'lere sahip kullanıcı "entity"si gibi.
diff --git a/docs/tr/docs/tutorial/first-steps.md b/docs/tr/docs/tutorial/first-steps.md
new file mode 100644
index 0000000000000..0ffa28dbfa339
--- /dev/null
+++ b/docs/tr/docs/tutorial/first-steps.md
@@ -0,0 +1,429 @@
+# İlk Adımlar { #first-steps }
+
+En sade FastAPI dosyası şu şekilde görünür:
+
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
+
+Yukarıdakini `main.py` adlı bir dosyaya kopyalayın.
+
+Canlı sunucuyu çalıştırın:
+
+get operation kullanarak
+
+/// info | `@decorator` Bilgisi
+
+Python'daki `@something` söz dizimi "decorator" olarak adlandırılır.
+
+Onu bir fonksiyonun üstüne koyarsınız. Güzel, dekoratif bir şapka gibi (sanırım terim de buradan geliyor).
+
+Bir "decorator", altındaki fonksiyonu alır ve onunla bir şey yapar.
+
+Bizim durumumuzda bu decorator, **FastAPI**'a altındaki fonksiyonun **path** `/` ile **operation** `get`'e karşılık geldiğini söyler.
+
+Bu, "**path operation decorator**"dır.
+
+///
+
+Diğer operation'ları da kullanabilirsiniz:
+
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+
+Ve daha egzotik olanları:
+
+* `@app.options()`
+* `@app.head()`
+* `@app.patch()`
+* `@app.trace()`
+
+/// tip | İpucu
+
+Her bir operation'ı (HTTP method'unu) istediğiniz gibi kullanmakta özgürsünüz.
+
+**FastAPI** herhangi bir özel anlamı zorunlu kılmaz.
+
+Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır.
+
+Örneğin GraphQL kullanırken, normalde tüm aksiyonları yalnızca `POST` operation'ları kullanarak gerçekleştirirsiniz.
+
+///
+
+### Adım 4: **path operation function**'ı tanımlayın { #step-4-define-the-path-operation-function }
+
+Bu bizim "**path operation function**"ımız:
+
+* **path**: `/`.
+* **operation**: `get`.
+* **function**: "decorator"ün altındaki fonksiyondur (`@app.get("/")`'in altındaki).
+
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
+
+Bu bir Python fonksiyonudur.
+
+**FastAPI**, "`/`" URL'ine `GET` operation kullanarak bir request aldığında bu fonksiyonu çağıracaktır.
+
+Bu durumda, bu bir `async` fonksiyondur.
+
+---
+
+Bunu `async def` yerine normal bir fonksiyon olarak da tanımlayabilirsiniz:
+
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
+
+/// note | Not
+
+Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurry) sayfasına bakın.
+
+///
+
+### Adım 5: içeriği döndürün { #step-5-return-the-content }
+
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
+
+Bir `dict`, `list`, `str`, `int` vb. tekil değerler döndürebilirsiniz.
+
+Ayrıca Pydantic modelleri de döndürebilirsiniz (bununla ilgili daha fazlasını ileride göreceksiniz).
+
+Otomatik olarak JSON'a dönüştürülecek (ORM'ler vb. dahil) başka birçok nesne ve model vardır. En sevdiğiniz nesne/model'leri kullanmayı deneyin; büyük ihtimalle zaten destekleniyordur.
+
+### Adım 6: Deploy edin { #step-6-deploy-it }
+
+Uygulamanızı tek komutla **[FastAPI Cloud](https://fastapicloud.com)**'a deploy edin: `fastapi deploy`. 🎉
+
+#### FastAPI Cloud Hakkında { #about-fastapi-cloud }
+
+**[FastAPI Cloud](https://fastapicloud.com)**, **FastAPI**'ın arkasındaki aynı yazar ve ekip tarafından geliştirilmiştir.
+
+Minimum eforla bir API'ı **oluşturma**, **deploy etme** ve **erişme** sürecini sadeleştirir.
+
+FastAPI ile uygulama geliştirirken yaşadığınız aynı **developer experience**'ı, onları buluta **deploy etme** aşamasına da taşır. 🎉
+
+FastAPI Cloud, *FastAPI and friends* açık kaynak projelerinin birincil sponsoru ve finansman sağlayıcısıdır. ✨
+
+#### Diğer cloud sağlayıcılarına deploy edin { #deploy-to-other-cloud-providers }
+
+FastAPI açık kaynaklıdır ve standartlara dayanır. FastAPI uygulamalarını seçtiğiniz herhangi bir cloud sağlayıcısına deploy edebilirsiniz.
+
+FastAPI uygulamalarını onlarla deploy etmek için cloud sağlayıcınızın kılavuzlarını takip edin. 🤓
+
+## Özet { #recap }
+
+* `FastAPI` import edin.
+* Bir `app` instance'ı oluşturun.
+* `@app.get("/")` gibi decorator'ları kullanarak bir **path operation decorator** yazın.
+* Bir **path operation function** tanımlayın; örneğin `def root(): ...`.
+* `fastapi dev` komutunu kullanarak geliştirme sunucusunu çalıştırın.
+* İsterseniz `fastapi deploy` ile uygulamanızı deploy edin.
diff --git a/docs/tr/docs/tutorial/first_steps.md b/docs/tr/docs/tutorial/first_steps.md
deleted file mode 100644
index b39802f5d6bf1..0000000000000
--- a/docs/tr/docs/tutorial/first_steps.md
+++ /dev/null
@@ -1,336 +0,0 @@
-# İlk Adımlar
-
-En basit FastAPI dosyası şu şekildedir:
-
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
-
-Bunu bir `main.py` dosyasına kopyalayın.
-
-Projeyi çalıştırın:
-
-get işlemi kullanılarak
-
-
-!!! info "`@decorator` Bilgisi"
- Python `@something` şeklinde ifadeleri "decorator" olarak adlandırır.
-
- Decoratoru bir fonksiyonun üzerine koyarsınız. Dekoratif bir şapka gibi (Sanırım terim buradan gelmektedir).
-
- Bir "decorator" fonksiyonu alır ve bazı işlemler gerçekleştir.
-
- Bizim durumumzda decarator **FastAPI'ye** fonksiyonun bir `get` işlemi ile `/` pathine geldiğini söyler.
-
- Bu **path işlem decoratordür**
-
-Ayrıca diğer işlemleri de kullanabilirsiniz:
-
-* `@app.post()`
-* `@app.put()`
-* `@app.delete()`
-
-Ve daha egzotik olanları:
-
-* `@app.options()`
-* `@app.head()`
-* `@app.patch()`
-* `@app.trace()`
-
-!!! tip
- Her işlemi (HTTP method) istediğiniz gibi kullanmakta özgürsünüz.
-
- **FastAPI** herhangi bir özel anlamı zorlamaz.
-
- Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır.
-
- Örneğin, GraphQL kullanırkan normalde tüm işlemleri yalnızca `POST` işlemini kullanarak gerçekleştirirsiniz.
-
-### Adım 4: **path işlem fonksiyonunu** tanımlayın
-
-Aşağıdakiler bizim **path işlem fonksiyonlarımızdır**:
-
-* **path**: `/`
-* **işlem**: `get`
-* **function**: "decorator"ün altındaki fonksiyondur (`@app.get("/")` altında).
-
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
-
-Bu bir Python fonksiyonudur.
-
-Bir `GET` işlemi kullanarak "`/`" URL'sine bir istek geldiğinde **FastAPI** tarafından çağrılır.
-
-Bu durumda bir `async` fonksiyonudur.
-
----
-
-Bunu `async def` yerine normal bir fonksiyon olarakta tanımlayabilirsiniz.
-
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
-
-!!! note
-
- Eğer farkı bilmiyorsanız, [Async: *"Acelesi var?"*](../async.md#in-a-hurry){.internal-link target=_blank} kontrol edebilirsiniz.
-
-### Adım 5: İçeriği geri döndürün
-
-
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
-
-Bir `dict`, `list` döndürebilir veya `str`, `int` gibi tekil değerler döndürebilirsiniz.
-
-Ayrıca, Pydantic modellerini de döndürebilirsiniz. (Bununla ilgili daha sonra ayrıntılı bilgi göreceksiniz.)
-
-Otomatik olarak JSON'a dönüştürülecek(ORM'ler vb. dahil) başka birçok nesne ve model vardır. En beğendiklerinizi kullanmayı deneyin, yüksek ihtimalle destekleniyordur.
-
-## Özet
-
-* `FastAPI`'yi içe aktarın.
-* Bir `app` örneği oluşturun.
-* **path işlem decorator** yazın. (`@app.get("/")` gibi)
-* **path işlem fonksiyonu** yazın. (`def root(): ...` gibi)
-* Development sunucunuzu çalıştırın. (`uvicorn main:app --reload` gibi)
diff --git a/docs/tr/docs/tutorial/handling-errors.md b/docs/tr/docs/tutorial/handling-errors.md
new file mode 100644
index 0000000000000..b90e186a6a3c3
--- /dev/null
+++ b/docs/tr/docs/tutorial/handling-errors.md
@@ -0,0 +1,244 @@
+# Hataları Yönetme { #handling-errors }
+
+API’nizi kullanan bir client’a hata bildirmek zorunda olduğunuz pek çok durum vardır.
+
+Bu client; frontend’i olan bir tarayıcı, başka birinin yazdığı bir kod, bir IoT cihazı vb. olabilir.
+
+Client’a şunları söylemeniz gerekebilir:
+
+* Client’ın bu işlem için yeterli yetkisi yok.
+* Client’ın bu kaynağa erişimi yok.
+* Client’ın erişmeye çalıştığı öğe mevcut değil.
+* vb.
+
+Bu durumlarda genellikle **400** aralığında (**400** ile **499** arası) bir **HTTP status code** döndürürsünüz.
+
+Bu, 200 HTTP status code’larına (200 ile 299 arası) benzer. Bu "200" status code’ları, request’in bir şekilde "başarılı" olduğunu ifade eder.
+
+400 aralığındaki status code’lar ise hatanın client tarafından kaynaklandığını gösterir.
+
+Şu meşhur **"404 Not Found"** hatalarını (ve şakalarını) hatırlıyor musunuz?
+
+## `HTTPException` Kullanma { #use-httpexception }
+
+Client’a hata içeren HTTP response’ları döndürmek için `HTTPException` kullanırsınız.
+
+### `HTTPException`’ı Import Etme { #import-httpexception }
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
+
+### Kodunuzda Bir `HTTPException` Raise Etme { #raise-an-httpexception-in-your-code }
+
+`HTTPException`, API’lerle ilgili ek veriler içeren normal bir Python exception’ıdır.
+
+Python exception’ı olduğu için `return` etmezsiniz, `raise` edersiniz.
+
+Bu aynı zamanda şunu da ifade eder: *path operation function*’ınızın içinde çağırdığınız bir yardımcı (utility) fonksiyonun içindeyken `HTTPException` raise ederseniz, *path operation function* içindeki kodun geri kalanı çalışmaz; request’i hemen sonlandırır ve `HTTPException` içindeki HTTP hatasını client’a gönderir.
+
+Bir değer döndürmek yerine exception raise etmenin faydası, Dependencies ve Security bölümünde daha da netleşecektir.
+
+Bu örnekte, client var olmayan bir ID ile bir item istediğinde, `404` status code’u ile bir exception raise edelim:
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
+
+### Ortaya Çıkan Response { #the-resulting-response }
+
+Client `http://example.com/items/foo` (bir `item_id` `"foo"`) isterse, HTTP status code olarak 200 ve şu JSON response’u alır:
+
+```JSON
+{
+ "item": "The Foo Wrestlers"
+}
+```
+
+Ancak client `http://example.com/items/bar` (mevcut olmayan bir `item_id` `"bar"`) isterse, HTTP status code olarak 404 ("not found" hatası) ve şu JSON response’u alır:
+
+```JSON
+{
+ "detail": "Item not found"
+}
+```
+
+/// tip | İpucu
+
+Bir `HTTPException` raise ederken, `detail` parametresine sadece `str` değil, JSON’a dönüştürülebilen herhangi bir değer geçebilirsiniz.
+
+Örneğin `dict`, `list` vb. geçebilirsiniz.
+
+Bunlar **FastAPI** tarafından otomatik olarak işlenir ve JSON’a dönüştürülür.
+
+///
+
+## Özel Header’lar Eklemek { #add-custom-headers }
+
+Bazı durumlarda HTTP hata response’una özel header’lar eklemek faydalıdır. Örneğin bazı güvenlik türlerinde.
+
+Muhtemelen bunu doğrudan kendi kodunuzda kullanmanız gerekmeyecek.
+
+Ama ileri seviye bir senaryo için ihtiyaç duyarsanız, özel header’lar ekleyebilirsiniz:
+
+{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
+
+## Özel Exception Handler’ları Kurmak { #install-custom-exception-handlers }
+
+[Starlette’in aynı exception yardımcı araçlarıyla](https://www.starlette.dev/exceptions/) özel exception handler’lar ekleyebilirsiniz.
+
+Diyelim ki sizin (ya da kullandığınız bir kütüphanenin) `raise` edebileceği `UnicornException` adında özel bir exception’ınız var.
+
+Ve bu exception’ı FastAPI ile global olarak handle etmek istiyorsunuz.
+
+`@app.exception_handler()` ile özel bir exception handler ekleyebilirsiniz:
+
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
+
+Burada `/unicorns/yolo` için request atarsanız, *path operation* bir `UnicornException` `raise` eder.
+
+Namun bu, `unicorn_exception_handler` tarafından handle edilir.
+
+Böylece HTTP status code’u `418` olan, JSON içeriği şu şekilde temiz bir hata response’u alırsınız:
+
+```JSON
+{"message": "Oops! yolo did something. There goes a rainbow..."}
+```
+
+/// note | Teknik Detaylar
+
+`from starlette.requests import Request` ve `from starlette.responses import JSONResponse` da kullanabilirsiniz.
+
+**FastAPI**, geliştirici olarak size kolaylık olsun diye `starlette.responses` içeriğini `fastapi.responses` olarak da sunar. Ancak mevcut response’ların çoğu doğrudan Starlette’ten gelir. `Request` için de aynısı geçerlidir.
+
+///
+
+## Varsayılan Exception Handler’ları Override Etmek { #override-the-default-exception-handlers }
+
+**FastAPI** bazı varsayılan exception handler’lara sahiptir.
+
+Bu handler’lar, `HTTPException` `raise` ettiğinizde ve request geçersiz veri içerdiğinde varsayılan JSON response’ları döndürmekten sorumludur.
+
+Bu exception handler’ları kendi handler’larınızla override edebilirsiniz.
+
+### Request Validation Exception’larını Override Etmek { #override-request-validation-exceptions }
+
+Bir request geçersiz veri içerdiğinde, **FastAPI** içeride `RequestValidationError` raise eder.
+
+Ve bunun için varsayılan bir exception handler da içerir.
+
+Override etmek için `RequestValidationError`’ı import edin ve exception handler’ı `@app.exception_handler(RequestValidationError)` ile decorate edin.
+
+Exception handler, bir `Request` ve exception’ı alır.
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
+
+Artık `/items/foo`’ya giderseniz, şu varsayılan JSON hatası yerine:
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ]
+}
+```
+
+şu şekilde bir metin (text) versiyonu alırsınız:
+
+```
+Validation errors:
+Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer
+```
+
+### `HTTPException` Hata Handler’ını Override Etmek { #override-the-httpexception-error-handler }
+
+Benzer şekilde `HTTPException` handler’ını da override edebilirsiniz.
+
+Örneğin bu hatalar için JSON yerine plain text response döndürmek isteyebilirsiniz:
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
+
+/// note | Teknik Detaylar
+
+`from starlette.responses import PlainTextResponse` da kullanabilirsiniz.
+
+**FastAPI**, geliştirici olarak size kolaylık olsun diye `starlette.responses` içeriğini `fastapi.responses` olarak da sunar. Ancak mevcut response’ların çoğu doğrudan Starlette’ten gelir.
+
+///
+
+/// warning | Uyarı
+
+`RequestValidationError`, validation hatasının gerçekleştiği dosya adı ve satır bilgilerini içerir; isterseniz bunu log’larınıza ilgili bilgilerle birlikte yazdırabilirsiniz.
+
+Ancak bu, eğer sadece string’e çevirip bu bilgiyi doğrudan response olarak döndürürseniz sisteminiz hakkında bir miktar bilgi sızdırabileceğiniz anlamına gelir. Bu yüzden burada kod, her bir hatayı ayrı ayrı çıkarıp gösterir.
+
+///
+
+### `RequestValidationError` Body’sini Kullanmak { #use-the-requestvalidationerror-body }
+
+`RequestValidationError`, geçersiz veriyle aldığı `body`’yi içerir.
+
+Uygulamanızı geliştirirken body’yi log’lamak, debug etmek, kullanıcıya döndürmek vb. için bunu kullanabilirsiniz.
+
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
+
+Şimdi şu gibi geçersiz bir item göndermeyi deneyin:
+
+```JSON
+{
+ "title": "towel",
+ "size": "XL"
+}
+```
+
+Aldığınız body’yi de içeren, verinin geçersiz olduğunu söyleyen bir response alırsınız:
+
+```JSON hl_lines="12-15"
+{
+ "detail": [
+ {
+ "loc": [
+ "body",
+ "size"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ],
+ "body": {
+ "title": "towel",
+ "size": "XL"
+ }
+}
+```
+
+#### FastAPI’nin `HTTPException`’ı vs Starlette’in `HTTPException`’ı { #fastapis-httpexception-vs-starlettes-httpexception }
+
+**FastAPI**’nin kendi `HTTPException`’ı vardır.
+
+Ve **FastAPI**’nin `HTTPException` hata sınıfı, Starlette’in `HTTPException` hata sınıfından kalıtım alır (inherit).
+
+Tek fark şudur: **FastAPI**’nin `HTTPException`’ı `detail` alanı için JSON’a çevrilebilir herhangi bir veri kabul ederken, Starlette’in `HTTPException`’ı burada sadece string kabul eder.
+
+Bu yüzden kodunuzda her zamanki gibi **FastAPI**’nin `HTTPException`’ını raise etmeye devam edebilirsiniz.
+
+Ancak bir exception handler register ederken, bunu Starlette’in `HTTPException`’ı için register etmelisiniz.
+
+Böylece Starlette’in internal kodunun herhangi bir bölümü ya da bir Starlette extension/plug-in’i Starlette `HTTPException` raise ederse, handler’ınız bunu yakalayıp (catch) handle edebilir.
+
+Bu örnekte, iki `HTTPException`’ı da aynı kodda kullanabilmek için Starlette’in exception’ı `StarletteHTTPException` olarak yeniden adlandırılıyor:
+
+```Python
+from starlette.exceptions import HTTPException as StarletteHTTPException
+```
+
+### **FastAPI**’nin Exception Handler’larını Yeniden Kullanmak { #reuse-fastapis-exception-handlers }
+
+Exception’ı, **FastAPI**’nin aynı varsayılan exception handler’larıyla birlikte kullanmak isterseniz, varsayılan exception handler’ları `fastapi.exception_handlers` içinden import edip yeniden kullanabilirsiniz:
+
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
+
+Bu örnekte sadece oldukça açıklayıcı bir mesajla hatayı yazdırıyorsunuz; ama fikir anlaşılıyor. Exception’ı kullanıp ardından varsayılan exception handler’ları olduğu gibi yeniden kullanabilirsiniz.
diff --git a/docs/tr/docs/tutorial/header-param-models.md b/docs/tr/docs/tutorial/header-param-models.md
new file mode 100644
index 0000000000000..9170515dcf9af
--- /dev/null
+++ b/docs/tr/docs/tutorial/header-param-models.md
@@ -0,0 +1,72 @@
+# Header Parametre Modelleri { #header-parameter-models }
+
+Birbiriyle ilişkili **header parametreleri**nden oluşan bir grubunuz varsa, bunları tanımlamak için bir **Pydantic model** oluşturabilirsiniz.
+
+Bu sayede modeli **birden fazla yerde yeniden kullanabilir**, ayrıca tüm parametreler için doğrulamaları ve metadata bilgilerini tek seferde tanımlayabilirsiniz. 😎
+
+/// note | Not
+
+Bu özellik FastAPI `0.115.0` sürümünden beri desteklenmektedir. 🤓
+
+///
+
+## Pydantic Model ile Header Parametreleri { #header-parameters-with-a-pydantic-model }
+
+İhtiyacınız olan **header parametreleri**ni bir **Pydantic model** içinde tanımlayın, ardından parametreyi `Header` olarak belirtin:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI**, request içindeki **headers** bölümünden **her alan** için veriyi **çıkarır** ve size tanımladığınız Pydantic model örneğini verir.
+
+## Dokümanları Kontrol Edin { #check-the-docs }
+
+Gerekli header'ları `/docs` altındaki doküman arayüzünde görebilirsiniz:
+
+
+contact alanları| Parametre | Tip | Açıklama |
|---|---|---|
name | str | İletişim kişisi/kuruluşunu tanımlayan ad. |
url | str | İletişim bilgilerine işaret eden URL. URL formatında OLMALIDIR. |
email | str | İletişim kişisi/kuruluşunun e-posta adresi. E-posta adresi formatında OLMALIDIR. |
license_info alanları| Parametre | Tip | Açıklama |
|---|---|---|
name | str | ZORUNLU (license_info ayarlanmışsa). API için kullanılan lisans adı. |
identifier | str | API için bir [SPDX](https://spdx.org/licenses/) lisans ifadesi. identifier alanı, url alanıyla karşılıklı olarak dışlayıcıdır (ikisi aynı anda kullanılamaz). OpenAPI 3.1.0, FastAPI 0.99.0 sürümünden itibaren mevcut. |
url | str | API için kullanılan lisansa ait URL. URL formatında OLMALIDIR. |
+
+## Lisans Tanımlayıcısı { #license-identifier }
+
+OpenAPI 3.1.0 ve FastAPI 0.99.0 sürümünden itibaren, `license_info` içinde `url` yerine bir `identifier` da ayarlayabilirsiniz.
+
+Örneğin:
+
+{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}
+
+## Tag'ler için Metadata { #metadata-for-tags }
+
+`openapi_tags` parametresiyle, path operation'larınızı gruplamak için kullandığınız farklı tag'ler adına ek metadata da ekleyebilirsiniz.
+
+Bu parametre, her tag için bir sözlük (dictionary) içeren bir liste alır.
+
+Her sözlük şunları içerebilir:
+
+* `name` (**zorunlu**): *path operation*'larda ve `APIRouter`'larda `tags` parametresinde kullandığınız tag adıyla aynı olan bir `str`.
+* `description`: tag için kısa bir açıklama içeren `str`. Markdown içerebilir ve doküman arayüzünde gösterilir.
+* `externalDocs`: harici dokümanları tanımlayan bir `dict`:
+ * `description`: harici dokümanlar için kısa açıklama içeren `str`.
+ * `url` (**zorunlu**): harici dokümantasyonun URL'sini içeren `str`.
+
+### Tag'ler için metadata oluşturun { #create-metadata-for-tags }
+
+`users` ve `items` tag'lerini içeren bir örnekle deneyelim.
+
+Tag'leriniz için metadata oluşturup `openapi_tags` parametresine geçin:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}
+
+Açıklamaların içinde Markdown kullanabileceğinizi unutmayın; örneğin "login" kalın (**login**) ve "fancy" italik (_fancy_) olarak gösterilecektir.
+
+/// tip | İpucu
+
+Kullandığınız tüm tag'ler için metadata eklemek zorunda değilsiniz.
+
+///
+
+### Tag'lerinizi kullanın { #use-your-tags }
+
+*path operation*'larınızı (ve `APIRouter`'ları) farklı tag'lere atamak için `tags` parametresini kullanın:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}
+
+/// info | Bilgi
+
+Tag'ler hakkında daha fazlası için: [Path Operation Configuration](path-operation-configuration.md#tags).
+
+///
+
+### Dokümanları kontrol edin { #check-the-docs }
+
+Artık dokümanlara baktığınızda, eklediğiniz tüm metadata gösterilir:
+
+
+
+### Tag sırası { #order-of-tags }
+
+Her tag metadata sözlüğünün listedeki sırası, doküman arayüzünde gösterilecek sırayı da belirler.
+
+Örneğin alfabetik sıralamada `users`, `items`'tan sonra gelirdi; ancak listedeki ilk sözlük olarak `users` metadata'sını eklediğimiz için, dokümanlarda önce o görünür.
+
+## OpenAPI URL'si { #openapi-url }
+
+Varsayılan olarak OpenAPI şeması `/openapi.json` adresinden sunulur.
+
+Ancak bunu `openapi_url` parametresiyle yapılandırabilirsiniz.
+
+Örneğin `/api/v1/openapi.json` adresinden sunulacak şekilde ayarlamak için:
+
+{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}
+
+OpenAPI şemasını tamamen kapatmak isterseniz `openapi_url=None` ayarlayabilirsiniz; bu, onu kullanan dokümantasyon arayüzlerini de devre dışı bırakır.
+
+## Doküman URL'leri { #docs-urls }
+
+Dahil gelen iki dokümantasyon arayüzünü yapılandırabilirsiniz:
+
+* **Swagger UI**: `/docs` adresinden sunulur.
+ * URL'sini `docs_url` parametresiyle ayarlayabilirsiniz.
+ * `docs_url=None` ayarlayarak devre dışı bırakabilirsiniz.
+* **ReDoc**: `/redoc` adresinden sunulur.
+ * URL'sini `redoc_url` parametresiyle ayarlayabilirsiniz.
+ * `redoc_url=None` ayarlayarak devre dışı bırakabilirsiniz.
+
+Örneğin Swagger UI'yi `/documentation` adresinden sunup ReDoc'u kapatmak için:
+
+{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}
diff --git a/docs/tr/docs/tutorial/middleware.md b/docs/tr/docs/tutorial/middleware.md
new file mode 100644
index 0000000000000..34048356824b5
--- /dev/null
+++ b/docs/tr/docs/tutorial/middleware.md
@@ -0,0 +1,95 @@
+# Middleware { #middleware }
+
+**FastAPI** uygulamalarına middleware ekleyebilirsiniz.
+
+"Middleware", herhangi bir özel *path operation* tarafından işlenmeden önce her **request** ile çalışan bir fonksiyondur. Ayrıca geri döndürmeden önce her **response** ile de çalışır.
+
+* Uygulamanıza gelen her **request**'i alır.
+* Ardından o **request** üzerinde bir işlem yapabilir veya gerekli herhangi bir kodu çalıştırabilir.
+* Sonra **request**'i uygulamanın geri kalanı tarafından işlenmesi için iletir (bir *path operation* tarafından).
+* Ardından uygulama tarafından üretilen **response**'u alır (bir *path operation* tarafından).
+* Sonra o **response** üzerinde bir işlem yapabilir veya gerekli herhangi bir kodu çalıştırabilir.
+* Son olarak **response**'u döndürür.
+
+/// note | Teknik Detaylar
+
+`yield` ile dependency'leriniz varsa, çıkış (exit) kodu middleware'den *sonra* çalışır.
+
+Herhangi bir background task varsa ([Background Tasks](background-tasks.md) bölümünde ele alınıyor, ileride göreceksiniz), bunlar tüm middleware'ler *tamamlandıktan sonra* çalışır.
+
+///
+
+## Middleware Oluşturma { #create-a-middleware }
+
+Bir middleware oluşturmak için bir fonksiyonun üzerine `@app.middleware("http")` decorator'ünü kullanırsınız.
+
+Middleware fonksiyonu şunları alır:
+
+* `request`.
+* Parametre olarak `request` alacak bir `call_next` fonksiyonu.
+ * Bu fonksiyon `request`'i ilgili *path operation*'a iletir.
+ * Ardından ilgili *path operation* tarafından üretilen `response`'u döndürür.
+* Sonrasında `response`'u döndürmeden önce ayrıca değiştirebilirsiniz.
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}
+
+/// tip | İpucu
+
+Özel (proprietary) header'lar [`X-` prefix'i kullanılarak](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) eklenebilir, bunu aklınızda tutun.
+
+Ancak tarayıcıdaki bir client'ın görebilmesini istediğiniz özel header'larınız varsa, bunları CORS konfigürasyonlarınıza ([CORS (Cross-Origin Resource Sharing)](cors.md)) eklemeniz gerekir. Bunun için, [Starlette'ın CORS dokümanlarında](https://www.starlette.dev/middleware/#corsmiddleware) belgelenen `expose_headers` parametresini kullanın.
+
+///
+
+/// note | Teknik Detaylar
+
+`from starlette.requests import Request` da kullanabilirdiniz.
+
+**FastAPI** bunu geliştirici olarak size kolaylık olsun diye sunar. Ancak doğrudan Starlette'tan gelir.
+
+///
+
+### `response`'tan Önce ve Sonra { #before-and-after-the-response }
+
+Herhangi bir *path operation* `request`'i almadan önce, `request` ile birlikte çalışacak kod ekleyebilirsiniz.
+
+Ayrıca `response` üretildikten sonra, geri döndürmeden önce de kod çalıştırabilirsiniz.
+
+Örneğin, request'i işleyip response üretmenin kaç saniye sürdüğünü içeren `X-Process-Time` adlı özel bir header ekleyebilirsiniz:
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}
+
+/// tip | İpucu
+
+Burada [`time.perf_counter()`](https://docs.python.org/3/library/time.html#time.perf_counter) yerine `time.time()` kullanıyoruz, çünkü bu kullanım senaryolarında daha hassas olabilir. 🤓
+
+///
+
+## Birden Fazla Middleware Çalıştırma Sırası { #multiple-middleware-execution-order }
+
+`@app.middleware()` decorator'ü veya `app.add_middleware()` metodu ile birden fazla middleware eklediğinizde, eklenen her yeni middleware uygulamayı sarar ve bir stack oluşturur. En son eklenen middleware en *dıştaki* (outermost), ilk eklenen ise en *içteki* (innermost) olur.
+
+Request tarafında önce en *dıştaki* middleware çalışır.
+
+Response tarafında ise en son o çalışır.
+
+Örneğin:
+
+```Python
+app.add_middleware(MiddlewareA)
+app.add_middleware(MiddlewareB)
+```
+
+Bu, aşağıdaki çalıştırma sırasını oluşturur:
+
+* **Request**: MiddlewareB → MiddlewareA → route
+
+* **Response**: route → MiddlewareA → MiddlewareB
+
+Bu stack davranışı, middleware'lerin öngörülebilir ve kontrol edilebilir bir sırayla çalıştırılmasını sağlar.
+
+## Diğer Middleware'ler { #other-middlewares }
+
+Diğer middleware'ler hakkında daha fazlasını daha sonra [Advanced User Guide: Advanced Middleware](../advanced/middleware.md) bölümünde okuyabilirsiniz.
+
+Bir sonraki bölümde, middleware ile CORS'un nasıl ele alınacağını göreceksiniz.
diff --git a/docs/tr/docs/tutorial/path-operation-configuration.md b/docs/tr/docs/tutorial/path-operation-configuration.md
new file mode 100644
index 0000000000000..3653090af4623
--- /dev/null
+++ b/docs/tr/docs/tutorial/path-operation-configuration.md
@@ -0,0 +1,107 @@
+# Path Operation Yapılandırması { #path-operation-configuration }
+
+Onu yapılandırmak için *path operation decorator*’ınıza geçebileceğiniz çeşitli parametreler vardır.
+
+/// warning | Uyarı
+
+Bu parametrelerin *path operation function*’ınıza değil, doğrudan *path operation decorator*’ına verildiğine dikkat edin.
+
+///
+
+## Response Status Code { #response-status-code }
+
+*Path operation*’ınızın response’unda kullanılacak (HTTP) `status_code`’u tanımlayabilirsiniz.
+
+`404` gibi `int` kodu doğrudan verebilirsiniz.
+
+Ancak her sayısal kodun ne işe yaradığını hatırlamıyorsanız, `status` içindeki kısayol sabitlerini kullanabilirsiniz:
+
+{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *}
+
+Bu status code response’da kullanılacak ve OpenAPI şemasına eklenecektir.
+
+/// note | Teknik Detaylar
+
+`from starlette import status` da kullanabilirsiniz.
+
+**FastAPI**, geliştirici olarak işinizi kolaylaştırmak için `starlette.status`’u `fastapi.status` olarak da sunar. Ancak kaynağı doğrudan Starlette’tir.
+
+///
+
+## Tags { #tags }
+
+*Path operation*’ınıza tag ekleyebilirsiniz; `tags` parametresine `str` öğelerinden oluşan bir `list` verin (genellikle tek bir `str`):
+
+{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *}
+
+Bunlar OpenAPI şemasına eklenecek ve otomatik dokümantasyon arayüzleri tarafından kullanılacaktır:
+
+
+
+### Enum ile Tags { #tags-with-enums }
+
+Büyük bir uygulamanız varsa, zamanla **birden fazla tag** birikebilir ve ilişkili *path operation*’lar için her zaman **aynı tag**’i kullandığınızdan emin olmak isteyebilirsiniz.
+
+Bu durumlarda tag’leri bir `Enum` içinde tutmak mantıklı olabilir.
+
+**FastAPI** bunu düz string’lerde olduğu gibi aynı şekilde destekler:
+
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
+
+## Özet ve açıklama { #summary-and-description }
+
+Bir `summary` ve `description` ekleyebilirsiniz:
+
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *}
+
+## Docstring’den Açıklama { #description-from-docstring }
+
+Açıklamalar genelde uzun olur ve birden fazla satıra yayılır; bu yüzden *path operation* açıklamasını, fonksiyonun içinde docstring olarak tanımlayabilirsiniz; **FastAPI** de onu buradan okur.
+
+Docstring içinde [Markdown](https://en.wikipedia.org/wiki/Markdown) yazabilirsiniz; doğru şekilde yorumlanır ve gösterilir (docstring girintisi dikkate alınarak).
+
+{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}
+
+Interactive docs’ta şöyle kullanılacaktır:
+
+
+
+## Response description { #response-description }
+
+`response_description` parametresi ile response açıklamasını belirtebilirsiniz:
+
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
+
+/// info | Bilgi
+
+`response_description` özellikle response’u ifade eder; `description` ise genel olarak *path operation*’ı ifade eder.
+
+///
+
+/// check | Ek bilgi
+
+OpenAPI, her *path operation* için bir response description zorunlu kılar.
+
+Bu yüzden siz sağlamazsanız, **FastAPI** otomatik olarak "Successful response" üretir.
+
+///
+
+
+
+## Bir *path operation*’ı Deprecate Etmek { #deprecate-a-path-operation }
+
+Bir *path operation*’ı kaldırmadan, deprecated olarak işaretlemeniz gerekiyorsa `deprecated` parametresini verin:
+
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
+
+Interactive docs’ta deprecated olduğu net şekilde işaretlenecektir:
+
+
+
+Deprecated olan ve olmayan *path operation*’ların nasıl göründüğüne bakın:
+
+
+
+## Özet { #recap }
+
+*Path operation*’larınızı, *path operation decorator*’larına parametre geçirerek kolayca yapılandırabilir ve metadata ekleyebilirsiniz.
diff --git a/docs/tr/docs/tutorial/path-params-numeric-validations.md b/docs/tr/docs/tutorial/path-params-numeric-validations.md
new file mode 100644
index 0000000000000..43da894bb95e7
--- /dev/null
+++ b/docs/tr/docs/tutorial/path-params-numeric-validations.md
@@ -0,0 +1,154 @@
+# Path Parametreleri ve Sayısal Doğrulamalar { #path-parameters-and-numeric-validations }
+
+`Query` ile query parametreleri için daha fazla doğrulama ve metadata tanımlayabildiğiniz gibi, `Path` ile de path parametreleri için aynı tür doğrulama ve metadata tanımlayabilirsiniz.
+
+## `Path`'i İçe Aktarın { #import-path }
+
+Önce `fastapi` içinden `Path`'i ve `Annotated`'ı içe aktarın:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
+
+/// info | Bilgi
+
+FastAPI, 0.95.0 sürümünde `Annotated` desteğini ekledi (ve bunu önermeye başladı).
+
+Daha eski bir sürüm kullanıyorsanız, `Annotated` kullanmaya çalıştığınızda hata alırsınız.
+
+`Annotated` kullanmadan önce mutlaka FastAPI sürümünü en az 0.95.1 olacak şekilde [FastAPI sürümünü yükseltin](../deployment/versions.md#upgrading-the-fastapi-versions).
+
+///
+
+## Metadata Tanımlayın { #declare-metadata }
+
+`Query` için geçerli olan parametrelerin aynısını tanımlayabilirsiniz.
+
+Örneğin, `item_id` path parametresi için bir `title` metadata değeri tanımlamak isterseniz şunu yazabilirsiniz:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *}
+
+/// note | Not
+
+Bir path parametresi her zaman zorunludur, çünkü path'in bir parçası olmak zorundadır. `None` ile tanımlasanız veya bir varsayılan değer verseniz bile bu hiçbir şeyi değiştirmez; yine her zaman zorunlu olur.
+
+///
+
+## Parametreleri İhtiyacınıza Göre Sıralayın { #order-the-parameters-as-you-need }
+
+/// tip | İpucu
+
+`Annotated` kullanıyorsanız, bu muhtemelen o kadar önemli ya da gerekli değildir.
+
+///
+
+Diyelim ki query parametresi `q`'yu zorunlu bir `str` olarak tanımlamak istiyorsunuz.
+
+Ayrıca bu parametre için başka bir şey tanımlamanız gerekmiyor; dolayısıyla `Query` kullanmanıza da aslında gerek yok.
+
+Ancak `item_id` path parametresi için yine de `Path` kullanmanız gerekiyor. Ve bir sebepten `Annotated` kullanmak istemiyorsunuz.
+
+Python, "default" değeri olan bir parametreyi, "default" değeri olmayan bir parametreden önce yazarsanız şikayet eder.
+
+Ama bunların sırasını değiştirebilir ve default değeri olmayan parametreyi (query parametresi `q`) en başa koyabilirsiniz.
+
+Bu **FastAPI** için önemli değildir. FastAPI parametreleri isimlerine, tiplerine ve default tanımlarına (`Query`, `Path`, vb.) göre tespit eder; sırayla ilgilenmez.
+
+Dolayısıyla fonksiyonunuzu şöyle tanımlayabilirsiniz:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
+
+Namun şunu unutmayın: `Annotated` kullanırsanız bu problem olmaz; çünkü `Query()` veya `Path()` için fonksiyon parametresi default değerlerini kullanmıyorsunuz.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
+
+## Parametreleri İhtiyacınıza Göre Sıralayın: Küçük Hileler { #order-the-parameters-as-you-need-tricks }
+
+/// tip | İpucu
+
+`Annotated` kullanıyorsanız, bu muhtemelen o kadar önemli ya da gerekli değildir.
+
+///
+
+İşte bazen işe yarayan **küçük bir hile**; ama çok sık ihtiyacınız olmayacak.
+
+Şunları yapmak istiyorsanız:
+
+* `q` query parametresini `Query` kullanmadan ve herhangi bir default değer vermeden tanımlamak
+* `item_id` path parametresini `Path` kullanarak tanımlamak
+* bunları farklı bir sırada yazmak
+* `Annotated` kullanmamak
+
+...Python bunun için küçük, özel bir sözdizimi sunar.
+
+Fonksiyonun ilk parametresi olarak `*` geçin.
+
+Python bu `*` ile bir şey yapmaz; ama bundan sonraki tüm parametrelerin keyword argument (anahtar-değer çiftleri) olarak çağrılması gerektiğini bilir; buna kwargs da denir. Default değerleri olmasa bile.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
+
+### `Annotated` ile Daha İyi { #better-with-annotated }
+
+Şunu da unutmayın: `Annotated` kullanırsanız, fonksiyon parametresi default değerlerini kullanmadığınız için bu sorun ortaya çıkmaz ve muhtemelen `*` kullanmanız da gerekmez.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
+
+## Sayı Doğrulamaları: Büyük Eşit { #number-validations-greater-than-or-equal }
+
+`Query` ve `Path` (ve ileride göreceğiniz diğerleri) ile sayı kısıtları tanımlayabilirsiniz.
+
+Burada `ge=1` ile, `item_id` değerinin `1`'den "`g`reater than or `e`qual" olacak şekilde bir tam sayı olması gerekir.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
+
+## Sayı Doğrulamaları: Büyük ve Küçük Eşit { #number-validations-greater-than-and-less-than-or-equal }
+
+Aynısı şunlar için de geçerlidir:
+
+* `gt`: `g`reater `t`han
+* `le`: `l`ess than or `e`qual
+
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
+
+## Sayı Doğrulamaları: `float` Değerler, Büyük ve Küçük { #number-validations-floats-greater-than-and-less-than }
+
+Sayı doğrulamaları `float` değerler için de çalışır.
+
+Burada gt tanımlayabilmek (sadece ge değil) önemli hale gelir. Çünkü örneğin bir değerin `0`'dan büyük olmasını isteyebilirsiniz; `1`'den küçük olsa bile.
+
+Bu durumda `0.5` geçerli bir değer olur. Ancak `0.0` veya `0` geçerli olmaz.
+
+Aynısı lt için de geçerlidir.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
+
+## Özet { #recap }
+
+`Query`, `Path` (ve henüz görmedikleriniz) ile metadata ve string doğrulamalarını, [Query Parametreleri ve String Doğrulamalar](query-params-str-validations.md) bölümündekiyle aynı şekilde tanımlayabilirsiniz.
+
+Ayrıca sayısal doğrulamalar da tanımlayabilirsiniz:
+
+* `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 | Bilgi
+
+`Query`, `Path` ve ileride göreceğiniz diğer class'lar ortak bir `Param` class'ının alt class'larıdır.
+
+Hepsi, gördüğünüz ek doğrulama ve metadata parametrelerini paylaşır.
+
+///
+
+/// note | Teknik Detaylar
+
+`Query`, `Path` ve diğerlerini `fastapi` içinden import ettiğinizde, bunlar aslında birer fonksiyondur.
+
+Çağrıldıklarında, aynı isme sahip class'ların instance'larını döndürürler.
+
+Yani `Query`'yi import edersiniz; bu bir fonksiyondur. Onu çağırdığınızda, yine `Query` adlı bir class'ın instance'ını döndürür.
+
+Bu fonksiyonlar (class'ları doğrudan kullanmak yerine) editörünüzün type'larıyla ilgili hata işaretlememesi için vardır.
+
+Bu sayede, bu hataları yok saymak üzere özel ayarlar eklemeden normal editörünüzü ve coding araçlarınızı kullanabilirsiniz.
+
+///
diff --git a/docs/tr/docs/tutorial/path-params.md b/docs/tr/docs/tutorial/path-params.md
new file mode 100644
index 0000000000000..c29d8567ea7e4
--- /dev/null
+++ b/docs/tr/docs/tutorial/path-params.md
@@ -0,0 +1,251 @@
+# Yol Parametreleri { #path-parameters }
+
+Python string biçimlemede kullanılan sözdizimiyle path "parametreleri"ni veya "değişkenleri"ni tanımlayabilirsiniz:
+
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
+
+Path parametresi `item_id`'nin değeri, fonksiyonunuza `item_id` argümanı olarak aktarılacaktır.
+
+Yani, bu örneği çalıştırıp [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo) adresine giderseniz, şöyle bir response görürsünüz:
+
+```JSON
+{"item_id":"foo"}
+```
+
+## Tip İçeren Yol Parametreleri { #path-parameters-with-types }
+
+Standart Python tip belirteçlerini kullanarak path parametresinin tipini fonksiyonun içinde tanımlayabilirsiniz:
+
+{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}
+
+Bu durumda, `item_id` bir `int` olarak tanımlanır.
+
+/// check | Ek bilgi
+
+Bu sayede, fonksiyon içinde hata denetimi, kod tamamlama vb. konularda editör desteğine kavuşursunuz.
+
+///
+
+## Veri dönüştürme { #data-conversion }
+
+Bu örneği çalıştırıp tarayıcınızda [http://127.0.0.1:8000/items/3](http://127.0.0.1:8000/items/3) adresini açarsanız, şöyle bir response görürsünüz:
+
+```JSON
+{"item_id":3}
+```
+
+/// check | Ek bilgi
+
+Dikkat edin: fonksiyonunuzun aldığı (ve döndürdüğü) değer olan `3`, string `"3"` değil, bir Python `int`'idir.
+
+Yani, bu tip tanımıyla birlikte **FastAPI** size otomatik request "ayrıştırma" sağlar.
+
+///
+
+## Veri Doğrulama { #data-validation }
+
+Ancak tarayıcınızda [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo) adresine giderseniz, şuna benzer güzel bir HTTP hatası görürsünüz:
+
+```JSON
+{
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo"
+ }
+ ]
+}
+```
+
+çünkü path parametresi `item_id`, `int` olmayan `"foo"` değerine sahipti.
+
+Aynı hata, şu örnekte olduğu gibi `int` yerine `float` verirseniz de ortaya çıkar: [http://127.0.0.1:8000/items/4.2](http://127.0.0.1:8000/items/4.2)
+
+/// check | Ek bilgi
+
+Yani, aynı Python tip tanımıyla birlikte **FastAPI** size veri doğrulama sağlar.
+
+Dikkat edin: hata ayrıca doğrulamanın geçmediği noktayı da açıkça belirtir.
+
+Bu, API'ınızla etkileşime giren kodu geliştirirken ve debug ederken inanılmaz derecede faydalıdır.
+
+///
+
+## Dokümantasyon { #documentation }
+
+Tarayıcınızı [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) adresinde açtığınızda, aşağıdaki gibi otomatik ve interaktif bir API dokümantasyonu görürsünüz:
+
+
+
+/// check | Ek bilgi
+
+Yine, sadece aynı Python tip tanımıyla **FastAPI** size otomatik ve interaktif dokümantasyon (Swagger UI entegrasyonuyla) sağlar.
+
+Dikkat edin: path parametresi integer olarak tanımlanmıştır.
+
+///
+
+## Standartlara Dayalı Avantajlar, Alternatif Dokümantasyon { #standards-based-benefits-alternative-documentation }
+
+Üretilen şema [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md) standardından geldiği için birçok uyumlu araç vardır.
+
+Bu nedenle **FastAPI**'ın kendisi, [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) adresinden erişebileceğiniz alternatif bir API dokümantasyonu (ReDoc kullanarak) sağlar:
+
+
+
+Aynı şekilde, birçok uyumlu araç vardır. Birçok dil için kod üretme araçları da buna dahildir.
+
+## Pydantic { #pydantic }
+
+Tüm veri doğrulamaları, arka planda [Pydantic](https://docs.pydantic.dev/) tarafından gerçekleştirilir; böylece onun tüm avantajlarından faydalanırsınız. Ve emin ellerde olduğunuzu bilirsiniz.
+
+Aynı tip tanımlarını `str`, `float`, `bool` ve daha birçok karmaşık veri tipiyle kullanabilirsiniz.
+
+Bunların birkaçı, eğitimin sonraki bölümlerinde ele alınacaktır.
+
+## Sıralama Önemlidir { #order-matters }
+
+*Path operation*'lar oluştururken sabit bir path'e sahip olduğunuz durumlarla karşılaşabilirsiniz.
+
+Örneğin `/users/me`'nin, geçerli kullanıcı hakkında veri almak için kullanıldığını varsayalım.
+
+Sonra belirli bir kullanıcı hakkında, kullanıcı ID'si ile veri almak için `/users/{user_id}` şeklinde bir path'iniz de olabilir.
+
+*Path operation*'lar sırayla değerlendirildiği için, `/users/me` için olan path'in `/users/{user_id}` olandan önce tanımlandığından emin olmanız gerekir:
+
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
+
+Aksi halde, `/users/{user_id}` için olan path, `"me"` değerini `user_id` parametresi olarak aldığını "düşünerek" `/users/me` için de eşleşir.
+
+Benzer şekilde, bir path operation'ı yeniden tanımlayamazsınız:
+
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
+
+Path önce eşleştiği için her zaman ilk olan kullanılır.
+
+## Ön Tanımlı Değerler { #predefined-values }
+
+Bir *path operation*'ınız *path parameter* alıyorsa ama olası geçerli *path parameter* değerlerinin önceden tanımlı olmasını istiyorsanız, standart bir Python `Enum` kullanabilirsiniz.
+
+### Bir `Enum` Sınıfı Oluşturalım { #create-an-enum-class }
+
+`Enum`'u import edin ve `str` ile `Enum`'dan miras alan bir alt sınıf oluşturun.
+
+`str`'den miras aldığınızda API dokümanları değerlerin `string` tipinde olması gerektiğini anlayabilir ve doğru şekilde render edebilir.
+
+Sonra, kullanılabilir geçerli değerler olacak sabit değerli class attribute'ları oluşturun:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
+
+/// tip | İpucu
+
+Merak ediyorsanız: "AlexNet", "ResNet" ve "LeNet", Makine Öğrenmesi modellerinin sadece isimleridir.
+
+///
+
+### Bir *Path Parameter* Tanımlayalım { #declare-a-path-parameter }
+
+Ardından oluşturduğunuz enum sınıfını (`ModelName`) kullanarak tip belirteciyle bir *path parameter* oluşturun:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
+
+### Dokümana Göz Atalım { #check-the-docs }
+
+*Path parameter* için kullanılabilir değerler ön tanımlı olduğu için, interaktif dokümanlar bunları güzelce gösterebilir:
+
+
+
+### Python *Enumeration*'ları ile Çalışmak { #working-with-python-enumerations }
+
+*Path parameter*'ın değeri bir *enumeration member* olacaktır.
+
+#### *Enumeration Member*'ları Karşılaştıralım { #compare-enumeration-members }
+
+Bunu, oluşturduğunuz enum `ModelName` içindeki *enumeration member* ile karşılaştırabilirsiniz:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}
+
+#### *Enumeration Value*'yu Alalım { #get-the-enumeration-value }
+
+Gerçek değeri (bu durumda bir `str`) `model_name.value` ile veya genel olarak `your_enum_member.value` ile alabilirsiniz:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}
+
+/// tip | İpucu
+
+`"lenet"` değerine `ModelName.lenet.value` ile de erişebilirsiniz.
+
+///
+
+#### *Enumeration Member*'ları Döndürelim { #return-enumeration-members }
+
+*Path operation*'ınızdan, bir JSON body'nin içine gömülü olsalar bile (ör. bir `dict`) *enum member*'ları döndürebilirsiniz.
+
+İstemciye dönmeden önce, karşılık gelen değerlerine (bu durumda string) dönüştürülürler:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}
+
+İstemcinizde şöyle bir JSON response alırsınız:
+
+```JSON
+{
+ "model_name": "alexnet",
+ "message": "Deep Learning FTW!"
+}
+```
+
+## Path İçeren Path Parametreleri { #path-parameters-containing-paths }
+
+Diyelim ki `/files/{file_path}` path'ine sahip bir *path operation*'ınız var.
+
+Ama `file_path`'in kendisinin `home/johndoe/myfile.txt` gibi bir *path* içermesi gerekiyor.
+
+Böylece, o dosyanın URL'si şu şekilde olur: `/files/home/johndoe/myfile.txt`.
+
+### OpenAPI Desteği { #openapi-support }
+
+OpenAPI, içinde bir *path* barındıracak bir *path parameter* tanımlamak için bir yöntem desteklemez; çünkü bu, test etmesi ve tanımlaması zor senaryolara yol açabilir.
+
+Yine de, Starlette'in dahili araçlarından birini kullanarak bunu **FastAPI**'da yapabilirsiniz.
+
+Ve dokümanlar, parametrenin bir path içermesi gerektiğini söyleyen herhangi bir dokümantasyon eklemese bile çalışmaya devam eder.
+
+### Path Dönüştürücü { #path-convertor }
+
+Starlette'ten doğrudan gelen bir seçenekle, *path* içeren bir *path parameter*'ı şu URL ile tanımlayabilirsiniz:
+
+```
+/files/{file_path:path}
+```
+
+Bu durumda parametrenin adı `file_path`'tir ve son kısım olan `:path`, parametrenin herhangi bir *path* ile eşleşmesi gerektiğini söyler.
+
+Yani şununla kullanabilirsiniz:
+
+{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}
+
+/// tip | İpucu
+
+Parametrenin başında `/home/johndoe/myfile.txt` örneğinde olduğu gibi bir eğik çizgi (`/`) ile başlaması gerekebilir.
+
+Bu durumda URL, `files` ile `home` arasında çift eğik çizgi (`//`) olacak şekilde `/files//home/johndoe/myfile.txt` olur.
+
+///
+
+## Özet { #recap }
+
+**FastAPI** ile kısa, sezgisel ve standart Python tip tanımlarını kullanarak şunları elde edersiniz:
+
+* Editör desteği: hata denetimleri, otomatik tamamlama vb.
+* Veri "ayrıştırma"
+* Veri doğrulama
+* API annotation ve otomatik dokümantasyon
+
+Ve bunları sadece bir kez tanımlamanız yeterlidir.
+
+Bu, (ham performans dışında) **FastAPI**'ın alternatif framework'lere kıyasla muhtemelen en görünür ana avantajıdır.
diff --git a/docs/tr/docs/tutorial/query-param-models.md b/docs/tr/docs/tutorial/query-param-models.md
new file mode 100644
index 0000000000000..75139a6777d89
--- /dev/null
+++ b/docs/tr/docs/tutorial/query-param-models.md
@@ -0,0 +1,68 @@
+# Query Parameter Modelleri { #query-parameter-models }
+
+Birbirleriyle ilişkili bir **query parameter** grubunuz varsa, bunları tanımlamak için bir **Pydantic model** oluşturabilirsiniz.
+
+Böylece **modeli yeniden kullanabilir**, **birden fazla yerde** tekrar tekrar kullanabilir ve tüm parametreler için validation (doğrulama) ile metadata’yı tek seferde tanımlayabilirsiniz. 😎
+
+/// note | Not
+
+Bu özellik FastAPI `0.115.0` sürümünden beri desteklenmektedir. 🤓
+
+///
+
+## Pydantic Model ile Query Parameters { #query-parameters-with-a-pydantic-model }
+
+İhtiyacınız olan **query parameter**’ları bir **Pydantic model** içinde tanımlayın, ardından parametreyi `Query` olarak belirtin:
+
+{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}
+
+**FastAPI**, request’teki **query parameter**’lardan **her field** için veriyi **extract** eder ve tanımladığınız Pydantic model’i size verir.
+
+## Dokümanları Kontrol Edin { #check-the-docs }
+
+Query parameter’ları `/docs` altındaki dokümantasyon arayüzünde görebilirsiniz:
+
+
+
+
+### Varsayılanlarla query parametresi listesi / birden fazla değer { #query-parameter-list-multiple-values-with-defaults }
+
+Hiç değer verilmezse varsayılan bir `list` de tanımlayabilirsiniz:
+
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
+
+Şu adrese giderseniz:
+
+```
+http://localhost:8000/items/
+```
+
+`q`’nun varsayılanı `["foo", "bar"]` olur ve response şöyle olur:
+
+```JSON
+{
+ "q": [
+ "foo",
+ "bar"
+ ]
+}
+```
+
+#### Sadece `list` kullanmak { #using-just-list }
+
+`list[str]` yerine doğrudan `list` de kullanabilirsiniz:
+
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
+
+/// note | Not
+
+Bu durumda FastAPI, listenin içeriğini kontrol etmez.
+
+Örneğin `list[int]`, listenin içeriğinin integer olduğunu kontrol eder (ve dokümante eder). Ancak tek başına `list` bunu yapmaz.
+
+///
+
+## Daha fazla metadata tanımlayın { #declare-more-metadata }
+
+Parametre hakkında daha fazla bilgi ekleyebilirsiniz.
+
+Bu bilgiler oluşturulan OpenAPI’a dahil edilir ve dokümantasyon arayüzleri ile harici araçlar tarafından kullanılır.
+
+/// note | Not
+
+Farklı araçların OpenAPI desteği farklı seviyelerde olabilir.
+
+Bazıları tanımladığınız ek bilgilerin hepsini göstermeyebilir; ancak çoğu durumda eksik özellik geliştirme planındadır.
+
+///
+
+Bir `title` ekleyebilirsiniz:
+
+{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *}
+
+Ve bir `description`:
+
+{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *}
+
+## Alias parametreleri { #alias-parameters }
+
+Parametrenin adının `item-query` olmasını istediğinizi düşünün.
+
+Örneğin:
+
+```
+http://127.0.0.1:8000/items/?item-query=foobaritems
+```
+
+Ancak `item-query` geçerli bir Python değişken adı değildir.
+
+En yakın seçenek `item_query` olur.
+
+Ama sizin hâlâ tam olarak `item-query` olmasına ihtiyacınız var...
+
+O zaman bir `alias` tanımlayabilirsiniz; bu alias, parametre değerini bulmak için kullanılacaktır:
+
+{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *}
+
+## Parametreleri deprecated yapmak { #deprecating-parameters }
+
+Diyelim ki artık bu parametreyi istemiyorsunuz.
+
+Bazı client’lar hâlâ kullandığı için bir süre tutmanız gerekiyor, ama dokümanların bunu açıkça deprecated olarak göstermesini istiyorsunuz.
+
+O zaman `Query`’ye `deprecated=True` parametresini geçin:
+
+{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *}
+
+Dokümanlarda şöyle görünür:
+
+
+
+## Parametreleri OpenAPI’dan hariç tutun { #exclude-parameters-from-openapi }
+
+Oluşturulan OpenAPI şemasından (dolayısıyla otomatik dokümantasyon sistemlerinden) bir query parametresini hariç tutmak için `Query`’nin `include_in_schema` parametresini `False` yapın:
+
+{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *}
+
+## Özel Doğrulama { #custom-validation }
+
+Yukarıdaki parametrelerle yapılamayan bazı **özel doğrulama** ihtiyaçlarınız olabilir.
+
+Bu durumlarda, normal doğrulamadan sonra (ör. değerin `str` olduğunun doğrulanmasından sonra) uygulanacak bir **custom validator function** kullanabilirsiniz.
+
+Bunu, `Annotated` içinde [Pydantic’in `AfterValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-after-validator)’ını kullanarak yapabilirsiniz.
+
+/// tip | İpucu
+
+Pydantic’te [`BeforeValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-before-validator) ve başka validator’lar da vardır. 🤓
+
+///
+
+Örneğin bu custom validator, bir item ID’sinin ISBN kitap numarası için `isbn-` ile veya IMDB film URL ID’si için `imdb-` ile başladığını kontrol eder:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
+
+/// info | Bilgi
+
+Bu özellik Pydantic 2 ve üzeri sürümlerde mevcuttur. 😎
+
+///
+
+/// tip | İpucu
+
+Veritabanı veya başka bir API gibi herhangi bir **harici bileşen** ile iletişim gerektiren bir doğrulama yapmanız gerekiyorsa, bunun yerine **FastAPI Dependencies** kullanmalısınız; onları ileride öğreneceksiniz.
+
+Bu custom validator’lar, request’te sağlanan **yalnızca** **aynı veri** ile kontrol edilebilen şeyler içindir.
+
+///
+
+### O Kodu Anlamak { #understand-that-code }
+
+Önemli nokta, **`Annotated` içinde bir fonksiyonla birlikte `AfterValidator` kullanmak**. İsterseniz bu kısmı atlayabilirsiniz. 🤸
+
+---
+
+Ama bu örnek kodun detaylarını merak ediyorsanız, birkaç ek bilgi:
+
+#### `value.startswith()` ile String { #string-with-value-startswith }
+
+Fark ettiniz mi? `value.startswith()` ile bir string, tuple alabilir ve tuple içindeki her değeri kontrol eder:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *}
+
+#### Rastgele Bir Item { #a-random-item }
+
+`data.items()` ile, her dictionary öğesi için key ve value içeren tuple’lardan oluşan bir yinelemeli nesne elde ederiz.
+
+Bu yinelemeli nesneyi `list(data.items())` ile düzgün bir `list`’e çeviririz.
+
+Ardından `random.choice()` ile list’ten **rastgele bir değer** alırız; yani `(id, name)` içeren bir tuple elde ederiz. Şuna benzer: `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")`.
+
+Sonra tuple içindeki bu **iki değeri** `id` ve `name` değişkenlerine **atarız**.
+
+Böylece kullanıcı bir item ID’si vermemiş olsa bile yine de rastgele bir öneri alır.
+
+...bütün bunları **tek bir basit satırda** yapıyoruz. 🤯 Python’u sevmemek elde mi? 🐍
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *}
+
+## Özet { #recap }
+
+Parametreleriniz için ek doğrulamalar ve metadata tanımlayabilirsiniz.
+
+Genel doğrulamalar ve metadata:
+
+* `alias`
+* `title`
+* `description`
+* `deprecated`
+
+String’lere özel doğrulamalar:
+
+* `min_length`
+* `max_length`
+* `pattern`
+
+`AfterValidator` ile custom doğrulamalar.
+
+Bu örneklerde `str` değerleri için doğrulamanın nasıl tanımlanacağını gördünüz.
+
+Sayılar gibi diğer tipler için doğrulamaları nasıl tanımlayacağınızı öğrenmek için sonraki bölümlere geçin.
diff --git a/docs/tr/docs/tutorial/query-params.md b/docs/tr/docs/tutorial/query-params.md
new file mode 100644
index 0000000000000..fa485f51a16a6
--- /dev/null
+++ b/docs/tr/docs/tutorial/query-params.md
@@ -0,0 +1,188 @@
+# Sorgu Parametreleri { #query-parameters }
+
+Fonksiyonda path parametrelerinin parçası olmayan diğer parametreleri tanımladığınızda, bunlar otomatik olarak "query" parametreleri olarak yorumlanır.
+
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
+
+Query, bir URL'de `?` işaretinden sonra gelen ve `&` karakterleriyle ayrılan anahtar-değer çiftlerinin kümesidir.
+
+Örneğin, şu URL'de:
+
+```
+http://127.0.0.1:8000/items/?skip=0&limit=10
+```
+
+...query parametreleri şunlardır:
+
+* `skip`: değeri `0`
+* `limit`: değeri `10`
+
+URL'nin bir parçası oldukları için "doğal olarak" string'tirler.
+
+Ancak, bunları Python tipleriyle (yukarıdaki örnekte `int` olarak) tanımladığınızda, o tipe dönüştürülürler ve o tipe göre doğrulanırlar.
+
+Path parametreleri için geçerli olan aynı süreç query parametreleri için de geçerlidir:
+
+* Editör desteği (tabii ki)
+* Veri "ayrıştırma"
+* Veri doğrulama
+* Otomatik dokümantasyon
+
+## Varsayılanlar { #defaults }
+
+Query parametreleri path'in sabit bir parçası olmadığından, opsiyonel olabilir ve varsayılan değerlere sahip olabilir.
+
+Yukarıdaki örnekte varsayılan değerleri `skip=0` ve `limit=10`'dur.
+
+Yani şu URL'ye gitmek:
+
+```
+http://127.0.0.1:8000/items/
+```
+
+şuraya gitmekle aynı olur:
+
+```
+http://127.0.0.1:8000/items/?skip=0&limit=10
+```
+
+Ancak örneğin şuraya giderseniz:
+
+```
+http://127.0.0.1:8000/items/?skip=20
+```
+
+Fonksiyonunuzdaki parametre değerleri şöyle olacaktır:
+
+* `skip=20`: çünkü URL'de siz ayarladınız
+* `limit=10`: çünkü varsayılan değer oydu
+
+## İsteğe bağlı parametreler { #optional-parameters }
+
+Aynı şekilde, varsayılan değerlerini `None` yaparak isteğe bağlı query parametreleri tanımlayabilirsiniz:
+
+{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *}
+
+Bu durumda, fonksiyon parametresi `q` isteğe bağlı olur ve varsayılan olarak `None` olur.
+
+/// check | Ek bilgi
+
+Ayrıca, **FastAPI** path parametresi olan `item_id`'nin bir path parametresi olduğunu ve `q`'nun path olmadığını fark edecek kadar akıllıdır; dolayısıyla bu bir query parametresidir.
+
+///
+
+## Sorgu parametresi tip dönüşümü { #query-parameter-type-conversion }
+
+`bool` tipleri de tanımlayabilirsiniz, ve bunlar dönüştürülür:
+
+{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *}
+
+Bu durumda, şuraya giderseniz:
+
+```
+http://127.0.0.1:8000/items/foo?short=1
+```
+
+veya
+
+```
+http://127.0.0.1:8000/items/foo?short=True
+```
+
+veya
+
+```
+http://127.0.0.1:8000/items/foo?short=true
+```
+
+veya
+
+```
+http://127.0.0.1:8000/items/foo?short=on
+```
+
+veya
+
+```
+http://127.0.0.1:8000/items/foo?short=yes
+```
+
+veya başka herhangi bir büyük/küçük harf varyasyonunda (tamamı büyük, ilk harf büyük, vb.), fonksiyonunuz `short` parametresini `bool` değeri `True` olarak görecektir. Aksi halde `False` olarak görür.
+
+
+## Çoklu path ve query parametreleri { #multiple-path-and-query-parameters }
+
+Aynı anda birden fazla path parametresi ve query parametresi tanımlayabilirsiniz; **FastAPI** hangisinin hangisi olduğunu bilir.
+
+Ayrıca bunları belirli bir sırayla tanımlamanız gerekmez.
+
+İsme göre tespit edilirler:
+
+{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *}
+
+## Zorunlu query parametreleri { #required-query-parameters }
+
+Path olmayan parametreler (şimdilik sadece query parametrelerini gördük) için varsayılan değer tanımladığınızda, bu parametre zorunlu olmaz.
+
+Belirli bir değer eklemek istemiyor ama sadece opsiyonel olmasını istiyorsanız, varsayılanı `None` olarak ayarlayın.
+
+Ancak bir query parametresini zorunlu yapmak istediğinizde, herhangi bir varsayılan değer tanımlamamanız yeterlidir:
+
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
+
+Burada query parametresi `needy`, `str` tipinde zorunlu bir query parametresidir.
+
+Tarayıcınızda şöyle bir URL açarsanız:
+
+```
+http://127.0.0.1:8000/items/foo-item
+```
+
+...zorunlu `needy` parametresini eklemeden, şuna benzer bir hata görürsünüz:
+
+```JSON
+{
+ "detail": [
+ {
+ "type": "missing",
+ "loc": [
+ "query",
+ "needy"
+ ],
+ "msg": "Field required",
+ "input": null
+ }
+ ]
+}
+```
+
+`needy` zorunlu bir parametre olduğundan, URL'de ayarlamanız gerekir:
+
+```
+http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
+```
+
+...bu çalışır:
+
+```JSON
+{
+ "item_id": "foo-item",
+ "needy": "sooooneedy"
+}
+```
+
+Ve elbette, bazı parametreleri zorunlu, bazılarını varsayılan değerli, bazılarını da tamamen isteğe bağlı olarak tanımlayabilirsiniz:
+
+{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *}
+
+Bu durumda, 3 tane query parametresi vardır:
+
+* `needy`, zorunlu bir `str`.
+* `skip`, varsayılan değeri `0` olan bir `int`.
+* `limit`, isteğe bağlı bir `int`.
+
+/// tip | İpucu
+
+[Path Parametreleri](path-params.md#predefined-values) ile aynı şekilde `Enum`'ları da kullanabilirsiniz.
+
+///
diff --git a/docs/tr/docs/tutorial/request-files.md b/docs/tr/docs/tutorial/request-files.md
new file mode 100644
index 0000000000000..0ba4f8af68c80
--- /dev/null
+++ b/docs/tr/docs/tutorial/request-files.md
@@ -0,0 +1,176 @@
+# Request Dosyaları { #request-files }
+
+İstemcinin upload edeceği dosyaları `File` kullanarak tanımlayabilirsiniz.
+
+/// info | Bilgi
+
+Upload edilen dosyaları alabilmek için önce [`python-multipart`](https://github.com/Kludex/python-multipart) yükleyin.
+
+Bir [virtual environment](../virtual-environments.md) oluşturduğunuzdan, aktive ettiğinizden ve ardından paketi yüklediğinizden emin olun. Örneğin:
+
+```console
+$ pip install python-multipart
+```
+
+Bunun nedeni, upload edilen dosyaların "form data" olarak gönderilmesidir.
+
+///
+
+## `File` Import Edin { #import-file }
+
+`fastapi` içinden `File` ve `UploadFile` import edin:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
+
+## `File` Parametrelerini Tanımlayın { #define-file-parameters }
+
+`Body` veya `Form` için yaptığınız gibi dosya parametreleri oluşturun:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
+
+/// info | Bilgi
+
+`File`, doğrudan `Form`’dan türeyen bir sınıftır.
+
+Ancak unutmayın: `fastapi` içinden `Query`, `Path`, `File` ve diğerlerini import ettiğinizde, bunlar aslında özel sınıflar döndüren fonksiyonlardır.
+
+///
+
+/// tip | İpucu
+
+File body’leri tanımlamak için `File` kullanmanız gerekir; aksi halde parametreler query parametreleri veya body (JSON) parametreleri olarak yorumlanır.
+
+///
+
+Dosyalar "form data" olarak upload edilir.
+
+*path operation function* parametrenizin tipini `bytes` olarak tanımlarsanız, **FastAPI** dosyayı sizin için okur ve içeriği `bytes` olarak alırsınız.
+
+Bunun, dosyanın tüm içeriğinin bellekte tutulacağı anlamına geldiğini unutmayın. Küçük dosyalar için iyi çalışır.
+
+Ancak bazı durumlarda `UploadFile` kullanmak size fayda sağlayabilir.
+
+## `UploadFile` ile Dosya Parametreleri { #file-parameters-with-uploadfile }
+
+Tipi `UploadFile` olan bir dosya parametresi tanımlayın:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
+
+`UploadFile` kullanmanın `bytes`’a göre birkaç avantajı vardır:
+
+* Parametrenin varsayılan değerinde `File()` kullanmak zorunda değilsiniz.
+* "Spooled" bir dosya kullanır:
+ * Belirli bir maksimum boyuta kadar bellekte tutulan, bu limiti aşınca diske yazılan bir dosya.
+* Bu sayede görüntüler, videolar, büyük binary’ler vb. gibi büyük dosyalarda tüm belleği tüketmeden iyi çalışır.
+* Upload edilen dosyadan metadata alabilirsiniz.
+* [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) bir `async` arayüze sahiptir.
+* [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) nesnesini dışa açar; bunu, file-like nesne bekleyen diğer library’lere doğrudan geçebilirsiniz.
+
+### `UploadFile` { #uploadfile }
+
+`UploadFile` şu attribute’lara sahiptir:
+
+* `filename`: Upload edilen orijinal dosya adını içeren bir `str` (örn. `myimage.jpg`).
+* `content_type`: Content type’ı (MIME type / media type) içeren bir `str` (örn. `image/jpeg`).
+* `file`: Bir [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) (bir [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) nesne). Bu, "file-like" nesne bekleyen diğer fonksiyonlara veya library’lere doğrudan verebileceğiniz gerçek Python file nesnesidir.
+
+`UploadFile` şu `async` method’lara sahiptir. Bunların hepsi altta ilgili dosya method’larını çağırır (dahili `SpooledTemporaryFile` kullanarak).
+
+* `write(data)`: Dosyaya `data` (`str` veya `bytes`) yazar.
+* `read(size)`: Dosyadan `size` (`int`) kadar byte/karakter okur.
+* `seek(offset)`: Dosyada `offset` (`int`) byte pozisyonuna gider.
+ * Örn. `await myfile.seek(0)` dosyanın başına gider.
+ * Bu, özellikle bir kez `await myfile.read()` çalıştırdıysanız ve sonra içeriği yeniden okumaya ihtiyaç duyuyorsanız faydalıdır.
+* `close()`: Dosyayı kapatır.
+
+Bu method’ların hepsi `async` olduğundan, bunları "await" etmeniz gerekir.
+
+Örneğin, bir `async` *path operation function* içinde içeriği şöyle alabilirsiniz:
+
+```Python
+contents = await myfile.read()
+```
+
+Normal bir `def` *path operation function* içindeyseniz `UploadFile.file`’a doğrudan erişebilirsiniz, örneğin:
+
+```Python
+contents = myfile.file.read()
+```
+
+/// note | `async` Teknik Detaylar
+
+`async` method’ları kullandığınızda, **FastAPI** dosya method’larını bir threadpool içinde çalıştırır ve bunları await eder.
+
+///
+
+/// note | Starlette Teknik Detaylar
+
+**FastAPI**’nin `UploadFile`’ı doğrudan **Starlette**’in `UploadFile`’ından türetilmiştir; ancak **Pydantic** ve FastAPI’nin diğer parçalarıyla uyumlu olması için bazı gerekli eklemeler yapar.
+
+///
+
+## "Form Data" Nedir { #what-is-form-data }
+
+HTML formları (``) veriyi server’a gönderirken normalde JSON’dan farklı, veri için "özel" bir encoding kullanır.
+
+**FastAPI**, JSON yerine bu veriyi doğru yerden okuyacağından emin olur.
+
+/// note | Teknik Detaylar
+
+Formlardan gelen veri, dosya içermiyorsa normalde "media type" olarak `application/x-www-form-urlencoded` ile encode edilir.
+
+Ancak form dosya içeriyorsa `multipart/form-data` olarak encode edilir. `File` kullanırsanız, **FastAPI** dosyaları body’nin doğru kısmından alması gerektiğini bilir.
+
+Bu encoding’ler ve form alanları hakkında daha fazla okumak isterseniz [MDN web dokümanlarındaki `POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) sayfasına bakın.
+
+///
+
+/// warning | Uyarı
+
+Bir *path operation* içinde birden fazla `File` ve `Form` parametresi tanımlayabilirsiniz, ancak JSON olarak almayı beklediğiniz `Body` alanlarını ayrıca tanımlayamazsınız; çünkü request body `application/json` yerine `multipart/form-data` ile encode edilmiş olur.
+
+Bu, **FastAPI**’nin bir kısıtı değildir; HTTP protocol’ünün bir parçasıdır.
+
+///
+
+## Opsiyonel Dosya Upload { #optional-file-upload }
+
+Standart type annotation’ları kullanıp varsayılan değeri `None` yaparak bir dosyayı opsiyonel hale getirebilirsiniz:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## Ek Metadata ile `UploadFile` { #uploadfile-with-additional-metadata }
+
+Ek metadata ayarlamak için `UploadFile` ile birlikte `File()` da kullanabilirsiniz. Örneğin:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
+
+## Birden Fazla Dosya Upload { #multiple-file-uploads }
+
+Aynı anda birden fazla dosya upload etmek mümkündür.
+
+Bu dosyalar, "form data" ile gönderilen aynı "form field" ile ilişkilendirilir.
+
+Bunu kullanmak için `bytes` veya `UploadFile` listesini tanımlayın:
+
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
+
+Tanımladığınız gibi, `bytes` veya `UploadFile`’lardan oluşan bir `list` alırsınız.
+
+/// note | Teknik Detaylar
+
+`from starlette.responses import HTMLResponse` da kullanabilirsiniz.
+
+**FastAPI**, geliştiriciye kolaylık olsun diye `starlette.responses` modülünü `fastapi.responses` olarak da sağlar. Ancak mevcut response’ların çoğu doğrudan Starlette’ten gelir.
+
+///
+
+### Ek Metadata ile Birden Fazla Dosya Upload { #multiple-file-uploads-with-additional-metadata }
+
+Daha önce olduğu gibi, `UploadFile` için bile ek parametreler ayarlamak amacıyla `File()` kullanabilirsiniz:
+
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
+
+## Özet { #recap }
+
+Request’te (form data olarak gönderilen) upload edilecek dosyaları tanımlamak için `File`, `bytes` ve `UploadFile` kullanın.
diff --git a/docs/tr/docs/tutorial/request-form-models.md b/docs/tr/docs/tutorial/request-form-models.md
new file mode 100644
index 0000000000000..30fdaee1383f8
--- /dev/null
+++ b/docs/tr/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Form Model'leri { #form-models }
+
+FastAPI'de **form field**'larını tanımlamak için **Pydantic model**'lerini kullanabilirsiniz.
+
+/// info | Bilgi
+
+Form'ları kullanmak için önce [`python-multipart`](https://github.com/Kludex/python-multipart)'ı yükleyin.
+
+Bir [virtual environment](../virtual-environments.md) oluşturduğunuzdan, onu etkinleştirdiğinizden ve ardından paketi kurduğunuzdan emin olun. Örneğin:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | Not
+
+Bu özellik FastAPI `0.113.0` sürümünden itibaren desteklenmektedir. 🤓
+
+///
+
+## Form'lar için Pydantic Model'leri { #pydantic-models-for-forms }
+
+Sadece, **form field** olarak almak istediğiniz alanlarla bir **Pydantic model** tanımlayın ve ardından parametreyi `Form` olarak bildirin:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
+
+**FastAPI**, request içindeki **form data**'dan **her bir field** için veriyi **çıkarır** ve size tanımladığınız Pydantic model'ini verir.
+
+## Dokümanları Kontrol Edin { #check-the-docs }
+
+Bunu `/docs` altındaki doküman arayüzünde doğrulayabilirsiniz:
+
+
+
+
+Ve her iki model de etkileşimli API dokümantasyonunda kullanılır:
+
+
+
+## Diğer Return Type Annotation’ları { #other-return-type-annotations }
+
+Bazı durumlarda Pydantic field olarak geçerli olmayan bir şey döndürebilir ve bunu fonksiyonda annotate edebilirsiniz; amaç sadece araçların (editör, mypy vb.) sağladığı desteği almaktır.
+
+### Doğrudan Response Döndürmek { #return-a-response-directly }
+
+En yaygın durum, [ileri seviye dokümanlarda daha sonra anlatıldığı gibi doğrudan bir Response döndürmektir](../advanced/response-directly.md).
+
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
+
+Bu basit durum FastAPI tarafından otomatik olarak ele alınır; çünkü dönüş tipi annotation’ı `Response` class’ıdır (veya onun bir subclass’ı).
+
+Araçlar da memnun olur; çünkü hem `RedirectResponse` hem `JSONResponse`, `Response`’un subclass’ıdır. Yani type annotation doğrudur.
+
+### Bir Response Subclass’ını Annotate Etmek { #annotate-a-response-subclass }
+
+Type annotation içinde `Response`’un bir subclass’ını da kullanabilirsiniz:
+
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
+
+Bu da çalışır; çünkü `RedirectResponse`, `Response`’un subclass’ıdır ve FastAPI bu basit durumu otomatik olarak yönetir.
+
+### Geçersiz Return Type Annotation’ları { #invalid-return-type-annotations }
+
+Ancak geçerli bir Pydantic tipi olmayan başka rastgele bir obje (ör. bir veritabanı objesi) döndürür ve fonksiyonu da öyle annotate ederseniz, FastAPI bu type annotation’dan bir Pydantic response model oluşturmaya çalışır ve başarısız olur.
+
+Aynı şey, farklı tipler arasında bir birleşim kullandığınızda ve bu tiplerden biri veya birkaçı geçerli bir Pydantic tipi değilse de olur; örneğin şu kullanım patlar 💥:
+
+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
+
+...bu, type annotation Pydantic tipi olmadığı ve tek bir `Response` class’ı (veya subclass’ı) olmadığı için başarısız olur; bu, bir `Response` ile bir `dict` arasında union’dır (ikiden herhangi biri).
+
+### Response Model’i Devre Dışı Bırakmak { #disable-response-model }
+
+Yukarıdaki örnekten devam edersek; FastAPI’nin varsayılan olarak yaptığı veri doğrulama, dokümantasyon, filtreleme vb. işlemleri istemiyor olabilirsiniz.
+
+Ancak yine de editörler ve type checker’lar (ör. mypy) gibi araçların desteğini almak için fonksiyonda dönüş tipi annotation’ını korumak isteyebilirsiniz.
+
+Bu durumda `response_model=None` ayarlayarak response model üretimini devre dışı bırakabilirsiniz:
+
+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}
+
+Bu, FastAPI’nin response model üretimini atlamasını sağlar; böylece FastAPI uygulamanızı etkilemeden ihtiyacınız olan herhangi bir return type annotation’ını kullanabilirsiniz. 🤓
+
+## Response Model encoding parametreleri { #response-model-encoding-parameters }
+
+Response model’inizde şu şekilde default değerler olabilir:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}
+
+* `description: Union[str, None] = None` (veya Python 3.10’da `str | None = None`) için default `None`’dır.
+* `tax: float = 10.5` için default `10.5`’tir.
+* `tags: List[str] = []` için default, boş bir list’tir: `[]`.
+
+Ancak gerçekte kaydedilmedilerse, bunları sonuçtan çıkarmak isteyebilirsiniz.
+
+Örneğin NoSQL veritabanında çok sayıda optional attribute içeren modelleriniz varsa, default değerlerle dolu çok uzun JSON response’ları göndermek istemeyebilirsiniz.
+
+### `response_model_exclude_unset` parametresini kullanın { #use-the-response-model-exclude-unset-parameter }
+
+*Path operation decorator* parametresi olarak `response_model_exclude_unset=True` ayarlayabilirsiniz:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}
+
+böylece response’a default değerler dahil edilmez; yalnızca gerçekten set edilmiş değerler gelir.
+
+Dolayısıyla ID’si `foo` olan item için bu *path operation*’a request atarsanız, response (default değerler olmadan) şöyle olur:
+
+```JSON
+{
+ "name": "Foo",
+ "price": 50.2
+}
+```
+
+/// info | Bilgi
+
+Ayrıca şunları da kullanabilirsiniz:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+Bunlar, `exclude_defaults` ve `exclude_none` için [Pydantic dokümanlarında](https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict) anlatıldığı gibidir.
+
+///
+
+#### Default’u olan field’lar için değer içeren data { #data-with-values-for-fields-with-defaults }
+
+Ama data’nız modelde default değeri olan field’lar için değer içeriyorsa, örneğin ID’si `bar` olan item gibi:
+
+```Python hl_lines="3 5"
+{
+ "name": "Bar",
+ "description": "The bartenders",
+ "price": 62,
+ "tax": 20.2
+}
+```
+
+bunlar response’a dahil edilir.
+
+#### Default değerlerle aynı değerlere sahip data { #data-with-the-same-values-as-the-defaults }
+
+Eğer data, default değerlerle aynı değerlere sahipse, örneğin ID’si `baz` olan item gibi:
+
+```Python hl_lines="3 5-6"
+{
+ "name": "Baz",
+ "description": None,
+ "price": 50.2,
+ "tax": 10.5,
+ "tags": []
+}
+```
+
+FastAPI yeterince akıllıdır (aslında Pydantic yeterince akıllıdır) ve `description`, `tax`, `tags` default ile aynı olsa bile bunların explicit olarak set edildiğini (default’tan alınmadığını) anlar.
+
+Bu yüzden JSON response içinde yer alırlar.
+
+/// tip | İpucu
+
+Default değerlerin yalnızca `None` olmak zorunda olmadığını unutmayın.
+
+Bir list (`[]`), `10.5` gibi bir `float` vb. olabilirler.
+
+///
+
+### `response_model_include` ve `response_model_exclude` { #response-model-include-and-response-model-exclude }
+
+Ayrıca *path operation decorator* parametreleri `response_model_include` ve `response_model_exclude`’u da kullanabilirsiniz.
+
+Bunlar; dahil edilecek attribute isimlerini (geri kalanını atlayarak) ya da hariç tutulacak attribute isimlerini (geri kalanını dahil ederek) belirten `str` değerlerinden oluşan bir `set` alır.
+
+Tek bir Pydantic model’iniz varsa ve output’tan bazı verileri hızlıca çıkarmak istiyorsanız, bu yöntem pratik bir kısayol olabilir.
+
+/// tip | İpucu
+
+Ancak yine de, bu parametreler yerine yukarıdaki yaklaşımı (birden fazla class kullanmayı) tercih etmeniz önerilir.
+
+Çünkü `response_model_include` veya `response_model_exclude` ile bazı attribute’ları atlıyor olsanız bile, uygulamanızın OpenAPI’sinde (ve dokümanlarda) üretilen JSON Schema hâlâ tam modelin JSON Schema’sı olacaktır.
+
+Bu durum, benzer şekilde çalışan `response_model_by_alias` için de geçerlidir.
+
+///
+
+{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}
+
+/// tip | İpucu
+
+`{"name", "description"}` sözdizimi, bu iki değere sahip bir `set` oluşturur.
+
+Bu, `set(["name", "description"])` ile eşdeğerdir.
+
+///
+
+#### `set` yerine `list` kullanmak { #using-lists-instead-of-sets }
+
+Yanlışlıkla `set` yerine `list` veya `tuple` kullanırsanız, FastAPI bunu yine `set`’e çevirir ve doğru şekilde çalışır:
+
+{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}
+
+## Özet { #recap }
+
+Response model’leri tanımlamak ve özellikle private data’nın filtrelendiğinden emin olmak için *path operation decorator* parametresi `response_model`’i kullanın.
+
+Yalnızca explicit olarak set edilmiş değerleri döndürmek için `response_model_exclude_unset` kullanın.
diff --git a/docs/tr/docs/tutorial/response-status-code.md b/docs/tr/docs/tutorial/response-status-code.md
new file mode 100644
index 0000000000000..c647c259ab08b
--- /dev/null
+++ b/docs/tr/docs/tutorial/response-status-code.md
@@ -0,0 +1,101 @@
+# Response Status Code { #response-status-code }
+
+Bir response model tanımlayabildiğiniz gibi, herhangi bir *path operation* içinde `status_code` parametresiyle response için kullanılacak HTTP status code'u da belirtebilirsiniz:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* vb.
+
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
+
+/// note | Not
+
+`status_code`'un, "decorator" metodunun (`get`, `post`, vb.) bir parametresi olduğuna dikkat edin. Tüm parametreler ve body gibi, sizin *path operation function*'ınızın bir parametresi değildir.
+
+///
+
+`status_code` parametresi, HTTP status code'u içeren bir sayı alır.
+
+/// info | Bilgi
+
+Alternatif olarak `status_code`, Python'un [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus)'ı gibi bir `IntEnum` da alabilir.
+
+///
+
+Bu sayede:
+
+* Response'da o status code döner.
+* OpenAPI şemasında (dolayısıyla kullanıcı arayüzlerinde de) bu şekilde dokümante edilir:
+
+
+
+/// note | Not
+
+Bazı response code'lar (bir sonraki bölümde göreceğiz) response'un bir body'ye sahip olmadığını belirtir.
+
+FastAPI bunu bilir ve response body olmadığını söyleyen OpenAPI dokümantasyonunu üretir.
+
+///
+
+## HTTP status code'lar hakkında { #about-http-status-codes }
+
+/// note | Not
+
+HTTP status code'ların ne olduğunu zaten biliyorsanız, bir sonraki bölüme geçin.
+
+///
+
+HTTP'de, response'un bir parçası olarak 3 basamaklı sayısal bir status code gönderirsiniz.
+
+Bu status code'ların tanınmalarını sağlayan bir isimleri de vardır; ancak önemli olan kısım sayıdır.
+
+Kısaca:
+
+* `100 - 199` "Information" içindir. Doğrudan nadiren kullanırsınız. Bu status code'lara sahip response'lar body içeremez.
+* **`200 - 299`** "Successful" response'lar içindir. En sık kullanacağınız aralık budur.
+ * `200`, varsayılan status code'dur ve her şeyin "OK" olduğunu ifade eder.
+ * Başka bir örnek `201` ("Created") olabilir. Genellikle veritabanında yeni bir kayıt oluşturduktan sonra kullanılır.
+ * Özel bir durum ise `204` ("No Content")'tür. Client'a döndürülecek içerik olmadığında kullanılır; bu nedenle response body olmamalıdır.
+* **`300 - 399`** "Redirection" içindir. Bu status code'lara sahip response'lar, `304` ("Not Modified") hariç, body içerebilir de içermeyebilir de; `304` kesinlikle body içermemelidir.
+* **`400 - 499`** "Client error" response'ları içindir. Muhtemelen en sık kullanacağınız ikinci aralık budur.
+ * Örneğin `404`, "Not Found" response'u içindir.
+ * Client kaynaklı genel hatalar için doğrudan `400` kullanabilirsiniz.
+* `500 - 599` server hataları içindir. Neredeyse hiç doğrudan kullanmazsınız. Uygulama kodunuzun bir bölümünde ya da server'da bir şeyler ters giderse, otomatik olarak bu status code'lardan biri döner.
+
+/// tip | İpucu
+
+Her bir status code hakkında daha fazla bilgi almak ve hangi kodun ne için kullanıldığını görmek için [MDN dokümantasyonu: HTTP status code'lar hakkında](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)'na göz atın.
+
+///
+
+## İsimleri hatırlamak için kısayol { #shortcut-to-remember-the-names }
+
+Önceki örneğe tekrar bakalım:
+
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
+
+`201`, "Created" için kullanılan status code'dur.
+
+Ancak bu kodların her birinin ne anlama geldiğini ezberlemek zorunda değilsiniz.
+
+`fastapi.status` içindeki kolaylık değişkenlerini (convenience variables) kullanabilirsiniz.
+
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
+
+Bunlar sadece kolaylık sağlar; aynı sayıyı taşırlar. Ancak bu şekilde editörün autocomplete özelliğiyle kolayca bulabilirsiniz:
+
+
+
+/// note | Teknik Detaylar
+
+`from starlette import status` da kullanabilirsiniz.
+
+**FastAPI**, geliştirici olarak size kolaylık olsun diye `starlette.status`'u `fastapi.status` olarak da sunar. Ancak bu aslında doğrudan Starlette'den gelir.
+
+///
+
+## Varsayılanı değiştirmek { #changing-the-default }
+
+Daha sonra, [İleri Düzey Kullanıcı Kılavuzu](../advanced/response-change-status-code.md) içinde, burada tanımladığınız varsayılanın dışında farklı bir status code nasıl döndüreceğinizi göreceksiniz.
diff --git a/docs/tr/docs/tutorial/schema-extra-example.md b/docs/tr/docs/tutorial/schema-extra-example.md
new file mode 100644
index 0000000000000..030db7756599f
--- /dev/null
+++ b/docs/tr/docs/tutorial/schema-extra-example.md
@@ -0,0 +1,202 @@
+# Request Örnek Verilerini Tanımlama { #declare-request-example-data }
+
+Uygulamanızın alabileceği veriler için örnekler (examples) tanımlayabilirsiniz.
+
+Bunu yapmanın birkaç yolu var.
+
+## Pydantic modellerinde ek JSON Schema verisi { #extra-json-schema-data-in-pydantic-models }
+
+Oluşturulan JSON Schema’ya eklenecek şekilde bir Pydantic model için `examples` tanımlayabilirsiniz.
+
+{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}
+
+Bu ek bilgi, o modelin çıktı **JSON Schema**’sına olduğu gibi eklenir ve API dokümanlarında kullanılır.
+
+[Pydantic dokümanları: Configuration](https://docs.pydantic.dev/latest/api/config/) bölümünde anlatıldığı gibi, bir `dict` alan `model_config` niteliğini kullanabilirsiniz.
+
+Üretilen JSON Schema’da görünmesini istediğiniz (ör. `examples` dahil) her türlü ek veriyi içeren bir `dict` ile `"json_schema_extra"` ayarlayabilirsiniz.
+
+/// tip | İpucu
+
+Aynı tekniği JSON Schema’yı genişletmek ve kendi özel ek bilgilerinizi eklemek için de kullanabilirsiniz.
+
+Örneğin, bir frontend kullanıcı arayüzü için metadata eklemek vb. amaçlarla kullanılabilir.
+
+///
+
+/// info | Bilgi
+
+OpenAPI 3.1.0 (FastAPI 0.99.0’dan beri kullanılıyor), **JSON Schema** standardının bir parçası olan `examples` için destek ekledi.
+
+Bundan önce yalnızca tek bir örnek için `example` anahtar kelimesini destekliyordu. Bu hâlâ OpenAPI 3.1.0 tarafından desteklenir; ancak artık deprecated durumdadır ve JSON Schema standardının parçası değildir. Bu nedenle `example` kullanımını `examples`’a taşımanız önerilir. 🤓
+
+Daha fazlasını sayfanın sonunda okuyabilirsiniz.
+
+///
+
+## `Field` ek argümanları { #field-additional-arguments }
+
+Pydantic modelleriyle `Field()` kullanırken ek `examples` de tanımlayabilirsiniz:
+
+{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}
+
+## JSON Schema - OpenAPI içinde `examples` { #examples-in-json-schema-openapi }
+
+Aşağıdakilerden herhangi birini kullanırken:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+OpenAPI içindeki **JSON Schema**’larına eklenecek ek bilgilerle birlikte bir `examples` grubu da tanımlayabilirsiniz.
+
+### `examples` ile `Body` { #body-with-examples }
+
+Burada `Body()` içinde beklenen veri için tek bir örnek içeren `examples` geçiriyoruz:
+
+{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *}
+
+### Doküman arayüzünde örnek { #example-in-the-docs-ui }
+
+Yukarıdaki yöntemlerden herhangi biriyle `/docs` içinde şöyle görünür:
+
+
+
+### Birden fazla `examples` ile `Body` { #body-with-multiple-examples }
+
+Elbette birden fazla `examples` da geçebilirsiniz:
+
+{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *}
+
+Bunu yaptığınızda, örnekler bu body verisi için dahili **JSON Schema**’nın bir parçası olur.
+
+Buna rağmen, bu yazı yazılırken, doküman arayüzünü gösteren araç olan Swagger UI, **JSON Schema** içindeki veriler için birden fazla örneği göstermeyi desteklemiyor. Ancak aşağıda bir çözüm yolu var.
+
+### OpenAPI’ye özel `examples` { #openapi-specific-examples }
+
+**JSON Schema** `examples`’ı desteklemeden önce OpenAPI, yine `examples` adlı farklı bir alanı destekliyordu.
+
+Bu **OpenAPI’ye özel** `examples`, OpenAPI spesifikasyonunda başka bir bölümde yer alır. Her bir JSON Schema’nın içinde değil, **her bir *path operation* detayları** içinde bulunur.
+
+Swagger UI da bu özel `examples` alanını bir süredir destekliyor. Dolayısıyla bunu, **doküman arayüzünde** farklı **örnekleri göstermek** için kullanabilirsiniz.
+
+OpenAPI’ye özel bu `examples` alanının şekli, (bir `list` yerine) **birden fazla örnek** içeren bir `dict`’tir; her örnek ayrıca **OpenAPI**’ye eklenecek ekstra bilgiler içerir.
+
+Bu, OpenAPI’nin içerdiği JSON Schema’ların içine girmez; bunun yerine doğrudan *path operation* üzerinde, dışarıda yer alır.
+
+### `openapi_examples` Parametresini Kullanma { #using-the-openapi-examples-parameter }
+
+FastAPI’de OpenAPI’ye özel `examples`’ı, şu araçlar için `openapi_examples` parametresiyle tanımlayabilirsiniz:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+`dict`’in anahtarları her bir örneği tanımlar; her bir değer ise başka bir `dict`’tir.
+
+`examples` içindeki her bir örnek `dict`’i şunları içerebilir:
+
+* `summary`: Örnek için kısa açıklama.
+* `description`: Markdown metni içerebilen uzun açıklama.
+* `value`: Gösterilecek gerçek örnek (ör. bir `dict`).
+* `externalValue`: `value`’a alternatif; örneğe işaret eden bir URL. Ancak bu, `value` kadar çok araç tarafından desteklenmiyor olabilir.
+
+Şöyle kullanabilirsiniz:
+
+{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *}
+
+### Doküman Arayüzünde OpenAPI Örnekleri { #openapi-examples-in-the-docs-ui }
+
+`Body()`’ye `openapi_examples` eklendiğinde `/docs` şöyle görünür:
+
+
+
+## Teknik Detaylar { #technical-details }
+
+/// tip | İpucu
+
+Zaten **FastAPI** sürümü **0.99.0 veya üzerini** kullanıyorsanız, büyük olasılıkla bu detayları **atlanabilirsiniz**.
+
+Bunlar daha çok OpenAPI 3.1.0’ın henüz mevcut olmadığı eski sürümler için geçerlidir.
+
+Bunu kısa bir OpenAPI ve JSON Schema **tarih dersi** gibi düşünebilirsiniz. 🤓
+
+///
+
+/// warning | Uyarı
+
+Bunlar **JSON Schema** ve **OpenAPI** standartları hakkında oldukça teknik detaylardır.
+
+Yukarıdaki fikirler sizin için zaten çalışıyorsa bu kadarı yeterli olabilir; muhtemelen bu detaylara ihtiyacınız yoktur, gönül rahatlığıyla atlayabilirsiniz.
+
+///
+
+OpenAPI 3.1.0’dan önce OpenAPI, **JSON Schema**’nın daha eski ve değiştirilmiş bir sürümünü kullanıyordu.
+
+JSON Schema’da `examples` yoktu; bu yüzden OpenAPI, değiştirilmiş sürümüne kendi `example` alanını ekledi.
+
+OpenAPI ayrıca spesifikasyonun diğer bölümlerine de `example` ve `examples` alanlarını ekledi:
+
+* [`Parameter Object` (spesifikasyonda)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object) — FastAPI’de şunlar tarafından kullanılıyordu:
+ * `Path()`
+ * `Query()`
+ * `Header()`
+ * `Cookie()`
+* [`Request Body Object`; `content` alanında, `Media Type Object` üzerinde (spesifikasyonda)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object) — FastAPI’de şunlar tarafından kullanılıyordu:
+ * `Body()`
+ * `File()`
+ * `Form()`
+
+/// info | Bilgi
+
+Bu eski OpenAPI’ye özel `examples` parametresi, FastAPI `0.103.0` sürümünden beri `openapi_examples` olarak kullanılıyor.
+
+///
+
+### JSON Schema’nın `examples` alanı { #json-schemas-examples-field }
+
+Sonrasında JSON Schema, spesifikasyonun yeni bir sürümüne [`examples`](https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.9.5) alanını ekledi.
+
+Ardından yeni OpenAPI 3.1.0, bu yeni `examples` alanını içeren en güncel sürümü (JSON Schema 2020-12) temel aldı.
+
+Ve artık, deprecated olan eski tekil (ve özel) `example` alanına kıyasla bu yeni `examples` alanı önceliklidir.
+
+JSON Schema’daki bu yeni `examples` alanı, OpenAPI’de başka yerlerde kullanılan (yukarıda anlatılan) metadata’lı `dict` yapısından farklı olarak **sadece örneklerden oluşan bir `list`**’tir.
+
+/// info | Bilgi
+
+OpenAPI 3.1.0, JSON Schema ile bu yeni ve daha basit entegrasyonla yayımlandıktan sonra bile bir süre, otomatik dokümantasyonu sağlayan araç Swagger UI OpenAPI 3.1.0’ı desteklemiyordu (5.0.0 sürümünden beri destekliyor 🎉).
+
+Bu nedenle, FastAPI’nin 0.99.0 öncesi sürümleri OpenAPI 3.1.0’dan daha düşük sürümleri kullanmaya devam etti.
+
+///
+
+### Pydantic ve FastAPI `examples` { #pydantic-and-fastapi-examples }
+
+Bir Pydantic modelinin içine `schema_extra` ya da `Field(examples=["something"])` kullanarak `examples` eklediğinizde, bu örnek o Pydantic modelinin **JSON Schema**’sına eklenir.
+
+Ve Pydantic modelinin bu **JSON Schema**’sı, API’nizin **OpenAPI**’sine dahil edilir; ardından doküman arayüzünde kullanılır.
+
+FastAPI 0.99.0’dan önceki sürümlerde (0.99.0 ve üzeri daha yeni OpenAPI 3.1.0’ı kullanır) `Query()`, `Body()` vb. diğer araçlarla `example` veya `examples` kullandığınızda, bu örnekler o veriyi tanımlayan JSON Schema’ya (OpenAPI’nin kendi JSON Schema sürümüne bile) eklenmiyordu; bunun yerine doğrudan OpenAPI’deki *path operation* tanımına ekleniyordu (JSON Schema kullanan OpenAPI bölümlerinin dışında).
+
+Ancak artık FastAPI 0.99.0 ve üzeri OpenAPI 3.1.0 kullandığı (JSON Schema 2020-12) ve Swagger UI 5.0.0 ve üzeriyle birlikte, her şey daha tutarlı ve örnekler JSON Schema’ya dahil ediliyor.
+
+### Swagger UI ve OpenAPI’ye özel `examples` { #swagger-ui-and-openapi-specific-examples }
+
+Swagger UI (2023-08-26 itibarıyla) birden fazla JSON Schema örneğini desteklemediği için, kullanıcıların dokümanlarda birden fazla örnek göstermesi mümkün değildi.
+
+Bunu çözmek için FastAPI `0.103.0`, yeni `openapi_examples` parametresiyle aynı eski **OpenAPI’ye özel** `examples` alanını tanımlamayı **desteklemeye başladı**. 🤓
+
+### Özet { #summary }
+
+Eskiden tarihten pek hoşlanmadığımı söylerdim... şimdi bakın, "teknoloji tarihi" dersi anlatıyorum. 😅
+
+Kısacası, **FastAPI 0.99.0 veya üzerine yükseltin**; her şey çok daha **basit, tutarlı ve sezgisel** olur ve bu tarihsel detayların hiçbirini bilmeniz gerekmez. 😎
diff --git a/docs/tr/docs/tutorial/security/first-steps.md b/docs/tr/docs/tutorial/security/first-steps.md
new file mode 100644
index 0000000000000..5aabd7554e721
--- /dev/null
+++ b/docs/tr/docs/tutorial/security/first-steps.md
@@ -0,0 +1,203 @@
+# Güvenlik - İlk Adımlar { #security-first-steps }
+
+**backend** API’nizin bir domain’de olduğunu düşünelim.
+
+Ve başka bir domain’de ya da aynı domain’in farklı bir path’inde (veya bir mobil uygulamada) bir **frontend**’iniz var.
+
+Ve frontend’in, **username** ve **password** kullanarak backend ile kimlik doğrulaması yapabilmesini istiyorsunuz.
+
+Bunu **FastAPI** ile **OAuth2** kullanarak oluşturabiliriz.
+
+Ama ihtiyacınız olan küçük bilgi parçalarını bulmak için uzun spesifikasyonun tamamını okuma zahmetine girmeyelim.
+
+Güvenliği yönetmek için **FastAPI**’nin sunduğu araçları kullanalım.
+
+## Nasıl Görünüyor { #how-it-looks }
+
+Önce kodu kullanıp nasıl çalıştığına bakalım, sonra neler olup bittiğini anlamak için geri döneriz.
+
+## `main.py` Oluşturun { #create-main-py }
+
+Örneği `main.py` adlı bir dosyaya kopyalayın:
+
+{* ../../docs_src/security/tutorial001_an_py310.py *}
+
+## Çalıştırın { #run-it }
+
+/// info | Bilgi
+
+The [`python-multipart`](https://github.com/Kludex/python-multipart) paketi, `pip install "fastapi[standard]"` komutunu çalıştırdığınızda **FastAPI** ile birlikte otomatik olarak kurulur.
+
+Ancak `pip install fastapi` komutunu kullanırsanız, `python-multipart` paketi varsayılan olarak dahil edilmez.
+
+Elle kurmak için bir [virtual environment](../../virtual-environments.md) oluşturduğunuzdan, onu aktive ettiğinizden emin olun ve ardından şununla kurun:
+
+```console
+$ pip install python-multipart
+```
+
+Bunun nedeni, **OAuth2**’nin `username` ve `password` göndermek için "form data" kullanmasıdır.
+
+///
+
+Örneği şu şekilde çalıştırın:
+
+
+
+/// check | Authorize butonu!
+
+Artık parıl parıl yeni bir "Authorize" butonunuz var.
+
+Ayrıca *path operation*’ınızın sağ üst köşesinde tıklayabileceğiniz küçük bir kilit simgesi de bulunuyor.
+
+///
+
+Ve ona tıklarsanız, `username` ve `password` (ve diğer opsiyonel alanları) girebileceğiniz küçük bir yetkilendirme formu görürsünüz:
+
+
+
+/// note | Not
+
+Formda ne yazdığınızın önemi yok; şimdilik çalışmayacak. Ama birazdan oraya da geleceğiz.
+
+///
+
+Bu, elbette son kullanıcılar için bir frontend değil; ancak tüm API’nizi etkileşimli şekilde belgelemek için harika bir otomatik araçtır.
+
+Frontend ekibi tarafından kullanılabilir (bu ekip siz de olabilirsiniz).
+
+Üçüncü taraf uygulamalar ve sistemler tarafından kullanılabilir.
+
+Ve aynı uygulamayı debug etmek, kontrol etmek ve test etmek için sizin tarafınızdan da kullanılabilir.
+
+## `password` Flow { #the-password-flow }
+
+Şimdi biraz geri dönüp bunların ne olduğuna bakalım.
+
+`password` "flow"u, OAuth2’de güvenlik ve authentication’ı yönetmek için tanımlanmış yöntemlerden ("flow"lardan) biridir.
+
+OAuth2, backend’in veya API’nin, kullanıcıyı authenticate eden server’dan bağımsız olabilmesi için tasarlanmıştır.
+
+Ancak bu örnekte, aynı **FastAPI** uygulaması hem API’yi hem de authentication’ı yönetecek.
+
+O yüzden basitleştirilmiş bu bakış açısından üzerinden geçelim:
+
+* Kullanıcı frontend’de `username` ve `password` yazar ve `Enter`’a basar.
+* Frontend (kullanıcının browser’ında çalışır), bu `username` ve `password` değerlerini API’mizdeki belirli bir URL’ye gönderir (`tokenUrl="token"` ile tanımlanan).
+* API, `username` ve `password` değerlerini kontrol eder ve bir "token" ile response döner (henüz bunların hiçbirini implement etmedik).
+ * "Token", daha sonra bu kullanıcıyı doğrulamak için kullanabileceğimiz içerik taşıyan bir string’dir.
+ * Normalde token’ın bir süre sonra süresi dolacak şekilde ayarlanması beklenir.
+ * Böylece kullanıcının bir noktada tekrar giriş yapması gerekir.
+ * Ayrıca token çalınırsa risk daha düşük olur. Çoğu durumda, sonsuza kadar çalışacak kalıcı bir anahtar gibi değildir.
+* Frontend bu token’ı geçici olarak bir yerde saklar.
+* Kullanıcı frontend’de tıklayarak web uygulamasının başka bir bölümüne gider.
+* Frontend’in API’den daha fazla veri alması gerekir.
+ * Ancak o endpoint için authentication gereklidir.
+ * Bu yüzden API’mizle authenticate olmak için `Authorization` header’ını, `Bearer ` + token değeriyle gönderir.
+ * Token `foobar` içeriyorsa `Authorization` header’ının içeriği `Bearer foobar` olur.
+
+## **FastAPI**’nin `OAuth2PasswordBearer`’ı { #fastapis-oauth2passwordbearer }
+
+**FastAPI**, bu güvenlik özelliklerini implement etmek için farklı soyutlama seviyelerinde çeşitli araçlar sağlar.
+
+Bu örnekte **OAuth2**’yi, **Password** flow ile, **Bearer** token kullanarak uygulayacağız. Bunu `OAuth2PasswordBearer` sınıfı ile yaparız.
+
+/// info | Bilgi
+
+"Bearer" token tek seçenek değildir.
+
+Ama bizim kullanım senaryomuz için en iyi seçenek odur.
+
+Ayrıca bir OAuth2 uzmanı değilseniz ve ihtiyaçlarınıza daha uygun başka bir seçeneğin neden gerekli olduğunu net olarak bilmiyorsanız, çoğu kullanım senaryosu için de en uygun seçenek olacaktır.
+
+Bu durumda bile **FastAPI**, onu oluşturabilmeniz için gereken araçları sunar.
+
+///
+
+`OAuth2PasswordBearer` sınıfının bir instance’ını oluştururken `tokenUrl` parametresini veririz. Bu parametre, client’ın (kullanıcının browser’ında çalışan frontend’in) token almak için `username` ve `password` göndereceği URL’yi içerir.
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
+
+/// tip | İpucu
+
+Burada `tokenUrl="token"`, henüz oluşturmadığımız göreli bir URL olan `token`’ı ifade eder. Göreli URL olduğu için `./token` ile eşdeğerdir.
+
+Göreli URL kullandığımız için, API’niz `https://example.com/` adresinde olsaydı `https://example.com/token` anlamına gelirdi. Ama API’niz `https://example.com/api/v1/` adresinde olsaydı, bu kez `https://example.com/api/v1/token` anlamına gelirdi.
+
+Göreli URL kullanmak, [Behind a Proxy](../../advanced/behind-a-proxy.md) gibi daha ileri kullanım senaryolarında bile uygulamanızın çalışmaya devam etmesini garanti etmek açısından önemlidir.
+
+///
+
+Bu parametre o endpoint’i / *path operation*’ı oluşturmaz; fakat `/token` URL’sinin client’ın token almak için kullanması gereken URL olduğunu bildirir. Bu bilgi OpenAPI’de, dolayısıyla etkileşimli API dokümantasyon sistemlerinde kullanılır.
+
+Birazdan gerçek path operation’ı da oluşturacağız.
+
+/// info | Teknik Detaylar
+
+Eğer çok katı bir "Pythonista" iseniz, `token_url` yerine `tokenUrl` şeklindeki parametre adlandırma stilini sevmeyebilirsiniz.
+
+Bunun nedeni, OpenAPI spesifikasyonundaki isimle aynı adın kullanılmasıdır. Böylece bu güvenlik şemalarından herhangi biri hakkında daha fazla araştırma yapmanız gerekirse, adı kopyalayıp yapıştırarak kolayca daha fazla bilgi bulabilirsiniz.
+
+///
+
+`oauth2_scheme` değişkeni, `OAuth2PasswordBearer`’ın bir instance’ıdır; ama aynı zamanda "callable"dır.
+
+Şu şekilde çağrılabilir:
+
+```Python
+oauth2_scheme(some, parameters)
+```
+
+Dolayısıyla `Depends` ile kullanılabilir.
+
+### Kullanın { #use-it }
+
+Artık `Depends` ile bir dependency olarak `oauth2_scheme`’i geçebilirsiniz.
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+Bu dependency, *path operation function* içindeki `token` parametresine atanacak bir `str` sağlar.
+
+**FastAPI**, bu dependency’yi OpenAPI şemasında (ve otomatik API dokümanlarında) bir "security scheme" tanımlamak için kullanabileceğini bilir.
+
+/// info | Teknik Detaylar
+
+**FastAPI**, bir dependency içinde tanımlanan `OAuth2PasswordBearer` sınıfını OpenAPI’de security scheme tanımlamak için kullanabileceğini bilir; çünkü bu sınıf `fastapi.security.oauth2.OAuth2`’den kalıtım alır, o da `fastapi.security.base.SecurityBase`’den kalıtım alır.
+
+OpenAPI (ve otomatik API dokümanları) ile entegre olan tüm security araçları `SecurityBase`’den kalıtım alır; **FastAPI** bu sayede onları OpenAPI’ye nasıl entegre edeceğini anlayabilir.
+
+///
+
+## Ne Yapar { #what-it-does }
+
+Request içinde `Authorization` header’ını arar, değerin `Bearer ` + bir token olup olmadığını kontrol eder ve token’ı `str` olarak döndürür.
+
+Eğer `Authorization` header’ını görmezse ya da değer `Bearer ` token’ı içermiyorsa, doğrudan 401 status code hatasıyla (`UNAUTHORIZED`) response döner.
+
+Token’ın var olup olmadığını kontrol edip ayrıca hata döndürmenize bile gerek yoktur. Fonksiyonunuz çalışıyorsa, token içinde bir `str` olacağından emin olabilirsiniz.
+
+Bunu şimdiden etkileşimli dokümanlarda deneyebilirsiniz:
+
+
+
+Henüz token’ın geçerliliğini doğrulamıyoruz, ama başlangıç için bu bile yeterli.
+
+## Özet { #recap }
+
+Yani sadece 3 veya 4 ekstra satırla, şimdiden ilkel de olsa bir güvenlik katmanı elde etmiş oldunuz.
diff --git a/docs/tr/docs/tutorial/security/get-current-user.md b/docs/tr/docs/tutorial/security/get-current-user.md
new file mode 100644
index 0000000000000..cc7f7a51b921a
--- /dev/null
+++ b/docs/tr/docs/tutorial/security/get-current-user.md
@@ -0,0 +1,105 @@
+# Mevcut Kullanıcıyı Alma { #get-current-user }
+
+Önceki bölümde güvenlik sistemi (dependency injection sistemine dayanır) *path operation function*'a `str` olarak bir `token` veriyordu:
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+Ancak bu hâlâ pek kullanışlı değil.
+
+Bize mevcut kullanıcıyı verecek şekilde düzenleyelim.
+
+## Bir kullanıcı modeli oluşturun { #create-a-user-model }
+
+Önce bir Pydantic kullanıcı modeli oluşturalım.
+
+Body'leri bildirmek için Pydantic'i nasıl kullanıyorsak, aynı şekilde onu başka her yerde de kullanabiliriz:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *}
+
+## `get_current_user` dependency'si oluşturun { #create-a-get-current-user-dependency }
+
+Bir `get_current_user` dependency'si oluşturalım.
+
+Dependency'lerin alt dependency'leri olabileceğini hatırlıyor musunuz?
+
+`get_current_user`, daha önce oluşturduğumuz `oauth2_scheme` ile aynı dependency'yi kullanacak.
+
+Daha önce *path operation* içinde doğrudan yaptığımız gibi, yeni dependency'miz `get_current_user`, alt dependency olan `oauth2_scheme` üzerinden `str` olarak bir `token` alacak:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *}
+
+## Kullanıcıyı alın { #get-the-user }
+
+`get_current_user`, oluşturduğumuz (sahte) bir yardımcı (utility) fonksiyonu kullanacak; bu fonksiyon `str` olarak bir token alır ve Pydantic `User` modelimizi döndürür:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *}
+
+## Mevcut kullanıcıyı enjekte edin { #inject-the-current-user }
+
+Artık *path operation* içinde `get_current_user` ile aynı `Depends` yaklaşımını kullanabiliriz:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *}
+
+`current_user` tipini Pydantic `User` modeli olarak belirttiğimize dikkat edin.
+
+Bu sayede fonksiyonun içinde otomatik tamamlama ve tip kontrollerinin tamamından faydalanırız.
+
+/// tip | İpucu
+
+Request body'lerinin de Pydantic modelleri ile bildirildiğini hatırlıyor olabilirsiniz.
+
+Burada `Depends` kullandığınız için **FastAPI** karışıklık yaşamaz.
+
+///
+
+/// check | Ek bilgi
+
+Bu dependency sisteminin tasarımı, hepsi `User` modeli döndüren farklı dependency'lere (farklı "dependable"lara) sahip olmamıza izin verir.
+
+Bu tipte veri döndürebilen yalnızca tek bir dependency ile sınırlı değiliz.
+
+///
+
+## Diğer modeller { #other-models }
+
+Artık *path operation function* içinde mevcut kullanıcıyı doğrudan alabilir ve güvenlik mekanizmalarını `Depends` kullanarak **Dependency Injection** seviyesinde yönetebilirsiniz.
+
+Ayrıca güvenlik gereksinimleri için herhangi bir model veya veri kullanabilirsiniz (bu örnekte bir Pydantic `User` modeli).
+
+Ancak belirli bir data model, class ya da type kullanmak zorunda değilsiniz.
+
+Modelinizde bir `id` ve `email` olsun, ama `username` olmasın mı istiyorsunuz? Elbette. Aynı araçları kullanabilirsiniz.
+
+Sadece bir `str` mı istiyorsunuz? Ya da sadece bir `dict`? Veya doğrudan bir veritabanı class model instance'ı? Hepsi aynı şekilde çalışır.
+
+Uygulamanıza giriş yapan kullanıcılar yok da robotlar, botlar veya yalnızca bir access token'a sahip başka sistemler mi var? Yine, her şey aynı şekilde çalışır.
+
+Uygulamanız için neye ihtiyacınız varsa o türden bir model, class ve veritabanı kullanın. **FastAPI**, dependency injection sistemiyle bunları destekler.
+
+## Kod boyutu { #code-size }
+
+Bu örnek biraz uzun görünebilir. Güvenlik, data model'ler, utility fonksiyonlar ve *path operation*'ları aynı dosyada bir araya getirdiğimizi unutmayın.
+
+Ama kritik nokta şu:
+
+Güvenlik ve dependency injection tarafını bir kez yazarsınız.
+
+İstediğiniz kadar karmaşık hâle getirebilirsiniz. Yine de hepsi tek bir yerde ve sadece bir kez yazılmış olur. Üstelik tüm esneklikle.
+
+Sonrasında aynı güvenlik sistemini kullanan binlerce endpoint (*path operation*) olabilir.
+
+Ve bunların hepsi (ya da istediğiniz bir kısmı) bu dependency'leri veya oluşturacağınız başka dependency'leri yeniden kullanmaktan faydalanabilir.
+
+Hatta bu binlerce *path operation* 3 satır kadar kısa olabilir:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *}
+
+## Özet { #recap }
+
+Artık *path operation function* içinde mevcut kullanıcıyı doğrudan alabilirsiniz.
+
+Yolun yarısına geldik.
+
+Kullanıcının/istemcinin gerçekten `username` ve `password` göndermesini sağlayacak bir *path operation* eklememiz gerekiyor.
+
+Sırada bu var.
diff --git a/docs/tr/docs/tutorial/security/index.md b/docs/tr/docs/tutorial/security/index.md
new file mode 100644
index 0000000000000..a592db6df5342
--- /dev/null
+++ b/docs/tr/docs/tutorial/security/index.md
@@ -0,0 +1,106 @@
+# Güvenlik { #security }
+
+Güvenlik, authentication ve authorization’ı ele almanın birçok yolu vardır.
+
+Ve bu konu genellikle karmaşık ve "zor"dur.
+
+Birçok framework ve sistemde yalnızca security ve authentication’ı yönetmek bile ciddi miktarda emek ve kod gerektirir (çoğu durumda yazılan toplam kodun %50’si veya daha fazlası olabilir).
+
+**FastAPI**, tüm security spesifikasyonlarını baştan sona inceleyip öğrenmek zorunda kalmadan **Security** konusunu kolay, hızlı ve standart bir şekilde ele almanıza yardımcı olacak çeşitli araçlar sunar.
+
+Ama önce, küçük birkaç kavrama bakalım.
+
+## Acelem var? { #in-a-hurry }
+
+Bu terimlerin hiçbirini umursamıyorsanız ve sadece kullanıcı adı ve parola tabanlı authentication ile security’yi *hemen şimdi* eklemeniz gerekiyorsa, bir sonraki bölümlere geçin.
+
+## OAuth2 { #oauth2 }
+
+OAuth2, authentication ve authorization’ı yönetmek için çeşitli yöntemleri tanımlayan bir spesifikasyondur.
+
+Oldukça kapsamlı bir spesifikasyondur ve birkaç karmaşık use case’i kapsar.
+
+"Üçüncü taraf" kullanarak authentication yapmanın yollarını da içerir.
+
+"Facebook, Google, X (Twitter), GitHub ile giriş yap" bulunan sistemlerin arka planda kullandığı şey de budur.
+
+### OAuth 1 { #oauth-1 }
+
+OAuth 1 de vardı; OAuth2’den çok farklıdır ve daha karmaşıktır, çünkü iletişimi nasıl şifreleyeceğinize dair doğrudan spesifikasyonlar içeriyordu.
+
+Günümüzde pek popüler değildir veya pek kullanılmaz.
+
+OAuth2 ise iletişimin nasıl şifreleneceğini belirtmez; uygulamanızın HTTPS ile sunulmasını bekler.
+
+/// tip | İpucu
+
+**deployment** bölümünde Traefik ve Let's Encrypt kullanarak ücretsiz şekilde HTTPS’i nasıl kuracağınızı göreceksiniz.
+
+///
+
+## OpenID Connect { #openid-connect }
+
+OpenID Connect, **OAuth2** tabanlı başka bir spesifikasyondur.
+
+OAuth2’de nispeten belirsiz kalan bazı noktaları tanımlayarak onu daha birlikte çalışabilir (interoperable) hâle getirmeye çalışır.
+
+Örneğin, Google ile giriş OpenID Connect kullanır (arka planda OAuth2 kullanır).
+
+Ancak Facebook ile giriş OpenID Connect’i desteklemez. Kendine özgü bir OAuth2 çeşidi vardır.
+
+### OpenID ("OpenID Connect" değil) { #openid-not-openid-connect }
+
+Bir de "OpenID" spesifikasyonu vardı. Bu da **OpenID Connect** ile aynı problemi çözmeye çalışıyordu ama OAuth2 tabanlı değildi.
+
+Dolayısıyla tamamen ayrı, ek bir sistemdi.
+
+Günümüzde pek popüler değildir veya pek kullanılmaz.
+
+## OpenAPI { #openapi }
+
+OpenAPI (önceden Swagger olarak biliniyordu), API’ler inşa etmek için açık spesifikasyondur (artık Linux Foundation’ın bir parçası).
+
+**FastAPI**, **OpenAPI** tabanlıdır.
+
+Bu sayede birden fazla otomatik etkileşimli dokümantasyon arayüzü, code generation vb. mümkün olur.
+
+OpenAPI, birden fazla security "scheme" tanımlamanın bir yolunu sunar.
+
+Bunları kullanarak, etkileşimli dokümantasyon sistemleri de dahil olmak üzere tüm bu standart tabanlı araçlardan faydalanabilirsiniz.
+
+OpenAPI şu security scheme’lerini tanımlar:
+
+* `apiKey`: uygulamaya özel bir anahtar; şuradan gelebilir:
+ * Bir query parameter.
+ * Bir header.
+ * Bir cookie.
+* `http`: standart HTTP authentication sistemleri, örneğin:
+ * `bearer`: `Authorization` header’ı; değeri `Bearer ` + bir token olacak şekilde. Bu, OAuth2’den gelir.
+ * HTTP Basic authentication.
+ * HTTP Digest, vb.
+* `oauth2`: OAuth2 ile security’yi yönetmenin tüm yolları ("flow" olarak adlandırılır).
+ * Bu flow’ların birçoğu, bir OAuth 2.0 authentication provider (Google, Facebook, X (Twitter), GitHub vb.) oluşturmak için uygundur:
+ * `implicit`
+ * `clientCredentials`
+ * `authorizationCode`
+ * Ancak, aynı uygulamanın içinde doğrudan authentication yönetmek için mükemmel şekilde kullanılabilecek özel bir "flow" vardır:
+ * `password`: sonraki bazı bölümlerde bunun örnekleri ele alınacak.
+* `openIdConnect`: OAuth2 authentication verisinin otomatik olarak nasıl keşfedileceğini tanımlamanın bir yolunu sunar.
+ * Bu otomatik keşif, OpenID Connect spesifikasyonunda tanımlanan şeydir.
+
+
+/// tip | İpucu
+
+Google, Facebook, X (Twitter), GitHub vb. gibi diğer authentication/authorization provider’larını entegre etmek de mümkündür ve nispeten kolaydır.
+
+En karmaşık kısım, bu tür bir authentication/authorization provider’ı inşa etmektir; ancak **FastAPI** ağır işleri sizin yerinize yaparken bunu kolayca yapabilmeniz için araçlar sunar.
+
+///
+
+## **FastAPI** yardımcı araçları { #fastapi-utilities }
+
+FastAPI, `fastapi.security` modülünde bu security scheme’lerinin her biri için, bu mekanizmaları kullanmayı kolaylaştıran çeşitli araçlar sağlar.
+
+Sonraki bölümlerde, **FastAPI**’nin sunduğu bu araçları kullanarak API’nize nasıl security ekleyeceğinizi göreceksiniz.
+
+Ayrıca bunun etkileşimli dokümantasyon sistemine nasıl otomatik olarak entegre edildiğini de göreceksiniz.
diff --git a/docs/tr/docs/tutorial/security/oauth2-jwt.md b/docs/tr/docs/tutorial/security/oauth2-jwt.md
new file mode 100644
index 0000000000000..4b68bc4517cb6
--- /dev/null
+++ b/docs/tr/docs/tutorial/security/oauth2-jwt.md
@@ -0,0 +1,277 @@
+# Password ile OAuth2 (ve hashing), JWT token'ları ile Bearer { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
+
+Artık tüm security flow elimizde olduğuna göre, uygulamayı gerçekten güvenli hâle getirelim: JWT token'ları ve güvenli password hashing kullanacağız.
+
+Bu kodu uygulamanızda gerçekten kullanabilirsiniz; password hash'lerini veritabanınıza kaydedebilirsiniz, vb.
+
+Bir önceki bölümde bıraktığımız yerden başlayıp üzerine ekleyerek ilerleyeceğiz.
+
+## JWT Hakkında { #about-jwt }
+
+JWT, "JSON Web Tokens" anlamına gelir.
+
+Bir JSON nesnesini, boşluk içermeyen uzun ve yoğun bir string'e kodlamak için kullanılan bir standarttır. Şuna benzer:
+
+```
+eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
+```
+
+Şifrelenmiş değildir; yani herkes içeriğindeki bilgiyi geri çıkarabilir.
+
+Ancak imzalanmıştır. Bu yüzden, sizin ürettiğiniz bir token'ı aldığınızda, gerçekten onu sizin ürettiğinizi doğrulayabilirsiniz.
+
+Bu şekilde, örneğin 1 haftalık süre sonu (expiration) olan bir token oluşturabilirsiniz. Sonra kullanıcı ertesi gün token ile geri geldiğinde, kullanıcının hâlâ sisteminizde oturum açmış olduğunu bilirsiniz.
+
+Bir hafta sonra token'ın süresi dolar; kullanıcı yetkilendirilmez ve yeni bir token almak için tekrar giriş yapmak zorunda kalır. Ayrıca kullanıcı (veya üçüncü bir taraf) token'ı değiştirip süre sonunu farklı göstermek isterse bunu tespit edebilirsiniz; çünkü imzalar eşleşmez.
+
+JWT token'larıyla oynayıp nasıl çalıştıklarını görmek isterseniz [https://jwt.io](https://jwt.io/) adresine bakın.
+
+## `PyJWT` Kurulumu { #install-pyjwt }
+
+Python'da JWT token'larını üretmek ve doğrulamak için `PyJWT` kurmamız gerekiyor.
+
+Bir [sanal ortam](../../virtual-environments.md) oluşturduğunuzdan emin olun, aktif edin ve ardından `pyjwt` kurun:
+
+
+
+Uygulamayı, öncekiyle aynı şekilde authorize edin.
+
+Şu kimlik bilgilerini kullanarak:
+
+Username: `johndoe`
+Password: `secret`
+
+/// check | Ek bilgi
+
+Kodun hiçbir yerinde düz metin password "`secret`" yok; sadece hash'lenmiş hâli var.
+
+///
+
+
+
+`/users/me/` endpoint'ini çağırın; response şöyle olacaktır:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false
+}
+```
+
+
+
+Developer tools'u açarsanız, gönderilen verinin sadece token'ı içerdiğini görebilirsiniz. Password sadece kullanıcıyı authenticate edip access token almak için yapılan ilk request'te gönderilir, sonrasında gönderilmez:
+
+
+
+/// note | Not
+
+`Authorization` header'ına dikkat edin; değeri `Bearer ` ile başlıyor.
+
+///
+
+## `scopes` ile İleri Seviye Kullanım { #advanced-usage-with-scopes }
+
+OAuth2'nin "scopes" kavramı vardır.
+
+Bunları kullanarak bir JWT token'a belirli bir izin seti ekleyebilirsiniz.
+
+Sonra bu token'ı bir kullanıcıya doğrudan veya bir üçüncü tarafa verip, API'nizle belirli kısıtlarla etkileşime girmesini sağlayabilirsiniz.
+
+Nasıl kullanıldıklarını ve **FastAPI** ile nasıl entegre olduklarını, ileride **Advanced User Guide** içinde öğreneceksiniz.
+
+## Özet { #recap }
+
+Şimdiye kadar gördüklerinizle, OAuth2 ve JWT gibi standartları kullanarak güvenli bir **FastAPI** uygulaması kurabilirsiniz.
+
+Neredeyse her framework'te security'yi ele almak oldukça hızlı bir şekilde karmaşık bir konu hâline gelir.
+
+Bunu çok basitleştiren birçok paket, veri modeli, veritabanı ve mevcut özelliklerle ilgili pek çok ödün vermek zorunda kalır. Hatta bazıları işi aşırı basitleştirirken arka planda güvenlik açıkları da barındırır.
+
+---
+
+**FastAPI**, hiçbir veritabanı, veri modeli veya araç konusunda ödün vermez.
+
+Projenize en uygun olanları seçebilmeniz için size tam esneklik sağlar.
+
+Ayrıca `pwdlib` ve `PyJWT` gibi iyi bakımı yapılan ve yaygın kullanılan paketleri doğrudan kullanabilirsiniz; çünkü **FastAPI**, haricî paketleri entegre etmek için karmaşık mekanizmalara ihtiyaç duymaz.
+
+Buna rağmen, esneklikten, sağlamlıktan veya güvenlikten ödün vermeden süreci mümkün olduğunca basitleştiren araçları sağlar.
+
+Ve OAuth2 gibi güvenli, standart protokolleri nispeten basit bir şekilde kullanabilir ve uygulayabilirsiniz.
+
+Aynı standartları izleyerek, daha ince taneli (fine-grained) bir izin sistemi için OAuth2 "scopes" kullanımını **Advanced User Guide** içinde daha detaylı öğrenebilirsiniz. Scopes'lu OAuth2; Facebook, Google, GitHub, Microsoft, X (Twitter) vb. pek çok büyük kimlik doğrulama sağlayıcısının, üçüncü taraf uygulamaların kullanıcıları adına API'leriyle etkileşebilmesine izin vermek için kullandığı mekanizmadır.
diff --git a/docs/tr/docs/tutorial/security/simple-oauth2.md b/docs/tr/docs/tutorial/security/simple-oauth2.md
new file mode 100644
index 0000000000000..9893cc800e207
--- /dev/null
+++ b/docs/tr/docs/tutorial/security/simple-oauth2.md
@@ -0,0 +1,289 @@
+# Password ve Bearer ile Basit OAuth2 { #simple-oauth2-with-password-and-bearer }
+
+Şimdi önceki bölümün üzerine inşa edip, eksik parçaları ekleyerek tam bir güvenlik akışı oluşturalım.
+
+## `username` ve `password`’ü Alma { #get-the-username-and-password }
+
+`username` ve `password`’ü almak için **FastAPI** security yardımcı araçlarını kullanacağız.
+
+OAuth2, (bizim kullandığımız) "password flow" kullanılırken client/kullanıcının form verisi olarak `username` ve `password` alanlarını göndermesi gerektiğini belirtir.
+
+Ayrıca spesifikasyon, bu alanların adlarının tam olarak böyle olması gerektiğini söyler. Yani `user-name` veya `email` işe yaramaz.
+
+Ancak merak etmeyin, frontend’de son kullanıcılarınıza dilediğiniz gibi gösterebilirsiniz.
+
+Veritabanı model(ler)inizde de istediğiniz başka isimleri kullanabilirsiniz.
+
+Fakat login *path operation*’ı için, spesifikasyonla uyumlu olmak (ve örneğin entegre API dokümantasyon sistemini kullanabilmek) adına bu isimleri kullanmamız gerekiyor.
+
+Spesifikasyon ayrıca `username` ve `password`’ün form verisi olarak gönderilmesi gerektiğini de söyler (yani burada JSON yok).
+
+### `scope` { #scope }
+
+Spesifikasyon, client’ın "`scope`" adlı başka bir form alanı da gönderebileceğini söyler.
+
+Form alanının adı `scope`’tur (tekil), ama aslında boşluklarla ayrılmış "scope"’lardan oluşan uzun bir string’dir.
+
+Her bir "scope" sadece bir string’dir (boşluk içermez).
+
+Genelde belirli güvenlik izinlerini (permission) belirtmek için kullanılırlar, örneğin:
+
+* `users:read` veya `users:write` yaygın örneklerdir.
+* `instagram_basic` Facebook / Instagram tarafından kullanılır.
+* `https://www.googleapis.com/auth/drive` Google tarafından kullanılır.
+
+/// info | Bilgi
+
+OAuth2’de bir "scope", gerekli olan belirli bir izni ifade eden basit bir string’dir.
+
+`:` gibi başka karakterler içermesi veya URL olması önemli değildir.
+
+Bu detaylar implementasyon’a özeldir.
+
+OAuth2 açısından bunlar sadece string’lerdir.
+
+///
+
+## `username` ve `password`’ü Almak İçin Kod { #code-to-get-the-username-and-password }
+
+Şimdi bunu yönetmek için **FastAPI**’nin sağladığı araçları kullanalım.
+
+### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform }
+
+Önce `OAuth2PasswordRequestForm`’u import edin ve `/token` için *path operation* içinde `Depends` ile dependency olarak kullanın:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}
+
+`OAuth2PasswordRequestForm`, şu alanları içeren bir form body tanımlayan bir class dependency’sidir:
+
+* `username`.
+* `password`.
+* Boşlukla ayrılmış string’lerden oluşan büyük bir string olarak opsiyonel `scope` alanı.
+* Opsiyonel `grant_type`.
+
+/// tip | İpucu
+
+OAuth2 spesifikasyonu aslında `grant_type` alanını sabit bir `password` değeriyle *zorunlu kılar*, ancak `OAuth2PasswordRequestForm` bunu zorlamaz.
+
+Bunu zorlamak istiyorsanız, `OAuth2PasswordRequestForm` yerine `OAuth2PasswordRequestFormStrict` kullanın.
+
+///
+
+* Opsiyonel `client_id` (bu örnekte ihtiyacımız yok).
+* Opsiyonel `client_secret` (bu örnekte ihtiyacımız yok).
+
+/// info | Bilgi
+
+`OAuth2PasswordRequestForm`, `OAuth2PasswordBearer` gibi **FastAPI**’ye özel “özel bir sınıf” değildir.
+
+`OAuth2PasswordBearer`, bunun bir security scheme olduğunu **FastAPI**’ye bildirir. Bu yüzden OpenAPI’ye o şekilde eklenir.
+
+Ama `OAuth2PasswordRequestForm` sadece bir class dependency’dir; bunu kendiniz de yazabilirdiniz ya da doğrudan `Form` parametreleri tanımlayabilirdiniz.
+
+Fakat çok yaygın bir kullanım olduğu için **FastAPI** bunu işleri kolaylaştırmak adına doğrudan sağlar.
+
+///
+
+### Form Verisini Kullanma { #use-the-form-data }
+
+/// tip | İpucu
+
+`OAuth2PasswordRequestForm` dependency class’ının instance’ında boşluklarla ayrılmış uzun string olarak bir `scope` attribute’u olmaz; bunun yerine gönderilen her scope için gerçek string listesini içeren `scopes` attribute’u olur.
+
+Bu örnekte `scopes` kullanmıyoruz, ama ihtiyacınız olursa bu özellik hazır.
+
+///
+
+Şimdi form alanındaki `username`’i kullanarak (sahte) veritabanından kullanıcı verisini alın.
+
+Böyle bir kullanıcı yoksa, "Incorrect username or password" diyerek bir hata döndürelim.
+
+Hata için `HTTPException` exception’ını kullanıyoruz:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}
+
+### Password’ü Kontrol Etme { #check-the-password }
+
+Bu noktada veritabanından kullanıcı verisine sahibiz, ancak password’ü henüz kontrol etmedik.
+
+Önce bu veriyi Pydantic `UserInDB` modeline koyalım.
+
+Asla düz metin (plaintext) password kaydetmemelisiniz; bu yüzden (sahte) password hashing sistemini kullanacağız.
+
+Password’ler eşleşmezse, aynı hatayı döndürürüz.
+
+#### Password hashing { #password-hashing }
+
+"Hashing" şudur: bir içeriği (bu örnekte password) anlaşılmaz görünen bayt dizisine (yani bir string’e) dönüştürmek.
+
+Aynı içeriği (aynı password’ü) her verdiğinizde, birebir aynı anlamsız görünen çıktıyı elde edersiniz.
+
+Ama bu anlamsız çıktıyı tekrar password’e geri çeviremezsiniz.
+
+##### Neden password hashing kullanılır { #why-use-password-hashing }
+
+Veritabanınız çalınırsa, hırsız kullanıcılarınızın düz metin password’lerine değil, sadece hash’lere sahip olur.
+
+Dolayısıyla hırsız, aynı password’leri başka bir sistemde denemeye çalışamaz (birçok kullanıcı her yerde aynı password’ü kullandığı için bu tehlikeli olurdu).
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}
+
+#### `**user_dict` Hakkında { #about-user-dict }
+
+`UserInDB(**user_dict)` şu anlama gelir:
+
+*`user_dict` içindeki key ve value’ları doğrudan key-value argümanları olarak geçir; şu ifadeyle eşdeğerdir:*
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ disabled = user_dict["disabled"],
+ hashed_password = user_dict["hashed_password"],
+)
+```
+
+/// info | Bilgi
+
+`**user_dict` için daha kapsamlı bir açıklama için [**Extra Models** dokümantasyonundaki ilgili bölüme](../extra-models.md#about-user-in-dict) geri dönüp bakın.
+
+///
+
+## Token’ı Döndürme { #return-the-token }
+
+`token` endpoint’inin response’u bir JSON object olmalıdır.
+
+Bir `token_type` içermelidir. Biz "Bearer" token’ları kullandığımız için token type "`bearer`" olmalıdır.
+
+Ayrıca `access_token` içermelidir; bunun değeri access token’ımızı içeren bir string olmalıdır.
+
+Bu basit örnekte tamamen güvensiz davranıp token olarak aynı `username`’i döndüreceğiz.
+
+/// tip | İpucu
+
+Bir sonraki bölümde, password hashing ve JWT token’ları ile gerçekten güvenli bir implementasyon göreceksiniz.
+
+Ama şimdilik ihtiyacımız olan spesifik detaylara odaklanalım.
+
+///
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}
+
+/// tip | İpucu
+
+Spesifikasyona göre, bu örnekteki gibi `access_token` ve `token_type` içeren bir JSON döndürmelisiniz.
+
+Bunu kendi kodunuzda kendiniz yapmalı ve bu JSON key’lerini kullandığınızdan emin olmalısınız.
+
+Spesifikasyonlara uyum için, doğru yapmanız gereken neredeyse tek şey budur.
+
+Geri kalanını **FastAPI** sizin yerinize yönetir.
+
+///
+
+## Dependency’leri Güncelleme { #update-the-dependencies }
+
+Şimdi dependency’lerimizi güncelleyeceğiz.
+
+`current_user`’ı *sadece* kullanıcı aktifse almak istiyoruz.
+
+Bu yüzden, `get_current_user`’ı dependency olarak kullanan ek bir dependency olan `get_current_active_user`’ı oluşturuyoruz.
+
+Bu iki dependency de kullanıcı yoksa veya pasifse sadece HTTP hatası döndürecek.
+
+Dolayısıyla endpoint’imizde kullanıcıyı ancak kullanıcı varsa, doğru şekilde authenticate edildiyse ve aktifse alacağız:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}
+
+/// info | Bilgi
+
+Burada `Bearer` değerine sahip ek `WWW-Authenticate` header’ını döndürmemiz de spesifikasyonun bir parçasıdır.
+
+Herhangi bir HTTP (hata) durum kodu 401 "UNAUTHORIZED", ayrıca `WWW-Authenticate` header’ı da döndürmelidir.
+
+Bearer token’lar (bizim durumumuz) için bu header’ın değeri `Bearer` olmalıdır.
+
+Aslında bu ekstra header’ı atlayabilirsiniz, yine de çalışır.
+
+Ama spesifikasyonlara uyumlu olması için burada eklenmiştir.
+
+Ayrıca, bunu bekleyen ve kullanan araçlar olabilir (şimdi veya ileride) ve bu da sizin ya da kullanıcılarınız için faydalı olabilir.
+
+Standartların faydası da bu...
+
+///
+
+## Çalışır Halini Görün { #see-it-in-action }
+
+Etkileşimli dokümanları açın: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).
+
+### Authenticate Olma { #authenticate }
+
+"Authorize" butonuna tıklayın.
+
+Şu bilgileri kullanın:
+
+User: `johndoe`
+
+Password: `secret`
+
+
+
+Sistemde authenticate olduktan sonra şöyle görürsünüz:
+
+
+
+### Kendi Kullanıcı Verinizi Alma { #get-your-own-user-data }
+
+Şimdi `/users/me` path’inde `GET` operasyonunu kullanın.
+
+Kullanıcınızın verisini şöyle alırsınız:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false,
+ "hashed_password": "fakehashedsecret"
+}
+```
+
+
+
+Kilit ikonuna tıklayıp logout olursanız ve sonra aynı operasyonu tekrar denerseniz, şu şekilde bir HTTP 401 hatası alırsınız:
+
+```JSON
+{
+ "detail": "Not authenticated"
+}
+```
+
+### Pasif Kullanıcı { #inactive-user }
+
+Şimdi pasif bir kullanıcıyla deneyin; şu bilgilerle authenticate olun:
+
+User: `alice`
+
+Password: `secret2`
+
+Ve `/users/me` path’inde `GET` operasyonunu kullanmayı deneyin.
+
+Şöyle bir "Inactive user" hatası alırsınız:
+
+```JSON
+{
+ "detail": "Inactive user"
+}
+```
+
+## Özet { #recap }
+
+Artık API’niz için `username` ve `password` tabanlı, eksiksiz bir güvenlik sistemi implement etmek için gerekli araçlara sahipsiniz.
+
+Bu araçlarla güvenlik sistemini herhangi bir veritabanıyla ve herhangi bir user veya veri modeliyle uyumlu hale getirebilirsiniz.
+
+Eksik kalan tek detay, bunun henüz gerçekten "güvenli" olmamasıdır.
+
+Bir sonraki bölümde güvenli bir password hashing kütüphanesini ve JWT token’larını nasıl kullanacağınızı göreceksiniz.
diff --git a/docs/tr/docs/tutorial/server-sent-events.md b/docs/tr/docs/tutorial/server-sent-events.md
new file mode 100644
index 0000000000000..3855410125486
--- /dev/null
+++ b/docs/tr/docs/tutorial/server-sent-events.md
@@ -0,0 +1,120 @@
+# Server-Sent Events (SSE) { #server-sent-events-sse }
+
+İstemciye veri akışını **Server-Sent Events** (SSE) ile sağlayabilirsiniz.
+
+Bu, [JSON Lines Akışı](stream-json-lines.md) ile benzerdir ancak tarayıcılar tarafından yerel olarak desteklenen [`EventSource` API'si](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) ile `text/event-stream` formatını kullanır.
+
+/// info | Bilgi
+
+FastAPI 0.135.0'da eklendi.
+
+///
+
+## Server-Sent Events Nedir? { #what-are-server-sent-events }
+
+SSE, HTTP üzerinden sunucudan istemciye veri akışı için bir standarttır.
+
+Her olay, aralarında boş satırlar bulunan ve `data`, `event`, `id` ve `retry` gibi "alanlar" içeren küçük bir metin bloğudur.
+
+Şuna benzer:
+
+```
+data: {"name": "Portal Gun", "price": 999.99}
+
+data: {"name": "Plumbus", "price": 32.99}
+
+```
+
+SSE; yapay zekâ sohbet akışı, canlı bildirimler, log ve gözlemlenebilirlik (observability) gibi senaryolarda ve sunucunun istemciye güncellemeleri ittiği diğer durumlarda yaygın olarak kullanılır.
+
+/// tip | İpucu
+
+İkili (binary) veri akışı yapmak istiyorsanız, gelişmiş kılavuza bakın: [Veri Akışı](../advanced/stream-data.md).
+
+///
+
+## FastAPI ile SSE Akışı { #stream-sse-with-fastapi }
+
+FastAPI ile SSE akışı yapmak için, *path operation function* içinde `yield` kullanın ve `response_class=EventSourceResponse` olarak ayarlayın.
+
+`EventSourceResponse`'u `fastapi.sse` içinden içe aktarın:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[4,22] *}
+
+Yield edilen her öğe JSON olarak kodlanır ve bir SSE olayının `data:` alanında gönderilir.
+
+Dönüş tipini `AsyncIterable[Item]` olarak bildirirseniz, FastAPI bunu Pydantic ile veriyi **doğrulamak**, **belgelemek** ve **serileştirmek** için kullanır.
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[10:12,23] *}
+
+/// tip | İpucu
+
+Pydantic serileştirmeyi **Rust** tarafında yapacağından, dönüş tipi bildirmediğiniz duruma göre çok daha yüksek **performans** elde edersiniz.
+
+///
+
+### Async Olmayan Path Operation Fonksiyonları { #non-async-path-operation-functions }
+
+Normal `def` fonksiyonlarını (yani `async` olmadan) da kullanabilir ve aynı şekilde `yield` kullanabilirsiniz.
+
+FastAPI, event loop'u bloke etmeyecek şekilde doğru biçimde çalışmasını sağlar.
+
+Bu örnekte fonksiyon async olmadığı için doğru dönüş tipi `Iterable[Item]` olur:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[28:31] hl[29] *}
+
+### Dönüş Tipi Olmadan { #no-return-type }
+
+Dönüş tipini belirtmeyebilirsiniz. FastAPI, veriyi dönüştürmek ve göndermek için [`jsonable_encoder`](./encoder.md) kullanır.
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[34:37] hl[35] *}
+
+## `ServerSentEvent` { #serversentevent }
+
+`event`, `id`, `retry` veya `comment` gibi SSE alanlarını ayarlamanız gerekirse, düz veri yerine `ServerSentEvent` nesneleri yield edebilirsiniz.
+
+`ServerSentEvent`'i `fastapi.sse` içinden içe aktarın:
+
+{* ../../docs_src/server_sent_events/tutorial002_py310.py hl[4,26] *}
+
+`data` alanı her zaman JSON olarak kodlanır. Pydantic modelleri dâhil, JSON olarak serileştirilebilen herhangi bir değeri geçebilirsiniz.
+
+## Ham Veri { #raw-data }
+
+Veriyi JSON kodlaması olmadan göndermeniz gerekiyorsa, `data` yerine `raw_data` kullanın.
+
+Bu, önceden biçimlendirilmiş metin, log satırları veya `[DONE]` gibi özel "işaretçi" değerleri göndermek için kullanışlıdır.
+
+{* ../../docs_src/server_sent_events/tutorial003_py310.py hl[17] *}
+
+/// note | Not
+
+`data` ve `raw_data` birbirini dışlar. Her `ServerSentEvent` için bunlardan yalnızca birini ayarlayabilirsiniz.
+
+///
+
+## `Last-Event-ID` ile Devam Etme { #resuming-with-last-event-id }
+
+Bir tarayıcı bağlantı koptuktan sonra yeniden bağlandığında, son aldığı `id`'yi `Last-Event-ID` header'ında gönderir.
+
+Bunu bir header parametresi olarak okuyup, istemcinin kaldığı yerden akışı sürdürmek için kullanabilirsiniz:
+
+{* ../../docs_src/server_sent_events/tutorial004_py310.py hl[25,27,31] *}
+
+## POST ile SSE { #sse-with-post }
+
+SSE, sadece `GET` değil, **tüm HTTP metodlarıyla** çalışır.
+
+Bu, SSE'yi `POST` üzerinden akıtan [MCP](https://modelcontextprotocol.io) gibi protokoller için kullanışlıdır:
+
+{* ../../docs_src/server_sent_events/tutorial005_py310.py hl[14] *}
+
+## Teknik Detaylar { #technical-details }
+
+FastAPI, bazı SSE en iyi uygulamalarını kutudan çıktığı gibi uygular.
+
+- [HTML spesifikasyonu: Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes) önerisine uygun olarak, bazı proxy'lerin bağlantıyı kapatmasını önlemek için, 15 saniye boyunca hiç mesaj gelmezse **"keep alive" `ping` yorumu** gönderir.
+- Akışın **cache'lenmesini önlemek** için `Cache-Control: no-cache` header'ını ayarlar.
+- Nginx gibi bazı proxy'lerde **buffering'i önlemek** için özel `X-Accel-Buffering: no` header'ını ayarlar.
+
+Bunun için ekstra bir şey yapmanız gerekmez, doğrudan çalışır. 🤓
diff --git a/docs/tr/docs/tutorial/sql-databases.md b/docs/tr/docs/tutorial/sql-databases.md
new file mode 100644
index 0000000000000..ea4b9ebc45613
--- /dev/null
+++ b/docs/tr/docs/tutorial/sql-databases.md
@@ -0,0 +1,357 @@
+# SQL (İlişkisel) Veritabanları { #sql-relational-databases }
+
+**FastAPI**, SQL (ilişkisel) bir veritabanı kullanmanızı zorunlu kılmaz. Ancak isterseniz **istediğiniz herhangi bir veritabanını** kullanabilirsiniz.
+
+Burada [SQLModel](https://sqlmodel.tiangolo.com/) kullanarak bir örnek göreceğiz.
+
+**SQLModel**, [SQLAlchemy](https://www.sqlalchemy.org/) ve Pydantic’in üzerine inşa edilmiştir. **FastAPI**’nin yazarı tarafından, **SQL veritabanları** kullanması gereken FastAPI uygulamalarıyla mükemmel uyum sağlaması için geliştirilmiştir.
+
+/// tip | İpucu
+
+İstediğiniz başka bir SQL veya NoSQL veritabanı kütüphanesini kullanabilirsiniz (bazı durumlarda "ORMs" olarak adlandırılır). FastAPI sizi hiçbir şeye zorlamaz. 😎
+
+///
+
+SQLModel, SQLAlchemy tabanlı olduğu için SQLAlchemy’nin **desteklediği herhangi bir veritabanını** kolayca kullanabilirsiniz (bu da SQLModel tarafından da desteklendikleri anlamına gelir), örneğin:
+
+* PostgreSQL
+* MySQL
+* SQLite
+* Oracle
+* Microsoft SQL Server, vb.
+
+Bu örnekte **SQLite** kullanacağız; çünkü tek bir dosya kullanır ve Python’da yerleşik desteği vardır. Yani bu örneği kopyalayıp olduğu gibi çalıştırabilirsiniz.
+
+Daha sonra, production uygulamanız için **PostgreSQL** gibi bir veritabanı sunucusu kullanmak isteyebilirsiniz.
+
+/// tip | İpucu
+
+Frontend ve daha fazla araçla birlikte **FastAPI** + **PostgreSQL** içeren resmi bir proje oluşturucu (project generator) var: [https://github.com/fastapi/full-stack-fastapi-template](https://github.com/fastapi/full-stack-fastapi-template)
+
+///
+
+Bu çok basit ve kısa bir eğitimdir. Veritabanları genelinde, SQL hakkında veya daha ileri özellikler hakkında öğrenmek isterseniz [SQLModel dokümantasyonuna](https://sqlmodel.tiangolo.com/) gidin.
+
+## `SQLModel` Kurulumu { #install-sqlmodel }
+
+Önce [virtual environment](../virtual-environments.md) oluşturduğunuzdan emin olun, aktive edin ve ardından `sqlmodel`’i yükleyin:
+
+
+
+lt
+* XWT
+* PSGI
+
+### Скорочення містить повну фразу та пояснення { #the-abbr-gives-a-full-phrase-and-an-explanation }
+
+* MDN
+* I/O.
+
+////
+
+//// tab | Інформація
+
+Атрибути "title" елементів "abbr" перекладаються за певними інструкціями.
+
+Переклади можуть додавати власні елементи "abbr", які LLM не повинен прибирати. Наприклад, щоб пояснити англійські слова.
+
+Див. розділ `### HTML abbr elements` в загальній підсказці в `scripts/translate.py`.
+
+////
+
+## Елементи HTML «dfn» { #html-dfn-elements }
+
+* кластер
+* Глибоке навчання
+
+## Заголовки { #headings }
+
+//// tab | Тест
+
+### Розробка вебзастосунку - навчальний посібник { #develop-a-webapp-a-tutorial }
+
+Привіт.
+
+### Підказки типів та - анотації { #type-hints-and-annotations }
+
+Ще раз привіт.
+
+### Супер- та підкласи { #super-and-subclasses }
+
+Ще раз привіт.
+
+////
+
+//// tab | Інформація
+
+Єдине жорстке правило для заголовків - LLM має залишати хеш-частину в фігурних дужках незмінною, щоб посилання не ламалися.
+
+Див. розділ `### Headings` у загальній підсказці в `scripts/translate.py`.
+
+Для деяких мовно-специфічних інструкцій див., наприклад, розділ `### Headings` у `docs/de/llm-prompt.md`.
+
+////
+
+## Терміни, що використовуються в документації { #terms-used-in-the-docs }
+
+//// tab | Тест
+
+* ви
+* ваш
+
+* напр.
+* тощо
+
+* `foo` як `int`
+* `bar` як `str`
+* `baz` як `list`
+
+* навчальний посібник - Керівництво користувача
+* просунутий посібник користувача
+* документація SQLModel
+* документація API
+* автоматична документація
+
+* Наука про дані
+* глибоке навчання
+* машинне навчання
+* впровадження залежностей
+* HTTP базова автентифікація
+* HTTP дайджест
+* формат ISO
+* стандарт Схеми JSON
+* Схема JSON
+* визначення схеми
+* потік паролю
+* мобільний
+
+* застаріле
+* спроєктовано
+* недійсний
+* на льоту
+* стандарт
+* типове
+* чутливий до регістру
+* нечутливий до регістру
+
+* обслуговувати застосунок
+* обслуговувати сторінку
+
+* застосунок
+* застосунок
+
+* запит
+* відповідь
+* відповідь з помилкою
+
+* операція шляху
+* декоратор операції шляху
+* функція операції шляху
+
+* тіло
+* тіло запиту
+* тіло відповіді
+* тіло JSON
+* тіло форми
+* тіло файлу
+* тіло функції
+
+* параметр
+* параметр тіла
+* параметр шляху
+* параметр запиту
+* параметр кукі
+* параметр заголовка
+* параметр форми
+* параметр функції
+
+* подія
+* подія запуску
+* запуск сервера
+* подія вимкнення
+* подія тривалості життя
+
+* обробник
+* обробник події
+* обробник винятків
+* обробляти
+
+* модель
+* модель Pydantic
+* модель даних
+* модель бази даних
+* модель форми
+* об'єкт моделі
+
+* клас
+* базовий клас
+* батьківський клас
+* підклас
+* дочірній клас
+* споріднений клас
+* метод класу
+
+* заголовок
+* заголовки
+* заголовок авторизації
+* заголовок `Authorization`
+* направлений заголовок
+
+* система впровадження залежностей
+* залежність
+* залежний
+* залежний
+
+* I/O-обмежений
+* CPU-обмежений
+* рівночасність
+* паралелізм
+* багатопроцесорність
+
+* змінна оточення
+* змінна оточення
+* `PATH`
+* змінна `PATH`
+
+* автентифікація
+* постачальник автентифікації
+* авторизація
+* форма авторизації
+* постачальник авторизації
+* користувач автентифікується
+* система автентифікує користувача
+
+* CLI
+* інтерфейс командного рядка
+
+* сервер
+* клієнт
+
+* хмарний постачальник
+* хмарний сервіс
+
+* розробка
+* етапи розробки
+
+* словник
+* словник
+* перелік
+* перелік
+* елемент переліку
+
+* кодувальник
+* декодувальник
+* кодувати
+* декодувати
+
+* виняток
+* породжувати
+
+* вираз
+* оператор
+
+* фронтенд
+* бекенд
+
+* обговорення GitHub
+* проблема GitHub
+
+* продуктивність
+* оптимізація продуктивності
+
+* тип, що повертається
+* повернене значення
+
+* безпека
+* схема безпеки
+
+* завдання
+* фонове завдання
+* функція завдання
+
+* шаблон
+* рушій шаблонів
+
+* анотація типу
+* підказка типу
+
+* серверний працівник
+* працівник Uvicorn
+* працівник Gunicorn
+* процес працівника
+* клас працівника
+* робоче навантаження
+
+* розгортання
+* розгортати
+
+* SDK
+* набір для розробки програмного забезпечення
+
+* `APIRouter`
+* `requirements.txt`
+* токен носія
+* несумісна зміна
+* помилка
+* кнопка
+* викликаємий
+* код
+* фіксація
+* менеджер контексту
+* співпрограма
+* сеанс бази даних
+* диск
+* домен
+* рушій
+* фальшивий X
+* метод HTTP GET
+* предмет
+* бібліотека
+* тривалість життя
+* блокування
+* проміжне програмне забезпечення
+* мобільний застосунок
+* модуль
+* монтування
+* мережа
+* джерело
+* переписування
+* корисне навантаження
+* процесор
+* властивість
+* представник
+* запит на витяг
+* запит
+* пам'ять з довільним доступом
+* віддалена машина
+* код статусу
+* строка
+* мітка
+* веб-фреймворк
+* дика карта
+* повертати
+* перевіряти
+
+////
+
+//// tab | Інформація
+
+Це неповний і не нормативний список (переважно) технічних термінів, що зустрічаються в документації. Він може бути корисним автору підсказки, щоб зрозуміти, для яких термінів LLM потрібна допомога. Наприклад, коли він постійно повертає хороший переклад до менш вдалого. Або коли йому складно відмінювати термін вашою мовою.
+
+Див., наприклад, розділ `### List of English terms and their preferred German translations` у `docs/de/llm-prompt.md`.
+
+////
diff --git a/docs/uk/docs/about/index.md b/docs/uk/docs/about/index.md
new file mode 100644
index 0000000000000..198fd828e5151
--- /dev/null
+++ b/docs/uk/docs/about/index.md
@@ -0,0 +1,3 @@
+# Про { #about }
+
+Про FastAPI, його проєктування, натхнення та інше. 🤓
diff --git a/docs/uk/docs/advanced/additional-responses.md b/docs/uk/docs/advanced/additional-responses.md
new file mode 100644
index 0000000000000..2d2005837fbca
--- /dev/null
+++ b/docs/uk/docs/advanced/additional-responses.md
@@ -0,0 +1,247 @@
+# Додаткові відповіді в OpenAPI { #additional-responses-in-openapi }
+
+/// warning | Попередження
+
+Це доволі просунута тема.
+
+Якщо ви лише починаєте з **FastAPI**, ймовірно, вам це не потрібно.
+
+///
+
+Ви можете оголосити додаткові відповіді з додатковими кодами статусу, типами медіа, описами тощо.
+
+Ці додаткові відповіді буде включено до схеми OpenAPI, тож вони з'являться і в документації API.
+
+Але для таких додаткових відповідей потрібно повертати `Response` на кшталт `JSONResponse` безпосередньо, із потрібним кодом статусу та вмістом.
+
+## Додаткова відповідь з `model` { #additional-response-with-model }
+
+Ви можете передати вашим декораторам операцій шляху параметр `responses`.
+
+Він приймає `dict`: ключі - це коди статусу для кожної відповіді (наприклад, `200`), а значення - інші `dict` з інформацією для кожної з них.
+
+Кожен із цих словників відповіді може мати ключ `model`, що містить Pydantic-модель, подібно до `response_model`.
+
+**FastAPI** візьме цю модель, згенерує її Схему JSON і додасть у відповідне місце в OpenAPI.
+
+Наприклад, щоб оголосити іншу відповідь з кодом статусу `404` і Pydantic-моделлю `Message`, ви можете написати:
+
+{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}
+
+/// note | Примітка
+
+Майте на увазі, що потрібно повертати `JSONResponse` безпосередньо.
+
+///
+
+/// info | Інформація
+
+Ключ `model` не є частиною OpenAPI.
+
+**FastAPI** візьме звідти Pydantic-модель, згенерує Схему JSON і помістить у відповідне місце.
+
+Відповідне місце це:
+
+- У ключі `content`, значенням якого є інший JSON-об'єкт (`dict`), що містить:
+ - Ключ із типом медіа, напр. `application/json`, значенням якого є інший JSON-об'єкт, що містить:
+ - Ключ `schema`, значенням якого є Схема JSON з моделі - ось це і є правильне місце.
+ - **FastAPI** додає тут посилання на глобальні Схеми JSON в іншому місці вашого OpenAPI замість прямого включення. Так інші застосунки та клієнти можуть напряму використовувати ці Схеми JSON, надавати кращі інструменти генерації коду тощо.
+
+///
+
+Згенеровані відповіді в OpenAPI для цієї операції шляху будуть такими:
+
+```JSON hl_lines="3-12"
+{
+ "responses": {
+ "404": {
+ "description": "Additional Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Message"
+ }
+ }
+ }
+ },
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+Схеми посилаються на інше місце всередині схеми OpenAPI:
+
+```JSON hl_lines="4-16"
+{
+ "components": {
+ "schemas": {
+ "Message": {
+ "title": "Message",
+ "required": [
+ "message"
+ ],
+ "type": "object",
+ "properties": {
+ "message": {
+ "title": "Message",
+ "type": "string"
+ }
+ }
+ },
+ "Item": {
+ "title": "Item",
+ "required": [
+ "id",
+ "value"
+ ],
+ "type": "object",
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
+ },
+ "value": {
+ "title": "Value",
+ "type": "string"
+ }
+ }
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": [
+ "loc",
+ "msg",
+ "type"
+ ],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string"
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string"
+ }
+ }
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+## Додаткові типи медіа для основної відповіді { #additional-media-types-for-the-main-response }
+
+Можна використати цей самий параметр `responses`, щоб додати різні типи медіа для тієї ж основної відповіді.
+
+Наприклад, можна додати додатковий тип медіа `image/png`, оголосивши, що ваша операція шляху може повертати JSON-об'єкт (з типом медіа `application/json`) або PNG-зображення:
+
+{* ../../docs_src/additional_responses/tutorial002_py310.py hl[17:22,26] *}
+
+/// note | Примітка
+
+Зверніть увагу, що потрібно повертати зображення безпосередньо за допомогою `FileResponse`.
+
+///
+
+/// info | Інформація
+
+Поки ви явно не вкажете інший тип медіа в параметрі `responses`, FastAPI вважатиме, що відповідь має той самий тип медіа, що й основний клас відповіді (типово `application/json`).
+
+Але якщо ви вказали власний клас відповіді з `None` як типом медіа, FastAPI використає `application/json` для будь-якої додаткової відповіді, що має пов'язану модель.
+
+///
+
+## Комбінування інформації { #combining-information }
+
+Ви також можете поєднувати інформацію про відповіді з кількох місць, зокрема з параметрів `response_model`, `status_code` і `responses`.
+
+Ви можете оголосити `response_model`, використовуючи типовий код статусу `200` (або власний за потреби), а потім оголосити додаткову інформацію для цієї ж відповіді в `responses`, безпосередньо в схемі OpenAPI.
+
+**FastAPI** збереже додаткову інформацію з `responses` і поєднає її зі Схемою JSON з вашої моделі.
+
+Наприклад, ви можете оголосити відповідь з кодом статусу `404`, яка використовує Pydantic-модель і має власний `description`.
+
+І відповідь з кодом статусу `200`, яка використовує ваш `response_model`, але містить власний `example`:
+
+{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}
+
+Усе це буде поєднано та включено до вашого OpenAPI і показано в документації API:
+
+
+
+## Комбінуйте попередньо визначені та власні відповіді { #combine-predefined-responses-and-custom-ones }
+
+Можливо, ви захочете мати кілька попередньо визначених відповідей, що застосовуються до багатьох операцій шляху, але поєднувати їх із власними відповідями, потрібними для кожної операції шляху.
+
+Для таких випадків можна скористатися прийомом Python «розпакування» `dict` за допомогою `**dict_to_unpack`:
+
+```Python
+old_dict = {
+ "old key": "old value",
+ "second old key": "second old value",
+}
+new_dict = {**old_dict, "new key": "new value"}
+```
+
+Тут `new_dict` міститиме всі пари ключ-значення з `old_dict` плюс нову пару ключ-значення:
+
+```Python
+{
+ "old key": "old value",
+ "second old key": "second old value",
+ "new key": "new value",
+}
+```
+
+Цей прийом можна використати, щоб перевикористовувати деякі попередньо визначені відповіді у ваших операціях шляху та поєднувати їх із додатковими власними.
+
+Наприклад:
+
+{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}
+
+## Докладніше про відповіді OpenAPI { #more-information-about-openapi-responses }
+
+Щоб побачити, що саме можна включати у відповіді, ознайомтеся з цими розділами специфікації OpenAPI:
+
+- [Об'єкт відповідей OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responses-object), він включає `Response Object`.
+- [Об'єкт відповіді OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#response-object), ви можете включити будь-що з цього безпосередньо в кожну відповідь у параметрі `responses`. Зокрема `description`, `headers`, `content` (усередині нього ви оголошуєте різні типи медіа та Схеми JSON) і `links`.
diff --git a/docs/uk/docs/advanced/additional-status-codes.md b/docs/uk/docs/advanced/additional-status-codes.md
new file mode 100644
index 0000000000000..26e2c14545f53
--- /dev/null
+++ b/docs/uk/docs/advanced/additional-status-codes.md
@@ -0,0 +1,41 @@
+# Додаткові коди статусу { #additional-status-codes }
+
+За замовчуванням **FastAPI** повертатиме відповіді за допомогою `JSONResponse`, поміщаючи вміст, який ви повертаєте з вашої *операції шляху*, у цей `JSONResponse`.
+
+Він використовуватиме код статусу за замовчуванням або той, який ви встановите у своїй *операції шляху*.
+
+## Додаткові коди статусу { #additional-status-codes_1 }
+
+Якщо ви хочете повертати додаткові коди статусу, окрім основного, зробіть це, повертаючи `Response` безпосередньо, наприклад `JSONResponse`, і встановіть додатковий код статусу напряму.
+
+Наприклад, припустімо, ви хочете мати *операцію шляху*, яка дозволяє оновлювати предмети та повертає код статусу HTTP 200 «OK» у разі успіху.
+
+Але ви також хочете приймати нові предмети. І коли таких предметів раніше не існувало, операція створює їх і повертає код статусу HTTP 201 «Created».
+
+Щоб це реалізувати, імпортуйте `JSONResponse` і поверніть ваш вміст безпосередньо там, встановивши потрібний `status_code`:
+
+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
+
+/// warning | Попередження
+
+Коли ви повертаєте `Response` безпосередньо, як у прикладі вище, він і буде повернений безпосередньо.
+
+Він не буде серіалізований за допомогою моделі тощо.
+
+Переконайтеся, що він містить саме ті дані, які вам потрібні, і що значення є коректним JSON (якщо ви використовуєте `JSONResponse`).
+
+///
+
+/// note | Технічні деталі
+
+Ви також можете використати `from starlette.responses import JSONResponse`.
+
+**FastAPI** надає ті самі `starlette.responses` як `fastapi.responses` просто для вашої зручності як розробника. Але більшість доступних відповідей надходить безпосередньо зі Starlette. Те саме і зі `status`.
+
+///
+
+## OpenAPI і документація API { #openapi-and-api-docs }
+
+Якщо ви повертаєте додаткові коди статусу та відповіді безпосередньо, вони не будуть включені до схеми OpenAPI (документації API), адже FastAPI не має способу заздалегідь знати, що саме ви повернете.
+
+Але ви можете задокументувати це у своєму коді, використовуючи: [Додаткові відповіді](additional-responses.md).
diff --git a/docs/uk/docs/advanced/advanced-dependencies.md b/docs/uk/docs/advanced/advanced-dependencies.md
new file mode 100644
index 0000000000000..48a10ba4d4475
--- /dev/null
+++ b/docs/uk/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,163 @@
+# Просунуті залежності { #advanced-dependencies }
+
+## Параметризовані залежності { #parameterized-dependencies }
+
+Усі залежності, які ми бачили, - це фіксована функція або клас.
+
+Але можуть бути випадки, коли ви хочете мати змогу задавати параметри залежності, не оголошуючи багато різних функцій або класів.
+
+Уявімо, що ми хочемо мати залежність, яка перевіряє, чи параметр запиту `q` містить певний фіксований вміст.
+
+Але ми хочемо мати змогу параметризувати цей фіксований вміст.
+
+## Екземпляр «callable» { #a-callable-instance }
+
+У Python є спосіб зробити екземпляр класу «callable».
+
+Не сам клас (який уже є «callable»), а екземпляр цього класу.
+
+Щоб це зробити, оголошуємо метод `__call__`:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}
+
+У цьому випадку саме `__call__` **FastAPI** використає для перевірки додаткових параметрів і підзалежностей, і саме його буде викликано, щоб передати значення параметру у вашу *функцію операції шляху* пізніше.
+
+## Параметризувати екземпляр { #parameterize-the-instance }
+
+Тепер ми можемо використати `__init__`, щоб оголосити параметри екземпляра, які можна застосувати для «параметризації» залежності:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}
+
+У цьому випадку **FastAPI** ніколи не торкається `__init__` і не покладається на нього - ми використовуватимемо його безпосередньо у своєму коді.
+
+## Створити екземпляр { #create-an-instance }
+
+Ми можемо створити екземпляр цього класу так:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}
+
+Таким чином ми «параметризуємо» нашу залежність, яка тепер містить «bar» як атрибут `checker.fixed_content`.
+
+## Використовувати екземпляр як залежність { #use-the-instance-as-a-dependency }
+
+Далі ми можемо використати цей `checker` у `Depends(checker)` замість `Depends(FixedContentQueryChecker)`, адже залежністю є екземпляр `checker`, а не сам клас.
+
+Коли залежність розв'язується, **FastAPI** викличе цей `checker` так:
+
+```Python
+checker(q="somequery")
+```
+
+...і передасть усе, що він поверне, як значення залежності у нашій *функції операції шляху* як параметр `fixed_content_included`:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}
+
+/// tip | Порада
+
+Усе це може здаватися надуманим. І поки що може бути не дуже зрозуміло, навіщо це корисно.
+
+Ці приклади навмисно прості, але показують, як усе працює.
+
+У розділах про безпеку є утилітарні функції, реалізовані таким самим способом.
+
+Якщо ви все це зрозуміли, ви вже знаєте, як під капотом працюють ті утиліти для безпеки.
+
+///
+
+## Залежності з `yield`, `HTTPException`, `except` та фоновими задачами { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+/// warning | Попередження
+
+Найімовірніше, вам не знадобляться ці технічні деталі.
+
+Вони корисні головно, якщо у вас був застосунок FastAPI старіший за 0.121.0 і ви стикаєтеся з проблемами залежностей із `yield`.
+
+///
+
+Залежності з `yield` еволюціонували з часом, щоб охопити різні сценарії використання та виправити деякі проблеми, ось підсумок змін.
+
+### Залежності з `yield` і `scope` { #dependencies-with-yield-and-scope }
+
+У версії 0.121.0 **FastAPI** додано підтримку `Depends(scope="function")` для залежностей з `yield`.
+
+З `Depends(scope="function")` завершальний код після `yield` виконується одразу після завершення *функції операції шляху*, до того як відповідь буде надіслана клієнту.
+
+А при використанні `Depends(scope="request")` (типове значення) завершальний код після `yield` виконується після відправлення відповіді.
+
+Докладніше читайте в документації: [Залежності з `yield` - Ранній вихід і `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope).
+
+### Залежності з `yield` і `StreamingResponse`, технічні деталі { #dependencies-with-yield-and-streamingresponse-technical-details }
+
+До **FastAPI** 0.118.0, якщо ви використовували залежність із `yield`, завершальний код виконувався після повернення з *функції операції шляху*, але безпосередньо перед відправленням відповіді.
+
+Метою було уникнути утримання ресурсів довше, ніж потрібно, очікуючи, поки відповідь пройде мережею.
+
+Це також означало, що якщо ви повертали `StreamingResponse`, завершальний код залежності з `yield` уже було б виконано.
+
+Наприклад, якщо у залежності з `yield` була сесія бази даних, `StreamingResponse` не зміг би використовувати цю сесію під час потокової передачі даних, тому що сесію вже закрито в завершальному коді після `yield`.
+
+Цю поведінку змінено у 0.118.0: завершальний код після `yield` знову виконується після відправлення відповіді.
+
+/// info | Інформація
+
+Як побачите нижче, це дуже схоже на поведінку до версії 0.106.0, але з кількома покращеннями та виправленнями помилок у крайових випадках.
+
+///
+
+#### Випадки використання з раннім завершальним кодом { #use-cases-with-early-exit-code }
+
+Є кілька сценаріїв із певними умовами, які можуть виграти від старої поведінки - виконувати завершальний код залежностей з `yield` до надсилання відповіді.
+
+Наприклад, уявіть, що у вас є код, який використовує сесію бази даних у залежності з `yield` лише для перевірки користувача, але сесія більше не використовується у *функції операції шляху*, тільки в залежності, і відправлення відповіді триває довго - як у `StreamingResponse`, що повільно надсилає дані, але з якоїсь причини не використовує базу даних.
+
+У такому разі сесія БД утримувалася б до завершення відправлення відповіді, але якщо ви її не використовуєте, утримувати її немає потреби.
+
+Ось як це може виглядати:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
+
+Завершальний код - автоматичне закриття `Session` у:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
+
+...виконається після того, як відповідь завершить надсилати повільні дані:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
+
+Але оскільки `generate_stream()` не використовує сесію бази даних, немає реальної потреби тримати сесію відкритою під час надсилання відповіді.
+
+Якщо у вас саме такий випадок із SQLModel (або SQLAlchemy), ви можете явно закрити сесію, коли вона більше не потрібна:
+
+{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}
+
+Так сесія звільнить з'єднання з базою даних, і його зможуть використовувати інші запити.
+
+Якщо у вас інший сценарій, де потрібно раннє завершення залежності з `yield`, створіть, будь ласка, [питання в обговореннях GitHub](https://github.com/fastapi/fastapi/discussions/new?category=questions) із вашим конкретним випадком і поясненням, чому вам корисне раннє закриття для залежностей з `yield`.
+
+Якщо будуть переконливі приклади для раннього закриття в залежностях з `yield`, я розгляну додавання нового способу увімкнути раннє закриття.
+
+### Залежності з `yield` і `except`, технічні деталі { #dependencies-with-yield-and-except-technical-details }
+
+До **FastAPI** 0.110.0, якщо ви використовували залежність із `yield`, перехоплювали виняток через `except` у цій залежності і не піднімали його знову, виняток автоматично піднімався/пересилався до будь-яких обробників винятків або внутрішнього обробника помилок сервера.
+
+Це змінено у версії 0.110.0, щоб усунути неконтрольоване споживання пам'яті від пересланих винятків без обробника (внутрішні помилки сервера) та зробити поведінку узгодженою зі звичайним Python-кодом.
+
+### Фонові задачі та залежності з `yield`, технічні деталі { #background-tasks-and-dependencies-with-yield-technical-details }
+
+До **FastAPI** 0.106.0 піднімати винятки після `yield` було неможливо: завершальний код у залежностях з `yield` виконувався після надсилання відповіді, тож [обробники винятків](../tutorial/handling-errors.md#install-custom-exception-handlers) уже відпрацювали б.
+
+Так було спроєктовано головно для того, щоб дозволити використовувати ті самі об'єкти, «віддані» залежностями через `yield`, усередині фонових задач, оскільки завершальний код виконувався після завершення фонових задач.
+
+У **FastAPI** 0.106.0 це змінено, щоб не утримувати ресурси під час очікування, поки відповідь піде мережею.
+
+/// tip | Порада
+
+Крім того, фонова задача зазвичай є незалежним набором логіки, який слід обробляти окремо, з власними ресурсами (наприклад, власним з'єднанням з базою даних).
+
+Тож так у вас, ймовірно, буде чистіший код.
+
+///
+
+Якщо ви раніше покладалися на цю поведінку, тепер слід створювати ресурси для фонових задач усередині самої фонової задачі та використовувати всередині лише дані, що не залежать від ресурсів залежностей із `yield`.
+
+Наприклад, замість використання тієї самої сесії бази даних ви створюватимете нову сесію в самій фоновій задачі та отримуватимете об'єкти з бази даних, використовуючи Цю нову сесію. І далі, замість передавання об'єкта з бази даних як параметра у функцію фонової задачі, ви передасте ідентифікатор цього об'єкта, а потім отримаєте об'єкт знову всередині функції фонової задачі.
diff --git a/docs/uk/docs/advanced/advanced-python-types.md b/docs/uk/docs/advanced/advanced-python-types.md
new file mode 100644
index 0000000000000..9eedc48568a7b
--- /dev/null
+++ b/docs/uk/docs/advanced/advanced-python-types.md
@@ -0,0 +1,61 @@
+# Просунуті типи Python { #advanced-python-types }
+
+Ось кілька додаткових ідей, які можуть бути корисні під час роботи з типами в Python.
+
+## Використання `Union` або `Optional` { #using-union-or-optional }
+
+Якщо ваш код з якоїсь причини не може використовувати `|`, наприклад, якщо це не анотація типів, а щось на кшталт `response_model=`, замість вертикальної риски (`|`) ви можете використати `Union` з `typing`.
+
+Наприклад, ви можете оголосити, що щось може бути `str` або `None`:
+
+```python
+from typing import Union
+
+
+def say_hi(name: Union[str, None]):
+ print(f"Hi {name}!")
+```
+
+У `typing` також є скорочення, щоб оголосити, що щось може бути `None`, - `Optional`.
+
+Ось порада з моєї дуже «суб'єктивної» точки зору:
+
+- 🚨 Уникайте використання `Optional[SomeType]`
+- Натомість ✨ **використовуйте `Union[SomeType, None]`** ✨.
+
+Обидва варіанти еквівалентні і під капотом однакові, але я рекомендую `Union` замість `Optional`, тому що слово «**optional**» ніби натякає, що значення є необов'язковим, а насправді означає «може бути `None`», навіть якщо воно не є необов'язковим і все ще обов'язкове.
+
+Вважаю, `Union[SomeType, None]` більш явно це передає.
+
+Йдеться лише про слова та назви. Але ці слова можуть впливати на те, як ви та ваша команда думаєте про код.
+
+Як приклад, розгляньмо цю функцію:
+
+```python
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+ print(f"Hey {name}!")
+```
+
+Параметр `name` визначено як `Optional[str]`, але він не є необов'язковим, ви не можете викликати функцію без цього параметра:
+
+```Python
+say_hi() # О ні, це викликає помилку! 😱
+```
+
+Параметр `name` все ще обов'язковий (не «необов'язковий»), тому що не має значення за замовчуванням. Водночас `name` приймає `None` як значення:
+
+```Python
+say_hi(name=None) # Це працює, None припустимий 🎉
+```
+
+Гарна новина: у більшості випадків ви зможете просто використовувати `|`, щоб визначати об'єднання типів:
+
+```python
+def say_hi(name: str | None):
+ print(f"Hey {name}!")
+```
+
+Тож зазвичай вам не доведеться перейматися такими назвами, як `Optional` і `Union`. 😎
diff --git a/docs/uk/docs/advanced/async-tests.md b/docs/uk/docs/advanced/async-tests.md
new file mode 100644
index 0000000000000..9f19bed14d814
--- /dev/null
+++ b/docs/uk/docs/advanced/async-tests.md
@@ -0,0 +1,99 @@
+# Асинхронні тести { #async-tests }
+
+Ви вже бачили, як тестувати ваші застосунки **FastAPI** за допомогою наданого `TestClient`. До цього часу ви бачили лише, як писати синхронні тести, без використання функцій `async`.
+
+Можливість використовувати асинхронні функції у тестах може бути корисною, наприклад, коли ви асинхронно звертаєтеся до бази даних. Уявіть, що ви хочете протестувати надсилання запитів до вашого застосунку FastAPI, а потім перевірити, що ваш бекенд успішно записав коректні дані в базу даних, використовуючи асинхронну бібліотеку для бази даних.
+
+Розгляньмо, як це реалізувати.
+
+## pytest.mark.anyio { #pytest-mark-anyio }
+
+Якщо ми хочемо викликати асинхронні функції у тестах, самі тестові функції мають бути асинхронними. AnyIO надає зручний плагін, який дозволяє вказати, що деякі тестові функції слід виконувати асинхронно.
+
+## HTTPX { #httpx }
+
+Навіть якщо ваш застосунок **FastAPI** використовує звичайні функції `def` замість `async def`, під капотом це все одно `async`-застосунок.
+
+`TestClient` робить певну «магію» всередині, щоб викликати асинхронний застосунок FastAPI у ваших звичайних тестових функціях `def`, використовуючи стандартний pytest. Але ця «магія» більше не працює, коли ми використовуємо його всередині асинхронних функцій. Запускаючи тести асинхронно, ми більше не можемо використовувати `TestClient` у наших тестових функціях.
+
+`TestClient` побудований на основі [HTTPX](https://www.python-httpx.org), і на щастя, ми можемо використовувати його безпосередньо для тестування API.
+
+## Приклад { #example }
+
+Для простого прикладу розгляньмо структуру файлів, подібну до описаної в [Більші застосунки](../tutorial/bigger-applications.md) та [Тестування](../tutorial/testing.md):
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+Файл `main.py` міститиме:
+
+{* ../../docs_src/async_tests/app_a_py310/main.py *}
+
+Файл `test_main.py` міститиме тести для `main.py`, тепер це може виглядати так:
+
+{* ../../docs_src/async_tests/app_a_py310/test_main.py *}
+
+## Запуск { #run-it }
+
+Ви можете запустити тести як зазвичай:
+
+
+
+Але якщо ми звернемося до інтерфейсу документації за «офіційним» URL, використовуючи представника з портом `9999`, за адресою `/api/v1/docs`, усе працює коректно! 🎉
+
+Ви можете перевірити це на [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs):
+
+
+
+Саме так, як ми хотіли. ✔️
+
+Це тому, що FastAPI використовує `root_path`, щоб створити типовий `server` в OpenAPI з URL, наданою `root_path`.
+
+## Додаткові сервери { #additional-servers }
+
+/// warning | Попередження
+
+Це більш просунутий випадок використання. Можете пропустити його.
+
+///
+
+За замовчуванням **FastAPI** створить `server` у схемі OpenAPI з URL для `root_path`.
+
+Але ви також можете надати інші альтернативні `servers`, наприклад, якщо хочете, щоб той самий інтерфейс документації взаємодіяв і зі стейджингом, і з продакшном.
+
+Якщо ви передасте власний список `servers`, і є `root_path` (тому що ваш API знаходиться за представником), **FastAPI** вставить «server» з цим `root_path` на початок списку.
+
+Наприклад:
+
+{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}
+
+Буде згенерована схема OpenAPI на кшталт:
+
+```JSON hl_lines="5-7"
+{
+ "openapi": "3.1.0",
+ // Ще дещо тут
+ "servers": [
+ {
+ "url": "/api/v1"
+ },
+ {
+ "url": "https://stag.example.com",
+ "description": "Staging environment"
+ },
+ {
+ "url": "https://prod.example.com",
+ "description": "Production environment"
+ }
+ ],
+ "paths": {
+ // Ще дещо тут
+ }
+}
+```
+
+/// tip | Порада
+
+Зверніть увагу на автоматично згенерований сервер із значенням `url` `/api/v1`, взятим із `root_path`.
+
+///
+
+В інтерфейсі документації за адресою [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs) це виглядатиме так:
+
+
+
+/// tip | Порада
+
+Інтерфейс документації взаємодіятиме з сервером, який ви оберете.
+
+///
+
+/// note | Технічні деталі
+
+Властивість `servers` у специфікації OpenAPI є необовʼязковою.
+
+Якщо ви не вкажете параметр `servers`, і `root_path` дорівнює `/`, властивість `servers` у згенерованій схемі OpenAPI буде повністю пропущено за замовчуванням, що еквівалентно одному серверу зі значенням `url` рівним `/`.
+
+///
+
+### Вимкнути автоматичний сервер із `root_path` { #disable-automatic-server-from-root-path }
+
+Якщо ви не хочете, щоб **FastAPI** додавав автоматичний сервер, використовуючи `root_path`, скористайтеся параметром `root_path_in_servers=False`:
+
+{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}
+
+і тоді він не буде включений у схему OpenAPI.
+
+## Монтування підзастосунку { #mounting-a-sub-application }
+
+Якщо вам потрібно змонтувати підзастосунок (як описано в [Підзастосунки - монтування](sub-applications.md)), одночасно використовуючи представника з `root_path`, ви можете робити це звичайним чином, як і очікуєте.
+
+FastAPI внутрішньо розумно використовуватиме `root_path`, тож усе просто працюватиме. ✨
diff --git a/docs/uk/docs/advanced/custom-response.md b/docs/uk/docs/advanced/custom-response.md
new file mode 100644
index 0000000000000..4ed7616bf79a5
--- /dev/null
+++ b/docs/uk/docs/advanced/custom-response.md
@@ -0,0 +1,273 @@
+# Користувацька відповідь - HTML, стрім, файл, інше { #custom-response-html-stream-file-others }
+
+Типово **FastAPI** повертатиме JSON-відповіді.
+
+Ви можете переписати це, повернувши `Response` безпосередньо, як показано в [Повернути відповідь безпосередньо](response-directly.md).
+
+Але якщо ви повертаєте `Response` безпосередньо (або будь-який його підклас, як-от `JSONResponse`), дані не будуть автоматично конвертовані (навіть якщо ви оголосите `response_model`), і документація не буде автоматично згенерована (наприклад, з включенням конкретного «медіа-типу» в HTTP-заголовку `Content-Type` як частини згенерованого OpenAPI).
+
+Ви також можете оголосити `Response`, який слід використовувати (наприклад, будь-який підклас `Response`), у декораторі операції шляху через параметр `response_class`.
+
+Вміст, який ви повертаєте з вашої функції операції шляху, буде поміщений усередину цього `Response`.
+
+/// note | Примітка
+
+Якщо ви використовуєте клас відповіді без медіа-типу, FastAPI очікуватиме, що у вашої відповіді не буде вмісту, тож формат відповіді не буде задокументовано в згенерованій документації OpenAPI.
+
+///
+
+## JSON-відповіді { #json-responses }
+
+Типово FastAPI повертає JSON-відповіді.
+
+Якщо ви оголосите [Модель відповіді](../tutorial/response-model.md), FastAPI використає її, щоб серіалізувати дані в JSON за допомогою Pydantic.
+
+Якщо ви не оголосите модель відповіді, FastAPI використає `jsonable_encoder`, пояснений у [Сумісний кодувальник JSON](../tutorial/encoder.md), і помістить результат у `JSONResponse`.
+
+Якщо ви оголосите `response_class` з JSON медіа-типом (`application/json`), як у випадку з `JSONResponse`, дані, що повертаються, будуть автоматично перетворені (і відфільтровані) згідно з будь-якою Pydantic `response_model`, яку ви оголосили в декораторі операції шляху. Але дані не будуть серіалізовані в JSON-байти за допомогою Pydantic, натомість вони будуть перетворені з `jsonable_encoder`, а потім передані класу `JSONResponse`, який і серіалізує їх у байти, використовуючи стандартну JSON-бібліотеку в Python.
+
+### Продуктивність JSON { #json-performance }
+
+Коротко: якщо вам потрібна максимальна продуктивність, використовуйте [Модель відповіді](../tutorial/response-model.md) і не оголошуйте `response_class` у декораторі операції шляху.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py ln[15:17] hl[16] *}
+
+## HTML-відповідь { #html-response }
+
+Щоб повернути відповідь із HTML безпосередньо з **FastAPI**, використовуйте `HTMLResponse`.
+
+- Імпортуйте `HTMLResponse`.
+- Передайте `HTMLResponse` як параметр `response_class` вашого декоратора операції шляху.
+
+{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}
+
+/// info | Інформація
+
+Параметр `response_class` також визначатиме «медіа-тип» відповіді.
+
+У цьому випадку HTTP-заголовок `Content-Type` буде встановлено в `text/html`.
+
+І це буде задокументовано відповідно в OpenAPI.
+
+///
+
+### Повернути `Response` { #return-a-response }
+
+Як показано в [Повернути відповідь безпосередньо](response-directly.md), ви також можете переписати відповідь безпосередньо у вашій операції шляху, просто повернувши її.
+
+Той самий приклад вище, що повертає `HTMLResponse`, може виглядати так:
+
+{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}
+
+/// warning | Попередження
+
+`Response`, повернений безпосередньо вашою функцією операції шляху, не буде задокументовано в OpenAPI (наприклад, `Content-Type` не буде задокументовано) і не буде видно в автоматичній інтерактивній документації.
+
+///
+
+/// info | Інформація
+
+Звісно, фактичні заголовок `Content-Type`, код статусу тощо прийдуть з об'єкта `Response`, який ви повернули.
+
+///
+
+### Задокументуйте в OpenAPI і перепишіть `Response` { #document-in-openapi-and-override-response }
+
+Якщо ви хочете переписати відповідь усередині функції, але водночас задокументувати «медіа-тип» в OpenAPI, ви можете використати параметр `response_class` І повернути об'єкт `Response`.
+
+Тоді `response_class` буде використано лише для документування операції шляху в OpenAPI, а ваша `Response` буде використана як є.
+
+#### Повернути `HTMLResponse` безпосередньо { #return-an-htmlresponse-directly }
+
+Наприклад, це може бути щось на кшталт:
+
+{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}
+
+У цьому прикладі функція `generate_html_response()` уже генерує та повертає `Response` замість повернення HTML як `str`.
+
+Повертаючи результат виклику `generate_html_response()`, ви вже повертаєте `Response`, яка перепише типову поведінку **FastAPI**.
+
+Але оскільки ви також передали `HTMLResponse` у `response_class`, **FastAPI** знатиме, як задокументувати це в OpenAPI та інтерактивній документації як HTML з `text/html`:
+
+
+
+## Доступні відповіді { #available-responses }
+
+Ось деякі з доступних відповідей.
+
+Майте на увазі, що ви можете використовувати `Response`, щоб повертати що завгодно інше, або навіть створити власний підклас.
+
+/// note | Технічні деталі
+
+Ви також можете використати `from starlette.responses import HTMLResponse`.
+
+**FastAPI** надає ті ж `starlette.responses` як `fastapi.responses` лише для вашої зручності як розробника. Але більшість доступних відповідей надходять безпосередньо зі Starlette.
+
+///
+
+### `Response` { #response }
+
+Головний клас `Response`, від якого успадковуються всі інші відповіді.
+
+Ви можете повертати його безпосередньо.
+
+Він приймає такі параметри:
+
+- `content` - `str` або `bytes`.
+- `status_code` - `int` - код статусу HTTP.
+- `headers` - `dict` строк.
+- `media_type` - `str`, що задає медіа-тип, напр. `"text/html"`.
+
+FastAPI (насправді Starlette) автоматично додасть заголовок Content-Length. Також буде додано заголовок Content-Type на основі `media_type` з додаванням набору символів для текстових типів.
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+### `HTMLResponse` { #htmlresponse }
+
+Приймає текст або байти та повертає HTML-відповідь, як описано вище.
+
+### `PlainTextResponse` { #plaintextresponse }
+
+Приймає текст або байти та повертає відповідь звичайним текстом.
+
+{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}
+
+### `JSONResponse` { #jsonresponse }
+
+Приймає дані та повертає відповідь, закодовану як `application/json`.
+
+Це типова відповідь, яку використовує **FastAPI**, як зазначено вище.
+
+/// note | Технічні деталі
+
+Але якщо ви оголосите модель відповіді або тип, його буде використано безпосередньо для серіалізації даних у JSON, і відповідь з коректним медіа-типом для JSON буде повернута безпосередньо, без використання класу `JSONResponse`.
+
+Це ідеальний спосіб отримати найкращу продуктивність.
+
+///
+
+### `RedirectResponse` { #redirectresponse }
+
+Повертає HTTP-перенаправлення. Типово використовує код статусу 307 (Temporary Redirect).
+
+Ви можете повернути `RedirectResponse` безпосередньо:
+
+{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}
+
+---
+
+Або ви можете використати його в параметрі `response_class`:
+
+
+{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}
+
+У такому разі ви можете повертати URL безпосередньо з вашої функції операції шляху.
+
+У цьому випадку `status_code` буде типовим для `RedirectResponse`, тобто `307`.
+
+---
+
+Ви також можете використати параметр `status_code` разом із параметром `response_class`:
+
+{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}
+
+### `StreamingResponse` { #streamingresponse }
+
+Приймає async-генератор або звичайний генератор/ітератор (функцію з `yield`) і потоково передає тіло відповіді.
+
+{* ../../docs_src/custom_response/tutorial007_py310.py hl[3,16] *}
+
+/// note | Технічні деталі
+
+Завдання `async` може бути скасовано лише тоді, коли воно досягає `await`. Якщо немає `await`, генератор (функція з `yield`) не може бути коректно скасований і може продовжувати працювати навіть після запиту на скасування.
+
+Оскільки цьому невеликому прикладу не потрібні жодні оператори `await`, ми додаємо `await anyio.sleep(0)`, щоб надати циклу подій шанс обробити скасування.
+
+Це ще важливіше для великих або нескінченних потоків.
+
+///
+
+/// tip | Порада
+
+Замість того щоб повертати `StreamingResponse` безпосередньо, імовірно, краще дотримуватися стилю в [Потокова передача даних](./stream-data.md), це значно зручніше та обробляє скасування «за лаштунками» для вас.
+
+Якщо ви транслюєте JSON Lines, дотримуйтесь навчального посібника [Потоки JSON Lines](../tutorial/stream-json-lines.md).
+
+///
+
+### `FileResponse` { #fileresponse }
+
+Асинхронно транслює файл як відповідь.
+
+Приймає інший набір аргументів для створення екземпляра, ніж інші типи відповідей:
+
+- `path` - шлях до файлу для трансляції.
+- `headers` - будь-які користувацькі заголовки як словник.
+- `media_type` - строка, що задає медіа-тип. Якщо не встановлено, медіа-тип буде виведено з імені файлу або шляху.
+- `filename` - якщо встановлено, буде включено до `Content-Disposition` відповіді.
+
+Відповіді з файлами включатимуть відповідні заголовки `Content-Length`, `Last-Modified` і `ETag`.
+
+{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}
+
+Ви також можете використати параметр `response_class`:
+
+{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}
+
+У цьому випадку ви можете повертати шлях до файлу безпосередньо з вашої функції операції шляху.
+
+## Власний клас відповіді { #custom-response-class }
+
+Ви можете створити власний клас відповіді, успадкувавши його від `Response`, і використовувати його.
+
+Наприклад, скажімо, ви хочете використовувати [`orjson`](https://github.com/ijl/orjson) з деякими налаштуваннями.
+
+Припустімо, ви хочете, щоб повертався відформатований із відступами JSON, тож ви хочете використати опцію orjson `orjson.OPT_INDENT_2`.
+
+Ви можете створити `CustomORJSONResponse`. Головне, що потрібно зробити, це створити метод `Response.render(content)`, який повертає вміст як `bytes`:
+
+{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}
+
+Тепер замість повернення:
+
+```json
+{"message": "Hello World"}
+```
+
+...ця відповідь повертатиме:
+
+```json
+{
+ "message": "Hello World"
+}
+```
+
+Звісно, ви, ймовірно, знайдете значно кращі способи скористатися цим, ніж просто форматування JSON. 😉
+
+### `orjson` або Модель відповіді { #orjson-or-response-model }
+
+Якщо ви шукаєте продуктивність, імовірно, краще використати [Модель відповіді](../tutorial/response-model.md), ніж відповідь `orjson`.
+
+З моделлю відповіді FastAPI використає Pydantic, щоб серіалізувати дані в JSON без проміжних кроків, як-от перетворення за допомогою `jsonable_encoder`, що відбувалося б в іншому випадку.
+
+І «під капотом» Pydantic використовує ті самі внутрішні механізми Rust, що й `orjson`, для серіалізації в JSON, тож ви вже отримаєте найкращу продуктивність із моделлю відповіді.
+
+## Типова відповідь за замовчуванням { #default-response-class }
+
+Створюючи екземпляр класу **FastAPI** або `APIRouter`, ви можете вказати, який клас відповіді використовувати за замовчуванням.
+
+Параметр, що це визначає, - `default_response_class`.
+
+У прикладі нижче **FastAPI** використовуватиме `HTMLResponse` за замовчуванням в усіх операціях шляху, замість JSON.
+
+{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}
+
+/// tip | Порада
+
+Ви все одно можете переписати `response_class` в операціях шляху, як і раніше.
+
+///
+
+## Додаткова документація { #additional-documentation }
+
+Ви також можете оголосити медіа-тип і багато інших деталей в OpenAPI, використовуючи `responses`: [Додаткові відповіді в OpenAPI](additional-responses.md).
diff --git a/docs/uk/docs/advanced/dataclasses.md b/docs/uk/docs/advanced/dataclasses.md
new file mode 100644
index 0000000000000..1c91304b08aa2
--- /dev/null
+++ b/docs/uk/docs/advanced/dataclasses.md
@@ -0,0 +1,95 @@
+# Використання dataclasses { #using-dataclasses }
+
+FastAPI побудовано поверх **Pydantic**, і я показував вам, як використовувати моделі Pydantic для оголошення запитів і відповідей.
+
+Але FastAPI також підтримує використання [`dataclasses`](https://docs.python.org/3/library/dataclasses.html) таким самим чином:
+
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
+
+Це підтримується завдяки **Pydantic**, адже він має [внутрішню підтримку `dataclasses`](https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel).
+
+Тож навіть із наведеним вище кодом, який явно не використовує Pydantic, FastAPI використовує Pydantic, щоб перетворити стандартні dataclasses у власний варіант dataclasses Pydantic.
+
+І, звісно, підтримується те саме:
+
+* валідація даних
+* серіалізація даних
+* документація даних тощо
+
+Це працює так само, як із моделями Pydantic. Насправді під капотом це також досягається за допомогою Pydantic.
+
+/// info
+
+Майте на увазі, що dataclasses не можуть робити все те, що можуть моделі Pydantic.
+
+Тож вам усе ще може знадобитися використовувати моделі Pydantic.
+
+Але якщо у вас вже є чимало dataclasses, це зручний трюк, щоб задіяти їх для веб-API на FastAPI. 🤓
+
+///
+
+## Dataclasses у `response_model` { #dataclasses-in-response-model }
+
+Ви також можете використовувати `dataclasses` у параметрі `response_model`:
+
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
+
+Dataclass буде автоматично перетворено на dataclass Pydantic.
+
+Таким чином його схема з'явиться в інтерфейсі користувача документації API:
+
+
+
+## Dataclasses у вкладених структурах даних { #dataclasses-in-nested-data-structures }
+
+Можна поєднувати `dataclasses` з іншими анотаціями типів, щоб створювати вкладені структури даних.
+
+У деяких випадках вам усе ж доведеться використовувати варіант `dataclasses` від Pydantic. Наприклад, якщо виникають помилки з автоматично згенерованою документацією API.
+
+У такому разі ви можете просто замінити стандартні `dataclasses` на `pydantic.dataclasses`, що є взаємозамінником:
+
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+
+1. Ми все ще імпортуємо `field` зі стандартних `dataclasses`.
+
+2. `pydantic.dataclasses` - це взаємозамінник для `dataclasses`.
+
+3. Dataclass `Author` містить список dataclass `Item`.
+
+4. Dataclass `Author` використовується як параметр `response_model`.
+
+5. Ви можете використовувати інші стандартні анотації типів із dataclasses як тіло запиту.
+
+ У цьому випадку це список dataclass `Item`.
+
+6. Тут ми повертаємо словник, що містить `items`, який є списком dataclass.
+
+ FastAPI усе ще здатний серіалізувати дані до JSON.
+
+7. Тут у `response_model` використано анотацію типу список dataclass `Author`.
+
+ Знову ж, ви можете поєднувати `dataclasses` зі стандартними анотаціями типів.
+
+8. Зверніть увагу, що ця *функція операції шляху* використовує звичайний `def` замість `async def`.
+
+ Як завжди, у FastAPI ви можете поєднувати `def` і `async def` за потреби.
+
+ Якщо вам потрібне коротке нагадування, коли що використовувати, перегляньте розділ _«Поспішаєте?»_ у документації про [`async` та `await`](../async.md#in-a-hurry).
+
+9. Ця *функція операції шляху* не повертає dataclasses (хоча могла б), а список словників із внутрішніми даними.
+
+ FastAPI використає параметр `response_model` (що включає dataclasses), щоб перетворити відповідь.
+
+Ви можете поєднувати `dataclasses` з іншими анотаціями типів у багатьох поєднаннях, щоб формувати складні структури даних.
+
+Перегляньте підказки щодо анотацій у коді вище, щоб побачити більше деталей.
+
+## Дізнатися більше { #learn-more }
+
+Можна поєднувати `dataclasses` з іншими моделями Pydantic, наслідувати їх, включати у власні моделі тощо.
+
+Щоб дізнатися більше, перегляньте [документацію Pydantic про dataclasses](https://docs.pydantic.dev/latest/concepts/dataclasses/).
+
+## Версія { #version }
+
+Доступно починаючи з версії FastAPI `0.67.0`. 🔖
diff --git a/docs/uk/docs/advanced/events.md b/docs/uk/docs/advanced/events.md
new file mode 100644
index 0000000000000..33f6314fe1f0c
--- /dev/null
+++ b/docs/uk/docs/advanced/events.md
@@ -0,0 +1,165 @@
+# Події тривалості життя { #lifespan-events }
+
+Ви можете визначити логіку (код), яку слід виконати перед тим, як застосунок запуститься. Це означає, що цей код буде виконано один раз, перед тим як застосунок почне отримувати запити.
+
+Так само ви можете визначити логіку (код), яку слід виконати під час вимкнення застосунку. У цьому випадку код буде виконано один раз, після обробки можливо багатьох запитів.
+
+Оскільки цей код виконується перед тим, як застосунок почне приймати запити, і одразу після того, як він завершить їх обробку, він охоплює всю тривалість життя застосунку (слово «lifespan» буде важливим за мить 😉).
+
+Це дуже корисно для налаштування ресурсів, які потрібні для всього застосунку, які спільні між запитами, та/або які потрібно потім прибрати. Наприклад, пул з’єднань з базою даних або завантаження спільної моделі машинного навчання.
+
+## Випадок використання { #use-case }
+
+Почнемо з прикладу випадку використання, а потім подивимось, як це вирішити.
+
+Уявімо, що у вас є моделі машинного навчання, якими ви хочете обробляти запити. 🤖
+
+Ті самі моделі спільні між запитами, тобто це не окрема модель на запит чи на користувача.
+
+Уявімо, що завантаження моделі може займати чимало часу, бо треба читати багато даних з диска. Тож ви не хочете робити це для кожного запиту.
+
+Ви могли б завантажити її на верхньому рівні модуля/файлу, але це означало б, що модель завантажиться навіть якщо ви просто запускаєте простий автоматизований тест - тоді тест буде повільним, бо йому доведеться чекати завантаження моделі перед виконанням незалежної частини коду.
+
+Ось це ми й вирішимо: завантажимо модель перед обробкою запитів, але лише безпосередньо перед тим, як застосунок почне отримувати запити, а не під час завантаження коду.
+
+## Тривалість життя { #lifespan }
+
+Ви можете визначити цю логіку запуску і вимкнення за допомогою параметра `lifespan` застосунку `FastAPI` та «менеджера контексту» (зараз покажу, що це).
+
+Почнемо з прикладу, а потім розберемо детально.
+
+Ми створюємо асинхронну функцію `lifespan()` з `yield` так:
+
+{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}
+
+Тут ми імітуємо дорогу операцію запуску із завантаженням моделі, поміщаючи (фальшиву) функцію моделі у словник з моделями машинного навчання перед `yield`. Цей код буде виконано перед тим, як застосунок почне приймати запити, під час запуску.
+
+А одразу після `yield` ми розвантажуємо модель. Цей код буде виконано після того, як застосунок завершить обробку запитів, безпосередньо перед вимкненням. Це, наприклад, може звільнити ресурси на кшталт пам’яті або GPU.
+
+/// tip | Порада
+
+Подія `shutdown` відбувається, коли ви зупиняєте застосунок.
+
+Можливо, вам треба запустити нову версію, або ви просто втомилися її запускати. 🤷
+
+///
+
+### Функція тривалості життя { #lifespan-function }
+
+Перше, на що слід звернути увагу: ми визначаємо асинхронну функцію з `yield`. Це дуже схоже на залежності з `yield`.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}
+
+Перша частина функції до `yield` буде виконана перед запуском застосунку.
+
+А частина після `yield` буде виконана після завершення роботи застосунку.
+
+### Асинхронний менеджер контексту { #async-context-manager }
+
+Якщо придивитися, функція задекорована за допомогою `@asynccontextmanager`.
+
+Це перетворює функцію на так званий «асинхронний менеджер контексту».
+
+{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}
+
+Менеджер контексту в Python - це те, що можна використовувати в операторі `with`, наприклад, `open()` можна використовувати як менеджер контексту:
+
+```Python
+with open("file.txt") as file:
+ file.read()
+```
+
+У новіших версіях Python також є асинхронний менеджер контексту. Його використовують з `async with`:
+
+```Python
+async with lifespan(app):
+ await do_stuff()
+```
+
+Коли ви створюєте менеджер контексту або асинхронний менеджер контексту, як вище, перед входом у блок `with` буде виконано код перед `yield`, а після виходу з блоку `with` буде виконано код після `yield`.
+
+У нашому прикладі коду вище ми не використовуємо його напряму, а передаємо його до FastAPI, щоб він його використав.
+
+Параметр `lifespan` застосунку `FastAPI` приймає асинхронний менеджер контексту, тож ми можемо передати йому наш новий асинхронний менеджер контексту `lifespan`.
+
+{* ../../docs_src/events/tutorial003_py310.py hl[22] *}
+
+## Альтернативні події (застаріло) { #alternative-events-deprecated }
+
+/// warning | Попередження
+
+Рекомендований спосіб обробляти запуск і вимкнення - використовувати параметр `lifespan` застосунку `FastAPI`, як описано вище. Якщо ви надаєте параметр `lifespan`, обробники подій `startup` і `shutdown` більше не будуть викликані. Або все через `lifespan`, або все через події - не обидва одночасно.
+
+Можете, ймовірно, пропустити цю частину.
+
+///
+
+Є альтернативний спосіб визначити логіку, яку слід виконати під час запуску і під час вимкнення.
+
+Ви можете визначити обробники подій (функції), які потрібно виконати перед запуском застосунку або коли застосунок вимикається.
+
+Ці функції можна оголошувати як з `async def`, так і звичайним `def`.
+
+### Подія `startup` { #startup-event }
+
+Щоб додати функцію, яку слід виконати перед запуском застосунку, оголосіть її з подією `"startup"`:
+
+{* ../../docs_src/events/tutorial001_py310.py hl[8] *}
+
+У цьому випадку функція-обробник події `startup` ініціалізує «базу даних» предметів (це лише `dict`) деякими значеннями.
+
+Ви можете додати більше ніж один обробник події.
+
+І ваш застосунок не почне приймати запити, доки всі обробники події `startup` не завершаться.
+
+### Подія `shutdown` { #shutdown-event }
+
+Щоб додати функцію, яку слід виконати, коли застосунок вимикається, оголосіть її з подією `"shutdown"`:
+
+{* ../../docs_src/events/tutorial002_py310.py hl[6] *}
+
+Тут функція-обробник події `shutdown` запише текстовий рядок `"Application shutdown"` у файл `log.txt`.
+
+/// info | Інформація
+
+У функції `open()` параметр `mode="a"` означає «append», тож рядок буде додано після всього, що є у файлі, без перезапису попереднього вмісту.
+
+///
+
+/// tip | Порада
+
+Зауважте, що в цьому випадку ми використовуємо стандартну Python-функцію `open()`, яка працює з файлом.
+
+Тобто вона включає I/O (input/output), де потрібно «чекати», поки дані буде записано на диск.
+
+Але `open()` не використовує `async` і `await`.
+
+Тому ми оголошуємо функцію-обробник події зі стандартним `def`, а не `async def`.
+
+///
+
+### Разом `startup` і `shutdown` { #startup-and-shutdown-together }
+
+Велика ймовірність, що логіка для вашого запуску і вимкнення пов’язана: ви можете хотіти щось запустити, а потім завершити, отримати ресурс, а потім звільнити його тощо.
+
+Робити це в окремих функціях, які не діляться логікою чи змінними, складніше - доведеться зберігати значення у глобальних змінних або вдаватися до подібних трюків.
+
+Тому зараз рекомендується натомість використовувати `lifespan`, як пояснено вище.
+
+## Технічні деталі { #technical-details }
+
+Невелика технічна деталь для допитливих нердів. 🤓
+
+Під капотом, у технічній специфікації ASGI, це частина [Протоколу тривалості життя](https://asgi.readthedocs.io/en/latest/specs/lifespan.html), і там визначені події `startup` і `shutdown`.
+
+/// info | Інформація
+
+Ви можете прочитати більше про обробники `lifespan` у [документації Starlette про Lifespan](https://www.starlette.dev/lifespan/).
+
+Зокрема, як працювати зі станом тривалості життя, який можна використовувати в інших ділянках вашого коду.
+
+///
+
+## Підзастосунки { #sub-applications }
+
+🚨 Майте на увазі, що ці події тривалості життя (startup і shutdown) виконуються лише для головного застосунку, а не для [Підзастосунки - монтування](sub-applications.md).
diff --git a/docs/uk/docs/advanced/generate-clients.md b/docs/uk/docs/advanced/generate-clients.md
new file mode 100644
index 0000000000000..257089c41a9d1
--- /dev/null
+++ b/docs/uk/docs/advanced/generate-clients.md
@@ -0,0 +1,208 @@
+# Генерація SDK { #generating-sdks }
+
+Оскільки **FastAPI** базується на специфікації **OpenAPI**, його API можна описати у стандартному форматі, який розуміють багато інструментів.
+
+Це спрощує створення актуальної **документації**, клієнтських бібліотек (**SDKs**) багатьма мовами, а також **тестування** чи **автоматизованих робочих процесів**, що залишаються синхронізованими з вашим кодом.
+
+У цьому посібнику ви дізнаєтеся, як згенерувати **TypeScript SDK** для вашого бекенда на FastAPI.
+
+## Генератори SDK з відкритим кодом { #open-source-sdk-generators }
+
+Універсальним варіантом є [OpenAPI Generator](https://openapi-generator.tech/), який підтримує **багато мов програмування** та може генерувати SDK з вашої специфікації OpenAPI.
+
+Для **клієнтів TypeScript** [Hey API](https://heyapi.dev/) — спеціалізоване рішення, що надає оптимізований досвід для екосистеми TypeScript.
+
+Більше генераторів SDK ви можете знайти на [OpenAPI.Tools](https://openapi.tools/#sdk).
+
+/// tip | Порада
+
+FastAPI автоматично генерує специфікації **OpenAPI 3.1**, тож будь-який інструмент, який ви використовуєте, має підтримувати цю версію.
+
+///
+
+## Генератори SDK від спонсорів FastAPI { #sdk-generators-from-fastapi-sponsors }
+
+У цьому розділі представлено рішення від компаній, що спонсорують FastAPI: вони мають **венчурну підтримку** та **корпоративну підтримку**. Ці продукти надають **додаткові можливості** та **інтеграції** поверх високоякісно згенерованих SDK.
+
+Завдяки ✨ [**спонсорству FastAPI**](../help-fastapi.md#sponsor-the-author) ✨ ці компанії допомагають підтримувати фреймворк та його **екосистему** здоровими та **сталими**.
+
+Їхня підтримка також демонструє сильну відданість **спільноті** FastAPI (вам), показуючи, що їм важливо не лише надавати **відмінний сервіс**, а й підтримувати **міцний і процвітаючий фреймворк**, FastAPI. 🙇
+
+Наприклад, ви можете спробувати:
+
+* [Speakeasy](https://speakeasy.com/editor?utm_source=fastapi+repo&utm_medium=github+sponsorship)
+* [Stainless](https://www.stainless.com/?utm_source=fastapi&utm_medium=referral)
+* [liblab](https://developers.liblab.com/tutorials/sdk-for-fastapi?utm_source=fastapi)
+
+Деякі з цих рішень також можуть бути з відкритим кодом або мати безкоштовні тарифи, тож ви можете спробувати їх без фінансових зобов'язань. Інші комерційні генератори SDK також доступні й їх можна знайти онлайн. 🤓
+
+## Створити TypeScript SDK { #create-a-typescript-sdk }
+
+Почнімо з простого застосунку FastAPI:
+
+{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}
+
+Зверніть увагу, що *операції шляху* визначають моделі, які вони використовують для корисного навантаження запиту та корисного навантаження відповіді, використовуючи моделі `Item` і `ResponseMessage`.
+
+### Документація API { #api-docs }
+
+Якщо ви перейдете до `/docs`, ви побачите **схеми** даних, які надсилаються в запитах і приймаються у відповідях:
+
+
+
+Ви бачите ці схеми, оскільки їх було оголошено як моделі в застосунку.
+
+Ця інформація доступна у **схемі OpenAPI** застосунку, а потім показується в документації API.
+
+Та сама інформація з моделей, яку включено до OpenAPI, може бути використана для **генерації клієнтського коду**.
+
+### Hey API { #hey-api }
+
+Коли у нас є застосунок FastAPI з моделями, ми можемо використати Hey API для генерації клієнта TypeScript. Найшвидший спосіб зробити це — через npx.
+
+```sh
+npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
+```
+
+Це згенерує TypeScript SDK у `./src/client`.
+
+Ви можете дізнатися, як [встановити `@hey-api/openapi-ts`](https://heyapi.dev/openapi-ts/get-started), і почитати про [згенерований результат](https://heyapi.dev/openapi-ts/output) на їхньому сайті.
+
+### Використання SDK { #using-the-sdk }
+
+Тепер ви можете імпортувати та використовувати клієнтський код. Це може виглядати так; зверніть увагу, що ви отримуєте «автодоповнення» для методів:
+
+
+
+Ви також отримаєте автодоповнення для корисного навантаження, яке надсилаєте:
+
+
+
+/// tip | Порада
+
+Зверніть увагу на автодоповнення для `name` і `price`, які були визначені в застосунку FastAPI, у моделі `Item`.
+
+///
+
+Ви бачитимете вбудовані помилки для даних, які надсилаєте:
+
+
+
+Об'єкт відповіді також матиме автодоповнення:
+
+
+
+## Застосунок FastAPI з мітками { #fastapi-app-with-tags }
+
+У багатьох випадках ваш застосунок FastAPI буде більшим, і ви, ймовірно, використовуватимете мітки, щоб розділяти різні групи *операцій шляху*.
+
+Наприклад, у вас може бути секція для **items** і окрема секція для **users**, і їх можна розділити мітками:
+
+{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}
+
+### Згенерувати TypeScript-клієнт із мітками { #generate-a-typescript-client-with-tags }
+
+Якщо ви згенеруєте клієнт для застосунку FastAPI, що використовує мітки, зазвичай клієнтський код також буде розділено за цими мітками.
+
+Таким чином, ви матимете правильно впорядковані та згруповані частини клієнтського коду:
+
+
+
+У цьому випадку у вас є:
+
+* `ItemsService`
+* `UsersService`
+
+### Назви методів клієнта { #client-method-names }
+
+Зараз згенеровані назви методів на кшталт `createItemItemsPost` виглядають не дуже охайно:
+
+```TypeScript
+ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
+```
+
+...це тому, що генератор клієнта використовує внутрішній OpenAPI **operation ID** для кожної *операції шляху*.
+
+OpenAPI вимагає, щоб кожен operation ID був унікальним для всіх *операцій шляху*, тому FastAPI використовує **назву функції**, **шлях** і **HTTP-метод/операцію** для генерації цього operation ID, адже так воно може гарантувати унікальність operation ID.
+
+Але далі я покажу, як це покращити. 🤓
+
+## Користувацькі operation ID та кращі назви методів { #custom-operation-ids-and-better-method-names }
+
+Ви можете **змінити** спосіб **генерації** цих operation ID, щоб зробити їх простішими та мати **простіші назви методів** у клієнтах.
+
+У цьому випадку вам потрібно буде іншим способом гарантувати, що кожен operation ID є **унікальним**.
+
+Наприклад, ви можете переконатися, що кожна *операція шляху* має мітку, а потім генерувати operation ID на основі **мітки** та **назви** *операції шляху* (назви функції).
+
+### Користувацька функція генерування унікального ID { #custom-generate-unique-id-function }
+
+FastAPI використовує **унікальний ID** для кожної *операції шляху*, який застосовується для **operation ID**, а також для назв будь-яких потрібних користувацьких моделей для запитів чи відповідей.
+
+Ви можете налаштувати цю функцію. Вона приймає `APIRoute` і повертає строку.
+
+Наприклад, тут використовується перша мітка (у вас, ймовірно, буде лише одна мітка) і назва *операції шляху* (назва функції).
+
+Потім ви можете передати цю користувацьку функцію до **FastAPI** як параметр `generate_unique_id_function`:
+
+{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}
+
+### Згенерувати TypeScript-клієнт з користувацькими operation ID { #generate-a-typescript-client-with-custom-operation-ids }
+
+Тепер, якщо ви згенеруєте клієнт знову, ви побачите покращені назви методів:
+
+
+
+Як бачите, тепер у назвах методів є мітка, а потім назва функції; вони більше не містять інформації з URL-шляху та HTTP-операції.
+
+### Попередня обробка специфікації OpenAPI для генератора клієнта { #preprocess-the-openapi-specification-for-the-client-generator }
+
+У згенерованому коді все ще є певна **дубльована інформація**.
+
+Ми вже знаємо, що цей метод стосується **items**, адже це слово є в `ItemsService` (взято з мітки), але все ще маємо назву мітки як префікс у назві методу. 😕
+
+Ми, ймовірно, все одно захочемо зберегти це загалом для OpenAPI, адже так гарантується унікальність operation ID.
+
+Але для згенерованого клієнта ми можемо **змінити** operation ID в OpenAPI безпосередньо перед генерацією клієнтів, просто щоб зробити назви методів приємнішими та **чистішими**.
+
+Ми можемо завантажити JSON OpenAPI у файл `openapi.json`, а потім **прибрати цей префікс із міткою** за допомогою такого скрипту:
+
+{* ../../docs_src/generate_clients/tutorial004_py310.py *}
+
+//// tab | Node.js
+
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
+```
+
+////
+
+Після цього operation ID буде перейменовано з чогось на кшталт `items-get_items` просто на `get_items`, тож генератор клієнта зможе створити простіші назви методів.
+
+### Згенерувати TypeScript-клієнт із попередньо обробленим OpenAPI { #generate-a-typescript-client-with-the-preprocessed-openapi }
+
+Оскільки кінцевий результат тепер у файлі `openapi.json`, вам потрібно оновити шлях до вхідних даних:
+
+```sh
+npx @hey-api/openapi-ts -i ./openapi.json -o src/client
+```
+
+Після генерації нового клієнта ви отримаєте **чисті назви методів**, із усім **автодоповненням**, **вбудованими помилками** тощо:
+
+
+
+## Переваги { #benefits }
+
+Використовуючи автоматично згенеровані клієнти, ви отримаєте **автодоповнення** для:
+
+* Методів.
+* Корисного навантаження запиту в тілі, параметрах запиту тощо.
+* Корисного навантаження відповіді.
+
+Також ви матимете **вбудовані помилки** для всього.
+
+І щоразу, коли ви оновлюєте код бекенда та **перегенеровуєте** фронтенд, у ньому з'являтимуться нові *операції шляху* як методи, старі буде видалено, а будь-які інші зміни відобразяться у згенерованому коді. 🤓
+
+Це також означає, що якщо щось змінилося, це буде **відображено** в клієнтському коді автоматично. А якщо ви **зіберете** клієнт, буде повідомлено про помилку, якщо є будь-яка **невідповідність** у використаних даних.
+
+Таким чином, ви **виявлятимете багато помилок** дуже рано в циклі розробки, замість того, щоб чекати, поки помилки проявляться у ваших кінцевих користувачів у продакшені, і лише потім намагатися з'ясувати, у чому проблема. ✨
diff --git a/docs/uk/docs/advanced/index.md b/docs/uk/docs/advanced/index.md
new file mode 100644
index 0000000000000..d856c1e9e1b4f
--- /dev/null
+++ b/docs/uk/docs/advanced/index.md
@@ -0,0 +1,21 @@
+# Просунутий посібник користувача { #advanced-user-guide }
+
+## Додаткові можливості { #additional-features }
+
+Основний [Навчальний посібник - Посібник користувача](../tutorial/index.md) має бути достатнім, щоб провести вас через усі основні можливості **FastAPI**.
+
+У наступних розділах ви побачите інші опції, конфігурації та додаткові можливості.
+
+/// tip
+
+Наступні розділи **не обов'язково «просунуті»**.
+
+І можливо, що рішення для вашого випадку використання може бути в одному з них.
+
+///
+
+## Спершу прочитайте навчальний посібник { #read-the-tutorial-first }
+
+Ви все ще можете використовувати більшість можливостей **FastAPI**, маючи знання з основного [Навчального посібника - Посібника користувача](../tutorial/index.md).
+
+А в наступних розділах передбачається, що ви вже його прочитали і знайомі з основними ідеями.
diff --git a/docs/uk/docs/advanced/json-base64-bytes.md b/docs/uk/docs/advanced/json-base64-bytes.md
new file mode 100644
index 0000000000000..2cb6461ec77ba
--- /dev/null
+++ b/docs/uk/docs/advanced/json-base64-bytes.md
@@ -0,0 +1,63 @@
+# JSON з байтами як Base64 { #json-with-bytes-as-base64 }
+
+Якщо ваш застосунок має отримувати і надсилати дані JSON, але потрібно включати туди двійкові дані, ви можете кодувати їх як base64.
+
+## Base64 проти файлів { #base64-vs-files }
+
+Насамперед розгляньте, чи можете ви використати [Файли запиту](../tutorial/request-files.md) для завантаження двійкових даних і [Користувацька відповідь - FileResponse](./custom-response.md#fileresponse--fileresponse-) для надсилання двійкових даних замість кодування їх у JSON.
+
+JSON може містити лише строки, закодовані в UTF-8, тому він не може містити «сирі» байти.
+
+Base64 може кодувати двійкові дані у строках, але для цього потрібно більше символів, ніж у початкових двійкових даних, тож зазвичай це менш ефективно, ніж звичайні файли.
+
+Використовуйте base64 лише якщо справді потрібно включати двійкові дані в JSON і ви не можете використати файли для цього.
+
+## Pydantic `bytes` { #pydantic-bytes }
+
+Ви можете оголосити модель Pydantic з полями `bytes`, а потім використати `val_json_bytes` у конфігурації моделі, щоб вказати їй використовувати base64 для перевірки вхідних даних JSON; як частина цієї перевірки, вона декодує строку base64 у байти.
+
+{* ../../docs_src/json_base64_bytes/tutorial001_py310.py ln[1:9,29:35] hl[9] *}
+
+Якщо ви перевірите `/docs`, там буде показано, що поле `data` очікує байти, закодовані в base64:
+
+
+
diff --git a/docs/uk/docs/advanced/openapi-webhooks.md b/docs/uk/docs/advanced/openapi-webhooks.md
new file mode 100644
index 0000000000000..bf51f54667504
--- /dev/null
+++ b/docs/uk/docs/advanced/openapi-webhooks.md
@@ -0,0 +1,55 @@
+# Вебхуки OpenAPI { #openapi-webhooks }
+
+Бувають випадки, коли ви хочете повідомити **користувачів** вашого API, що ваш застосунок може викликати *їхній* застосунок (надсилаючи запит) із деякими даними, зазвичай щоб **сповістити** про певний тип **події**.
+
+Це означає, що замість звичного процесу, коли ваші користувачі надсилають запити до вашого API, саме **ваш API** (або ваш застосунок) може **надсилати запити до їхньої системи** (до їх API, їх застосунку).
+
+Зазвичай це називають **вебхуком**.
+
+## Кроки вебхуків { #webhooks-steps }
+
+Зазвичай процес такий: ви визначаєте у своєму коді, яке повідомлення надсилатимете, тобто **тіло запиту**.
+
+Ви також якимось чином визначаєте моменти, коли ваш застосунок надсилатиме ці запити або події.
+
+А **ваші користувачі** якимось чином (наприклад, у веб-дашборді) визначають **URL**, куди ваш застосунок має надсилати ці запити.
+
+Уся **логіка** щодо реєстрації URL для вебхуків і код для фактичного надсилання цих запитів - на ваш розсуд. Ви пишете це у **власному коді** так, як вважаєте за потрібне.
+
+## Документування вебхуків у **FastAPI** та OpenAPI { #documenting-webhooks-with-fastapi-and-openapi }
+
+У **FastAPI**, використовуючи OpenAPI, ви можете визначити назви цих вебхуків, типи HTTP-операцій, які ваш застосунок може надсилати (наприклад, `POST`, `PUT` тощо), і **тіла** запитів, які ваш застосунок надсилатиме.
+
+Це значно спростить для ваших користувачів **реалізацію їхніх API** для отримання ваших запитів **вебхуків**; вони навіть зможуть згенерувати частину власного коду API автоматично.
+
+/// info | Інформація
+
+Вебхуки доступні в OpenAPI 3.1.0 і вище, підтримуються FastAPI `0.99.0` і вище.
+
+///
+
+## Застосунок із вебхуками { #an-app-with-webhooks }
+
+Коли ви створюєте застосунок **FastAPI**, є атрибут `webhooks`, який можна використати для визначення *вебхуків* так само, як ви визначаєте *операції шляху*, наприклад за допомогою `@app.webhooks.post()`.
+
+{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}
+
+Визначені вами вебхуки потраплять до **схеми OpenAPI** та автоматичного **інтерфейсу документації**.
+
+/// info | Інформація
+
+Об'єкт `app.webhooks` насправді є просто `APIRouter` - тим самим типом, який ви використовуєте, структуризуючи застосунок у кількох файлах.
+
+///
+
+Зверніть увагу, що з вебхуками ви фактично не оголошуєте *шлях* (на кшталт `/items/`), текст, який ви передаєте там, - це лише **ідентифікатор** вебхука (назва події). Наприклад, у `@app.webhooks.post("new-subscription")` назва вебхука - `new-subscription`.
+
+Це тому, що очікується, що **ваші користувачі** іншим способом (наприклад, у веб-дашборді) визначать фактичний **URL-шлях**, де вони хочуть отримувати запит вебхука.
+
+### Перевірте документацію { #check-the-docs }
+
+Тепер ви можете запустити свій застосунок і перейти за адресою [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).
+
+Ви побачите у своїй документації звичайні *операції шляху*, а також деякі **вебхуки**:
+
+
diff --git a/docs/uk/docs/advanced/path-operation-advanced-configuration.md b/docs/uk/docs/advanced/path-operation-advanced-configuration.md
new file mode 100644
index 0000000000000..f760209abedad
--- /dev/null
+++ b/docs/uk/docs/advanced/path-operation-advanced-configuration.md
@@ -0,0 +1,172 @@
+# Додаткова конфігурація операцій шляху { #path-operation-advanced-configuration }
+
+## OpenAPI operationId { #openapi-operationid }
+
+/// warning | Попередження
+
+Якщо ви не «експерт» з OpenAPI, імовірно, вам це не потрібно.
+
+///
+
+Ви можете встановити OpenAPI `operationId`, який буде використано у вашій *операції шляху*, за допомогою параметра `operation_id`.
+
+Потрібно переконатися, що він унікальний для кожної операції.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
+
+### Використання назви *функції операції шляху* як operationId { #using-the-path-operation-function-name-as-the-operationid }
+
+Якщо ви хочете використовувати назви функцій ваших API як `operationId`, ви можете пройтися по всіх них і переписати `operation_id` кожної *операції шляху*, використовуючи їхній `APIRoute.name`.
+
+Зробіть це після додавання всіх *операцій шляху*.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *}
+
+/// tip | Порада
+
+Якщо ви вручну викликаєте `app.openapi()`, оновіть усі `operationId` до цього.
+
+///
+
+/// warning | Попередження
+
+Якщо ви робите це, переконайтеся, що кожна з ваших *функцій операцій шляху* має унікальну назву.
+
+Навіть якщо вони в різних модулях (файлах Python).
+
+///
+
+## Виключення з OpenAPI { #exclude-from-openapi }
+
+Щоб виключити *операцію шляху* зі згенерованої Схеми OpenAPI (а отже, і з автоматичних систем документації), використайте параметр `include_in_schema` і встановіть його в `False`:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}
+
+## Розширений опис із docstring { #advanced-description-from-docstring }
+
+Ви можете обмежити кількість рядків із docstring *функції операції шляху*, що використовуються для OpenAPI.
+
+Додавання `\f` (екранованого символу «form feed») змусить **FastAPI** обрізати вивід для OpenAPI в цій точці.
+
+Це не з’явиться в документації, але інші інструменти (такі як Sphinx) зможуть використати решту.
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}
+
+## Додаткові відповіді { #additional-responses }
+
+Ймовірно, ви вже бачили, як оголошувати `response_model` і `status_code` для *операції шляху*.
+
+Це визначає метадані про основну відповідь *операції шляху*.
+
+Також можна оголосити додаткові відповіді з їхніми моделями, кодами статусу тощо.
+
+У документації є цілий розділ про це, ви можете прочитати його тут: [Додаткові відповіді в OpenAPI](additional-responses.md).
+
+## Додатково в OpenAPI { #openapi-extra }
+
+Коли ви оголошуєте *операцію шляху* у своєму застосунку, **FastAPI** автоматично генерує відповідні метадані про цю *операцію шляху* для включення в Схему OpenAPI.
+
+/// note | Технічні деталі
+
+У специфікації OpenAPI це називається [Об'єкт Operation](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object).
+
+///
+
+Він містить усю інформацію про *операцію шляху* і використовується для побудови автоматичної документації.
+
+Він включає `tags`, `parameters`, `requestBody`, `responses` тощо.
+
+Цю OpenAPI-схему, специфічну для *операції шляху*, зазвичай генерує **FastAPI** автоматично, але ви також можете її розширити.
+
+/// tip | Порада
+
+Це низькорівнева точка розширення.
+
+Якщо вам потрібно лише оголосити додаткові відповіді, зручніше зробити це через [Додаткові відповіді в OpenAPI](additional-responses.md).
+
+///
+
+Ви можете розширити OpenAPI-схему для *операції шляху*, використовуючи параметр `openapi_extra`.
+
+### Розширення OpenAPI { #openapi-extensions }
+
+`openapi_extra` може бути корисним, наприклад, для оголошення [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py310.py hl[6] *}
+
+Якщо ви відкриєте автоматичну документацію API, ваше розширення з’явиться внизу конкретної *операції шляху*.
+
+
+
+І якщо ви відкриєте згенерований OpenAPI (за адресою `/openapi.json` у вашому API), ви також побачите своє розширення як частину конкретної *операції шляху*:
+
+```JSON hl_lines="22"
+{
+ "openapi": "3.1.0",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0"
+ },
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ }
+ },
+ "x-aperture-labs-portal": "blue"
+ }
+ }
+ }
+}
+```
+
+### Власна схема OpenAPI для *операції шляху* { #custom-openapi-path-operation-schema }
+
+Словник у `openapi_extra` буде глибоко об’єднано з автоматично згенерованою OpenAPI-схемою для *операції шляху*.
+
+Тож ви можете додати додаткові дані до автоматично згенерованої схеми.
+
+Наприклад, ви можете вирішити читати та перевіряти запит власним кодом, не використовуючи автоматичні можливості FastAPI з Pydantic, але все ж захотіти визначити запит у Схемі OpenAPI.
+
+Ви можете зробити це за допомогою `openapi_extra`:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py310.py hl[19:36, 39:40] *}
+
+У цьому прикладі ми не оголошували жодної моделі Pydantic. Насправді тіло запиту навіть не розібрано як JSON, воно читається безпосередньо як `bytes`, а функція `magic_data_reader()` відповідатиме за його розбір певним чином.
+
+Водночас ми можемо оголосити очікувану схему для тіла запиту.
+
+### Власний тип вмісту OpenAPI { #custom-openapi-content-type }
+
+Використовуючи той самий прийом, ви можете застосувати модель Pydantic, щоб визначити Схему JSON, яка потім включається в користувацький розділ OpenAPI-схеми для *операції шляху*.
+
+І ви можете зробити це, навіть якщо тип даних у запиті - не JSON.
+
+Наприклад, у цьому застосунку ми не використовуємо вбудовану функціональність FastAPI для отримання Схеми JSON з моделей Pydantic і не використовуємо автоматичну валідацію для JSON. Насправді ми оголошуємо тип вмісту запиту як YAML, а не JSON:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[15:20, 22] *}
+
+Попри те, що ми не використовуємо типову вбудовану функціональність, ми все одно використовуємо модель Pydantic, щоб вручну згенерувати Схему JSON для даних, які хочемо отримати у форматі YAML.
+
+Потім ми працюємо із запитом безпосередньо і отримуємо тіло як `bytes`. Це означає, що FastAPI навіть не намагатиметься розібрати корисне навантаження запиту як JSON.
+
+Далі у нашому коді ми безпосередньо розбираємо цей YAML-вміст і знову використовуємо ту саму модель Pydantic, щоб перевірити YAML-вміст:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *}
+
+/// tip | Порада
+
+Тут ми перевикористовуємо ту саму модель Pydantic.
+
+Але так само ми могли б перевіряти дані іншим способом.
+
+///
diff --git a/docs/uk/docs/advanced/response-change-status-code.md b/docs/uk/docs/advanced/response-change-status-code.md
new file mode 100644
index 0000000000000..167df83132b49
--- /dev/null
+++ b/docs/uk/docs/advanced/response-change-status-code.md
@@ -0,0 +1,31 @@
+# Відповідь - зміна коду статусу { #response-change-status-code }
+
+Ймовірно, ви вже читали, що можна встановити типовий [код статусу відповіді](../tutorial/response-status-code.md).
+
+Але інколи потрібно повернути інший код статусу, ніж типовий.
+
+## Випадок використання { #use-case }
+
+Наприклад, уявімо, що ви хочете за замовчуванням повертати код статусу HTTP «OK» `200`.
+
+Але якщо даних не існувало, ви хочете створити їх і повернути код статусу HTTP «CREATED» `201`.
+
+Водночас ви все одно хочете мати змогу фільтрувати та перетворювати повернені дані за допомогою `response_model`.
+
+Для таких випадків ви можете використати параметр `Response`.
+
+## Використовуйте параметр `Response` { #use-a-response-parameter }
+
+Ви можете оголосити параметр типу `Response` у своїй функції операції шляху (так само, як для кукі та заголовків).
+
+Потім ви можете встановити `status_code` у цьому *тимчасовому* об'єкті відповіді.
+
+{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}
+
+Після цього ви можете повернути будь-який потрібний об'єкт, як зазвичай (`dict`, модель бази даних тощо).
+
+І якщо ви оголосили `response_model`, він усе одно буде використаний для фільтрації та перетворення поверненого об'єкта.
+
+**FastAPI** використає цей *тимчасовий* об'єкт відповіді, щоб отримати код статусу (а також кукі та заголовки), і помістить їх у фінальну відповідь, що містить повернуте вами значення, відфільтроване за допомогою `response_model`.
+
+Ви також можете оголосити параметр `Response` у залежностях і встановлювати там код статусу. Але майте на увазі: останнє встановлене значення матиме пріоритет.
diff --git a/docs/uk/docs/advanced/response-cookies.md b/docs/uk/docs/advanced/response-cookies.md
new file mode 100644
index 0000000000000..f4a79fb985d04
--- /dev/null
+++ b/docs/uk/docs/advanced/response-cookies.md
@@ -0,0 +1,51 @@
+# Кукі у відповіді { #response-cookies }
+
+## Використовуйте параметр `Response` { #use-a-response-parameter }
+
+Ви можете оголосити параметр типу `Response` у вашій *функції операції шляху*.
+
+Потім ви можете встановити кукі в цьому *тимчасовому* об'єкті відповіді.
+
+{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}
+
+Після цього ви можете повернути будь-який потрібний об'єкт, як зазвичай (наприклад, `dict`, модель бази даних тощо).
+
+І якщо ви оголосили `response_model`, він усе одно буде використаний для фільтрації та перетворення об'єкта, який ви повернули.
+
+**FastAPI** використає цю *тимчасову* відповідь, щоб витягнути кукі (а також заголовки та код статусу) і помістить їх у фінальну відповідь, що містить значення, яке ви повернули, відфільтроване будь-якою `response_model`.
+
+Ви також можете оголосити параметр `Response` у залежностях і встановлювати в них кукі (і заголовки).
+
+## Повертайте `Response` безпосередньо { #return-a-response-directly }
+
+Ви також можете створювати кукі, повертаючи `Response` безпосередньо у вашому коді.
+
+Для цього ви можете створити відповідь, як описано в [Повернути відповідь безпосередньо](response-directly.md).
+
+Потім встановіть у ньому кукі і поверніть його:
+
+{* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *}
+
+/// tip
+
+Майте на увазі, що якщо ви повертаєте відповідь безпосередньо замість використання параметра `Response`, FastAPI поверне її напряму.
+
+Тому вам потрібно переконатися, що ваші дані мають коректний тип. Наприклад, сумісні з JSON, якщо ви повертаєте `JSONResponse`.
+
+А також що ви не надсилаєте дані, які мали б бути відфільтровані за допомогою `response_model`.
+
+///
+
+### Більше інформації { #more-info }
+
+/// note | Технічні деталі
+
+Ви також можете використати `from starlette.responses import Response` або `from starlette.responses import JSONResponse`.
+
+**FastAPI** надає ті самі `starlette.responses` як `fastapi.responses` лише для зручності для вас, розробника. Але більшість доступних відповідей надходять безпосередньо зі Starlette.
+
+І оскільки `Response` часто використовується для встановлення заголовків і кукі, **FastAPI** також надає його як `fastapi.Response`.
+
+///
+
+Щоб побачити всі доступні параметри та опції, перегляньте [документацію в Starlette](https://www.starlette.dev/responses/#set-cookie).
diff --git a/docs/uk/docs/advanced/response-directly.md b/docs/uk/docs/advanced/response-directly.md
new file mode 100644
index 0000000000000..30d8f58609fa4
--- /dev/null
+++ b/docs/uk/docs/advanced/response-directly.md
@@ -0,0 +1,83 @@
+# Повернення Response безпосередньо { #return-a-response-directly }
+
+Коли ви створюєте операцію шляху **FastAPI**, зазвичай ви можете повертати з неї будь-які дані: `dict`, `list`, модель Pydantic, модель бази даних тощо.
+
+Якщо ви оголосите [Модель відповіді](../tutorial/response-model.md), **FastAPI** використає її, щоб серіалізувати дані у JSON за допомогою Pydantic.
+
+Якщо ви не оголошуєте модель відповіді, **FastAPI** використає `jsonable_encoder`, описаний у [Сумісному з JSON кодері](../tutorial/encoder.md), і помістить результат у `JSONResponse`.
+
+Ви також можете створити `JSONResponse` безпосередньо і повернути його.
+
+/// tip | Порада
+
+Зазвичай ви отримаєте значно кращу продуктивність, використовуючи [Модель відповіді](../tutorial/response-model.md), ніж повертаючи `JSONResponse` безпосередньо, адже так дані серіалізуються Pydantic на Rust.
+
+///
+
+## Повернення `Response` { #return-a-response }
+
+Ви можете повертати `Response` або будь-який його підклас.
+
+/// info | Інформація
+
+`JSONResponse` сам є підкласом `Response`.
+
+///
+
+І коли ви повертаєте `Response`, **FastAPI** передасть його безпосередньо.
+
+Він не виконуватиме жодних перетворень даних за допомогою моделей Pydantic, не перетворюватиме вміст на будь-який тип тощо.
+
+Це дає вам багато гнучкості. Ви можете повертати будь-які типи даних, переписувати будь-які оголошення або перевірки даних тощо.
+
+Це також покладає на вас багато відповідальності. Ви маєте переконатися, що дані, які ви повертаєте, коректні, у правильному форматі, можуть бути серіалізовані тощо.
+
+## Використання `jsonable_encoder` у `Response` { #using-the-jsonable-encoder-in-a-response }
+
+Оскільки **FastAPI** не вносить змін у `Response`, який ви повертаєте, вам потрібно впевнитися, що його вміст готовий.
+
+Наприклад, ви не можете помістити модель Pydantic у `JSONResponse`, не перетворивши її спочатку на `dict` з усіма типами даних (як-от `datetime`, `UUID` тощо), перетвореними на типи, сумісні з JSON.
+
+Для таких випадків ви можете використати `jsonable_encoder`, щоб перетворити ваші дані перед тим, як передати їх у відповідь:
+
+{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}
+
+/// note | Технічні деталі
+
+Ви також можете використати `from starlette.responses import JSONResponse`.
+
+**FastAPI** надає ті самі `starlette.responses` як `fastapi.responses` просто як зручність для вас, розробника. Але більшість доступних відповідей походять безпосередньо зі Starlette.
+
+///
+
+## Повернення власного `Response` { #returning-a-custom-response }
+
+Наведений вище приклад показує всі необхідні частини, але він ще не дуже корисний, адже ви могли просто повернути `item` безпосередньо, і **FastAPI** помістив би його у `JSONResponse`, перетворивши на `dict` тощо. Усе це відбувається за замовчуванням.
+
+Тепер подивімося, як це використати, щоб повернути власну відповідь.
+
+Припустімо, ви хочете повернути відповідь [XML](https://en.wikipedia.org/wiki/XML).
+
+Ви можете помістити свій вміст XML у строку, помістити це в `Response` і повернути:
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+## Як працює модель відповіді { #how-a-response-model-works }
+
+Коли ви оголошуєте [Модель відповіді - Тип, що повертається](../tutorial/response-model.md) в операції шляху, **FastAPI** використає її, щоб серіалізувати дані у JSON за допомогою Pydantic.
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+Оскільки це відбувається на боці Rust, продуктивність буде значно кращою, ніж якби це робилося звичайним Python і класом `JSONResponse`.
+
+Коли використовується `response_model` або тип, що повертається, **FastAPI** не використовуватиме `jsonable_encoder` для перетворення даних (що було б повільніше) і не використовуватиме клас `JSONResponse`.
+
+Натомість воно бере байти JSON, згенеровані Pydantic за допомогою моделі відповіді (або типу, що повертається), і повертає `Response` з відповідним медіа-типом для JSON (`application/json`) безпосередньо.
+
+## Примітки { #notes }
+
+Коли ви повертаєте `Response` безпосередньо, його дані не перевіряються, не перетворюються (серіалізуються) і не документуються автоматично.
+
+Але ви все ще можете задокументувати це, як описано в [Додаткових відповідях в OpenAPI](additional-responses.md).
+
+У подальших розділах ви побачите, як використовувати/оголошувати ці власні `Response`, водночас зберігаючи автоматичне перетворення даних, документацію тощо.
diff --git a/docs/uk/docs/advanced/response-headers.md b/docs/uk/docs/advanced/response-headers.md
new file mode 100644
index 0000000000000..95ab57fe08a0e
--- /dev/null
+++ b/docs/uk/docs/advanced/response-headers.md
@@ -0,0 +1,41 @@
+# Заголовки відповіді { #response-headers }
+
+## Використовуйте параметр `Response` { #use-a-response-parameter }
+
+Ви можете оголосити параметр типу `Response` у вашій функції операції шляху (так само, як і для кукі).
+
+Потім ви можете встановлювати заголовки в цьому *тимчасовому* обʼєкті відповіді.
+
+{* ../../docs_src/response_headers/tutorial002_py310.py hl[1, 7:8] *}
+
+Далі ви можете повернути будь-який потрібний обʼєкт, як зазвичай (наприклад, `dict`, модель бази даних тощо).
+
+Якщо ви оголосили `response_model`, його все одно буде використано для фільтрації та перетворення поверненого обʼєкта.
+
+**FastAPI** використає цей *тимчасовий* обʼєкт відповіді, щоб витягти заголовки (а також кукі та код статусу) і помістить їх у кінцеву відповідь, яка міститиме повернуте вами значення, відфільтроване будь-яким `response_model`.
+
+Також ви можете оголосити параметр `Response` у залежностях і встановлювати в них заголовки (та кукі).
+
+## Поверніть `Response` безпосередньо { #return-a-response-directly }
+
+Ви також можете додавати заголовки, коли повертаєте `Response` безпосередньо.
+
+Створіть відповідь, як описано в [Повернення Response безпосередньо](response-directly.md), і передайте заголовки як додатковий параметр:
+
+{* ../../docs_src/response_headers/tutorial001_py310.py hl[10:12] *}
+
+/// note | Технічні деталі
+
+Ви також можете використати `from starlette.responses import Response` або `from starlette.responses import JSONResponse`.
+
+**FastAPI** надає ті самі `starlette.responses` як `fastapi.responses` просто для зручності для вас, розробника. Але більшість доступних типів відповідей походять безпосередньо зі Starlette.
+
+Оскільки `Response` часто використовують для встановлення заголовків і кукі, **FastAPI** також надає його як `fastapi.Response`.
+
+///
+
+## Власні заголовки { #custom-headers }
+
+Майте на увазі, що власні пропрієтарні заголовки можна додавати [за допомогою префікса `X-`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers).
+
+Але якщо у вас є власні заголовки, які клієнт у браузері має бачити, вам потрібно додати їх у вашу конфігурацію CORS (докладніше в [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md)), використовуючи параметр `expose_headers`, задокументований у [документації Starlette щодо CORS](https://www.starlette.dev/middleware/#corsmiddleware).
diff --git a/docs/uk/docs/advanced/security/http-basic-auth.md b/docs/uk/docs/advanced/security/http-basic-auth.md
new file mode 100644
index 0000000000000..ac356dd8d6283
--- /dev/null
+++ b/docs/uk/docs/advanced/security/http-basic-auth.md
@@ -0,0 +1,107 @@
+# HTTP Basic Auth { #http-basic-auth }
+
+Для найпростіших випадків ви можете використовувати HTTP Basic Auth.
+
+У HTTP Basic Auth застосунок очікує заголовок, що містить ім'я користувача та пароль.
+
+Якщо він його не отримує, повертається помилка HTTP 401 «Unauthorized».
+
+І повертається заголовок `WWW-Authenticate` зі значенням `Basic` та необов'язковим параметром `realm`.
+
+Це каже браузеру показати вбудовану підсказку для введення імені користувача та пароля.
+
+Потім, коли ви введете це ім'я користувача та пароль, браузер автоматично надішле їх у заголовку.
+
+## Простий HTTP Basic Auth { #simple-http-basic-auth }
+
+- Імпортуйте `HTTPBasic` і `HTTPBasicCredentials`.
+- Створіть «`security` scheme» за допомогою `HTTPBasic`.
+- Використайте цей `security` як залежність у вашій операції шляху.
+- Він повертає об'єкт типу `HTTPBasicCredentials`:
+ - Він містить надіслані `username` і `password`.
+
+{* ../../docs_src/security/tutorial006_an_py310.py hl[4,8,12] *}
+
+Коли ви спробуєте відкрити URL вперше (або натиснете кнопку «Execute» у документації), браузер попросить вас ввести ім'я користувача та пароль:
+
+
+
+## Перевірте ім'я користувача { #check-the-username }
+
+Ось більш повний приклад.
+
+Використайте залежність, щоб перевірити, чи правильні ім'я користувача та пароль.
+
+Для цього використайте стандартний модуль Python [`secrets`](https://docs.python.org/3/library/secrets.html), щоб перевірити ім'я користувача та пароль.
+
+`secrets.compare_digest()` повинен отримувати `bytes` або `str`, що містить лише ASCII-символи (англійські), це означає, що він не працюватиме з символами на кшталт `á`, як у `Sebastián`.
+
+Щоб це обійти, ми спочатку перетворюємо `username` і `password` у `bytes`, кодувавши їх у UTF-8.
+
+Потім ми можемо використати `secrets.compare_digest()`, щоб упевнитися, що `credentials.username` дорівнює `"stanleyjobson"`, а `credentials.password` дорівнює `"swordfish"`.
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[1,12:24] *}
+
+Це було б подібно до:
+
+```Python
+if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
+ # Поверніть якусь помилку
+ ...
+```
+
+Але використовуючи `secrets.compare_digest()`, це буде захищено від типу атак, що називаються «атаки за часом» (timing attacks).
+
+### Атаки за часом { #timing-attacks }
+
+Що таке «атака за часом»?
+
+Уявімо, що зловмисники намагаються вгадати ім'я користувача та пароль.
+
+Вони надсилають запит з ім'ям користувача `johndoe` та паролем `love123`.
+
+Тоді Python-код у вашому застосунку буде еквівалентний чомусь на кшталт:
+
+```Python
+if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Але в той момент, коли Python порівнює першу `j` у `johndoe` з першою `s` у `stanleyjobson`, він поверне `False`, тому що вже знає, що ці дві строки не однакові, «немає сенсу витрачати обчислення на порівняння решти літер». І ваш застосунок скаже «Невірні ім'я користувача або пароль».
+
+А потім зловмисники спробують з ім'ям користувача `stanleyjobsox` і паролем `love123`.
+
+І ваш код застосунку зробить щось на кшталт:
+
+```Python
+if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Python доведеться порівняти весь `stanleyjobso` у обох `stanleyjobsox` і `stanleyjobson`, перш ніж зрозуміти, що строки різні. Тому відповідь «Невірні ім'я користувача або пароль» займе на кілька мікросекунд довше.
+
+#### Час відповіді допомагає зловмисникам { #the-time-to-answer-helps-the-attackers }
+
+У цей момент, помітивши, що сервер витратив на кілька мікросекунд більше, щоб надіслати відповідь «Невірні ім'я користувача або пароль», зловмисники знатимуть, що вони щось вгадали, деякі початкові літери правильні.
+
+І тоді вони можуть спробувати знову, знаючи, що це, ймовірно, щось більш схоже на `stanleyjobsox`, ніж на `johndoe`.
+
+#### «Професійна» атака { #a-professional-attack }
+
+Звісно, зловмисники не робитимуть усе це вручну, вони напишуть програму, можливо з тисячами або мільйонами перевірок за секунду. І вони отримуватимуть лише по одній правильній літері за раз.
+
+Але так за кілька хвилин або годин зловмисники вгадають правильні ім'я користувача та пароль, «за допомогою» нашого застосунку, просто використовуючи час, потрібний для відповіді.
+
+#### Виправте за допомогою `secrets.compare_digest()` { #fix-it-with-secrets-compare-digest }
+
+Але в нашому коді ми насправді використовуємо `secrets.compare_digest()`.
+
+Коротко, він витрачає однаковий час на порівняння `stanleyjobsox` зі `stanleyjobson`, як і на порівняння `johndoe` зі `stanleyjobson`. І так само для пароля.
+
+Таким чином, використовуючи `secrets.compare_digest()` у коді вашого застосунку, він буде захищений від усього цього класу атак безпеки.
+
+### Поверніть помилку { #return-the-error }
+
+Після виявлення, що облікові дані неправильні, поверніть `HTTPException` з кодом статусу 401 (такий самий повертається, коли облікові дані не надані) і додайте заголовок `WWW-Authenticate`, щоб браузер знову показав підсказку входу:
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[26:30] *}
diff --git a/docs/uk/docs/advanced/security/index.md b/docs/uk/docs/advanced/security/index.md
new file mode 100644
index 0000000000000..2c00d68a19b47
--- /dev/null
+++ b/docs/uk/docs/advanced/security/index.md
@@ -0,0 +1,19 @@
+# Просунута безпека { #advanced-security }
+
+## Додаткові можливості { #additional-features }
+
+Є кілька додаткових можливостей для роботи з безпекою, окрім тих, що розглянуті в [Навчальний посібник - Посібник користувача: Безпека](../../tutorial/security/index.md).
+
+/// tip | Порада
+
+Наступні розділи **не обов'язково «просунуті»**.
+
+І можливо, що для вашого випадку використання рішення є в одному з них.
+
+///
+
+## Спершу прочитайте навчальний посібник { #read-the-tutorial-first }
+
+У наступних розділах передбачається, що ви вже прочитали основний [Навчальний посібник - Посібник користувача: Безпека](../../tutorial/security/index.md).
+
+Усі вони базуються на тих самих концепціях, але надають деякі додаткові можливості.
diff --git a/docs/uk/docs/advanced/security/oauth2-scopes.md b/docs/uk/docs/advanced/security/oauth2-scopes.md
new file mode 100644
index 0000000000000..7f5ba9692696f
--- /dev/null
+++ b/docs/uk/docs/advanced/security/oauth2-scopes.md
@@ -0,0 +1,274 @@
+# OAuth2 scopes { #oauth2-scopes }
+
+Ви можете використовувати OAuth2 scopes безпосередньо з **FastAPI**, вони інтегровані для безшовної роботи.
+
+Це дозволить мати більш детальну систему дозволів, відповідно до стандарту OAuth2, інтегровану у ваш застосунок OpenAPI (і документацію API).
+
+OAuth2 зі scopes - це механізм, який використовують багато великих провайдерів автентифікації, як-от Facebook, Google, GitHub, Microsoft, X (Twitter) тощо. Вони застосовують його, щоб надавати конкретні дозволи користувачам і застосункам.
+
+Кожного разу, коли ви «log in with» Facebook, Google, GitHub, Microsoft, X (Twitter), цей застосунок використовує OAuth2 зі scopes.
+
+У цьому розділі ви побачите, як керувати автентифікацією та авторизацією за допомогою того ж OAuth2 зі scopes у вашому застосунку **FastAPI**.
+
+/// warning | Попередження
+
+Це більш-менш просунутий розділ. Якщо ви тільки починаєте, можете пропустити його.
+
+Вам не обов’язково потрібні OAuth2 scopes, ви можете керувати автентифікацією та авторизацією будь-яким зручним способом.
+
+Але OAuth2 зі scopes можна гарно інтегрувати у ваш API (з OpenAPI) і документацію API.
+
+Водночас ви все одно примушуєте виконувати ці scopes або будь-які інші вимоги безпеки/авторизації так, як потрібно, у своєму коді.
+
+У багатьох випадках OAuth2 зі scopes - це надмірність.
+
+Але якщо ви знаєте, що це потрібно, або просто цікаво, читайте далі.
+
+///
+
+## OAuth2 scopes та OpenAPI { #oauth2-scopes-and-openapi }
+
+Специфікація OAuth2 визначає «scopes» як список строк, розділених пробілами.
+
+Вміст кожної з цих строк може мати будь-який формат, але не повинен містити пробілів.
+
+Ці scopes представляють «дозволи».
+
+В OpenAPI (наприклад, у документації API) ви можете визначати «схеми безпеки».
+
+Коли одна з цих схем безпеки використовує OAuth2, ви також можете оголошувати та використовувати scopes.
+
+Кожен «scope» - це просто строка (без пробілів).
+
+Зазвичай їх використовують для оголошення конкретних дозволів безпеки, наприклад:
+
+- `users:read` або `users:write` - поширені приклади.
+- `instagram_basic` використовується Facebook / Instagram.
+- `https://www.googleapis.com/auth/drive` використовується Google.
+
+/// info | Інформація
+
+В OAuth2 «scope» - це просто строка, що декларує конкретний потрібний дозвіл.
+
+Не має значення, чи містить вона інші символи на кшталт `:` або чи це URL.
+
+Ці деталі специфічні для реалізації.
+
+Для OAuth2 це просто строки.
+
+///
+
+## Загальний огляд { #global-view }
+
+Спочатку швидко подивімося на частини, що відрізняються від прикладів у головному **Навчальному посібнику - Керівництві користувача** для [OAuth2 з паролем (і хешуванням), Bearer з JWT-токенами](../../tutorial/security/oauth2-jwt.md). Тепер із використанням OAuth2 scopes:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}
+
+Тепер розгляньмо ці зміни крок за кроком.
+
+## Схема безпеки OAuth2 { #oauth2-security-scheme }
+
+Перша зміна - тепер ми оголошуємо схему безпеки OAuth2 з двома доступними scopes: `me` і `items`.
+
+Параметр `scopes` приймає `dict`, де кожен scope - це ключ, а опис - значення:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *}
+
+Оскільки тепер ми оголошуємо ці scopes, вони з’являться в документації API, коли ви увійдете/авторизуєтеся.
+
+І ви зможете обрати, які scopes надати доступ: `me` і `items`.
+
+Це той самий механізм, який використовується, коли ви надаєте дозволи під час входу через Facebook, Google, GitHub тощо:
+
+
+
+## JWT токен зі scopes { #jwt-token-with-scopes }
+
+Тепер змініть операцію шляху токена, щоб повертати запитані scopes.
+
+Ми все ще використовуємо той самий `OAuth2PasswordRequestForm`. Він містить властивість `scopes` зі `list` з `str`, по одному scope, отриманому в запиті.
+
+І ми повертаємо scopes як частину JWT токена.
+
+/// danger | Обережно
+
+Для простоти тут ми просто додаємо отримані scopes безпосередньо до токена.
+
+Але у вашому застосунку, з міркувань безпеки, переконайтеся, що ви додаєте лише ті scopes, які користувач дійсно може мати, або ті, що ви попередньо визначили.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}
+
+## Оголосіть scopes в операціях шляху та залежностях { #declare-scopes-in-path-operations-and-dependencies }
+
+Тепер ми оголошуємо, що операція шляху для `/users/me/items/` вимагає scope `items`.
+
+Для цього імпортуємо і використовуємо `Security` з `fastapi`.
+
+Ви можете використовувати `Security` для оголошення залежностей (так само як `Depends`), але `Security` також приймає параметр `scopes` зі списком scopes (строк).
+
+У цьому випадку ми передаємо функцію-залежність `get_current_active_user` до `Security` (так само, як зробили б із `Depends`).
+
+А також передаємо `list` scopes, у цьому випадку лише один scope: `items` (їх могло б бути більше).
+
+І функція-залежність `get_current_active_user` також може оголошувати підзалежності не лише з `Depends`, а й з `Security`. Оголошуючи свою підзалежність (`get_current_user`) і додаткові вимоги до scopes.
+
+У цьому випадку вона вимагає scope `me` (вона могла б вимагати більш ніж один scope).
+
+/// note | Примітка
+
+Вам не обов’язково додавати різні scopes у різних місцях.
+
+Ми робимо це тут, щоб показати, як **FastAPI** обробляє scopes, оголошені на різних рівнях.
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}
+
+/// info | Технічні деталі
+
+`Security` насправді є підкласом `Depends`, і має лише один додатковий параметр, який ми побачимо пізніше.
+
+Але використовуючи `Security` замість `Depends`, **FastAPI** знатиме, що можна оголошувати scopes безпеки, використовувати їх внутрішньо та документувати API через OpenAPI.
+
+Коли ви імпортуєте `Query`, `Path`, `Depends`, `Security` та інші з `fastapi`, це насправді функції, що повертають спеціальні класи.
+
+///
+
+## Використовуйте `SecurityScopes` { #use-securityscopes }
+
+Тепер оновіть залежність `get_current_user`.
+
+Вона використовується наведеними вище залежностями.
+
+Тут ми використовуємо ту саму схему OAuth2, створену раніше, оголошуючи її як залежність: `oauth2_scheme`.
+
+Оскільки ця функція-залежність не має власних вимог до scopes, ми можемо використовувати `Depends` з `oauth2_scheme`, немає потреби застосовувати `Security`, коли не потрібно вказувати scopes безпеки.
+
+Ми також оголошуємо спеціальний параметр типу `SecurityScopes`, імпортований з `fastapi.security`.
+
+Клас `SecurityScopes` подібний до `Request` (у `Request` ми напряму отримували об’єкт запиту).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}
+
+## Використовуйте scopes { #use-the-scopes }
+
+Параметр `security_scopes` матиме тип `SecurityScopes`.
+
+Він матиме властивість `scopes` зі списком, що містить усі scopes, потрібні самій функції та всім залежним, які використовують її як підзалежність. Тобто всім «залежним»... це може звучати заплутано, нижче пояснено ще раз.
+
+Об’єкт `security_scopes` (класу `SecurityScopes`) також надає атрибут `scope_str` з одним рядком, що містить ці scopes, розділені пробілами (ми його використаємо).
+
+Ми створюємо `HTTPException`, який зможемо повторно використати (`raise`) у кількох місцях.
+
+У цьому винятку ми включаємо потрібні scopes (якщо є) як строку, розділену пробілами (використовуючи `scope_str`). Ми поміщаємо цю строку зі scopes в заголовок `WWW-Authenticate` (це частина специфікації).
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}
+
+## Перевірте `username` і структуру даних { #verify-the-username-and-data-shape }
+
+Ми перевіряємо, що отримали `username`, і видобуваємо scopes.
+
+Потім валідовуємо ці дані за допомогою Pydantic-моделі (перехоплюючи виняток `ValidationError`), і якщо виникає помилка читання JWT токена або валідації даних Pydantic, підіймаємо раніше створений `HTTPException`.
+
+Для цього ми оновлюємо Pydantic-модель `TokenData` новою властивістю `scopes`.
+
+Валідувавши дані через Pydantic, ми гарантуємо, що, наприклад, маємо саме `list` із `str` для scopes і `str` для `username`.
+
+Замість, наприклад, `dict` або чогось іншого, що може зламати застосунок далі, створивши ризик безпеки.
+
+Ми також перевіряємо, що існує користувач із цим username, інакше підіймаємо той самий виняток.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}
+
+## Перевірте `scopes` { #verify-the-scopes }
+
+Тепер перевіряємо, що всі потрібні scopes - для цієї залежності та всіх залежних (включно з операціями шляху) - містяться в scopes, наданих у отриманому токені, інакше підіймаємо `HTTPException`.
+
+Для цього використовуємо `security_scopes.scopes`, що містить `list` із усіма цими scopes як `str`.
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}
+
+## Дерево залежностей і scopes { #dependency-tree-and-scopes }
+
+Ще раз розгляньмо дерево залежностей і scopes.
+
+Оскільки залежність `get_current_active_user` має підзалежність `get_current_user`, scope «me», оголошений у `get_current_active_user`, буде включений до списку потрібних scopes у `security_scopes.scopes`, переданого до `get_current_user`.
+
+Сама операція шляху також оголошує scope «items», отже він також буде у списку `security_scopes.scopes`, переданому до `get_current_user`.
+
+Ось як виглядає ієрархія залежностей і scopes:
+
+- Операція шляху `read_own_items` має:
+ - Потрібні scopes `["items"]` із залежністю:
+ - `get_current_active_user`:
+ - Функція-залежність `get_current_active_user` має:
+ - Потрібні scopes `["me"]` із залежністю:
+ - `get_current_user`:
+ - Функція-залежність `get_current_user` має:
+ - Власних scopes не потребує.
+ - Залежність, що використовує `oauth2_scheme`.
+ - Параметр `security_scopes` типу `SecurityScopes`:
+ - Цей параметр `security_scopes` має властивість `scopes` із `list`, що містить усі наведені вище scopes, отже:
+ - `security_scopes.scopes` міститиме `["me", "items"]` для операції шляху `read_own_items`.
+ - `security_scopes.scopes` міститиме `["me"]` для операції шляху `read_users_me`, адже він оголошений у залежності `get_current_active_user`.
+ - `security_scopes.scopes` міститиме `[]` (нічого) для операції шляху `read_system_status`, бо вона не оголошує жодного `Security` зі `scopes`, і її залежність `get_current_user` також не оголошує жодних `scopes`.
+
+/// tip | Порада
+
+Важливе і «магічне» тут у тому, що `get_current_user` матиме різні списки `scopes` для перевірки для кожної операції шляху.
+
+Усе залежить від `scopes`, оголошених у кожній операції шляху та кожній залежності в дереві залежностей для конкретної операції шляху.
+
+///
+
+## Більше деталей про `SecurityScopes` { #more-details-about-securityscopes }
+
+Ви можете використовувати `SecurityScopes` у будь-якому місці й у кількох місцях, він не обов’язково має бути в «кореневій» залежності.
+
+Він завжди міститиме scopes безпеки, оголошені в поточних залежностях `Security` і всіх залежних для **цієї конкретної** операції шляху і **цього конкретного** дерева залежностей.
+
+Оскільки `SecurityScopes` міститиме всі scopes, оголошені залежними, ви можете використовувати його, щоб перевірити, що токен має потрібні scopes, у центральній функції-залежності, а потім оголошувати різні вимоги до scopes у різних операціях шляху.
+
+Вони перевірятимуться незалежно для кожної операції шляху.
+
+## Перевірте { #check-it }
+
+Якщо ви відкриєте документацію API, ви зможете автентифікуватися і вказати, які scopes хочете авторизувати.
+
+
+
+Якщо ви не оберете жодного scope, ви будете «автентифіковані», але при спробі доступу до `/users/me/` або `/users/me/items/` отримаєте помилку про недостатні дозволи. Ви все ще матимете доступ до `/status/`.
+
+Якщо оберете scope `me`, але не scope `items`, ви зможете отримати доступ до `/users/me/`, але не до `/users/me/items/`.
+
+Так станеться зі стороннім застосунком, який спробує звернутися до однієї з цих операцій шляху з токеном, наданим користувачем, залежно від того, скільки дозволів користувач надав застосунку.
+
+## Про сторонні інтеграції { #about-third-party-integrations }
+
+У цьому прикладі ми використовуємо «потік паролю» OAuth2.
+
+Це доречно, коли ми входимо у власний застосунок, ймовірно, з власним фронтендом.
+
+Адже ми можемо довіряти йому отримання `username` і `password`, бо ми його контролюємо.
+
+Але якщо ви створюєте OAuth2-застосунок, до якого підключатимуться інші (тобто якщо ви створюєте провайдера автентифікації на кшталт Facebook, Google, GitHub тощо), слід використовувати один з інших потоків.
+
+Найпоширеніший - неявний потік (implicit flow).
+
+Найбезпечніший - потік коду (code flow), але його складніше реалізувати, оскільки він потребує більше кроків. Через складність багато провайдерів у підсумку радять неявний потік.
+
+/// note | Примітка
+
+Часто кожен провайдер автентифікації називає свої потоки по-різному, роблячи це частиною свого бренду.
+
+Але зрештою вони реалізують той самий стандарт OAuth2.
+
+///
+
+**FastAPI** містить утиліти для всіх цих потоків автентифікації OAuth2 у `fastapi.security.oauth2`.
+
+## `Security` у параметрі декоратора `dependencies` { #security-in-decorator-dependencies }
+
+Так само як ви можете визначити `list` із `Depends` у параметрі `dependencies` декоратора (як пояснено в [Залежності в декораторах операцій шляху](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md)), ви також можете використовувати там `Security` зі `scopes`.
diff --git a/docs/uk/docs/advanced/settings.md b/docs/uk/docs/advanced/settings.md
new file mode 100644
index 0000000000000..b369e2f12026b
--- /dev/null
+++ b/docs/uk/docs/advanced/settings.md
@@ -0,0 +1,302 @@
+# Налаштування та змінні оточення { #settings-and-environment-variables }
+
+У багатьох випадках вашому застосунку можуть знадобитися зовнішні налаштування або конфігурації, наприклад секретні ключі, облікові дані бази даних, облікові дані для email-сервісів тощо.
+
+Більшість із цих налаштувань змінні (можуть змінюватися), як-от URL-адреси баз даних. І багато з них можуть бути чутливими, як-от секрети.
+
+З цієї причини поширено надавати їх у змінних оточення, які зчитуються застосунком.
+
+/// tip | Порада
+
+Щоб зрозуміти змінні оточення, ви можете прочитати [Змінні оточення](../environment-variables.md).
+
+///
+
+## Типи та перевірка { #types-and-validation }
+
+Ці змінні оточення можуть містити лише текстові строки, оскільки вони зовнішні до Python і мають бути сумісні з іншими програмами та рештою системи (і навіть з різними операційними системами, як-от Linux, Windows, macOS).
+
+Це означає, що будь-яке значення, прочитане в Python зі змінної оточення, буде `str`, і будь-яке перетворення в інший тип або будь-яка перевірка мають виконуватися в коді.
+
+## Pydantic `Settings` { #pydantic-settings }
+
+На щастя, Pydantic надає чудовий інструмент для обробки цих налаштувань із змінних оточення - [Pydantic: Settings management](https://docs.pydantic.dev/latest/concepts/pydantic_settings/).
+
+### Встановіть `pydantic-settings` { #install-pydantic-settings }
+
+Спершу переконайтеся, що ви створили [віртуальне оточення](../virtual-environments.md), активували його, а потім встановили пакет `pydantic-settings`:
+
+
+
+А потім відкрийте документацію для підзастосунку за адресою [http://127.0.0.1:8000/subapi/docs](http://127.0.0.1:8000/subapi/docs).
+
+Ви побачите автоматичну документацію API для підзастосунку, що містить лише його власні _операції шляху_, усі з правильним префіксом підшляху `/subapi`:
+
+
+
+Якщо ви спробуєте взаємодіяти з будь-яким із двох інтерфейсів користувача, вони працюватимуть коректно, адже браузер зможе спілкуватися з кожним конкретним застосунком або підзастосунком.
+
+### Технічні деталі: `root_path` { #technical-details-root-path }
+
+Коли ви монтуєте підзастосунок, як описано вище, FastAPI подбає про передачу шляху монтування для підзастосунку, використовуючи механізм зі специфікації ASGI під назвою `root_path`.
+
+Таким чином підзастосунок знатиме, що слід використовувати цей префікс шляху для інтерфейсу документації.
+
+Підзастосунок також може мати власні змонтовані підзастосунки, і все працюватиме коректно, оскільки FastAPI автоматично обробляє всі ці `root_path`.
+
+Ви дізнаєтеся більше про `root_path` і як використовувати його явно в розділі [За представником](behind-a-proxy.md).
diff --git a/docs/uk/docs/advanced/templates.md b/docs/uk/docs/advanced/templates.md
new file mode 100644
index 0000000000000..3d9f96e72f86c
--- /dev/null
+++ b/docs/uk/docs/advanced/templates.md
@@ -0,0 +1,126 @@
+# Шаблони { #templates }
+
+Ви можете використовувати будь-який рушій шаблонів з **FastAPI**.
+
+Поширений вибір - Jinja2, той самий, що використовується у Flask та інших інструментах.
+
+Є утиліти для простої конфігурації, які ви можете використовувати безпосередньо у вашому застосунку **FastAPI** (надає Starlette).
+
+## Встановіть залежності { #install-dependencies }
+
+Переконайтеся, що ви створили [віртуальне оточення](../virtual-environments.md), активували його та встановили `jinja2`:
+
+
+
+Ви можете вводити повідомлення у поле вводу та надсилати їх:
+
+
+
+І ваш застосунок **FastAPI** з WebSockets відповість:
+
+
+
+Ви можете надсилати (і отримувати) багато повідомлень:
+
+
+
+І всі вони використовуватимуть те саме з'єднання WebSocket.
+
+## Використання `Depends` та іншого { #using-depends-and-others }
+
+У кінцевих точках WebSocket ви можете імпортувати з `fastapi` і використовувати:
+
+* `Depends`
+* `Security`
+* `Cookie`
+* `Header`
+* `Path`
+* `Query`
+
+Вони працюють так само, як для інших ендпойнтів FastAPI/*операцій шляху*:
+
+{* ../../docs_src/websockets_/tutorial002_an_py310.py hl[68:69,82] *}
+
+/// info
+
+Оскільки це WebSocket, не має сенсу піднімати `HTTPException`, натомість ми піднімаємо `WebSocketException`.
+
+Ви можете використати код закриття з [чинних кодів, визначених у специфікації](https://tools.ietf.org/html/rfc6455#section-7.4.1).
+
+///
+
+### Спробуйте WebSockets із залежностями { #try-the-websockets-with-dependencies }
+
+Запустіть ваш застосунок:
+
+
+
+## Обробка відключень і кількох клієнтів { #handling-disconnections-and-multiple-clients }
+
+Коли з'єднання WebSocket закривається, `await websocket.receive_text()` підніме виняток `WebSocketDisconnect`, який ви можете перехопити й обробити, як у цьому прикладі.
+
+{* ../../docs_src/websockets_/tutorial003_py310.py hl[79:81] *}
+
+Щоб спробувати:
+
+* Відкрийте застосунок у кількох вкладках браузера.
+* Надсилайте з них повідомлення.
+* Потім закрийте одну з вкладок.
+
+Це підніме виняток `WebSocketDisconnect`, і всі інші клієнти отримають повідомлення на кшталт:
+
+```
+Client #1596980209979 left the chat
+```
+
+/// tip
+
+Застосунок вище - це мінімальний і простий приклад, що демонструє, як обробляти та розсилати повідомлення кільком з'єднанням WebSocket.
+
+Але майте на увазі, що оскільки все обробляється в пам'яті, в одному списку, це працюватиме лише поки процес запущений, і лише з одним процесом.
+
+Якщо вам потрібне щось просте для інтеграції з FastAPI, але більш надійне, з підтримкою Redis, PostgreSQL чи інших, перегляньте [encode/broadcaster](https://github.com/encode/broadcaster).
+
+///
+
+## Детальніше { #more-info }
+
+Щоб дізнатися більше про можливості, перегляньте документацію Starlette:
+
+* [Клас `WebSocket`](https://www.starlette.dev/websockets/).
+* [Обробка WebSocket на основі класів](https://www.starlette.dev/endpoints/#websocketendpoint).
diff --git a/docs/uk/docs/advanced/wsgi.md b/docs/uk/docs/advanced/wsgi.md
new file mode 100644
index 0000000000000..84d4aa46099ab
--- /dev/null
+++ b/docs/uk/docs/advanced/wsgi.md
@@ -0,0 +1,51 @@
+# Підключення WSGI - Flask, Django та інші { #including-wsgi-flask-django-others }
+
+Ви можете монтувати застосунки WSGI, як ви бачили в [Підзастосунки - монтування](sub-applications.md), [За представником](behind-a-proxy.md).
+
+Для цього ви можете використати `WSGIMiddleware` і обгорнути ним ваш застосунок WSGI, наприклад Flask, Django тощо.
+
+## Використання `WSGIMiddleware` { #using-wsgimiddleware }
+
+/// info | Інформація
+
+Для цього потрібно встановити `a2wsgi`, наприклад за допомогою `pip install a2wsgi`.
+
+///
+
+Потрібно імпортувати `WSGIMiddleware` з `a2wsgi`.
+
+Потім обгорніть застосунок WSGI (напр., Flask) цим проміжним програмним забезпеченням.
+
+І змонтуйте його під певним шляхом.
+
+{* ../../docs_src/wsgi/tutorial001_py310.py hl[1,3,23] *}
+
+/// note | Примітка
+
+Раніше рекомендувалося використовувати `WSGIMiddleware` з `fastapi.middleware.wsgi`, але тепер його визнано застарілим.
+
+Замість цього радимо використовувати пакет `a2wsgi`. Використання залишається таким самим.
+
+Просто переконайтеся, що у вас встановлено пакет `a2wsgi`, і імпортуйте `WSGIMiddleware` коректно з `a2wsgi`.
+
+///
+
+## Перевірте { #check-it }
+
+Тепер кожен запит за шляхом `/v1/` оброблятиметься застосунком Flask.
+
+А решта - **FastAPI**.
+
+Якщо ви запустите це й перейдете на [http://localhost:8000/v1/](http://localhost:8000/v1/), ви побачите відповідь від Flask:
+
+```txt
+Hello, World from Flask!
+```
+
+А якщо ви перейдете на [http://localhost:8000/v2](http://localhost:8000/v2), ви побачите відповідь від FastAPI:
+
+```JSON
+{
+ "message": "Hello World"
+}
+```
diff --git a/docs/uk/docs/alternatives.md b/docs/uk/docs/alternatives.md
index e712579769906..1e9d479da1067 100644
--- a/docs/uk/docs/alternatives.md
+++ b/docs/uk/docs/alternatives.md
@@ -1,8 +1,8 @@
-# Альтернативи, натхнення та порівняння
+# Альтернативи, натхнення та порівняння { #alternatives-inspiration-and-comparisons }
-Що надихнуло на створення **FastAPI**, який він у порінянні з іншими альтернативами та чого він у них навчився.
+Що надихнуло **FastAPI**, як він порівнюється з альтернативами та чого він у них навчився.
-## Вступ
+## Вступ { #intro }
**FastAPI** не існувало б, якби не попередні роботи інших.
@@ -12,17 +12,17 @@
Але в якийсь момент не було іншого виходу, окрім створення чогось, що надавало б усі ці функції, взявши найкращі ідеї з попередніх інструментів і поєднавши їх найкращим чином, використовуючи мовні функції, які навіть не були доступні раніше (Python 3.6+ підказки типів).
-## Попередні інструменти
+## Попередні інструменти { #previous-tools }
-### Django
+### [Django](https://www.djangoproject.com/) { #django }
Це найпопулярніший фреймворк Python, який користується широкою довірою. Він використовується для створення таких систем, як Instagram.
Він відносно тісно пов’язаний з реляційними базами даних (наприклад, MySQL або PostgreSQL), тому мати базу даних NoSQL (наприклад, Couchbase, MongoDB, Cassandra тощо) як основний механізм зберігання не дуже просто.
-Він був створений для створення HTML у серверній частині, а не для створення API, які використовуються сучасним інтерфейсом (як-от React, Vue.js і Angular) або іншими системами (як-от IoT пристрої), які спілкуються з ним.
+Він був створений для створення HTML у серверній частині, а не для створення API, які використовуються сучасним інтерфейсом (як-от React, Vue.js і Angular) або іншими системами (як-от IoT пристрої), які спілкуються з ним.
-### Django REST Framework
+### [Django REST Framework](https://www.django-rest-framework.org/) { #django-rest-framework }
Фреймворк Django REST був створений як гнучкий інструментарій для створення веб-інтерфейсів API використовуючи Django в основі, щоб покращити його можливості API.
@@ -30,14 +30,19 @@
Це був один із перших прикладів **автоматичної документації API**, і саме це була одна з перших ідей, яка надихнула на «пошук» **FastAPI**.
-!!! Примітка
- Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**.
+/// note | Примітка
+Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**.
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Мати автоматичний веб-інтерфейс документації API.
+///
-### Flask
+/// check | Надихнуло **FastAPI** на
+
+Мати автоматичний веб-інтерфейс документації API.
+
+///
+
+### [Flask](https://flask.palletsprojects.com) { #flask }
Flask — це «мікрофреймворк», він не включає інтеграцію бази даних, а також багато речей, які за замовчуванням є в Django.
@@ -51,13 +56,15 @@ Flask — це «мікрофреймворк», він не включає ін
Враховуючи простоту Flask, він здавався хорошим підходом для створення API. Наступним, що знайшов, був «Django REST Framework» для Flask.
-!!! Переглянте "Надихнуло **FastAPI** на"
- Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин.
+/// check | Надихнуло **FastAPI** на
- Мати просту та легку у використанні систему маршрутизації.
+Бути мікрофреймворком. Зробити легким комбінування та поєднання необхідних інструментів та частин.
+Мати просту та легку у використанні систему маршрутизації.
-### Requests
+///
+
+### [Requests](https://requests.readthedocs.io) { #requests }
**FastAPI** насправді не є альтернативою **Requests**. Сфера їх застосування дуже різна.
@@ -81,23 +88,25 @@ Requests мають дуже простий та інтуїтивно зрозу
response = requests.get("http://example.com/some/url")
```
-Відповідна операція *роуту* API FastAPI може виглядати так:
+Відповідна операція шляху API FastAPI може виглядати так:
```Python hl_lines="1"
@app.get("/some/url")
def read_url():
- return {"message": "Hello World"}
+ return {"message": "Hello World"}
```
Зверніть увагу на схожість у `requests.get(...)` і `@app.get(...)`.
-!!! Перегляньте "Надихнуло **FastAPI** на"
- * Майте простий та інтуїтивно зрозумілий API.
- * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом.
- * Розумні параметри за замовчуванням, але потужні налаштування.
+/// check | Надихнуло **FastAPI** на
+
+* Мати простий та інтуїтивно зрозумілий API.
+* Використовувати імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом.
+* Мати розумні параметри за замовчуванням, але потужні налаштування.
+///
-### Swagger / OpenAPI
+### [Swagger](https://swagger.io/) / [OpenAPI](https://github.com/OAI/OpenAPI-Specification/) { #swagger-openapi }
Головною функцією, яку я хотів від Django REST Framework, була автоматична API документація.
@@ -109,23 +118,26 @@ def read_url():
Тому, коли говорять про версію 2.0, прийнято говорити «Swagger», а про версію 3+ «OpenAPI».
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми.
+/// check | Надихнуло **FastAPI** на
+
+Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми.
- Інтегрувати інструменти інтерфейсу на основі стандартів:
+Інтегрувати інструменти інтерфейсу на основі стандартів:
- * Інтерфейс Swagger
- * ReDoc
+* [Інтерфейс Swagger](https://github.com/swagger-api/swagger-ui)
+* [ReDoc](https://github.com/Rebilly/ReDoc)
- Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**).
+Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**).
-### Фреймворки REST для Flask
+///
+
+### Фреймворки REST для Flask { #flask-rest-frameworks }
Існує кілька фреймворків Flask REST, але, витративши час і роботу на їх дослідження, я виявив, що багато з них припинено або залишено, з кількома постійними проблемами, які зробили їх непридатними.
-### Marshmallow
+### [Marshmallow](https://marshmallow.readthedocs.io/en/stable/) { #marshmallow }
-Однією з головних функцій, необхідних для систем API, є "серіалізація", яка бере дані з коду (Python) і перетворює їх на щось, що можна надіслати через мережу. Наприклад, перетворення об’єкта, що містить дані з бази даних, на об’єкт JSON. Перетворення об’єктів `datetime` на строки тощо.
+Однією з головних функцій, необхідних для систем API, є «серіалізація», яка бере дані з коду (Python) і перетворює їх на щось, що можна надіслати через мережу. Наприклад, перетворення об’єкта, що містить дані з бази даних, на об’єкт JSON. Перетворення об’єктів `datetime` на строки тощо.
Іншою важливою функцією, необхідною для API, є перевірка даних, яка забезпечує дійсність даних за певними параметрами. Наприклад, що деяке поле є `int`, а не деяка випадкова строка. Це особливо корисно для вхідних даних.
@@ -133,14 +145,17 @@ def read_url():
Marshmallow створено для забезпечення цих функцій. Це чудова бібліотека, і я часто нею користувався раніше.
-Але він був створений до того, як існували підказки типу Python. Отже, щоб визначити кожну схему, вам потрібно використовувати спеціальні утиліти та класи, надані Marshmallow.
+Але він був створений до того, як існували підказки типу Python. Отже, щоб визначити кожну схему, вам потрібно використовувати спеціальні утиліти та класи, надані Marshmallow.
+
+/// check | Надихнуло **FastAPI** на
+
+Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку.
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку.
+///
-### Webargs
+### [Webargs](https://webargs.readthedocs.io/en/latest/) { #webargs }
-Іншою важливою функцією, необхідною для API, є аналіз даних із вхідних запитів.
+Іншою важливою функцією, необхідною для API, є аналіз даних із вхідних запитів.
Webargs — це інструмент, створений, щоб забезпечити це поверх кількох фреймворків, включаючи Flask.
@@ -148,13 +163,19 @@ Webargs — це інструмент, створений, щоб забезпе
Це чудовий інструмент, і я також часто використовував його, перш ніж створити **FastAPI**.
-!!! Інформація
- Webargs був створений тими ж розробниками Marshmallow.
+/// info | Інформація
+
+Webargs був створений тими ж розробниками Marshmallow.
+
+///
+
+/// check | Надихнуло **FastAPI** на
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Мати автоматичну перевірку даних вхідного запиту.
+Мати автоматичну перевірку даних вхідного запиту.
-### APISpec
+///
+
+### [APISpec](https://apispec.readthedocs.io/en/stable/) { #apispec }
Marshmallow і Webargs забезпечують перевірку, аналіз і серіалізацію як плагіни.
@@ -172,14 +193,19 @@ Marshmallow і Webargs забезпечують перевірку, аналіз
Редактор тут нічим не може допомогти. І якщо ми змінимо параметри чи схеми Marshmallow і забудемо також змінити цю строку документа YAML, згенерована схема буде застарілою.
-!!! Інформація
- APISpec був створений тими ж розробниками Marshmallow.
+/// info | Інформація
+
+APISpec був створений тими ж розробниками Marshmallow.
+
+///
+/// check | Надихнуло **FastAPI** на
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Підтримувати відкритий стандарт API, OpenAPI.
+Підтримувати відкритий стандарт API, OpenAPI.
-### Flask-apispec
+///
+
+### [Flask-apispec](https://flask-apispec.readthedocs.io/en/latest/) { #flask-apispec }
Це плагін Flask, який об’єднує Webargs, Marshmallow і APISpec.
@@ -191,27 +217,33 @@ Marshmallow і Webargs забезпечують перевірку, аналіз
Ця комбінація Flask, Flask-apispec із Marshmallow і Webargs була моїм улюбленим бекенд-стеком до створення **FastAPI**.
-Їі використання призвело до створення кількох генераторів повного стека Flask. Це основний стек, який я (та кілька зовнішніх команд) використовував досі:
+Її використання призвело до створення кількох генераторів повного стека Flask. Це основний стек, який я (та кілька зовнішніх команд) використовував досі:
+
+* [https://github.com/tiangolo/full-stack](https://github.com/tiangolo/full-stack)
+* [https://github.com/tiangolo/full-stack-flask-couchbase](https://github.com/tiangolo/full-stack-flask-couchbase)
+* [https://github.com/tiangolo/full-stack-flask-couchdb](https://github.com/tiangolo/full-stack-flask-couchdb)
+
+І ці самі генератори повного стеку були основою [**FastAPI** генераторів проектів](project-generation.md).
-* https://github.com/tiangolo/full-stack
-* https://github.com/tiangolo/full-stack-flask-couchbase
-* https://github.com/tiangolo/full-stack-flask-couchdb
+/// info | Інформація
-І ці самі генератори повного стеку були основою [**FastAPI** генераторів проектів](project-generation.md){.internal-link target=_blank}.
+Flask-apispec був створений тими ж розробниками Marshmallow.
-!!! Інформація
- Flask-apispec був створений тими ж розробниками Marshmallow.
+///
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку.
+/// check | Надихнуло **FastAPI** на
-### NestJS (та Angular)
+Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку.
+
+///
+
+### [NestJS](https://nestjs.com/) (та [Angular](https://angular.io/)) { #nestjs-and-angular }
Це навіть не Python, NestJS — це фреймворк NodeJS JavaScript (TypeScript), натхненний Angular.
Це досягає чогось подібного до того, що можна зробити з Flask-apispec.
-Він має інтегровану систему впровадження залежностей, натхненну Angular two. Він потребує попередньої реєстрації «injectables» (як і всі інші системи впровадження залежностей, які я знаю), тому це збільшує багатослівність та повторення коду.
+Він має інтегровану систему впровадження залежностей, натхненну Angular 2. Він потребує попередньої реєстрації «injectables» (як і всі інші системи впровадження залежностей, які я знаю), тому це збільшує багатослівність та повторення коду.
Оскільки параметри описані за допомогою типів TypeScript (подібно до підказок типу Python), підтримка редактора досить хороша.
@@ -219,26 +251,35 @@ Marshmallow і Webargs забезпечують перевірку, аналіз
Він не дуже добре обробляє вкладені моделі. Отже, якщо тіло JSON у запиті є об’єктом JSON із внутрішніми полями, які, у свою чергу, є вкладеними об’єктами JSON, його неможливо належним чином задокументувати та перевірити.
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Використовувати типи Python, щоб мати чудову підтримку редактора.
+/// check | Надихнуло **FastAPI** на
+
+Використовувати типи Python, щоб мати чудову підтримку редактора.
- Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду.
+Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду.
-### Sanic
+///
+
+### [Sanic](https://sanic.readthedocs.io/en/latest/) { #sanic }
Це був один із перших надзвичайно швидких фреймворків Python на основі `asyncio`. Він був дуже схожий на Flask.
-!!! Примітка "Технічні деталі"
- Він використовував `uvloop` замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким.
+/// note | Технічні деталі
+
+Він використовував [`uvloop`](https://github.com/MagicStack/uvloop) замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким.
+
+Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах.
- Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах.
+///
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Знайти спосіб отримати божевільну продуктивність.
+/// check | Надихнуло **FastAPI** на
- Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників).
+Знайти спосіб отримати божевільну продуктивність.
-### Falcon
+Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників).
+
+///
+
+### [Falcon](https://falconframework.org/) { #falcon }
Falcon — ще один високопродуктивний фреймворк Python, він розроблений як мінімальний і працює як основа інших фреймворків, таких як Hug.
@@ -246,14 +287,17 @@ Falcon — ще один високопродуктивний фреймворк
Таким чином, перевірка даних, серіалізація та документація повинні виконуватися в коді, а не автоматично. Або вони повинні бути реалізовані як фреймворк поверх Falcon, як Hug. Така сама відмінність спостерігається в інших фреймворках, натхненних дизайном Falcon, що мають один об’єкт запиту та один об’єкт відповіді як параметри.
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Знайти способи отримати чудову продуктивність.
+/// check | Надихнуло **FastAPI** на
+
+Знайти способи отримати чудову продуктивність.
- Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях.
+Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях.
- Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів стану.
+Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів статусу.
-### Molten
+///
+
+### [Molten](https://moltenframework.com/) { #molten }
Я відкрив для себе Molten на перших етапах створення **FastAPI**. І він має досить схожі ідеї:
@@ -269,12 +313,15 @@ Falcon — ще один високопродуктивний фреймворк
Маршрути оголошуються в одному місці з використанням функцій, оголошених в інших місцях (замість використання декораторів, які можна розмістити безпосередньо поверх функції, яка обробляє кінцеву точку). Це ближче до того, як це робить Django, ніж до Flask (і Starlette). Він розділяє в коді речі, які відносно тісно пов’язані.
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic.
+/// check | Надихнуло **FastAPI** на
+
+Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic.
+
+Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic).
- Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic).
+///
-### Hug
+### [Hug](https://github.com/hugapi/hug) { #hug }
Hug був одним із перших фреймворків, який реалізував оголошення типів параметрів API за допомогою підказок типу Python. Це була чудова ідея, яка надихнула інші інструменти зробити те саме.
@@ -288,17 +335,23 @@ Hug був одним із перших фреймворків, який реа
Оскільки він заснований на попередньому стандарті для синхронних веб-фреймворків Python (WSGI), він не може працювати з Websockets та іншими речами, хоча він також має високу продуктивність.
-!!! Інформація
- Hug створив Тімоті Крослі, той самий творець `isort`, чудовий інструмент для автоматичного сортування імпорту у файлах Python.
+/// info | Інформація
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar.
+Hug створив Тімоті Крослі, той самий творець [`isort`](https://github.com/timothycrosley/isort), чудовий інструмент для автоматичного сортування імпорту у файлах Python.
- Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API.
+///
- Hug надихнув **FastAPI** оголосити параметр `response` у функціях для встановлення заголовків і файлів cookie.
+/// check | Ідеї, що надихнули **FastAPI**
-### APIStar (<= 0,5)
+Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar.
+
+Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API.
+
+Hug надихнув **FastAPI** оголосити параметр `response` у функціях для встановлення заголовків і файлів cookie.
+
+///
+
+### [APIStar](https://github.com/encode/apistar) (<= 0,5) { #apistar-0-5 }
Безпосередньо перед тим, як вирішити створити **FastAPI**, я знайшов сервер **APIStar**. Він мав майже все, що я шукав, і мав чудовий дизайн.
@@ -322,40 +375,51 @@ Hug був одним із перших фреймворків, який реа
Тепер APIStar — це набір інструментів для перевірки специфікацій OpenAPI, а не веб-фреймворк.
-!!! Інформація
- APIStar створив Том Крісті. Той самий хлопець, який створив:
+/// info | Інформація
+
+APIStar створив Том Крісті. Той самий хлопець, який створив:
+
+* Django REST Framework
+* Starlette (на якому базується **FastAPI**)
+* Uvicorn (використовується Starlette і **FastAPI**)
- * Django REST Framework
- * Starlette (на якому базується **FastAPI**)
- * Uvicorn (використовується Starlette і **FastAPI**)
+///
-!!! Перегляньте "Надихнуло **FastAPI** на"
- Існувати.
+/// check | Надихнуло **FastAPI** на
- Ідею оголошення кількох речей (перевірки даних, серіалізації та документації) за допомогою тих самих типів Python, які в той же час забезпечували чудову підтримку редактора, я вважав геніальною ідеєю.
+Існувати.
- І після тривалого пошуку подібної структури та тестування багатьох різних альтернатив, APIStar став найкращим доступним варіантом.
+Ідею оголошення кількох речей (перевірки даних, серіалізації та документації) за допомогою тих самих типів Python, які в той же час забезпечували чудову підтримку редактора, я вважав геніальною ідеєю.
- Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**. Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему введення тексту та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів.
+І після тривалого пошуку подібної структури та тестування багатьох різних альтернатив, APIStar став найкращим доступним варіантом.
-## Використовується **FastAPI**
+Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**.
-### Pydantic
+Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему типізації та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів.
-Pydantic — це бібліотека для визначення перевірки даних, серіалізації та документації (за допомогою схеми JSON) на основі підказок типу Python.
+///
+
+## Використовується **FastAPI** { #used-by-fastapi }
+
+### [Pydantic](https://docs.pydantic.dev/) { #pydantic }
+
+Pydantic — це бібліотека для визначення перевірки даних, серіалізації та документації (за допомогою Схеми JSON) на основі підказок типу Python.
Це робить його надзвичайно інтуїтивним.
Його можна порівняти з Marshmallow. Хоча він швидший за Marshmallow у тестах. Оскільки він базується на тих самих підказках типу Python, підтримка редактора чудова.
-!!! Перегляньте "**FastAPI** використовує його для"
- Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON).
+/// check | **FastAPI** використовує його для
- Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить.
+Виконання перевірки всіх даних, серіалізації даних і автоматичної документації моделі (на основі Схеми JSON).
-### Starlette
+Потім **FastAPI** бере ці дані Схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить.
-Starlette — це легкий фреймворк/набір інструментів ASGI, який ідеально підходить для створення високопродуктивних asyncio сервісів.
+///
+
+### [Starlette](https://www.starlette.dev/) { #starlette }
+
+Starlette — це легкий фреймворк/набір інструментів ASGI, який ідеально підходить для створення високопродуктивних asyncio сервісів.
Він дуже простий та інтуїтивно зрозумілий. Його розроблено таким чином, щоб його можна було легко розширювати та мати модульні компоненти.
@@ -380,19 +444,25 @@ Starlette надає всі основні функції веб-мікрофр
Це одна з головних речей, які **FastAPI** додає зверху, все на основі підказок типу Python (з використанням Pydantic). Це, а також система впровадження залежностей, утиліти безпеки, створення схеми OpenAPI тощо.
-!!! Примітка "Технічні деталі"
- ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього.
+/// note | Технічні деталі
+
+ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього.
- Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`.
+Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`.
-!!! Перегляньте "**FastAPI** використовує його для"
- Керування всіма основними веб-частинами. Додавання функцій зверху.
+///
- Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`.
+/// check | **FastAPI** використовує його для
- Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах.
+Керування всіма основними веб-частинами. Додавання функцій зверху.
-### Uvicorn
+Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`.
+
+Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах.
+
+///
+
+### [Uvicorn](https://www.uvicorn.dev/) { #uvicorn }
Uvicorn — це блискавичний сервер ASGI, побудований на uvloop і httptools.
@@ -400,13 +470,16 @@ Uvicorn — це блискавичний сервер ASGI, побудован
Це рекомендований сервер для Starlette і **FastAPI**.
-!!! Перегляньте "**FastAPI** рекомендує це як"
- Основний веб-сервер для запуску програм **FastAPI**.
+/// check | **FastAPI** рекомендує це як
+
+Основний веб-сервер для запуску програм **FastAPI**.
+
+Ви також можете використати параметр командного рядка `--workers`, щоб мати асинхронний багатопроцесний сервер.
- Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер.
+Додаткову інформацію див. у розділі [Розгортання](deployment/index.md).
- Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}.
+///
-## Орієнтири та швидкість
+## Орієнтири та швидкість { #benchmarks-and-speed }
-Щоб зрозуміти, порівняти та побачити різницю між Uvicorn, Starlette і FastAPI, перегляньте розділ про [Бенчмарки](benchmarks.md){.internal-link target=_blank}.
+Щоб зрозуміти, порівняти та побачити різницю між Uvicorn, Starlette і FastAPI, перегляньте розділ про [Бенчмарки](benchmarks.md).
diff --git a/docs/uk/docs/async.md b/docs/uk/docs/async.md
new file mode 100644
index 0000000000000..95ecec21f1b2d
--- /dev/null
+++ b/docs/uk/docs/async.md
@@ -0,0 +1,444 @@
+# Рівночасність і async / await { #concurrency-and-async-await }
+
+Деталі щодо синтаксису `async def` для функцій операції шляху і деякі відомості про асинхронний код, рівночасність і паралелізм.
+
+## Поспішаєте? { #in-a-hurry }
+
+TL;DR:
+
+Якщо ви використовуєте сторонні бібліотеки, які вимагають виклику з `await`, наприклад:
+
+```Python
+results = await some_library()
+```
+
+Тоді оголошуйте ваші функції операції шляху з `async def`, наприклад:
+
+```Python hl_lines="2"
+@app.get('/')
+async def read_results():
+ results = await some_library()
+ return results
+```
+
+/// note | Примітка
+
+Ви можете використовувати `await` лише всередині функцій, створених з `async def`.
+
+///
+
+---
+
+Якщо ви використовуєте сторонню бібліотеку, яка взаємодіє з чимось (база даних, API, файлова система тощо) і не підтримує використання `await` (наразі це стосується більшості бібліотек баз даних), тоді оголошуйте ваші функції операції шляху як зазвичай, просто з `def`, наприклад:
+
+```Python hl_lines="2"
+@app.get('/')
+def results():
+ results = some_library()
+ return results
+```
+
+---
+
+Якщо ваш застосунок (якимось чином) не має комунікувати з чимось іншим і чекати на відповідь, використовуйте `async def`, навіть якщо вам не потрібно використовувати `await` всередині.
+
+---
+
+Якщо ви не певні, використовуйте звичайний `def`.
+
+---
+
+Примітка: ви можете змішувати `def` і `async def` у ваших функціях операції шляху скільки завгодно і визначати кожну з них найкращим для вас способом. FastAPI зробить з ними все правильно.
+
+У будь-якому з наведених випадків FastAPI все одно працюватиме асинхронно і буде надзвичайно швидким.
+
+Але слідуючи крокам вище, він зможе зробити деякі оптимізації продуктивності.
+
+## Технічні деталі { #technical-details }
+
+Сучасні версії Python мають підтримку «асинхронного коду» за допомогою так званих «співпрограм» з синтаксисом **`async` і `await`**.
+
+Розгляньмо цю фразу по частинах у секціях нижче:
+
+- Асинхронний код
+- `async` і `await`
+- Співпрограми
+
+## Асинхронний код { #asynchronous-code }
+
+Асинхронний код означає, що мова 💬 має спосіб сказати комп’ютеру/програмі 🤖, що в певний момент у коді він 🤖 має почекати, поки «щось інше» завершиться десь ще. Скажімо, це «щось інше» називається «slow-file» 📝.
+
+Отже, в цей час комп’ютер може піти і зробити іншу роботу, доки «slow-file» 📝 завершується.
+
+Далі комп’ютер/програма 🤖 повертатиметься щоразу, коли матиме можливість, бо знову чекає, або коли він 🤖 завершив усю роботу, яка була в нього на той момент. І він 🤖 перевірить, чи якась із задач, на які він чекав, уже завершилася, виконавши все, що потрібно.
+
+Потім він 🤖 бере першу завершену задачу (скажімо, наш «slow-file» 📝) і продовжує робити те, що потрібно було зробити з нею.
+
+Це «чекати на щось інше» зазвичай стосується операцій I/O, які відносно «повільні» (порівняно зі швидкістю процесора та пам’яті з довільним доступом), наприклад, очікування:
+
+- даних від клієнта, що надсилаються мережею
+- даних, надісланих вашим застосунком, які клієнт має отримати мережею
+- вмісту файла на диску, який система має прочитати і передати вашому застосунку
+- вмісту, який ваш застосунок передав системі, щоб він був записаний на диск
+- віддаленої операції API
+- завершення операції бази даних
+- повернення результатів запиту до бази даних
+- тощо
+
+Оскільки час виконання переважно витрачається на очікування операцій I/O, їх називають операціями «I/O bound».
+
+Це називається «асинхронним», тому що комп’ютеру/програмі не потрібно бути «синхронізованими» з повільною задачею, очікуючи точного моменту її завершення, нічого не роблячи, лише щоб отримати результат задачі та продовжити роботу.
+
+Натомість, у «асинхронній» системі щойно завершена задача може трохи зачекати в черзі (кілька мікросекунд), доки комп’ютер/програма завершить те, що пішов робити, а потім повернеться, щоб забрати результати і продовжити роботу з ними.
+
+Для «синхронного» (на противагу «асинхронному») часто також використовують термін «послідовний», бо комп’ютер/програма слідує всім крокам послідовно, перш ніж перемкнутися на іншу задачу, навіть якщо ці кроки включають очікування.
+
+### Рівночасність і бургери { #concurrency-and-burgers }
+
+Ідею **асинхронного** коду, описану вище, інколи також називають **«рівночасністю»**. Вона відрізняється від **«паралелізму»**.
+
+І рівночасність, і паралелізм стосуються «різних речей, що відбуваються більш-менш одночасно».
+
+Але деталі між рівночасністю і паралелізмом досить різні.
+
+Щоб побачити різницю, уявімо таку історію про бургери:
+
+### Рівночасні бургери { #concurrent-burgers }
+
+Ви йдете зі своєю симпатією по фастфуд, стаєте в чергу, доки касир приймає замовлення у людей перед вами. 😍
+
+
+
+Потім ваша черга, ви замовляєте 2 дуже вишукані бургери для вашої симпатії і для себе. 🍔🍔
+
+
+
+Касир каже щось кухарю на кухні, щоб той знав, що треба приготувати ваші бургери (хоча зараз він готує бургери для попередніх клієнтів).
+
+
+
+Ви платите. 💸
+
+Касир дає вам номер вашої черги.
+
+
+
+Поки ви чекаєте, ви з вашою симпатією обираєте столик, сідаєте і довго розмовляєте (адже ваші бургери дуже вишукані і потребують часу на приготування).
+
+Сидячи за столиком із вашою симпатією, доки чекаєте бургери, ви можете витратити цей час, милуючись тим, яка ваша симпатія класна, мила і розумна ✨😍✨.
+
+
+
+Чекаючи і спілкуючись із вашою симпатією, час від часу ви перевіряєте номер на табло біля прилавка, щоб побачити, чи вже ваша черга.
+
+І от нарешті ваша черга. Ви підходите до прилавка, забираєте бургери і повертаєтеся до столика.
+
+
+
+Ви з вашою симпатією їсте бургери і гарно проводите час. ✨
+
+
+
+/// info | Інформація
+
+Прекрасні ілюстрації від [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨
+
+///
+
+---
+
+Уявіть, що в цій історії ви - комп’ютер/програма 🤖.
+
+Поки ви в черзі, ви просто бездіяльні 😴, чекаєте своєї черги, нічого «продуктивного» не роблячи. Але черга рухається швидко, бо касир лише приймає замовлення (а не готує їх), тож це нормально.
+
+Коли ж ваша черга, ви виконуєте справді «продуктивну» роботу: переглядаєте меню, вирішуєте, що бажаєте, дізнаєтеся вибір вашої симпатії, платите, перевіряєте, що віддаєте правильну купюру чи картку, що з вас правильно списали кошти, що замовлення містить правильні позиції тощо.
+
+Але потім, хоча у вас ще немає бургерів, ваша взаємодія з касиром «на паузі» ⏸, бо вам доводиться чекати 🕙, поки бургери будуть готові.
+
+Втім, відійшовши від прилавка і сівши за столик із номерком, ви можете перемкнути 🔀 увагу на свою симпатію і «попрацювати» ⏯ 🤓 над цим. Тоді ви знову робите щось дуже «продуктивне» - фліртуєте зі своєю симпатією 😍.
+
+Потім касир 💁 каже «Я закінчив робити бургери», виводячи ваш номер на табло прилавка, але ви не підстрибуєте миттєво, щойно номер змінюється на ваш. Ви знаєте, що ніхто не вкраде ваші бургери, адже у вас є номер вашої черги, а в інших - свій.
+
+Тож ви чекаєте, поки ваша симпатія завершить історію (завершить поточну роботу ⏯/задачу 🤓), лагідно усміхаєтеся і кажете, що підете за бургерами ⏸.
+
+Потім ви йдете до прилавка 🔀, до початкової задачі, яку тепер завершено ⏯, забираєте бургери, дякуєте і несете їх до столу. Це завершує той крок/задачу взаємодії з прилавком ⏹. Натомість з’являється нова задача «їсти бургери» 🔀 ⏯, але попередня «отримати бургери» завершена ⏹.
+
+### Паралельні бургери { #parallel-burgers }
+
+А тепер уявімо, що це не «рівночасні бургери», а «паралельні бургери».
+
+Ви йдете зі своєю симпатією по паралельний фастфуд.
+
+Ви стаєте в чергу, поки кілька (скажімо, 8) касирів, які водночас є кухарями, приймають замовлення у людей перед вами.
+
+Кожен перед вами чекає, поки його бургери будуть готові, перш ніж відійти від прилавка, тому що кожен з 8 касирів одразу йде і готує бургер, перш ніж приймати наступне замовлення.
+
+
+
+Нарешті ваша черга, ви замовляєте 2 дуже вишукані бургери для вашої симпатії і для себе.
+
+Ви платите 💸.
+
+
+
+Касир іде на кухню.
+
+Ви чекаєте, стоячи перед прилавком 🕙, щоб ніхто інший не забрав ваші бургери раніше, ніж ви, адже номерків черги немає.
+
+
+
+Оскільки ви з вашою симпатією зайняті тим, щоб ніхто не став перед вами і не забрав ваші бургери, щойно вони з’являться, ви не можете приділяти увагу своїй симпатії. 😞
+
+Це «синхронна» робота, ви «синхронізовані» з касиром/кухарем 👨🍳. Вам доводиться чекати 🕙 і бути тут у точний момент, коли касир/кухар 👨🍳 завершить бургери і віддасть їх вам, інакше хтось інший може їх забрати.
+
+
+
+Потім ваш касир/кухар 👨🍳 нарешті повертається з вашими бургерами після довгого очікування 🕙 перед прилавком.
+
+
+
+Ви берете бургери і йдете до столика зі своєю симпатією.
+
+Ви просто їх їсте - і все. ⏹
+
+
+
+Багато розмов чи флірту не було, бо більшість часу пішла на очікування 🕙 перед прилавком. 😞
+
+/// info | Інформація
+
+Прекрасні ілюстрації від [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨
+
+///
+
+---
+
+У цьому сценарії паралельних бургерів ви - комп’ютер/програма 🤖 з двома процесорами (ви і ваша симпатія), які обидва чекають 🕙 і приділяють увагу ⏯ «очікуванню біля прилавка» 🕙 тривалий час.
+
+У закладу фастфуду 8 процесорів (касира/кухаря). У той час як у закладу з рівночасними бургерами могло бути лише 2 (один касир і один кухар).
+
+Та все одно фінальний досвід не найкращий. 😞
+
+---
+
+Це була б паралельна історія про бургери. 🍔
+
+Для більш «реального» прикладу уявіть банк.
+
+До недавнього часу більшість банків мали кілька касирів 👨💼👨💼👨💼👨💼 і велику чергу 🕙🕙🕙🕙🕙🕙🕙🕙.
+
+Усі касири робили всю роботу з одним клієнтом за іншим 👨💼⏯.
+
+І вам доводилося 🕙 довго стояти в черзі, інакше ви втратите свою чергу.
+
+Ви, напевно, не хотіли б брати свою симпатію 😍 із собою у справи до банку 🏦.
+
+### Висновок про бургери { #burger-conclusion }
+
+У цьому сценарії «фастфуд із вашою симпатією», оскільки є багато очікування 🕙, значно доцільніше мати рівночасну систему ⏸🔀⏯.
+
+Так є у більшості вебзастосунків.
+
+Багато-багато користувачів, але ваш сервер чекає 🕙 на їхнє не надто гарне з’єднання, щоб вони надіслали свої запити.
+
+А потім знову чекає 🕙 на повернення відповідей.
+
+Це «очікування» 🕙 вимірюється у мікросекундах, але все ж, у сумі - це багато очікування в підсумку.
+
+Ось чому дуже логічно використовувати асинхронний ⏸🔀⏯ код для веб API.
+
+Такий тип асинхронності зробив NodeJS популярним (хоча NodeJS не є паралельним), і це сила Go як мови програмування.
+
+І такий самий рівень продуктивності ви отримуєте з **FastAPI**.
+
+А оскільки можна мати паралелізм і асинхронність одночасно, ви отримуєте вищу продуктивність, ніж більшість протестованих фреймворків NodeJS, і на рівні з Go, який є компільованою мовою, ближчою до C [(усе завдяки Starlette)](https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=query&l=zijmkf-1).
+
+### Чи краща рівночасність за паралелізм? { #is-concurrency-better-than-parallelism }
+
+Ні! Це не мораль історії.
+
+Рівночасність відрізняється від паралелізму. І вона краща у конкретних сценаріях, що містять багато очікування. Через це зазвичай вона значно краща за паралелізм для розробки вебзастосунків. Але не для всього.
+
+Щоб урівноважити це, уявімо коротку історію:
+
+> Ви маєте прибрати великий брудний будинок.
+
+*Так, це вся історія*.
+
+---
+
+Тут немає очікування 🕙 - просто багато роботи, яку треба зробити, у багатьох місцях будинку.
+
+У вас могли б бути «черги» як у прикладі з бургерами: спочатку вітальня, потім кухня. Але оскільки ви ні на що не чекаєте 🕙, а просто прибираєте, «черги» нічого не змінять.
+
+Завершення займе той самий час із «чергами» чи без (рівночасність), і ви виконаєте той самий обсяг роботи.
+
+Але в цьому випадку, якби ви могли привести 8 колишніх касирів/кухарів/тепер прибиральників, і кожен з них (разом із вами) взяв би свою зону будинку для прибирання, ви могли б виконати всю роботу паралельно — з додатковою допомогою — і завершити значно швидше.
+
+У цьому сценарії кожен з прибиральників (включно з вами) був би процесором, що виконує свою частину роботи.
+
+І оскільки більшість часу виконання займає реальна робота (а не очікування), а роботу на комп’ютері виконує CPU, ці проблеми називають «CPU bound».
+
+---
+
+Поширені приклади «CPU bound» операцій - це речі, що потребують складної математичної обробки.
+
+Наприклад:
+
+- **Обробка аудіо** або **зображень**.
+- **Комп’ютерний зір**: зображення складається з мільйонів пікселів, кожен піксель має 3 значення/кольори, обробка зазвичай потребує обчислення чогось над цими пікселями, усіма одночасно.
+- **Машинне навчання**: зазвичай потребує великої кількості множень «матриць» і «векторів». Уявіть величезну таблицю з числами і множення всіх їх разом одночасно.
+- **Глибоке навчання**: це підгалузь машинного навчання, тож те саме застосовується. Просто тут не одна таблиця чисел для множення, а величезний їх набір, і в багатьох випадках ви використовуєте спеціальний процесор для побудови та/або використання цих моделей.
+
+### Рівночасність + паралелізм: веб + машинне навчання { #concurrency-parallelism-web-machine-learning }
+
+З **FastAPI** ви можете скористатися рівночасністю, що дуже поширена у веброзробці (та ж головна принада NodeJS).
+
+Але ви також можете використати переваги паралелізму і багатопроцесорності (наявність кількох процесів, що працюють паралельно) для навантажень «CPU bound», як у системах машинного навчання.
+
+Це, плюс простий факт, що Python є основною мовою для **Data Science**, машинного навчання і особливо глибокого навчання, робить FastAPI дуже вдалим вибором для веб API та застосунків Data Science / машинного навчання (серед багатьох інших).
+
+Щоб побачити, як досягти цього паралелізму у продакшні, див. розділ про [Розгортання](deployment/index.md).
+
+## `async` і `await` { #async-and-await }
+
+Сучасні версії Python мають дуже інтуїтивний спосіб визначення асинхронного коду. Це робить його схожим на звичайний «послідовний» код і виконує «очікування» за вас у відповідні моменти.
+
+Коли є операція, яка вимагатиме очікування перед поверненням результатів і має підтримку цих нових можливостей Python, ви можете написати її так:
+
+```Python
+burgers = await get_burgers(2)
+```
+
+Ключ тут - `await`. Він каже Python, що потрібно почекати ⏸, поки `get_burgers(2)` завершить свою роботу 🕙, перш ніж зберегти результати в `burgers`. Завдяки цьому Python знатиме, що може піти і зробити щось інше 🔀 ⏯ тим часом (наприклад, прийняти інший запит).
+
+Щоб `await` працював, він має бути всередині функції, що підтримує цю асинхронність. Для цього просто оголосіть її як `async def`:
+
+```Python hl_lines="1"
+async def get_burgers(number: int):
+ # Виконайте деякі асинхронні дії, щоб створити бургери
+ return burgers
+```
+
+...замість `def`:
+
+```Python hl_lines="2"
+# Це не асинхронно
+def get_sequential_burgers(number: int):
+ # Виконайте деякі послідовні дії, щоб створити бургери
+ return burgers
+```
+
+З `async def` Python знає, що всередині цієї функції він має відслідковувати вирази `await`, і що він може «ставити на паузу» ⏸ виконання цієї функції і йти робити щось інше 🔀, перш ніж повернутися.
+
+Коли ви хочете викликати функцію, визначену з `async def`, ви маєте «очікувати» її. Тож це не спрацює:
+
+```Python
+# Це не спрацює, тому що get_burgers визначено як: async def
+burgers = get_burgers(2)
+```
+
+---
+
+Отже, якщо ви використовуєте бібліотеку, яку можна викликати з `await`, вам потрібно створити функцію операції шляху, що її використовує, з `async def`, як тут:
+
+```Python hl_lines="2-3"
+@app.get('/burgers')
+async def read_burgers():
+ burgers = await get_burgers(2)
+ return burgers
+```
+
+### Більше технічних деталей { #more-technical-details }
+
+Ви могли помітити, що `await` можна використовувати лише всередині функцій, визначених з `async def`.
+
+А водночас функції, визначені з `async def`, потрібно «очікувати». Тож функції з `async def` також можна викликати лише всередині функцій, визначених з `async def`.
+
+Тож як же викликати першу `async`-функцію - курка чи яйце?
+
+Якщо ви працюєте з **FastAPI**, вам не потрібно про це турбуватися, адже цією «першою» функцією буде ваша функція операції шляху, і FastAPI знатиме, як учинити правильно.
+
+Але якщо ви хочете використовувати `async` / `await` без FastAPI, ви також можете це зробити.
+
+### Пишемо свій власний async-код { #write-your-own-async-code }
+
+Starlette (і **FastAPI**) базуються на [AnyIO](https://anyio.readthedocs.io/en/stable/), що робить їх сумісними як зі стандартною бібліотекою Python [asyncio](https://docs.python.org/3/library/asyncio-task.html), так і з [Trio](https://trio.readthedocs.io/en/stable/).
+
+Зокрема, ви можете безпосередньо використовувати [AnyIO](https://anyio.readthedocs.io/en/stable/) для ваших просунутих сценаріїв рівночасності, що потребують складніших патернів у вашому коді.
+
+І навіть якщо ви не використовували FastAPI, ви могли б писати свої власні async-застосунки з [AnyIO](https://anyio.readthedocs.io/en/stable/), щоб мати високу сумісність і отримати його переваги (наприклад, *структурована рівночасність*).
+
+Я створив іншу бібліотеку поверх AnyIO, як тонкий шар, щоб дещо покращити анотації типів і отримати кращу **автодопомогу** (autocompletion), **вбудовані помилки** (inline errors) тощо. Вона також має дружній вступ і навчальний посібник, щоб допомогти вам **зрозуміти** і написати **власний async-код**: [Asyncer](https://asyncer.tiangolo.com/). Вона буде особливо корисною, якщо вам потрібно **поєднувати async-код зі звичайним** (блокуючим/синхронним) кодом.
+
+### Інші форми асинхронного коду { #other-forms-of-asynchronous-code }
+
+Такий стиль використання `async` і `await` відносно новий у мові.
+
+Але він значно полегшує роботу з асинхронним кодом.
+
+Такий самий (або майже ідентичний) синтаксис нещодавно з’явився в сучасних версіях JavaScript (у Browser і NodeJS).
+
+До цього робота з асинхронним кодом була значно складнішою.
+
+У попередніх версіях Python ви могли використовувати потоки (threads) або [Gevent](https://www.gevent.org/). Але код набагато складніший для розуміння, налагодження і мислення про нього.
+
+У попередніх версіях NodeJS/Browser JavaScript ви б використовували «callbacks», що призводить до «callback hell».
+
+## Співпрограми { #coroutines }
+
+**Співпрограма** - це просто дуже вишукана назва для об’єкта, який повертає функція `async def`. Python знає, що це щось на кшталт функції, яку можна запустити і яка завершиться в певний момент, але яку також можна поставити на паузу ⏸ всередині, коли є `await`.
+
+Але всю цю функціональність використання асинхронного коду з `async` і `await` часто підсумовують як використання «співпрограм». Це порівняно з головною ключовою особливістю Go - «Goroutines».
+
+## Висновок { #conclusion }
+
+Погляньмо на ту саму фразу ще раз:
+
+> Сучасні версії Python мають підтримку «асинхронного коду» за допомогою так званих «співпрограм», з синтаксисом **`async` і `await`**.
+
+Тепер це має більше сенсу. ✨
+
+Усе це приводить у дію FastAPI (через Starlette) і дає йому таку вражаючу продуктивність.
+
+## Дуже технічні деталі { #very-technical-details }
+
+/// warning | Попередження
+
+Ймовірно, ви можете пропустити це.
+
+Це дуже технічні деталі про те, як **FastAPI** працює «під капотом».
+
+Якщо у вас є чимало технічних знань (співпрограми, потоки, блокування тощо) і вам цікаво, як FastAPI обробляє `async def` проти звичайного `def`, - вперед.
+
+///
+
+### Функції операції шляху { #path-operation-functions }
+
+Коли ви оголошуєте функцію операції шляху зі звичайним `def` замість `async def`, вона виконується у зовнішньому пулі потоків (threadpool), який потім «очікується», замість прямого виклику (оскільки прямий виклик блокував би сервер).
+
+Якщо ви прийшли з іншого async-фреймворку, який не працює так, як описано вище, і звикли визначати тривіальні, лише обчислювальні функції операції шляху зі звичайним `def` заради крихітного виграшу у продуктивності (близько 100 наносекунд), зверніть увагу, що у **FastAPI** ефект буде протилежним. У таких випадках краще використовувати `async def`, якщо тільки ваші функції операції шляху не використовують код, що виконує блокуюче I/O.
+
+Втім, у будь-якій ситуації є велика ймовірність, що **FastAPI** [все одно буде швидшим](index.md#performance) (або принаймні порівнянним) за ваш попередній фреймворк.
+
+### Залежності { #dependencies }
+
+Те саме стосується і [залежностей](tutorial/dependencies/index.md). Якщо залежність є стандартною функцією `def` замість `async def`, вона виконується у зовнішньому пулі потоків.
+
+### Підзалежності { #sub-dependencies }
+
+Ви можете мати кілька залежностей і [підзалежностей](tutorial/dependencies/sub-dependencies.md), які вимагають одна одну (як параметри визначень функцій). Деякі з них можуть бути створені з `async def`, а деякі - зі звичайним `def`. Все працюватиме, і ті, що створені зі звичайним `def`, будуть викликані у зовнішньому потоці (з пулу потоків), а не «очікувані».
+
+### Інші допоміжні функції { #other-utility-functions }
+
+Будь-яка інша допоміжна функція, яку ви викликаєте безпосередньо, може бути створена зі звичайним `def` або `async def`, і FastAPI не впливатиме на спосіб її виклику.
+
+Це відрізняється від функцій, які FastAPI викликає за вас: функції операції шляху і залежності.
+
+Якщо ваша допоміжна функція є звичайною функцією з `def`, її буде викликано безпосередньо (як ви написали у своєму коді), не в пулі потоків; якщо функція створена з `async def`, тоді вам слід використовувати `await` при її виклику у вашому коді.
+
+---
+
+Знову ж таки, це дуже технічні деталі, які, ймовірно, стануть у пригоді, якщо ви спеціально їх шукали.
+
+Інакше вам вистачить настанов із розділу вище: Поспішаєте?.
diff --git a/docs/uk/docs/benchmarks.md b/docs/uk/docs/benchmarks.md
new file mode 100644
index 0000000000000..b55ef720fa680
--- /dev/null
+++ b/docs/uk/docs/benchmarks.md
@@ -0,0 +1,34 @@
+# Бенчмарки { #benchmarks }
+
+Незалежні бенчмарки TechEmpower показують, що застосунки **FastAPI**, запущені під керуванням Uvicorn, є [одним із найшвидших доступних фреймворків Python](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7), поступаючись лише самим Starlette і Uvicorn (використовуються FastAPI внутрішньо).
+
+Але переглядаючи бенчмарки та порівняння, майте на увазі таке.
+
+## Бенчмарки та швидкість { #benchmarks-and-speed }
+
+Під час перегляду бенчмарків часто порівнюють кілька інструментів різних типів як рівноцінні.
+
+Зокрема, разом порівнюють Uvicorn, Starlette і FastAPI (серед багатьох інших інструментів).
+
+Чим простіше завдання, яке розв'язує інструмент, тим кращою буде продуктивність. І більшість бенчмарків не перевіряють додаткові можливості, що надає інструмент.
+
+Ієрархія приблизно така:
+
+* **Uvicorn**: сервер ASGI
+ * **Starlette**: (використовує Uvicorn) веб-мікрофреймворк
+ * **FastAPI**: (використовує Starlette) мікрофреймворк для API з низкою додаткових можливостей для створення API, з валідацією даних тощо.
+
+* **Uvicorn**:
+ * Матиме найвищу продуктивність, адже майже не містить додаткового коду окрім власне сервера.
+ * Ви не писатимете застосунок безпосередньо на Uvicorn. Це означало б, що ваш код мав би включати принаймні приблизно весь код, який надає Starlette (або **FastAPI**). І якщо зробити так, ваш кінцевий застосунок матиме ті самі накладні витрати, що й під час використання фреймворку, який мінімізує код застосунку та помилки.
+ * Якщо ви порівнюєте Uvicorn, порівнюйте його з Daphne, Hypercorn, uWSGI тощо. Сервери застосунків.
+* **Starlette**:
+ * Матиме наступну за швидкістю продуктивність після Uvicorn. Насправді Starlette використовує Uvicorn для запуску. Тож вона може бути «повільнішою» за Uvicorn лише через необхідність виконувати більше коду.
+ * Але надає інструменти для створення простих веб-застосунків із маршрутизацією на основі шляхів тощо.
+ * Якщо ви порівнюєте Starlette, порівнюйте її з Sanic, Flask, Django тощо. Веб-фреймворки (або мікрофреймворки).
+* **FastAPI**:
+ * Аналогічно до того, як Starlette використовує Uvicorn і не може бути швидшою за нього, **FastAPI** використовує Starlette, тож не може бути швидшою за неї.
+ * FastAPI надає більше можливостей поверх Starlette. Можливості, які майже завжди потрібні під час створення API, як-от валідація та серіалізація даних. І, використовуючи його, ви безкоштовно отримуєте автоматичну документацію (автоматична документація навіть не додає накладних витрат під час роботи застосунку - вона генерується під час запуску).
+ * Якби ви не використовували FastAPI і застосували Starlette безпосередньо (або інший інструмент, наприклад Sanic, Flask, Responder тощо), вам довелося б самостійно реалізувати всю валідацію та серіалізацію даних. Тож ваш кінцевий застосунок усе одно мав би ті самі накладні витрати, ніби він був створений із використанням FastAPI. І в багатьох випадках саме ця валідація та серіалізація даних становить найбільший обсяг коду в застосунках.
+ * Отже, використовуючи FastAPI, ви заощаджуєте час розробки, зменшуєте кількість помилок і рядків коду та, ймовірно, отримуєте таку саму (або кращу) продуктивність, як і без нього (адже інакше вам довелося б реалізувати все це у власному коді).
+ * Якщо ви порівнюєте FastAPI, порівнюйте його з веб-фреймворком (або набором інструментів), який надає валідацію даних, серіалізацію та документацію, наприклад Flask-apispec, NestJS, Molten тощо. Фреймворки з вбудованою автоматичною валідацією даних, серіалізацією та документацією.
diff --git a/docs/uk/docs/deployment/cloud.md b/docs/uk/docs/deployment/cloud.md
new file mode 100644
index 0000000000000..97d972717fdc9
--- /dev/null
+++ b/docs/uk/docs/deployment/cloud.md
@@ -0,0 +1,24 @@
+# Розгортання FastAPI у хмарних постачальників { #deploy-fastapi-on-cloud-providers }
+
+Ви можете використовувати практично **будь-якого хмарного постачальника**, щоб розгорнути свій застосунок FastAPI.
+
+У більшості випадків основні хмарні постачальники мають інструкції з розгортання FastAPI у них.
+
+## FastAPI Cloud { #fastapi-cloud }
+
+**[FastAPI Cloud](https://fastapicloud.com)** створено тим самим автором і командою, що стоять за **FastAPI**.
+
+Воно спрощує процес **створення**, **розгортання** та **доступу** до API з мінімальними зусиллями.
+
+Воно переносить той самий **досвід розробника** зі створення застосунків із FastAPI на їх **розгортання** у хмарі. 🎉
+
+FastAPI Cloud є основним спонсором і джерелом фінансування проєктів з відкритим кодом *FastAPI and friends*. ✨
+
+## Хмарні постачальники - спонсори { #cloud-providers-sponsors }
+
+Деякі інші хмарні постачальники ✨ [**спонсорують FastAPI**](../help-fastapi.md#sponsor-the-author) ✨ також. 🙇
+
+Можливо, ви захочете розглянути їх, щоб дотримуватися їхніх інструкцій і спробувати їхні сервіси:
+
+* [Render](https://docs.render.com/deploy-fastapi?utm_source=deploydoc&utm_medium=referral&utm_campaign=fastapi)
+* [Railway](https://docs.railway.com/guides/fastapi?utm_medium=integration&utm_source=docs&utm_campaign=fastapi)
diff --git a/docs/uk/docs/deployment/concepts.md b/docs/uk/docs/deployment/concepts.md
new file mode 100644
index 0000000000000..a6a5bc80e024e
--- /dev/null
+++ b/docs/uk/docs/deployment/concepts.md
@@ -0,0 +1,321 @@
+# Концепції розгортання { #deployments-concepts }
+
+Під час розгортання застосунку **FastAPI** (або будь-якого веб-API) є кілька концепцій, які, ймовірно, вас цікавлять, і, спираючись на них, ви зможете знайти **найвідповідніший** спосіб **розгорнути ваш застосунок**.
+
+Деякі важливі концепції:
+
+- Безпека - HTTPS
+- Запуск під час старту
+- Перезапуски
+- Реплікація (кількість запущених процесів)
+- Пам'ять
+- Попередні кроки перед стартом
+
+Подивимось, як вони впливають на **розгортання**.
+
+Зрештою головна мета - **обслуговувати клієнтів вашого API** так, щоб це було **безпечним**, з **мінімумом перерв у роботі**, і щоб **обчислювальні ресурси** (наприклад, віддалені сервери/віртуальні машини) використовувалися якомога ефективніше. 🚀
+
+Нижче я трохи більше розповім про ці **концепції**, і, сподіваюся, це дасть вам потрібну **інтуїцію**, щоб вирішувати, як розгортати ваш API в дуже різних середовищах, можливо, навіть у **майбутніх**, яких ще не існує.
+
+Враховуючи ці концепції, ви зможете **оцінювати та проєктувати** найкращий спосіб розгортання **ваших власних API**.
+
+У наступних розділах я наведу більш **конкретні рецепти** розгортання застосунків FastAPI.
+
+А поки перегляньмо ці важливі **концептуальні ідеї**. Вони також застосовні до будь-якого іншого типу веб-API. 💡
+
+## Безпека - HTTPS { #security-https }
+
+У [попередньому розділі про HTTPS](https.md) ми дізналися, як HTTPS забезпечує шифрування для вашого API.
+
+Ми також бачили, що HTTPS зазвичай надається компонентом, **зовнішнім** щодо вашого серверного застосунку, - **TLS Termination Proxy**.
+
+І має бути щось, що відповідає за **оновлення сертифікатів HTTPS** - це може бути той самий компонент або інший.
+
+### Приклади інструментів для HTTPS { #example-tools-for-https }
+
+Деякі інструменти, які можна використовувати як TLS Termination Proxy:
+
+- Traefik
+ - Автоматично обробляє оновлення сертифікатів ✨
+- Caddy
+ - Автоматично обробляє оновлення сертифікатів ✨
+- Nginx
+ - З зовнішнім компонентом на кшталт Certbot для оновлення сертифікатів
+- HAProxy
+ - З зовнішнім компонентом на кшталт Certbot для оновлення сертифікатів
+- Kubernetes з Ingress Controller, наприклад Nginx
+ - З зовнішнім компонентом на кшталт cert-manager для оновлення сертифікатів
+- Обробляється внутрішньо хмарним провайдером як частина їхніх сервісів (див. нижче 👇)
+
+Ще один варіант - використати **хмарний сервіс**, який зробить більше роботи, зокрема налаштує HTTPS. Можуть бути обмеження або додаткова вартість тощо. Але у такому разі вам не потрібно самостійно налаштовувати TLS Termination Proxy.
+
+У наступних розділах я покажу кілька конкретних прикладів.
+
+---
+
+Далі всі наступні концепції стосуються програми, яка запускає ваш фактичний API (наприклад, Uvicorn).
+
+## Програма і процес { #program-and-process }
+
+Ми багато говоритимемо про запущений «процес», тож корисно чітко розуміти, що це означає, і чим відрізняється від слова «програма».
+
+### Що таке програма { #what-is-a-program }
+
+Слово **програма** зазвичай вживають для опису багатьох речей:
+
+- **Код**, який ви пишете, **файли Python**.
+- **Файл**, який може бути **виконаний** операційною системою, наприклад: `python`, `python.exe` або `uvicorn`.
+- Конкретна програма під час **виконання** в операційній системі, що використовує CPU та зберігає дані в пам'яті. Це також називають **процесом**.
+
+### Що таке процес { #what-is-a-process }
+
+Слово **процес** зазвичай використовують у більш специфічному значенні, маючи на увазі саме те, що виконується в операційній системі (як у попередньому пункті):
+
+- Конкретна програма під час **виконання** в операційній системі.
+ - Це не про файл і не про код, це **конкретно** про те, що **виконується** та керується операційною системою.
+- Будь-яка програма, будь-який код **може щось робити** лише під час **виконання**. Тобто коли **процес запущений**.
+- Процес може бути **завершений** (або «kill») вами чи операційною системою. У цей момент він припиняє виконання і **більше нічого не може робити**.
+- Кожен застосунок, який працює на вашому комп'ютері, має певний процес за собою: кожна запущена програма, кожне вікно тощо. Зазвичай на комп'ютері одночасно працює **багато процесів**.
+- **Кілька процесів** **однієї й тієї самої програми** можуть працювати одночасно.
+
+Якщо ви відкриєте «диспетчер завдань» або «системний монітор» (чи подібні інструменти) в операційній системі, ви побачите багато таких процесів.
+
+Наприклад, ви, ймовірно, побачите кілька процесів того самого браузера (Firefox, Chrome, Edge тощо). Зазвичай він запускає один процес на вкладку плюс деякі додаткові процеси.
+
+
+
+---
+
+Тепер, коли ми знаємо різницю між термінами **процес** і **програма**, продовжимо говорити про розгортання.
+
+## Запуск під час старту { #running-on-startup }
+
+У більшості випадків, коли ви створюєте веб-API, ви хочете, щоб він **працював постійно**, без перерв, щоб клієнти завжди мали до нього доступ. Звісно, якщо немає особливих причин запускати його лише в певних ситуаціях. Але зазвичай ви хочете, щоб він постійно працював і був **доступний**.
+
+### На віддаленому сервері { #in-a-remote-server }
+
+Коли ви налаштовуєте віддалений сервер (хмарний сервер, віртуальну машину тощо), найпростіше - використовувати `fastapi run` (який використовує Uvicorn) або щось схоже, вручну, так само, як під час локальної розробки.
+
+І це працюватиме та буде корисним **під час розробки**.
+
+Але якщо ви втратите з'єднання з сервером, **запущений процес**, найімовірніше, завершиться.
+
+І якщо сервер буде перезавантажено (наприклад, після оновлень або міграцій у хмарного провайдера), ви, ймовірно, **не помітите цього**. І через це ви навіть не знатимете, що треба вручну перезапустити процес. У результаті ваш API просто залишиться «мертвим». 😱
+
+### Автоматичний запуск під час старту { #run-automatically-on-startup }
+
+Загалом ви, напевно, захочете, щоб серверна програма (наприклад, Uvicorn) запускалася автоматично під час старту сервера і без будь-якого **людського втручання**, щоб завжди був запущений процес із вашим API (наприклад, Uvicorn із вашим FastAPI-застосунком).
+
+### Окрема програма { #separate-program }
+
+Щоб цього досягти, зазвичай використовують **окрему програму**, яка гарантує запуск вашого застосунку під час старту. І в багатьох випадках вона також забезпечує запуск інших компонентів або застосунків, наприклад бази даних.
+
+### Приклади інструментів для запуску під час старту { #example-tools-to-run-at-startup }
+
+Приклади інструментів, які можуть це робити:
+
+- Docker
+- Kubernetes
+- Docker Compose
+- Docker у режимі Swarm
+- Systemd
+- Supervisor
+- Обробляється внутрішньо хмарним провайдером як частина їхніх сервісів
+- Інші...
+
+У наступних розділах я наведу більш конкретні приклади.
+
+## Перезапуски { #restarts }
+
+Подібно до забезпечення запуску застосунку під час старту системи, ви, ймовірно, також захочете гарантувати його **перезапуск** після збоїв.
+
+### Ми помиляємося { #we-make-mistakes }
+
+Ми, люди, постійно робимо **помилки**. Майже завжди у програмному забезпеченні є приховані **помилки**. 🐛
+
+І ми як розробники постійно покращуємо код, знаходячи ці помилки та додаючи нові можливості (можливо, теж додаючи нові помилки 😅).
+
+### Невеликі помилки обробляються автоматично { #small-errors-automatically-handled }
+
+Створюючи веб-API з FastAPI, якщо в нашому коді є помилка, FastAPI зазвичай обмежує її одним запитом, який цю помилку спровокував. 🛡
+
+Клієнт отримає **500 Internal Server Error** для цього запиту, але застосунок продовжить працювати для наступних запитів замість повного краху.
+
+### Великі помилки - крахи { #bigger-errors-crashes }
+
+Втім, бувають випадки, коли ми пишемо код, який **падає весь застосунок**, спричиняючи крах Uvicorn і Python. 💥
+
+І все ж ви, ймовірно, не захочете, щоб застосунок залишався «мертвим» через помилку в одному місці - ви, напевно, хочете, щоб він **продовжував працювати** принаймні для тих *операцій шляху*, що не зламані.
+
+### Перезапуск після краху { #restart-after-crash }
+
+Але в таких випадках із серйозними помилками, що призводять до краху запущеного **процесу**, потрібен зовнішній компонент, відповідальний за **перезапуск** процесу, принаймні кілька разів...
+
+/// tip | Порада
+
+...Хоча якщо весь застосунок просто **миттєво падає**, безглуздо перезапускати його безкінечно. Але в таких випадках ви, ймовірно, помітите це під час розробки або принаймні відразу після розгортання.
+
+Тож зосередьмося на основних випадках, коли у майбутньому він може повністю падати за певних обставин, і тоді все ще має сенс його перезапускати.
+
+///
+
+Ймовірно, ви захочете мати відокремлений **зовнішній компонент**, який відповідає за перезапуск застосунку, адже до того моменту сам застосунок з Uvicorn і Python уже впав, і нічого в тому ж коді цієї ж програми зробити не зможе.
+
+### Приклади інструментів для автоматичного перезапуску { #example-tools-to-restart-automatically }
+
+У більшості випадків той самий інструмент, який використовується для **запуску програми під час старту**, також використовується для автоматичних **перезапусків**.
+
+Наприклад, це можуть забезпечувати:
+
+- Docker
+- Kubernetes
+- Docker Compose
+- Docker у режимі Swarm
+- Systemd
+- Supervisor
+- Обробляється внутрішньо хмарним провайдером як частина їхніх сервісів
+- Інші...
+
+## Реплікація - процеси та пам'ять { #replication-processes-and-memory }
+
+У застосунку FastAPI, використовуючи серверну програму, як-от команду `fastapi`, що запускає Uvicorn, один запуск в **одному процесі** може обслуговувати кількох клієнтів рівночасно.
+
+Але часто ви захочете запускати кілька процесів-працівників одночасно.
+
+### Кілька процесів - працівники { #multiple-processes-workers }
+
+Якщо у вас більше клієнтів, ніж може обробити один процес (наприклад, якщо віртуальна машина не надто потужна) і на сервері є **кілька ядер** CPU, тоді ви можете запустити **кілька процесів** із тим самим застосунком паралельно і розподіляти запити між ними.
+
+Коли ви запускаєте **кілька процесів** того самого програмного забезпечення API, їх зазвичай називають **працівниками** (workers).
+
+### Процеси-працівники і порти { #worker-processes-and-ports }
+
+Пам'ятаєте з документації [Про HTTPS](https.md), що на сервері лише один процес може слухати певну комбінацію порту та IP-адреси?
+
+Это досі так.
+
+Отже, щоб мати **кілька процесів** одночасно, має бути **єдиний процес, який слухає порт**, і який далі якимось чином передає комунікацію кожному процесу-працівнику.
+
+### Пам'ять на процес { #memory-per-process }
+
+Коли програма завантажує щось у пам'ять, наприклад модель машинного навчання в змінну або вміст великого файлу в змінну, все це **споживає частину пам'яті (RAM)** сервера.
+
+І кілька процесів зазвичай **не діляться пам'яттю**. Це означає, що кожен запущений процес має власні речі, змінні та пам'ять. І якщо у вашому коді споживається багато пам'яті, **кожен процес** споживатиме еквівалентний обсяг пам'яті.
+
+### Пам'ять сервера { #server-memory }
+
+Наприклад, якщо ваш код завантажує модель машинного навчання розміром **1 GB**, то при запуску одного процесу з вашим API він споживатиме щонайменше 1 GB RAM. А якщо ви запустите **4 процеси** (4 працівники) - кожен споживатиме 1 GB RAM. Отже, загалом ваш API споживатиме **4 GB RAM**.
+
+І якщо ваш віддалений сервер або віртуальна машина має лише 3 GB RAM, спроба використати понад 4 GB призведе до проблем. 🚨
+
+### Кілька процесів - приклад { #multiple-processes-an-example }
+
+У цьому прикладі є **керівний процес** (Manager Process), який запускає і контролює два **процеси-працівники**.
+
+Цей керівний процес, імовірно, саме і слухатиме **порт** на IP. І він передаватиме всю комунікацію процесам-працівникам.
+
+Ці процеси-працівники виконуватимуть ваш застосунок, здійснюватимуть основні обчислення, щоб отримати **запит** і повернути **відповідь**, і завантажуватимуть усе, що ви зберігаєте в змінних у RAM.
+
++ +**FastAPI** не існував би без попередньої роботи інших. + +Було створено багато інструментів, які надихнули на його створення. + +Я роками уникав створення нового фреймворку. Спочатку я намагався вирішити всі можливості, які покриває **FastAPI**, використовуючи різні фреймворки, плагіни та інструменти. + +Але в певний момент не залишилося іншого варіанту, окрім створити щось, що надає всі ці можливості, узявши найкращі ідеї з попередніх інструментів і поєднавши їх якнайкраще, використовуючи можливості самої мови, яких раніше взагалі не було (підказки типів Python 3.6+). + ++ +## Дослідження { #investigation } + +Використовуючи всі попередні альтернативи, я мав змогу повчитися в кожної, узяти ідеї й поєднати їх якнайкраще для себе та команд розробників, з якими працював. + +Наприклад, було очевидно, що в ідеалі все має ґрунтуватися на стандартних підказках типів Python. + +Також найкращим підходом було використовувати вже наявні стандарти. + +Тож, ще до початку написання коду **FastAPI**, я провів кілька місяців, вивчаючи специфікації OpenAPI, Схеми JSON, OAuth2 тощо. Розуміючи їхні взаємозв'язки, перетини та відмінності. + +## Проєктування { #design } + +Потім я приділив час проєктуванню «API» для розробника, яке я хотів мати як користувач (як розробник, що використовує FastAPI). + +Я протестував кілька ідей у найпопулярніших Python-редакторах: PyCharm, VS Code, редакторах на основі Jedi. + +За даними [Python Developer Survey](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools), це охоплює близько 80% користувачів. + +Це означає, що **FastAPI** спеціально тестувався з редакторами, якими користуються 80% розробників Python. І оскільки більшість інших редакторів працюють подібно, усі ці переваги мають працювати практично у всіх редакторах. + +Так я зміг знайти найкращі способи максимально зменшити дублювання коду, забезпечити автодоповнення всюди, перевірки типів і помилок тощо. + +І все це так, щоб надати найкращий досвід розробки для всіх розробників. + +## Вимоги { #requirements } + +Після перевірки кількох альтернатив я вирішив використовувати [**Pydantic**](https://docs.pydantic.dev/) через його переваги. + +Потім я зробив внески до нього, щоб зробити його повністю сумісним із Схемою JSON, додати підтримку різних способів оголошення обмежень і поліпшити підтримку редакторів (перевірки типів, автодоповнення) на основі тестів у кількох редакторах. + +Під час розробки я також зробив внески до [**Starlette**](https://www.starlette.dev/), іншої ключової залежності. + +## Розробка { #development } + +Коли я взявся безпосередньо за створення **FastAPI**, більшість складових уже були на місцях: дизайн визначено, вимоги та інструменти підготовлено, знання про стандарти й специфікації - чіткі та свіжі. + +## Майбутнє { #future } + +На цей момент уже зрозуміло, що **FastAPI** зі своїми ідеями корисний для багатьох. + +Його обирають замість попередніх альтернатив, бо він краще відповідає багатьом сценаріям використання. + +Багато розробників і команд уже залежать від **FastAPI** у своїх проєктах (включно зі мною та моєю командою). + +Але попереду ще багато покращень і можливостей. + +**FastAPI** має велике майбутнє. + +І [ваша допомога](help-fastapi.md) дуже цінується. diff --git a/docs/uk/docs/how-to/authentication-error-status-code.md b/docs/uk/docs/how-to/authentication-error-status-code.md new file mode 100644 index 0000000000000..d67071371195b --- /dev/null +++ b/docs/uk/docs/how-to/authentication-error-status-code.md @@ -0,0 +1,17 @@ +# Використовуйте старі коди статусу помилки автентифікації 403 { #use-old-403-authentication-error-status-codes } + +До версії FastAPI `0.122.0`, коли інтегровані засоби безпеки повертали клієнту помилку після невдалої автентифікації, вони використовували HTTP код статусу `403 Forbidden`. + +Починаючи з версії FastAPI `0.122.0`, вони використовують більш доречний HTTP код статусу `401 Unauthorized` і повертають змістовний заголовок `WWW-Authenticate` у відповіді, відповідно до специфікацій HTTP, [RFC 7235](https://datatracker.ietf.org/doc/html/rfc7235#section-3.1), [RFC 9110](https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized). + +Але якщо з якоїсь причини ваші клієнти залежать від старої поведінки, ви можете повернутися до неї, переписавши метод `make_not_authenticated_error` у ваших класах безпеки. + +Наприклад, ви можете створити підклас `HTTPBearer`, який повертатиме помилку `403 Forbidden` замість типового `401 Unauthorized`: + +{* ../../docs_src/authentication_error_status_code/tutorial001_an_py310.py hl[9:13] *} + +/// tip | Порада + +Зверніть увагу, що функція повертає екземпляр винятку, вона не породжує його. Породження відбувається в іншій частині внутрішнього коду. + +/// diff --git a/docs/uk/docs/how-to/conditional-openapi.md b/docs/uk/docs/how-to/conditional-openapi.md new file mode 100644 index 0000000000000..80c22eeb5d221 --- /dev/null +++ b/docs/uk/docs/how-to/conditional-openapi.md @@ -0,0 +1,56 @@ +# Умовний OpenAPI { #conditional-openapi } + +Якщо потрібно, ви можете використовувати налаштування і змінні оточення, щоб умовно налаштовувати OpenAPI залежно від середовища, а також повністю вимикати його. + +## Про безпеку, API та документацію { #about-security-apis-and-docs } + +Приховування інтерфейсів документації у продукційному середовищі не має бути способом захисту вашого API. + +Це не додає жодної додаткової безпеки вашому API, операції шляху й надалі будуть доступні там, де вони є. + +Якщо у вашому коді є вразливість, вона залишиться. + +Приховування документації лише ускладнює розуміння того, як взаємодіяти з вашим API, і може ускладнити для вас його налагодження у продакшні. Це можна вважати просто формою [Безпека через неясність](https://en.wikipedia.org/wiki/Security_through_obscurity). + +Якщо ви хочете захистити ваш API, є кілька кращих дій, які ви можете зробити, наприклад: + +- Переконайтеся, що у вас добре визначені моделі Pydantic для тіл запитів і відповідей. +- Налаштуйте потрібні дозволи та ролі за допомогою залежностей. +- Ніколи не зберігайте паролі у відкритому вигляді, лише хеші паролів. +- Реалізуйте та використовуйте відомі криптографічні інструменти, як-от pwdlib і токени JWT. +- Додайте більш детальний контроль дозволів із областями OAuth2 там, де це потрібно. +- ...тощо. + +Втім, у вас може бути дуже специфічний випадок використання, коли справді потрібно вимкнути документацію API для певного середовища (наприклад, для продакшну) або залежно від конфігурацій зі змінних оточення. + +## Умовний OpenAPI з налаштувань і змінних оточення { #conditional-openapi-from-settings-and-env-vars } + +Ви можете легко використати ті самі налаштування Pydantic, щоб налаштувати згенерований OpenAPI та інтерфейси документації. + +Наприклад: + +{* ../../docs_src/conditional_openapi/tutorial001_py310.py hl[6,11] *} + +Тут ми оголошуємо налаштування `openapi_url` з тим самим значенням за замовчуванням `"/openapi.json"`. + +Потім ми використовуємо його під час створення застосунку `FastAPI`. + +Далі ви можете вимкнути OpenAPI (включно з інтерфейсами документації), встановивши змінну оточення `OPENAPI_URL` у пусту строку, наприклад: + +
+
+Але ви можете вимкнути її, встановивши `syntaxHighlight` у `False`:
+
+{* ../../docs_src/configure_swagger_ui/tutorial001_py310.py hl[3] *}
+
+...після цього Swagger UI більше не показуватиме підсвітку синтаксису:
+
+
+
+## Змініть тему { #change-the-theme }
+
+Так само ви можете задати тему підсвітки синтаксису ключем `"syntaxHighlight.theme"` (зверніть увагу, що посередині є крапка):
+
+{* ../../docs_src/configure_swagger_ui/tutorial002_py310.py hl[3] *}
+
+Це налаштування змінить колірну тему підсвітки синтаксису:
+
+
+
+## Змініть параметри Swagger UI за замовчуванням { #change-default-swagger-ui-parameters }
+
+FastAPI містить деякі параметри конфігурації за замовчуванням, що підходять для більшості випадків.
+
+Вони включають такі типові налаштування:
+
+{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}
+
+Ви можете переписати будь-яке з них, задавши інше значення в аргументі `swagger_ui_parameters`.
+
+Наприклад, щоб вимкнути `deepLinking`, ви можете передати такі налаштування до `swagger_ui_parameters`:
+
+{* ../../docs_src/configure_swagger_ui/tutorial003_py310.py hl[3] *}
+
+## Інші параметри Swagger UI { #other-swagger-ui-parameters }
+
+Щоб побачити всі можливі налаштування, які ви можете використовувати, прочитайте офіційну [документацію щодо параметрів Swagger UI](https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/).
+
+## Налаштування лише для JavaScript { #javascript-only-settings }
+
+Swagger UI також дозволяє інші налаштування як об’єкти, що є тільки для **JavaScript** (наприклад, функції JavaScript).
+
+FastAPI також включає такі налаштування `presets`, що є лише для JavaScript:
+
+```JavaScript
+presets: [
+ SwaggerUIBundle.presets.apis,
+ SwaggerUIBundle.SwaggerUIStandalonePreset
+]
+```
+
+Це об’єкти **JavaScript**, а не строки, тому ви не можете передати їх безпосередньо з коду Python.
+
+Якщо вам потрібно використати такі налаштування лише для JavaScript, скористайтеся одним із методів вище. Повністю перепишіть операцію шляху Swagger UI та вручну напишіть потрібний JavaScript.
diff --git a/docs/uk/docs/how-to/custom-docs-ui-assets.md b/docs/uk/docs/how-to/custom-docs-ui-assets.md
new file mode 100644
index 0000000000000..f8a4f99662a89
--- /dev/null
+++ b/docs/uk/docs/how-to/custom-docs-ui-assets.md
@@ -0,0 +1,185 @@
+# Користувацькі статичні ресурси інтерфейсу документації (самохостинг) { #custom-docs-ui-static-assets-self-hosting }
+
+Документація API використовує **Swagger UI** і **ReDoc**, і кожному з них потрібні файли JavaScript та CSS.
+
+Типово ці файли віддаються з CDN.
+
+Але це можна налаштувати: ви можете вказати конкретний CDN або віддавати файли самостійно.
+
+## Власний CDN для JavaScript і CSS { #custom-cdn-for-javascript-and-css }
+
+Припустімо, що ви хочете використовувати інший CDN, наприклад `https://unpkg.com/`.
+
+Це може бути корисно, якщо, наприклад, ви живете в країні, що обмежує деякі URL-адреси.
+
+### Вимкніть автоматичну документацію { #disable-the-automatic-docs }
+
+Перший крок - вимкнути автоматичну документацію, адже типово вона використовує стандартний CDN.
+
+Щоб їх вимкнути, встановіть їхні URL у `None` під час створення вашого застосунку `FastAPI`:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[8] *}
+
+### Додайте користувацьку документацію { #include-the-custom-docs }
+
+Тепер ви можете створити *операції шляху* для користувацької документації.
+
+Ви можете перевикористати внутрішні функції FastAPI для створення HTML-сторінок документації і передати їм потрібні аргументи:
+
+- `openapi_url`: URL, за яким HTML-сторінка документації зможе отримати схему OpenAPI для вашого API. Тут можна використати атрибут `app.openapi_url`.
+- `title`: заголовок вашого API.
+- `oauth2_redirect_url`: тут можна використати `app.swagger_ui_oauth2_redirect_url`, щоб узяти значення за замовчуванням.
+- `swagger_js_url`: URL, за яким HTML для Swagger UI зможе отримати файл **JavaScript**. Це URL вашого користувацького CDN.
+- `swagger_css_url`: URL, за яким HTML для Swagger UI зможе отримати файл **CSS**. Це URL вашого користувацького CDN.
+
+Аналогічно для ReDoc...
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[2:6,11:19,22:24,27:33] *}
+
+/// tip | Порада
+
+*Операція шляху* для `swagger_ui_redirect` - це допоміжний маршрут, коли ви використовуєте OAuth2.
+
+Якщо ви інтегруєте ваш API з провайдером OAuth2, ви зможете автентифікуватися і повернутися до документації API з отриманими обліковими даними. І взаємодіяти з ним, використовуючи реальну автентифікацію OAuth2.
+
+Swagger UI впорається з цим «за лаштунками», але йому потрібен цей «redirect» хелпер.
+
+///
+
+### Створіть операцію шляху для перевірки { #create-a-path-operation-to-test-it }
+
+Тепер, щоб перевірити, що все працює, створіть *операцію шляху*:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[36:38] *}
+
+### Перевірте { #test-it }
+
+Тепер ви маєте змогу відкрити документацію за [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) і перезавантажити сторінку, вона завантажить ці ресурси з нового CDN.
+
+## Самохостинг JavaScript і CSS для документації { #self-hosting-javascript-and-css-for-docs }
+
+Самохостинг JavaScript і CSS може бути корисним, якщо, наприклад, ваш застосунок має працювати офлайн, без доступу до Інтернету, або в локальній мережі.
+
+Тут ви побачите, як віддавати ці файли самостійно, у тому самому застосунку FastAPI, і налаштувати документацію на їх використання.
+
+### Структура файлів проєкту { #project-file-structure }
+
+Припустімо, що структура файлів вашого проєкту виглядає так:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+```
+
+Тепер створіть каталог для збереження цих статичних файлів.
+
+Нова структура файлів може виглядати так:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static/
+```
+
+### Завантажте файли { #download-the-files }
+
+Завантажте статичні файли, потрібні для документації, і помістіть їх у каталог `static/`.
+
+Ви, ймовірно, можете натиснути правою кнопкою на кожному посиланні і вибрати опцію на кшталт «Зберегти посилання як...».
+
+**Swagger UI** використовує файли:
+
+- [`swagger-ui-bundle.js`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js)
+- [`swagger-ui.css`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css)
+
+А **ReDoc** використовує файл:
+
+- [`redoc.standalone.js`](https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js)
+
+Після цього ваша структура файлів може виглядати так:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static
+ ├── redoc.standalone.js
+ ├── swagger-ui-bundle.js
+ └── swagger-ui.css
+```
+
+### Обслуговуйте статичні файли { #serve-the-static-files }
+
+- Імпортуйте `StaticFiles`.
+- Змонтуйте екземпляр `StaticFiles()` у певному шляху.
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[7,11] *}
+
+### Перевірте статичні файли { #test-the-static-files }
+
+Запустіть ваш застосунок і перейдіть до [http://127.0.0.1:8000/static/redoc.standalone.js](http://127.0.0.1:8000/static/redoc.standalone.js).
+
+Ви маєте побачити дуже довгий файл JavaScript для **ReDoc**.
+
+Він може починатися приблизно так:
+
+```JavaScript
+/*! For license information please see redoc.standalone.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")):
+...
+```
+
+Це підтверджує, що ви можете віддавати статичні файли з вашого застосунку і що ви розмістили статичні файли для документації у правильному місці.
+
+Тепер ми можемо налаштувати застосунок на використання цих статичних файлів для документації.
+
+### Вимкніть автоматичну документацію для статичних файлів { #disable-the-automatic-docs-for-static-files }
+
+Як і при використанні користувацького CDN, першим кроком є вимкнення автоматичної документації, оскільки типово вона використовує CDN.
+
+Щоб їх вимкнути, встановіть їхні URL у `None` під час створення вашого застосунку `FastAPI`:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[9] *}
+
+### Додайте користувацьку документацію для статичних файлів { #include-the-custom-docs-for-static-files }
+
+Аналогічно користувацькому CDN, тепер ви можете створити *операції шляху* для користувацької документації.
+
+Знову ж, ви можете перевикористати внутрішні функції FastAPI для створення HTML-сторінок документації і передати їм потрібні аргументи:
+
+- `openapi_url`: URL, за яким HTML-сторінка документації зможе отримати схему OpenAPI для вашого API. Тут можна використати атрибут `app.openapi_url`.
+- `title`: заголовок вашого API.
+- `oauth2_redirect_url`: тут можна використати `app.swagger_ui_oauth2_redirect_url`, щоб узяти значення за замовчуванням.
+- `swagger_js_url`: URL, за яким HTML для Swagger UI зможе отримати файл **JavaScript**. **Це той файл, який тепер віддає ваш власний застосунок**.
+- `swagger_css_url`: URL, за яким HTML для Swagger UI зможе отримати файл **CSS**. **Це той файл, який тепер віддає ваш власний застосунок**.
+
+Аналогічно для ReDoc...
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[2:6,14:22,25:27,30:36] *}
+
+/// tip | Порада
+
+*Операція шляху* для `swagger_ui_redirect` - це допоміжний маршрут, коли ви використовуєте OAuth2.
+
+Якщо ви інтегруєте ваш API з провайдером OAuth2, ви зможете автентифікуватися і повернутися до документації API з отриманими обліковими даними. І взаємодіяти з ним, використовуючи реальну автентифікацію OAuth2.
+
+Swagger UI впорається з цим «за лаштунками», але йому потрібен цей «redirect» хелпер.
+
+///
+
+### Створіть операцію шляху для перевірки статичних файлів { #create-a-path-operation-to-test-static-files }
+
+Тепер, щоб перевірити, що все працює, створіть *операцію шляху*:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[39:41] *}
+
+### Перевірте UI зі статичними файлами { #test-static-files-ui }
+
+Тепер ви маєте змогу вимкнути WiFi, відкрити документацію за [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) і перезавантажити сторінку.
+
+І навіть без Інтернету ви зможете побачити документацію для вашого API і взаємодіяти з ним.
diff --git a/docs/uk/docs/how-to/custom-request-and-route.md b/docs/uk/docs/how-to/custom-request-and-route.md
new file mode 100644
index 0000000000000..6a46b57239402
--- /dev/null
+++ b/docs/uk/docs/how-to/custom-request-and-route.md
@@ -0,0 +1,109 @@
+# Користувацькі класи Request та APIRoute { #custom-request-and-apiroute-class }
+
+У деяких випадках ви можете захотіти перевизначити логіку, яку використовують класи `Request` та `APIRoute`.
+
+Зокрема, це може бути доброю альтернативою логіці в проміжному програмному забезпеченні.
+
+Наприклад, якщо потрібно прочитати або змінити тіло запиту до того, як його обробить ваш застосунок.
+
+/// danger | Обережно
+
+Це «просунута» можливість.
+
+Якщо ви тільки починаєте працювати з **FastAPI**, можливо, варто пропустити цей розділ.
+
+///
+
+## Випадки використання { #use-cases }
+
+Деякі варіанти використання:
+
+- Перетворення не-JSON тіл запитів на JSON (наприклад, [`msgpack`](https://msgpack.org/index.html)).
+- Розпакування тіл запитів, стиснених gzip.
+- Автоматичне логування всіх тіл запитів.
+
+## Обробка користувацьких кодувань тіла запиту { #handling-custom-request-body-encodings }
+
+Розгляньмо, як використати користувацький підклас `Request` для розпакування gzip-запитів.
+
+А також підклас `APIRoute`, щоб застосувати цей користувацький клас запиту.
+
+### Створіть користувацький клас `GzipRequest` { #create-a-custom-gziprequest-class }
+
+/// tip | Порада
+
+Це навчальний приклад, щоб продемонструвати принцип роботи. Якщо вам потрібна підтримка Gzip, скористайтеся вбудованим [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware).
+
+///
+
+Спочатку створимо клас `GzipRequest`, який перевизначить метод `Request.body()`, щоб розпаковувати тіло за наявності відповідного заголовка.
+
+Якщо в заголовку немає `gzip`, він не намагатиметься розпаковувати тіло.
+
+Таким чином один і той самий клас маршруту зможе обробляти як стиснені gzip, так і нестиснені запити.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[9:16] *}
+
+### Створіть користувацький клас `GzipRoute` { #create-a-custom-gziproute-class }
+
+Далі створимо користувацький підклас `fastapi.routing.APIRoute`, який використовуватиме `GzipRequest`.
+
+Цього разу він перевизначить метод `APIRoute.get_route_handler()`.
+
+Цей метод повертає функцію. І саме ця функція прийме запит і поверне відповідь.
+
+Тут ми використовуємо її, щоб створити `GzipRequest` з початкового запиту.
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[19:27] *}
+
+/// note | Технічні деталі
+
+У `Request` є атрибут `request.scope` - це просто Python `dict`, що містить метадані, пов'язані із запитом.
+
+Також `Request` має `request.receive` - це функція для «отримання» тіла запиту.
+
+`scope` `dict` і функція `receive` є частиною специфікації ASGI.
+
+І саме ці дві сутності - `scope` та `receive` - потрібні для створення нового екземпляра `Request`.
+
+Щоб дізнатися більше про `Request`, перегляньте [документацію Starlette про запити](https://www.starlette.dev/requests/).
+
+///
+
+Єдине, що робить інакше функція, повернена `GzipRequest.get_route_handler`, - перетворює `Request` на `GzipRequest`.
+
+Завдяки цьому наш `GzipRequest` подбає про розпакування даних (за потреби) перед передаванням їх у наші *операції шляху*.
+
+Після цього вся логіка обробки залишається тією самою.
+
+А завдяки змінам у `GzipRequest.body` тіло запиту за потреби буде автоматично розпаковане під час завантаження **FastAPI**.
+
+## Доступ до тіла запиту в обробнику виключень { #accessing-the-request-body-in-an-exception-handler }
+
+/// tip | Порада
+
+Щоб розв’язати це саме завдання, скоріш за все, простіше використати `body` у користувацькому обробнику `RequestValidationError` ([Обробка помилок](../tutorial/handling-errors.md#use-the-requestvalidationerror-body)).
+
+Але цей приклад усе ще корисний і показує, як взаємодіяти з внутрішніми компонентами.
+
+///
+
+Ми також можемо скористатися цим підходом, щоб отримати доступ до тіла запиту в обробнику виключень.
+
+Усе, що потрібно, - обробити запит усередині блоку `try`/`except`:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[14,16] *}
+
+Якщо станеться виключення, екземпляр `Request` усе ще буде у видимості, тож ми зможемо прочитати й використати тіло запиту під час обробки помилки:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[17:19] *}
+
+## Користувацький клас `APIRoute` у маршрутизаторі { #custom-apiroute-class-in-a-router }
+
+Можна також встановити параметр `route_class` у `APIRouter`:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[26] *}
+
+У цьому прикладі *операції шляху* в `router` використовуватимуть користувацький клас `TimedRoute` і матимуть додатковий заголовок відповіді `X-Response-Time` із часом, витраченим на формування відповіді:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[13:20] *}
diff --git a/docs/uk/docs/how-to/extending-openapi.md b/docs/uk/docs/how-to/extending-openapi.md
new file mode 100644
index 0000000000000..fcd0982a9d14e
--- /dev/null
+++ b/docs/uk/docs/how-to/extending-openapi.md
@@ -0,0 +1,80 @@
+# Розширення OpenAPI { #extending-openapi }
+
+У деяких випадках вам може знадобитися змінити згенеровану схему OpenAPI.
+
+У цьому розділі ви побачите як це зробити.
+
+## Звичайний процес { #the-normal-process }
+
+Звичайний (типовий) процес такий.
+
+Застосунок `FastAPI` (екземпляр) має метод `.openapi()`, який має повертати схему OpenAPI.
+
+Під час створення об'єкта застосунку реєструється *операція шляху* для `/openapi.json` (або для того значення, яке ви встановили в `openapi_url`).
+
+Вона просто повертає відповідь JSON з результатом методу `.openapi()` застосунку.
+
+Типово метод `.openapi()` перевіряє властивість `.openapi_schema`, і якщо там вже є дані, повертає їх.
+
+Якщо ні, він генерує їх за допомогою утилітарної функції `fastapi.openapi.utils.get_openapi`.
+
+Функція `get_openapi()` приймає такі параметри:
+
+- `title`: Заголовок OpenAPI, показується в документації.
+- `version`: Версія вашого API, напр. `2.5.0`.
+- `openapi_version`: Версія специфікації OpenAPI, що використовується. Типово остання: `3.1.0`.
+- `summary`: Короткий підсумок API.
+- `description`: Опис вашого API; може містити markdown і буде показаний у документації.
+- `routes`: Список маршрутів, це кожна з зареєстрованих *операцій шляху*. Їх беруть з `app.routes`.
+
+/// info | Інформація
+
+Параметр `summary` доступний в OpenAPI 3.1.0 і вище, підтримується FastAPI 0.99.0 і вище.
+
+///
+
+## Переписування типових значень { #overriding-the-defaults }
+
+Використовуючи наведене вище, ви можете скористатися тією ж утилітарною функцією для генерації схеми OpenAPI і переписати потрібні частини.
+
+Наприклад, додаймо [розширення OpenAPI ReDoc для додавання власного логотипа](https://github.com/Rebilly/ReDoc/blob/master/docs/redoc-vendor-extensions.md#x-logo).
+
+### Звичайний **FastAPI** { #normal-fastapi }
+
+Спочатку напишіть ваш застосунок **FastAPI** як зазвичай:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[1,4,7:9] *}
+
+### Згенерувати схему OpenAPI { #generate-the-openapi-schema }
+
+Далі використайте ту ж утилітарну функцію для генерації схеми OpenAPI всередині функції `custom_openapi()`:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[2,15:21] *}
+
+### Змінити схему OpenAPI { #modify-the-openapi-schema }
+
+Тепер можна додати розширення ReDoc, додавши власний `x-logo` до «об'єкта» `info` у схемі OpenAPI:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[22:24] *}
+
+### Кешувати схему OpenAPI { #cache-the-openapi-schema }
+
+Ви можете використовувати властивість `.openapi_schema` як «кеш» для збереження згенерованої схеми.
+
+Так вашому застосунку не доведеться щоразу генерувати схему, коли користувач відкриває документацію вашого API.
+
+Вона буде згенерована лише один раз, а потім та сама закешована схема використовуватиметься для наступних запитів.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[13:14,25:26] *}
+
+### Переписати метод { #override-the-method }
+
+Тепер ви можете замінити метод `.openapi()` вашою новою функцією.
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[29] *}
+
+### Перевірте { #check-it }
+
+Коли ви перейдете за адресою [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc), побачите, що використовується ваш власний логотип (у цьому прикладі логотип **FastAPI**):
+
+
diff --git a/docs/uk/docs/how-to/general.md b/docs/uk/docs/how-to/general.md
new file mode 100644
index 0000000000000..75761dff5346a
--- /dev/null
+++ b/docs/uk/docs/how-to/general.md
@@ -0,0 +1,43 @@
+# Загальне - Як зробити - Рецепти { #general-how-to-recipes }
+
+Нижче наведено кілька вказівок до інших розділів документації для загальних або частих питань.
+
+## Фільтрування даних - Безпека { #filter-data-security }
+
+Щоб гарантувати, що ви не повертаєте більше даних, ніж слід, прочитайте документацію [Навчальний посібник - Модель відповіді - Тип повернення](../tutorial/response-model.md).
+
+## Оптимізувати продуктивність відповіді - Модель відповіді - Тип повернення { #optimize-response-performance-response-model-return-type }
+
+Щоб оптимізувати продуктивність під час повернення даних JSON, використовуйте тип повернення або модель відповіді, таким чином Pydantic виконуватиме серіалізацію в JSON на боці Rust, без проходження через Python. Докладніше читайте в документації [Навчальний посібник - Модель відповіді - Тип повернення](../tutorial/response-model.md).
+
+## Мітки документації - OpenAPI { #documentation-tags-openapi }
+
+Щоб додати мітки до ваших *операцій шляху* та згрупувати їх в інтерфейсі документації, прочитайте документацію [Навчальний посібник - Налаштування операції шляху - Мітки](../tutorial/path-operation-configuration.md#tags).
+
+## Короткий опис і опис - OpenAPI { #documentation-summary-and-description-openapi }
+
+Щоб додати короткий опис і опис до ваших *операцій шляху* і показати їх в інтерфейсі документації, прочитайте документацію [Навчальний посібник - Налаштування операції шляху - Короткий опис і опис](../tutorial/path-operation-configuration.md#summary-and-description).
+
+## Опис відповіді в документації - OpenAPI { #documentation-response-description-openapi }
+
+Щоб визначити опис відповіді, що відображається в інтерфейсі документації, прочитайте документацію [Навчальний посібник - Налаштування операції шляху - Опис відповіді](../tutorial/path-operation-configuration.md#response-description).
+
+## Позначити застарілою *операцію шляху* - OpenAPI { #documentation-deprecate-a-path-operation-openapi }
+
+Щоб позначити *операцію шляху* як застарілу і показати це в інтерфейсі документації, прочитайте документацію [Навчальний посібник - Налаштування операції шляху - Позначення як застаріле](../tutorial/path-operation-configuration.md#deprecate-a-path-operation).
+
+## Перетворити будь-які дані на сумісні з JSON { #convert-any-data-to-json-compatible }
+
+Щоб перетворити будь-які дані на сумісні з JSON, прочитайте документацію [Навчальний посібник - Кодувальник, сумісний з JSON](../tutorial/encoder.md).
+
+## Метадані OpenAPI - Документація { #openapi-metadata-docs }
+
+Щоб додати метадані до вашої схеми OpenAPI, зокрема ліцензію, версію, контактні дані тощо, прочитайте документацію [Навчальний посібник - Метадані та URL документації](../tutorial/metadata.md).
+
+## Власний URL OpenAPI { #openapi-custom-url }
+
+Щоб налаштувати URL OpenAPI (або прибрати його), прочитайте документацію [Навчальний посібник - Метадані та URL документації](../tutorial/metadata.md#openapi-url).
+
+## URL документації OpenAPI { #openapi-docs-urls }
+
+Щоб оновити URL, які використовуються для автоматично згенерованих інтерфейсів користувача документації, прочитайте документацію [Навчальний посібник - Метадані та URL документації](../tutorial/metadata.md#docs-urls).
diff --git a/docs/uk/docs/how-to/graphql.md b/docs/uk/docs/how-to/graphql.md
new file mode 100644
index 0000000000000..c070c7e0cd6ca
--- /dev/null
+++ b/docs/uk/docs/how-to/graphql.md
@@ -0,0 +1,60 @@
+# GraphQL { #graphql }
+
+Оскільки FastAPI базується на стандарті ASGI, дуже просто інтегрувати будь-яку бібліотеку GraphQL, сумісну з ASGI.
+
+Ви можете поєднувати звичайні *операції шляху* FastAPI з GraphQL в одному застосунку.
+
+/// tip | Порада
+
+GraphQL розв’язує деякі дуже специфічні сценарії використання.
+
+Порівняно зі звичайними веб-API він має переваги та недоліки.
+
+Переконайтеся, що переваги для вашого випадку використання переважають недоліки. 🤓
+
+///
+
+## Бібліотеки GraphQL { #graphql-libraries }
+
+Ось деякі бібліотеки GraphQL з підтримкою ASGI. Ви можете використовувати їх із FastAPI:
+
+* [Strawberry](https://strawberry.rocks/) 🍓
+ * З [документацією для FastAPI](https://strawberry.rocks/docs/integrations/fastapi)
+* [Ariadne](https://ariadnegraphql.org/)
+ * З [документацією для FastAPI](https://ariadnegraphql.org/docs/fastapi-integration)
+* [Tartiflette](https://tartiflette.io/)
+ * З [Tartiflette ASGI](https://tartiflette.github.io/tartiflette-asgi/) для інтеграції з ASGI
+* [Graphene](https://graphene-python.org/)
+ * З [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3)
+
+## GraphQL зі Strawberry { #graphql-with-strawberry }
+
+Якщо вам потрібен або ви хочете використовувати GraphQL, [Strawberry](https://strawberry.rocks/) - рекомендована бібліотека, адже її дизайн найближчий до дизайну FastAPI; усе базується на анотаціях типів.
+
+Залежно від вашого сценарію використання ви можете надати перевагу іншій бібліотеці, але якби ви запитали мене, я, ймовірно, порадив би спробувати Strawberry.
+
+Ось невеликий приклад того, як інтегрувати Strawberry з FastAPI:
+
+{* ../../docs_src/graphql_/tutorial001_py310.py hl[3,22,25] *}
+
+Більше про Strawberry ви можете дізнатися в [документації Strawberry](https://strawberry.rocks/).
+
+І також [документацію про Strawberry з FastAPI](https://strawberry.rocks/docs/integrations/fastapi).
+
+## Застарілий `GraphQLApp` зі Starlette { #older-graphqlapp-from-starlette }
+
+Попередні версії Starlette містили клас `GraphQLApp` для інтеграції з [Graphene](https://graphene-python.org/).
+
+Його вилучено з Starlette як застарілий, але якщо у вас є код, що його використовував, ви можете легко мігрувати на [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3), який покриває той самий сценарій використання та має майже ідентичний інтерфейс.
+
+/// tip | Порада
+
+Якщо вам потрібен GraphQL, я все ж рекомендую звернути увагу на [Strawberry](https://strawberry.rocks/), адже він базується на анотаціях типів, а не на власних класах і типах.
+
+///
+
+## Дізнайтеся більше { #learn-more }
+
+Ви можете дізнатися більше про GraphQL в [офіційній документації GraphQL](https://graphql.org/).
+
+Також ви можете почитати більше про кожну з цих бібліотек за наведеними посиланнями.
diff --git a/docs/uk/docs/how-to/index.md b/docs/uk/docs/how-to/index.md
new file mode 100644
index 0000000000000..db72181a357db
--- /dev/null
+++ b/docs/uk/docs/how-to/index.md
@@ -0,0 +1,13 @@
+# Як зробити - Рецепти { #how-to-recipes }
+
+Тут ви побачите різні рецепти або керівництва «як зробити» з **різних тем**.
+
+Більшість із цих ідей є більш-менш **незалежними**, і в більшості випадків вам слід вивчати їх лише тоді, коли вони безпосередньо стосуються **вашого проєкту**.
+
+Якщо щось здається цікавим і корисним для вашого проєкту, сміливо перевірте це, інакше, ймовірно, просто пропустіть.
+
+/// tip | Порада
+
+Якщо ви хочете **вивчити FastAPI** у структурований спосіб (рекомендується), натомість прочитайте [Навчальний посібник - Посібник користувача](../tutorial/index.md) розділ за розділом.
+
+///
diff --git a/docs/uk/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/uk/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
new file mode 100644
index 0000000000000..c5519b98d8de6
--- /dev/null
+++ b/docs/uk/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -0,0 +1,135 @@
+# Перехід з Pydantic v1 на Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 }
+
+Якщо у вас стара програма FastAPI, можливо, ви використовуєте Pydantic версії 1.
+
+FastAPI версії 0.100.0 підтримував як Pydantic v1, так і v2. Використовувалася та версія, яку ви встановили.
+
+FastAPI версії 0.119.0 запровадив часткову підтримку Pydantic v1 всередині Pydantic v2 (як `pydantic.v1`), щоб спростити перехід на v2.
+
+FastAPI 0.126.0 припинив підтримку Pydantic v1, водночас ще певний час підтримував `pydantic.v1`.
+
+/// warning | Попередження
+
+Команда Pydantic припинила підтримку Pydantic v1 для останніх версій Python, починаючи з Python 3.14.
+
+Це стосується і `pydantic.v1`, який більше не підтримується в Python 3.14 і новіших.
+
+Якщо ви хочете використовувати найновіші можливості Python, вам потрібно переконатися, що ви використовуєте Pydantic v2.
+
+///
+
+Якщо у вас стара програма FastAPI з Pydantic v1, нижче я покажу, як мігрувати на Pydantic v2, а також можливості FastAPI 0.119.0, які допоможуть з поступовою міграцією.
+
+## Офіційний посібник { #official-guide }
+
+У Pydantic є офіційний [Посібник з міграції](https://docs.pydantic.dev/latest/migration/) з v1 на v2.
+
+Там описано, що змінилося, як перевірки тепер стали коректнішими та суворішими, можливі застереження тощо.
+
+Прочитайте його, щоб краще зрозуміти зміни.
+
+## Тести { #tests }
+
+Переконайтеся, що у вашій програмі є [тести](../tutorial/testing.md) і що ви запускаєте їх у системі безперервної інтеграції (CI).
+
+Так ви зможете виконати оновлення і впевнитися, що все працює як очікується.
+
+## `bump-pydantic` { #bump-pydantic }
+
+У багатьох випадках, якщо ви використовуєте звичайні моделі Pydantic без налаштувань, більшу частину процесу міграції з Pydantic v1 на Pydantic v2 можна автоматизувати.
+
+Ви можете скористатися [`bump-pydantic`](https://github.com/pydantic/bump-pydantic) від тієї ж команди Pydantic.
+
+Цей інструмент допоможе автоматично змінити більшість коду, який потрібно змінити.
+
+Після цього запустіть тести й перевірте, чи все працює. Якщо так - ви все завершили. 😎
+
+## Pydantic v1 у v2 { #pydantic-v1-in-v2 }
+
+Pydantic v2 містить усе з Pydantic v1 як підмодуль `pydantic.v1`. Але це більше не підтримується у версіях Python вище 3.13.
+
+Це означає, що ви можете встановити останню версію Pydantic v2 та імпортувати і використовувати старі компоненти Pydantic v1 з цього підмодуля, ніби у вас встановлено старий Pydantic v1.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}
+
+### Підтримка FastAPI для Pydantic v1 у v2 { #fastapi-support-for-pydantic-v1-in-v2 }
+
+Починаючи з FastAPI 0.119.0, також є часткова підтримка Pydantic v1 всередині Pydantic v2, щоб спростити перехід на v2.
+
+Тож ви можете оновити Pydantic до останньої версії 2 і змінити імпорти на використання підмодуля `pydantic.v1`, і в багатьох випадках усе просто запрацює.
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py hl[2,5,15] *}
+
+/// warning | Попередження
+
+Майте на увазі, що оскільки команда Pydantic більше не підтримує Pydantic v1 у нових версіях Python, починаючи з Python 3.14, використання `pydantic.v1` також не підтримується в Python 3.14 і новіших.
+
+///
+
+### Pydantic v1 і v2 в одній програмі { #pydantic-v1-and-v2-on-the-same-app }
+
+Pydantic не підтримує ситуацію, коли модель Pydantic v2 має власні поля, визначені як моделі Pydantic v1, або навпаки.
+
+```mermaid
+graph TB
+ subgraph "❌ Not Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+...але в одній програмі ви можете мати окремі моделі на Pydantic v1 і v2.
+
+```mermaid
+graph TB
+ subgraph "✅ Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+У деяких випадках можна навіть використовувати моделі і Pydantic v1, і v2 в одній операції шляху у вашій програмі FastAPI:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}
+
+У наведеному вище прикладі вхідна модель - це модель Pydantic v1, а вихідна модель (визначена як `response_model=ItemV2`) - модель Pydantic v2.
+
+### Параметри Pydantic v1 { #pydantic-v1-parameters }
+
+Якщо вам потрібно використовувати деякі специфічні для FastAPI інструменти для параметрів, як-от `Body`, `Query`, `Form` тощо, з моделями Pydantic v1, ви можете імпортувати їх з `fastapi.temp_pydantic_v1_params`, поки завершуєте міграцію на Pydantic v2:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py hl[4,18] *}
+
+### Покрокова міграція { #migrate-in-steps }
+
+/// tip | Порада
+
+Спершу спробуйте `bump-pydantic`: якщо ваші тести проходять і все працює - ви впоралися однією командою. ✨
+
+///
+
+Якщо `bump-pydantic` не підходить для вашого випадку, скористайтеся підтримкою одночасно Pydantic v1 і v2 в одній програмі, щоб виконати поступову міграцію на Pydantic v2.
+
+Спочатку ви можете оновити Pydantic до останньої версії 2 і змінити імпорти на `pydantic.v1` для всіх ваших моделей.
+
+Потім починайте переносити моделі з Pydantic v1 на v2 групами, поступовими кроками. 🚶
diff --git a/docs/uk/docs/how-to/separate-openapi-schemas.md b/docs/uk/docs/how-to/separate-openapi-schemas.md
new file mode 100644
index 0000000000000..7e6fcbf5f99b2
--- /dev/null
+++ b/docs/uk/docs/how-to/separate-openapi-schemas.md
@@ -0,0 +1,101 @@
+# Окремі схеми OpenAPI для введення та виведення, чи ні { #separate-openapi-schemas-for-input-and-output-or-not }
+
+Відколи вийшов **Pydantic v2**, згенерований OpenAPI став трохи точнішим і більш коректним, ніж раніше. 😎
+
+Насправді подекуди буде навіть **дві схеми JSON** в OpenAPI для тієї самої моделі Pydantic: для введення та для виведення - залежно від наявності значень за замовчуванням.
+
+Розгляньмо, як це працює, і як це змінити за потреби.
+
+## Моделі Pydantic для введення та виведення { #pydantic-models-for-input-and-output }
+
+Припустімо, у вас є модель Pydantic зі значеннями за замовчуванням, наприклад:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *}
+
+### Модель для введення { #model-for-input }
+
+Якщо ви використовуєте цю модель як введення, як тут:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *}
+
+…тоді поле `description` не буде обов'язковим, адже воно має значення за замовчуванням `None`.
+
+### Модель для введення в документації { #input-model-in-docs }
+
+У документації ви побачите, що поле `description` не має **червоної зірочки** - воно не позначене як обов'язкове:
+
+
+
+
+
+
++ Фреймворк FastAPI - це висока продуктивність, легко вивчати, швидко писати код, готовий до продакшину +
+ + +--- + +**Документація**: [https://fastapi.tiangolo.com](https://fastapi.tiangolo.com/uk) + +**Вихідний код**: [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi) + +--- + +FastAPI - це сучасний, швидкий (високопродуктивний) вебфреймворк для створення API за допомогою Python, що базується на стандартних підказках типів Python. + +Ключові особливості: + +* **Швидкий**: дуже висока продуктивність, на рівні з **NodeJS** та **Go** (завдяки Starlette та Pydantic). [Один із найшвидших Python-фреймворків](#performance). +* **Швидке написання коду**: пришвидшує розробку функціоналу приблизно на 200%–300%. * +* **Менше помилок**: зменшує приблизно на 40% кількість помилок, спричинених людиною (розробником). * +* **Інтуїтивний**: чудова підтримка редакторами коду. Автодоповнення всюди. Менше часу на налагодження. +* **Простий**: спроєктований так, щоб бути простим у використанні та вивченні. Менше часу на читання документації. +* **Короткий**: мінімізує дублювання коду. Кілька можливостей з кожного оголошення параметра. Менше помилок. +* **Надійний**: ви отримуєте код, готовий до продакшину. З автоматичною інтерактивною документацією. +* **Заснований на стандартах**: базується на (і повністю сумісний з) відкритими стандартами для API: [OpenAPI](https://github.com/OAI/OpenAPI-Specification) (раніше відомий як Swagger) та [JSON Schema](https://json-schema.org/). + +* оцінка на основі тестів, проведених внутрішньою командою розробників, що створює продакшн-застосунки. + +## Спонсори { #sponsors } + + + +### Ключовий спонсор { #keystone-sponsor } + +{% for sponsor in sponsors.keystone -%} +
+
+## **Typer**, FastAPI для CLI { #typer-the-fastapi-of-clis }
+
+async def...fastapi dev...
-### Додайте типи
+### Додайте типи { #add-types }
Давайте змінимо один рядок з попередньої версії.
@@ -77,11 +76,9 @@ John Doe
Ось і все.
-Це "type hints":
+Це «підказки типів»:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
Це не те саме, що оголошення значень за замовчуванням, як це було б з:
@@ -91,45 +88,41 @@ John Doe
Це зовсім інше.
-Ми використовуємо двокрапку (`:`), не дорівнює (`=`).
+Ми використовуємо двокрапку (`:`), не знак дорівнює (`=`).
-І додавання анотації типу зазвичай не змінює того, що сталось би без них.
+І додавання підказок типів зазвичай не змінює того, що відбувається, порівняно з тим, що відбувалося б без них.
-Але тепер, уявіть що ви посеред процесу створення функції, але з анотаціями типів.
+Але тепер уявіть, що ви знову посеред процесу створення функції, але з підказками типів.
-В цей же момент, ви спробуєте викликати автозаповнення з допомогою `Ctrl+Space` і побачите:
+У той самий момент ви спробуєте викликати автозаповнення за допомогою `Ctrl+Space` і побачите:
-Разом з цим, ви можете прокручувати, переглядати опції, допоки ви не знайдете одну, що звучить схоже:
+Разом з цим ви можете прокручувати, переглядаючи опції, допоки не знайдете ту, що «щось вам підказує»:
-## Більше мотивації
+## Більше мотивації { #more-motivation }
-Перевірте цю функцію, вона вже має анотацію типу:
+Перевірте цю функцію, вона вже має підказки типів:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
Оскільки редактор знає типи змінних, ви не тільки отримаєте автозаповнення, ви також отримаєте перевірку помилок:
-Тепер ви знаєте, щоб виправити це, вам потрібно перетворити `age` у строку з допомогою `str(age)`:
+Тепер ви знаєте, щоб виправити це, вам потрібно перетворити `age` у строку за допомогою `str(age)`:
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
-## Оголошення типів
+## Оголошення типів { #declaring-types }
-Щойно ви побачили основне місце для оголошення анотацій типу. Як параметри функції.
+Щойно ви побачили основне місце для оголошення підказок типів. Як параметри функції.
Це також основне місце, де ви б їх використовували у **FastAPI**.
-### Прості типи
+### Прості типи { #simple-types }
Ви можете оголошувати усі стандартні типи у Python, не тільки `str`.
@@ -140,69 +133,54 @@ John Doe
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
-```
-
-### Generic-типи з параметрами типів
-
-Існують деякі структури даних, які можуть містити інші значення, наприклад `dict`, `list`, `set` та `tuple`. І внутрішні значення також можуть мати свій тип.
-
-Ці типи, які мають внутрішні типи, називаються "**generic**" типами. І оголосити їх можна навіть із внутрішніми типами.
-
-Щоб оголосити ці типи та внутрішні типи, ви можете використовувати стандартний модуль Python `typing`. Він існує спеціально для підтримки анотацій типів.
-
-#### Новіші версії Python
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
-Синтаксис із використанням `typing` **сумісний** з усіма версіями, від Python 3.6 до останніх, включаючи Python 3.9, Python 3.10 тощо.
+### Модуль `typing` { #typing-module }
-У міру розвитку Python **новіші версії** мають покращену підтримку анотацій типів і в багатьох випадках вам навіть не потрібно буде імпортувати та використовувати модуль `typing` для оголошення анотацій типу.
+Для деяких додаткових випадків використання може знадобитися імпортувати елементи зі стандартної бібліотеки, модуля `typing`. Наприклад, коли ви хочете оголосити, що щось має «будь-який тип», ви можете використати `Any` з `typing`:
-Якщо ви можете вибрати новішу версію Python для свого проекту, ви зможете скористатися цією додатковою простотою. Дивіться кілька прикладів нижче.
+```python
+from typing import Any
-#### List (список)
-Наприклад, давайте визначимо змінну, яка буде `list` із `str`.
+def some_function(data: Any):
+ print(data)
+```
-=== "Python 3.6 і вище"
+### Generic типи { #generic-types }
- З модуля `typing`, імпортуємо `List` (з великої літери `L`):
+Деякі типи можуть приймати «параметри типів» у квадратних дужках, щоб визначити їх внутрішні типи. Наприклад, «list строк» буде оголошений як `list[str]`.
- ``` Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+Ці типи, які можуть приймати параметри типів, називаються **generic типами** або **generics**.
- Оголосимо змінну з тим самим синтаксисом двокрапки (`:`).
+Ви можете використовувати ті самі вбудовані типи як generics (з квадратними дужками та типами всередині):
- Як тип вкажемо `List`, який ви імпортували з `typing`.
+* `list`
+* `tuple`
+* `set`
+* `dict`
- Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки:
+#### List { #list }
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
+Наприклад, давайте визначимо змінну, яка буде `list` із `str`.
-=== "Python 3.9 і вище"
+Оголосіть змінну з тим самим синтаксисом двокрапки (`:`).
- Оголосимо змінну з тим самим синтаксисом двокрапки (`:`).
+Як тип вкажіть `list`.
- Як тип вкажемо `list`.
+Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки:
- Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки:
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
+/// info | Інформація
-!!! info
- Ці внутрішні типи в квадратних дужках називаються "параметрами типу".
+Ці внутрішні типи в квадратних дужках називаються «параметрами типу».
- У цьому випадку, `str` це параметр типу переданий у `List` (або `list` у Python 3.9 і вище).
+У цьому випадку `str` — це параметр типу, переданий у `list`.
-Це означає: "змінна `items` це `list`, і кожен з елементів у цьому списку - `str`".
+///
-!!! tip
- Якщо ви використовуєте Python 3.9 і вище, вам не потрібно імпортувати `List` з `typing`, ви можете використовувати натомість тип `list`.
+Це означає: «змінна `items` — це `list`, і кожен з елементів у цьому списку — `str`».
Зробивши це, ваш редактор може надати підтримку навіть під час обробки елементів зі списку:
@@ -214,219 +192,138 @@ John Doe
І все ж редактор знає, що це `str`, і надає підтримку для цього.
-#### Tuple and Set (кортеж та набір)
+#### Tuple and Set { #tuple-and-set }
Ви повинні зробити те ж саме, щоб оголосити `tuple` і `set`:
-=== "Python 3.6 і вище"
-
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
-
-=== "Python 3.9 і вище"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
Це означає:
-* Змінна `items_t` це `tuple` з 3 елементами, `int`, ще `int`, та `str`.
-* Змінна `items_s` це `set`, і кожен його елемент типу `bytes`.
+* Змінна `items_t` — це `tuple` з 3 елементами: `int`, ще `int`, та `str`.
+* Змінна `items_s` — це `set`, і кожен його елемент має тип `bytes`.
-#### Dict (словник)
+#### Dict { #dict }
Щоб оголосити `dict`, вам потрібно передати 2 параметри типу, розділені комами.
-Перший параметр типу для ключа у `dict`.
-
-Другий параметр типу для значення у `dict`:
-
-=== "Python 3.6 і вище"
+Перший параметр типу для ключів у `dict`.
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
+Другий параметр типу для значень у `dict`:
-=== "Python 3.9 і вище"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
Це означає:
-* Змінна `prices` це `dict`:
- * Ключі цього `dict` типу `str` (наприклад, назва кожного елементу).
- * Значення цього `dict` типу `float` (наприклад, ціна кожного елементу).
-
-#### Union (об'єднання)
-
-Ви можете оголосити, що змінна може бути будь-яким із **кількох типів**, наприклад, `int` або `str`.
-
-У Python 3.6 і вище (включаючи Python 3.10) ви можете використовувати тип `Union` з `typing` і вставляти в квадратні дужки можливі типи, які можна прийняти.
+* Змінна `prices` — це `dict`:
+ * Ключі цього `dict` мають тип `str` (скажімо, назва кожного предмета).
+ * Значення цього `dict` мають тип `float` (скажімо, ціна кожного предмета).
-У Python 3.10 також є **альтернативний синтаксис**, у якому ви можете розділити можливі типи за допомогою вертикальної смуги (`|`).
+#### Union { #union }
-=== "Python 3.6 і вище"
+Ви можете оголосити, що змінна може бути будь-яким із **кількох типів**, наприклад `int` або `str`.
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
- ```
+Щоб визначити це, використовуйте вертикальну риску (`|`), щоб розділити обидва типи.
-=== "Python 3.10 і вище"
+Це називається «union», тому що змінна може бути чимось із об’єднання цих двох множин типів.
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
+```
-В обох випадках це означає, що `item` може бути `int` або `str`.
+Це означає, що `item` може бути `int` або `str`.
-#### Possibly `None` (Optional)
+#### Можливо `None` { #possibly-none }
Ви можете оголосити, що значення може мати тип, наприклад `str`, але також може бути `None`.
-У Python 3.6 і вище (включаючи Python 3.10) ви можете оголосити його, імпортувавши та використовуючи `Optional` з модуля `typing`.
+//// tab | Python 3.10+
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
```
-Використання `Optional[str]` замість просто `str` дозволить редактору допомогти вам виявити помилки, коли ви могли б вважати, що значенням завжди є `str`, хоча насправді воно також може бути `None`.
-
-`Optional[Something]` насправді є скороченням для `Union[Something, None]`, вони еквівалентні.
+////
-Це також означає, що в Python 3.10 ви можете використовувати `Something | None`:
+Використання `str | None` замість просто `str` дозволить редактору допомогти вам виявити помилки, коли ви могли б вважати, що значенням завжди є `str`, хоча насправді воно також може бути `None`.
-=== "Python 3.6 і вище"
+### Класи як типи { #classes-as-types }
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
- ```
-
-=== "Python 3.6 і вище - альтернатива"
-
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
-
-=== "Python 3.10 і вище"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
-
-#### Generic типи
-
-Ці типи, які приймають параметри типу у квадратних дужках, називаються **Generic types** or **Generics**, наприклад:
-
-=== "Python 3.6 і вище"
-
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ...та інші.
-
-=== "Python 3.9 і вище"
+Ви також можете оголосити клас як тип змінної.
- Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині):
+Скажімо, у вас є клас `Person` з імʼям:
- * `list`
- * `tuple`
- * `set`
- * `dict`
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
- І те саме, що й у Python 3.6, із модуля `typing`:
+Потім ви можете оголосити змінну типу `Person`:
- * `Union`
- * `Optional`
- * ...та інші.
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
-=== "Python 3.10 і вище"
+І знову ж таки, ви отримуєте всю підтримку редактора:
- Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині):
+
- * `list`
- * `tuple`
- * `set`
- * `dict`
+Зверніть увагу, що це означає: «`one_person` — це **екземпляр** класу `Person`».
- І те саме, що й у Python 3.6, із модуля `typing`:
+Це не означає: «`one_person` — це **клас** з назвою `Person`».
- * `Union`
- * `Optional` (так само як у Python 3.6)
- * ...та інші.
+## Pydantic моделі { #pydantic-models }
- У Python 3.10, як альтернатива використанню `Union` та `Optional`, ви можете використовувати вертикальну смугу (`|`) щоб оголосити об'єднання типів.
+[Pydantic](https://docs.pydantic.dev/) — це бібліотека Python для валідації даних.
-### Класи як типи
+Ви оголошуєте «форму» даних як класи з атрибутами.
-Ви також можете оголосити клас як тип змінної.
+І кожен атрибут має тип.
-Скажімо, у вас є клас `Person` з імʼям:
+Потім ви створюєте екземпляр цього класу з деякими значеннями, і він перевірить ці значення, перетворить їх у відповідний тип (якщо є потреба) і надасть вам об’єкт з усіма даними.
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+І ви отримуєте всю підтримку редактора з цим отриманим об’єктом.
-Потім ви можете оголосити змінну типу `Person`:
+Приклад з офіційної документації Pydantic:
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+{* ../../docs_src/python_types/tutorial011_py310.py *}
-І знову ж таки, ви отримуєте всю підтримку редактора:
+/// info | Інформація
-
+Щоб дізнатись більше про [Pydantic, перегляньте його документацію](https://docs.pydantic.dev/).
-## Pydantic моделі
+///
-Pydantic це бібліотека Python для валідації даних.
+**FastAPI** повністю базується на Pydantic.
-Ви оголошуєте «форму» даних як класи з атрибутами.
+Ви побачите набагато більше цього всього на практиці в [Навчальний посібник - Посібник користувача](tutorial/index.md).
-І кожен атрибут має тип.
+## Підказки типів з анотаціями метаданих { #type-hints-with-metadata-annotations }
-Потім ви створюєте екземпляр цього класу з деякими значеннями, і він перевірить ці значення, перетворить їх у відповідний тип (якщо є потреба) і надасть вам об’єкт з усіма даними.
+У Python також є можливість додавати **додаткові метадані** до цих підказок типів за допомогою `Annotated`.
-І ви отримуєте всю підтримку редактора з цим отриманим об’єктом.
+Ви можете імпортувати `Annotated` з `typing`.
-Приклад з документації Pydantic:
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
-=== "Python 3.6 і вище"
+Сам Python нічого не робить із цим `Annotated`. А для редакторів та інших інструментів тип усе ще є `str`.
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
+Але ви можете використати це місце в `Annotated`, щоб надати **FastAPI** додаткові метадані про те, як ви хочете, щоб ваш застосунок поводився.
-=== "Python 3.9 і вище"
+Важливо пам’ятати, що **перший *параметр типу***, який ви передаєте в `Annotated`, — це **фактичний тип**. Решта — це лише метадані для інших інструментів.
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
+Наразі вам просто потрібно знати, що `Annotated` існує і що це стандартний Python. 😎
-=== "Python 3.10 і вище"
+Пізніше ви побачите, наскільки **потужним** це може бути.
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
+/// tip | Порада
-!!! info
- Щоб дізнатись більше про Pydantic, перегляньте його документацію.
+Той факт, що це **стандартний Python**, означає, що ви й надалі отримуватимете **найкращий можливий досвід розробки** у вашому редакторі, з інструментами, які ви використовуєте для аналізу та рефакторингу коду тощо. ✨
-**FastAPI** повністю базується на Pydantic.
+А також те, що ваш код буде дуже сумісним із багатьма іншими інструментами та бібліотеками Python. 🚀
-Ви побачите набагато більше цього всього на практиці в [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}.
+///
-## Анотації типів у **FastAPI**
+## Підказки типів у **FastAPI** { #type-hints-in-fastapi }
-**FastAPI** використовує ці підказки для виконання кількох речей.
+**FastAPI** використовує ці підказки типів для виконання кількох речей.
-З **FastAPI** ви оголошуєте параметри з підказками типу, і отримуєте:
+З **FastAPI** ви оголошуєте параметри з підказками типів, і отримуєте:
* **Підтримку редактора**.
* **Перевірку типів**.
@@ -435,14 +332,17 @@ John Doe
* **Визначення вимог**: з параметрів шляху запиту, параметрів запиту, заголовків, тіл, залежностей тощо.
* **Перетворення даних**: із запиту в необхідний тип.
-* **Перевірка даних**: що надходять від кожного запиту:
+* **Перевірки даних**: що надходять від кожного запиту:
* Генерування **автоматичних помилок**, що повертаються клієнту, коли дані недійсні.
* **Документування** API за допомогою OpenAPI:
* який потім використовується для автоматичної інтерактивної документації користувальницьких інтерфейсів.
-Все це може здатися абстрактним. Не хвилюйтеся. Ви побачите все це в дії в [Туторіал - Посібник користувача](tutorial/index.md){.internal-link target=_blank}.
+Все це може здатися абстрактним. Не хвилюйтеся. Ви побачите все це в дії в [Навчальний посібник - Посібник користувача](tutorial/index.md).
Важливо те, що за допомогою стандартних типів Python в одному місці (замість того, щоб додавати більше класів, декораторів тощо), **FastAPI** зробить багато роботи за вас.
-!!! info
- Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс "шпаргалка" від `mypy`.
+/// info | Інформація
+
+Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс: [«шпаргалка» від `mypy`](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html).
+
+///
diff --git a/docs/uk/docs/resources/index.md b/docs/uk/docs/resources/index.md
new file mode 100644
index 0000000000000..353992fad4dc3
--- /dev/null
+++ b/docs/uk/docs/resources/index.md
@@ -0,0 +1,3 @@
+# Ресурси { #resources }
+
+Додаткові ресурси, зовнішні посилання та інше. ✈️
diff --git a/docs/uk/docs/translation-banner.md b/docs/uk/docs/translation-banner.md
new file mode 100644
index 0000000000000..86408039947f0
--- /dev/null
+++ b/docs/uk/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 Переклад ШІ та людьми
+
+Цей переклад виконано ШІ під керівництвом людей. 🤝
+
+Можливі помилки через неправильне розуміння початкового змісту або неприродні формулювання тощо. 🤖
+
+Ви можете покращити цей переклад, [допомігши нам краще спрямовувати AI LLM](https://fastapi.tiangolo.com/uk/contributing/#translations).
+
+[Англійська версія](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/uk/docs/tutorial/background-tasks.md b/docs/uk/docs/tutorial/background-tasks.md
new file mode 100644
index 0000000000000..2894bd2d086a0
--- /dev/null
+++ b/docs/uk/docs/tutorial/background-tasks.md
@@ -0,0 +1,84 @@
+# Фонові задачі { #background-tasks }
+
+Ви можете створювати фонові задачі, які будуть виконуватися після повернення відповіді.
+
+Це корисно для операцій, які потрібно виконати після обробки запиту, але клієнту не обов’язково чекати завершення цієї операції перед отриманням відповіді.
+
+Це включає, наприклад:
+
+* Надсилання email-сповіщень після виконання певної дії:
+ * Підключення до поштового сервера та надсилання листа може займати кілька секунд. Ви можете відразу повернути відповідь, а email-сповіщення надіслати у фоні.
+* Обробка даних:
+ * Наприклад, якщо ви отримали файл, який потрібно обробити довготривалим процесом, можна повернути відповідь «Accepted» (HTTP 202) і виконати обробку файлу у фоні.
+
+## Використання `BackgroundTasks` { #using-backgroundtasks }
+
+Спочатку імпортуйте `BackgroundTasks` і оголосіть параметр у вашій функції операції шляху з анотацією типу `BackgroundTasks`:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
+
+**FastAPI** створить для вас об’єкт типу `BackgroundTasks` і передасть його як цей параметр.
+
+## Створення функції задачі { #create-a-task-function }
+
+Створіть функцію, яка буде виконуватися як фонова задача.
+
+Це звичайна функція, яка може отримувати параметри.
+
+Вона може бути асинхронною `async def` або звичайною `def` функцією – **FastAPI** обробить її правильно.
+
+У нашому випадку функція записує у файл (імітуючи надсилання email).
+
+І оскільки операція запису не використовує `async` та `await`, ми визначаємо функцію як звичайну `def`:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
+
+## Додавання фонової задачі { #add-the-background-task }
+
+Усередині вашої функції операції шляху, передайте функцію задачі в об'єкт background tasks, використовуючи метод `.add_task()`:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
+
+`.add_task()` приймає аргументи:
+
+* Функцію задачі, яка буде виконуватися у фоновому режимі (`write_notification`).
+* Будь-яку послідовність аргументів, які потрібно передати у функцію задачі у відповідному порядку (`email`).
+* Будь-які іменовані аргументи, які потрібно передати у функцію задачі (`message="some notification"`).
+
+## Впровадження залежностей { #dependency-injection }
+
+Використання `BackgroundTasks` також працює з системою впровадження залежностей. Ви можете оголосити параметр типу `BackgroundTasks` на різних рівнях: у функції операції шляху, у залежності (залежний), у підзалежності тощо.
+
+**FastAPI** знає, як діяти в кожному випадку і як повторно використовувати один і той самий об'єкт, щоб усі фонові задачі були об’єднані та виконувалися у фоновому режимі після завершення основного запиту:
+
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
+
+У цьому прикладі повідомлення будуть записані у файл `log.txt` після того, як відповідь буде надіслана.
+
+Якщо у запиті був переданий параметр запиту, він буде записаний у лог у фоновій задачі.
+
+А потім інша фонова задача, згенерована у функції операції шляху, запише повідомлення з використанням параметра шляху `email`.
+
+## Технічні деталі { #technical-details }
+
+Клас `BackgroundTasks` походить безпосередньо з [`starlette.background`](https://www.starlette.dev/background/).
+
+Він імпортується/включається безпосередньо у FastAPI, щоб ви могли імпортувати його з `fastapi` і випадково не імпортували альтернативний `BackgroundTask` (без `s` в кінці) з `starlette.background`.
+
+Якщо використовувати лише `BackgroundTasks` (а не `BackgroundTask`), то його можна передавати як параметр у функції операції шляху, і **FastAPI** подбає про все інше, так само як і про використання об'єкта `Request`.
+
+Також можна використовувати `BackgroundTask` окремо в FastAPI, але для цього вам доведеться створити об'єкт у коді та повернути Starlette `Response`, включаючи його.
+
+Детальніше можна почитати в [офіційній документації Starlette про Background Tasks](https://www.starlette.dev/background/).
+
+## Застереження { #caveat }
+
+Якщо вам потрібно виконувати складні фонові обчислення, і при цьому нема потреби запускати їх у тому ж процесі (наприклад, не потрібно спільного доступу до пам’яті чи змінних), можливо, варто скористатися більш потужними інструментами, такими як [Celery](https://docs.celeryq.dev).
+
+Такі інструменти зазвичай потребують складнішої конфігурації та менеджера черги повідомлень/завдань, наприклад, RabbitMQ або Redis. Однак вони дозволяють виконувати фонові задачі в кількох процесах і особливо — на кількох серверах.
+
+Якщо ж вам потрібно отримати доступ до змінних і об’єктів із тієї ж **FastAPI**-програми або виконувати невеликі фонові завдання (наприклад, надсилати email-сповіщення), достатньо просто використовувати `BackgroundTasks`.
+
+## Підсумок { #recap }
+
+Імпортуйте та використовуйте `BackgroundTasks` як параметри у функціях операції шляху та залежностях, щоб додавати фонові задачі.
diff --git a/docs/uk/docs/tutorial/bigger-applications.md b/docs/uk/docs/tutorial/bigger-applications.md
new file mode 100644
index 0000000000000..7745509ddf380
--- /dev/null
+++ b/docs/uk/docs/tutorial/bigger-applications.md
@@ -0,0 +1,535 @@
+# Більші застосунки - кілька файлів { #bigger-applications-multiple-files }
+
+Якщо ви створюєте застосунок або веб-API, рідко вдається вмістити все в один файл.
+
+**FastAPI** надає зручний інструмент для структурування вашого застосунку, зберігаючи всю гнучкість.
+
+/// info | Інформація
+
+Якщо ви прийшли з Flask, це еквівалент «Blueprints» у Flask.
+
+///
+
+## Приклад структури файлів { #an-example-file-structure }
+
+Припустімо, у вас така структура файлів:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ ├── dependencies.py
+│ └── routers
+│ │ ├── __init__.py
+│ │ ├── items.py
+│ │ └── users.py
+│ └── internal
+│ ├── __init__.py
+│ └── admin.py
+```
+
+/// tip | Порада
+
+Тут кілька файлів `__init__.py`: по одному в кожному каталозі та підкаталозі.
+
+Саме це дозволяє імпортувати код з одного файлу в інший.
+
+Наприклад, у `app/main.py` ви можете мати рядок:
+
+```
+from app.routers import items
+```
+
+///
+
+* Каталог `app` містить усе. І він має порожній файл `app/__init__.py`, тож це «пакет Python» (збірка «модулів Python»): `app`.
+* Він містить файл `app/main.py`. Оскільки він усередині пакета Python (каталог з файлом `__init__.py`), це «модуль» цього пакета: `app.main`.
+* Є також файл `app/dependencies.py`, так само як `app/main.py`, це «модуль»: `app.dependencies`.
+* Є підкаталог `app/routers/` з іншим файлом `__init__.py`, отже це «підпакет Python»: `app.routers`.
+* Файл `app/routers/items.py` знаходиться в пакеті `app/routers/`, отже це підмодуль: `app.routers.items`.
+* Так само і `app/routers/users.py`, це інший підмодуль: `app.routers.users`.
+* Є також підкаталог `app/internal/` з іншим файлом `__init__.py`, отже це інший «підпакет Python»: `app.internal`.
+* І файл `app/internal/admin.py` - ще один підмодуль: `app.internal.admin`.
+
+
+
+## Включайте той самий router кілька разів з різними `prefix` { #include-the-same-router-multiple-times-with-different-prefix }
+
+Ви також можете використовувати `.include_router()` кілька разів з одним і тим самим router'ом, але з різними префіксами.
+
+Це може бути корисно, наприклад, щоб публікувати той самий API під різними префіксами, наприклад `/api/v1` і `/api/latest`.
+
+Це просунуте використання, яке вам може й не знадобитися, але воно є на випадок, якщо потрібно.
+
+## Включіть один `APIRouter` до іншого { #include-an-apirouter-in-another }
+
+Так само як ви можете включити `APIRouter` у застосунок `FastAPI`, ви можете включити `APIRouter` в інший `APIRouter`, використовуючи:
+
+```Python
+router.include_router(other_router)
+```
+
+Переконайтеся, що ви робите це до включення `router` в застосунок `FastAPI`, щоб *операції шляху* з `other_router` також були включені.
diff --git a/docs/uk/docs/tutorial/body-fields.md b/docs/uk/docs/tutorial/body-fields.md
new file mode 100644
index 0000000000000..70d94f3d6e950
--- /dev/null
+++ b/docs/uk/docs/tutorial/body-fields.md
@@ -0,0 +1,61 @@
+# Тіло — Поля { #body-fields }
+
+Так само як ви можете оголошувати додаткову валідацію та метадані в параметрах *функції операції шляху* за допомогою `Query`, `Path` та `Body`, ви можете оголошувати валідацію та метадані всередині моделей Pydantic, використовуючи `Field` від Pydantic.
+
+## Імпорт `Field` { #import-field }
+
+Спочатку вам потрібно імпортувати це:
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}
+
+
+/// warning | Попередження
+
+Зверніть увагу, що `Field` імпортується безпосередньо з `pydantic`, а не з `fastapi`, як усе інше (`Query`, `Path`, `Body` тощо).
+
+///
+
+## Оголошення атрибутів моделі { #declare-model-attributes }
+
+Потім ви можете використовувати `Field` з атрибутами моделі:
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}
+
+`Field` працює так само, як `Query`, `Path` і `Body`, має ті самі параметри тощо.
+
+/// note | Технічні деталі
+
+Насправді `Query`, `Path` та інші, які ви побачите далі, створюють об'єкти підкласів спільного класу `Param`, який сам є підкласом класу `FieldInfo` з Pydantic.
+
+І `Field` від Pydantic також повертає екземпляр `FieldInfo`.
+
+`Body` також безпосередньо повертає об'єкти підкласу `FieldInfo`. І є інші, які ви побачите пізніше, що є підкласами класу `Body`.
+
+Пам'ятайте, що коли ви імпортуєте `Query`, `Path` та інші з `fastapi`, це фактично функції, які повертають спеціальні класи.
+
+///
+
+/// tip | Порада
+
+Зверніть увагу, що кожен атрибут моделі з типом, значенням за замовчуванням і `Field` має ту саму структуру, що й параметр *функції операції шляху*, з `Field` замість `Path`, `Query` і `Body`.
+
+///
+
+## Додавання додаткової інформації { #add-extra-information }
+
+Ви можете оголошувати додаткову інформацію в `Field`, `Query`, `Body` тощо. І вона буде включена до згенерованої JSON Schema.
+
+Ви дізнаєтеся більше про додавання додаткової інформації пізніше в документації, коли вивчатимете, як оголошувати приклади.
+
+/// warning | Попередження
+
+Додаткові ключі, передані в `Field`, також будуть присутні в отриманій схемі OpenAPI для вашого застосунку.
+Оскільки ці ключі не обов'язково є частиною специфікації OpenAPI, деякі інструменти OpenAPI, наприклад [валідатор OpenAPI](https://validator.swagger.io/), можуть не працювати з вашою згенерованою схемою.
+
+///
+
+## Підсумок { #recap }
+
+Ви можете використовувати `Field` від Pydantic, щоб оголошувати додаткову валідацію та метадані для атрибутів моделі.
+
+Ви також можете використовувати додаткові keyword arguments, щоб передавати додаткові метадані JSON Schema.
diff --git a/docs/uk/docs/tutorial/body-multiple-params.md b/docs/uk/docs/tutorial/body-multiple-params.md
new file mode 100644
index 0000000000000..a0db2b1865463
--- /dev/null
+++ b/docs/uk/docs/tutorial/body-multiple-params.md
@@ -0,0 +1,169 @@
+# Тіло - Декілька параметрів { #body-multiple-parameters }
+
+Тепер, коли ми побачили, як використовувати `Path` і `Query`, розгляньмо більш просунуті варіанти оголошення тіла запиту.
+
+## Змішування `Path`, `Query` та параметрів тіла { #mix-path-query-and-body-parameters }
+
+По-перше, звісно, ви можете вільно змішувати оголошення параметрів `Path`, `Query` та тіла запиту, і **FastAPI** знатиме, що робити.
+
+Також ви можете оголошувати параметри тіла як необов’язкові, встановивши для них значення за замовчуванням `None`:
+
+{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
+
+/// note | Примітка
+
+Зверніть увагу, що в цьому випадку параметр `item`, який береться з тіла, є необов'язковим. Оскільки має значення за замовчуванням `None`.
+
+///
+
+## Декілька параметрів тіла { #multiple-body-parameters }
+
+У попередньому прикладi *операції шляху* очікували б JSON-тіло з атрибутами `Item`, наприклад:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+
+Але ви також можете оголосити декілька параметрів тіла, наприклад `item` та `user`:
+
+{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}
+
+
+У цьому випадку **FastAPI** помітить, що у функції є більше ніж один параметр тіла (є два параметри, які є моделями Pydantic).
+
+Тож він використає назви параметрів як ключі (назви полів) у тілі та очікуватиме тіло такого вигляду:
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ }
+}
+```
+
+/// note | Примітка
+
+Зверніть увагу, що хоча `item` оголошено так само, як і раніше, тепер він очікується всередині тіла з ключем `item`.
+
+///
+
+**FastAPI** виконає автоматичне перетворення із запиту, щоб параметр `item` отримав свій конкретний вміст, і те ж саме для `user`.
+
+Він виконає валідацію складених даних і задокументує це таким чином у схемі OpenAPI та в автоматичній документації.
+
+## Одиничні значення в тілі { #singular-values-in-body }
+
+Так само як є `Query` і `Path` для визначення додаткових даних для параметрів запиту та шляху, **FastAPI** надає еквівалентний `Body`.
+
+Наприклад, розширивши попередню модель, ви можете вирішити додати ще один ключ `importance` у те саме тіло, окрім `item` і `user`.
+
+Якщо оголосити його як є, оскільки це одиничне значення, **FastAPI** припустить, що це параметр запиту.
+
+Але ви можете вказати **FastAPI** обробляти його як інший ключ тіла, використовуючи `Body`:
+
+{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
+
+
+У цьому випадку **FastAPI** очікуватиме тіло такого вигляду:
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ },
+ "importance": 5
+}
+```
+
+Знову ж таки, він перетворюватиме типи даних, перевірятиме, документуватиме тощо.
+
+## Декілька параметрів тіла та query { #multiple-body-params-and-query }
+
+Звісно, ви також можете оголошувати додаткові query параметри щоразу, коли це потрібно, додатково до будь-яких параметрів тіла.
+
+Оскільки за замовчуванням одиничні значення інтерпретуються як параметри запиту, вам не потрібно явно додавати `Query`, ви можете просто зробити:
+
+```Python
+q: str | None = None
+```
+
+Наприклад:
+
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
+
+
+/// info | Інформація
+
+`Body` також має всі ті самі додаткові параметри валідації та метаданих, що й `Query`, `Path` та інші, які ви побачите пізніше.
+
+///
+
+## Вбудувати один параметр тіла { #embed-a-single-body-parameter }
+
+Скажімо, у вас є лише один параметр тіла `item` з моделі Pydantic `Item`.
+
+За замовчуванням **FastAPI** очікуватиме його тіло безпосередньо.
+
+Але якщо ви хочете, щоб він очікував JSON з ключем `item`, а всередині нього - вміст моделі, як це відбувається, коли ви оголошуєте додаткові параметри тіла, ви можете використати спеціальний параметр `Body` - `embed`:
+
+```Python
+item: Item = Body(embed=True)
+```
+
+як у прикладі:
+
+{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}
+
+
+У цьому випадку **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
+}
+```
+
+## Підсумок { #recap }
+
+Ви можете додавати кілька параметрів тіла до вашої *функції операції шляху*, навіть якщо запит може мати лише одне тіло.
+
+Але **FastAPI** обробить це, надасть вам правильні дані у функції та перевірить і задокументує правильну схему в *операції шляху*.
+
+Також ви можете оголошувати одиничні значення, щоб отримувати їх як частину тіла.
+
+І ви можете вказати **FastAPI** вбудовувати тіло в ключ, навіть коли оголошено лише один параметр.
diff --git a/docs/uk/docs/tutorial/body-nested-models.md b/docs/uk/docs/tutorial/body-nested-models.md
new file mode 100644
index 0000000000000..97fea36dc5c25
--- /dev/null
+++ b/docs/uk/docs/tutorial/body-nested-models.md
@@ -0,0 +1,221 @@
+# Тіло - Вкладені моделі { #body-nested-models }
+
+З **FastAPI** ви можете визначати, перевіряти, документувати та використовувати моделі, які можуть бути вкладені на будь-яку глибину (завдяки Pydantic).
+
+## Поля списку { #list-fields }
+
+Ви можете визначити атрибут як підтип. Наприклад, Python-список (`list`):
+
+{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}
+
+Це зробить `tags` списком, хоча не визначається тип елементів списку.
+
+## Поля списку з параметром типу { #list-fields-with-type-parameter }
+
+Але Python має специфічний спосіб оголошення списків з внутрішніми типами або «параметрами типу»:
+
+### Оголошення `list` з параметром типу { #declare-a-list-with-a-type-parameter }
+
+Щоб оголосити типи з параметрами типу (внутрішніми типами), такими як `list`, `dict`, `tuple`,
+передайте внутрішні тип(и) як «параметри типу», використовуючи квадратні дужки: `[` та `]`
+
+```Python
+my_list: list[str]
+```
+
+Це стандартний синтаксис Python для оголошення типів.
+
+Використовуйте той самий стандартний синтаксис для атрибутів моделей з внутрішніми типами.
+
+Отже, у нашому прикладі, ми можемо зробити `tags` саме «списком рядків»:
+
+{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}
+
+## Типи множин { #set-types }
+
+Але потім ми подумали, що теги не повинні повторюватися, вони, ймовірно, повинні бути унікальними рядками.
+
+І Python має спеціальний тип даних для множин унікальних елементів — це `set`.
+
+Тому ми можемо оголосити `tags` як множину рядків:
+
+{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}
+
+Навіть якщо ви отримаєте запит з дубльованими даними, він буде перетворений у множину унікальних елементів.
+
+І коли ви будете виводити ці дані, навіть якщо джерело містить дублікати, вони будуть виведені як множина унікальних елементів.
+
+І це буде анотовано/документовано відповідно.
+
+## Вкладені моделі { #nested-models }
+
+Кожен атрибут моделі Pydantic має тип.
+
+Але цей тип сам може бути іншою моделлю Pydantic.
+
+Отже, ви можете оголосити глибоко вкладені JSON «об'єкти» з конкретними іменами атрибутів, типами та перевірками.
+
+Усе це, вкладене без обмежень.
+
+### Визначення підмоделі { #define-a-submodel }
+
+Наприклад, ми можемо визначити модель `Image`:
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}
+
+### Використання підмоделі як типу { #use-the-submodel-as-a-type }
+
+А потім ми можемо використовувати її як тип атрибута:
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}
+
+Це означатиме, що **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** ви отримуєте:
+
+* Підтримку в редакторі (автозавершення тощо), навіть для вкладених моделей
+* Конвертацію даних
+* Валідацію даних
+* Автоматичну документацію
+
+## Спеціальні типи та валідація { #special-types-and-validation }
+
+Окрім звичайних типів, таких як `str`, `int`, `float`, та ін. ви можете використовувати складніші типи, які наслідують `str`.
+
+Щоб побачити всі доступні варіанти, ознайомтеся з [Оглядом типів у Pydantic](https://docs.pydantic.dev/latest/concepts/types/). Деякі приклади будуть у наступному розділі.
+
+Наприклад, у моделі `Image` є поле `url`, тому ми можемо оголосити його як `HttpUrl` від Pydantic замість `str`:
+
+{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}
+
+Рядок буде перевірено як дійсну URL-адресу і задокументовано в JSON Schema / OpenAPI як URL.
+
+## Атрибути зі списками підмоделей { #attributes-with-lists-of-submodels }
+
+У Pydantic ви можете використовувати моделі як підтипи для `list`, `set` тощо:
+
+{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}
+
+Це означає, що **FastAPI** буде очікувати (конвертувати, валідувати, документувати тощо) 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` містить список об'єктів зображень.
+
+///
+
+## Глибоко вкладені моделі { #deeply-nested-models }
+
+Ви можете визначати вкладені моделі довільної глибини:
+
+{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}
+
+/// info | Інформація
+
+Зверніть увагу, що в моделі `Offer` є список `Item`ів, які, своєю чергою, можуть мати необов'язковий список `Image`ів.
+
+///
+
+## Тіла запитів, що складаються зі списків { #bodies-of-pure-lists }
+
+Якщо верхній рівень JSON тіла, яке ви очікуєте, є JSON `масивом` (у Python — `list`), ви можете оголосити тип у параметрі функції, як і в моделях Pydantic:
+
+```Python
+images: list[Image]
+```
+
+наприклад:
+
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
+
+## Підтримка в редакторі всюди { #editor-support-everywhere }
+
+Ви отримаєте підтримку в редакторі всюди.
+
+Навіть для елементів у списках:
+
+
+
+Ви не змогли б отримати таку підтримку в редакторі, якби працювали напряму зі `dict`, а не з моделями Pydantic.
+
+Але вам не потрібно турбуватися про це: вхідні dict'и автоматично конвертуються, а вихідні дані автоматично перетворюються в JSON.
+
+## Тіла з довільними `dict` { #bodies-of-arbitrary-dicts }
+
+Ви також можете оголосити тіло як `dict` з ключами одного типу та значеннями іншого типу.
+
+Це корисно, якщо ви не знаєте наперед, які імена полів будуть дійсними (як у випадку з моделями Pydantic).
+
+Це буде корисно, якщо ви хочете приймати ключі, які заздалегідь невідомі.
+
+---
+
+Це також зручно, якщо ви хочете мати ключі іншого типу (наприклад, `int`).
+
+Ось що ми розглянемо далі.
+
+У цьому випадку ви можете приймати будь-який `dict`, якщо його ключі — це `int`, а значення — `float`:
+
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
+
+/// tip | Порада
+
+Майте на увазі, що в JSON тілі ключі можуть бути лише рядками (`str`).
+
+Але Pydantic автоматично конвертує дані.
+
+Це означає, що навіть якщо клієнти вашого API надсилатимуть ключі у вигляді рядків, якщо вони містять цілі числа, Pydantic конвертує їх і проведе валідацію.
+
+Тобто `dict`, який ви отримаєте як `weights`, матиме ключі типу `int` та значення типу `float`.
+
+///
+
+## Підсумок { #recap }
+
+З **FastAPI** ви маєте максимальну гнучкість завдяки моделям Pydantic, зберігаючи при цьому код простим, коротким та елегантним.
+
+А також отримуєте всі переваги:
+
+* Підтримка в редакторі (автодоповнення всюди!)
+* Конвертація даних (парсинг/серіалізація)
+* Валідація даних
+* Документація схем
+* Автоматичне створення документації
diff --git a/docs/uk/docs/tutorial/body-updates.md b/docs/uk/docs/tutorial/body-updates.md
new file mode 100644
index 0000000000000..082bec1f03397
--- /dev/null
+++ b/docs/uk/docs/tutorial/body-updates.md
@@ -0,0 +1,100 @@
+# Тіло — Оновлення { #body-updates }
+
+## Оновлення із заміною за допомогою `PUT` { #update-replacing-with-put }
+
+Щоб оновити елемент, ви можете використати [HTTP `PUT`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) операцію.
+
+Ви можете використати `jsonable_encoder`, щоб перетворити вхідні дані на такі, які можна зберігати як JSON (наприклад, у NoSQL базі даних). Наприклад, перетворюючи `datetime` у `str`.
+
+{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}
+
+`PUT` використовується для отримання даних, які мають замінити чинні дані.
+
+### Попередження про заміну { #warning-about-replacing }
+
+Це означає, що якщо Ви хочете оновити елемент `bar`, використовуючи `PUT` з тілом:
+
+```Python
+{
+ "name": "Barz",
+ "price": 3,
+ "description": None,
+}
+```
+
+оскільки він не містить вже збереженого атрибута `"tax": 20.2`, модель введення прийме значення за замовчуванням `"tax": 10.5`.
+
+І дані будуть збережені з цим "новим" значенням `tax` = `10.5`.
+
+## Часткові оновлення з `PATCH` { #partial-updates-with-patch }
+
+Ви також можете використовувати операцію [HTTP `PATCH`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) для *часткового* оновлення даних.
+
+Це означає, що Ви можете надіслати лише ті дані, які хочете оновити, залишаючи інші без змін.
+
+/// note | Примітка
+
+`PATCH` менш поширений і менш відомий, ніж `PUT`.
+
+І багато команд використовують лише `PUT`, навіть для часткових оновлень.
+
+Ви **вільні** використовувати їх так, як хочете, **FastAPI** не накладає жодних обмежень.
+
+Але цей посібник показує вам, більш-менш, як їх задумано використовувати.
+
+///
+
+### Використання параметра `exclude_unset` у Pydantic { #using-pydantics-exclude-unset-parameter }
+
+Якщо Ви хочете отримувати часткові оновлення, дуже корисно використовувати параметр `exclude_unset` у `.model_dump()` моделі Pydantic.
+
+Наприклад: `item.model_dump(exclude_unset=True)`.
+
+Це згенерує `dict` лише з тими даними, які були встановлені під час створення моделі `item`, виключаючи значення за замовчуванням.
+
+Тоді Ви можете використовувати це, щоб згенерувати `dict` лише з даними, які були встановлені (надіслані у запиті), пропускаючи значення за замовчуванням:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}
+
+### Використання параметра `update` у Pydantic { #using-pydantics-update-parameter }
+
+Тепер Ви можете створити копію наявної моделі за допомогою `.model_copy()`, і передати параметр `update` з `dict`, який містить дані для оновлення.
+
+Наприклад: `stored_item_model.model_copy(update=update_data)`:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}
+
+### Підсумок часткових оновлень { #partial-updates-recap }
+
+У підсумку, щоб застосувати часткові оновлення, Ви:
+
+* (Опціонально) використовуєте `PATCH` замість `PUT`.
+* Отримуєте збережені дані.
+* Поміщаєте ці дані в модель Pydantic.
+* Генеруєте `dict` без значень за замовчуванням з моделі введення (використовуючи `exclude_unset`).
+ * Таким чином Ви оновите лише ті значення, які були явно задані користувачем, замість того, щоб перезаписувати вже збережені значення значеннями за замовчуванням з вашої моделі.
+* Створюєте копію збереженої моделі, оновлюючи її атрибути отриманими частковими оновленнями (використовуючи параметр `update`).
+* Перетворюєте скопійовану модель на щось, що можна зберегти у вашу БД (наприклад, використовуючи `jsonable_encoder`).
+ * Це можна порівняти з повторним використанням методу `.model_dump()` моделі, але це гарантує (і перетворює) значення у типи даних, які можна перетворити на JSON, наприклад, `datetime` на `str`.
+* Зберігаєте дані у вашу БД.
+* Повертаєте оновлену модель.
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *}
+
+/// tip | Порада
+
+Насправді Ви можете використовувати цю саму техніку і з операцією HTTP `PUT`.
+
+Але приклад тут використовує `PATCH`, тому що він був створений для таких випадків.
+
+///
+
+/// note | Примітка
+
+Зверніть увагу, що модель запиту все ще проходить валідацію.
+
+Тож, якщо Ви хочете отримувати часткові оновлення, які можуть пропускати всі атрибути, Вам потрібно мати модель, де всі атрибути позначені як необов’язкові (зі значеннями за замовчуванням або `None`).
+
+Щоб розрізняти моделі з усіма необов’язковими значеннями для **оновлення** і моделі з обов’язковими значеннями для **створення**, Ви можете скористатись ідеями, описаними у [Додаткові моделі](extra-models.md).
+
+///
diff --git a/docs/uk/docs/tutorial/body.md b/docs/uk/docs/tutorial/body.md
index e78c5de0e3cf2..91c4b42527f66 100644
--- a/docs/uk/docs/tutorial/body.md
+++ b/docs/uk/docs/tutorial/body.md
@@ -1,55 +1,39 @@
-# Тіло запиту
+# Тіло запиту { #request-body }
Коли вам потрібно надіслати дані з клієнта (скажімо, браузера) до вашого API, ви надсилаєте їх як **тіло запиту**.
-Тіло **запиту** — це дані, надіслані клієнтом до вашого API. Тіло **відповіді** — це дані, які ваш API надсилає клієнту.
+Тіло **запиту** - це дані, надіслані клієнтом до вашого API. Тіло **відповіді** - це дані, які ваш API надсилає клієнту.
-Ваш API майже завжди має надсилати тіло **відповіді**. Але клієнтам не обов’язково потрібно постійно надсилати тіла **запитів**.
+Ваш API майже завжди має надсилати тіло **відповіді**. Але клієнтам не обов’язково потрібно постійно надсилати тіла **запитів** — інколи вони лише запитують шлях, можливо з деякими параметрами запиту, але не надсилають тіло.
-Щоб оголосити тіло **запиту**, ви використовуєте Pydantic моделі з усією їх потужністю та перевагами.
+Щоб оголосити тіло **запиту**, ви використовуєте [Pydantic](https://docs.pydantic.dev/) моделі з усією їх потужністю та перевагами.
-!!! info
- Щоб надіслати дані, ви повинні використовувати один із: `POST` (більш поширений), `PUT`, `DELETE` або `PATCH`.
+/// info | Інформація
- Надсилання тіла із запитом `GET` має невизначену поведінку в специфікаціях, проте воно підтримується FastAPI лише для дуже складних/екстремальних випадків використання.
+Щоб надіслати дані, ви повинні використовувати один із: `POST` (більш поширений), `PUT`, `DELETE` або `PATCH`.
- Оскільки це не рекомендується, інтерактивна документація з Swagger UI не відображатиме документацію для тіла запиту під час використання `GET`, і проксі-сервери в середині можуть не підтримувати її.
+Надсилання тіла із запитом `GET` має невизначену поведінку в специфікаціях, проте воно підтримується FastAPI лише для дуже складних/екстремальних випадків використання.
-## Імпортуйте `BaseModel` від Pydantic
+Оскільки це не рекомендується, інтерактивна документація з Swagger UI не відображатиме документацію для тіла запиту під час використання `GET`, і проксі-сервери в середині можуть не підтримувати її.
-Спочатку вам потрібно імпортувати `BaseModel` з `pydantic`:
-
-=== "Python 3.6 і вище"
+///
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+## Імпортуйте `BaseModel` від Pydantic { #import-pydantics-basemodel }
-=== "Python 3.10 і вище"
+Спочатку вам потрібно імпортувати `BaseModel` з `pydantic`:
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+{* ../../docs_src/body/tutorial001_py310.py hl[2] *}
-## Створіть свою модель даних
+## Створіть свою модель даних { #create-your-data-model }
Потім ви оголошуєте свою модель даних як клас, який успадковується від `BaseModel`.
Використовуйте стандартні типи Python для всіх атрибутів:
-=== "Python 3.6 і вище"
-
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
-
-=== "Python 3.10 і вище"
+{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
-Так само, як і при оголошенні параметрів запиту, коли атрибут моделі має значення за замовчуванням, він не є обов’язковим. В іншому випадку це потрібно. Використовуйте `None`, щоб зробити його необов'язковим.
+Так само, як і при оголошенні параметрів запиту, коли атрибут моделі має значення за замовчуванням, він не є обов’язковим. В іншому випадку це потрібно. Використовуйте `None`, щоб зробити його просто необов'язковим.
Наприклад, ця модель вище оголошує JSON "`об'єкт`" (або Python `dict`), як:
@@ -71,25 +55,15 @@
}
```
-## Оголоси її як параметр
+## Оголосіть її як параметр { #declare-it-as-a-parameter }
Щоб додати модель даних до вашої *операції шляху*, оголосіть її так само, як ви оголосили параметри шляху та запиту:
-=== "Python 3.6 і вище"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
-
-=== "Python 3.10 і вище"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+{* ../../docs_src/body/tutorial001_py310.py hl[16] *}
...і вкажіть її тип як модель, яку ви створили, `Item`.
-## Результати
+## Результати { #results }
Лише з цим оголошенням типу Python **FastAPI** буде:
@@ -99,10 +73,10 @@
* Якщо дані недійсні, він поверне гарну та чітку помилку, вказуючи, де саме і які дані були неправильними.
* Надавати отримані дані у параметрі `item`.
* Оскільки ви оголосили його у функції як тип `Item`, ви також матимете всю підтримку редактора (автозаповнення, тощо) для всіх атрибутів та їх типів.
-* Генерувати JSON Schema визначення для вашої моделі, ви також можете використовувати їх де завгодно, якщо це має сенс для вашого проекту.
-* Ці схеми будуть частиною згенерованої схеми OpenAPI і використовуватимуться автоматичною документацією інтерфейсу користувача.
+* Генерувати визначення [Схеми JSON](https://json-schema.org) для вашої моделі, ви також можете використовувати їх де завгодно, якщо це має сенс для вашого проекту.
+* Ці схеми будуть частиною згенерованої схеми OpenAPI і використовуватимуться автоматичною документацією UIs.
-## Автоматична документація
+## Автоматична документація { #automatic-docs }
Схеми JSON ваших моделей будуть частиною вашої схеми, згенерованої OpenAPI, і будуть показані в інтерактивній API документації:
@@ -112,7 +86,7 @@
-## Підтримка редактора
+## Підтримка редактора { #editor-support }
У вашому редакторі, всередині вашої функції, ви будете отримувати підказки типу та завершення скрізь (це б не сталося, якби ви отримали `dict` замість моделі Pydantic):
@@ -128,86 +102,65 @@
Були навіть деякі зміни в самому Pydantic, щоб підтримати це.
-Попередні скріншоти були зроблені у Visual Studio Code.
+Попередні скріншоти були зроблені у [Visual Studio Code](https://code.visualstudio.com).
-Але ви отримаєте ту саму підтримку редактора у PyCharm та більшість інших редакторів Python:
+Але ви отримаєте ту саму підтримку редактора у [PyCharm](https://www.jetbrains.com/pycharm/) та більшість інших редакторів Python:
-!!! tip
- Якщо ви використовуєте PyCharm як ваш редактор, ви можете використати Pydantic PyCharm Plugin.
+/// tip | Порада
- Він покращує підтримку редакторів для моделей Pydantic за допомогою:
+Якщо ви використовуєте [PyCharm](https://www.jetbrains.com/pycharm/) як ваш редактор, ви можете використати [Pydantic PyCharm Plugin](https://github.com/koxudaxi/pydantic-pycharm-plugin/).
- * автозаповнення
- * перевірки типу
- * рефакторингу
- * пошуку
- * інспекції
+Він покращує підтримку редакторів для моделей Pydantic за допомогою:
-## Використовуйте модель
-
-Усередині функції ви можете отримати прямий доступ до всіх атрибутів об’єкта моделі:
+* автозаповнення
+* перевірки типу
+* рефакторингу
+* пошуку
+* інспекції
-=== "Python 3.6 і вище"
+///
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+## Використовуйте модель { #use-the-model }
-=== "Python 3.10 і вище"
+Усередині функції ви можете отримати прямий доступ до всіх атрибутів об’єкта моделі:
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+{* ../../docs_src/body/tutorial002_py310.py *}
-## Тіло запиту + параметри шляху
+## Тіло запиту + параметри шляху { #request-body-path-parameters }
Ви можете одночасно оголошувати параметри шляху та тіло запиту.
**FastAPI** розпізнає, що параметри функції, які відповідають параметрам шляху, мають бути **взяті з шляху**, а параметри функції, які оголошуються як моделі Pydantic, **взяті з тіла запиту**.
-=== "Python 3.6 і вище"
-
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
-
-=== "Python 3.10 і вище"
+{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
-## Тіло запиту + шлях + параметри запиту
+## Тіло запиту + шлях + параметри запиту { #request-body-path-query-parameters }
Ви також можете оголосити параметри **тіло**, **шлях** і **запит** одночасно.
**FastAPI** розпізнає кожен з них і візьме дані з потрібного місця.
-=== "Python 3.6 і вище"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
-
-=== "Python 3.10 і вище"
-
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
+{* ../../docs_src/body/tutorial004_py310.py hl[16] *}
Параметри функції будуть розпізнаватися наступним чином:
* Якщо параметр також оголошено в **шляху**, він використовуватиметься як параметр шляху.
* Якщо параметр має **сингулярний тип** (наприклад, `int`, `float`, `str`, `bool` тощо), він буде інтерпретуватися як параметр **запиту**.
-* Якщо параметр оголошується як тип **Pydantic моделі**, він інтерпретується як **тіло** запиту.
+* Якщо параметр оголошується як тип **Pydantic моделі**, він інтерпретується як **тіло** **запиту**.
+
+/// note | Примітка
+
+FastAPI буде знати, що значення `q` не є обов'язковим через значення за замовчуванням `= None`.
+
+`str | None` FastAPI не використовує, щоб визначити, що значення не є обов’язковим - він знатиме, що воно не є обов’язковим, тому що має значення за замовчуванням `= None`.
-!!! note
- FastAPI буде знати, що значення "q" не є обов'язковим через значення за замовчуванням "= None".
+Але додавання анотацій типів дозволить вашому редактору надати вам кращу підтримку та виявляти помилки.
- `Optional` у `Optional[str]` не використовується FastAPI, але дозволить вашому редактору надати вам кращу підтримку та виявляти помилки.
+///
-## Без Pydantic
+## Без Pydantic { #without-pydantic }
-Якщо ви не хочете використовувати моделі Pydantic, ви також можете використовувати параметри **Body**. Перегляньте документацію для [Тіло – Кілька параметрів: сингулярні значення в тілі](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}.
+Якщо ви не хочете використовувати моделі Pydantic, ви також можете використовувати параметри **Body**. Перегляньте документацію для [Тіло - Кілька параметрів: Окремі значення в тілі](body-multiple-params.md#singular-values-in-body).
diff --git a/docs/uk/docs/tutorial/cookie-param-models.md b/docs/uk/docs/tutorial/cookie-param-models.md
new file mode 100644
index 0000000000000..dab57c5365ad2
--- /dev/null
+++ b/docs/uk/docs/tutorial/cookie-param-models.md
@@ -0,0 +1,76 @@
+# Моделі параметрів Cookie { #cookie-parameter-models }
+
+Якщо у вас є група **cookies**, які пов'язані між собою, ви можете створити **Pydantic-модель**, щоб оголосити їх. 🍪
+
+Це дозволить вам повторно **використовувати модель** у **різних місцях**, а також оголосити валідацію та метадані для всіх параметрів одночасно. 😎
+
+/// note | Примітка
+
+Це підтримується з версії FastAPI `0.115.0`. 🤓
+
+///
+
+/// tip | Порада
+
+Ця ж техніка застосовується до `Query`, `Cookie` та `Header`. 😎
+
+///
+
+## Cookie з Pydantic-моделлю { #cookies-with-a-pydantic-model }
+
+Оголосіть **cookie**-параметри, які вам потрібні, у **Pydantic-моделі**, а потім оголосіть параметр як `Cookie`:
+
+{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}
+
+**FastAPI** буде **витягувати** дані для **кожного поля** з **cookies**, отриманих у запиті, і передавати вам Pydantic-модель, яку ви визначили.
+
+## Перевірка у документації { #check-the-docs }
+
+Ви можете побачити визначені cookies в інтерфейсі документації за адресою `/docs`:
+
+
+
+
+---
+
+Якщо ви використовуєте PyCharm, ви можете:
+
+* Відкрити меню «Run».
+* Вибрати опцію «Debug...».
+* Потім з'явиться контекстне меню.
+* Вибрати файл для налагодження (у цьому випадку, `main.py`).
+
+Після цього він запустить сервер з вашим кодом **FastAPI**, зупиниться на точках зупину тощо.
+
+Ось як це може виглядати:
+
+
diff --git a/docs/uk/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/uk/docs/tutorial/dependencies/classes-as-dependencies.md
new file mode 100644
index 0000000000000..e64f90ae24277
--- /dev/null
+++ b/docs/uk/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -0,0 +1,288 @@
+# Класи як залежності { #classes-as-dependencies }
+
+Перш ніж заглибитися у систему **впровадження залежностей**, оновімо попередній приклад.
+
+## `dict` з попереднього прикладу { #a-dict-from-the-previous-example }
+
+У попередньому прикладі ми повертали `dict` із нашого «залежного»:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *}
+
+Але тоді ми отримуємо `dict` у параметрі `commons` функції операції шляху.
+
+І ми знаємо, що редактори не можуть надати багато підтримки (наприклад, автодоповнення) для `dict`, адже вони не знають їхніх ключів і типів значень.
+
+Можна зробити краще…
+
+## Що робить об’єкт залежністю { #what-makes-a-dependency }
+
+Дотепер ви бачили залежності, оголошені як функції.
+
+Але це не єдиний спосіб оголошувати залежності (хоча, ймовірно, найпоширеніший).
+
+Ключовий момент у тому, що залежність має бути «викликаємим».
+
+«Викликаємий» у Python - це будь-що, що Python може «викликати», як функцію.
+
+Отже, якщо у вас є об’єкт `something` (який може й не бути функцією) і ви можете «викликати» його (виконати) так:
+
+```Python
+something()
+```
+
+або
+
+```Python
+something(some_argument, some_keyword_argument="foo")
+```
+
+тоді це «викликаємий».
+
+## Класи як залежності { #classes-as-dependencies_1 }
+
+Ви могли помітити, що для створення екземпляра класу 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`:
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *}
+
+Зверніть увагу на метод `__init__`, який використовують для створення екземпляра класу:
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *}
+
+…він має ті самі параметри, що й наш попередній `common_parameters`:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *}
+
+Саме ці параметри **FastAPI** використає, щоб «розв’язати» залежність.
+
+В обох випадках буде:
+
+- Необов’язковий параметр запиту `q`, який є `str`.
+- Параметр запиту `skip`, який є `int`, зі значенням за замовчуванням `0`.
+- Параметр запиту `limit`, який є `int`, зі значенням за замовчуванням `100`.
+
+В обох випадках дані будуть перетворені, перевірені й задокументовані в схемі OpenAPI тощо.
+
+## Використання { #use-it }
+
+Тепер ви можете оголосити залежність, використовуючи цей клас.
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *}
+
+**FastAPI** викликає клас `CommonQueryParams`. Це створює «екземпляр» цього класу, і цей екземпляр буде передано як параметр `commons` у вашу функцію.
+
+## Анотація типів проти `Depends` { #type-annotation-vs-depends }
+
+Зверніть увагу, що вище ми двічі пишемо `CommonQueryParams`:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | Порада
+
+Надавайте перевагу варіанту з `Annotated`, якщо це можливо.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+Останній `CommonQueryParams` у:
+
+```Python
+... Depends(CommonQueryParams)
+```
+
+ - це те, що **FastAPI** фактично використає, щоб дізнатися, яка залежність.
+
+Саме з нього **FastAPI** витягне оголошені параметри і саме його **FastAPI** буде викликати.
+
+---
+
+У цьому випадку перший `CommonQueryParams` у:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, ...
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | Порада
+
+Надавайте перевагу варіанту з `Annotated`, якщо це можливо.
+
+///
+
+```Python
+commons: CommonQueryParams ...
+```
+
+////
+
+…не має жодного особливого значення для **FastAPI**. FastAPI не використовуватиме його для перетворення даних, перевірки тощо (адже для цього використовується `Depends(CommonQueryParams)`).
+
+Насправді ви могли б написати просто:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[Any, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | Порада
+
+Надавайте перевагу варіанту з `Annotated`, якщо це можливо.
+
+///
+
+```Python
+commons = Depends(CommonQueryParams)
+```
+
+////
+
+…як у:
+
+{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *}
+
+Але оголошувати тип рекомендується - так ваш редактор знатиме, що буде передано в параметр `commons`, і зможе допомагати з автодоповненням, перевірками типів тощо:
+
+
+
+## Скорочення { #shortcut }
+
+Але ви бачите, що тут маємо деяке дублювання коду - `CommonQueryParams` пишемо двічі:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | Порада
+
+Надавайте перевагу варіанту з `Annotated`, якщо це можливо.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+**FastAPI** надає скорочення для таких випадків, коли залежність - це саме клас, який **FastAPI** «викличе», щоб створити екземпляр цього класу.
+
+Для таких випадків ви можете зробити так:
+
+Замість того щоб писати:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | Порада
+
+Надавайте перевагу варіанту з `Annotated`, якщо це можливо.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+…напишіть:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | Порада
+
+Надавайте перевагу варіанту з `Annotated`, якщо це можливо.
+
+///
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
+
+Ви оголошуєте залежність як тип параметра і використовуєте `Depends()` без параметрів, замість того щоб вдруге писати повний клас усередині `Depends(CommonQueryParams)`.
+
+Той самий приклад виглядатиме так:
+
+{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *}
+
+…і **FastAPI** знатиме, що робити.
+
+/// tip | Порада
+
+Якщо це здається заплутанішим, ніж корисним, просто не використовуйте це - воно не є обов’язковим.
+
+Це лише скорочення. Адже **FastAPI** дбає про мінімізацію дублювання коду.
+
+///
diff --git a/docs/uk/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/uk/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
new file mode 100644
index 0000000000000..a82461c8dc15a
--- /dev/null
+++ b/docs/uk/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -0,0 +1,69 @@
+# Залежності в декораторах операцій шляху { #dependencies-in-path-operation-decorators }
+
+Іноді вам насправді не потрібне значення, яке повертає залежність, у вашій *функції операції шляху*.
+
+Або залежність узагалі не повертає значення.
+
+Але її все одно потрібно виконати/опрацювати.
+
+Для таких випадків, замість оголошення параметра *функції операції шляху* з `Depends`, ви можете додати `list` `dependencies` до *декоратора операції шляху*.
+
+## Додайте `dependencies` до *декоратора операції шляху* { #add-dependencies-to-the-path-operation-decorator }
+
+*Декоратор операції шляху* приймає необов'язковий аргумент `dependencies`.
+
+Це має бути `list` з `Depends()`:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
+
+Ці залежності будуть виконані/оброблені так само, як звичайні залежності. Але їхні значення (якщо щось повертають) не передаватимуться у вашу *функцію операції шляху*.
+
+/// tip | Порада
+
+Деякі редактори перевіряють невикористані параметри функцій і показують їх як помилки.
+
+Використовуючи ці `dependencies` у *декораторі операції шляху*, ви можете гарантувати їх виконання та водночас уникнути помилок редактора/інструментів.
+
+Це також може допомогти уникнути плутанини для нових розробників, які бачать невикористаний параметр у вашому коді й можуть вирішити, що він зайвий.
+
+///
+
+/// info | Інформація
+
+У цьому прикладі ми використовуємо вигадані власні заголовки `X-Key` і `X-Token`.
+
+Але в реальних випадках, під час впровадження безпеки, ви отримаєте більше користі, використовуючи вбудовані [Інструменти безпеки (наступний розділ)](../security/index.md).
+
+///
+
+## Помилки залежностей і значення, що повертаються { #dependencies-errors-and-return-values }
+
+Ви можете використовувати ті самі *функції* залежностей, що й зазвичай.
+
+### Вимоги залежностей { #dependency-requirements }
+
+Вони можуть оголошувати вимоги до запиту (наприклад, заголовки) або інші підзалежності:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
+
+### Підіймати винятки { #raise-exceptions }
+
+Ці залежності можуть `raise` винятки, так само як і звичайні залежності:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
+
+### Значення, що повертаються { #return-values }
+
+Вони можуть повертати значення або ні - ці значення не використовуватимуться.
+
+Отже, ви можете перевикористати звичайну залежність (яка повертає значення), яку вже застосовуєте деінде, і навіть якщо значення не буде використано, залежність буде виконана:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
+
+## Залежності для групи операцій шляху { #dependencies-for-a-group-of-path-operations }
+
+Далі, читаючи про структурування великих застосунків ([Більші застосунки - декілька файлів](../../tutorial/bigger-applications.md)), можливо з кількома файлами, ви дізнаєтеся, як оголосити один параметр `dependencies` для групи *операцій шляху*.
+
+## Глобальні залежності { #global-dependencies }
+
+Далі ми побачимо, як додати залежності до всього застосунку `FastAPI`, щоб вони застосовувалися до кожної *операції шляху*.
diff --git a/docs/uk/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/uk/docs/tutorial/dependencies/dependencies-with-yield.md
new file mode 100644
index 0000000000000..53b49e61b6d45
--- /dev/null
+++ b/docs/uk/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -0,0 +1,289 @@
+# Залежності з yield { #dependencies-with-yield }
+
+FastAPI підтримує залежності, які виконують деякі додаткові кроки після завершення.
+
+Щоб це зробити, використовуйте `yield` замість `return` і напишіть додаткові кроки (код) після нього.
+
+/// tip | Порада
+
+Переконайтесь, що ви використовуєте `yield` лише один раз на залежність.
+
+///
+
+/// note | Технічні деталі
+
+Будь-яка функція, яку можна використовувати з:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) або
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+буде придатною як залежність у **FastAPI**.
+
+Насправді FastAPI використовує ці два декоратори внутрішньо.
+
+///
+
+## Залежність бази даних з `yield` { #a-database-dependency-with-yield }
+
+Наприклад, ви можете використати це, щоб створити сесію бази даних і закрити її після завершення.
+
+Перед створенням відповіді виконується лише код до і включно з оператором `yield`:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
+
+Значення, передане `yield`, впроваджується в *операції шляху* та інші залежності:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
+
+Код після оператора `yield` виконується після відповіді:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
+
+/// tip | Порада
+
+Можете використовувати як `async`, так і звичайні функції.
+
+**FastAPI** зробить усе правильно з кожною з них, так само як і зі звичайними залежностями.
+
+///
+
+## Залежність з `yield` та `try` { #a-dependency-with-yield-and-try }
+
+Якщо ви використовуєте блок `try` в залежності з `yield`, ви отримаєте будь-який виняток, який був згенерований під час використання залежності.
+
+Наприклад, якщо якийсь код десь посередині, в іншій залежності або в *операції шляху*, зробив «rollback» транзакції бази даних або створив будь-який інший виняток, ви отримаєте цей виняток у своїй залежності.
+
+Тож ви можете обробити цей конкретний виняток усередині залежності за допомогою `except SomeException`.
+
+Так само ви можете використовувати `finally`, щоб гарантувати виконання завершальних кроків незалежно від того, був виняток чи ні.
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
+
+## Підзалежності з `yield` { #sub-dependencies-with-yield }
+
+Ви можете мати підзалежності та «дерева» підзалежностей будь-якого розміру і форми, і будь-яка або всі з них можуть використовувати `yield`.
+
+**FastAPI** гарантує, що «exit code» у кожній залежності з `yield` буде виконано в правильному порядку.
+
+Наприклад, `dependency_c` може залежати від `dependency_b`, а `dependency_b` - від `dependency_a`:
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
+
+І всі вони можуть використовувати `yield`.
+
+У цьому випадку `dependency_c`, щоб виконати свій завершальний код, потребує, щоб значення з `dependency_b` (тут `dep_b`) все ще було доступним.
+
+І, у свою чергу, `dependency_b` потребує, щоб значення з `dependency_a` (тут `dep_a`) було доступним для свого завершального коду.
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
+
+Так само ви можете мати деякі залежності з `yield`, а інші - з `return`, і частина з них може залежати від інших.
+
+І ви можете мати одну залежність, яка вимагає кілька інших залежностей з `yield` тощо.
+
+Ви можете мати будь-які комбінації залежностей, які вам потрібні.
+
+**FastAPI** подбає, щоб усе виконувалося в правильному порядку.
+
+/// note | Технічні деталі
+
+Це працює завдяки Python [Менеджерам контексту](https://docs.python.org/3/library/contextlib.html).
+
+**FastAPI** використовує їх внутрішньо, щоб досягти цього.
+
+///
+
+## Залежності з `yield` та `HTTPException` { #dependencies-with-yield-and-httpexception }
+
+Ви бачили, що можна використовувати залежності з `yield` і мати блоки `try`, які намагаються виконати деякий код, а потім запускають завершальний код після `finally`.
+
+Також можна використовувати `except`, щоб перехопити згенерований виняток і щось із ним зробити.
+
+Наприклад, ви можете підняти інший виняток, як-от `HTTPException`.
+
+/// tip | Порада
+
+Це доволі просунута техніка, і в більшості випадків вона вам не знадобиться, адже ви можете піднімати винятки (включно з `HTTPException`) всередині іншого коду вашого застосунку, наприклад, у *функції операції шляху*.
+
+Але вона є, якщо вам це потрібно. 🤓
+
+///
+
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
+
+Якщо ви хочете перехоплювати винятки та створювати на їх основі користувацьку відповідь, створіть [Користувацький обробник винятків](../handling-errors.md#install-custom-exception-handlers).
+
+## Залежності з `yield` та `except` { #dependencies-with-yield-and-except }
+
+Якщо ви перехоплюєте виняток за допомогою `except` у залежності з `yield` і не піднімаєте його знову (або не піднімаєте новий виняток), FastAPI не зможе помітити, що стався виняток, так само як це було б у звичайному Python:
+
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
+
+У цьому випадку клієнт побачить відповідь *HTTP 500 Internal Server Error*, як і має бути, з огляду на те, що ми не піднімаємо `HTTPException` або подібний виняток, але на сервері **не буде жодних логів** чи інших ознак того, що це була за помилка. 😱
+
+### Завжди використовуйте `raise` у залежностях з `yield` та `except` { #always-raise-in-dependencies-with-yield-and-except }
+
+Якщо ви перехоплюєте виняток у залежності з `yield`, якщо тільки ви не піднімаєте інший `HTTPException` або подібний, **вам слід повторно підняти початковий виняток**.
+
+Ви можете повторно підняти той самий виняток, використовуючи `raise`:
+
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
+
+Тепер клієнт отримає ту саму відповідь *HTTP 500 Internal Server Error*, але сервер матиме наш користувацький `InternalError` у логах. 😎
+
+## Виконання залежностей з `yield` { #execution-of-dependencies-with-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,operation: Can raise exceptions, including HTTPException
+ client ->> dep: Start request
+ Note over dep: Run code up to yield
+ opt raise Exception
+ dep -->> handler: Raise Exception
+ handler -->> client: HTTP error response
+ end
+ dep ->> operation: Run dependency, e.g. DB session
+ opt raise
+ operation -->> dep: Raise Exception (e.g. HTTPException)
+ opt handle
+ dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception
+ end
+ handler -->> client: HTTP error response
+ 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 -->> tasks: Handle exceptions in the background task code
+ end
+```
+
+/// info | Інформація
+
+Лише **одна відповідь** буде надіслана клієнту. Це може бути одна з помилкових відповідей або відповідь від *операції шляху*.
+
+Після відправлення однієї з цих відповідей іншу відправити не можна.
+
+///
+
+/// tip | Порада
+
+Якщо ви піднімаєте будь-який виняток у коді з *функції операції шляху*, він буде переданий у залежності з `yield`, включно з `HTTPException`. У більшості випадків ви захочете повторно підняти той самий виняток або новий із залежності з `yield`, щоб переконатися, що його коректно оброблено.
+
+///
+
+## Ранній вихід і `scope` { #early-exit-and-scope }
+
+Зазвичай завершальний код залежностей з `yield` виконується **після того**, як відповідь надіслано клієнту.
+
+Але якщо ви знаєте, що вам не потрібно використовувати залежність після повернення з *функції операції шляху*, ви можете використати `Depends(scope="function")`, щоб сказати FastAPI, що слід закрити залежність після повернення з *функції операції шляху*, але **до** надсилання **відповіді**.
+
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
+
+`Depends()` приймає параметр `scope`, який може бути:
+
+* `"function"`: запустити залежність перед *функцією операції шляху*, що обробляє запит, завершити залежність після завершення *функції операції шляху*, але **до** того, як відповідь буде відправлена клієнту. Тобто функція залежності буде виконуватися **навколо** *функції операції **шляху***.
+* `"request"`: запустити залежність перед *функцією операції шляху*, що обробляє запит (подібно до `"function"`), але завершити **після** того, як відповідь буде відправлена клієнту. Тобто функція залежності буде виконуватися **навколо** циклу **запиту** та відповіді.
+
+Якщо не вказано, і залежність має `yield`, за замовчуванням `scope` дорівнює `"request"`.
+
+### `scope` для підзалежностей { #scope-for-sub-dependencies }
+
+Коли ви оголошуєте залежність із `scope="request"` (за замовчуванням), будь-яка підзалежність також має мати `scope` рівний `"request"`.
+
+Але залежність з `scope` рівним `"function"` може мати залежності з `scope` `"function"` і `scope` `"request"`.
+
+Це тому, що будь-яка залежність має бути здатною виконати свій завершальний код раніше за підзалежності, оскільки вона може все ще потребувати їх під час свого завершального коду.
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant dep_req as Dep scope="request"
+participant dep_func as Dep scope="function"
+participant operation as Path Operation
+
+ client ->> dep_req: Start request
+ Note over dep_req: Run code up to yield
+ dep_req ->> dep_func: Pass dependency
+ Note over dep_func: Run code up to yield
+ dep_func ->> operation: Run path operation with dependency
+ operation ->> dep_func: Return from path operation
+ Note over dep_func: Run code after yield
+ Note over dep_func: ✅ Dependency closed
+ dep_func ->> client: Send response to client
+ Note over client: Response sent
+ Note over dep_req: Run code after yield
+ Note over dep_req: ✅ Dependency closed
+```
+
+## Залежності з `yield`, `HTTPException`, `except` і фоновими задачами { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+Залежності з `yield` еволюціонували з часом, щоб покрити різні сценарії та виправити деякі проблеми.
+
+Якщо ви хочете дізнатися, що змінювалося в різних версіях FastAPI, прочитайте про це в просунутому посібнику користувача: [Розширені залежності - Залежності з `yield`, `HTTPException`, `except` і фоновими задачами](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks).
+## Менеджери контексту { #context-managers }
+
+### Що таке «Менеджери контексту» { #what-are-context-managers }
+
+«Менеджери контексту» - це будь-які Python-об'єкти, які можна використовувати в операторі `with`.
+
+Наприклад, [можна використати `with`, щоб прочитати файл](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files):
+
+```Python
+with open("./somefile.txt") as f:
+ contents = f.read()
+ print(contents)
+```
+
+Під капотом `open("./somefile.txt")` створює об'єкт, який називається «Менеджер контексту».
+
+Коли блок `with` завершується, він гарантує закриття файлу, навіть якщо були винятки.
+
+Коли ви створюєте залежність з `yield`, **FastAPI** внутрішньо створить для неї менеджер контексту й поєднає його з іншими пов'язаними інструментами.
+
+### Використання менеджерів контексту в залежностях з `yield` { #using-context-managers-in-dependencies-with-yield }
+
+/// warning | Попередження
+
+Це, загалом, «просунута» ідея.
+
+Якщо ви тільки починаєте з **FastAPI**, можливо, варто наразі пропустити це.
+
+///
+
+У Python ви можете створювати Менеджери контексту, [створивши клас із двома методами: `__enter__()` і `__exit__()`](https://docs.python.org/3/reference/datamodel.html#context-managers).
+
+Ви також можете використовувати їх усередині залежностей **FastAPI** з `yield`, використовуючи
+`with` або `async with` у середині функції залежності:
+
+{* ../../docs_src/dependencies/tutorial010_py310.py hl[1:9,13] *}
+
+/// tip | Порада
+
+Інший спосіб створити менеджер контексту:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) або
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+використовуючи їх для декорування функції з одним `yield`.
+
+Саме це **FastAPI** використовує внутрішньо для залежностей з `yield`.
+
+Але вам не потрібно використовувати ці декоратори для залежностей FastAPI (і не варто).
+
+FastAPI зробить це за вас внутрішньо.
+
+///
diff --git a/docs/uk/docs/tutorial/dependencies/global-dependencies.md b/docs/uk/docs/tutorial/dependencies/global-dependencies.md
new file mode 100644
index 0000000000000..da8b08cdff9f2
--- /dev/null
+++ b/docs/uk/docs/tutorial/dependencies/global-dependencies.md
@@ -0,0 +1,15 @@
+# Глобальні залежності { #global-dependencies }
+
+Для деяких типів застосунків ви можете захотіти додати залежності до всього застосунку.
+
+Подібно до того, як ви можете [додавати `dependencies` до *декораторів операцій шляху*](dependencies-in-path-operation-decorators.md), ви можете додати їх до застосунку `FastAPI`.
+
+У такому разі вони будуть застосовані до всіх *операцій шляху* в застосунку:
+
+{* ../../docs_src/dependencies/tutorial012_an_py310.py hl[17] *}
+
+Усі ідеї з розділу про [додавання `dependencies` до *декораторів операцій шляху*](dependencies-in-path-operation-decorators.md) так само застосовні, але в цьому випадку - до всіх *операцій шляху* в застосунку.
+
+## Залежності для груп *операцій шляху* { #dependencies-for-groups-of-path-operations }
+
+Пізніше, читаючи про структуру більших застосунків ([Більші застосунки - кілька файлів](../../tutorial/bigger-applications.md)), можливо з кількома файлами, ви дізнаєтеся, як оголосити єдиний параметр `dependencies` для групи *операцій шляху*.
diff --git a/docs/uk/docs/tutorial/dependencies/index.md b/docs/uk/docs/tutorial/dependencies/index.md
new file mode 100644
index 0000000000000..bea5f598d6c90
--- /dev/null
+++ b/docs/uk/docs/tutorial/dependencies/index.md
@@ -0,0 +1,250 @@
+# Залежності { #dependencies }
+
+**FastAPI** має дуже потужну, але інтуїтивну систему **Впровадження залежностей**.
+
+Вона створена так, щоб бути дуже простою у використанні та щоб полегшити будь-якому розробнику інтеграцію інших компонентів з **FastAPI**.
+
+## Що таке «Впровадження залежностей» { #what-is-dependency-injection }
+
+У програмуванні **«Впровадження залежностей»** означає, що існує спосіб для вашого коду (у цьому випадку ваших *функцій операцій шляху*) задекларувати речі, які йому потрібні для роботи: «залежності».
+
+А потім ця система (у цьому випадку **FastAPI**) подбає про все необхідне, щоб надати вашому коду ці потрібні залежності («інжектувати» залежності).
+
+Це дуже корисно, коли вам потрібно:
+
+* Мати спільну логіку (одна й та сама логіка знову і знову).
+* Ділитися з’єднаннями з базою даних.
+* Примусово застосовувати безпеку, автентифікацію, вимоги до ролей тощо.
+* І багато іншого...
+
+Все це з мінімізацією дублювання коду.
+
+## Перші кроки { #first-steps }
+
+Розгляньмо дуже простий приклад. Він буде таким простим, що поки що не дуже корисним.
+
+Але так ми зможемо зосередитися на тому, як працює система **Впровадження залежностей**.
+
+### Створіть залежність або «залежний» { #create-a-dependency-or-dependable }
+
+Спочатку зосередьмося на залежності.
+
+Це просто функція, яка може приймати ті самі параметри, що й *функція операції шляху*:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}
+
+Ось і все.
+
+**2 рядки**.
+
+І вона має ту саму форму та структуру, що й усі ваші *функції операцій шляху*.
+
+Можете думати про неї як про *функцію операції шляху* без «декоратора» (без `@app.get("/some-path")`).
+
+І вона може повертати будь-що.
+
+У цьому випадку ця залежність очікує:
+
+* Необов’язковий параметр запиту `q` типу `str`.
+* Необов’язковий параметр запиту `skip` типу `int`, за замовчуванням `0`.
+* Необов’язковий параметр запиту `limit` типу `int`, за замовчуванням `100`.
+
+Потім вона просто повертає `dict`, що містить ці значення.
+
+/// info | Інформація
+
+FastAPI додав підтримку `Annotated` (і почав її рекомендувати) у версії 0.95.0.
+
+Якщо у вас старіша версія, ви отримаєте помилки при спробі використати `Annotated`.
+
+Переконайтеся, що ви [Оновіть версію FastAPI](../../deployment/versions.md#upgrading-the-fastapi-versions) щонайменше до 0.95.1 перед використанням `Annotated`.
+
+///
+
+### Імпортуйте `Depends` { #import-depends }
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}
+
+### Оголосіть залежність у «залежному» { #declare-the-dependency-in-the-dependant }
+
+Так само, як ви використовуєте `Body`, `Query` тощо з параметрами вашої *функції операції шляху*, використовуйте `Depends` з новим параметром:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}
+
+Хоча ви використовуєте `Depends` у параметрах вашої функції так само, як `Body`, `Query` тощо, `Depends` працює трохи інакше.
+
+Ви передаєте в `Depends` лише один параметр.
+
+Цей параметр має бути чимось на кшталт функції.
+
+Ви її не викликаєте безпосередньо (не додавайте дужки в кінці), ви просто передаєте її як параметр у `Depends()`.
+
+І ця функція приймає параметри так само, як і *функції операцій шляху*.
+
+/// tip | Порада
+
+У наступному розділі ви побачите, які ще «речі», окрім функцій, можна використовувати як залежності.
+
+///
+
+Щоразу, коли надходить новий запит, **FastAPI** подбає про:
+
+* Виклик вашої функції-залежності («залежного») з правильними параметрами.
+* Отримання результату з вашої функції.
+* Присвоєння цього результату параметру у вашій *функції операції шляху*.
+
+```mermaid
+graph TB
+
+common_parameters(["common_parameters"])
+read_items["/items/"]
+read_users["/users/"]
+
+common_parameters --> read_items
+common_parameters --> read_users
+```
+
+Таким чином ви пишете спільний код один раз, а **FastAPI** подбає про його виклик для ваших *операцій шляху*.
+
+/// check | Перевірте
+
+Зверніть увагу, що вам не потрібно створювати спеціальний клас і передавати його кудись у **FastAPI**, щоб «зареєструвати» його чи щось подібне.
+
+Ви просто передаєте його в `Depends`, і **FastAPI** знає, що робити далі.
+
+///
+
+## Спільне використання залежностей `Annotated` { #share-annotated-dependencies }
+
+У наведених вище прикладах видно невелике **дублювання коду**.
+
+Коли вам потрібно використати залежність `common_parameters()`, доводиться писати весь параметр з анотацією типу та `Depends()`:
+
+```Python
+commons: Annotated[dict, Depends(common_parameters)]
+```
+
+Але оскільки ми використовуємо `Annotated`, ми можемо зберегти це значення `Annotated` у змінній і використовувати його в кількох місцях:
+
+{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}
+
+/// tip | Порада
+
+Це просто стандартний Python, це називається «псевдонім типу» і насправді не є специфічним для **FastAPI**.
+
+Але оскільки **FastAPI** базується на стандартах Python, включно з `Annotated`, ви можете використати цей трюк у своєму коді. 😎
+
+///
+
+Залежності продовжать працювати як очікується, і **найкраще** те, що **інформація про типи буде збережена**, а це означає, що ваш редактор зможе й надалі надавати **автозаповнення**, **помилки в рядку** тощо. Те саме і для інших інструментів, як-от `mypy`.
+
+Це буде особливо корисно у **великій кодовій базі**, де ви використовуєте **одні й ті самі залежності** знову і знову в **багатьох *операціях шляху***.
+
+## Бути `async` чи не бути `async` { #to-async-or-not-to-async }
+
+Оскільки залежності також викликатимуться **FastAPI** (так само, як і ваші *функції операцій шляху*), під час визначення ваших функцій діють ті самі правила.
+
+Ви можете використовувати `async def` або звичайний `def`.
+
+І ви можете оголошувати залежності з `async def` всередині звичайних *функцій операцій шляху* з `def`, або залежності з `def` всередині *функцій операцій шляху* з `async def` тощо.
+
+Це не має значення. **FastAPI** знатиме, що робити.
+
+/// note | Примітка
+
+Якщо ви не впевнені, перегляньте розділ [Async: *"In a hurry?"*](../../async.md#in-a-hurry) про `async` і `await` у документації.
+
+///
+
+## Інтегровано з OpenAPI { #integrated-with-openapi }
+
+Усі декларації запитів, перевірки та вимоги ваших залежностей (і субзалежностей) будуть інтегровані в ту саму схему OpenAPI.
+
+Тож інтерактивна документація також міститиме всю інформацію з цих залежностей:
+
+
+
+## Просте використання { #simple-usage }
+
+Якщо придивитися, *функції операцій шляху* оголошуються для використання щоразу, коли збігаються *шлях* та *операція*, а потім **FastAPI** подбає про виклик функції з правильними параметрами, витягуючи дані із запиту.
+
+Насправді всі (або більшість) вебфреймворків працюють так само.
+
+Ви ніколи не викликаєте ці функції безпосередньо. Їх викликає ваш фреймворк (у цьому випадку **FastAPI**).
+
+За допомогою системи впровадження залежностей ви також можете вказати **FastAPI**, що ваша *функція операції шляху* також «залежить» від чогось, що має бути виконано до вашої *функції операції шляху*, і **FastAPI** подбає про виконання цього та «інжектування» результатів.
+
+Інші поширені терміни для цієї самої ідеї «впровадження залежностей»:
+
+* ресурси
+* провайдери
+* сервіси
+* інжектовані об’єкти
+* компоненти
+
+## Плагіни **FastAPI** { #fastapi-plug-ins }
+
+Інтеграції та «плагіни» можна будувати за допомогою системи **Впровадження залежностей**. Але насправді **немає потреби створювати «плагіни»**, оскільки, використовуючи залежності, можна оголосити безмежну кількість інтеграцій та взаємодій, які стають доступними для ваших *функцій операцій шляху*.
+
+І залежності можна створювати дуже просто та інтуїтивно, що дозволяє вам просто імпортувати потрібні пакунки Python і інтегрувати їх з вашими функціями API за кілька рядків коду, буквально.
+
+Ви побачите приклади цього в наступних розділах, про реляційні та NoSQL бази даних, безпеку тощо.
+
+## Сумісність **FastAPI** { #fastapi-compatibility }
+
+Простота системи впровадження залежностей робить **FastAPI** сумісним з:
+
+* усіма реляційними базами даних
+* NoSQL базами даних
+* зовнішніми пакунками
+* зовнішніми API
+* системами автентифікації та авторизації
+* системами моніторингу використання API
+* системами інжекції даних у відповідь
+* тощо.
+
+## Просто і потужно { #simple-and-powerful }
+
+Хоча ієрархічна система впровадження залежностей дуже проста у визначенні та використанні, вона все ще дуже потужна.
+
+Ви можете визначати залежності, які своєю чергою можуть визначати власні залежності.
+
+Зрештою будується ієрархічне дерево залежностей, і система **Впровадження залежностей** подбає про розв’язання всіх цих залежностей (і їхніх субзалежностей) та надання (інжектування) результатів на кожному кроці.
+
+Наприклад, припустімо, у вас є 4 кінцеві точки API (*операції шляху*):
+
+* `/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** { #integrated-with-openapi_1 }
+
+Усі ці залежності, декларуючи свої вимоги, також додають параметри, перевірки тощо до ваших *операцій шляху*.
+
+**FastAPI** подбає про додавання всього цього до схеми OpenAPI, щоб це відображалося в інтерактивних системах документації.
diff --git a/docs/uk/docs/tutorial/dependencies/sub-dependencies.md b/docs/uk/docs/tutorial/dependencies/sub-dependencies.md
new file mode 100644
index 0000000000000..4e7488086ae39
--- /dev/null
+++ b/docs/uk/docs/tutorial/dependencies/sub-dependencies.md
@@ -0,0 +1,105 @@
+# Підзалежності { #sub-dependencies }
+
+Ви можете створювати залежності, які мають підзалежності.
+
+Вони можуть бути настільки глибокими, наскільки потрібно.
+
+FastAPI подбає про їх розв'язання.
+
+## Перша залежність «dependable» { #first-dependency-dependable }
+
+Можна створити першу залежність («dependable») так:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}
+
+Вона оголошує необов'язковий параметр запиту `q` типу `str`, а потім просто повертає його.
+
+Це досить просто (не дуже корисно), але допоможе зосередитися на тому, як працюють підзалежності.
+
+## Друга залежність, «dependable» і «dependant» { #second-dependency-dependable-and-dependant }
+
+Далі ви можете створити іншу функцію залежності («dependable»), яка водночас оголошує власну залежність (тож вона також є «dependant»):
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}
+
+Зосередьмося на оголошених параметрах:
+
+- Хоча ця функція сама є залежністю («dependable»), вона також оголошує іншу залежність (вона «залежить» від чогось).
+ - Вона залежить від `query_extractor` і присвоює значення, яке він повертає, параметру `q`.
+- Вона також оголошує необов'язкове кукі `last_query` типу `str`.
+ - Якщо користувач не надав параметр запиту `q`, ми використовуємо останній запит, який зберегли раніше в кукі.
+
+## Використання залежності { #use-the-dependency }
+
+Потім ми можемо використати залежність так:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}
+
+/// info | Інформація
+
+Зверніть увагу, що ми оголошуємо лише одну залежність у функції операції шляху — `query_or_cookie_extractor`.
+
+Але 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
+```
+
+## Використання тієї ж залежності кілька разів { #using-the-same-dependency-multiple-times }
+
+Якщо одна з ваших залежностей оголошена кілька разів для однієї операції шляху, наприклад, кілька залежностей мають спільну підзалежність, FastAPI знатиме, що цю підзалежність потрібно викликати лише один раз на запит.
+
+І він збереже повернуте значення у «кеш» і передасть його всім «dependants», яким воно потрібне в цьому конкретному запиті, замість того щоб викликати залежність кілька разів для одного й того ж запиту.
+
+У просунутому сценарії, коли ви знаєте, що залежність має викликатися на кожному кроці (можливо, кілька разів) у межах того самого запиту замість використання «кешованого» значення, ви можете встановити параметр `use_cache=False` при використанні `Depends`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+//// tab | Python 3.10+ без Annotated
+
+/// tip | Порада
+
+Надавайте перевагу версії з `Annotated`, якщо це можливо.
+
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+## Підсумок { #recap }
+
+Попри всі модні терміни, система впровадження залежностей досить проста.
+
+Це просто функції, які виглядають так само, як функції операцій шляху.
+
+Втім вона дуже потужна і дозволяє оголошувати довільно глибоко вкладені «графи» залежностей (дерева).
+
+/// tip | Порада
+
+Усе це може здаватися не надто корисним на простих прикладах.
+
+Але ви побачите, наскільки це корисно, у розділах про **безпеку**.
+
+І також побачите, скільки коду це вам заощадить.
+
+///
diff --git a/docs/uk/docs/tutorial/encoder.md b/docs/uk/docs/tutorial/encoder.md
index d660447b43bba..7bbc45ef7b4ae 100644
--- a/docs/uk/docs/tutorial/encoder.md
+++ b/docs/uk/docs/tutorial/encoder.md
@@ -1,42 +1,35 @@
-# JSON Compatible Encoder
+# JSON-сумісний кодувальник { #json-compatible-encoder }
-Існують випадки, коли вам може знадобитися перетворити тип даних (наприклад, модель Pydantic) в щось сумісне з JSON (наприклад, `dict`, `list`, і т. д.).
+Існують випадки, коли вам може знадобитися перетворити тип даних (наприклад, модель Pydantic) на щось сумісне з JSON (наприклад, `dict`, `list` тощо).
Наприклад, якщо вам потрібно зберегти це в базі даних.
-Для цього, **FastAPI** надає `jsonable_encoder()` функцію.
+Для цього **FastAPI** надає функцію `jsonable_encoder()`.
-## Використання `jsonable_encoder`
+## Використання `jsonable_encoder` { #using-the-jsonable-encoder }
Давайте уявимо, що у вас є база даних `fake_db`, яка приймає лише дані, сумісні з JSON.
Наприклад, вона не приймає об'єкти типу `datetime`, оскільки вони не сумісні з JSON.
-Отже, об'єкт типу `datetime` потрібно перетворити в рядок `str`, який містить дані в ISO форматі.
+Отже, об'єкт типу `datetime` потрібно перетворити на `str`, який містить дані в [форматі ISO](https://en.wikipedia.org/wiki/ISO_8601).
-Тим самим способом ця база даних не прийматиме об'єкт типу Pydantic model (об'єкт з атрибутами), а лише `dict`.
+Так само ця база даних не прийматиме модель Pydantic (об'єкт з атрибутами), а лише `dict`.
Ви можете використовувати `jsonable_encoder` для цього.
-Вона приймає об'єкт, такий як Pydantic model, і повертає його версію, сумісну з JSON:
+Вона приймає об'єкт, такий як модель Pydantic, і повертає його версію, сумісну з JSON:
-=== "Python 3.10+"
+{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *}
- ```Python hl_lines="4 21"
- {!> ../../../docs_src/encoder/tutorial001_py310.py!}
- ```
+У цьому прикладі вона конвертує модель Pydantic у `dict`, а `datetime` у `str`.
-=== "Python 3.6+"
+Результат виклику цієї функції — це щось, що можна кодувати з використанням стандарту Python [`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps).
- ```Python hl_lines="5 22"
- {!> ../../../docs_src/encoder/tutorial001.py!}
- ```
+Вона не повертає великий `str`, який містить дані у форматі JSON (як рядок). Вона повертає стандартну структуру даних Python (наприклад, `dict`) зі значеннями та підзначеннями, які є сумісними з JSON.
-У цьому прикладі вона конвертує Pydantic model у `dict`, а `datetime` у `str`.
+/// note | Примітка
-Результат виклику цієї функції - це щось, що можна кодувати з використанням стандарту Python `json.dumps()`.
+`jsonable_encoder` фактично використовується **FastAPI** внутрішньо для перетворення даних. Проте вона корисна в багатьох інших сценаріях.
-Вона не повертає велику строку `str`, яка містить дані у форматі JSON (як строка). Вона повертає стандартну структуру даних Python (наприклад `dict`) із значеннями та підзначеннями, які є сумісними з JSON.
-
-!!! Примітка
- `jsonable_encoder` фактично використовується **FastAPI** внутрішньо для перетворення даних. Проте вона корисна в багатьох інших сценаріях.
+///
diff --git a/docs/uk/docs/tutorial/extra-data-types.md b/docs/uk/docs/tutorial/extra-data-types.md
index ba75ee627efd1..26d7c306fe989 100644
--- a/docs/uk/docs/tutorial/extra-data-types.md
+++ b/docs/uk/docs/tutorial/extra-data-types.md
@@ -1,13 +1,13 @@
-# Додаткові типи даних
+# Додаткові типи даних { #extra-data-types }
-До цього часу, ви використовували загальнопоширені типи даних, такі як:
+До цього часу ви використовували загальнопоширені типи даних, такі як:
* `int`
* `float`
* `str`
* `bool`
-Але можна також використовувати більш складні типи даних.
+Але ви також можете використовувати більш складні типи даних.
І ви все ще матимете ті ж можливості, які були показані до цього:
@@ -17,30 +17,30 @@
* Валідація даних.
* Автоматична анотація та документація.
-## Інші типи даних
+## Інші типи даних { #other-data-types }
Ось додаткові типи даних для використання:
* `UUID`:
- * Стандартний "Універсальний Унікальний Ідентифікатор", який часто використовується як ідентифікатор у багатьох базах даних та системах.
+ * Стандартний "Універсальний унікальний ідентифікатор", який часто використовується як ID у багатьох базах даних та системах.
* У запитах та відповідях буде представлений як `str`.
* `datetime.datetime`:
* Пайтонівський `datetime.datetime`.
- * У запитах та відповідях буде представлений як `str` в форматі ISO 8601, як: `2008-09-15T15:53:00+05:00`.
+ * У запитах та відповідях буде представлений як `str` у форматі ISO 8601, як: `2008-09-15T15:53:00+05:00`.
* `datetime.date`:
* Пайтонівський `datetime.date`.
- * У запитах та відповідях буде представлений як `str` в форматі ISO 8601, як: `2008-09-15`.
+ * У запитах та відповідях буде представлений як `str` у форматі ISO 8601, як: `2008-09-15`.
* `datetime.time`:
* Пайтонівський `datetime.time`.
- * У запитах та відповідях буде представлений як `str` в форматі ISO 8601, як: `14:23:55.003`.
+ * У запитах та відповідях буде представлений як `str` у форматі ISO 8601, як: `14:23:55.003`.
* `datetime.timedelta`:
* Пайтонівський `datetime.timedelta`.
* У запитах та відповідях буде представлений як `float` загальної кількості секунд.
- * Pydantic також дозволяє представляти це як "ISO 8601 time diff encoding", більше інформації дивись у документації.
+ * Pydantic також дозволяє представляти це як "ISO 8601 time diff encoding", [дивіться документацію для отримання додаткової інформації](https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers).
* `frozenset`:
* У запитах і відповідях це буде оброблено так само, як і `set`:
- * У запитах список буде зчитано, дублікати будуть видалені та він буде перетворений на `set`.
- * У відповідях, `set` буде перетворений на `list`.
+ * У запитах список буде зчитано, дублікати буде видалено, і його буде перетворено на `set`.
+ * У відповідях `set` буде перетворено на `list`.
* Згенерована схема буде вказувати, що значення `set` є унікальними (з використанням JSON Schema's `uniqueItems`).
* `bytes`:
* Стандартний Пайтонівський `bytes`.
@@ -49,82 +49,14 @@
* `Decimal`:
* Стандартний Пайтонівський `Decimal`.
* У запитах і відповідях це буде оброблено так само, як і `float`.
-* Ви можете перевірити всі дійсні типи даних Pydantic тут: типи даних Pydantic.
+* Ви можете перевірити всі дійсні типи даних Pydantic тут: [типи даних Pydantic](https://docs.pydantic.dev/latest/usage/types/types/).
-## Приклад
+## Приклад { #example }
-Ось приклад *path operation* з параметрами, використовуючи деякі з вищезазначених типів.
+Ось приклад *операції шляху* з параметрами, використовуючи деякі з вищезазначених типів.
-=== "Python 3.10+"
-
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="1 3 13-17"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
-
- ```Python hl_lines="1 2 11-15"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
-
- ```Python hl_lines="1 2 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *}
Зверніть увагу, що параметри всередині функції мають свій звичайний тип даних, і ви можете, наприклад, виконувати звичайні маніпуляції з датами, такі як:
-=== "Python 3.10+"
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="19-20"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
-
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- Бажано використовувати `Annotated` версію, якщо це можливо.
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *}
diff --git a/docs/uk/docs/tutorial/extra-models.md b/docs/uk/docs/tutorial/extra-models.md
new file mode 100644
index 0000000000000..271e553fd82a7
--- /dev/null
+++ b/docs/uk/docs/tutorial/extra-models.md
@@ -0,0 +1,211 @@
+# Додаткові моделі { #extra-models }
+
+Продовжуючи попередній приклад, часто потрібно мати більше ніж одну пов’язану модель.
+
+Особливо це стосується моделей користувача, тому що:
+
+* **вхідна модель** повинна мати пароль.
+* **вихідна модель** не повинна містити пароль.
+* **модель бази даних**, ймовірно, повинна містити хеш пароля.
+
+/// danger | Обережно
+
+Ніколи не зберігайте паролі користувачів у відкритому вигляді. Завжди зберігайте «безпечний хеш», який потім можна перевірити.
+
+Якщо ви ще не знаєте, що таке «хеш пароля», ви дізнаєтесь у [розділах про безпеку](security/simple-oauth2.md#password-hashing).
+
+///
+
+## Кілька моделей { #multiple-models }
+
+Ось загальна ідея того, як можуть виглядати моделі з їхніми полями пароля та місцями використання:
+
+{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}
+
+### Про `**user_in.model_dump()` { #about-user-in-model-dump }
+
+#### `.model_dump()` у Pydantic { #pydantics-model-dump }
+
+`user_in` - це модель Pydantic класу `UserIn`.
+
+Моделі Pydantic мають метод `.model_dump()`, який повертає `dict` з даними моделі.
+
+Отже, якщо ми створимо об’єкт Pydantic `user_in` так:
+
+```Python
+user_in = UserIn(username="john", password="secret", email="john.doe@example.com")
+```
+
+і викличемо:
+
+```Python
+user_dict = user_in.model_dump()
+```
+
+тепер ми маємо `dict` з даними у змінній `user_dict` (це `dict`, а не об’єкт моделі Pydantic).
+
+А якщо викликати:
+
+```Python
+print(user_dict)
+```
+
+ми отримаємо Python `dict` з:
+
+```Python
+{
+ 'username': 'john',
+ 'password': 'secret',
+ 'email': 'john.doe@example.com',
+ 'full_name': None,
+}
+```
+
+#### Розпакування `dict` { #unpacking-a-dict }
+
+Якщо взяти `dict`, наприклад `user_dict`, і передати його у функцію (або клас) як `**user_dict`, Python «розпакує» його. Ключі та значення `user_dict` будуть передані безпосередньо як іменовані аргументи.
+
+Отже, продовжуючи з `user_dict` вище, запис:
+
+```Python
+UserInDB(**user_dict)
+```
+
+дасть еквівалентний результат:
+
+```Python
+UserInDB(
+ username="john",
+ password="secret",
+ email="john.doe@example.com",
+ 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 зі вмісту іншої { #a-pydantic-model-from-the-contents-of-another }
+
+Як у прикладі вище ми отримали `user_dict` з `user_in.model_dump()`, цей код:
+
+```Python
+user_dict = user_in.model_dump()
+UserInDB(**user_dict)
+```
+
+буде еквівалентним:
+
+```Python
+UserInDB(**user_in.model_dump())
+```
+
+...тому що `user_in.model_dump()` - це `dict`, а ми змушуємо Python «розпакувати» його, передаючи в `UserInDB` з префіксом `**`.
+
+Тож ми отримуємо модель Pydantic з даних іншої моделі Pydantic.
+
+#### Розпакування `dict` і додаткові ключові аргументи { #unpacking-a-dict-and-extra-keywords }
+
+Додаючи додатковий іменований аргумент `hashed_password=hashed_password`, як тут:
+
+```Python
+UserInDB(**user_in.model_dump(), 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 | Попередження
+
+Додаткові допоміжні функції `fake_password_hasher` і `fake_save_user` лише демонструють можливий потік даних і, звісно, не забезпечують реальної безпеки.
+
+///
+
+## Зменшення дублювання { #reduce-duplication }
+
+Зменшення дублювання коду - одна з ключових ідей у **FastAPI**.
+
+Адже дублювання коду підвищує ймовірність помилок, проблем безпеки, розсинхронізації коду (коли ви оновлюєте в одному місці, але не в інших) тощо.
+
+І ці моделі спільно використовують багато даних та дублюють назви і типи атрибутів.
+
+Можна зробити краще.
+
+Можна оголосити модель `UserBase`, яка буде базовою для інших моделей. Потім створити підкласи цієї моделі, що наслідуватимуть її атрибути (оголошення типів, валідацію тощо).
+
+Уся конвертація даних, валідація, документація тощо працюватимуть як зазвичай.
+
+Таким чином, ми оголошуємо лише відмінності між моделями (з відкритим `password`, з `hashed_password` і без пароля):
+
+{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}
+
+## `Union` або `anyOf` { #union-or-anyof }
+
+Ви можете оголосити відповідь як `Union` двох або більше типів - це означає, що відповідь може бути будь-якого з них.
+
+В OpenAPI це буде визначено як `anyOf`.
+
+Для цього використайте стандартну підказку типу Python [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union):
+
+/// note | Примітка
+
+Під час визначення [`Union`](https://docs.pydantic.dev/latest/concepts/types/#unions) спочатку вказуйте найконкретніший тип, а потім менш конкретний. У прикладі нижче більш конкретний `PlaneItem` стоїть перед `CarItem` у `Union[PlaneItem, CarItem]`.
+
+///
+
+{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}
+
+### `Union` у Python 3.10 { #union-in-python-3-10 }
+
+У цьому прикладі ми передаємо `Union[PlaneItem, CarItem]` як значення аргументу `response_model`.
+
+Оскільки ми передаємо його як значення аргументу, а не в анотації типу, потрібно використовувати `Union` навіть у Python 3.10.
+
+Якби це була анотація типу, можна було б використати вертикальну риску, наприклад:
+
+```Python
+some_variable: PlaneItem | CarItem
+```
+
+Але якщо записати це як присвоєння `response_model=PlaneItem | CarItem`, отримаємо помилку, тому що Python спробує виконати невалідну операцію між `PlaneItem` і `CarItem`, замість того щоб трактувати це як анотацію типу.
+
+## Список моделей { #list-of-models }
+
+Аналогічно можна оголошувати відповіді як списки об’єктів.
+
+Для цього використайте стандартний Python `list`:
+
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
+
+## Відповідь з довільним `dict` { #response-with-arbitrary-dict }
+
+Також можна оголосити відповідь, використовуючи звичайний довільний `dict`, вказавши лише типи ключів і значень, без моделі Pydantic.
+
+Це корисно, якщо ви заздалегідь не знаєте допустимі назви полів/атрибутів (які були б потрібні для моделі Pydantic).
+
+У такому разі можна використати `dict`:
+
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
+
+## Підсумок { #recap }
+
+Використовуйте кілька моделей Pydantic і вільно наслідуйте для кожного випадку.
+
+Не обов’язково мати одну модель даних на сутність, якщо ця сутність може мати різні «стани». Як у випадку сутності користувача зі станами: з `password`, з `password_hash` і без пароля.
diff --git a/docs/uk/docs/tutorial/first-steps.md b/docs/uk/docs/tutorial/first-steps.md
new file mode 100644
index 0000000000000..0f46890d9b311
--- /dev/null
+++ b/docs/uk/docs/tutorial/first-steps.md
@@ -0,0 +1,429 @@
+# Перші кроки { #first-steps }
+
+Найпростіший файл FastAPI може виглядати так:
+
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
+
+Скопіюйте це до файлу `main.py`.
+
+Запустіть live-сервер:
+
+get операція
+
+/// info | `@decorator` Інформація
+
+Синтаксис `@something` у Python називається «декоратором».
+
+Ви розташовуєте його над функцією. Як гарний декоративний капелюх (мабуть, звідти походить термін).
+
+«Декоратор» бере функцію нижче і виконує з нею якусь дію.
+
+У нашому випадку, цей декоратор повідомляє **FastAPI**, що функція нижче відповідає **шляху** `/` і **операції** `get`.
+
+Це і є «**декоратор операції шляху**».
+
+///
+
+Можна також використовувати інші операції:
+
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+
+І більш екзотичні:
+
+* `@app.options()`
+* `@app.head()`
+* `@app.patch()`
+* `@app.trace()`
+
+/// tip
+
+Ви можете використовувати кожну операцію (HTTP-метод) як забажаєте.
+
+**FastAPI** не навʼязує жодного конкретного значення.
+
+Наведена тут інформація подана як настанова, а не вимога.
+
+Наприклад, під час використання GraphQL ви зазвичай виконуєте всі дії, використовуючи лише `POST` операції.
+
+///
+
+### Крок 4: визначте **функцію операції шляху** { #step-4-define-the-path-operation-function }
+
+Ось наша «**функція операції шляху**»:
+
+* **шлях**: це `/`.
+* **операція**: це `get`.
+* **функція**: це функція нижче «декоратора» (нижче `@app.get("/")`).
+
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
+
+Це функція Python.
+
+**FastAPI** викликатиме її щоразу, коли отримає запит до URL «`/`», використовуючи операцію `GET`.
+
+У цьому випадку це `async` функція.
+
+---
+
+Ви також можете визначити її як звичайну функцію замість `async def`:
+
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
+
+/// note
+
+Якщо ви не знаєте різницю, подивіться [Асинхронність: *«Поспішаєте?»*](../async.md#in-a-hurry).
+
+///
+
+### Крок 5: поверніть вміст { #step-5-return-the-content }
+
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
+
+Ви можете повернути `dict`, `list`, а також окремі значення `str`, `int` тощо.
+
+Також можна повернути моделі Pydantic (про це ви дізнаєтесь пізніше).
+
+Існує багато інших обʼєктів і моделей, які будуть автоматично конвертовані в JSON (зокрема ORM тощо). Спробуйте використати свої улюблені — велика ймовірність, що вони вже підтримуються.
+
+### Крок 6: розгорніть його { #step-6-deploy-it }
+
+Розгорніть ваш застосунок у **[FastAPI Cloud](https://fastapicloud.com)** однією командою: `fastapi deploy`. 🎉
+
+#### Про FastAPI Cloud { #about-fastapi-cloud }
+
+**[FastAPI Cloud](https://fastapicloud.com)** створено тим самим автором і командою, які стоять за **FastAPI**.
+
+Він спрощує процес **створення**, **розгортання** та **доступу** до API з мінімальними зусиллями.
+
+Він переносить той самий **досвід розробника** зі створення застосунків на FastAPI на **розгортання** їх у хмарі. 🎉
+
+FastAPI Cloud — основний спонсор і джерело фінансування для open source проєктів *FastAPI and friends*. ✨
+
+#### Розгортання в інших хмарних провайдерах { #deploy-to-other-cloud-providers }
+
+FastAPI — це open source і базується на стандартах. Ви можете розгортати FastAPI-застосунки у будь-якого хмарного провайдера на ваш вибір.
+
+Дотримуйтеся інструкцій вашого хмарного провайдера, щоб розгорнути FastAPI-застосунки з їхньою допомогою. 🤓
+
+## Підібʼємо підсумки { #recap }
+
+* Імпортуйте `FastAPI`.
+* Створіть екземпляр `app`.
+* Напишіть **декоратор операції шляху**, використовуючи декоратори на кшталт `@app.get("/")`.
+* Визначте **функцію операції шляху**; наприклад, `def root(): ...`.
+* Запустіть сервер розробки командою `fastapi dev`.
+* За бажанням розгорніть ваш застосунок за допомогою `fastapi deploy`.
diff --git a/docs/uk/docs/tutorial/handling-errors.md b/docs/uk/docs/tutorial/handling-errors.md
new file mode 100644
index 0000000000000..262efa0e03d4e
--- /dev/null
+++ b/docs/uk/docs/tutorial/handling-errors.md
@@ -0,0 +1,244 @@
+# Обробка помилок { #handling-errors }
+
+Є багато ситуацій, коли вам потрібно повідомити про помилку клієнта, який використовує ваш API.
+
+Цим клієнтом може бути браузер із фронтендом, код іншого розробника, IoT-пристрій тощо.
+
+Можливо, вам потрібно повідомити клієнта, що:
+
+* У нього недостатньо прав для виконання цієї операції.
+* Він не має доступу до цього ресурсу.
+* Елемент, до якого він намагається отримати доступ, не існує.
+* тощо.
+
+У таких випадках зазвичай повертається **код статусу HTTP** у діапазоні **400** (від 400 до 499).
+
+Це схоже на коди статусу HTTP 200 (від 200 до 299). Ці «200» коди статусу означають, що якимось чином запит був «успішним».
+
+Коди статусу в діапазоні 400 означають, що сталася помилка з боку клієнта.
+
+Пам'ятаєте всі ці помилки **«404 Not Found»** (і жарти про них)?
+
+## Використання `HTTPException` { #use-httpexception }
+
+Щоб повернути HTTP-відповіді з помилками клієнту, використовуйте `HTTPException`.
+
+### Імпорт `HTTPException` { #import-httpexception }
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
+
+### Згенеруйте `HTTPException` у своєму коді { #raise-an-httpexception-in-your-code }
+
+`HTTPException` - це звичайна помилка Python із додатковими даними, які стосуються API.
+
+Оскільки це помилка Python, ви не `return` її, а `raise` її.
+
+Це також означає, що якщо ви перебуваєте всередині допоміжної функції, яку викликаєте всередині своєї *функції операції шляху*, і там згенеруєте `HTTPException` всередині цієї допоміжної функції, то решта коду в *функції операції шляху* не буде виконана. Запит одразу завершиться, і HTTP-помилка з `HTTPException` буде надіслана клієнту.
+
+Перевага генерації виключення замість повернення значення стане більш очевидною в розділі про залежності та безпеку.
+
+У цьому прикладі, коли клієнт запитує елемент за ID, якого не існує, згенеруйте виключення з кодом статусу `404`:
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
+
+### Отримана відповідь { #the-resulting-response }
+
+Якщо клієнт робить запит за шляхом `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 (помилка «не знайдено») та JSON відповідь:
+
+```JSON
+{
+ "detail": "Item not found"
+}
+```
+
+/// tip | Порада
+
+Під час генерації `HTTPException` ви можете передати будь-яке значення, яке може бути перетворене в JSON, як параметр `detail`, а не лише `str`.
+
+Ви можете передати `dict`, `list` тощо.
+
+Вони обробляються автоматично за допомогою **FastAPI** та перетворюються в JSON.
+
+///
+
+## Додавання власних заголовків { #add-custom-headers }
+
+Є деякі ситуації, коли корисно мати можливість додавати власні заголовки до HTTP-помилки. Наприклад, для деяких типів безпеки.
+
+Ймовірно, вам не доведеться використовувати це безпосередньо у своєму коді.
+
+Але якщо вам знадобиться це для складного сценарію, ви можете додати власні заголовки:
+
+{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
+
+## Встановлення власних обробників виключень { #install-custom-exception-handlers }
+
+Ви можете додати власні обробники виключень за допомогою [тих самих утиліт для виключень зі Starlette](https://www.starlette.dev/exceptions/).
+
+Припустімо, у вас є власне виключення `UnicornException`, яке ви (або бібліотека, яку ви використовуєте) можете `raise`.
+
+І ви хочете обробляти це виключення глобально за допомогою FastAPI.
+
+Ви можете додати власний обробник виключень за допомогою `@app.exception_handler()`:
+
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
+
+Тут, якщо ви звернетеся до `/unicorns/yolo`, *операція шляху* згенерує (`raise`) `UnicornException`.
+
+Але вона буде оброблена функцією-обробником `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** надає ті самі `starlette.responses`, що й `fastapi.responses`, просто для зручності для вас, розробника. Але більшість доступних відповідей надходять безпосередньо зі Starlette. Те ж саме з `Request`.
+
+///
+
+## Перевизначення обробників виключень за замовчуванням { #override-the-default-exception-handlers }
+
+**FastAPI** має кілька обробників виключень за замовчуванням.
+
+Ці обробники відповідають за повернення стандартних JSON-відповідей, коли ви `raise` `HTTPException`, а також коли запит містить некоректні дані.
+
+Ви можете перевизначити ці обробники виключень власними.
+
+### Перевизначення виключень валідації запиту { #override-request-validation-exceptions }
+
+Коли запит містить некоректні дані, **FastAPI** внутрішньо генерує `RequestValidationError`.
+
+І також включає обробник виключень за замовчуванням для нього.
+
+Щоб перевизначити його, імпортуйте `RequestValidationError` і використовуйте його з `@app.exception_handler(RequestValidationError)` для декорування обробника виключень.
+
+Обробник виключень отримає `Request` і саме виключення.
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
+
+Тепер, якщо ви перейдете за посиланням `/items/foo`, замість того, щоб отримати стандартну JSON-помилку:
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ]
+}
+```
+
+ви отримаєте текстову версію:
+
+```
+Validation errors:
+Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer
+```
+
+### Перевизначення обробника помилок `HTTPException` { #override-the-httpexception-error-handler }
+
+Аналогічно, ви можете перевизначити обробник `HTTPException`.
+
+Наприклад, ви можете захотіти повернути відповідь у вигляді простого тексту замість JSON для цих помилок:
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
+
+/// note | Технічні деталі
+
+Ви також можете використовувати `from starlette.responses import PlainTextResponse`.
+
+**FastAPI** надає ті самі `starlette.responses`, що й `fastapi.responses`, просто для зручності для вас, розробника. Але більшість доступних відповідей надходять безпосередньо зі Starlette.
+
+///
+
+/// warning | Попередження
+
+Пам’ятайте, що `RequestValidationError` містить інформацію про назву файлу та рядок, де сталася помилка валідації, щоб за потреби ви могли показати це у своїх логах із відповідною інформацією.
+
+Але це означає, що якщо ви просто перетворите це на рядок і повернете цю інформацію напряму, ви можете розкрити трохи інформації про вашу систему, тому тут код витягає та показує кожну помилку незалежно.
+
+///
+
+### Використання тіла `RequestValidationError` { #use-the-requestvalidationerror-body }
+
+`RequestValidationError` містить `body`, який він отримав із некоректними даними.
+
+Ви можете використовувати це під час розробки свого додатка, щоб логувати тіло запиту та налагоджувати його, повертати користувачеві тощо.
+
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
+
+Тепер спробуйте надіслати некоректний елемент, наприклад:
+
+```JSON
+{
+ "title": "towel",
+ "size": "XL"
+}
+```
+
+Ви отримаєте відповідь, яка повідомить вам, що дані є некоректними, і міститиме отримане тіло запиту:
+
+```JSON hl_lines="12-15"
+{
+ "detail": [
+ {
+ "loc": [
+ "body",
+ "size"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ],
+ "body": {
+ "title": "towel",
+ "size": "XL"
+ }
+}
+```
+
+#### `HTTPException` FastAPI проти `HTTPException` Starlette { #fastapis-httpexception-vs-starlettes-httpexception }
+
+**FastAPI** має власний `HTTPException`.
+
+І клас помилки `HTTPException` в **FastAPI** успадковується від класу помилки `HTTPException` у Starlette.
+
+Єдина різниця полягає в тому, що `HTTPException` в **FastAPI** приймає будь-які дані, які можна перетворити на JSON, для поля `detail`, тоді як `HTTPException` у Starlette приймає тільки рядки.
+
+Отже, ви можете продовжувати генерувати `HTTPException` **FastAPI** як зазвичай у своєму коді.
+
+Але коли ви реєструєте обробник виключень, слід реєструвати його для `HTTPException` зі Starlette.
+
+Таким чином, якщо будь-яка частина внутрішнього коду Starlette або розширення чи плагін Starlette згенерує Starlette `HTTPException`, ваш обробник зможе перехопити та обробити її.
+
+У цьому прикладі, щоб мати можливість використовувати обидва `HTTPException` в одному коді, виключення Starlette перейменовується на `StarletteHTTPException`:
+
+```Python
+from starlette.exceptions import HTTPException as StarletteHTTPException
+```
+
+### Повторне використання обробників виключень **FastAPI** { #reuse-fastapis-exception-handlers }
+
+Якщо ви хочете використовувати виключення разом із такими ж обробниками виключень за замовчуванням, як у **FastAPI**, ви можете імпортувати та повторно використати обробники виключень за замовчуванням із `fastapi.exception_handlers`:
+
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
+
+У цьому прикладі ви просто друкуєте помилку з дуже виразним повідомленням, але ви зрозуміли основну ідею. Ви можете використовувати виключення, а потім просто повторно використати обробники виключень за замовчуванням.
diff --git a/docs/uk/docs/tutorial/header-param-models.md b/docs/uk/docs/tutorial/header-param-models.md
new file mode 100644
index 0000000000000..dd734eaee7bf5
--- /dev/null
+++ b/docs/uk/docs/tutorial/header-param-models.md
@@ -0,0 +1,72 @@
+# Моделі параметрів заголовків { #header-parameter-models }
+
+Якщо у вас є група пов’язаних **параметрів заголовків**, ви можете створити **Pydantic модель** для їх оголошення.
+
+Це дозволить вам повторно **використовувати модель** в **різних місцях**, а також оголосити валідації та метадані для всіх параметрів одночасно. 😎
+
+/// note | Примітка
+
+Ця можливість підтримується починаючи з версії FastAPI `0.115.0`. 🤓
+
+///
+
+## Параметри заголовків з використанням Pydantic моделі { #header-parameters-with-a-pydantic-model }
+
+Оголосіть потрібні **параметри заголовків** у **Pydantic моделі**, а потім оголосіть параметр як `Header`:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI** буде **витягувати** дані для **кожного поля** з **заголовків** у запиті та передавати їх у створену вами Pydantic модель.
+
+## Перевірка в документації { #check-the-docs }
+
+Ви можете побачити необхідні заголовки в інтерфейсі документації за адресою `/docs`:
+
+
+contact поля| Параметр | Тип | Опис |
|---|---|---|
name | str | Ідентифікаційне ім'я контактної особи або організації. |
url | str | URL, що вказує на контактну інформацію. МАЄ бути у форматі URL. |
email | str | Адреса електронної пошти контактної особи або організації. МАЄ бути у форматі адреси електронної пошти. |
license_info поля| Параметр | Тип | Опис |
|---|---|---|
name | str | ОБОВ'ЯЗКОВО (якщо встановлено license_info). Назва ліцензії для API. |
identifier | str | Ліцензійний вираз за [SPDX](https://spdx.org/licenses/) для API. Поле identifier взаємовиключне з полем url. Доступно з OpenAPI 3.1.0, FastAPI 0.99.0. |
url | str | URL до ліцензії, яка використовується для API. МАЄ бути у форматі URL. |
+
+## Ідентифікатор ліцензії { #license-identifier }
+
+З початку використання OpenAPI 3.1.0 та FastAPI 0.99.0 Ви також можете налаштувати `license_info` за допомогою `identifier` замість `url`.
+
+Наприклад:
+
+{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}
+
+## Метадані для тегів { #metadata-for-tags }
+
+Ви також можете додати додаткові метадані для різних тегів, які використовуються для групування операцій шляху, за допомогою параметра `openapi_tags`.
+
+Він приймає список, який містить один словник для кожного тега.
+
+Кожен словник може містити:
+
+* `name` (**обов'язково**): `str` з тією ж назвою тегу, яку Ви використовуєте у параметрі `tags` у Ваших *операціях шляху* та `APIRouter`s.
+* `description`: `str` з коротким описом тегу. Може містити Markdown і буде показано в інтерфейсі документації.
+* `externalDocs`: `dict`, який описує зовнішню документацію з такими полями:
+ * `description`: `str` з коротким описом зовнішньої документації.
+ * `url` (**обов'язково**): `str` з URL-адресою зовнішньої документації.
+
+### Створення метаданих для тегів { #create-metadata-for-tags }
+
+Спробуймо це на прикладі з тегами для `users` та `items`.
+
+Створіть метадані для своїх тегів і передайте їх у параметр `openapi_tags`:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}
+
+Зверніть увагу, що в описах можна використовувати Markdown, наприклад, «login» буде показано жирним шрифтом (**login**), а «fancy» буде показано курсивом (_fancy_).
+
+/// tip | Порада
+
+Вам не потрібно додавати метадані для всіх тегів, які Ви використовуєте.
+
+///
+
+### Використовуйте свої теги { #use-your-tags }
+
+Використовуйте параметр `tags` зі своїми *операціями шляху* (і `APIRouter`s), щоб призначити їх до різних тегів:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}
+
+/// info | Інформація
+
+Детальніше про теги читайте в розділі [Конфігурація операції шляху](path-operation-configuration.md#tags).
+
+///
+
+### Перевірте документацію { #check-the-docs }
+
+Тепер, якщо Ви перевірите документацію, вона покаже всі додаткові метадані:
+
+
+
+### Порядок тегів { #order-of-tags }
+
+Порядок кожного словника метаданих тегу також визначає порядок відображення в інтерфейсі документації.
+
+Наприклад, хоча `users` мав би йти після `items` в алфавітному порядку, він відображається перед ними, оскільки ми додали їхні метадані як перший словник у списку.
+
+## URL для OpenAPI { #openapi-url }
+
+За замовчуванням схема OpenAPI надається за адресою `/openapi.json`.
+
+Але Ви можете налаштувати це за допомогою параметра `openapi_url`.
+
+Наприклад, щоб налаштувати його на `/api/v1/openapi.json`:
+
+{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}
+
+Якщо Ви хочете повністю вимкнути схему OpenAPI, Ви можете встановити `openapi_url=None`, це також вимкне інтерфейси документації, які її використовують.
+
+## URL-адреси документації { #docs-urls }
+
+Ви можете налаштувати два інтерфейси користувача для документації, які включені:
+
+* **Swagger UI**: доступний за адресою `/docs`.
+ * Ви можете змінити його URL за допомогою параметра `docs_url`.
+ * Ви можете вимкнути його, встановивши `docs_url=None`.
+* **ReDoc**: доступний за адресою `/redoc`.
+ * Ви можете змінити його URL за допомогою параметра `redoc_url`.
+ * Ви можете вимкнути його, встановивши `redoc_url=None`.
+
+Наприклад, щоб налаштувати Swagger UI на `/documentation` і вимкнути ReDoc:
+
+{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}
diff --git a/docs/uk/docs/tutorial/middleware.md b/docs/uk/docs/tutorial/middleware.md
new file mode 100644
index 0000000000000..a31357ba10cc6
--- /dev/null
+++ b/docs/uk/docs/tutorial/middleware.md
@@ -0,0 +1,95 @@
+# Middleware { #middleware }
+
+У **FastAPI** можна додавати middleware.
+
+«Middleware» — це функція, яка працює з кожним **запитом** перед його обробкою будь-якою конкретною *операцією шляху*. А також з кожною **відповіддю** перед її поверненням.
+
+* Вона отримує кожен **запит**, що надходить до вашого застосунку.
+* Потім вона може виконати певні дії із цим **запитом** або запустити необхідний код.
+* Далі вона передає **запит** для обробки рештою застосунку (якоюсь *операцією шляху*).
+* Потім вона отримує **відповідь**, сформовану застосунком (якоюсь *операцією шляху*).
+* Вона може виконати певні дії із цією **відповіддю** або запустити необхідний код.
+* Потім вона повертає **відповідь**.
+
+/// note | Технічні деталі
+
+Якщо у вас є залежності з `yield`, код виходу виконається *після* middleware.
+
+Якщо були заплановані фонові задачі (розглянуто в розділі [Фонові задачі](background-tasks.md), ви побачите це пізніше), вони виконаються *після* всіх middleware.
+
+///
+
+## Створення middleware { #create-a-middleware }
+
+Щоб створити middleware, ви використовуєте декоратор `@app.middleware("http")` над функцією.
+
+Функція middleware отримує:
+
+* `request`.
+* Функцію `call_next`, яка отримає `request` як параметр.
+ * Ця функція передасть `request` відповідній *операції шляху*.
+ * Потім вона поверне `response`, згенеровану відповідною *операцією шляху*.
+* Потім ви можете додатково змінити `response` перед тим, як повернути її.
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}
+
+/// tip
+
+Пам’ятайте, що власні пропрієтарні заголовки можна додавати [використовуючи префікс `X-`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers).
+
+Але якщо у вас є власні заголовки, які ви хочете, щоб клієнт у браузері міг побачити, потрібно додати їх до ваших конфігурацій CORS ([CORS (Спільне використання ресурсів між джерелами)](cors.md)) за допомогою параметра `expose_headers`, описаного в [документації Starlette по CORS](https://www.starlette.dev/middleware/#corsmiddleware).
+
+///
+
+/// note | Технічні деталі
+
+Ви також можете використати `from starlette.requests import Request`.
+
+**FastAPI** надає це для вашої зручності як розробника. Але воно походить безпосередньо зі Starlette.
+
+///
+
+### До і після `response` { #before-and-after-the-response }
+
+Ви можете додати код, який буде виконуватися з `request`, до того, як його отримає будь-яка *операція шляху*.
+
+Також ви можете додати код, який буде виконуватися після того, як `response` буде згенеровано, перед тим як її повернути.
+
+Наприклад, ви можете додати власний заголовок `X-Process-Time`, який міститиме час у секундах, який витратився на обробку запиту та генерацію відповіді:
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}
+
+/// tip
+
+Тут ми використовуємо [`time.perf_counter()`](https://docs.python.org/3/library/time.html#time.perf_counter) замість `time.time()` оскільки він може бути більш точним для таких випадків. 🤓
+
+///
+
+## Порядок виконання кількох middleware { #multiple-middleware-execution-order }
+
+Коли ви додаєте кілька middleware, використовуючи або декоратор `@app.middleware()` або метод `app.add_middleware()`, кожен новий middleware обгортає застосунок, утворюючи стек. Останній доданий middleware є *зовнішнім*, а перший — *внутрішнім*.
+
+На шляху запиту першим виконується *зовнішній* middleware.
+
+На шляху відповіді він виконується останнім.
+
+Наприклад:
+
+```Python
+app.add_middleware(MiddlewareA)
+app.add_middleware(MiddlewareB)
+```
+
+Це призводить до такого порядку виконання:
+
+* **Запит**: MiddlewareB → MiddlewareA → route
+
+* **Відповідь**: route → MiddlewareA → MiddlewareB
+
+Така поведінка стеку гарантує, що middleware виконуються у передбачуваному та керованому порядку.
+
+## Інші middlewares { #other-middlewares }
+
+Ви можете пізніше прочитати більше про інші middlewares у [просунутому посібнику користувача: просунуте middleware](../advanced/middleware.md).
+
+Ви дізнаєтесь, як обробляти CORS за допомогою middleware в наступному розділі.
diff --git a/docs/uk/docs/tutorial/path-operation-configuration.md b/docs/uk/docs/tutorial/path-operation-configuration.md
new file mode 100644
index 0000000000000..292066c1f84cc
--- /dev/null
+++ b/docs/uk/docs/tutorial/path-operation-configuration.md
@@ -0,0 +1,107 @@
+# Налаштування операції шляху { #path-operation-configuration }
+
+Є кілька параметрів, які ви можете передати вашому «декоратору операції шляху» для налаштування.
+
+/// warning | Попередження
+
+Зверніть увагу, що ці параметри передаються безпосередньо «декоратору операції шляху», а не вашій «функції операції шляху».
+
+///
+
+## Код статусу відповіді { #response-status-code }
+
+Ви можете визначити (HTTP) `status_code`, який буде використано у відповіді вашої «операції шляху».
+
+Можна передати безпосередньо цілий код, наприклад `404`.
+
+Якщо ви не пам'ятаєте призначення числових кодів, скористайтеся скороченими константами в `status`:
+
+{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *}
+
+Цей код статусу буде використано у відповіді та додано до схеми OpenAPI.
+
+/// note | Технічні деталі
+
+Ви також можете використати `from starlette import status`.
+
+FastAPI надає той самий `starlette.status` як `fastapi.status` для вашої зручності як розробника. Але він походить безпосередньо зі Starlette.
+
+///
+
+## Мітки { #tags }
+
+Ви можете додати мітки до вашої «операції шляху», передайте параметр `tags` зі `list` із `str` (зазвичай лише один `str`):
+
+{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *}
+
+Вони будуть додані до схеми OpenAPI та використані інтерфейсами автоматичної документації:
+
+
+
+### Мітки з переліками { #tags-with-enums }
+
+У великому застосунку ви можете накопичити багато міток і захочете переконатися, що завжди використовуєте ту саму мітку для пов'язаних «операцій шляху».
+
+У таких випадках має сенс зберігати мітки в `Enum`.
+
+FastAPI підтримує це так само, як і зі звичайними строками:
+
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
+
+## Короткий опис і опис { #summary-and-description }
+
+Ви можете додати `summary` і `description`:
+
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *}
+
+## Опис зі строки документації { #description-from-docstring }
+
+Оскільки описи зазвичай довгі та займають кілька рядків, ви можете оголосити опис «операції шляху» у строці документації функції, і FastAPI прочитає його звідти.
+
+Ви можете писати [Markdown](https://en.wikipedia.org/wiki/Markdown) у строці документації, його буде інтерпретовано та показано коректно (з урахуванням відступів у строці документації).
+
+{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}
+
+Його буде використано в інтерактивній документації:
+
+
+
+## Опис відповіді { #response-description }
+
+Ви можете вказати опис відповіді параметром `response_description`:
+
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
+
+/// info | Інформація
+
+Зверніть увагу, що `response_description` стосується саме відповіді, а `description` стосується «операції шляху» загалом.
+
+///
+
+/// check | Перевірте
+
+OpenAPI визначає, що кожна «операція шляху» потребує опису відповіді.
+
+Тому, якщо ви його не надасте, FastAPI автоматично згенерує «Successful response».
+
+///
+
+
+
+## Позначити операцію шляху як застарілу { #deprecate-a-path-operation }
+
+Якщо потрібно позначити «операцію шляху» як застарілу, але не видаляючи її, передайте параметр `deprecated`:
+
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
+
+У інтерактивній документації вона буде чітко позначена як застаріла:
+
+
+
+Подивіться, як виглядають застарілі та незастарілі «операції шляху»:
+
+
+
+## Підсумок { #recap }
+
+Ви можете легко налаштовувати та додавати метадані до ваших «операцій шляху», передаючи параметри «декораторам операцій шляху».
diff --git a/docs/uk/docs/tutorial/path-params-numeric-validations.md b/docs/uk/docs/tutorial/path-params-numeric-validations.md
new file mode 100644
index 0000000000000..39397a3b1d80b
--- /dev/null
+++ b/docs/uk/docs/tutorial/path-params-numeric-validations.md
@@ -0,0 +1,154 @@
+# Параметри шляху та валідація числових даних { #path-parameters-and-numeric-validations }
+
+Так само як ви можете оголошувати додаткові перевірки та метадані для query параметрів за допомогою `Query`, ви можете оголошувати той самий тип перевірок і метаданих для параметрів шляху за допомогою `Path`.
+
+## Імпорт `Path` { #import-path }
+
+Спочатку імпортуйте `Path` з `fastapi` і імпортуйте `Annotated`:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
+
+/// info | Інформація
+
+FastAPI додав підтримку `Annotated` (і почав рекомендувати його використання) у версії 0.95.0.
+
+Якщо у вас стара версія, при спробі використати `Annotated` можуть виникати помилки.
+
+Переконайтеся, що ви [оновили версію FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions) принаймні до версії 0.95.1 перед використанням `Annotated`.
+
+///
+
+## Оголошення метаданих { #declare-metadata }
+
+Ви можете оголошувати всі ті ж параметри, що і для `Query`.
+
+Наприклад, щоб оголосити значення метаданих `title` для параметра шляху `item_id`, ви можете написати:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *}
+
+/// note | Примітка
+
+Параметр шляху завжди є обов’язковим, оскільки він має бути частиною шляху. Навіть якщо ви оголосите його зі значенням `None` або встановите значення за замовчуванням — це ні на що не вплине, він все одно завжди буде обов’язковим.
+
+///
+
+## Упорядковуйте параметри, як вам потрібно { #order-the-parameters-as-you-need }
+
+/// tip | Порада
+
+Це, мабуть, не настільки важливо або необхідно, якщо ви використовуєте `Annotated`.
+
+///
+
+Припустимо, ви хочете оголосити параметр запиту `q` як обов’язковий `str`.
+
+І вам не потрібно оголошувати нічого іншого для цього параметра, тому вам насправді не потрібно використовувати `Query`.
+
+Але вам все одно потрібно використовувати `Path` для параметра шляху `item_id`. І з певних причин ви не хочете використовувати `Annotated`.
+
+Python видасть помилку, якщо розмістити значення з "default" перед значенням, яке не має "default".
+
+Але ви можете змінити порядок і розмістити значення без значення за замовчуванням (параметр запиту `q`) першим.
+
+Для **FastAPI** порядок не має значення. Він визначає параметри за їхніми іменами, типами та оголошеннями за замовчуванням (`Query`, `Path` тощо) і не звертає уваги на порядок.
+
+Тому ви можете оголосити вашу функцію так:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
+
+Але майте на увазі, що якщо ви використовуєте `Annotated`, цієї проблеми не буде, це не матиме значення, оскільки ви не використовуєте значення за замовчуванням параметрів функції для `Query()` або `Path()`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
+
+## Упорядковуйте параметри, як вам потрібно: хитрощі { #order-the-parameters-as-you-need-tricks }
+
+/// tip | Порада
+
+Це, мабуть, не настільки важливо або необхідно, якщо ви використовуєте `Annotated`.
+
+///
+
+Ось **невелика хитрість**, яка може стати в пригоді, хоча вона рідко знадобиться.
+
+Якщо ви хочете:
+
+* оголосити параметр запиту `q` без `Query` і без жодного значення за замовчуванням
+* оголосити параметр шляху `item_id`, використовуючи `Path`
+* розмістити їх у різному порядку
+* не використовувати `Annotated`
+
+...у Python є спеціальний синтаксис для цього.
+
+Передайте `*` як перший параметр функції.
+
+Python нічого не зробить із цією `*`, але розпізнає, що всі наступні параметри слід викликати як аргументи за ключовим словом (пари ключ-значення), також відомі як kwargs. Навіть якщо вони не мають значення за замовчуванням.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
+
+### Краще з `Annotated` { #better-with-annotated }
+
+Майте на увазі, що якщо ви використовуєте `Annotated`, оскільки ви не використовуєте значення за замовчуванням параметрів функції, цієї проблеми не буде, і, ймовірно, вам не потрібно буде використовувати `*`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
+
+## Валідація числових даних: більше або дорівнює { #number-validations-greater-than-or-equal }
+
+За допомогою `Query` і `Path` (та інших, які ви побачите пізніше) можна оголошувати числові обмеження.
+
+Тут, завдяки `ge=1`, `item_id` має бути цілим числом, яке "`g`reater than or `e`qual" (більше або дорівнює) `1`.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
+
+## Валідація числових даних: більше ніж і менше або дорівнює { #number-validations-greater-than-and-less-than-or-equal }
+
+Те саме застосовується до:
+
+* `gt`: `g`reater `t`han
+* `le`: `l`ess than or `e`qual
+
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
+
+## Валідація числових даних: float, більше ніж і менше ніж { #number-validations-floats-greater-than-and-less-than }
+
+Валідація чисел також працює для значень типу `float`.
+
+Ось де стає важливо мати можливість оголошувати gt, а не тільки ge. Це дозволяє, наприклад, вимагати, щоб значення було більше `0`, навіть якщо воно менше `1`.
+
+Таким чином, значення `0.5` буде допустимим. Але `0.0` або `0` — ні.
+
+Те саме стосується lt.
+
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
+
+## Підсумок { #recap }
+
+За допомогою `Query`, `Path` (і інших параметрів, які ви ще не бачили) можна оголошувати метадані та перевірки рядків так само як у [Query параметри та валідація рядків](query-params-str-validations.md).
+
+Також можна оголошувати числові перевірки:
+
+* `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 | Технічні деталі
+
+Коли ви імпортуєте `Query`, `Path` та інші з `fastapi`, насправді це функції.
+
+При виклику вони повертають екземпляри класів з такими ж іменами.
+
+Тобто ви імпортуєте `Query`, яка є функцією. А коли ви її викликаєте, вона повертає екземпляр класу, який теж називається `Query`.
+
+Ці функції створені таким чином (замість використання класів напряму), щоб ваш редактор не відзначав їхні типи як помилки.
+
+Таким чином, ви можете користуватися своїм звичайним редактором і інструментами для програмування без додаткових налаштувань для ігнорування таких помилок.
+
+///
diff --git a/docs/uk/docs/tutorial/path-params.md b/docs/uk/docs/tutorial/path-params.md
new file mode 100644
index 0000000000000..eb05a4412fdca
--- /dev/null
+++ b/docs/uk/docs/tutorial/path-params.md
@@ -0,0 +1,251 @@
+# Параметри шляху { #path-parameters }
+
+Ви можете оголосити «параметри» або «змінні» шляху, використовуючи той самий синтаксис, що й у форматованих рядках Python:
+
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
+
+Значення параметра шляху `item_id` буде передано у вашу функцію як аргумент `item_id`.
+
+Отже, якщо ви запустите цей приклад і перейдете за посиланням [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo), то побачите відповідь:
+
+```JSON
+{"item_id":"foo"}
+```
+
+## Параметри шляху з типами { #path-parameters-with-types }
+
+Ви можете оголосити тип параметра шляху у функції, використовуючи стандартні анотації типів Python:
+
+{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}
+
+У цьому випадку `item_id` оголошено як `int`.
+
+/// check | Перевірте
+
+Це дасть вам підтримку редактора всередині функції з перевірками помилок, автодоповненням тощо.
+
+///
+
+## Перетворення даних { #data-conversion }
+
+Якщо ви запустите цей приклад і відкриєте у браузері [http://127.0.0.1:8000/items/3](http://127.0.0.1:8000/items/3), то побачите відповідь:
+
+```JSON
+{"item_id":3}
+```
+
+/// check | Перевірте
+
+Зверніть увагу, що значення, яке отримала (і повернула) ваша функція, — це `3`, як Python `int`, а не рядок `"3"`.
+
+Отже, з таким оголошенням типу **FastAPI** надає вам автоматичний запит «парсинг».
+
+///
+
+## Валідація даних { #data-validation }
+
+Але якщо ви перейдете у браузері за посиланням [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo), ви побачите гарну HTTP-помилку:
+
+```JSON
+{
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo"
+ }
+ ]
+}
+```
+
+тому що параметр шляху `item_id` мав значення `"foo"`, яке не є `int`.
+
+Та сама помилка з’явиться, якщо ви передасте `float` замість `int`, як у: [http://127.0.0.1:8000/items/4.2](http://127.0.0.1:8000/items/4.2)
+
+/// check | Перевірте
+
+Отже, з тим самим оголошенням типу в Python **FastAPI** надає вам валідацію даних.
+
+Зверніть увагу, що помилка також чітко вказує саме місце, де валідація не пройшла.
+
+Це неймовірно корисно під час розробки та налагодження коду, що взаємодіє з вашим API.
+
+///
+
+## Документація { #documentation }
+
+А коли ви відкриєте у браузері [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs), ви побачите автоматичну, інтерактивну, API-документацію на кшталт:
+
+
+
+/// check | Перевірте
+
+Знову ж таки, лише з тим самим оголошенням типу в Python **FastAPI** надає вам автоматичну, інтерактивну документацію (з інтеграцією Swagger UI).
+
+Зверніть увагу, що параметр шляху оголошено як ціле число.
+
+///
+
+## Переваги стандартів, альтернативна документація { #standards-based-benefits-alternative-documentation }
+
+І оскільки згенерована схема відповідає стандарту [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md), існує багато сумісних інструментів.
+
+Через це **FastAPI** також надає альтернативну API-документацію (використовуючи ReDoc), до якої ви можете отримати доступ за посиланням [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc):
+
+
+
+Так само, існує багато сумісних інструментів. Зокрема інструменти генерації коду для багатьох мов.
+
+## Pydantic { #pydantic }
+
+Уся валідація даних виконується за лаштунками за допомогою [Pydantic](https://docs.pydantic.dev/), тож ви отримуєте всі переваги від його використання. І ви знаєте, що ви в надійних руках.
+
+Ви можете використовувати ті самі оголошення типів з `str`, `float`, `bool` та багатьма іншими складними типами даних.
+
+Декілька з них розглядаються в наступних розділах посібника.
+
+## Порядок має значення { #order-matters }
+
+Під час створення *операцій шляху* можуть виникати ситуації, коли у вас є фіксований шлях.
+
+Наприклад, `/users/me` — припустімо, це для отримання даних про поточного користувача.
+
+І тоді у вас також може бути шлях `/users/{user_id}` для отримання даних про конкретного користувача за його ID.
+
+Оскільки *операції шляху* оцінюються по черзі, вам потрібно переконатися, що шлях для `/users/me` оголошено перед шляхом для `/users/{user_id}`:
+
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
+
+Інакше шлях для `/users/{user_id}` також відповідатиме `/users/me`, «вважаючи», що отримує параметр `user_id` зі значенням `"me"`.
+
+Так само ви не можете перевизначити операцію шляху:
+
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
+
+Завжди використовуватиметься перша, оскільки шлях збігається першим.
+
+## Попередньо визначені значення { #predefined-values }
+
+Якщо у вас є *операція шляху*, яка отримує *параметр шляху*, але ви хочете, щоб можливі коректні значення *параметра шляху* були попередньо визначені, ви можете використати стандартний Python `Enum`.
+
+### Створіть клас `Enum` { #create-an-enum-class }
+
+Імпортуйте `Enum` і створіть підклас, що наслідується від `str` та `Enum`.
+
+Завдяки наслідуванню від `str` документація API зможе визначити, що значення повинні бути типу `string`, і зможе коректно їх відобразити.
+
+Після цього створіть атрибути класу з фіксованими значеннями, які будуть доступними коректними значеннями:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
+
+/// tip | Порада
+
+Якщо вам цікаво, «AlexNet», «ResNet» та «LeNet» — це просто назви моделей машинного навчання моделі.
+
+///
+
+### Оголосіть *параметр шляху* { #declare-a-path-parameter }
+
+Потім створіть *параметр шляху* з анотацією типу, використовуючи створений вами клас enum (`ModelName`):
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
+
+### Перевірте документацію { #check-the-docs }
+
+Оскільки доступні значення для *параметра шляху* визначені заздалегідь, інтерактивна документація може красиво їх показати:
+
+
+
+### Робота з Python *переліченнями* { #working-with-python-enumerations }
+
+Значення *параметра шляху* буде *елементом перелічування*.
+
+#### Порівняйте *елементи перелічування* { #compare-enumeration-members }
+
+Ви можете порівнювати його з *елементом перелічування* у створеному вами enum `ModelName`:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}
+
+#### Отримайте *значення перелічування* { #get-the-enumeration-value }
+
+Ви можете отримати фактичне значення (у цьому випадку це `str`), використовуючи `model_name.value`, або загалом `your_enum_member.value`:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}
+
+/// tip | Порада
+
+Ви також можете отримати доступ до значення `"lenet"` через `ModelName.lenet.value`.
+
+///
+
+#### Поверніть *елементи перелічування* { #return-enumeration-members }
+
+Ви можете повертати *елементи enum* з вашої *операції шляху*, навіть вкладені у JSON-тіло (наприклад, `dict`).
+
+Вони будуть перетворені на відповідні значення (у цьому випадку рядки) перед поверненням клієнту:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}
+
+На стороні клієнта ви отримаєте відповідь у форматі JSON, наприклад:
+
+```JSON
+{
+ "model_name": "alexnet",
+ "message": "Deep Learning FTW!"
+}
+```
+
+## Параметри шляху, що містять шляхи { #path-parameters-containing-paths }
+
+Припустімо, у вас є *операція шляху* зі шляхом `/files/{file_path}`.
+
+Але вам потрібно, щоб `file_path` сам містив *шлях*, наприклад `home/johndoe/myfile.txt`.
+
+Отже, URL для цього файлу виглядатиме приблизно так: `/files/home/johndoe/myfile.txt`.
+
+### Підтримка OpenAPI { #openapi-support }
+
+OpenAPI не підтримує спосіб оголошення *параметра шляху*, який має містити всередині *шлях*, оскільки це може призвести до сценаріїв, які складно тестувати та визначати.
+
+Проте ви все одно можете зробити це в **FastAPI**, використовуючи один із внутрішніх інструментів Starlette.
+
+І документація все ще працюватиме, хоча й не додаватиме жодної документації, яка б казала, що параметр має містити шлях.
+
+### Конвертер шляху { #path-convertor }
+
+Використовуючи опцію безпосередньо зі Starlette, ви можете оголосити *параметр шляху*, що містить *шлях*, використовуючи URL на кшталт:
+
+```
+/files/{file_path:path}
+```
+
+У цьому випадку ім’я параметра — `file_path`, а остання частина `:path` вказує, що параметр має відповідати будь-якому *шляху*.
+
+Отже, ви можете використати його так:
+
+{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}
+
+/// tip | Порада
+
+Вам може знадобитися, щоб параметр містив `/home/johndoe/myfile.txt` із початковою косою рискою (`/`).
+
+У такому випадку URL виглядатиме так: `/files//home/johndoe/myfile.txt`, із подвійною косою рискою (`//`) між `files` і `home`.
+
+///
+
+## Підсумок { #recap }
+
+З **FastAPI**, використовуючи короткі, інтуїтивно зрозумілі та стандартні оголошення типів Python, ви отримуєте:
+
+* Підтримку редактора: перевірка помилок, автодоповнення тощо.
+* Перетворення даних «парсинг»
+* Валідацію даних
+* Анотацію API та автоматичну документацію
+
+І вам потрібно оголосити їх лише один раз.
+
+Це, ймовірно, основна видима перевага **FastAPI** порівняно з альтернативними фреймворками (окрім сирої продуктивності).
diff --git a/docs/uk/docs/tutorial/query-param-models.md b/docs/uk/docs/tutorial/query-param-models.md
new file mode 100644
index 0000000000000..5affc8a6c26b3
--- /dev/null
+++ b/docs/uk/docs/tutorial/query-param-models.md
@@ -0,0 +1,68 @@
+# Моделі параметрів запиту { #query-parameter-models }
+
+Якщо у Вас є група **параметрів запиту**, які пов’язані між собою, Ви можете створити **Pydantic-модель** для їх оголошення.
+
+Це дозволить Вам **повторно використовувати модель** у **різних місцях**, а також оголошувати перевірки та метадані для всіх параметрів одночасно. 😎
+
+/// note | Примітка
+
+Ця можливість підтримується, починаючи з версії FastAPI `0.115.0`. 🤓
+
+///
+
+## Параметри запиту з Pydantic-моделлю { #query-parameters-with-a-pydantic-model }
+
+Оголосіть **параметри запиту**, які Вам потрібні, у **Pydantic-моделі**, а потім оголосіть цей параметр як `Query`:
+
+{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}
+
+**FastAPI** буде **витягувати** дані для **кожного поля** з **параметрів запиту** у запиті та передавати їх у визначену вами Pydantic-модель.
+
+## Перевірте документацію { #check-the-docs }
+
+Ви можете побачити параметри запиту в UI документації за `/docs`:
+
+
+
+
+### Список query параметрів / кілька значень за замовчуванням { #query-parameter-list-multiple-values-with-defaults }
+
+Ви також можете визначити значення за замовчуванням `list`, якщо жодне значення не було передане:
+
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
+
+Якщо ви перейдете за посиланням:
+
+```
+http://localhost:8000/items/
+```
+
+то значення `q` за замовчуванням буде: `["foo", "bar"]`, і ваша відповідь виглядатиме так:
+
+```JSON
+{
+ "q": [
+ "foo",
+ "bar"
+ ]
+}
+```
+
+#### Використання тільки `list` { #using-just-list }
+
+Ви також можете використовувати `list` напряму замість `list[str]`:
+
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
+
+/// note | Примітка
+
+Майте на увазі, що в цьому випадку FastAPI не перевірятиме вміст списку.
+
+Наприклад, `list[int]` перевірятиме (і документуватиме), що вміст списку — цілі числа. Але `list` без уточнення цього не робитиме.
+
+///
+
+## Оголосити більше метаданих { #declare-more-metadata }
+
+Ви можете додати більше інформації про параметр.
+
+Ця інформація буде включена у згенерований OpenAPI та використана інтерфейсами документації та зовнішніми інструментами.
+
+/// note | Примітка
+
+Майте на увазі, що різні інструменти можуть мати різний рівень підтримки OpenAPI.
+
+Деякі з них можуть ще не відображати всю додаткову інформацію, хоча в більшості випадків відсутню функцію вже заплановано до реалізації.
+
+///
+
+Ви можете додати `title`:
+
+{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *}
+
+А також `description`:
+
+{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *}
+
+## Аліаси параметрів { #alias-parameters }
+
+Уявіть, що ви хочете, щоб параметр називався `item-query`.
+
+Наприклад:
+
+```
+http://127.0.0.1:8000/items/?item-query=foobaritems
+```
+
+Але `item-query` — це некоректна назва змінної в Python.
+
+Найближчий допустимий варіант — `item_query`.
+
+Проте вам потрібно, щоб параметр залишався саме `item-query`...
+
+У такому випадку можна оголосити `alias`, і саме він буде використовуватися для отримання значення параметра:
+
+{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *}
+
+## Позначення параметрів як застарілих { #deprecating-parameters }
+
+Припустімо, що вам більше не подобається цей параметр.
+
+Вам потрібно залишити його на деякий час, оскільки ним користуються клієнти, але ви хочете, щоб документація чітко показувала, що він є застарілий.
+
+Тоді передайте параметр `deprecated=True` до `Query`:
+
+{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *}
+
+Документація буде показувати це таким чином:
+
+
+
+## Виняток параметрів з OpenAPI { #exclude-parameters-from-openapi }
+
+Щоб виключити query параметр зі згенерованої схеми OpenAPI (і, таким чином, з автоматичних систем документації), встановіть параметр `include_in_schema` для `Query` в `False`:
+
+{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *}
+
+## Кастомна валідація { #custom-validation }
+
+Можуть бути випадки, коли вам потрібно провести кастомну валідацію, яку не можна реалізувати за допомогою параметрів, показаних вище.
+
+У таких випадках ви можете використати кастомну функцію-валідатор, яка буде застосована після звичайної валідації (наприклад, після перевірки, що значення є типом `str`).
+
+Це можна досягти за допомогою [Pydantic's `AfterValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-after-validator) в середині `Annotated`.
+
+/// tip | Порада
+
+Pydantic також має [`BeforeValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-before-validator) та інші. 🤓
+
+///
+
+Наприклад, цей кастомний валідатор перевіряє, чи починається ID елемента з `isbn-` для номера книги ISBN або з `imdb-` для ID URL фільму на IMDB:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
+
+/// info | Інформація
+
+Це доступно з версії Pydantic 2 або вище. 😎
+
+///
+
+/// tip | Порада
+
+Якщо вам потрібно виконати будь-яку валідацію, яка вимагає взаємодії з будь-яким зовнішнім компонентом, таким як база даних чи інший API, замість цього слід використовувати FastAPI Dependencies — ви дізнаєтесь про них пізніше.
+
+Ці кастомні валідатори використовуються для речей, які можна перевірити лише з тими самими даними, що надані в запиті.
+
+///
+
+### Зрозумійте цей код { #understand-that-code }
+
+Головний момент — це використання `AfterValidator` з функцією всередині `Annotated`. Можете пропустити цю частину, якщо хочете. 🤸
+
+---
+
+Але якщо вам цікаво розібратися в цьому конкретному прикладі коду і вам ще не набридло, ось кілька додаткових деталей.
+
+#### Рядок із `value.startswith()` { #string-with-value-startswith }
+
+Звернули увагу? Рядок із `value.startswith()` може приймати кортеж, і тоді він перевірятиме кожне значення в кортежі:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *}
+
+#### Випадковий елемент { #a-random-item }
+
+За допомогою `data.items()` ми отримуємо ітерабельний об'єкт із кортежами, що містять ключ і значення для кожного елемента словника.
+
+Ми перетворюємо цей ітерабельний об'єкт у звичайний `list` за допомогою `list(data.items())`.
+
+Потім, використовуючи `random.choice()`, ми можемо отримати випадкове значення зі списку, тобто отримуємо кортеж із `(id, name)`. Це може бути щось на зразок `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")`.
+
+Далі ми присвоюємо ці два значення кортежу змінним `id` і `name`.
+
+Тож, якщо користувач не вказав ID елемента, він все одно отримає випадкову рекомендацію.
+
+...ми робимо все це в одному простому рядку. 🤯 Хіба ви не любите Python? 🐍
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *}
+
+## Підсумок { #recap }
+
+Ви можете оголошувати додаткові валідації та метадані для ваших параметрів.
+
+Загальні валідації та метадані:
+
+* `alias`
+* `title`
+* `description`
+* `deprecated`
+
+Валідації, специфічні для рядків:
+
+* `min_length`
+* `max_length`
+* `pattern`
+
+Кастомні валідації за допомогою `AfterValidator`.
+
+У цих прикладах ви побачили, як оголошувати валідації для значень `str`.
+
+Дивіться наступні розділи, щоб дізнатися, як оголошувати валідації для інших типів, наприклад чисел.
diff --git a/docs/uk/docs/tutorial/query-params.md b/docs/uk/docs/tutorial/query-params.md
new file mode 100644
index 0000000000000..b665a620e5761
--- /dev/null
+++ b/docs/uk/docs/tutorial/query-params.md
@@ -0,0 +1,188 @@
+# Query параметри { #query-parameters }
+
+Коли ви оголошуєте інші параметри функції, які не є частиною параметрів шляху, вони автоматично інтерпретуються як параметри «query».
+
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
+
+Query — це набір пар ключ-значення, що йдуть після символу `?` в URL, розділені символами `&`.
+
+Наприклад, в URL:
+
+```
+http://127.0.0.1:8000/items/?skip=0&limit=10
+```
+
+...параметрами query є:
+
+* `skip`: зі значенням `0`
+* `limit`: зі значенням `10`
+
+Оскільки вони є частиною URL, вони «природно» є рядками.
+
+Але коли ви оголошуєте їх із типами Python (у наведеному прикладі як `int`), вони перетворюються на цей тип і проходять перевірку відповідності.
+
+Увесь той самий процес, який застосовується до параметрів шляху, також застосовується до параметрів query:
+
+* Підтримка в редакторі (очевидно)
+* «парсинг» даних
+* Валідація даних
+* Автоматична документація
+
+## Значення за замовчуванням { #defaults }
+
+Оскільки параметри query не є фіксованою частиною шляху, вони можуть бути необов’язковими та мати значення за замовчуванням.
+
+У наведеному вище прикладі вони мають значення за замовчуванням: `skip=0` і `limit=10`.
+
+Отже, перехід за URL:
+
+```
+http://127.0.0.1:8000/items/
+```
+
+буде таким самим, як і перехід за посиланням:
+
+```
+http://127.0.0.1:8000/items/?skip=0&limit=10
+```
+
+Але якщо ви перейдете, наприклад, за посиланням:
+
+```
+http://127.0.0.1:8000/items/?skip=20
+```
+
+Значення параметрів у вашій функції будуть такими:
+
+* `skip=20`: оскільки ви вказали його в URL
+* `limit=10`: оскільки це значення за замовчуванням
+
+## Необов'язкові параметри { #optional-parameters }
+
+Так само ви можете оголосити необов’язкові параметри query, встановивши для них значення за замовчуванням `None`:
+
+{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *}
+
+У цьому випадку параметр функції `q` буде необов’язковим і за замовчуванням матиме значення `None`.
+
+/// check | Перевірте
+
+Також зверніть увагу, що **FastAPI** достатньо розумний, щоб визначити, що параметр шляху `item_id` є параметром шляху, а `q` — ні, отже, це параметр query.
+
+///
+
+## Перетворення типу параметра query { #query-parameter-type-conversion }
+
+Ви також можете оголошувати параметри типу `bool`, і вони будуть автоматично конвертовані:
+
+{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *}
+
+У цьому випадку, якщо ви перейдете за:
+
+```
+http://127.0.0.1:8000/items/foo?short=1
+```
+
+або
+
+```
+http://127.0.0.1:8000/items/foo?short=True
+```
+
+або
+
+```
+http://127.0.0.1:8000/items/foo?short=true
+```
+
+або
+
+```
+http://127.0.0.1:8000/items/foo?short=on
+```
+
+або
+
+```
+http://127.0.0.1:8000/items/foo?short=yes
+```
+
+або будь-який інший варіант написання (великі літери, перша літера велика тощо), ваша функція побачить параметр `short` зі значенням `True` типу `bool`. В іншому випадку — `False`.
+
+
+## Кілька path і query параметрів { #multiple-path-and-query-parameters }
+
+Ви можете одночасно оголошувати кілька параметрів шляху та параметрів query, **FastAPI** знає, який з них який.
+
+І вам не потрібно оголошувати їх у якомусь конкретному порядку.
+
+Вони визначаються за назвою:
+
+{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *}
+
+## Обов’язкові параметри query { #required-query-parameters }
+
+Коли ви оголошуєте значення за замовчуванням для не-path-параметрів (поки що ми бачили лише параметри query), тоді вони не є обов’язковими.
+
+Якщо ви не хочете задавати конкретне значення, а просто зробити параметр необов’язковим, задайте `None` як значення за замовчуванням.
+
+Але якщо ви хочете зробити параметр query обов’язковим, просто не вказуйте для нього значення за замовчуванням:
+
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
+
+Тут параметр query `needy` — обов’язковий параметр query типу `str`.
+
+Якщо ви відкриєте у браузері URL-адресу:
+
+```
+http://127.0.0.1:8000/items/foo-item
+```
+
+...без додавання обов’язкового параметра `needy`, ви побачите помилку на кшталт:
+
+```JSON
+{
+ "detail": [
+ {
+ "type": "missing",
+ "loc": [
+ "query",
+ "needy"
+ ],
+ "msg": "Field required",
+ "input": null
+ }
+ ]
+}
+```
+
+Оскільки `needy` є обов’язковим параметром, вам потрібно вказати його в URL:
+
+```
+http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
+```
+
+...це спрацює:
+
+```JSON
+{
+ "item_id": "foo-item",
+ "needy": "sooooneedy"
+}
+```
+
+І звісно, ви можете визначити деякі параметри як обов’язкові, деякі — зі значенням за замовчуванням, а деякі — повністю необов’язкові:
+
+{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *}
+
+У цьому випадку є 3 параметри query:
+
+* `needy`, обов’язковий `str`.
+* `skip`, `int` зі значенням за замовчуванням `0`.
+* `limit`, необов’язковий `int`.
+
+/// tip | Порада
+
+Ви також можете використовувати `Enum` так само, як і з [Параметри шляху](path-params.md#predefined-values).
+
+///
diff --git a/docs/uk/docs/tutorial/request-files.md b/docs/uk/docs/tutorial/request-files.md
new file mode 100644
index 0000000000000..f81e468d0d430
--- /dev/null
+++ b/docs/uk/docs/tutorial/request-files.md
@@ -0,0 +1,176 @@
+# Запит файлів { #request-files }
+
+Ви можете визначити файли, які будуть завантажуватися клієнтом, використовуючи `File`.
+
+/// info | Інформація
+
+Щоб отримувати завантажені файли, спочатку встановіть [`python-multipart`](https://github.com/Kludex/python-multipart).
+
+Переконайтеся, що ви створили [віртуальне середовище](../virtual-environments.md), активували його, а потім встановили його, наприклад:
+
+```console
+$ pip install python-multipart
+```
+
+Це необхідно, оскільки завантажені файли передаються у вигляді «form data».
+
+///
+
+## Імпорт `File` { #import-file }
+
+Імпортуйте `File` та `UploadFile` з `fastapi`:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
+
+## Визначення параметрів `File` { #define-file-parameters }
+
+Створіть параметри файлів так само як ви б створювали `Body` або `Form`:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
+
+/// info | Інформація
+
+`File` — це клас, який безпосередньо успадковує `Form`.
+
+Але пам’ятайте, що коли ви імпортуєте `Query`, `Path`, `File` та інші з `fastapi`, це насправді функції, які повертають спеціальні класи.
+
+///
+
+/// tip | Порада
+
+Щоб оголосити тіла файлів, вам потрібно використовувати `File`, тому що інакше параметри будуть інтерпретовані як параметри запиту або параметри тіла (JSON).
+
+///
+
+Файли будуть завантажені у вигляді «form data».
+
+Якщо ви оголосите тип параметра *функції операції шляху* як `bytes`, **FastAPI** прочитає файл за вас, і ви отримаєте його вміст у вигляді `bytes`.
+
+Майте на увазі, що це означає, що весь вміст буде збережено в пам'яті. Це працюватиме добре для малих файлів.
+
+Але є кілька випадків, у яких вам може бути корисно використовувати `UploadFile`.
+
+## Параметри файлу з `UploadFile` { #file-parameters-with-uploadfile }
+
+Визначте параметр файлу з типом `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
+
+Використання `UploadFile` має кілька переваг перед `bytes`:
+
+* Вам не потрібно використовувати `File()` у значенні за замовчуванням параметра.
+* Використовується «spooled» файл:
+ * Файл зберігається в пам'яті до досягнення максимального обмеження розміру, після чого він буде збережений на диску.
+* Це означає, що він добре працюватиме для великих файлів, таких як зображення, відео, великі двійкові файли тощо, не споживаючи всю пам'ять.
+* Ви можете отримати метадані про завантажений файл.
+* Він має [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) `async` інтерфейс.
+* Він надає фактичний об'єкт Python [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile), який можна передавати безпосередньо іншим бібліотекам, що очікують file-like об'єкт.
+
+### `UploadFile` { #uploadfile }
+
+`UploadFile` має такі атрибути:
+
+* `filename`: Рядок `str` з оригінальною назвою файлу, який був завантажений (наприклад, `myimage.jpg`).
+* `content_type`: Рядок `str` з типом вмісту (MIME type / media type) (наприклад, `image/jpeg`).
+* `file`: [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) ([file-like](https://docs.python.org/3/glossary.html#term-file-like-object) об'єкт). Це фактичний файловий об'єкт Python, який ви можете передавати безпосередньо іншим функціям або бібліотекам, що очікують «file-like» об'єкт.
+
+`UploadFile` має такі асинхронні `async` методи. Вони всі викликають відповідні методи файлу під капотом (використовуючи внутрішній `SpooledTemporaryFile`).
+
+* `write(data)`: Записує `data` (`str` або `bytes`) у файл.
+* `read(size)`: Читає `size` (`int`) байтів/символів з файлу.
+* `seek(offset)`: Переходить до байтової позиції `offset` (`int`) у файлі.
+ * Наприклад, `await myfile.seek(0)` перейде на початок файлу.
+ * Це особливо корисно, якщо ви виконаєте `await myfile.read()` один раз, а потім потрібно знову прочитати вміст.
+* `close()`: Закриває файл.
+
+Оскільки всі ці методи є асинхронними `async` методами, вам потрібно їх «await»-ити.
+
+Наприклад, всередині `async` *функції операції шляху* ви можете отримати вміст за допомогою:
+
+```Python
+contents = await myfile.read()
+```
+
+Якщо ви знаходитесь у звичайній `def` *функції операції шляху*, ви можете отримати доступ до `UploadFile.file` безпосередньо, наприклад:
+
+```Python
+contents = myfile.file.read()
+```
+
+/// note | Технічні деталі `async`
+
+Коли ви використовуєте `async` методи, **FastAPI** виконує файлові методи у пулі потоків і очікує на них.
+
+///
+
+/// note | Технічні деталі Starlette
+
+`UploadFile` у **FastAPI** успадковується безпосередньо від `UploadFile` у **Starlette**, але додає деякі необхідні частини, щоб зробити його сумісним із **Pydantic** та іншими частинами FastAPI.
+
+///
+
+## Що таке «Form Data» { #what-is-form-data }
+
+Спосіб, у який HTML-форми (``) надсилають дані на сервер, зазвичай використовує «спеціальне» кодування для цих даних, відмінне від JSON.
+
+**FastAPI** забезпечить зчитування цих даних з правильного місця, а не з JSON.
+
+/// note | Технічні деталі
+
+Дані з форм зазвичай кодуються за допомогою «media type» `application/x-www-form-urlencoded`, якщо вони не містять файлів.
+
+Але якщо форма містить файли, вона кодується як `multipart/form-data`. Якщо ви використовуєте `File`, **FastAPI** знатиме, що потрібно отримати файли з правильної частини тіла.
+
+Якщо ви хочете дізнатися більше про ці типи кодування та формові поля, ознайомтеся з [MDN web docs для `POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST).
+
+///
+
+/// warning | Попередження
+
+Ви можете оголосити кілька параметрів `File` і `Form` в *операції шляху*, але ви не можете одночасно оголошувати поля `Body`, які ви очікуєте отримати як JSON, оскільки запит матиме тіло, закодоване як `multipart/form-data`, а не `application/json`.
+
+Це не обмеження **FastAPI**, а частина протоколу HTTP.
+
+///
+
+## Необов’язкове завантаження файлу { #optional-file-upload }
+
+Ви можете зробити файл необов’язковим, використовуючи стандартні анотації типів і встановивши значення за замовчуванням `None`:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## `UploadFile` із додатковими метаданими { #uploadfile-with-additional-metadata }
+
+Ви також можете використовувати `File()` разом із `UploadFile`, наприклад, щоб встановити додаткові метадані:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
+
+## Завантаження кількох файлів { #multiple-file-uploads }
+
+Можна завантажувати кілька файлів одночасно.
+
+Вони будуть пов’язані з одним і тим самим «form field», який передається у вигляді «form data».
+
+Щоб це реалізувати, потрібно оголосити список `bytes` або `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
+
+Ви отримаєте, як і було оголошено, `list` із `bytes` або `UploadFile`.
+
+/// note | Технічні деталі
+
+Ви також можете використати `from starlette.responses import HTMLResponse`.
+
+**FastAPI** надає ті ж самі `starlette.responses`, що й `fastapi.responses`, просто для зручності для вас, розробника. Але більшість доступних відповідей надходять безпосередньо від Starlette.
+
+///
+
+### Завантаження кількох файлів із додатковими метаданими { #multiple-file-uploads-with-additional-metadata }
+
+Так само як і раніше, ви можете використовувати `File()`, щоб встановити додаткові параметри навіть для `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
+
+## Підсумок { #recap }
+
+Використовуйте `File`, `bytes` та `UploadFile`, щоб оголошувати файли для завантаження в запиті, надіслані у вигляді form data.
diff --git a/docs/uk/docs/tutorial/request-form-models.md b/docs/uk/docs/tutorial/request-form-models.md
new file mode 100644
index 0000000000000..6f785016dad13
--- /dev/null
+++ b/docs/uk/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# Моделі форм { #form-models }
+
+У FastAPI ви можете використовувати **Pydantic-моделі** для оголошення **полів форми**.
+
+/// info
+
+Щоб використовувати форми, спочатку встановіть [`python-multipart`](https://github.com/Kludex/python-multipart).
+
+Переконайтеся, що ви створили [віртуальне середовище](../virtual-environments.md), активували його, а потім встановили його, наприклад:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note
+
+Це підтримується, починаючи з FastAPI версії `0.113.0`. 🤓
+
+///
+
+## Pydantic-моделі для форм { #pydantic-models-for-forms }
+
+Вам просто потрібно оголосити **Pydantic-модель** з полями, які ви хочете отримати як **поля форми**, а потім оголосити параметр як `Form`:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
+
+**FastAPI** **витягне** дані для **кожного поля** з **формових даних** у запиті та надасть вам Pydantic-модель, яку ви визначили.
+
+## Перевірте документацію { #check-the-docs }
+
+Ви можете перевірити це в UI документації за `/docs`:
+
+
+
+
+І обидві моделі будуть використані для інтерактивної документації API:
+
+
+
+## Інші анотації типів повернення { #other-return-type-annotations }
+
+Можуть бути випадки, коли ви повертаєте щось, що не є валідним полем Pydantic, і анотуєте це у функції лише для того, щоб отримати підтримку від інструментів (редактора, mypy тощо).
+
+### Повернути Response напряму { #return-a-response-directly }
+
+Найпоширенішим випадком буде [повернення Response напряму, як пояснюється пізніше у розширеній документації](../advanced/response-directly.md).
+
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
+
+Цей простий випадок автоматично обробляється FastAPI, тому що анотація типу повернення — це клас (або підклас) `Response`.
+
+І інструменти також будуть задоволені, бо і `RedirectResponse`, і `JSONResponse` є підкласами `Response`, отже анотація типу коректна.
+
+### Анотувати підклас Response { #annotate-a-response-subclass }
+
+Ви також можете використати підклас `Response` в анотації типу:
+
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
+
+Це теж працюватиме, бо `RedirectResponse` — підклас `Response`, і FastAPI автоматично обробить цей простий випадок.
+
+### Некоректні анотації типу повернення { #invalid-return-type-annotations }
+
+Але коли ви повертаєте якийсь інший довільний об’єкт, що не є валідним типом Pydantic (наприклад, об’єкт бази даних), і анотуєте його так у функції, FastAPI спробує створити модель відповіді Pydantic на основі цієї анотації типу і це завершиться помилкою.
+
+Те саме станеться, якщо у вас буде об'єднання між різними типами, де один або більше не є валідними типами Pydantic, наприклад, це завершиться помилкою 💥:
+
+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
+
+...це не працює, тому що анотація типу не є типом Pydantic і не є просто одним класом `Response` або його підкласом, це union (будь-який із двох) між `Response` і `dict`.
+
+### Вимкнути модель відповіді { #disable-response-model }
+
+Продовжуючи приклад вище, можливо, ви не хочете мати стандартну валідацію даних, документацію, фільтрацію тощо, які виконує FastAPI.
+
+Але ви можете все одно хотіти залишити анотацію типу повернення у функції, щоб отримати підтримку від інструментів, як-от редактори та перевірки типів (наприклад, mypy).
+
+У такому випадку ви можете вимкнути генерацію моделі відповіді, встановивши `response_model=None`:
+
+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}
+
+Це змусить FastAPI пропустити генерацію моделі відповіді, і таким чином ви зможете використовувати будь-які потрібні анотації типів повернення без впливу на ваш FastAPI застосунок. 🤓
+
+## Параметри кодування моделі відповіді { #response-model-encoding-parameters }
+
+Ваша модель відповіді може мати значення за замовчуванням, наприклад:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}
+
+* `description: Union[str, None] = None` (або `str | None = None` у Python 3.10) має значення за замовчуванням `None`.
+* `tax: float = 10.5` має значення за замовчуванням `10.5`.
+* `tags: List[str] = []` має значення за замовчуванням порожній список: `[]`.
+
+але ви можете захотіти не включати їх у результат, якщо вони фактично не були збережені.
+
+Наприклад, якщо у вас є моделі з багатьма необов’язковими атрибутами у NoSQL базі даних, але ви не хочете надсилати дуже довгі JSON-відповіді, повні значень за замовчуванням.
+
+### Використовуйте параметр `response_model_exclude_unset` { #use-the-response-model-exclude-unset-parameter }
+
+Ви можете встановити параметр *декоратора операції шляху* `response_model_exclude_unset=True`:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}
+
+і ці значення за замовчуванням не будуть включені у відповідь, лише значення, які фактично встановлені.
+
+Отже, якщо ви надішлете запит до цієї *операції шляху* для елемента з ID `foo`, відповідь (без включення значень за замовчуванням) буде:
+
+```JSON
+{
+ "name": "Foo",
+ "price": 50.2
+}
+```
+
+/// info | Інформація
+
+Ви також можете використовувати:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+як описано в [документації Pydantic](https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict) для `exclude_defaults` та `exclude_none`.
+
+///
+
+#### Дані зі значеннями для полів із типовими значеннями { #data-with-values-for-fields-with-defaults }
+
+Але якщо ваші дані мають значення для полів моделі з типовими значеннями, як у елемента з ID `bar`:
+
+```Python hl_lines="3 5"
+{
+ "name": "Bar",
+ "description": "The bartenders",
+ "price": 62,
+ "tax": 20.2
+}
+```
+
+вони будуть включені у відповідь.
+
+#### Дані з тими самими значеннями, що й типові { #data-with-the-same-values-as-the-defaults }
+
+Якщо дані мають ті самі значення, що й типові, як у елемента з ID `baz`:
+
+```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`.
+
+Це може бути list (`[]`), `float` зі значенням `10.5` тощо.
+
+///
+
+### `response_model_include` та `response_model_exclude` { #response-model-include-and-response-model-exclude }
+
+Ви також можете використовувати параметри *декоратора операції шляху* `response_model_include` та `response_model_exclude`.
+
+Вони приймають `set` зі `str` з іменами атрибутів, які потрібно включити (пропускаючи решту) або виключити (включаючи решту).
+
+Це можна використовувати як швидкий спосіб, якщо у вас є лише одна модель Pydantic і ви хочете видалити деякі дані з виводу.
+
+/// tip | Порада
+
+Але все ж рекомендується використовувати описані вище підходи, застосовуючи кілька класів, замість цих параметрів.
+
+Це тому, що JSON Schema, який генерується в OpenAPI вашого застосунку (і в документації), все одно буде відповідати повній моделі, навіть якщо ви використовуєте `response_model_include` або `response_model_exclude`, щоб пропустити деякі атрибути.
+
+Це також стосується `response_model_by_alias`, який працює подібним чином.
+
+///
+
+{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}
+
+/// tip | Порада
+
+Синтаксис `{"name", "description"}` створює `set` з цими двома значеннями.
+
+Він еквівалентний `set(["name", "description"])`.
+
+///
+
+#### Використання `list` замість `set` { #using-lists-instead-of-sets }
+
+Якщо ви забудете використати `set` і натомість застосуєте `list` або `tuple`, FastAPI все одно перетворить це на `set`, і все працюватиме правильно:
+
+{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}
+
+## Підсумок { #recap }
+
+Використовуйте параметр `response_model` *декоратора операції шляху*, щоб визначати моделі відповіді і особливо щоб гарантувати фільтрацію приватних даних.
+
+Використовуйте `response_model_exclude_unset`, щоб повертати лише явно встановлені значення.
diff --git a/docs/uk/docs/tutorial/response-status-code.md b/docs/uk/docs/tutorial/response-status-code.md
new file mode 100644
index 0000000000000..d453510f92e42
--- /dev/null
+++ b/docs/uk/docs/tutorial/response-status-code.md
@@ -0,0 +1,101 @@
+# Код статусу відповіді { #response-status-code }
+
+Так само, як ви можете вказати модель відповіді, ви також можете оголосити HTTP код статусу, що використовується для відповіді, за допомогою параметра `status_code` в будь-якій з *операцій шляху*:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* тощо.
+
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
+
+/// note | Примітка
+
+Зверніть увагу, що `status_code` є параметром методу «декоратора» (`get`, `post`, тощо). Не вашої *функції операції шляху*, як усі параметри та тіло.
+
+///
+
+Параметр `status_code` приймає число з HTTP кодом статусу.
+
+/// info | Інформація
+
+`status_code` також може, як альтернативу, приймати `IntEnum`, наприклад, Python [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus).
+
+///
+
+Він буде:
+
+* Повертати цей код статусу у відповіді.
+* Документувати його як такий у схемі OpenAPI (і, таким чином, в інтерфейсах користувача):
+
+
+
+/// note | Примітка
+
+Деякі коди відповіді (див. наступний розділ) вказують, що відповідь не має тіла.
+
+FastAPI знає про це і створить документацію OpenAPI, яка вказує, що тіла відповіді немає.
+
+///
+
+## Про HTTP коди статусу { #about-http-status-codes }
+
+/// note | Примітка
+
+Якщо ви вже знаєте, що таке HTTP коди статусу, перейдіть до наступного розділу.
+
+///
+
+В HTTP ви надсилаєте числовий код статусу з 3 цифр як частину відповіді.
+
+Ці коди статусу мають пов’язану назву для їх розпізнавання, але важливою частиною є число.
+
+Коротко:
+
+* `100 - 199` — для «Information». Ви рідко використовуєте їх напряму. Відповіді з такими кодами статусу не можуть мати тіла.
+* **`200 - 299`** — для «Successful» відповідей. Це ті, які ви використовуватимете найчастіше.
+ * `200` — код статусу за замовчуванням, який означає, що все було «OK».
+ * Інший приклад — `201`, «Created». Його зазвичай використовують після створення нового запису в базі даних.
+ * Особливий випадок — `204`, «No Content». Цю відповідь використовують, коли немає вмісту для повернення клієнту, і тому відповідь не повинна мати тіла.
+* **`300 - 399`** — для «Redirection». Відповіді з цими кодами статусу можуть мати або не мати тіла, за винятком `304`, «Not Modified», яка не повинна мати тіла.
+* **`400 - 499`** — для відповідей «Client error». Це другий тип, який ви, ймовірно, будете використовувати найчастіше.
+ * Приклад — `404`, для відповіді «Not Found».
+ * Для загальних помилок з боку клієнта ви можете просто використовувати `400`.
+* `500 - 599` — для помилок сервера. Ви майже ніколи не використовуєте їх напряму. Коли щось піде не так у якійсь частині коду вашого застосунку або на сервері, автоматично буде повернено один із цих кодів статусу.
+
+/// tip | Порада
+
+Щоб дізнатися більше про кожен код статусу і для чого призначений кожен із них, перегляньте [документацію MDN про HTTP коди статусу](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status).
+
+///
+
+## Скорочення, щоб запам’ятати назви { #shortcut-to-remember-the-names }
+
+Розглянемо попередній приклад ще раз:
+
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
+
+`201` — це код статусу для «Created».
+
+Але вам не потрібно запам'ятовувати, що означає кожен із цих кодів.
+
+Ви можете використовувати зручні змінні з `fastapi.status`.
+
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
+
+Вони — просто для зручності, містять те саме число, але так ви можете скористатися автозаповненням редактора, щоб знайти їх:
+
+
+
+/// note | Технічні деталі
+
+Ви також можете використати `from starlette import status`.
+
+**FastAPI** надає той самий `starlette.status` як `fastapi.status` просто як зручність для вас, розробника. Але він походить безпосередньо зі Starlette.
+
+///
+
+## Зміна значення за замовчуванням { #changing-the-default }
+
+Пізніше, у [Просунутому посібнику користувача](../advanced/response-change-status-code.md), ви побачите, як повертати інший код статусу, ніж значення за замовчуванням, яке ви оголошуєте тут.
diff --git a/docs/uk/docs/tutorial/schema-extra-example.md b/docs/uk/docs/tutorial/schema-extra-example.md
new file mode 100644
index 0000000000000..742871e394abb
--- /dev/null
+++ b/docs/uk/docs/tutorial/schema-extra-example.md
@@ -0,0 +1,202 @@
+# Декларування прикладів вхідних даних { #declare-request-example-data }
+
+Ви можете задати приклади даних, які ваш застосунок може отримувати.
+
+Ось кілька способів, як це зробити.
+
+## Додаткові дані Схеми JSON у моделях Pydantic { #extra-json-schema-data-in-pydantic-models }
+
+Ви можете задати `examples` для моделі Pydantic, які буде додано до згенерованої Схеми JSON.
+
+{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}
+
+Ця додаткова інформація буде додана як є до **Схеми JSON** для цієї моделі, і вона буде використана в документації до API.
+
+Ви можете використати атрибут `model_config`, який приймає `dict`, як описано в [документації Pydantic: Configuration](https://docs.pydantic.dev/latest/api/config/).
+
+Ви можете встановити `"json_schema_extra"` як `dict`, що містить будь-які додаткові дані, які ви хочете відобразити у згенерованій Схемі JSON, включаючи `examples`.
+
+/// tip | Порада
+
+Ви можете використати ту ж техніку, щоб розширити Схему JSON і додати власну додаткову інформацію.
+
+Наприклад, ви можете використати її для додавання метаданих для інтерфейсу користувача на фронтенді тощо.
+
+///
+
+/// info | Інформація
+
+OpenAPI 3.1.0 (який використовується починаючи з FastAPI 0.99.0) додав підтримку `examples`, що є частиною стандарту **Схеми JSON**.
+
+До цього підтримувався лише ключ `example` з одним прикладом. Він все ще підтримується в OpenAPI 3.1.0, але є застарілим і не входить до стандарту Схеми JSON. Тому рекомендується перейти з `example` на `examples`. 🤓
+
+Більше про це можна прочитати в кінці цієї сторінки.
+
+///
+
+## Додаткові аргументи `Field` { #field-additional-arguments }
+
+Коли ви використовуєте `Field()` у моделях Pydantic, ви також можете вказати додаткові `examples`:
+
+{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}
+
+## `examples` у Схемі JSON - OpenAPI { #examples-in-json-schema-openapi }
+
+При використанні будь-кого з наступного:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+ви також можете задати набір `examples` з додатковою інформацією, яка буде додана до їхніх **Схем JSON** у **OpenAPI**.
+
+### `Body` з `examples` { #body-with-examples }
+
+Тут ми передаємо `examples`, які містять один приклад очікуваних даних у `Body()`:
+
+{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *}
+
+### Приклад у UI документації { #example-in-the-docs-ui }
+
+За допомогою будь-якого з наведених вище методів це виглядатиме так у `/docs`:
+
+
+
+### `Body` з кількома `examples` { #body-with-multiple-examples }
+
+Звичайно, ви також можете передати кілька `examples`:
+
+{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *}
+
+Коли ви це робите, приклади будуть частиною внутрішньої **Схеми JSON** для цих даних тіла.
+
+Втім, на час написання цього, Swagger UI - інструмент, який відповідає за відображення UI документації - не підтримує показ кількох прикладів для даних у **Схемі JSON**. Але нижче можна прочитати про обхідний шлях.
+
+### Специфічні для OpenAPI `examples` { #openapi-specific-examples }
+
+Ще до того, як **Схема JSON** почала підтримувати `examples`, OpenAPI вже мала підтримку іншого поля, яке також називається `examples`.
+
+Це **специфічне для OpenAPI** поле `examples` розміщується в іншому розділі специфікації OpenAPI. Воно розміщується в **деталях кожної *операції шляху***, а не всередині кожної Схеми JSON.
+
+І Swagger UI вже давно підтримує це поле `examples`. Тому ви можете використовувати його, щоб **відображати** різні **приклади в UI документації**.
+
+Форма цього специфічного для OpenAPI поля `examples` - це `dict` з **кількома прикладами** (а не `list`), кожен із яких має додаткову інформацію, яка також буде додана до **OpenAPI**.
+
+Воно не включається всередину кожної Схеми JSON, що міститься в OpenAPI, воно розміщується зовні, безпосередньо в *операції шляху*.
+
+### Використання параметра `openapi_examples` { #using-the-openapi-examples-parameter }
+
+Ви можете оголосити специфічні для OpenAPI `examples` у FastAPI за допомогою параметра `openapi_examples` для:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+Ключі `dict` ідентифікують кожен приклад, а кожне значення - це інший `dict`.
+
+Кожен специфічний `dict` прикладу в `examples` може містити:
+
+* `summary`: короткий опис прикладу.
+* `description`: розгорнутий опис, який може містити Markdown.
+* `value`: це сам приклад, який буде показано, наприклад `dict`.
+* `externalValue`: альтернатива `value`, URL-адреса, що вказує на приклад. Проте це може не підтримуватися такою кількістю інструментів, як `value`.
+
+Використання виглядає так:
+
+{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *}
+
+### Приклади OpenAPI в UI документації { #openapi-examples-in-the-docs-ui }
+
+З `openapi_examples`, доданим до `Body()`, `/docs` виглядатиме так:
+
+
+
+## Технічні деталі { #technical-details }
+
+/// tip | Порада
+
+Якщо ви вже використовуєте **FastAPI** версії **0.99.0 або вище**, ви, ймовірно, можете **пропустити** ці технічні деталі.
+
+Вони більш актуальні для старих версій, до появи OpenAPI 3.1.0.
+
+Можна вважати це коротким **історичним екскурсом** у OpenAPI та Схему JSON. 🤓
+
+///
+
+/// warning | Попередження
+
+Це дуже технічна інформація про стандарти **Схема JSON** і **OpenAPI**.
+
+Якщо вищезгадані ідеї вже працюють у вас, цього може бути достатньо, і вам, ймовірно, не потрібні ці деталі - можете пропустити.
+
+///
+
+До OpenAPI 3.1.0 OpenAPI використовував стару та модифіковану версію **Схеми JSON**.
+
+Схема JSON не мала `examples`, тож OpenAPI додала власне поле `example` до своєї модифікованої версії.
+
+OpenAPI також додала поля `example` і `examples` до інших частин специфікації:
+
+* [`Parameter Object` (у специфікації)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object), який використовувався утилітами FastAPI:
+ * `Path()`
+ * `Query()`
+ * `Header()`
+ * `Cookie()`
+* [`Request Body Object`, у полі `content`, у `Media Type Object` (у специфікації)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object), який використовувався утилітами FastAPI:
+ * `Body()`
+ * `File()`
+ * `Form()`
+
+/// info | Інформація
+
+Цей старий специфічний для OpenAPI параметр `examples` тепер називається `openapi_examples`, починаючи з FastAPI `0.103.0`.
+
+///
+
+### Поле `examples` у Схемі JSON { #json-schemas-examples-field }
+
+Пізніше Схема JSON додала поле [`examples`](https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.9.5) у нову версію специфікації.
+
+А потім новий OpenAPI 3.1.0 базувався на найновішій версії (JSON Schema 2020-12), яка включала це нове поле `examples`.
+
+І тепер це нове поле `examples` має вищий пріоритет за старе одиночне (і кастомне) поле `example`, яке тепер є застарілим.
+
+Це нове поле `examples` у Схемі JSON - це **просто `list`** прикладів, а не `dict` з додатковими метаданими, як в інших місцях OpenAPI (описаних вище).
+
+/// info | Інформація
+
+Навіть після релізу OpenAPI 3.1.0 з цією новою простішою інтеграцією зі Схемою JSON, протягом певного часу Swagger UI, інструмент, який надає автоматичну документацію, не підтримував OpenAPI 3.1.0 (тепер підтримує, починаючи з версії 5.0.0 🎉).
+
+Через це версії FastAPI до 0.99.0 все ще використовували версії OpenAPI нижчі за 3.1.0.
+
+///
+
+### `examples` у Pydantic і FastAPI { #pydantic-and-fastapi-examples }
+
+Коли ви додаєте `examples` у модель Pydantic через `schema_extra` або `Field(examples=["something"])`, цей приклад додається до **Схеми JSON** для цієї моделі Pydantic.
+
+І ця **Схема JSON** Pydantic-моделі включається до **OpenAPI** вашого API, а потім використовується в UI документації.
+
+У версіях FastAPI до 0.99.0 (0.99.0 і вище використовують новіший OpenAPI 3.1.0), коли ви використовували `example` або `examples` з будь-якими іншими утилітами (`Query()`, `Body()` тощо), ці приклади не додавалися до Схеми JSON, що описує ці дані (навіть не до власної версії Схеми JSON в OpenAPI), натомість вони додавалися безпосередньо до декларації *операції шляху* в OpenAPI (поза межами частин OpenAPI, які використовують Схему JSON).
+
+Але тепер, коли FastAPI 0.99.0 і вище використовує OpenAPI 3.1.0, який використовує JSON Schema 2020-12, і Swagger UI 5.0.0 і вище, все стало більш узгодженим, і приклади включаються до Схеми JSON.
+
+### Swagger UI та специфічні для OpenAPI `examples` { #swagger-ui-and-openapi-specific-examples }
+
+Оскільки Swagger UI не підтримував кілька прикладів Схеми JSON (станом на 2023-08-26), користувачі не мали можливості показати кілька прикладів у документації.
+
+Щоб вирішити це, FastAPI `0.103.0` **додав підтримку** оголошення того самого старого **OpenAPI-специфічного** поля `examples` через новий параметр `openapi_examples`. 🤓
+
+### Підсумок { #summary }
+
+Раніше я казав, що не дуже люблю історію... а тепер подивіться на мене - читаю «технічні історичні» лекції. 😅
+
+Коротко: **оновіться до FastAPI 0.99.0 або вище** - і все стане значно **простішим, узгодженим та інтуїтивно зрозумілим**, і вам не доведеться знати всі ці історичні деталі. 😎
diff --git a/docs/uk/docs/tutorial/security/first-steps.md b/docs/uk/docs/tutorial/security/first-steps.md
new file mode 100644
index 0000000000000..bfe1962234068
--- /dev/null
+++ b/docs/uk/docs/tutorial/security/first-steps.md
@@ -0,0 +1,203 @@
+# Безпека - перші кроки { #security-first-steps }
+
+Уявімо, що ваш **backend** API працює на певному домені.
+
+А **frontend** - на іншому домені або в іншому шляху того ж домену (або у мобільному застосунку).
+
+І ви хочете, щоб frontend міг автентифікуватися в backend, використовуючи ім'я користувача та пароль.
+
+Ми можемо використати **OAuth2**, щоб збудувати це з **FastAPI**.
+
+Але заощадимо вам час на читання всієї довгої специфікації, щоб знайти лише потрібні дрібниці.
+
+Скористаймося інструментами, які надає **FastAPI**, щоб обробляти безпеку.
+
+## Як це виглядає { #how-it-looks }
+
+Спочатку просто запустімо код і подивімося, як він працює, а потім повернемося, щоб розібратися, що відбувається.
+
+## Створіть `main.py` { #create-main-py }
+
+Скопіюйте приклад у файл `main.py`:
+
+{* ../../docs_src/security/tutorial001_an_py310.py *}
+
+## Запустіть { #run-it }
+
+/// info | Інформація
+
+Пакет [`python-multipart`](https://github.com/Kludex/python-multipart) автоматично встановлюється з **FastAPI**, коли ви виконуєте команду `pip install "fastapi[standard]"`.
+
+Однак, якщо ви використовуєте команду `pip install fastapi`, пакет `python-multipart` за замовчуванням не включено.
+
+Щоб встановити його вручну, переконайтеся, що ви створили [віртуальне оточення](../../virtual-environments.md), активували його, а потім встановили:
+
+```console
+$ pip install python-multipart
+```
+
+Це тому, що **OAuth2** використовує «form data» для надсилання `username` та `password`.
+
+///
+
+Запустіть приклад:
+
+
+
+/// check | Кнопка Authorize!
+
+У вас уже є нова блискуча кнопка «Authorize».
+
+А ваша *операція шляху* має маленький замок у правому верхньому куті, на який можна натиснути.
+
+///
+
+Якщо натиснути її, з’явиться маленька форма авторизації, щоб ввести `username` і `password` (та інші необов’язкові поля):
+
+
+
+/// note | Примітка
+
+Неважливо, що ви введете у форму, поки що це не спрацює. Але ми скоро це доробимо.
+
+///
+
+Звісно, це не frontend для кінцевих користувачів, але це чудовий інструмент для інтерактивної документації всього вашого API.
+
+Ним може користуватися команда frontend (якою можете бути і ви самі).
+
+Ним можуть користуватися сторонні застосунки та системи.
+
+І ним також можете користуватися ви самі, щоб налагоджувати, перевіряти та тестувати той самий застосунок.
+
+## Потік паролю { #the-password-flow }
+
+Тепер повернімося трохи назад і розберімося, що це все таке.
+
+`password` «flow» - це один зі способів («flows»), визначених в OAuth2, для обробки безпеки та автентифікації.
+
+OAuth2 був спроєктований так, щоб backend або API могли бути незалежними від сервера, який автентифікує користувача.
+
+Але в нашому випадку той самий застосунок **FastAPI** оброблятиме і API, і автентифікацію.
+
+Тож розгляньмо це у спрощеному вигляді:
+
+- Користувач вводить `username` і `password` у frontend і натискає `Enter`.
+- Frontend (у браузері користувача) надсилає ці `username` і `password` на специфічну URL-адресу нашого API (оголошену як `tokenUrl="token"`).
+- API перевіряє ці `username` і `password` та повертає «токен» (ми ще нічого з цього не реалізували).
+ - «Токен» - це просто строка з деяким вмістом, який ми можемо пізніше використати, щоб перевірити цього користувача.
+ - Зазвичай токен налаштований на завершення строку дії через певний час.
+ - Тож користувачу доведеться знову увійти пізніше.
+ - І якщо токен викрадуть, ризик менший. Це не як постійний ключ, який працюватиме завжди (у більшості випадків).
+- Frontend тимчасово зберігає цей токен десь.
+- Користувач клікає у frontend, щоб перейти до іншого розділу вебзастосунку.
+- Frontend має отримати ще дані з API.
+ - Але для того конкретного кінцевого пункту потрібна автентифікація.
+ - Тож, щоб автентифікуватися в нашому API, він надсилає заголовок `Authorization` зі значенням `Bearer ` плюс токен.
+ - Якщо токен містить `foobar`, вміст заголовка `Authorization` буде: `Bearer foobar`.
+
+## `OAuth2PasswordBearer` у **FastAPI** { #fastapis-oauth2passwordbearer }
+
+**FastAPI** надає кілька інструментів на різних рівнях абстракції, щоб реалізувати ці функції безпеки.
+
+У цьому прикладі ми використаємо **OAuth2** з потоком **Password**, використовуючи токен **Bearer**. Це робиться за допомогою класу `OAuth2PasswordBearer`.
+
+/// info | Інформація
+
+«Bearer»-токен - не єдиний варіант.
+
+Але це найкращий для нашого сценарію.
+
+І, можливо, найкращий для більшості сценаріїв, якщо ви не експерт з OAuth2 і точно не знаєте, чому інша опція краще відповідає вашим потребам.
+
+У такому разі **FastAPI** теж надає інструменти, щоб це збудувати.
+
+///
+
+Коли ми створюємо екземпляр класу `OAuth2PasswordBearer`, ми передаємо параметр `tokenUrl`. Цей параметр містить URL, який клієнт (frontend у браузері користувача) використовуватиме, щоб надіслати `username` і `password` для отримання токена.
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
+
+/// tip | Порада
+
+Тут `tokenUrl="token"` відноситься до відносної URL-адреси `token`, яку ми ще не створили. Оскільки це відносна URL-адреса, вона еквівалентна `./token`.
+
+Тому, якщо ваш API розміщений на `https://example.com/`, це буде `https://example.com/token`. А якщо на `https://example.com/api/v1/`, тоді це буде `https://example.com/api/v1/token`.
+
+Використання відносної URL-адреси важливе, щоб ваша програма продовжувала працювати навіть у просунутому сценарії, як-от [За представником](../../advanced/behind-a-proxy.md).
+
+///
+
+Цей параметр не створює той endpoint / *операцію шляху*, а декларує, що URL `/token` буде тим, який клієнт має використовувати, щоб отримати токен. Ця інформація використовується в OpenAPI, а потім - у системах інтерактивної документації API.
+
+Незабаром ми також створимо фактичну операцію шляху.
+
+/// info | Інформація
+
+Якщо ви дуже строгий «Pythonista», вам може не подобатися стиль імені параметра `tokenUrl` замість `token_url`.
+
+Це тому, що використано ту саму назву, що і в специфікації OpenAPI. Тож якщо вам потрібно буде дослідити ці схеми безпеки глибше, ви зможете просто скопіювати та вставити її, щоб знайти більше інформації.
+
+///
+
+Змінна `oauth2_scheme` - це екземпляр `OAuth2PasswordBearer`, але це також і «викликаємий» об’єкт.
+
+Його можна викликати так:
+
+```Python
+oauth2_scheme(some, parameters)
+```
+
+Тож його можна використовувати з `Depends`.
+
+### Використання { #use-it }
+
+Тепер ви можете передати `oauth2_scheme` як залежність через `Depends`.
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+Ця залежність надасть `str`, який буде присвоєний параметру `token` *функції операції шляху*.
+
+**FastAPI** знатиме, що може використати цю залежність, щоб визначити «схему безпеки» в схемі OpenAPI (і в автоматичній документації API).
+
+/// info | Технічні деталі
+
+**FastAPI** знатиме, що може використати клас `OAuth2PasswordBearer` (оголошений у залежності), щоб визначити схему безпеки в OpenAPI, тому що він наслідує `fastapi.security.oauth2.OAuth2`, який своєю чергою наслідує `fastapi.security.base.SecurityBase`.
+
+Усі утиліти безпеки, які інтегруються з OpenAPI (і автоматичною документацією API), наслідують `SecurityBase`. Так **FastAPI** розуміє, як інтегрувати їх в OpenAPI.
+
+///
+
+## Що відбувається { #what-it-does }
+
+Вона шукатиме в запиті заголовок `Authorization`, перевірить, чи його значення - це `Bearer ` плюс деякий токен, і поверне токен як `str`.
+
+Якщо заголовка `Authorization` немає або значення не містить токена `Bearer `, вона одразу відповість помилкою зі статус-кодом 401 (`UNAUTHORIZED`).
+
+Вам навіть не потрібно перевіряти, чи існує токен, щоб повернути помилку. Ви можете бути певні: якщо ваша функція виконується, у параметрі токена буде `str`.
+
+Ви вже можете спробувати це в інтерактивній документації:
+
+
+
+Ми ще не перевіряємо дійсність токена, але це вже початок.
+
+## Підсумок { #recap }
+
+Отже, лише 3-4 додатковими рядками ви вже маєте деяку примітивну форму безпеки.
diff --git a/docs/uk/docs/tutorial/security/get-current-user.md b/docs/uk/docs/tutorial/security/get-current-user.md
new file mode 100644
index 0000000000000..2371ad9fc04e1
--- /dev/null
+++ b/docs/uk/docs/tutorial/security/get-current-user.md
@@ -0,0 +1,105 @@
+# Отримати поточного користувача { #get-current-user }
+
+У попередньому розділі система безпеки (яка базується на системі впровадження залежностей) передавала функції операції шляху `token` як `str`:
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+Але це ще не дуже корисно.
+
+Зробімо так, щоб вона повертала поточного користувача.
+
+## Створити модель користувача { #create-a-user-model }
+
+Спочатку створімо модель користувача в Pydantic.
+
+Так само, як ми використовуємо Pydantic для оголошення тіл, ми можемо використовувати його будь-де:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *}
+
+## Створити залежність `get_current_user` { #create-a-get-current-user-dependency }
+
+Створімо залежність `get_current_user`.
+
+Пам'ятаєте, що залежності можуть мати підзалежності?
+
+`get_current_user` матиме залежність із тим самим `oauth2_scheme`, який ми створили раніше.
+
+Так само, як ми робили раніше безпосередньо в операції шляху, наша нова залежність `get_current_user` отримає `token` як `str` від підзалежності `oauth2_scheme`:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *}
+
+## Отримати користувача { #get-the-user }
+
+`get_current_user` використає (фальшиву) утилітну функцію, яку ми створили, що приймає `token` як `str` і повертає нашу Pydantic-модель `User`:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *}
+
+## Впровадити поточного користувача { #inject-the-current-user }
+
+Тепер ми можемо використати той самий `Depends` з нашим `get_current_user` в операції шляху:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *}
+
+Зверніть увагу, що ми оголошуємо тип `current_user` як Pydantic-модель `User`.
+
+Це допоможе всередині функції з автодоповненням і перевірками типів.
+
+/// tip | Порада
+
+Можливо, ви пам'ятаєте, що тіла запиту також оголошуються моделями Pydantic.
+
+Тут **FastAPI** не заплутається, тому що ви використовуєте `Depends`.
+
+///
+
+/// check | Перевірте
+
+Те, як спроєктована ця система залежностей, дозволяє мати різні залежності (різні «залежні»), які всі повертають модель `User`.
+
+Ми не обмежені наявністю лише однієї залежності, що може повертати такі дані.
+
+///
+
+## Інші моделі { #other-models }
+
+Тепер ви можете отримувати поточного користувача безпосередньо у функціях операцій шляху та працювати з механізмами безпеки на рівні **впровадження залежностей**, використовуючи `Depends`.
+
+І ви можете використовувати будь-яку модель або дані для вимог безпеки (у цьому випадку Pydantic-модель `User`).
+
+Але ви не обмежені використанням якоїсь конкретної модели даних, класу чи типу.
+
+Хочете мати id та email і не мати жодного username у вашій моделі? Без проблем. Ви можете використовувати ті самі інструменти.
+
+Хочете мати просто `str`? Або лише `dict`? Або безпосередньо екземпляр класу моделі бази даних? Усе працює так само.
+
+У вашій програмі насправді входять не користувачі, а роботи, боти чи інші системи, що мають лише токен доступу? Знову ж, усе працює так само.
+
+Просто використовуйте будь-який тип моделі, будь-який клас, будь-яку базу даних, які потрібні вашій програмі. **FastAPI** подбає про це завдяки системі впровадження залежностей.
+
+## Розмір коду { #code-size }
+
+Цей приклад може здаватися багатослівним. Майте на увазі, що ми змішуємо безпеку, моделі даних, утилітні функції та операції шляху в одному файлі.
+
+Але ось ключовий момент.
+
+Речі, пов'язані з безпекою та впровадженням залежностей, пишуться один раз.
+
+І ви можете зробити це настільки складним, наскільки потрібно. І все одно мати це написаним лише один раз, в одному місці. З усією гнучкістю.
+
+Зате ви можете мати тисячі кінцевих точок (операцій шляху), що використовують одну й ту саму систему безпеки.
+
+І всі вони (або будь-яка їхня частина, яку ви захочете) можуть скористатися повторним використанням цих залежностей або будь-яких інших, які ви створите.
+
+І всі ці тисячі операцій шляху можуть бути всього у 3 рядки:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *}
+
+## Підсумок { #recap }
+
+Тепер ви можете отримувати поточного користувача безпосередньо у вашій функції операції шляху.
+
+Ми вже на півдорозі.
+
+Потрібно лише додати операцію шляху, щоб користувач/клієнт міг фактично надіслати `username` і `password`.
+
+Далі саме це.
diff --git a/docs/uk/docs/tutorial/security/index.md b/docs/uk/docs/tutorial/security/index.md
new file mode 100644
index 0000000000000..de09c728bcdd9
--- /dev/null
+++ b/docs/uk/docs/tutorial/security/index.md
@@ -0,0 +1,106 @@
+# Безпека { #security }
+
+Існує багато способів реалізувати безпеку, автентифікацію та авторизацію.
+
+І зазвичай це складна і «непроста» тема.
+
+У багатьох фреймворках і системах лише обробка безпеки та автентифікації потребує великих зусиль і коду (у багатьох випадках це може бути 50% або більше від усього написаного коду).
+
+**FastAPI** надає кілька інструментів, які допоможуть вам працювати з **безпекою** легко, швидко, стандартним способом, без необхідності вивчати всі специфікації безпеки.
+
+Але спочатку розгляньмо кілька невеликих понять.
+
+## Поспішаєте? { #in-a-hurry }
+
+Якщо вам не цікаві всі ці терміни й вам просто потрібно додати безпеку з автентифікацією на основі імені користувача та пароля *прямо зараз*, переходьте до наступних розділів.
+
+## OAuth2 { #oauth2 }
+
+OAuth2 — це специфікація, що визначає кілька способів обробки автентифікації та авторизації.
+
+Це досить об'ємна специфікація, яка охоплює кілька складних випадків використання.
+
+Вона включає способи автентифікації через «третю сторону».
+
+Саме це лежить в основі всіх систем із «увійти через Facebook, Google, X (Twitter), GitHub».
+
+### OAuth 1 { #oauth-1 }
+
+Раніше існував OAuth 1, який значно відрізняється від OAuth2 і є складнішим, оскільки містив прямі специфікації щодо того, як шифрувати комунікацію.
+
+Зараз він не дуже популярний або використовується.
+
+OAuth2 не вказує, як саме шифрувати комунікацію — він очікує, що ваш застосунок доступний через HTTPS.
+
+/// tip | Порада
+
+У розділі про **деплой** ви побачите, як налаштувати HTTPS безкоштовно з Traefik та Let's Encrypt.
+
+///
+
+## OpenID Connect { #openid-connect }
+
+OpenID Connect — ще одна специфікація, побудована на основі **OAuth2**.
+
+Вона просто розширює OAuth2, уточнюючи деякі відносно неоднозначні речі в OAuth2, щоб зробити його більш сумісним.
+
+Наприклад, вхід через Google використовує OpenID Connect (який під капотом використовує OAuth2).
+
+Але вхід через Facebook не підтримує OpenID Connect. Він має власний різновид OAuth2.
+
+### OpenID (не «OpenID Connect») { #openid-not-openid-connect }
+
+Існувала також специфікація «OpenID». Вона намагалася розвʼязати те саме, що й **OpenID Connect**, але не базувалась на OAuth2.
+
+Тож це була повністю додаткова система.
+
+Зараз вона не дуже популярна або використовується.
+
+## OpenAPI { #openapi }
+
+OpenAPI (раніше відомий як Swagger) — це відкрита специфікація для побудови API (тепер частина Linux Foundation).
+
+**FastAPI** базується на **OpenAPI**.
+
+Саме це робить можливими кілька автоматичних інтерактивних інтерфейсів документації, генерацію коду тощо.
+
+OpenAPI має спосіб визначати різні «схеми» безпеки.
+
+Використовуючи їх, ви можете скористатися всіма цими інструментами, що базуються на стандартах, зокрема цими інтерактивними системами документації.
+
+OpenAPI визначає такі схеми безпеки:
+
+* `apiKey`: специфічний для застосунку ключ, який може передаватися через:
+ * Параметр запиту.
+ * Заголовок.
+ * Кукі.
+* `http`: стандартні системи HTTP-автентифікації, включаючи:
+ * `bearer`: заголовок `Authorization` зі значенням `Bearer ` та токеном. Це успадковано з OAuth2.
+ * базову автентифікацію HTTP.
+ * HTTP дайджест тощо.
+* `oauth2`: усі способи обробки безпеки за допомогою OAuth2 (так звані «потоки»).
+ * Декілька з цих потоків підходять для створення провайдера автентифікації OAuth 2.0 (наприклад, Google, Facebook, X (Twitter), GitHub тощо):
+ * `implicit`
+ * `clientCredentials`
+ * `authorizationCode`
+ * Але є один окремий «потік», який можна ідеально використати для обробки автентифікації напряму в цьому ж застосунку:
+ * `password`: у кількох наступних розділах будуть приклади цього.
+* `openIdConnect`: має спосіб визначити, як автоматично виявляти дані автентифікації OAuth2.
+ * Саме це автоматичне виявлення визначено у специфікації OpenID Connect.
+
+
+/// tip | Порада
+
+Інтеграція інших провайдерів автентифікації/авторизації, таких як Google, Facebook, X (Twitter), GitHub тощо, також можлива і відносно проста.
+
+Найскладніше — це створити провайдера автентифікації/авторизації на кшталт таких, але **FastAPI** надає вам інструменти, щоб зробити це легко, виконуючи важку частину роботи за вас.
+
+///
+
+## Утиліти **FastAPI** { #fastapi-utilities }
+
+FastAPI надає кілька інструментів для кожної з описаних схем безпеки в модулі `fastapi.security`, які спрощують використання цих механізмів безпеки.
+
+У наступних розділах ви побачите, як додати безпеку до свого API за допомогою цих інструментів, які надає **FastAPI**.
+
+А також побачите, як це автоматично інтегрується в інтерактивну систему документації.
diff --git a/docs/uk/docs/tutorial/security/oauth2-jwt.md b/docs/uk/docs/tutorial/security/oauth2-jwt.md
new file mode 100644
index 0000000000000..64774af6d025a
--- /dev/null
+++ b/docs/uk/docs/tutorial/security/oauth2-jwt.md
@@ -0,0 +1,277 @@
+# OAuth2 з паролем (і хешуванням), Bearer з токенами JWT { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
+
+Тепер, коли ми маємо весь потік безпеки, зробімо застосунок справді захищеним, використовуючи токени JWT і безпечне хешування паролів.
+
+Цей код ви можете реально використовувати у своєму застосунку, зберігати хеші паролів у своїй базі даних тощо.
+
+Ми почнемо з того місця, де зупинилися в попередньому розділі, і розширимо його.
+
+## Про JWT { #about-jwt }
+
+JWT означає «JSON Web Tokens».
+
+Це стандарт кодування об'єкта JSON у довгий щільний рядок без пробілів. Він виглядає так:
+
+```
+eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
+```
+
+Він не зашифрований, тому кожен може відновити інформацію з вмісту.
+
+Але він підписаний. Тож коли ви отримуєте токен, який ви видали, ви можете перевірити, що справді його видали ви.
+
+Таким чином, ви можете створити токен із терміном дії, наприклад, 1 тиждень. І коли користувач повернеться наступного дня з токеном, ви знатимете, що користувач досі увійшов у вашу систему.
+
+Через тиждень токен завершить термін дії, і користувач не буде авторизований та має знову увійти, щоб отримати новий токен. І якщо користувач (або третя сторона) намагатиметься змінити токен, щоб змінити термін дії, ви це виявите, бо підписи не співпадатимуть.
+
+Якщо хочете «погратися» з токенами JWT і побачити, як вони працюють, перегляньте [https://jwt.io](https://jwt.io/).
+
+## Встановіть `PyJWT` { #install-pyjwt }
+
+Нам потрібно встановити `PyJWT`, щоб створювати та перевіряти токени JWT у Python.
+
+Переконайтеся, що ви створили [віртуальне оточення](../../virtual-environments.md), активували його і тоді встановіть `pyjwt`:
+
+
+
+Авторизуйте застосунок так само, як раніше.
+
+Використайте облікові дані:
+
+Username: `johndoe`
+Password: `secret`
+
+/// check | Перевірте
+
+Зверніть увагу, що ніде в коді немає відкритого пароля "`secret`", ми маємо лише хешовану версію.
+
+///
+
+
+
+Викличте кінцеву точку `/users/me/`, ви отримаєте відповідь:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false
+}
+```
+
+
+
+Якщо відкриєте інструменти розробника, ви побачите, що у відправлених даних є лише токен, пароль надсилається тільки в першому запиті для автентифікації користувача та отримання токена доступу, але не надсилається далі:
+
+
+
+/// note | Примітка
+
+Зверніть увагу на заголовок `Authorization` зі значенням, що починається з `Bearer `.
+
+///
+
+## Просунуте використання зі `scopes` { #advanced-usage-with-scopes }
+
+OAuth2 має поняття «scopes».
+
+Ви можете використовувати їх, щоб додати конкретний набір дозволів до токена JWT.
+
+Потім ви можете видати цей токен користувачу напряму або третій стороні для взаємодії з вашою API із набором обмежень.
+
+Ви можете дізнатися, як їх використовувати і як вони інтегровані з **FastAPI** пізніше у **просунутому посібнику користувача**.
+
+## Підсумок { #recap }
+
+Маючи все, що ви бачили досі, ви можете налаштувати захищений застосунок **FastAPI**, використовуючи стандарти на кшталт OAuth2 і JWT.
+
+Майже в будь-якому фреймворку опрацювання безпеки дуже швидко стає досить складною темою.
+
+Багато пакетів, що сильно це спрощують, змушені йти на численні компроміси з моделлю даних, базою даних і доступними можливостями. Дехто з цих пакетів, які надто все спрощують, насправді мають приховані вади безпеки.
+
+---
+
+**FastAPI** не йде на жодні компроміси з будь-якою базою даних, моделлю даних чи інструментом.
+
+Він дає вам усю гнучкість, щоб обрати ті, які найкраще підходять вашому проєкту.
+
+І ви можете напряму використовувати добре підтримувані та широко застосовувані пакети на кшталт `pwdlib` і `PyJWT`, адже **FastAPI** не вимагає жодних складних механізмів для інтеграції зовнішніх пакетів.
+
+Водночас він надає інструменти, щоб максимально спростити процес без компромісів у гнучкості, надійності чи безпеці.
+
+І ви можете використовувати та впроваджувати безпечні стандартні протоколи, як-от OAuth2, відносно простим способом.
+
+У **просунутому посібнику користувача** ви можете дізнатися більше про те, як використовувати «scopes» в OAuth2 для більш детальної системи дозволів, дотримуючись тих самих стандартів. OAuth2 зі scopes - це механізм, який використовують багато великих провайдерів автентифікації, як-от Facebook, Google, GitHub, Microsoft, X (Twitter) тощо, щоб авторизувати сторонні застосунки на взаємодію з їхніми API від імені користувачів.
diff --git a/docs/uk/docs/tutorial/security/simple-oauth2.md b/docs/uk/docs/tutorial/security/simple-oauth2.md
new file mode 100644
index 0000000000000..7c83e4c2a7ca0
--- /dev/null
+++ b/docs/uk/docs/tutorial/security/simple-oauth2.md
@@ -0,0 +1,289 @@
+# Простий OAuth2 з паролем і Bearer { #simple-oauth2-with-password-and-bearer }
+
+Тепер продовжимо з попереднього розділу і додамо відсутні частини, щоб отримати повний потік безпеки.
+
+## Отримайте `username` і `password` { #get-the-username-and-password }
+
+Ми використаємо утиліти безпеки **FastAPI**, щоб отримати `username` і `password`.
+
+OAuth2 визначає, що під час використання «потоку паролю» (який ми використовуємо) клієнт/користувач має надіслати поля `username` і `password` як дані форми.
+
+І специфікація каже, що поля мають називатися саме так. Тому `user-name` або `email` не підійдуть.
+
+Але не хвилюйтеся, у фронтенді ви можете відображати це так, як забажаєте, для кінцевих користувачів.
+
+І ваші моделі бази даних можуть використовувати будь-які інші назви.
+
+Але для *операції шляху* входу ми маємо використовувати саме ці назви, щоб бути сумісними зі специфікацією (і мати змогу, наприклад, користуватися вбудованою системою документації API).
+
+Специфікація також вказує, що `username` і `password` мають надсилатися як дані форми (тобто без JSON).
+
+### `scope` { #scope }
+
+Специфікація також каже, що клієнт може надіслати інше поле форми «`scope`».
+
+Назва поля форми — `scope` (в однині), але насправді це довга строка зі «scopes», розділеними пробілами.
+
+Кожен «scope» — це просто строка (без пробілів).
+
+Їх зазвичай використовують для оголошення конкретних прав доступу, наприклад:
+
+- `users:read` або `users:write` — поширені приклади.
+- `instagram_basic` використовується Facebook / Instagram.
+- `https://www.googleapis.com/auth/drive` використовується Google.
+
+/// info | Інформація
+
+У OAuth2 «scope» — це просто строка, що оголошує конкретний потрібний дозвіл.
+
+Не має значення, чи містить вона інші символи на кшталт `:` або чи це URL.
+
+Ці деталі залежать від реалізації.
+
+Для OAuth2 це просто строки.
+
+///
+
+## Код для отримання `username` і `password` { #code-to-get-the-username-and-password }
+
+Тепер скористаймося утилітами, наданими **FastAPI**, щоб обробити це.
+
+### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform }
+
+Спочатку імпортуйте `OAuth2PasswordRequestForm` і використайте його як залежність із `Depends` в *операції шляху* для `/token`:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}
+
+`OAuth2PasswordRequestForm` — це клас залежності, що оголошує тіло форми з:
+
+- `username`.
+- `password`.
+- Необов'язковим полем `scope` як великою строкою, складеною зі строк, розділених пробілами.
+- Необов'язковим `grant_type`.
+
+/// tip | Порада
+
+Специфікація OAuth2 насправді вимагає поле `grant_type` із фіксованим значенням `password`, але `OAuth2PasswordRequestForm` цього не примушує.
+
+Якщо вам потрібно це примусити, використовуйте `OAuth2PasswordRequestFormStrict` замість `OAuth2PasswordRequestForm`.
+
+///
+
+- Необов'язковим `client_id` (для нашого прикладу не потрібно).
+- Необов'язковим `client_secret` (для нашого прикладу не потрібно).
+
+/// info | Інформація
+
+`OAuth2PasswordRequestForm` — не спеціальний клас для **FastAPI**, як `OAuth2PasswordBearer`.
+
+`OAuth2PasswordBearer` робить так, що **FastAPI** знає, що це схема безпеки. Тому її додають таким чином до OpenAPI.
+
+Але `OAuth2PasswordRequestForm` — це просто клас залежності, який ви могли б написати самі, або ви могли б напряму оголосити параметри `Form`.
+
+Оскільки це типова задача, **FastAPI** надає його безпосередньо, щоб спростити роботу.
+
+///
+
+### Використовуйте дані форми { #use-the-form-data }
+
+/// tip | Порада
+
+Екземпляр класу залежності `OAuth2PasswordRequestForm` не матиме атрибута `scope` з довгою строкою, розділеною пробілами, натомість він матиме атрибут `scopes` зі справжнім списком строк для кожного надісланого scope.
+
+У цьому прикладі ми не використовуємо `scopes`, але ця можливість є, якщо знадобиться.
+
+///
+
+Тепер отримайте дані користувача з (фальшивої) бази даних, використовуючи `username` з поля форми.
+
+Якщо такого користувача немає, повертаємо помилку «Incorrect username or password».
+
+Для помилки використовуємо виняток `HTTPException`:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}
+
+### Перевірте пароль { #check-the-password }
+
+На цьому етапі ми маємо дані користувача з нашої бази даних, але ще не перевірили пароль.
+
+Спершу розмістимо ці дані в Pydantic-моделі `UserInDB`.
+
+Ви ніколи не повинні зберігати паролі у відкритому вигляді, тож ми використаємо (фальшиву) систему хешування паролів.
+
+Якщо паролі не збігаються, повертаємо ту саму помилку.
+
+#### Хешування паролів { #password-hashing }
+
+«Хешування» означає: перетворення деякого вмісту (у цьому випадку пароля) у послідовність байтів (просто строку), яка виглядає як нісенітниця.
+
+Кожного разу, коли ви передаєте точно той самий вміст (точно той самий пароль), ви отримуєте точно ту саму «нісенітницю».
+
+Але ви не можете перетворити цю «нісенітницю» назад у пароль.
+
+##### Навіщо використовувати хешування паролів { #why-use-password-hashing }
+
+Якщо вашу базу даних вкрадуть, зловмисник не матиме паролів користувачів у відкритому вигляді, лише хеші.
+
+Тож зловмисник не зможе спробувати використати ті самі паролі в іншій системі (оскільки багато користувачів використовують той самий пароль всюди, це було б небезпечно).
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}
+
+#### Про `**user_dict` { #about-user-dict }
+
+`UserInDB(**user_dict)` означає:
+
+Передати ключі та значення з `user_dict` безпосередньо як аргументи ключ-значення, еквівалентно до:
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ disabled = user_dict["disabled"],
+ hashed_password = user_dict["hashed_password"],
+)
+```
+
+/// info | Інформація
+
+Для повнішого пояснення `**user_dict` перегляньте [документацію для **Додаткових моделей**](../extra-models.md#about-user-in-dict).
+
+///
+
+## Поверніть токен { #return-the-token }
+
+Відповідь точки входу `token` має бути об'єктом JSON.
+
+Вона повинна містити `token_type`. У нашому випадку, оскільки ми використовуємо токени «Bearer», тип токена має бути «`bearer`».
+
+Також має бути `access_token` зі строкою, що містить наш токен доступу.
+
+Для цього простого прикладу ми зробимо повністю небезпечно і повернемо той самий `username` як токен.
+
+/// tip | Порада
+
+У наступному розділі ви побачите справді безпечну реалізацію з хешуванням паролів і токенами JWT.
+
+А поки зосередьмося на конкретних деталях, які нам потрібні.
+
+///
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}
+
+/// tip | Порада
+
+Згідно зі специфікацією, ви маєте повертати JSON з `access_token` і `token_type`, як у цьому прикладі.
+
+Це те, що ви маєте зробити самостійно у своєму коді, і переконатися, що використовуєте саме ці ключі JSON.
+
+Це майже єдине, що ви маєте зробити правильно самі, щоб відповідати специфікації.
+
+Решту **FastAPI** зробить за вас.
+
+///
+
+## Оновіть залежності { #update-the-dependencies }
+
+Тепер оновимо наші залежності.
+
+Ми хочемо отримати `current_user` лише якщо цей користувач активний.
+
+Тому створимо додаткову залежність `get_current_active_user`, яка своєю чергою використовує як залежність `get_current_user`.
+
+Обидві ці залежності просто повернуть HTTP-помилку, якщо користувача не існує або він неактивний.
+
+Отже, у нашій кінцевій точці ми отримаємо користувача лише якщо він існує, був правильно автентифікований і є активним:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}
+
+/// info | Інформація
+
+Додатковий заголовок `WWW-Authenticate` зі значенням `Bearer`, який ми тут повертаємо, також є частиною специфікації.
+
+Будь-який HTTP (помилка) зі статус-кодом 401 «UNAUTHORIZED» також має повертати заголовок `WWW-Authenticate`.
+
+У випадку токенів носія (наш випадок) значенням цього заголовка має бути `Bearer`.
+
+Фактично ви можете пропустити цей додатковий заголовок, і все одно працюватиме.
+
+Але він наданий тут, щоб відповідати специфікаціям.
+
+Також можуть існувати інструменти, які очікують і використовують його (зараз або в майбутньому), і це може бути корисно вам або вашим користувачам, зараз або в майбутньому.
+
+У цьому користь стандартів...
+
+///
+
+## Подивіться в дії { #see-it-in-action }
+
+Відкрийте інтерактивну документацію: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).
+
+### Автентифікація { #authenticate }
+
+Натисніть кнопку «Authorize».
+
+Використайте облікові дані:
+
+Користувач: `johndoe`
+
+Пароль: `secret`
+
+
+
+Після автентифікації в системі ви побачите таке:
+
+
+
+### Отримайте власні дані користувача { #get-your-own-user-data }
+
+Тепер використайте операцію `GET` зі шляхом `/users/me`.
+
+Ви отримаєте дані свого користувача, наприклад:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false,
+ "hashed_password": "fakehashedsecret"
+}
+```
+
+
+
+Якщо натиснути значок замка й вийти з системи, а потім знову спробувати ту саму операцію, ви отримаєте помилку HTTP 401 такого вигляду:
+
+```JSON
+{
+ "detail": "Not authenticated"
+}
+```
+
+### Неактивний користувач { #inactive-user }
+
+Тепер спробуйте з неактивним користувачем, автентифікуйтеся з:
+
+Користувач: `alice`
+
+Пароль: `secret2`
+
+І спробуйте використати операцію `GET` зі шляхом `/users/me`.
+
+Ви отримаєте помилку «Inactive user», наприклад:
+
+```JSON
+{
+ "detail": "Inactive user"
+}
+```
+
+## Підсумок { #recap }
+
+Тепер у вас є інструменти для реалізації повної системи безпеки на основі `username` і `password` для вашого API.
+
+Використовуючи ці інструменти, ви можете зробити систему безпеки сумісною з будь-якою базою даних і з будь-якою моделлю користувача чи даних.
+
+Єдина відсутня деталь у тому, що наразі це ще не «безпечна» реалізація.
+
+У наступному розділі ви побачите, як використовувати безпечну бібліотеку для хешування паролів і токени JWT.
diff --git a/docs/uk/docs/tutorial/server-sent-events.md b/docs/uk/docs/tutorial/server-sent-events.md
new file mode 100644
index 0000000000000..8234085cfabd1
--- /dev/null
+++ b/docs/uk/docs/tutorial/server-sent-events.md
@@ -0,0 +1,120 @@
+# Події, надіслані сервером (SSE) { #server-sent-events-sse }
+
+Ви можете транслювати дані клієнту за допомогою **Server-Sent Events** (SSE).
+
+Це подібно до [Потік JSON Lines](stream-json-lines.md), але використовує формат `text/event-stream`, який нативно підтримується браузерами через [API `EventSource`](https://developer.mozilla.org/en-US/docs/Web/API/EventSource).
+
+/// info | Інформація
+
+Додано у FastAPI 0.135.0.
+
+///
+
+## Що таке Server-Sent Events { #what-are-server-sent-events }
+
+SSE - це стандарт для трансляції даних із сервера до клієнта по HTTP.
+
+Кожна подія - це невеликий текстовий блок із «полями» на кшталт `data`, `event`, `id` та `retry`, розділений порожніми рядками.
+
+Виглядає так:
+
+```
+data: {"name": "Portal Gun", "price": 999.99}
+
+data: {"name": "Plumbus", "price": 32.99}
+
+```
+
+SSE часто використовують для стрімінгу чатів ШІ, живих сповіщень, логів і спостережуваності, а також інших випадків, коли сервер надсилає оновлення клієнту.
+
+/// tip | Порада
+
+Якщо ви хочете транслювати бінарні дані, наприклад відео чи аудіо, перегляньте просунутий посібник: [Потік даних](../advanced/stream-data.md).
+
+///
+
+## Стрімінг SSE у FastAPI { #stream-sse-with-fastapi }
+
+Щоб транслювати SSE з FastAPI, використовуйте `yield` у вашій *функції операції шляху* і встановіть `response_class=EventSourceResponse`.
+
+Імпортуйте `EventSourceResponse` з `fastapi.sse`:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[4,22] *}
+
+Кожен елемент, повернений через `yield`, кодується як JSON і надсилається в полі `data:` події SSE.
+
+Якщо ви оголосите тип повернення як `AsyncIterable[Item]`, FastAPI використає його, щоб **перевіряти**, **документувати** і **серіалізувати** дані за допомогою Pydantic.
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[10:12,23] *}
+
+/// tip | Порада
+
+Оскільки Pydantic серіалізує це на боці **Rust**, ви отримаєте значно вищу **продуктивність**, ніж якби не оголошували тип повернення.
+
+///
+
+### Не-async *функції операцій шляху* { #non-async-path-operation-functions }
+
+Ви також можете використовувати звичайні функції `def` (без `async`) і використовувати `yield` так само.
+
+FastAPI подбає про коректне виконання, щоб воно не блокувало цикл подій.
+
+Оскільки в цьому випадку функція не async, коректним типом повернення буде `Iterable[Item]`:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[28:31] hl[29] *}
+
+### Без типу повернення { #no-return-type }
+
+Можна також опустити тип повернення. FastAPI використає [`jsonable_encoder`](./encoder.md), щоб конвертувати дані і надіслати їх.
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[34:37] hl[35] *}
+
+## `ServerSentEvent` { #serversentevent }
+
+Якщо вам потрібно встановити поля SSE, такі як `event`, `id`, `retry` або `comment`, ви можете повертати через `yield` об'єкти `ServerSentEvent` замість звичайних даних.
+
+Імпортуйте `ServerSentEvent` з `fastapi.sse`:
+
+{* ../../docs_src/server_sent_events/tutorial002_py310.py hl[4,26] *}
+
+Поле `data` завжди кодується як JSON. Ви можете передати будь-яке значення, яке можна серіалізувати в JSON, включно з моделями Pydantic.
+
+## Сирі дані { #raw-data }
+
+Якщо потрібно надіслати дані **без** кодування в JSON, використовуйте `raw_data` замість `data`.
+
+Це корисно для надсилання попередньо відформатованого тексту, рядків логів або спеціальних значень «значення-сторож», як-от `[DONE]`.
+
+{* ../../docs_src/server_sent_events/tutorial003_py310.py hl[17] *}
+
+/// note | Примітка
+
+`data` і `raw_data` взаємовиключні. У кожному `ServerSentEvent` ви можете встановити лише одне з них.
+
+///
+
+## Відновлення з `Last-Event-ID` { #resuming-with-last-event-id }
+
+Коли браузер перепідключається після розриву з'єднання, він надсилає останній отриманий `id` у заголовку `Last-Event-ID`.
+
+Ви можете прочитати його як параметр заголовка і використати, щоб відновити потік із місця, де клієнт зупинився:
+
+{* ../../docs_src/server_sent_events/tutorial004_py310.py hl[25,27,31] *}
+
+## SSE з POST { #sse-with-post }
+
+SSE працює з **будь-яким HTTP-методом**, не лише з `GET`.
+
+Це корисно для протоколів на кшталт [MCP](https://modelcontextprotocol.io), які транслюють SSE через `POST`:
+
+{* ../../docs_src/server_sent_events/tutorial005_py310.py hl[14] *}
+
+## Технічні деталі { #technical-details }
+
+FastAPI реалізує деякі найкращі практики SSE «з коробки».
+
+- Надсилати **коментар «keep alive» `ping`** кожні 15 секунд, коли не було жодного повідомлення, щоб запобігти закриттю з'єднання деякими проксі, як рекомендовано у [Специфікації HTML: Події, надіслані сервером](https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes).
+- Встановити заголовок `Cache-Control: no-cache`, щоб **запобігти кешуванню** потоку.
+- Встановити спеціальний заголовок `X-Accel-Buffering: no`, щоб **запобігти буферизації** у деяких проксі, наприклад Nginx.
+
+Вам не потрібно нічого з цим робити, воно працює «з коробки». 🤓
diff --git a/docs/uk/docs/tutorial/sql-databases.md b/docs/uk/docs/tutorial/sql-databases.md
new file mode 100644
index 0000000000000..57b67226a0095
--- /dev/null
+++ b/docs/uk/docs/tutorial/sql-databases.md
@@ -0,0 +1,357 @@
+# SQL (реляційні) бази даних { #sql-relational-databases }
+
+**FastAPI** не вимагає від вас використовувати SQL (реляційну) базу даних. Але ви можете скористатися будь-якою базою даних, яку забажаєте.
+
+Тут ми розглянемо приклад з [SQLModel](https://sqlmodel.tiangolo.com/).
+
+**SQLModel** побудовано поверх [SQLAlchemy](https://www.sqlalchemy.org/) та Pydantic. Її створив той самий автор, що і **FastAPI**, як ідеальну пару для застосунків FastAPI, яким потрібні **SQL бази даних**.
+
+/// tip | Порада
+
+Ви можете використовувати будь-яку іншу бібліотеку для SQL або NoSQL баз (інколи їх називають "ORMs"), FastAPI нічого не нав’язує. 😎
+
+///
+
+Оскільки SQLModel базується на SQLAlchemy, ви можете легко використовувати будь-яку базу даних, яку підтримує SQLAlchemy (а отже й SQLModel), наприклад:
+
+* PostgreSQL
+* MySQL
+* SQLite
+* Oracle
+* Microsoft SQL Server тощо
+
+У цьому прикладі ми використаємо **SQLite**, оскільки вона зберігається в одному файлі, а Python має вбудовану підтримку. Тож ви можете скопіювати цей приклад і запустити «як є».
+
+Пізніше, для вашого продакшн-застосунку, ви можете перейти на сервер бази даних, наприклад **PostgreSQL**.
+
+/// tip | Порада
+
+Існує офіційний генератор проєкту з **FastAPI** та **PostgreSQL**, включно з фронтендом та іншими інструментами: [https://github.com/fastapi/full-stack-fastapi-template](https://github.com/fastapi/full-stack-fastapi-template)
+
+///
+
+Це дуже простий і короткий навчальний посібник. Якщо ви хочете вивчити бази даних загалом, SQL або більш просунуті можливості, зверніться до [документації SQLModel](https://sqlmodel.tiangolo.com/).
+
+## Встановіть `SQLModel` { #install-sqlmodel }
+
+Спочатку переконайтеся, що ви створили [віртуальне оточення](../virtual-environments.md), активували його та встановили `sqlmodel`:
+
+
+
+- FastAPI framework, hiệu năng cao, dễ học, dễ code, sẵn sàng để tạo ra sản phẩm -
- - ---- - -**Tài liệu**: https://fastapi.tiangolo.com - -**Mã nguồn**: https://github.com/tiangolo/fastapi - ---- - -FastAPI là một web framework hiện đại, hiệu năng cao để xây dựng web APIs với Python 3.7+ dựa trên tiêu chuẩn Python type hints. - -Những tính năng như: - -* **Nhanh**: Hiệu năng rất cao khi so sánh với **NodeJS** và **Go** (cảm ơn Starlette và Pydantic). [Một trong những Python framework nhanh nhất](#performance). -* **Code nhanh**: Tăng tốc độ phát triển tính năng từ 200% tới 300%. * -* **Ít lỗi hơn**: Giảm khoảng 40% những lỗi phát sinh bởi con người (nhà phát triển). * -* **Trực giác tốt hơn**: Được các trình soạn thảo hỗ tuyệt vời. Completion mọi nơi. Ít thời gian gỡ lỗi. -* **Dễ dàng**: Được thiết kế để dễ dàng học và sử dụng. Ít thời gian đọc tài liệu. -* **Ngắn**: Tối thiểu code bị trùng lặp. Nhiều tính năng được tích hợp khi định nghĩa tham số. Ít lỗi hơn. -* **Tăng tốc**: Có được sản phẩm cùng với tài liệu (được tự động tạo) có thể tương tác. -* **Được dựa trên các tiêu chuẩn**: Dựa trên (và hoàn toàn tương thích với) các tiêu chuẩn mở cho APIs : OpenAPI (trước đó được biết đến là Swagger) và JSON Schema. - -* ước tính được dựa trên những kiểm chứng trong nhóm phát triển nội bộ, xây dựng các ứng dụng sản phẩm. - -## Nhà tài trợ - - - -{% if sponsors %} -{% for sponsor in sponsors.gold -%} -async def...uvicorn main:app --reload...ujson - "Parse" JSON nhanh hơn.
-* email_validator - cho email validation.
-
-Sử dụng Starlette:
-
-* httpx - Bắt buộc nếu bạn muốn sử dụng `TestClient`.
-* jinja2 - Bắt buộc nếu bạn muốn sử dụng cấu hình template engine mặc định.
-* python-multipart - Bắt buộc nếu bạn muốn hỗ trợ "parsing", form với `request.form()`.
-* itsdangerous - Bắt buộc để hỗ trợ `SessionMiddleware`.
-* pyyaml - Bắt buộc để hỗ trợ `SchemaGenerator` cho Starlette (bạn có thể không cần nó trong FastAPI).
-* ujson - Bắt buộc nếu bạn muốn sử dụng `UJSONResponse`.
-
-Sử dụng bởi FastAPI / Starlette:
-
-* uvicorn - Server để chạy ứng dụng của bạn.
-* orjson - Bắt buộc nếu bạn muốn sử dụng `ORJSONResponse`.
-
-Bạn có thể cài đặt tất cả những dependency trên với `pip install "fastapi[all]"`.
-
-## Giấy phép
-
-Dự án này được cấp phép dưới những điều lệ của giấy phép MIT.
diff --git a/docs/vi/docs/python-types.md b/docs/vi/docs/python-types.md
deleted file mode 100644
index 7f4f51131f513..0000000000000
--- a/docs/vi/docs/python-types.md
+++ /dev/null
@@ -1,545 +0,0 @@
-# Giới thiệu kiểu dữ liệu Python
-
-Python hỗ trợ tùy chọn "type hints" (còn được gọi là "type annotations").
-
-Những **"type hints"** hay chú thích là một cú pháp đặc biệt cho phép khai báo kiểu dữ liệu của một biến.
-
-Bằng việc khai báo kiểu dữ liệu cho các biến của bạn, các trình soạn thảo và các công cụ có thể hỗ trợ bạn tốt hơn.
-
-Đây chỉ là một **hướng dẫn nhanh** về gợi ý kiểu dữ liệu trong Python. Nó chỉ bao gồm những điều cần thiết tối thiểu để sử dụng chúng với **FastAPI**... đó thực sự là rất ít.
-
-**FastAPI** hoàn toàn được dựa trên những gợi ý kiểu dữ liệu, chúng mang đến nhiều ưu điểm và lợi ích.
-
-Nhưng thậm chí nếu bạn không bao giờ sử dụng **FastAPI**, bạn sẽ được lợi từ việc học một ít về chúng.
-
-!!! note
- Nếu bạn là một chuyên gia về Python, và bạn đã biết mọi thứ về gợi ý kiểu dữ liệu, bỏ qua và đi tới chương tiếp theo.
-
-## Động lực
-
-Hãy bắt đầu với một ví dụ đơn giản:
-
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
-
-Kết quả khi gọi chương trình này:
-
-```
-John Doe
-```
-
-Hàm thực hiện như sau:
-
-* Lấy một `first_name` và `last_name`.
-* Chuyển đổi kí tự đầu tiên của mỗi biến sang kiểu chữ hoa với `title()`.
-* Nối chúng lại với nhau bằng một kí tự trắng ở giữa.
-
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
-
-### Sửa đổi
-
-Nó là một chương trình rất đơn giản.
-
-Nhưng bây giờ hình dung rằng bạn đang viết nó từ đầu.
-
-Tại một vài thời điểm, bạn sẽ bắt đầu định nghĩa hàm, bạn có các tham số...
-
-Nhưng sau đó bạn phải gọi "phương thức chuyển đổi kí tự đầu tiên sang kiểu chữ hoa".
-
-Có phải là `upper`? Có phải là `uppercase`? `first_uppercase`? `capitalize`?
-
-Sau đó, bạn thử hỏi người bạn cũ của mình, autocompletion của trình soạn thảo.
-
-Bạn gõ tham số đầu tiên của hàm, `first_name`, sau đó một dấu chấm (`.`) và sau đó ấn `Ctrl+Space` để kích hoạt bộ hoàn thành.
-
-Nhưng đáng buồn, bạn không nhận được điều gì hữu ích cả:
-
-
-
-### Thêm kiểu dữ liệu
-
-Hãy sửa một dòng từ phiên bản trước.
-
-Chúng ta sẽ thay đổi chính xác đoạn này, tham số của hàm, từ:
-
-```Python
- first_name, last_name
-```
-
-sang:
-
-```Python
- first_name: str, last_name: str
-```
-
-Chính là nó.
-
-Những thứ đó là "type hints":
-
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
-
-Đó không giống như khai báo những giá trị mặc định giống như:
-
-```Python
- first_name="john", last_name="doe"
-```
-
-Nó là một thứ khác.
-
-Chúng ta sử dụng dấu hai chấm (`:`), không phải dấu bằng (`=`).
-
-Và việc thêm gợi ý kiểu dữ liệu không làm thay đổi những gì xảy ra so với khi chưa thêm chúng.
-
-But now, imagine you are again in the middle of creating that function, but with type hints.
-
-Tại cùng một điểm, bạn thử kích hoạt autocomplete với `Ctrl+Space` và bạn thấy:
-
-
-
-Với cái đó, bạn có thể cuộn, nhìn thấy các lựa chọn, cho đến khi bạn tìm thấy một "tiếng chuông":
-
-
-
-## Động lực nhiều hơn
-
-Kiểm tra hàm này, nó đã có gợi ý kiểu dữ liệu:
-
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
-
-Bởi vì trình soạn thảo biết kiểu dữ liệu của các biến, bạn không chỉ có được completion, bạn cũng được kiểm tra lỗi:
-
-
-
-Bây giờ bạn biết rằng bạn phải sửa nó, chuyển `age` sang một xâu với `str(age)`:
-
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
-
-## Khai báo các kiểu dữ liệu
-
-Bạn mới chỉ nhìn thấy những nơi chủ yếu để đặt khai báo kiểu dữ liệu. Như là các tham số của hàm.
-
-Đây cũng là nơi chủ yếu để bạn sử dụng chúng với **FastAPI**.
-
-### Kiểu dữ liệu đơn giản
-
-Bạn có thể khai báo tất cả các kiểu dữ liệu chuẩn của Python, không chỉ là `str`.
-
-Bạn có thể sử dụng, ví dụ:
-
-* `int`
-* `float`
-* `bool`
-* `bytes`
-
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
-```
-
-### Các kiểu dữ liệu tổng quát với tham số kiểu dữ liệu
-
-Có một vài cấu trúc dữ liệu có thể chứa các giá trị khác nhau như `dict`, `list`, `set` và `tuple`. Và những giá trị nội tại cũng có thể có kiểu dữ liệu của chúng.
-
-Những kiểu dữ liệu nội bộ này được gọi là những kiểu dữ liệu "**tổng quát**". Và có khả năng khai báo chúng, thậm chí với các kiểu dữ liệu nội bộ của chúng.
-
-Để khai báo những kiểu dữ liệu và những kiểu dữ liệu nội bộ đó, bạn có thể sử dụng mô đun chuẩn của Python là `typing`. Nó có hỗ trợ những gợi ý kiểu dữ liệu này.
-
-#### Những phiên bản mới hơn của Python
-
-Cú pháp sử dụng `typing` **tương thích** với tất cả các phiên bản, từ Python 3.6 tới những phiên bản cuối cùng, bao gồm Python 3.9, Python 3.10,...
-
-As Python advances, **những phiên bản mới** mang tới sự hỗ trợ được cải tiến cho những chú thích kiểu dữ liệu và trong nhiều trường hợp bạn thậm chí sẽ không cần import và sử dụng mô đun `typing` để khai báo chú thích kiểu dữ liệu.
-
-Nếu bạn có thể chọn một phiên bản Python gần đây hơn cho dự án của bạn, ban sẽ có được những ưu điểm của những cải tiến đơn giản đó.
-
-Trong tất cả các tài liệu tồn tại những ví dụ tương thích với mỗi phiên bản Python (khi có một sự khác nhau).
-
-Cho ví dụ "**Python 3.6+**" có nghĩa là nó tương thích với Python 3.7 hoặc lớn hơn (bao gồm 3.7, 3.8, 3.9, 3.10,...). và "**Python 3.9+**" nghĩa là nó tương thích với Python 3.9 trở lên (bao gồm 3.10,...).
-
-Nếu bạn có thể sử dụng **phiên bản cuối cùng của Python**, sử dụng những ví dụ cho phiên bản cuối, những cái đó sẽ có **cú pháp đơn giản và tốt nhât**, ví dụ, "**Python 3.10+**".
-
-#### List
-
-Ví dụ, hãy định nghĩa một biến là `list` các `str`.
-
-=== "Python 3.9+"
-
- Khai báo biến với cùng dấu hai chấm (`:`).
-
- Tương tự kiểu dữ liệu `list`.
-
- Như danh sách là một kiểu dữ liệu chứa một vài kiểu dữ liệu có sẵn, bạn đặt chúng trong các dấu ngoặc vuông:
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- Từ `typing`, import `List` (với chữ cái `L` viết hoa):
-
- ``` Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
-
- Khai báo biến với cùng dấu hai chấm (`:`).
-
- Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`.
-
- Như danh sách là một kiểu dữ liệu chứa các kiểu dữ liệu có sẵn, bạn đặt chúng bên trong dấu ngoặc vuông:
-
- ```Python hl_lines="4"
- {!> ../../../docs_src/python_types/tutorial006.py!}
- ```
-
-!!! info
- Các kiểu dữ liệu có sẵn bên trong dấu ngoặc vuông được gọi là "tham số kiểu dữ liệu".
-
- Trong trường hợp này, `str` là tham số kiểu dữ liệu được truyền tới `List` (hoặc `list` trong Python 3.9 trở lên).
-
-Có nghĩa là: "biến `items` là một `list`, và mỗi phần tử trong danh sách này là một `str`".
-
-!!! tip
- Nếu bạn sử dụng Python 3.9 hoặc lớn hơn, bạn không phải import `List` từ `typing`, bạn có thể sử dụng `list` để thay thế.
-
-Bằng cách này, trình soạn thảo của bạn có thể hỗ trợ trong khi xử lí các phần tử trong danh sách:
-
-
-
-Đa phần đều không thể đạt được nếu không có các kiểu dữ liệu.
-
-Chú ý rằng, biến `item` là một trong các phần tử trong danh sách `items`.
-
-Và do vậy, trình soạn thảo biết nó là một `str`, và cung cấp sự hỗ trợ cho nó.
-
-#### Tuple and Set
-
-Bạn sẽ làm điều tương tự để khai báo các `tuple` và các `set`:
-
-=== "Python 3.9+"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial007_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial007.py!}
- ```
-
-Điều này có nghĩa là:
-
-* Biến `items_t` là một `tuple` với 3 phần tử, một `int`, một `int` nữa, và một `str`.
-* Biến `items_s` là một `set`, và mỗi phần tử của nó có kiểu `bytes`.
-
-#### Dict
-
-Để định nghĩa một `dict`, bạn truyền 2 tham số kiểu dữ liệu, phân cách bởi dấu phẩy.
-
-Tham số kiểu dữ liệu đầu tiên dành cho khóa của `dict`.
-
-Tham số kiểu dữ liệu thứ hai dành cho giá trị của `dict`.
-
-=== "Python 3.9+"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008.py!}
- ```
-
-Điều này có nghĩa là:
-
-* Biến `prices` là một `dict`:
- * Khóa của `dict` này là kiểu `str` (đó là tên của mỗi vật phẩm).
- * Giá trị của `dict` này là kiểu `float` (đó là giá của mỗi vật phẩm).
-
-#### Union
-
-Bạn có thể khai báo rằng một biến có thể là **một vài kiểu dữ liệu" bất kì, ví dụ, một `int` hoặc một `str`.
-
-Trong Python 3.6 hoặc lớn hơn (bao gồm Python 3.10) bạn có thể sử dụng kiểu `Union` từ `typing` và đặt trong dấu ngoặc vuông những giá trị được chấp nhận.
-
-In Python 3.10 there's also a **new syntax** where you can put the possible types separated by a vertical bar (`|`).
-
-Trong Python 3.10 cũng có một **cú pháp mới** mà bạn có thể đặt những kiểu giá trị khả thi phân cách bởi một dấu sổ dọc (`|`).
-
-
-=== "Python 3.10+"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial008b_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial008b.py!}
- ```
-
-Trong cả hai trường hợp có nghĩa là `item` có thể là một `int` hoặc `str`.
-
-#### Khả năng `None`
-
-Bạn có thể khai báo một giá trị có thể có một kiểu dữ liệu, giống như `str`, nhưng nó cũng có thể là `None`.
-
-Trong Python 3.6 hoặc lớn hơn (bao gồm Python 3.10) bạn có thể khai báo nó bằng các import và sử dụng `Optional` từ mô đun `typing`.
-
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009.py!}
-```
-
-Sử dụng `Optional[str]` thay cho `str` sẽ cho phép trình soạn thảo giúp bạn phát hiện các lỗi mà bạn có thể gặp như một giá trị luôn là một `str`, trong khi thực tế nó rất có thể là `None`.
-
-`Optional[Something]` là một cách viết ngắn gọn của `Union[Something, None]`, chúng là tương đương nhau.
-
-Điều này cũng có nghĩa là trong Python 3.10, bạn có thể sử dụng `Something | None`:
-
-=== "Python 3.10+"
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/python_types/tutorial009_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009.py!}
- ```
-
-=== "Python 3.6+ alternative"
-
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial009b.py!}
- ```
-
-#### Sử dụng `Union` hay `Optional`
-
-If you are using a Python version below 3.10, here's a tip from my very **subjective** point of view:
-
-Nếu bạn đang sử dụng phiên bản Python dưới 3.10, đây là một mẹo từ ý kiến rất "chủ quan" của tôi:
-
-* 🚨 Tránh sử dụng `Optional[SomeType]`
-* Thay vào đó ✨ **sử dụng `Union[SomeType, None]`** ✨.
-
-Cả hai là tương đương và bên dưới chúng giống nhau, nhưng tôi sẽ đễ xuất `Union` thay cho `Optional` vì từ "**tùy chọn**" có vẻ ngầm định giá trị là tùy chọn, và nó thực sự có nghĩa rằng "nó có thể là `None`", do đó nó không phải là tùy chọn và nó vẫn được yêu cầu.
-
-Tôi nghĩ `Union[SomeType, None]` là rõ ràng hơn về ý nghĩa của nó.
-
-Nó chỉ là về các từ và tên. Nhưng những từ đó có thể ảnh hưởng cách bạn và những đồng đội của bạn suy nghĩ về code.
-
-Cho một ví dụ, hãy để ý hàm này:
-
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c.py!}
-```
-
-Tham số `name` được định nghĩa là `Optional[str]`, nhưng nó **không phải là tùy chọn**, bạn không thể gọi hàm mà không có tham số:
-
-```Python
-say_hi() # Oh, no, this throws an error! 😱
-```
-
-Tham số `name` **vẫn được yêu cầu** (không phải là *tùy chọn*) vì nó không có giá trị mặc định. Trong khi đó, `name` chấp nhận `None` như là giá trị:
-
-```Python
-say_hi(name=None) # This works, None is valid 🎉
-```
-
-Tin tốt là, khi bạn sử dụng Python 3.10, bạn sẽ không phải lo lắng về điều đó, bạn sẽ có thể sử dụng `|` để định nghĩa hợp của các kiểu dữ liệu một cách đơn giản:
-
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial009c_py310.py!}
-```
-
-Và sau đó, bạn sẽ không phải lo rằng những cái tên như `Optional` và `Union`. 😎
-
-
-#### Những kiểu dữ liệu tổng quát
-
-Những kiểu dữ liệu này lấy tham số kiểu dữ liệu trong dấu ngoặc vuông được gọi là **Kiểu dữ liệu tổng quát**, cho ví dụ:
-
-=== "Python 3.10+"
-
- Bạn có thể sử dụng các kiểu dữ liệu có sẵn như là kiểu dữ liệu tổng quát (với ngoặc vuông và kiểu dữ liệu bên trong):
-
- * `list`
- * `tuple`
- * `set`
- * `dict`
-
- Và tương tự với Python 3.6, từ mô đun `typing`:
-
- * `Union`
- * `Optional` (tương tự như Python 3.6)
- * ...và các kiểu dữ liệu khác.
-
- Trong Python 3.10, thay vì sử dụng `Union` và `Optional`, bạn có thể sử dụng sổ dọc ('|') để khai báo hợp của các kiểu dữ liệu, điều đó tốt hơn và đơn giản hơn nhiều.
-
-=== "Python 3.9+"
-
- Bạn có thể sử dụng các kiểu dữ liệu có sẵn tương tự như (với ngoặc vuông và kiểu dữ liệu bên trong):
-
- * `list`
- * `tuple`
- * `set`
- * `dict`
-
- Và tương tự với Python 3.6, từ mô đun `typing`:
-
- * `Union`
- * `Optional`
- * ...and others.
-
-=== "Python 3.6+"
-
- * `List`
- * `Tuple`
- * `Set`
- * `Dict`
- * `Union`
- * `Optional`
- * ...và các kiểu khác.
-
-### Lớp như kiểu dữ liệu
-
-Bạn cũng có thể khai báo một lớp như là kiểu dữ liệu của một biến.
-
-Hãy nói rằng bạn muốn có một lớp `Person` với một tên:
-
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
-
-Sau đó bạn có thể khai báo một biến có kiểu là `Person`:
-
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
-```
-
-Và lại một lần nữa, bạn có được tất cả sự hỗ trợ từ trình soạn thảo:
-
-
-
-Lưu ý rằng, điều này có nghĩa rằng "`one_person`" là một **thực thể** của lớp `Person`.
-
-Nó không có nghĩa "`one_person`" là một **lớp** gọi là `Person`.
-
-## Pydantic models
-
-Pydantic là một thư viện Python để validate dữ liệu hiệu năng cao.
-
-Bạn có thể khai báo "hình dạng" của dữa liệu như là các lớp với các thuộc tính.
-
-Và mỗi thuộc tính có một kiểu dữ liệu.
-
-Sau đó bạn tạo một thực thể của lớp đó với một vài giá trị và nó sẽ validate các giá trị, chuyển đổi chúng sang kiểu dữ liệu phù hợp (nếu đó là trường hợp) và cho bạn một object với toàn bộ dữ liệu.
-
-Và bạn nhận được tất cả sự hỗ trợ của trình soạn thảo với object kết quả đó.
-
-Một ví dụ từ tài liệu chính thức của Pydantic:
-
-=== "Python 3.10+"
-
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python
- {!> ../../../docs_src/python_types/tutorial011_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python
- {!> ../../../docs_src/python_types/tutorial011.py!}
- ```
-
-!!! info
- Để học nhiều hơn về Pydantic, tham khảo tài liệu của nó.
-
-**FastAPI** được dựa hoàn toàn trên Pydantic.
-
-Bạn sẽ thấy nhiều ví dụ thực tế hơn trong [Hướng dẫn sử dụng](tutorial/index.md){.internal-link target=_blank}.
-
-!!! tip
- Pydantic có một hành vi đặc biệt khi bạn sử dụng `Optional` hoặc `Union[Something, None]` mà không có giá trị mặc dịnh, bạn có thể đọc nhiều hơn về nó trong tài liệu của Pydantic về Required Optional fields.
-
-
-## Type Hints với Metadata Annotations
-
-Python cũng có một tính năng cho phép đặt **metadata bổ sung** trong những gợi ý kiểu dữ liệu này bằng cách sử dụng `Annotated`.
-
-=== "Python 3.9+"
-
- Trong Python 3.9, `Annotated` là một phần của thư viện chuẩn, do đó bạn có thể import nó từ `typing`.
-
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- Ở phiên bản dưới Python 3.9, bạn import `Annotated` từ `typing_extensions`.
-
- Nó đã được cài đặt sẵng cùng với **FastAPI**.
-
- ```Python hl_lines="1 4"
- {!> ../../../docs_src/python_types/tutorial013.py!}
- ```
-
-Python bản thân nó không làm bất kì điều gì với `Annotated`. Với các trình soạn thảo và các công cụ khác, kiểu dữ liệu vẫn là `str`.
-
-Nhưng bạn có thể sử dụng `Annotated` để cung cấp cho **FastAPI** metadata bổ sung về cách mà bạn muốn ứng dụng của bạn xử lí.
-
-Điều quan trọng cần nhớ là ***tham số kiểu dữ liệu* đầu tiên** bạn truyền tới `Annotated` là **kiểu giá trị thực sự**. Phần còn lại chỉ là metadata cho các công cụ khác.
-
-Bây giờ, bạn chỉ cần biết rằng `Annotated` tồn tại, và nó là tiêu chuẩn của Python. 😎
-
-
-Sau đó, bạn sẽ thấy sự **mạnh mẽ** mà nó có thể làm.
-
-!!! tip
- Thực tế, cái này là **tiêu chuẩn của Python**, nghĩa là bạn vẫn sẽ có được **trải nghiệm phát triển tốt nhất có thể** với trình soạn thảo của bạn, với các công cụ bạn sử dụng để phân tích và tái cấu trúc code của bạn, etc. ✨
-
- Và code của bạn sẽ tương thích với nhiều công cụ và thư viện khác của Python. 🚀
-
-## Các gợi ý kiểu dữ liệu trong **FastAPI**
-
-**FastAPI** lấy các ưu điểm của các gợi ý kiểu dữ liệu để thực hiện một số thứ.
-
-Với **FastAPI**, bạn khai báo các tham số với gợi ý kiểu và bạn có được:
-
-* **Sự hỗ trợ từ các trình soạn thảo**.
-* **Kiểm tra kiểu dữ liệu (type checking)**.
-
-...và **FastAPI** sử dụng các khia báo để:
-
-* **Định nghĩa các yêu cầu**: từ tham số đường dẫn của request, tham số query, headers, bodies, các phụ thuộc (dependencies),...
-* **Chuyển dổi dữ liệu*: từ request sang kiểu dữ liệu được yêu cầu.
-* **Kiểm tra tính đúng đắn của dữ liệu**: tới từ mỗi request:
- * Sinh **lỗi tự động** để trả về máy khác khi dữ liệu không hợp lệ.
-* **Tài liệu hóa** API sử dụng OpenAPI:
- * cái mà sau được được sử dụng bởi tài liệu tương tác người dùng.
-
-Điều này có thể nghe trừu tượng. Đừng lo lắng. Bạn sẽ thấy tất cả chúng trong [Hướng dẫn sử dụng](tutorial/index.md){.internal-link target=_blank}.
-
-Điều quan trọng là bằng việc sử dụng các kiểu dữ liệu chuẩn của Python (thay vì thêm các lớp, decorators,...), **FastAPI** sẽ thực hiện nhiều công việc cho bạn.
-
-!!! info
- Nếu bạn đã đi qua toàn bộ các hướng dẫn và quay trở lại để tìm hiểu nhiều hơn về các kiểu dữ liệu, một tài nguyên tốt như "cheat sheet" từ `mypy`.
diff --git a/docs/vi/docs/tutorial/first-steps.md b/docs/vi/docs/tutorial/first-steps.md
deleted file mode 100644
index 712f00852f594..0000000000000
--- a/docs/vi/docs/tutorial/first-steps.md
+++ /dev/null
@@ -1,333 +0,0 @@
-# Những bước đầu tiên
-
-Tệp tin FastAPI đơn giản nhất có thể trông như này:
-
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
-
-Sao chép sang một tệp tin `main.py`.
-
-Chạy live server:
-
-get
-
-!!! info Thông tin về "`@decorator`"
- Cú pháp `@something` trong Python được gọi là một "decorator".
-
- Bạn đặt nó trên một hàm. Giống như một chiếc mũ xinh xắn (Tôi ddonas đó là lí do mà thuật ngữ này ra đời).
-
- Một "decorator" lấy một hàm bên dưới và thực hiện một vài thứ với nó.
-
- Trong trường hợp của chúng ta, decorator này nói **FastAPI** rằng hàm bên dưới ứng với **đường dẫn** `/` và một **toán tử** `get`.
-
- Nó là một "**decorator đường dẫn toán tử**".
-
-Bạn cũng có thể sử dụng với các toán tử khác:
-
-* `@app.post()`
-* `@app.put()`
-* `@app.delete()`
-
-Và nhiều hơn với các toán tử còn lại:
-
-* `@app.options()`
-* `@app.head()`
-* `@app.patch()`
-* `@app.trace()`
-
-!!! tip
- Bạn thoải mái sử dụng mỗi toán tử (phương thức HTTP) như bạn mơ ước.
-
- **FastAPI** không bắt buộc bất kì ý nghĩa cụ thể nào.
-
- Thông tin ở đây được biểu thị như là một chỉ dẫn, không phải là một yêu cầu bắt buộc.
-
- Ví dụ, khi sử dụng GraphQL bạn thông thường thực hiện tất cả các hành động chỉ bằng việc sử dụng các toán tử `POST`.
-
-### Step 4: Định nghĩa **hàm cho đường dẫn toán tử**
-
-Đây là "**hàm cho đường dẫn toán tử**":
-
-* **đường dẫn**: là `/`.
-* **toán tử**: là `get`.
-* **hàm**: là hàm bên dưới "decorator" (bên dưới `@app.get("/")`).
-
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
-
-Đây là một hàm Python.
-
-Nó sẽ được gọi bởi **FastAPI** bất cứ khi nào nó nhận một request tới URL "`/`" sử dụng một toán tử `GET`.
-
-Trong trường hợp này, nó là một hàm `async`.
-
----
-
-Bạn cũng có thể định nghĩa nó như là một hàm thông thường thay cho `async def`:
-
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
-
-!!! note
- Nếu bạn không biết sự khác nhau, kiểm tra [Async: *"Trong khi vội vàng?"*](../async.md#in-a-hurry){.internal-link target=_blank}.
-
-### Bước 5: Nội dung trả về
-
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
-
-Bạn có thể trả về một `dict`, `list`, một trong những giá trị đơn như `str`, `int`,...
-
-Bạn cũng có thể trả về Pydantic model (bạn sẽ thấy nhiều hơn về nó sau).
-
-Có nhiều object và model khác nhau sẽ được tự động chuyển đổi sang JSON (bao gồm cả ORM,...). Thử sử dụng loại ưa thích của bạn, nó có khả năng cao đã được hỗ trợ.
-
-## Tóm lại
-
-* Import `FastAPI`.
-* Tạo một `app` instance.
-* Viết một **decorator cho đường dẫn toán tử** (giống như `@app.get("/")`).
-* Viết một **hàm cho đường dẫn toán tử** (giống như `def root(): ...` ở trên).
-* Chạy server trong môi trường phát triển (giống như `uvicorn main:app --reload`).
diff --git a/docs/vi/docs/tutorial/index.md b/docs/vi/docs/tutorial/index.md
deleted file mode 100644
index e8a93fe4084f4..0000000000000
--- a/docs/vi/docs/tutorial/index.md
+++ /dev/null
@@ -1,80 +0,0 @@
-# Hướng dẫn sử dụng
-
-Hướng dẫn này cho bạn thấy từng bước cách sử dụng **FastAPI** đa số các tính năng của nó.
-
-Mỗi phần được xây dựng từ những phần trước đó, nhưng nó được cấu trúc thành các chủ đề riêng biệt, do đó bạn có thể xem trực tiếp từng phần cụ thể bất kì để giải quyết những API cụ thể mà bạn cần.
-
-Nó cũng được xây dựng để làm việc như một tham chiếu trong tương lai.
-
-Do đó bạn có thể quay lại và tìm chính xác những gì bạn cần.
-
-## Chạy mã
-
-Tất cả các code block có thể được sao chép và sử dụng trực tiếp (chúng thực chất là các tệp tin Python đã được kiểm thử).
-
-Để chạy bất kì ví dụ nào, sao chép code tới tệp tin `main.py`, và bắt đầu `uvicorn` với:
-
-- Ìlànà wẹ́ẹ́bù FastAPI, iṣẹ́ gíga, ó rọrùn láti kọ̀, o yára láti kóòdù, ó sì ṣetán fún iṣelọpọ ní lílo -
- - ---- - -**Àkọsílẹ̀**: https://fastapi.tiangolo.com - -**Orisun Kóòdù**: https://github.com/tiangolo/fastapi - ---- - -FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́bù fún kikọ àwọn API pẹ̀lú Python 3.7+ èyí tí ó da lori àwọn ìtọ́kasí àmì irúfẹ́ Python. - -Àwọn ẹya pàtàkì ni: - -* **Ó yára**: Iṣẹ tí ó ga púpọ̀, tí ó wa ni ibamu pẹ̀lú **NodeJS** àti **Go** (ọpẹ si Starlette àti Pydantic). [Ọkan nínú àwọn ìlànà Python ti o yára jùlọ ti o wa](#performance). -* **Ó yára láti kóòdù**: O mu iyara pọ si láti kọ àwọn ẹya tuntun kóòdù nipasẹ "Igba ìdá ọgọ́rùn-ún" (i.e. 200%) si "ọ̀ọ́dúrún ìdá ọgọ́rùn-ún" (i.e. 300%). -* **Àìtọ́ kékeré**: O n din aṣiṣe ku bi ọgbon ìdá ọgọ́rùn-ún (i.e. 40%) ti eda eniyan (oṣiṣẹ kóòdù) fa. * -* **Ọgbọ́n àti ìmọ̀**: Atilẹyin olootu nla. Ìparí nibi gbogbo. Àkókò díẹ̀ nipa wíwá ibi tí ìṣòro kóòdù wà. -* **Irọrun**: A kọ kí ó le rọrun láti lo àti láti kọ ẹkọ nínú rè. Ó máa fún ọ ní àkókò díẹ̀ látı ka àkọsílẹ. -* **Ó kúkurú ní kikọ**: Ó dín àtúnkọ àti àtúntò kóòdù kù. Ìkéde àṣàyàn kọ̀ọ̀kan nínú rẹ̀ ní ọ̀pọ̀lọpọ̀ àwọn ìlò. O ṣe iranlọwọ láti má ṣe ní ọ̀pọ̀lọpọ̀ àṣìṣe. -* **Ó lágbára**: Ó ń ṣe àgbéjáde kóòdù tí ó ṣetán fún ìṣelọ́pọ̀. Pẹ̀lú àkọsílẹ̀ tí ó máa ṣàlàyé ara rẹ̀ fún ẹ ní ìbáṣepọ̀ aládàáṣiṣẹ́ pẹ̀lú rè. -* **Ajohunše/Ìtọ́kasí**: Ó da lori (àti ibamu ni kikun pẹ̀lú) àwọn ìmọ ajohunše/ìtọ́kasí fún àwọn API: OpenAPI (èyí tí a mọ tẹlẹ si Swagger) àti JSON Schema. - -* iṣiro yi da lori àwọn idanwo tí ẹgbẹ ìdàgbàsókè FastAPI ṣe, nígbàtí wọn kọ àwọn ohun elo iṣelọpọ kóòdù pẹ̀lú rẹ. - -## Àwọn onígbọ̀wọ́ - - - -{% if sponsors %} -{% for sponsor in sponsors.gold -%} -async def...uvicorn main:app --reload...email_validator - fún ifọwọsi ímeèlì.
-* pydantic-settings - fún ètò ìsàkóso.
-* pydantic-extra-types - fún àfikún oríṣi láti lọ pẹ̀lú Pydantic.
-
-Èyí tí Starlette ń lò:
-
-* httpx - Nílò tí ó bá fẹ́ láti lọ `TestClient`.
-* jinja2 - Nílò tí ó bá fẹ́ láti lọ iṣeto awoṣe aiyipada.
-* python-multipart - Nílò tí ó bá fẹ́ láti ṣe àtìlẹ́yìn fún "àyẹ̀wò" fọọmu, pẹ̀lú `request.form()`.
-* itsdangerous - Nílò fún àtìlẹ́yìn `SessionMiddleware`.
-* pyyaml - Nílò fún àtìlẹ́yìn Starlette's `SchemaGenerator` (ó ṣe ṣe kí ó má nílò rẹ̀ fún FastAPI).
-* ujson - Nílò tí ó bá fẹ́ láti lọ `UJSONResponse`.
-
-Èyí tí FastAPI / Starlette ń lò:
-
-* uvicorn - Fún olupin tí yóò sẹ́ àmúyẹ àti tí yóò ṣe ìpèsè fún iṣẹ́ rẹ tàbí ohun èlò rẹ.
-* orjson - Nílò tí ó bá fẹ́ láti lọ `ORJSONResponse`.
-
-Ó lè fi gbogbo àwọn wọ̀nyí sórí ẹrọ pẹ̀lú `pip install "fastapi[all]"`.
-
-## Iwe-aṣẹ
-
-Iṣẹ́ yìí ni iwe-aṣẹ lábẹ́ àwọn òfin tí iwe-aṣẹ MIT.
diff --git a/docs/yo/mkdocs.yml b/docs/yo/mkdocs.yml
deleted file mode 100644
index de18856f445aa..0000000000000
--- a/docs/yo/mkdocs.yml
+++ /dev/null
@@ -1 +0,0 @@
-INHERIT: ../en/mkdocs.yml
diff --git a/docs/zh-hant/docs/_llm-test.md b/docs/zh-hant/docs/_llm-test.md
new file mode 100644
index 0000000000000..f4c1efca82f64
--- /dev/null
+++ b/docs/zh-hant/docs/_llm-test.md
@@ -0,0 +1,503 @@
+# LLM 測試檔案 { #llm-test-file }
+
+本文件用來測試用於翻譯文件的 LLM 是否理解 `scripts/translate.py` 中的 `general_prompt`,以及 `docs/{language code}/llm-prompt.md` 中的語言特定提示。語言特定提示會附加在 `general_prompt` 後面。
+
+此處新增的測試會提供給所有語言特定提示的設計者參考。
+
+使用方式:
+
+* 準備語言特定提示 - `docs/{language code}/llm-prompt.md`。
+* 針對本文件做一次全新的翻譯為你想要的目標語言(例如使用 `translate.py` 的 `translate-page` 指令)。這會在 `docs/{language code}/docs/_llm-test.md` 產生翻譯檔。
+* 檢查翻譯是否正確。
+* 如有需要,改進你的語言特定提示、通用提示,或英文原文。
+* 然後手動修正翻譯中剩下的問題,讓它成為一個好的譯文。
+* 重新翻譯,並保留這份好的譯文。理想結果是 LLM 不再對該譯文做任何變更。這代表通用提示與你的語言特定提示已經盡可能完善(有時它仍可能做出幾個看似隨機的變更,原因是[LLMs 並非決定性演算法](https://doublespeak.chat/#/handbook#deterministic-output))。
+
+測試:
+
+## 程式碼片段 { #code-snippets }
+
+//// tab | 測試
+
+這是一個程式碼片段:`foo`。這是另一個程式碼片段:`bar`。還有一個:`baz quux`。
+
+////
+
+//// tab | 資訊
+
+程式碼片段內的內容應保持原樣。
+
+請見 `scripts/translate.py` 中通用提示的 `### Content of code snippets` 小節。
+
+////
+
+## 引號 { #quotes }
+
+//// tab | 測試
+
+Yesterday, my friend wrote: "If you spell incorrectly correctly, you have spelled it incorrectly". To which I answered: "Correct, but 'incorrectly' is incorrectly not '"incorrectly"'".
+
+/// note | 注意
+
+LLM 很可能會把這段翻譯錯。重點只在於重新翻譯時是否能保留已修正的翻譯。
+
+///
+
+////
+
+//// tab | 資訊
+
+提示設計者可以選擇是否將中性引號轉換為排印引號。保留原樣也可以。
+
+例如請見 `docs/de/llm-prompt.md` 中的 `### Quotes` 小節。
+
+////
+
+## 程式碼片段中的引號 { #quotes-in-code-snippets }
+
+//// tab | 測試
+
+`pip install "foo[bar]"`
+
+程式碼片段中字串常值的例子:"this"、'that'。
+
+較難的程式碼片段中字串常值例子:`f"I like {'oranges' if orange else "apples"}"`
+
+進階:`Yesterday, my friend wrote: "If you spell incorrectly correctly, you have spelled it incorrectly". To which I answered: "Correct, but 'incorrectly' is incorrectly not '"incorrectly"'"`
+
+////
+
+//// tab | 資訊
+
+... 不過,程式碼片段中的引號必須保持原樣。
+
+////
+
+## 程式碼區塊 { #code-blocks }
+
+//// tab | 測試
+
+一個 Bash 程式碼範例...
+
+```bash
+# 向宇宙輸出問候
+echo "Hello universe"
+```
+
+...以及一個主控台範例...
+
+```console
+$ fastapi run main.py
+ FastAPI Starting server
+ Searching for package file structure
+```
+
+...以及另一個主控台範例...
+
+```console
+// 建立目錄 "Code"
+$ mkdir code
+// 切換到該目錄
+$ cd code
+```
+
+...以及一個 Python 程式碼範例...
+
+```Python
+wont_work() # 這不會運作 😱
+works(foo="bar") # 這可以運作 🎉
+```
+
+...就是這樣。
+
+////
+
+//// tab | 資訊
+
+程式碼區塊中的程式碼不應修改,註解除外。
+
+請見 `scripts/translate.py` 中通用提示的 `### Content of code blocks` 小節。
+
+////
+
+## 分頁與色塊 { #tabs-and-colored-boxes }
+
+//// tab | 測試
+
+/// info | 資訊
+Some text
+///
+
+/// note | 注意
+Some text
+///
+
+/// note | 技術細節
+Some text
+///
+
+/// check | 檢查
+Some text
+///
+
+/// tip | 提示
+Some text
+///
+
+/// warning | 警告
+Some text
+///
+
+/// danger | 危險
+Some text
+///
+
+////
+
+//// tab | 資訊
+
+分頁與 `Info`/`Note`/`Warning`/等區塊,應在直線(`|`)後加入其標題的翻譯。
+
+請見 `scripts/translate.py` 中通用提示的 `### Special blocks` 與 `### Tab blocks` 小節。
+
+////
+
+## 網頁與內部連結 { #web-and-internal-links }
+
+//// tab | 測試
+
+連結文字應被翻譯,連結位址應保持不變:
+
+* [連結到上方標題](#code-snippets)
+* [內部連結](index.md#installation)
+* [外部連結](https://sqlmodel.tiangolo.com/)
+* [連結到樣式](https://fastapi.tiangolo.com/css/styles.css)
+* [連結到腳本](https://fastapi.tiangolo.com/js/logic.js)
+* [連結到圖片](https://fastapi.tiangolo.com/img/foo.jpg)
+
+連結文字應被翻譯,連結位址應指向對應的翻譯版本:
+
+* [FastAPI 連結](https://fastapi.tiangolo.com/zh-hant/)
+
+////
+
+//// tab | 資訊
+
+連結應翻譯其文字,但位址需保持不變。例外是指向 FastAPI 文件網站的絕對連結,該情況下位址應指向對應的翻譯版本。
+
+請見 `scripts/translate.py` 中通用提示的 `### Links` 小節。
+
+////
+
+## HTML「abbr」元素 { #html-abbr-elements }
+
+//// tab | 測試
+
+以下是一些包在 HTML「abbr」元素中的內容(部分為杜撰):
+
+### abbr 提供完整詞組 { #the-abbr-gives-a-full-phrase }
+
+* GTD
+* lt
+* XWT
+* PSGI
+
+### abbr 提供完整詞組與說明 { #the-abbr-gives-a-full-phrase-and-an-explanation }
+
+* MDN
+* I/O.
+
+////
+
+//// tab | 資訊
+
+「abbr」元素的「title」屬性需依特定規則翻譯。
+
+翻譯可以自行新增「abbr」元素(例如為解釋英文單字),LLM 不應移除它們。
+
+請見 `scripts/translate.py` 中通用提示的 `### HTML abbr elements` 小節。
+
+////
+
+## HTML「dfn」元素 { #html-dfn-elements }
+
+* 叢集
+* 深度學習
+
+## 標題 { #headings }
+
+//// tab | 測試
+
+### 開發網頁應用程式 - 教學 { #develop-a-webapp-a-tutorial }
+
+Hello.
+
+### 型別提示與註解 { #type-hints-and-annotations }
+
+Hello again.
+
+### 超類與子類別 { #super-and-subclasses }
+
+Hello again.
+
+////
+
+//// tab | 資訊
+
+標題唯一的硬性規則是保留花括號中的雜湊片段不變,以確保連結不會失效。
+
+請見 `scripts/translate.py` 中通用提示的 `### Headings` 小節。
+
+關於語言特定的說明,參見例如 `docs/de/llm-prompt.md` 中的 `### Headings` 小節。
+
+////
+
+## 文件中使用的術語 { #terms-used-in-the-docs }
+
+//// tab | 測試
+
+* you
+* your
+
+* e.g.
+* etc.
+
+* `foo` as an `int`
+* `bar` as a `str`
+* `baz` as a `list`
+
+* 教學 - 使用者指南
+* 進階使用者指南
+* SQLModel 文件
+* API 文件
+* 自動文件
+
+* 資料科學
+* 深度學習
+* 機器學習
+* 相依性注入
+* HTTP 基本驗證
+* HTTP 摘要驗證
+* ISO 格式
+* JSON Schema 標準
+* JSON 結構描述
+* 結構描述定義
+* 密碼流程
+* 行動裝置
+
+* 已棄用
+* 設計的
+* 無效
+* 即時
+* 標準
+* 預設
+* 区分大小寫
+* 不區分大小寫
+
+* 提供應用程式服務
+* 提供頁面服務
+
+* 應用程式
+* 應用程式
+
+* 請求
+* 回應
+* 錯誤回應
+
+* 路徑操作
+* 路徑操作裝飾器
+* 路徑操作函式
+
+* 主體
+* 請求主體
+* 回應主體
+* JSON 主體
+* 表單主體
+* 檔案主體
+* 函式主體
+
+* 參數
+* 主體參數
+* 路徑參數
+* 查詢參數
+* Cookie 參數
+* 標頭參數
+* 表單參數
+* 函式參數
+
+* 事件
+* 啟動事件
+* 伺服器的啟動
+* 關閉事件
+* 生命週期事件
+
+* 處理器
+* 事件處理器
+* 例外處理器
+* 處理
+
+* 模型
+* Pydantic 模型
+* 資料模型
+* 資料庫模型
+* 表單模型
+* 模型物件
+
+* 類別
+* 基底類別
+* 父類別
+* 子類別
+* 子類別
+* 同級類別
+* 類別方法
+
+* 標頭
+* 標頭
+* 授權標頭
+* `Authorization` 標頭
+* 轉送標頭
+
+* 相依性注入系統
+* 相依項
+* 可相依對象
+* 相依者
+
+* I/O 受限
+* CPU 受限
+* 並發
+* 平行處理
+* 多處理程序
+
+* 環境變數
+* 環境變數
+* `PATH`
+* `PATH` 變數
+
+* 驗證
+* 驗證提供者
+* 授權
+* 授權表單
+* 授權提供者
+* 使用者進行驗證
+* 系統驗證使用者
+
+* CLI
+* 命令列介面
+
+* 伺服器
+* 用戶端
+
+* 雲端提供者
+* 雲端服務
+
+* 開發
+* 開發階段
+
+* dict
+* 字典
+* 列舉
+* enum
+* 列舉成員
+
+* 編碼器
+* 解碼器
+* 編碼
+* 解碼
+
+* 例外
+* 拋出
+
+* 運算式
+* 陳述式
+
+* 前端
+* 後端
+
+* GitHub 討論
+* GitHub 議題
+
+* 效能
+* 效能優化
+
+* 回傳型別
+* 回傳值
+
+* 安全性
+* 安全性機制
+
+* 任務
+* 背景任務
+* 任務函式
+
+* 樣板
+* 樣板引擎
+
+* 型別註解
+* 型別提示
+
+* 伺服器工作進程
+* Uvicorn 工作進程
+* Gunicorn 工作進程
+* 工作進程
+* worker 類別
+* 工作負載
+
+* 部署
+* 部署
+
+* SDK
+* 軟體開發工具組
+
+* `APIRouter`
+* `requirements.txt`
+* Bearer Token
+* 相容性破壞變更
+* 錯誤
+* 按鈕
+* 可呼叫對象
+* 程式碼
+* 提交
+* 情境管理器
+* 協程
+* 資料庫工作階段
+* 磁碟
+* 網域
+* 引擎
+* 假的 X
+* HTTP GET 方法
+* 項目
+* 函式庫
+* 生命週期
+* 鎖
+* 中介軟體
+* 行動應用程式
+* 模組
+* 掛載
+* 網路
+* 來源
+* 覆寫
+* 有效負載
+* 處理器
+* 屬性
+* 代理
+* pull request
+* 查詢
+* RAM
+* 遠端機器
+* 狀態碼
+* 字串
+* 標籤
+* Web 框架
+* 萬用字元
+* 回傳
+* 驗證
+
+////
+
+//// tab | 資訊
+
+這是一份不完整且非規範性的(多為)技術術語清單,來源為文件內容。它可能有助於提示設計者判斷哪些術語需要 LLM 的特別協助。例如當 LLM 反覆把好的翻譯改回成較差的版本,或在你的語言中對某詞的詞形變化處理有困難時。
+
+請見例如 `docs/de/llm-prompt.md` 中的 `### List of English terms and their preferred German translations` 小節。
+
+////
diff --git a/docs/zh-hant/docs/about/index.md b/docs/zh-hant/docs/about/index.md
new file mode 100644
index 0000000000000..cf5b5742c5818
--- /dev/null
+++ b/docs/zh-hant/docs/about/index.md
@@ -0,0 +1,3 @@
+# 關於 { #about }
+
+關於 FastAPI、其設計、靈感來源等更多資訊。 🤓
diff --git a/docs/zh-hant/docs/advanced/additional-responses.md b/docs/zh-hant/docs/advanced/additional-responses.md
new file mode 100644
index 0000000000000..118c65e044bf7
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/additional-responses.md
@@ -0,0 +1,247 @@
+# OpenAPI 中的額外回應 { #additional-responses-in-openapi }
+
+/// warning | 警告
+
+這是一個偏進階的主題。
+
+如果你剛開始使用 **FastAPI**,大多情況下不需要用到它。
+
+///
+
+你可以宣告額外的回應,包含額外的狀態碼、媒體型別、描述等。
+
+這些額外回應會被包含在 OpenAPI 中,因此也會顯示在 API 文件裡。
+
+但對於這些額外回應,你必須直接回傳像 `JSONResponse` 這樣的 `Response`,並包含你的狀態碼與內容。
+
+## 使用 `model` 的額外回應 { #additional-response-with-model }
+
+你可以在你的「路徑操作裝飾器」中傳入參數 `responses`。
+
+它接收一個 `dict`:鍵是各回應的狀態碼(例如 `200`),值是另一個 `dict`,其中包含每個回應的資訊。
+
+每個回應的 `dict` 都可以有一個鍵 `model`,包含一個 Pydantic 模型,與 `response_model` 類似。
+
+**FastAPI** 會取用該模型、產生其 JSON Schema,並把它放到 OpenAPI 中正確的位置。
+
+例如,要宣告一個狀態碼為 `404` 的額外回應,並使用 Pydantic 模型 `Message`,你可以這樣寫:
+
+{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}
+
+/// note | 注意
+
+請記住你必須直接回傳 `JSONResponse`。
+
+///
+
+/// info | 說明
+
+`model` 這個鍵不屬於 OpenAPI。
+
+**FastAPI** 會從這裡取出 Pydantic 模型,產生 JSON Schema,並放到正確位置。
+
+正確的位置是:
+
+* 在 `content` 這個鍵中,其值是一個 JSON 物件(`dict`),包含:
+ * 一個媒體型別作為鍵,例如 `application/json`,其值是另一個 JSON 物件,當中包含:
+ * 鍵 `schema`,其值是該模型的 JSON Schema,這裡就是正確的位置。
+ * **FastAPI** 會在這裡加入一個指向你 OpenAPI 中全域 JSON Schemas 的參照,而不是直接把它嵌入。如此一來,其他應用與用戶端可以直接使用那些 JSON Schemas,提供更好的程式碼產生工具等。
+
+///
+
+這個路徑操作在 OpenAPI 中產生的回應將會是:
+
+```JSON hl_lines="3-12"
+{
+ "responses": {
+ "404": {
+ "description": "Additional Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Message"
+ }
+ }
+ }
+ },
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+這些 Schemas 會在 OpenAPI 中以參照的方式指向其他位置:
+
+```JSON hl_lines="4-16"
+{
+ "components": {
+ "schemas": {
+ "Message": {
+ "title": "Message",
+ "required": [
+ "message"
+ ],
+ "type": "object",
+ "properties": {
+ "message": {
+ "title": "Message",
+ "type": "string"
+ }
+ }
+ },
+ "Item": {
+ "title": "Item",
+ "required": [
+ "id",
+ "value"
+ ],
+ "type": "object",
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
+ },
+ "value": {
+ "title": "Value",
+ "type": "string"
+ }
+ }
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": [
+ "loc",
+ "msg",
+ "type"
+ ],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string"
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string"
+ }
+ }
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+## 主回應的其他媒體型別 { #additional-media-types-for-the-main-response }
+
+你可以用同一個 `responses` 參數,替相同的主回應新增不同的媒體型別。
+
+例如,你可以新增 `image/png` 這種媒體型別,宣告你的「路徑操作」可以回傳 JSON 物件(媒體型別為 `application/json`)或一張 PNG 圖片:
+
+{* ../../docs_src/additional_responses/tutorial002_py310.py hl[17:22,26] *}
+
+/// note | 注意
+
+請注意你必須直接用 `FileResponse` 回傳圖片。
+
+///
+
+/// info | 說明
+
+除非你在 `responses` 參數中明確指定不同的媒體型別,否則 FastAPI 會假設回應的媒體型別與主回應類別相同(預設為 `application/json`)。
+
+但如果你指定了一個自訂的回應類別,且其媒體型別為 `None`,那麼對於任何具關聯模型的額外回應,FastAPI 會使用 `application/json`。
+
+///
+
+## 結合資訊 { #combining-information }
+
+你也可以從多個地方結合回應資訊,包括 `response_model`、`status_code` 與 `responses` 參數。
+
+你可以宣告一個 `response_model`,使用預設狀態碼 `200`(或你需要的自訂狀態碼),然後在 `responses` 中直接於 OpenAPI Schema 為相同的回應宣告額外資訊。
+
+**FastAPI** 會保留 `responses` 提供的額外資訊,並把它和你模型的 JSON Schema 結合。
+
+例如,你可以宣告一個狀態碼為 `404` 的回應,使用一個 Pydantic 模型,並帶有自訂的 `description`。
+
+以及一個狀態碼為 `200` 的回應,使用你的 `response_model`,但包含自訂的 `example`:
+
+{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}
+
+以上都會被結合並包含在你的 OpenAPI 中,並顯示在 API 文件:
+
+
+
+## 結合預先定義與自訂的回應 { #combine-predefined-responses-and-custom-ones }
+
+你可能想要有一些適用於多個「路徑操作」的預先定義回應,但也想與每個「路徑操作」所需的自訂回應結合。
+
+在這些情況下,你可以使用 Python 的「解包」`dict` 技巧,透過 `**dict_to_unpack`:
+
+```Python
+old_dict = {
+ "old key": "old value",
+ "second old key": "second old value",
+}
+new_dict = {**old_dict, "new key": "new value"}
+```
+
+此處,`new_dict` 會包含 `old_dict` 的所有鍵值配對,再加上新的鍵值配對:
+
+```Python
+{
+ "old key": "old value",
+ "second old key": "second old value",
+ "new key": "new value",
+}
+```
+
+你可以用這個技巧在「路徑操作」中重用一些預先定義的回應,並與其他自訂回應結合。
+
+例如:
+
+{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}
+
+## 關於 OpenAPI 回應的更多資訊 { #more-information-about-openapi-responses }
+
+若要查看回應中究竟可以包含哪些內容,你可以參考 OpenAPI 規範中的這些章節:
+
+* [OpenAPI Responses 物件](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responses-object),其中包含 `Response Object`。
+* [OpenAPI Response 物件](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#response-object),你可以把這裡的任何內容直接放到 `responses` 參數內各個回應中。包含 `description`、`headers`、`content`(在其中宣告不同的媒體型別與 JSON Schemas)、以及 `links`。
diff --git a/docs/zh-hant/docs/advanced/additional-status-codes.md b/docs/zh-hant/docs/advanced/additional-status-codes.md
new file mode 100644
index 0000000000000..0e5941a8d6c8d
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/additional-status-codes.md
@@ -0,0 +1,41 @@
+# 額外的狀態碼 { #additional-status-codes }
+
+在預設情況下,**FastAPI** 會使用 `JSONResponse` 傳回回應,並把你從你的「路徑操作(path operation)」回傳的內容放進該 `JSONResponse` 中。
+
+它會使用預設的狀態碼,或你在路徑操作中設定的狀態碼。
+
+## 額外的狀態碼 { #additional-status-codes_1 }
+
+如果你想在主要狀態碼之外再回傳其他狀態碼,可以直接回傳一個 `Response`(例如 `JSONResponse`),並直接設定你想要的額外狀態碼。
+
+例如,你想要有一個允許更新項目的路徑操作,成功時回傳 HTTP 狀態碼 200 "OK"。
+
+但你也希望它能接受新項目;當項目先前不存在時就建立它們,並回傳 HTTP 狀態碼 201 "Created"。
+
+要達成這點,匯入 `JSONResponse`,直接在那裡回傳內容,並設定你想要的 `status_code`:
+
+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
+
+/// warning
+
+當你直接回傳一個 `Response`(就像上面的範例),它會原封不動地被送出。
+
+不會再經過模型序列化等處理。
+
+請確認其中包含你要的資料,且各值是合法的 JSON(如果你使用的是 `JSONResponse`)。
+
+///
+
+/// note | 技術細節
+
+你也可以使用 `from starlette.responses import JSONResponse`。
+
+**FastAPI** 也將同樣的 `starlette.responses` 以 `fastapi.responses` 的形式提供,純粹是為了讓你(開發者)更方便。但大多數可用的回應類別其實都直接來自 Starlette。`status` 也一樣。
+
+///
+
+## OpenAPI 與 API 文件 { #openapi-and-api-docs }
+
+如果你直接回傳額外的狀態碼與回應,它們不會被包含進 OpenAPI 綱要(API 文件)中,因為 FastAPI 無法事先知道你會回傳什麼。
+
+但你可以在程式碼中補充文件,使用:[額外的回應](additional-responses.md)。
diff --git a/docs/zh-hant/docs/advanced/advanced-dependencies.md b/docs/zh-hant/docs/advanced/advanced-dependencies.md
new file mode 100644
index 0000000000000..559ca245fa10c
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,163 @@
+# 進階相依 { #advanced-dependencies }
+
+## 參數化的相依 { #parameterized-dependencies }
+
+到目前為止看到的相依都是固定的函式或類別。
+
+但有些情況下,你可能想要能為相依設定參數,而不必宣告許多不同的函式或類別。
+
+想像我們想要一個相依,用來檢查查詢參數 `q` 是否包含某些固定內容。
+
+同時我們希望能將那個固定內容參數化。
+
+## 「callable」的實例 { #a-callable-instance }
+
+在 Python 中有一種方式可以讓一個類別的實例變成「callable」。
+
+不是類別本身(類別本來就可呼叫),而是該類別的實例。
+
+要做到這點,我們宣告一個 `__call__` 方法:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}
+
+在這個情境中,**FastAPI** 會用這個 `__call__` 來檢查額外的參數與子相依,並在之後呼叫它,把回傳值傳遞給你的「路徑操作函式」中的參數。
+
+## 讓實例可參數化 { #parameterize-the-instance }
+
+接著,我們可以用 `__init__` 來宣告這個實例的參數,用以「參數化」這個相依:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}
+
+在這裡,**FastAPI** 完全不會接觸或在意 `__init__`,我們會直接在自己的程式碼中使用它。
+
+## 建立一個實例 { #create-an-instance }
+
+我們可以這樣建立該類別的實例:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}
+
+如此一來我們就能「參數化」相依,現在它內部含有 `"bar"`,作為屬性 `checker.fixed_content`。
+
+## 將實例作為相依使用 { #use-the-instance-as-a-dependency }
+
+然後,我們可以在 `Depends(checker)` 中使用這個 `checker`,而不是 `Depends(FixedContentQueryChecker)`,因為相依是那個實例 `checker`,不是類別本身。
+
+當解析相依時,**FastAPI** 會像這樣呼叫這個 `checker`:
+
+```Python
+checker(q="somequery")
+```
+
+...並將其回傳值,作為相依的值,以參數 `fixed_content_included` 傳給我們的「路徑操作函式」:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}
+
+/// tip | 提示
+
+這一切現在看起來也許有點牽強,而且目前可能還不太清楚有何用途。
+
+這些範例刻意保持簡單,但展示了整個機制如何運作。
+
+在關於安全性的章節裡,有一些工具函式也是用同樣的方式實作。
+
+如果你理解了以上內容,你其實已經知道那些安全性工具在底層是如何運作的。
+
+///
+
+## 同時含有 `yield`、`HTTPException`、`except` 與背景任務的相依 { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+/// warning | 警告
+
+你很可能不需要這些技術細節。
+
+這些細節主要在於:如果你有一個 0.121.0 之前的 FastAPI 應用,並且在使用含有 `yield` 的相依時遇到問題,會對你有幫助。
+
+///
+
+含有 `yield` 的相依隨著時間演進,以涵蓋不同的使用情境並修正一些問題。以下是變更摘要。
+
+### 含有 `yield` 與 `scope` 的相依 { #dependencies-with-yield-and-scope }
+
+在 0.121.0 版中,FastAPI 為含有 `yield` 的相依加入了 `Depends(scope="function")` 的支援。
+
+使用 `Depends(scope="function")` 時,`yield` 之後的結束程式碼會在「路徑操作函式」執行完畢後立刻執行,在回應發送回客戶端之前。
+
+而當使用 `Depends(scope="request")`(預設值)時,`yield` 之後的結束程式碼會在回應送出之後才執行。
+
+你可以在文件中閱讀更多:[含有 `yield` 的相依 - 提前結束與 `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope)。
+
+### 含有 `yield` 與 `StreamingResponse` 的相依,技術細節 { #dependencies-with-yield-and-streamingresponse-technical-details }
+
+在 FastAPI 0.118.0 之前,如果你使用含有 `yield` 的相依,它會在「路徑操作函式」回傳之後、發送回應之前,執行結束程式碼。
+
+這樣做的用意是避免在等待回應穿越網路時,比必要的時間更久地占用資源。
+
+但這也意味著,如果你回傳的是 `StreamingResponse`,該含有 `yield` 的相依的結束程式碼早已執行完畢。
+
+例如,如果你在含有 `yield` 的相依中使用了一個資料庫 session,`StreamingResponse` 在串流資料時將無法使用該 session,因為它已在 `yield` 之後的結束程式碼中被關閉了。
+
+這個行為在 0.118.0 被還原,使得 `yield` 之後的結束程式碼會在回應送出之後才被執行。
+
+/// info | 資訊
+
+如下所見,這與 0.106.0 之前的行為非常類似,但對一些邊界情況做了多項改進與錯誤修正。
+
+///
+
+#### 需要提早執行結束程式碼的情境 { #use-cases-with-early-exit-code }
+
+有些特定條件的使用情境,可能會受益於舊行為(在送出回應之前執行含有 `yield` 的相依的結束程式碼)。
+
+例如,假設你在含有 `yield` 的相依中只用資料庫 session 來驗證使用者,而這個 session 之後並未在「路徑操作函式」中使用,僅在相依中使用,且回應需要很長時間才會送出,例如一個慢速傳送資料的 `StreamingResponse`,但它並沒有使用資料庫。
+
+在這種情況下,資料庫 session 會一直被保留到回應傳送完畢為止,但如果你根本不會用到它,就沒有必要一直持有它。
+
+可能會像這樣:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
+
+結束程式碼(自動關閉 `Session`)在:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
+
+...會在回應完成傳送這些慢速資料後才執行:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
+
+但因為 `generate_stream()` 並未使用資料庫 session,實際上不需要在傳送回應時保持 session 開啟。
+
+如果你用的是 SQLModel(或 SQLAlchemy)且有這種特定情境,你可以在不再需要時明確關閉該 session:
+
+{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}
+
+如此一來,該 session 就會釋放資料庫連線,讓其他請求可以使用。
+
+如果你有不同的情境,需要從含有 `yield` 的相依中提早結束,請建立一個 [GitHub 討論問題](https://github.com/fastapi/fastapi/discussions/new?category=questions),描述你的具體情境,以及為何提早關閉含有 `yield` 的相依對你有幫助。
+
+如果有令人信服的案例需要在含有 `yield` 的相依中提前關閉,我會考慮加入一種新的選項,讓你可以選擇性啟用提前關閉。
+
+### 含有 `yield` 與 `except` 的相依,技術細節 { #dependencies-with-yield-and-except-technical-details }
+
+在 FastAPI 0.110.0 之前,如果你使用含有 `yield` 的相依,並且在該相依中用 `except` 捕捉到例外,且沒有再次拋出,那個例外會自動被拋出/轉交給任何例外處理器或內部伺服器錯誤處理器。
+
+在 0.110.0 版本中,這被修改以修復沒有處理器(內部伺服器錯誤)而被轉交的例外所造成的未處理記憶體消耗,並使其行為與一般 Python 程式碼一致。
+
+### 背景任務與含有 `yield` 的相依,技術細節 { #background-tasks-and-dependencies-with-yield-technical-details }
+
+在 FastAPI 0.106.0 之前,不可能在 `yield` 之後拋出例外;含有 `yield` 的相依的結束程式碼會在回應送出之後才執行,因此[例外處理器](../tutorial/handling-errors.md#install-custom-exception-handlers) 早就已經跑完了。
+
+當初這樣設計主要是為了允許在背景任務中使用由相依「yield」出來的同一組物件,因為結束程式碼會在背景任務結束後才執行。
+
+在 FastAPI 0.106.0 中,這個行為被修改,目的是在等待回應穿越網路的期間,不要持有資源。
+
+/// tip | 提示
+
+此外,背景任務通常是一組獨立的邏輯,應該用自己的資源(例如自己的資料庫連線)來處理。
+
+這樣你的程式碼通常會更乾淨。
+
+///
+
+如果你先前依賴這種行為,現在應該在背景任務本身裡建立所需資源,並且只使用不依賴含有 `yield` 的相依之資源的資料。
+
+例如,不要共用同一個資料庫 session,而是在背景任務中建立一個新的資料庫 session,並用這個新的 session 從資料庫取得物件。接著,在呼叫背景任務函式時,不是傳遞資料庫物件本身,而是傳遞該物件的 ID,然後在背景任務函式內再透過這個 ID 取得物件。
diff --git a/docs/zh-hant/docs/advanced/advanced-python-types.md b/docs/zh-hant/docs/advanced/advanced-python-types.md
new file mode 100644
index 0000000000000..ffa139427acdf
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/advanced-python-types.md
@@ -0,0 +1,61 @@
+# 進階 Python 型別 { #advanced-python-types }
+
+以下是一些在使用 Python 型別時可能有用的額外想法。
+
+## 使用 `Union` 或 `Optional` { #using-union-or-optional }
+
+如果你的程式碼因某些原因無法使用 `|`,例如不是在型別註記中,而是在像 `response_model=` 之類的參數位置,那麼你可以用 `typing` 中的 `Union` 來取代豎線(`|`)。
+
+例如,你可以宣告某個值可以是 `str` 或 `None`:
+
+```python
+from typing import Union
+
+
+def say_hi(name: Union[str, None]):
+ print(f"Hi {name}!")
+```
+
+在 `typing` 中也有用 `Optional` 宣告某個值可以是 `None` 的速記法。
+
+以下是我個人(非常主觀)的建議:
+
+* 🚨 避免使用 `Optional[SomeType]`
+* 改為 ✨ 使用 `Union[SomeType, None]` ✨。
+
+兩者等價且底層相同,但我會推薦用 `Union` 而不要用 `Optional`,因為「optional」這個詞看起來會讓人以為這個值是可選的,但實際上它的意思是「可以是 `None`」,即使它不是可選的、仍然是必填。
+
+我認為 `Union[SomeType, None]` 更能清楚表達其含義。
+
+這只是措辭與命名問題,但這些詞會影響你與團隊成員對程式碼的理解。
+
+例如,看看下面這個函式:
+
+```python
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+ print(f"Hey {name}!")
+```
+
+參數 `name` 被標註為 `Optional[str]`,但它並不是可選的;你不能在沒有該參數的情況下呼叫這個函式:
+
+```Python
+say_hi() # 糟了,這會拋出錯誤!😱
+```
+
+參數 `name` 仍是必填(不是可選),因為它沒有預設值。不過,`name` 可以接受 `None` 作為值:
+
+```Python
+say_hi(name=None) # 這可行,None 是有效的 🎉
+```
+
+好消息是,多數情況下你可以直接用 `|` 來定義型別聯集:
+
+```python
+def say_hi(name: str | None):
+ print(f"Hey {name}!")
+```
+
+因此,通常你不必為 `Optional` 與 `Union` 這些名稱操心。😎
diff --git a/docs/zh-hant/docs/advanced/async-tests.md b/docs/zh-hant/docs/advanced/async-tests.md
new file mode 100644
index 0000000000000..639c42b7db876
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/async-tests.md
@@ -0,0 +1,99 @@
+# 非同步測試 { #async-tests }
+
+你已經看過如何使用提供的 `TestClient` 來測試你的 FastAPI 應用。到目前為止,你只看到如何撰寫同步測試,沒有使用 `async` 函式。
+
+在測試中能使用非同步函式會很有用,例如當你以非同步方式查詢資料庫時。想像你想測試發送請求到 FastAPI 應用,然後在使用非同步資料庫函式庫時,驗證後端是否成功把正確資料寫入資料庫。
+
+來看看怎麼做。
+
+## pytest.mark.anyio { #pytest-mark-anyio }
+
+若要在測試中呼叫非同步函式,測試函式本身也必須是非同步的。AnyIO 為此提供了一個好用的外掛,讓我們可以標示某些測試函式以非同步方式執行。
+
+## HTTPX { #httpx }
+
+即使你的 FastAPI 應用使用一般的 `def` 函式而非 `async def`,它在底層仍然是個 `async` 應用。
+
+`TestClient` 在內部做了一些魔法,讓我們能在一般的 `def` 測試函式中,使用標準 pytest 來呼叫非同步的 FastAPI 應用。但當我們在非同步函式中使用它時,這個魔法就不再奏效了。也就是說,當以非同步方式執行測試時,就不能在測試函式內使用 `TestClient`。
+
+`TestClient` 是建立在 [HTTPX](https://www.python-httpx.org) 之上,所幸我們可以直接使用它來測試 API。
+
+## 範例 { #example }
+
+作為簡單範例,讓我們考慮與[更大型的應用](../tutorial/bigger-applications.md)與[測試](../tutorial/testing.md)中描述的類似檔案結構:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+檔案 `main.py` 會是:
+
+{* ../../docs_src/async_tests/app_a_py310/main.py *}
+
+檔案 `test_main.py` 會包含針對 `main.py` 的測試,現在可能像這樣:
+
+{* ../../docs_src/async_tests/app_a_py310/test_main.py *}
+
+## 執行 { #run-it }
+
+如常執行測試:
+
+
+
+但如果我們改用「正式」的 URL,也就是使用埠號 `9999` 的代理、並在 `/api/v1/docs`,它就能正確運作了!🎉
+
+你可以在 [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs) 檢查:
+
+
+
+正如我們所希望的那樣。✔️
+
+這是因為 FastAPI 使用這個 `root_path` 來在 OpenAPI 中建立預設的 `server`,其 URL 就是 `root_path` 所提供的值。
+
+## 其他 servers { #additional-servers }
+
+/// warning
+
+這是更進階的用法。你可以選擇略過。
+
+///
+
+預設情況下,FastAPI 會在 OpenAPI 模式中建立一個 `server`,其 URL 為 `root_path`。
+
+但你也可以另外提供其他 `servers`,例如你想要用「同一份」文件 UI 來與測試(staging)與正式(production)環境互動。
+
+如果你傳入自訂的 `servers` 清單,且同時存在 `root_path`(因為你的 API 位於代理之後),FastAPI 會在清單開頭插入一個 `server`,其 URL 為該 `root_path`。
+
+例如:
+
+{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}
+
+將會產生如下的 OpenAPI 模式:
+
+```JSON hl_lines="5-7"
+{
+ "openapi": "3.1.0",
+ // 其他內容
+ "servers": [
+ {
+ "url": "/api/v1"
+ },
+ {
+ "url": "https://stag.example.com",
+ "description": "Staging environment"
+ },
+ {
+ "url": "https://prod.example.com",
+ "description": "Production environment"
+ }
+ ],
+ "paths": {
+ // 其他內容
+ }
+}
+```
+
+/// tip
+
+注意自動產生的 server,其 `url` 值為 `/api/v1`,取自 `root_path`。
+
+///
+
+在位於 [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs) 的文件 UI 中看起來會像這樣:
+
+
+
+/// tip
+
+文件 UI 會與你所選擇的 server 互動。
+
+///
+
+/// note | 技術細節
+
+OpenAPI 規格中的 `servers` 屬性是可選的。
+
+如果你沒有指定 `servers` 參數,且 `root_path` 等於 `/`,則在產生的 OpenAPI 模式中會完全省略 `servers` 屬性(預設行為),這等同於只有一個 `url` 值為 `/` 的 server。
+
+///
+
+### 停用從 `root_path` 自動加入的 server { #disable-automatic-server-from-root-path }
+
+如果你不希望 FastAPI 使用 `root_path` 自動加入一個 server,你可以使用參數 `root_path_in_servers=False`:
+
+{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}
+
+這樣它就不會被包含在 OpenAPI 模式中。
+
+## 掛載子應用 { #mounting-a-sub-application }
+
+如果你需要在同時使用具有 `root_path` 的代理時,掛載一個子應用(如[[子應用 - 掛載](sub-applications.md)]中所述),可以像平常一樣操作,正如你所預期的那樣。
+
+FastAPI 會在內部智慧地使用 `root_path`,所以一切都能順利運作。✨
diff --git a/docs/zh-hant/docs/advanced/custom-response.md b/docs/zh-hant/docs/advanced/custom-response.md
new file mode 100644
index 0000000000000..c8355937c8f4c
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/custom-response.md
@@ -0,0 +1,272 @@
+# 自訂回應——HTML、串流、檔案與其他 { #custom-response-html-stream-file-others }
+
+預設情況下,**FastAPI** 會回傳 JSON 回應。
+
+你可以像在[直接回傳 Response](response-directly.md)中所示,直接回傳一個 `Response` 來覆寫它。
+
+但如果你直接回傳一個 `Response`(或其子類別,例如 `JSONResponse`),資料將不會被自動轉換(即使你宣告了 `response_model`),而且文件也不會自動產生(例如,在產生的 OpenAPI 中包含 HTTP 標頭 `Content-Type` 的特定「media type」)。
+
+你也可以在「路徑操作裝飾器」中使用 `response_class` 參數,宣告要使用的 `Response`(例如任意 `Response` 子類別)。
+
+你從「路徑操作函式」回傳的內容,會被放進該 `Response` 中。
+
+/// note
+
+若你使用的回應類別沒有 media type,FastAPI 會假設你的回應沒有內容,因此不會在產生的 OpenAPI 文件中記錄回應格式。
+
+///
+
+## JSON 回應 { #json-responses }
+
+FastAPI 預設回傳 JSON 回應。
+
+如果你宣告了[回應模型](../tutorial/response-model.md),FastAPI 會使用 Pydantic 將資料序列化為 JSON。
+
+如果你沒有宣告回應模型,FastAPI 會使用在[JSON 相容編碼器](../tutorial/encoder.md)中解釋的 `jsonable_encoder`,並將結果放進 `JSONResponse`。
+
+如果你宣告的 `response_class` 具有 JSON 的 media type(`application/json`),像 `JSONResponse`,你回傳的資料會自動以你在「路徑操作裝飾器」中宣告的任何 Pydantic `response_model` 進行轉換(與過濾)。但資料不會由 Pydantic 直接序列化成 JSON 位元組;取而代之,會先經由 `jsonable_encoder` 轉換,然後交給 `JSONResponse` 類別,該類別會使用 Python 標準的 JSON 函式庫將其序列化為位元組。
+
+### JSON 效能 { #json-performance }
+
+簡而言之,若你想要最佳效能,請使用[回應模型](../tutorial/response-model.md),並且不要在「路徑操作裝飾器」中宣告 `response_class`。
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py ln[15:17] hl[16] *}
+
+## HTML 回應 { #html-response }
+
+要直接從 **FastAPI** 回傳 HTML,使用 `HTMLResponse`。
+
+- 匯入 `HTMLResponse`。
+- 在「路徑操作裝飾器」中,將 `HTMLResponse` 傳給 `response_class` 參數。
+
+{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}
+
+/// info
+
+參數 `response_class` 也會用來定義回應的「media type」。
+
+在此情況下,HTTP 標頭 `Content-Type` 會被設為 `text/html`。
+
+而且它會以此形式被記錄到 OpenAPI 中。
+
+///
+
+### 回傳 `Response` { #return-a-response }
+
+如[直接回傳 Response](response-directly.md)所示,你也可以在「路徑操作」中直接回傳以覆寫回應。
+
+上面的相同範例,回傳 `HTMLResponse`,可以像這樣:
+
+{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}
+
+/// warning
+
+由你的「路徑操作函式」直接回傳的 `Response` 不會被記錄進 OpenAPI(例如不會記錄 `Content-Type`),也不會出現在自動產生的互動式文件中。
+
+///
+
+/// info
+
+當然,實際的 `Content-Type` 標頭、狀態碼等,會來自你回傳的 `Response` 物件。
+
+///
+
+### 在 OpenAPI 中文件化並覆寫 `Response` { #document-in-openapi-and-override-response }
+
+如果你想在函式內覆寫回應,同時又要在 OpenAPI 中記錄「media type」,你可以同時使用 `response_class` 參數並回傳一個 `Response` 物件。
+
+此時,`response_class` 只會用於記錄該 OpenAPI「路徑操作」,而你回傳的 `Response` 將會如實使用。
+
+#### 直接回傳 `HTMLResponse` { #return-an-htmlresponse-directly }
+
+例如,可能會像這樣:
+
+{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}
+
+在這個例子中,函式 `generate_html_response()` 已經產生並回傳了一個 `Response`,而不是把 HTML 當作 `str` 回傳。
+
+透過回傳 `generate_html_response()` 的結果,你其實已經回傳了一個 `Response`,這會覆寫 **FastAPI** 的預設行為。
+
+但因為你同時也在 `response_class` 中傳入了 `HTMLResponse`,**FastAPI** 便能在 OpenAPI 與互動式文件中,將其以 `text/html` 的 HTML 形式記錄:
+
+
+
+## 可用的回應 { #available-responses }
+
+以下是一些可用的回應類別。
+
+記得你可以用 `Response` 回傳其他任何東西,甚至建立自訂的子類別。
+
+/// note | 技術細節
+
+你也可以使用 `from starlette.responses import HTMLResponse`。
+
+**FastAPI** 將 `starlette.responses` 以 `fastapi.responses` 提供給你(開發者)做為方便之用。但大多數可用的回應其實直接來自 Starlette。
+
+///
+
+### `Response` { #response }
+
+主要的 `Response` 類別,其他回應皆繼承自它。
+
+你也可以直接回傳它。
+
+它接受以下參數:
+
+- `content` - `str` 或 `bytes`。
+- `status_code` - `int` 類型的 HTTP 狀態碼。
+- `headers` - 由字串組成的 `dict`。
+- `media_type` - 描述 media type 的 `str`。例如 `"text/html"`。
+
+FastAPI(實際上是 Starlette)會自動包含 Content-Length 標頭。也會根據 `media_type`(並為文字型別附加 charset)包含 Content-Type 標頭。
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+### `HTMLResponse` { #htmlresponse }
+
+接收文字或位元組並回傳 HTML 回應,如上所述。
+
+### `PlainTextResponse` { #plaintextresponse }
+
+接收文字或位元組並回傳純文字回應。
+
+{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}
+
+### `JSONResponse` { #jsonresponse }
+
+接收資料並回傳 `application/json` 編碼的回應。
+
+這是 **FastAPI** 的預設回應,如上所述。
+
+/// note | 技術細節
+
+但如果你宣告了回應模型或回傳型別,將會直接用它來把資料序列化為 JSON,並直接回傳具有正確 JSON media type 的回應,而不會使用 `JSONResponse` 類別。
+
+這是取得最佳效能的理想方式。
+
+///
+
+### `RedirectResponse` { #redirectresponse }
+
+回傳一個 HTTP 重新導向。預設使用 307 狀態碼(Temporary Redirect)。
+
+你可以直接回傳 `RedirectResponse`:
+
+{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}
+
+---
+
+或者你可以在 `response_class` 參數中使用它:
+
+{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}
+
+若這麼做,你就可以在「路徑操作函式」中直接回傳 URL。
+
+在此情況下,所使用的 `status_code` 會是 `RedirectResponse` 的預設值 `307`。
+
+---
+
+你也可以同時搭配 `status_code` 與 `response_class` 參數:
+
+{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}
+
+### `StreamingResponse` { #streamingresponse }
+
+接收一個 async 產生器或一般的產生器/疊代器(帶有 `yield` 的函式),並以串流方式傳送回應本文。
+
+{* ../../docs_src/custom_response/tutorial007_py310.py hl[3,16] *}
+
+/// note | 技術細節
+
+一個 `async` 任務只能在抵達某個 `await` 時才能被取消。如果沒有 `await`,該產生器(帶有 `yield` 的函式)將無法被正確取消,甚至在請求取消後仍可能持續執行。
+
+因為這個小範例不需要任何 `await` 陳述式,我們加入 `await anyio.sleep(0)`,讓事件迴圈有機會處理取消。
+
+對於大型或無限的串流來說,這點更為重要。
+
+///
+
+/// tip
+
+與其直接回傳 `StreamingResponse`,你大概會想遵循[資料串流](./stream-data.md)中的作法,這樣更方便,並且會在底層幫你處理取消。
+
+如果你要串流 JSON Lines,請參考教學:[串流 JSON Lines](../tutorial/stream-json-lines.md)。
+
+///
+
+### `FileResponse` { #fileresponse }
+
+以非同步串流方式將檔案作為回應。
+
+它在初始化時所需的參數與其他回應型別不同:
+
+- `path` - 要串流的檔案路徑。
+- `headers` - 要包含的自訂標頭,字典形式。
+- `media_type` - 描述 media type 的字串。若未設定,將根據檔名或路徑推斷 media type。
+- `filename` - 若設定,會包含在回應的 `Content-Disposition` 中。
+
+檔案回應會包含適當的 `Content-Length`、`Last-Modified` 與 `ETag` 標頭。
+
+{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}
+
+你也可以使用 `response_class` 參數:
+
+{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}
+
+在此情況下,你可以在「路徑操作函式」中直接回傳檔案路徑。
+
+## 自訂回應類別 { #custom-response-class }
+
+你可以建立自己的自訂回應類別,繼承自 `Response` 並加以使用。
+
+例如,假設你要使用 [`orjson`](https://github.com/ijl/orjson) 並套用一些設定。
+
+假設你想回傳縮排且格式化的 JSON,因此要使用 orjson 選項 `orjson.OPT_INDENT_2`。
+
+你可以建立 `CustomORJSONResponse`。你主要需要做的是建立一個 `Response.render(content)` 方法,將內容以 `bytes` 回傳:
+
+{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}
+
+現在,不再是回傳:
+
+```json
+{"message": "Hello World"}
+```
+
+...這個回應會回傳:
+
+```json
+{
+ "message": "Hello World"
+}
+```
+
+當然,你大概能找到比格式化 JSON 更好的方式來利用這個能力。😉
+
+### `orjson` 或回應模型 { #orjson-or-response-model }
+
+如果你追求效能,使用[回應模型](../tutorial/response-model.md) 大概會比使用 `orjson` 回應更好。
+
+有了回應模型,FastAPI 會使用 Pydantic 直接將資料序列化為 JSON,而不需要像其他情況那樣先經過 `jsonable_encoder` 之類的中介步驟。
+
+而且在底層,Pydantic 用來序列化為 JSON 的 Rust 機制和 `orjson` 相同,因此用回應模型已經能獲得最佳效能。
+
+## 預設回應類別 { #default-response-class }
+
+在建立 **FastAPI** 類別實例或 `APIRouter` 時,你可以指定預設要使用哪個回應類別。
+
+用來設定的是 `default_response_class` 參數。
+
+在下面的例子中,**FastAPI** 會在所有「路徑操作」中預設使用 `HTMLResponse`,而不是 JSON。
+
+{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}
+
+/// tip
+
+你仍然可以在「路徑操作」中像以前一樣覆寫 `response_class`。
+
+///
+
+## 其他文件化選項 { #additional-documentation }
+
+你也可以在 OpenAPI 中使用 `responses` 宣告 media type 與其他許多細節:[在 OpenAPI 中的額外回應](additional-responses.md)。
diff --git a/docs/zh-hant/docs/advanced/dataclasses.md b/docs/zh-hant/docs/advanced/dataclasses.md
new file mode 100644
index 0000000000000..a18b421c42ccd
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/dataclasses.md
@@ -0,0 +1,87 @@
+# 使用 Dataclasses { #using-dataclasses }
+
+FastAPI 建立在 **Pydantic** 之上,我之前示範過如何使用 Pydantic 模型來宣告請求與回應。
+
+但 FastAPI 也同樣支援以相同方式使用 [`dataclasses`](https://docs.python.org/3/library/dataclasses.html):
+
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
+
+這之所以可行,要感謝 **Pydantic**,因為它 [內建支援 `dataclasses`](https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel)。
+
+所以,即使上面的程式碼沒有明確使用 Pydantic,FastAPI 仍會使用 Pydantic 將那些標準的 dataclass 轉換為 Pydantic 版本的 dataclass。
+
+而且當然一樣支援:
+
+- 資料驗證
+- 資料序列化
+- 資料文件化等
+
+它的運作方式與 Pydantic 模型相同;實際上,底層就是透過 Pydantic 達成的。
+
+/// info
+
+請記得,dataclass 無法做到 Pydantic 模型能做的一切。
+
+所以你可能仍然需要使用 Pydantic 模型。
+
+但如果你手邊剛好有一堆 dataclass,這是個不錯的小技巧,可以用來用 FastAPI 驅動一個 Web API。🤓
+
+///
+
+## 在 `response_model` 中使用 Dataclasses { #dataclasses-in-response-model }
+
+你也可以在 `response_model` 參數中使用 `dataclasses`:
+
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
+
+該 dataclass 會自動轉換為 Pydantic 的 dataclass。
+
+如此一來,其結構描述(schema)會顯示在 API 文件介面中:
+
+
+
+## 巢狀資料結構中的 Dataclasses { #dataclasses-in-nested-data-structures }
+
+你也可以將 `dataclasses` 與其他型別註記結合,建立巢狀的資料結構。
+
+在某些情況下,你可能仍需要使用 Pydantic 版本的 `dataclasses`。例如,當自動產生的 API 文件出現錯誤時。
+
+這種情況下,你可以把標準的 `dataclasses` 直接換成 `pydantic.dataclasses`,它是可直接替換(drop-in replacement)的:
+
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+
+1. 我們仍然從標準的 `dataclasses` 匯入 `field`。
+2. `pydantic.dataclasses` 是 `dataclasses` 的可直接替換版本。
+3. `Author` dataclass 內含一個 `Item` dataclass 的清單。
+4. `Author` dataclass 被用作 `response_model` 參數。
+5. 你可以將其他標準型別註記與 dataclass 一起用作請求本文。
+
+ 在此例中,它是 `Item` dataclass 的清單。
+6. 這裡我們回傳一個字典,其中的 `items` 是一個 dataclass 清單。
+
+ FastAPI 仍能將資料序列化為 JSON。
+7. 這裡 `response_model` 使用的是「`Author` dataclass 的清單」這種型別註記。
+
+ 同樣地,你可以把 `dataclasses` 與標準型別註記組合使用。
+8. 注意這個「路徑操作函式」使用的是一般的 `def` 而非 `async def`。
+
+ 一如往常,在 FastAPI 中你可以視需要混用 `def` 與 `async def`。
+
+ 如果需要複習何時用哪個,請參考文件中關於 [`async` 與 `await`](../async.md#in-a-hurry) 的章節「In a hurry?」。
+9. 這個「路徑操作函式」回傳的不是 dataclass(雖然也可以),而是一個包含內部資料的字典清單。
+
+ FastAPI 會使用 `response_model` 參數(其中包含 dataclass)來轉換回應。
+
+你可以把 `dataclasses` 與其他型別註記以多種方式組合,形成複雜的資料結構。
+
+查看上面程式碼中的註解提示以了解更具體的細節。
+
+## 延伸閱讀 { #learn-more }
+
+你也可以將 `dataclasses` 與其他 Pydantic 模型結合、從它們繼承、把它們包含進你的自訂模型等。
+
+想了解更多,請參考 [Pydantic 關於 dataclasses 的文件](https://docs.pydantic.dev/latest/concepts/dataclasses/)。
+
+## 版本 { #version }
+
+自 FastAPI 版本 `0.67.0` 起可用。🔖
diff --git a/docs/zh-hant/docs/advanced/events.md b/docs/zh-hant/docs/advanced/events.md
new file mode 100644
index 0000000000000..7def525fa6ed1
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/events.md
@@ -0,0 +1,165 @@
+# 生命週期事件 { #lifespan-events }
+
+你可以定義在應用程式**啟動**之前要執行的邏輯(程式碼)。也就是說,這段程式碼會在應用開始接收請求**之前**、**只執行一次**。
+
+同樣地,你也可以定義在應用程式**關閉**時要執行的邏輯(程式碼)。在這種情況下,這段程式碼會在處理了**許多請求**之後、**只執行一次**。
+
+因為這些程式碼分別在應用開始接收請求**之前**與**完成**處理請求之後執行,所以涵蓋了整個應用的**生命週期**(「lifespan」這個詞稍後會很重要 😉)。
+
+這對於為整個應用設定需要**共用**於多個請求的**資源**,以及在之後進行**清理**,非常有用。比如資料庫連線池、或載入一個共用的機器學習模型。
+
+## 使用情境 { #use-case }
+
+先從一個**使用情境**開始,然後看看如何用這個機制解決。
+
+想像你有一些要用來處理請求的**機器學習模型**。🤖
+
+同一組模型會在多個請求間共用,所以不是每個請求或每個使用者各有一個模型。
+
+再想像一下,載入模型**需要一段時間**,因為它必須從**磁碟**讀取大量資料。所以你不想在每個請求都做一次。
+
+你可以在模組/檔案的最上層載入,但這也表示即使只是要跑一個簡單的自動化測試,也會去**載入模型**,導致測試**變慢**,因為它得等模型載入完才能執行與模型無關的程式碼部分。
+
+我們要解決的正是這件事:在開始處理請求之前再載入模型,但只在應用程式即將開始接收請求時載入,而不是在匯入程式碼時就載入。
+
+## 生命週期(Lifespan) { #lifespan }
+
+你可以使用 `FastAPI` 應用的 `lifespan` 參數,搭配「context manager」(稍後會示範),來定義這些 *startup* 與 *shutdown* 邏輯。
+
+先看一個例子,接著再深入說明。
+
+我們建立一個帶有 `yield` 的非同步函式 `lifespan()`,如下:
+
+{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}
+
+這裡我們透過在 `yield` 之前把(假的)模型函式放進機器學習模型的字典中,來模擬昂貴的 *startup* 載入模型操作。這段程式會在應用**開始接收請求之前**執行,也就是 *startup* 階段。
+
+接著,在 `yield` 之後,我們卸載模型。這段程式會在應用**完成處理請求之後**、也就是 *shutdown* 前執行。這可以用來釋放資源,例如記憶體或 GPU。
+
+/// tip
+
+`shutdown` 會在你**停止**應用程式時發生。
+
+也許你要啟動新版本,或只是不想再跑它了。🤷
+
+///
+
+### Lifespan 函式 { #lifespan-function }
+
+首先要注意的是,我們定義了一個帶有 `yield` 的 async 函式。這和帶有 `yield` 的依賴(Dependencies)非常相似。
+
+{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}
+
+函式在 `yield` 之前的部分,會在應用啟動前先執行。
+
+`yield` 之後的部分,會在應用結束後再執行。
+
+### 非同步內容管理器(Async Context Manager) { #async-context-manager }
+
+你會看到這個函式被 `@asynccontextmanager` 裝飾。
+
+它會把函式轉換成所謂的「**非同步內容管理器(async context manager)**」。
+
+{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}
+
+Python 中的**內容管理器(context manager)**可以用在 `with` 陳述式中,例如 `open()` 可以作為內容管理器使用:
+
+```Python
+with open("file.txt") as file:
+ file.read()
+```
+
+在較新的 Python 版本中,也有**非同步內容管理器**。你可以用 `async with` 來使用它:
+
+```Python
+async with lifespan(app):
+ await do_stuff()
+```
+
+當你像上面那樣建立一個內容管理器或非同步內容管理器時,在進入 `with` 區塊之前,會先執行 `yield` 之前的程式碼;離開 `with` 區塊之後,會執行 `yield` 之後的程式碼。
+
+在我們的範例中,並不是直接用它,而是把它傳給 FastAPI 來使用。
+
+`FastAPI` 應用的 `lifespan` 參數需要一個**非同步內容管理器**,所以我們可以把剛寫好的 `lifespan` 非同步內容管理器傳給它。
+
+{* ../../docs_src/events/tutorial003_py310.py hl[22] *}
+
+## 替代事件(已棄用) { #alternative-events-deprecated }
+
+/// warning
+
+目前建議使用上面所述,透過 `FastAPI` 應用的 `lifespan` 參數來處理 *startup* 與 *shutdown*。如果你提供了 `lifespan` 參數,`startup` 與 `shutdown` 事件處理器將不會被呼叫。要嘛全用 `lifespan`,要嘛全用事件,不能同時混用。
+
+你大概可以直接跳過這一節。
+
+///
+
+也有另一種方式可以定義在 *startup* 與 *shutdown* 期間要執行的邏輯。
+
+你可以定義事件處理器(函式)來在應用啟動前或關閉時執行。
+
+這些函式可以用 `async def` 或一般的 `def` 宣告。
+
+### `startup` 事件 { #startup-event }
+
+要加入一個在應用啟動前執行的函式,使用事件 `"startup"` 來宣告:
+
+{* ../../docs_src/events/tutorial001_py310.py hl[8] *}
+
+在這個例子中,`startup` 事件處理器函式會用一些值來初始化 items 的「資料庫」(其實就是個 `dict`)。
+
+你可以註冊多個事件處理函式。
+
+而且在所有 `startup` 事件處理器都完成之前,你的應用不會開始接收請求。
+
+### `shutdown` 事件 { #shutdown-event }
+
+要加入一個在應用關閉時執行的函式,使用事件 `"shutdown"` 來宣告:
+
+{* ../../docs_src/events/tutorial002_py310.py hl[6] *}
+
+在這裡,`shutdown` 事件處理器函式會把一行文字 `"Application shutdown"` 寫入檔案 `log.txt`。
+
+/// info
+
+在 `open()` 函式中,`mode="a"` 表示「append(附加)」;也就是說,這行文字會加在檔案現有內容之後,而不會覆寫先前的內容。
+
+///
+
+/// tip
+
+注意這裡我們使用的是標準 Python 的 `open()` 函式來操作檔案。
+
+這涉及 I/O(輸入/輸出),也就是需要「等待」資料寫入磁碟。
+
+但 `open()` 並不使用 `async` 與 `await`。
+
+所以我們用一般的 `def` 來宣告事件處理器,而不是 `async def`。
+
+///
+
+### 同時使用 `startup` 與 `shutdown` { #startup-and-shutdown-together }
+
+你的 *startup* 與 *shutdown* 邏輯很可能是相關聯的:你可能會先啟動某個東西再把它結束、先取得資源再釋放它,等等。
+
+如果把它們拆成兩個彼此不共享邏輯或變數的獨立函式,會比較麻煩,你得把值存在全域變數或用其他技巧。
+
+因此,現在建議改用上面介紹的 `lifespan`。
+
+## 技術細節 { #technical-details }
+
+給有興趣鑽研的同好一點技術細節。🤓
+
+在底層的 ASGI 技術規範中,這屬於 [Lifespan Protocol](https://asgi.readthedocs.io/en/latest/specs/lifespan.html) 的一部分,並定義了 `startup` 與 `shutdown` 兩種事件。
+
+/// info
+
+你可以在 [Starlette 的 Lifespan 文件](https://www.starlette.dev/lifespan/) 讀到更多關於 Starlette `lifespan` 處理器的資訊。
+
+也包含如何處理可在程式其他區域使用的 lifespan 狀態。
+
+///
+
+## 子應用程式 { #sub-applications }
+
+🚨 請記住,這些生命週期事件(startup 與 shutdown)只會在主應用程式上執行,不會在[子應用程式 - 掛載](sub-applications.md)上執行。
diff --git a/docs/zh-hant/docs/advanced/generate-clients.md b/docs/zh-hant/docs/advanced/generate-clients.md
new file mode 100644
index 0000000000000..c069a8034f119
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/generate-clients.md
@@ -0,0 +1,208 @@
+# 產生 SDK { #generating-sdks }
+
+由於 **FastAPI** 建立在 **OpenAPI** 規格之上,其 API 能以許多工具都能理解的標準格式來描述。
+
+這讓你能輕鬆產生最新的**文件**、多語言的用戶端程式庫(**SDKs**),以及與程式碼保持同步的**測試**或**自動化工作流程**。
+
+在本指南中,你將學會如何為你的 FastAPI 後端產生 **TypeScript SDK**。
+
+## 開源 SDK 產生器 { #open-source-sdk-generators }
+
+其中一個相當萬用的選擇是 [OpenAPI Generator](https://openapi-generator.tech/),它支援**多種程式語言**,並能從你的 OpenAPI 規格產生 SDK。
+
+針對 **TypeScript 用戶端**,[Hey API](https://heyapi.dev/) 是專門打造的解決方案,為 TypeScript 生態系提供最佳化的體驗。
+
+你可以在 [OpenAPI.Tools](https://openapi.tools/#sdk) 找到更多 SDK 產生器。
+
+/// tip
+
+FastAPI 會自動產生 **OpenAPI 3.1** 規格,因此你使用的任何工具都必須支援這個版本。
+
+///
+
+## 來自 FastAPI 贊助商的 SDK 產生器 { #sdk-generators-from-fastapi-sponsors }
+
+本節重點介紹由贊助 FastAPI 的公司提供的**創投支持**與**公司維運**的解決方案。這些產品在高品質的自動產生 SDK 之外,還提供**額外功能**與**整合**。
+
+透過 ✨ [**贊助 FastAPI**](../help-fastapi.md#sponsor-the-author) ✨,這些公司幫助確保框架與其**生態系**維持健康且**永續**。
+
+他們的贊助也展現對 FastAPI **社群**(你)的高度承諾,不僅關心提供**優良服務**,也支持 **FastAPI** 作為一個**穩健且蓬勃的框架**。🙇
+
+例如,你可以嘗試:
+
+* [Speakeasy](https://speakeasy.com/editor?utm_source=fastapi+repo&utm_medium=github+sponsorship)
+* [Stainless](https://www.stainless.com/?utm_source=fastapi&utm_medium=referral)
+* [liblab](https://developers.liblab.com/tutorials/sdk-for-fastapi?utm_source=fastapi)
+
+其中有些方案也可能是開源或提供免費方案,讓你不需財務承諾就能試用。其他商業的 SDK 產生器也不少,你可以在網路上找到。🤓
+
+## 建立 TypeScript SDK { #create-a-typescript-sdk }
+
+先從一個簡單的 FastAPI 應用開始:
+
+{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}
+
+注意這些 *路徑操作* 為請求與回應的有效載荷定義了所用的模型,使用了 `Item` 與 `ResponseMessage` 這兩個模型。
+
+### API 文件 { #api-docs }
+
+如果你前往 `/docs`,你會看到其中包含了請求要送出的資料與回應接收的資料之**結構(schemas)**:
+
+
+
+你之所以能看到這些結構,是因為它們在應用內以模型宣告了。
+
+這些資訊都在應用的 **OpenAPI 結構**中,並顯示在 API 文件裡。
+
+同樣包含在 OpenAPI 中的模型資訊,也可以用來**產生用戶端程式碼**。
+
+### Hey API { #hey-api }
+
+當我們有含模型的 FastAPI 應用後,就能用 Hey API 來產生 TypeScript 用戶端。最快的方法是透過 npx:
+
+```sh
+npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client
+```
+
+這會在 `./src/client` 產生一個 TypeScript SDK。
+
+你可以在他們的網站了解如何[安裝 `@hey-api/openapi-ts`](https://heyapi.dev/openapi-ts/get-started),以及閱讀[產生的輸出內容](https://heyapi.dev/openapi-ts/output)。
+
+### 使用 SDK { #using-the-sdk }
+
+現在你可以匯入並使用用戶端程式碼。大致看起來會像這樣,你會發現方法有自動完成:
+
+
+
+你也會對要送出的有效載荷獲得自動完成:
+
+
+
+/// tip
+
+注意 `name` 與 `price` 的自動完成,這是由 FastAPI 應用中的 `Item` 模型所定義。
+
+///
+
+你在送出的資料上也會看到行內錯誤:
+
+
+
+回應物件同樣有自動完成:
+
+
+
+## 含標籤的 FastAPI 應用 { #fastapi-app-with-tags }
+
+在許多情況下,你的 FastAPI 應用會更大,你可能會用標籤將不同群組的 *路徑操作* 分開。
+
+例如,你可以有一個 **items** 區塊與另一個 **users** 區塊,並透過標籤區分:
+
+{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}
+
+### 使用標籤產生 TypeScript 用戶端 { #generate-a-typescript-client-with-tags }
+
+若你為使用標籤的 FastAPI 應用產生用戶端,產生器通常也會依標籤將用戶端程式碼分開。
+
+如此一來,用戶端程式碼就能有條理地正確分組與排列:
+
+
+
+在此例中,你會有:
+
+* `ItemsService`
+* `UsersService`
+
+### 用戶端方法名稱 { #client-method-names }
+
+目前像 `createItemItemsPost` 這樣的產生方法名稱看起來不太俐落:
+
+```TypeScript
+ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
+```
+
+...那是因為用戶端產生器對每個 *路徑操作* 都使用 OpenAPI 內部的**操作 ID(operation ID)**。
+
+OpenAPI 要求每個操作 ID 在所有 *路徑操作* 之間必須唯一,因此 FastAPI 會用**函式名稱**、**路徑**與 **HTTP 方法/操作**來產生該操作 ID,如此便能確保操作 ID 的唯一性。
+
+接下來我會示範如何把它變得更好看。🤓
+
+## 自訂 Operation ID 與更好的方法名稱 { #custom-operation-ids-and-better-method-names }
+
+你可以**修改**這些操作 ID 的**產生方式**,讓它們更簡潔,並在用戶端中得到**更簡潔的方法名稱**。
+
+在這種情況下,你需要用其他方式確保每個操作 ID 都是**唯一**的。
+
+例如,你可以確保每個 *路徑操作* 都有標籤,接著根據**標籤**與 *路徑操作* 的**名稱**(函式名稱)來產生操作 ID。
+
+### 自訂唯一 ID 產生函式 { #custom-generate-unique-id-function }
+
+FastAPI 會為每個 *路徑操作* 使用一個**唯一 ID**,它會被用於**操作 ID**,以及任何請求或回應所需的自訂模型名稱。
+
+你可以自訂該函式。它接收一個 APIRoute 並回傳字串。
+
+例如,下面使用第一個標籤(你通常只會有一個標籤)以及 *路徑操作* 的名稱(函式名稱)。
+
+接著你可以將這個自訂函式以 `generate_unique_id_function` 參數傳給 **FastAPI**:
+
+{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}
+
+### 使用自訂 Operation ID 產生 TypeScript 用戶端 { #generate-a-typescript-client-with-custom-operation-ids }
+
+現在,如果你再次產生用戶端,會看到方法名稱已改善:
+
+
+
+如你所見,方法名稱現在包含標籤與函式名稱,不再包含 URL 路徑與 HTTP 操作的資訊。
+
+### 為用戶端產生器預處理 OpenAPI 規格 { #preprocess-the-openapi-specification-for-the-client-generator }
+
+產生的程式碼仍有一些**重複資訊**。
+
+我們已經知道這個方法與 **items** 相關,因為該字已出現在 `ItemsService`(取自標籤)中,但方法名稱仍然加上了標籤名稱做前綴。😕
+
+對於 OpenAPI 本身,我們可能仍想保留,因為那能確保操作 ID 是**唯一**的。
+
+但就產生用戶端而言,我們可以在產生前**修改** OpenAPI 的操作 ID,來讓方法名稱更**簡潔**、更**乾淨**。
+
+我們可以把 OpenAPI JSON 下載到 `openapi.json` 檔案,然後用像這樣的腳本**移除該標籤前綴**:
+
+{* ../../docs_src/generate_clients/tutorial004_py310.py *}
+
+//// tab | Node.js
+
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
+```
+
+////
+
+如此一來,操作 ID 會從 `items-get_items` 之類的字串,變成單純的 `get_items`,讓用戶端產生器能產生更簡潔的方法名稱。
+
+### 使用預處理後的 OpenAPI 產生 TypeScript 用戶端 { #generate-a-typescript-client-with-the-preprocessed-openapi }
+
+由於最終結果現在是在 `openapi.json` 檔案中,你需要更新輸入位置:
+
+```sh
+npx @hey-api/openapi-ts -i ./openapi.json -o src/client
+```
+
+產生新的用戶端後,你現在會得到**乾淨的方法名稱**,同時保有所有的**自動完成**、**行內錯誤**等功能:
+
+
+
+## 好處 { #benefits }
+
+使用自動產生的用戶端時,你會得到以下項目的**自動完成**:
+
+* 方法
+* 本文中的請求有效載荷、查詢參數等
+* 回應的有效載荷
+
+你也會對所有內容獲得**行內錯誤**提示。
+
+而且每當你更新後端程式碼並**重新產生**前端(用戶端),新的 *路徑操作* 會以方法形式可用、舊的會被移除,其他任何變更也都會反映到產生的程式碼中。🤓
+
+這也代表只要有任何變更,便會自動**反映**到用戶端程式碼;而當你**建置**用戶端時,如果使用的資料有任何**不匹配**,就會直接報錯。
+
+因此,你能在開發週期的很早期就**偵測到許多錯誤**,而不必等到錯誤在正式環境的最終使用者那裡才出現,然後才開始追查問題所在。✨
diff --git a/docs/zh-hant/docs/advanced/index.md b/docs/zh-hant/docs/advanced/index.md
new file mode 100644
index 0000000000000..9b1cb539aedb9
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/index.md
@@ -0,0 +1,21 @@
+# 進階使用者指南 { #advanced-user-guide }
+
+## 更多功能 { #additional-features }
+
+主要的[教學 - 使用者指南](../tutorial/index.md) 應足以帶你快速瀏覽 **FastAPI** 的所有核心功能。
+
+在接下來的章節中,你會看到其他選項、設定,以及更多功能。
+
+/// tip
+
+接下來的章節**不一定是「進階」**。
+
+而且對於你的使用情境,解法很可能就在其中某一節。
+
+///
+
+## 先閱讀教學 { #read-the-tutorial-first }
+
+只要掌握主要[教學 - 使用者指南](../tutorial/index.md) 的內容,你就能使用 **FastAPI** 的大多數功能。
+
+接下來的章節也假設你已經讀過,並已了解那些主要觀念。
diff --git a/docs/zh-hant/docs/advanced/json-base64-bytes.md b/docs/zh-hant/docs/advanced/json-base64-bytes.md
new file mode 100644
index 0000000000000..9f1ecfa2ea7b2
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/json-base64-bytes.md
@@ -0,0 +1,63 @@
+# 使用 Base64 表示位元組的 JSON { #json-with-bytes-as-base64 }
+
+如果你的應用需要收發 JSON 資料,但其中需要包含二進位資料,你可以將它以 base64 編碼。
+
+## Base64 與檔案 { #base64-vs-files }
+
+請先考慮是否能用 [請求檔案](../tutorial/request-files.md) 來上傳二進位資料,並用 [自訂回應 - FileResponse](./custom-response.md#fileresponse--fileresponse-) 來傳送二進位資料,而不是把它們編碼進 JSON。
+
+JSON 只能包含 UTF-8 編碼的字串,因此無法直接包含原始位元組。
+
+Base64 可以把二進位資料編碼成字串,但為此會使用比原始二進位資料更多的字元,因此通常比直接使用檔案來得沒那麼有效率。
+
+只有在確實必須把二進位資料包含在 JSON 裡,且無法改用檔案時,才使用 base64。
+
+## Pydantic `bytes` { #pydantic-bytes }
+
+你可以宣告含有 `bytes` 欄位的 Pydantic 模型,並在模型設定中使用 `val_json_bytes`,使其在驗證輸入的 JSON 資料時使用 base64;在驗證過程中,它會將 base64 字串解碼為位元組。
+
+{* ../../docs_src/json_base64_bytes/tutorial001_py310.py ln[1:9,29:35] hl[9] *}
+
+如果你查看 `/docs`,會看到欄位 `data` 需要 base64 編碼的位元組:
+
+
+
diff --git a/docs/zh-hant/docs/advanced/openapi-webhooks.md b/docs/zh-hant/docs/advanced/openapi-webhooks.md
new file mode 100644
index 0000000000000..18206c447bf85
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/openapi-webhooks.md
@@ -0,0 +1,55 @@
+# OpenAPI Webhook { #openapi-webhooks }
+
+有些情況下,你會想告訴你的 API 使用者,你的應用程式可能會攜帶一些資料去呼叫他們的應用程式(發送請求),通常是為了通知某種類型的事件。
+
+這表示,與其由使用者向你的 API 發送請求,改為你的 API(或你的應用)可能會向他們的系統(他們的 API、他們的應用)發送請求。
+
+這通常稱為 webhook。
+
+## Webhook 步驟 { #webhooks-steps }
+
+流程通常是:你在程式碼中定義要發送的訊息,也就是請求的主體(request body)。
+
+你也會以某種方式定義應用在哪些時刻會發送那些請求或事件。
+
+而你的使用者則會以某種方式(例如在某個 Web 控制台)設定你的應用應該將這些請求送往的 URL。
+
+關於如何註冊 webhook 的 URL,以及實際發送那些請求的程式碼等所有邏輯,都由你決定。你可以在自己的程式碼中用你想要的方式撰寫。
+
+## 使用 FastAPI 與 OpenAPI 記錄 webhook { #documenting-webhooks-with-fastapi-and-openapi }
+
+在 FastAPI 中,透過 OpenAPI,你可以定義這些 webhook 的名稱、你的應用將發送的 HTTP 操作類型(例如 `POST`、`PUT` 等),以及你的應用要發送的請求主體。
+
+這能讓你的使用者更容易實作他們的 API 以接收你的 webhook 請求,甚至可能自動產生部分他們自己的 API 程式碼。
+
+/// info
+
+Webhook 功能自 OpenAPI 3.1.0 起提供,FastAPI `0.99.0` 以上版本支援。
+
+///
+
+## 含有 webhook 的應用 { #an-app-with-webhooks }
+
+建立 FastAPI 應用時,會有一個 `webhooks` 屬性可用來定義 webhook,方式與定義路徑操作相同,例如使用 `@app.webhooks.post()`。
+
+{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}
+
+你定義的 webhook 會出現在 OpenAPI 結構描述與自動產生的文件 UI 中。
+
+/// info
+
+`app.webhooks` 其實就是一個 `APIRouter`,與你在將應用拆分為多個檔案時所使用的型別相同。
+
+///
+
+注意,使用 webhook 時你其實不是在宣告路徑(例如 `/items/`),你傳入的文字只是該 webhook 的識別名稱(事件名稱)。例如在 `@app.webhooks.post("new-subscription")` 中,webhook 名稱是 `new-subscription`。
+
+這是因為預期由你的使用者以其他方式(例如 Web 控制台)來設定實際要接收 webhook 請求的 URL 路徑。
+
+### 查看文件 { #check-the-docs }
+
+現在你可以啟動應用,然後前往 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)。
+
+你會在文件中看到一般的路徑操作,另外還有一些 webhook:
+
+
diff --git a/docs/zh-hant/docs/advanced/path-operation-advanced-configuration.md b/docs/zh-hant/docs/advanced/path-operation-advanced-configuration.md
new file mode 100644
index 0000000000000..f1607a1da5614
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/path-operation-advanced-configuration.md
@@ -0,0 +1,172 @@
+# 路徑操作進階設定 { #path-operation-advanced-configuration }
+
+## OpenAPI operationId { #openapi-operationid }
+
+/// warning
+
+如果你不是 OpenAPI 的「專家」,大概不需要這個。
+
+///
+
+你可以用參數 `operation_id` 為你的*路徑操作(path operation)*設定要使用的 OpenAPI `operationId`。
+
+你必須確保每個操作的 `operationId` 都是唯一的。
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
+
+### 使用路徑操作函式(path operation function)的名稱作為 operationId { #using-the-path-operation-function-name-as-the-operationid }
+
+如果你想用 API 的函式名稱作為 `operationId`,你可以遍歷所有路徑,並使用各自的 `APIRoute.name` 覆寫每個*路徑操作*的 `operation_id`。
+
+應在加入所有*路徑操作*之後再這麼做。
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *}
+
+/// tip
+
+如果你會手動呼叫 `app.openapi()`,請務必先更新所有 `operationId` 再呼叫。
+
+///
+
+/// warning
+
+如果你這樣做,必須確保每個*路徑操作函式*都有唯一的名稱,
+
+即使它們位於不同的模組(Python 檔案)中。
+
+///
+
+## 從 OpenAPI 排除 { #exclude-from-openapi }
+
+若要從產生的 OpenAPI 結構(也就是自動文件系統)中排除某個*路徑操作*,使用參數 `include_in_schema` 並將其設為 `False`:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}
+
+## 從 docstring 提供進階描述 { #advanced-description-from-docstring }
+
+你可以限制 OpenAPI 從*路徑操作函式*的 docstring 中使用的內容行數。
+
+加上一個 `\f`(跳頁字元,form feed)會讓 FastAPI 在此處截斷用於 OpenAPI 的輸出。
+
+這個字元不會出現在文件中,但其他工具(例如 Sphinx)仍可使用其後的內容。
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}
+
+## 額外回應 { #additional-responses }
+
+你大概已看過如何為*路徑操作*宣告 `response_model` 與 `status_code`。
+
+這會定義該*路徑操作*主要回應的中繼資料。
+
+你也可以宣告額外的回應及其模型、狀態碼等。
+
+文件中有完整章節說明,請見 [OpenAPI 中的額外回應](additional-responses.md)。
+
+## OpenAPI 額外資訊 { #openapi-extra }
+
+當你在應用程式中宣告一個*路徑操作*時,FastAPI 會自動產生該*路徑操作*的相關中繼資料,並納入 OpenAPI 結構中。
+
+/// note | 技術細節
+
+在 OpenAPI 規格中,這稱為 [Operation 物件](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object)。
+
+///
+
+它包含關於*路徑操作*的所有資訊,並用於產生自動文件。
+
+其中包含 `tags`、`parameters`、`requestBody`、`responses` 等。
+
+這個針對單一路徑操作的 OpenAPI 結構通常由 FastAPI 自動產生,但你也可以擴充它。
+
+/// tip
+
+這是一個較低階的擴充介面。
+
+如果你只需要宣告額外回應,更方便的方式是使用 [OpenAPI 中的額外回應](additional-responses.md)。
+
+///
+
+你可以使用參數 `openapi_extra` 來擴充某個*路徑操作*的 OpenAPI 結構。
+
+### OpenAPI 擴充 { #openapi-extensions }
+
+`openapi_extra` 可用來宣告例如 [OpenAPI 擴充](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) 的資料:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py310.py hl[6] *}
+
+打開自動產生的 API 文件時,你的擴充會顯示在該*路徑操作*頁面的底部。
+
+
+
+而在檢視產生出的 OpenAPI(位於你的 API 的 `/openapi.json`)時,也可以在相應*路徑操作*中看到你的擴充:
+
+```JSON hl_lines="22"
+{
+ "openapi": "3.1.0",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0"
+ },
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ }
+ },
+ "x-aperture-labs-portal": "blue"
+ }
+ }
+ }
+}
+```
+
+### 自訂 OpenAPI 路徑操作結構 { #custom-openapi-path-operation-schema }
+
+`openapi_extra` 中的字典會與自動產生的該*路徑操作*之 OpenAPI 結構進行深度合併。
+
+因此你可以在自動產生的結構上加入額外資料。
+
+例如,你可以選擇用自己的程式碼讀取並驗證請求,而不使用 FastAPI 與 Pydantic 的自動功能,但仍然希望在 OpenAPI 結構中定義該請求。
+
+你可以透過 `openapi_extra` 辦到:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py310.py hl[19:36, 39:40] *}
+
+在這個範例中,我們沒有宣告任何 Pydantic 模型。事實上,請求本文甚至不會被 解析 為 JSON,而是直接以 `bytes` 讀取,並由函式 `magic_data_reader()` 以某種方式負責解析。
+
+儘管如此,我們仍可宣告請求本文的預期結構。
+
+### 自訂 OpenAPI Content-Type { #custom-openapi-content-type }
+
+用同樣的方法,你可以使用 Pydantic 模型來定義 JSON Schema,並把它包含到該*路徑操作*的自訂 OpenAPI 區段中。
+
+即使請求中的資料型別不是 JSON 也可以這麼做。
+
+例如,在這個應用中,我們不使用 FastAPI 內建的從 Pydantic 模型擷取 JSON Schema 的功能,也不使用 JSON 的自動驗證。實際上,我們將請求的 content type 宣告為 YAML,而非 JSON:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[15:20, 22] *}
+
+儘管沒有使用預設的內建功能,我們仍透過 Pydantic 模型手動產生想以 YAML 接收之資料的 JSON Schema。
+
+接著我們直接使用請求,並將本文擷取為 `bytes`。這表示 FastAPI 甚至不會嘗試把請求負載解析為 JSON。
+
+然後在程式中直接解析該 YAML 內容,並再次使用相同的 Pydantic 模型來驗證該 YAML 內容:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *}
+
+/// tip
+
+這裡我們重複使用同一個 Pydantic 模型。
+
+不過也可以用其他方式進行驗證。
+
+///
diff --git a/docs/zh-hant/docs/advanced/response-change-status-code.md b/docs/zh-hant/docs/advanced/response-change-status-code.md
new file mode 100644
index 0000000000000..31b688512eecf
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/response-change-status-code.md
@@ -0,0 +1,31 @@
+# 回應 - 變更狀態碼 { #response-change-status-code }
+
+你可能已經讀過,可以設定預設的[回應狀態碼](../tutorial/response-status-code.md)。
+
+但有些情況你需要回傳與預設不同的狀態碼。
+
+## 使用情境 { #use-case }
+
+例如,假設你預設想回傳 HTTP 狀態碼 "OK" `200`。
+
+但如果資料不存在,你想要建立它,並回傳 HTTP 狀態碼 "CREATED" `201`。
+
+同時你仍希望能用 `response_model` 過濾並轉換所回傳的資料。
+
+在這些情況下,你可以使用 `Response` 參數。
+
+## 使用 `Response` 參數 { #use-a-response-parameter }
+
+你可以在你的路徑操作函式(path operation function)中宣告一個 `Response` 型別的參數(就像你可以對 Cookies 和標頭那樣)。
+
+接著你可以在那個「*暫時的*」回應物件上設定 `status_code`。
+
+{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}
+
+然後你可以照常回傳任何需要的物件(例如 `dict`、資料庫模型等)。
+
+若你宣告了 `response_model`,它仍會被用來過濾並轉換你回傳的物件。
+
+**FastAPI** 會使用那個「*暫時的*」回應來取得狀態碼(以及 Cookies 和標頭),並將它們放入最終回應中;最終回應包含你回傳的值,且會被任何 `response_model` 過濾。
+
+你也可以在相依性(dependencies)中宣告 `Response` 參數,並在其中設定狀態碼。但請注意,最後被設定的值會生效。
diff --git a/docs/zh-hant/docs/advanced/response-cookies.md b/docs/zh-hant/docs/advanced/response-cookies.md
new file mode 100644
index 0000000000000..2ba14c3f6f5ca
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/response-cookies.md
@@ -0,0 +1,51 @@
+# 回應 Cookie { #response-cookies }
+
+## 使用 `Response` 參數 { #use-a-response-parameter }
+
+你可以在路徑操作函式(path operation function)中宣告一個型別為 `Response` 的參數。
+
+接著你可以在那個「暫時」的 `Response` 物件上設定 Cookie。
+
+{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}
+
+之後如常回傳你需要的任何物件(例如 `dict`、資料庫模型等)。
+
+如果你宣告了 `response_model`,它仍會用來過濾並轉換你回傳的物件。
+
+FastAPI 會使用那個暫時的 `Response` 取出 Cookie(以及標頭與狀態碼),並將它們放入最終回應;最終回應包含你回傳的值,且會套用任何 `response_model` 的過濾。
+
+你也可以在相依項(dependencies)中宣告 `Response` 參數,並在其中設定 Cookie(與標頭)。
+
+## 直接回傳 `Response` { #return-a-response-directly }
+
+當你在程式碼中直接回傳 `Response` 時,也可以建立 Cookie。
+
+要這麼做,你可以依照 [直接回傳 Response](response-directly.md) 中的說明建立一個回應。
+
+接著在其中設定 Cookie,然後回傳它:
+
+{* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *}
+
+/// tip | 提示
+
+請注意,如果你不是使用 `Response` 參數,而是直接回傳一個 `Response`,FastAPI 會原樣回傳它。
+
+因此你必須確保資料型別正確;例如,如果你回傳的是 `JSONResponse`,就要確保資料可與 JSON 相容。
+
+同時也要確認沒有送出原本應該由 `response_model` 過濾的資料。
+
+///
+
+### 更多資訊 { #more-info }
+
+/// note | 技術細節
+
+你也可以使用 `from starlette.responses import Response` 或 `from starlette.responses import JSONResponse`。
+
+為了方便開發者,FastAPI 也將相同的 `starlette.responses` 透過 `fastapi.responses` 提供。不過,大多數可用的回應類別都直接來自 Starlette。
+
+另外由於 `Response` 常用於設定標頭與 Cookie,FastAPI 也在 `fastapi.Response` 提供了它。
+
+///
+
+想查看所有可用的參數與選項,請參閱 [Starlette 文件](https://www.starlette.dev/responses/#set-cookie)。
diff --git a/docs/zh-hant/docs/advanced/response-directly.md b/docs/zh-hant/docs/advanced/response-directly.md
new file mode 100644
index 0000000000000..16face2612876
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/response-directly.md
@@ -0,0 +1,83 @@
+# 直接回傳 Response { #return-a-response-directly }
+
+當你建立一個 **FastAPI** 的路徑操作 (path operation) 時,通常可以從中回傳任何資料:`dict`、`list`、Pydantic 模型、資料庫模型等。
+
+如果你宣告了 [回應模型](../tutorial/response-model.md),FastAPI 會用 Pydantic 將資料序列化為 JSON。
+
+如果你沒有宣告回應模型,FastAPI 會使用在[JSON 相容編碼器](../tutorial/encoder.md)中說明的 `jsonable_encoder`,並把它放進 `JSONResponse`。
+
+但你也可以直接從路徑操作回傳 `JSONResponse`。
+
+/// tip
+
+通常使用 [回應模型](../tutorial/response-model.md) 會有更好的效能,因為那樣會在 Rust 端使用 Pydantic 來序列化資料,而不是直接回傳 `JSONResponse`。
+
+///
+
+## 回傳 `Response` { #return-a-response }
+
+其實,你可以回傳任何 `Response`,或其任何子類別。
+
+/// info
+
+`JSONResponse` 本身就是 `Response` 的子類別。
+
+///
+
+當你回傳一個 `Response` 時,**FastAPI** 會直接傳遞它。
+
+它不會對 Pydantic 模型做任何資料轉換,也不會把內容轉成其他型別等。
+
+這給了你很大的彈性。你可以回傳任何資料型別、覆寫任何資料宣告或驗證等。
+
+同時也帶來了很大的責任。你必須確保你回傳的資料是正確的、格式正確、可被序列化等。
+
+## 在 `Response` 中使用 `jsonable_encoder` { #using-the-jsonable-encoder-in-a-response }
+
+因為 **FastAPI** 不會對你回傳的 `Response` 做任何更動,你需要自行確保它的內容已經準備好。
+
+例如,你不能直接把一個 Pydantic 模型放進 `JSONResponse`,需要先把它轉成 `dict`,並將所有資料型別(像是 `datetime`、`UUID` 等)轉成與 JSON 相容的型別。
+
+在這些情況下,你可以先用 `jsonable_encoder` 把資料轉好,再傳給回應物件:
+
+{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}
+
+/// note | 技術細節
+
+你也可以使用 `from starlette.responses import JSONResponse`。
+
+**FastAPI** 為了方便開發者,將 `starlette.responses` 也提供為 `fastapi.responses`。但大多數可用的回應類型其實直接來自 Starlette。
+
+///
+
+## 回傳自訂 `Response` { #returning-a-custom-response }
+
+上面的範例展示了所需的各個部分,但目前還不太實用,因為你其實可以直接回傳 `item`,**FastAPI** 就會幫你把它放進 `JSONResponse`,轉成 `dict` 等,這些都是預設行為。
+
+現在來看看如何用它來回傳自訂回應。
+
+假設你想要回傳一個 [XML](https://en.wikipedia.org/wiki/XML) 回應。
+
+你可以把 XML 內容放進一個字串,把它放進 `Response`,然後回傳它:
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+## 回應模型如何運作 { #how-a-response-model-works }
+
+當你在路徑操作中宣告 [回應模型 - 回傳型別](../tutorial/response-model.md) 時,**FastAPI** 會用 Pydantic 將資料序列化為 JSON。
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+由於這會在 Rust 端發生,效能會比用一般的 Python 與 `JSONResponse` 類別來完成好得多。
+
+當使用 `response_model` 或回傳型別時,FastAPI 不會使用 `jsonable_encoder` 來轉換資料(那會較慢),也不會使用 `JSONResponse` 類別。
+
+相反地,它會取用用回應模型(或回傳型別)透過 Pydantic 產生的 JSON 位元組,並直接回傳具備正確 JSON 媒體型別(`application/json`)的 `Response`。
+
+## 注意事項 { #notes }
+
+當你直接回傳 `Response` 時,其資料不會自動被驗證、轉換(序列化)或文件化。
+
+但你仍然可以依照[在 OpenAPI 中的額外回應](additional-responses.md)中的說明進行文件化。
+
+在後續章節中,你會看到如何在仍保有自動資料轉換、文件化等的同時,使用/宣告這些自訂的 `Response`。
diff --git a/docs/zh-hant/docs/advanced/response-headers.md b/docs/zh-hant/docs/advanced/response-headers.md
new file mode 100644
index 0000000000000..4f7494a8b39f3
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/response-headers.md
@@ -0,0 +1,41 @@
+# 回應標頭 { #response-headers }
+
+## 使用 `Response` 參數 { #use-a-response-parameter }
+
+你可以在你的*路徑操作函式(path operation function)*中宣告一個 `Response` 型別的參數(就像處理 Cookie 一樣)。
+
+然後你可以在那個*暫時性的* `Response` 物件上設定標頭。
+
+{* ../../docs_src/response_headers/tutorial002_py310.py hl[1, 7:8] *}
+
+接著你可以像平常一樣回傳任何你需要的物件(`dict`、資料庫模型等)。
+
+如果你宣告了 `response_model`,它仍會用來過濾並轉換你回傳的物件。
+
+FastAPI 會使用那個暫時性的回應來擷取標頭(還有 Cookie 與狀態碼),並把它們放到最終回應中;最終回應包含你回傳的值,且會依任何 `response_model` 進行過濾。
+
+你也可以在依賴中宣告 `Response` 參數,並在其中設定標頭(與 Cookie)。
+
+## 直接回傳 `Response` { #return-a-response-directly }
+
+當你直接回傳 `Response` 時,也能加入標頭。
+
+依照[直接回傳 Response](response-directly.md)中的說明建立回應,並把標頭作為額外參數傳入:
+
+{* ../../docs_src/response_headers/tutorial001_py310.py hl[10:12] *}
+
+/// note | 技術細節
+
+你也可以使用 `from starlette.responses import Response` 或 `from starlette.responses import JSONResponse`。
+
+為了方便開發者,FastAPI 提供與 `starlette.responses` 相同的內容於 `fastapi.responses`。但大多數可用的回應類型其實直接來自 Starlette。
+
+由於 `Response` 常用來設定標頭與 Cookie,FastAPI 也在 `fastapi.Response` 提供了它。
+
+///
+
+## 自訂標頭 { #custom-headers }
+
+請記住,專有的自訂標頭可以[使用 `X-` 前綴](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers)來新增。
+
+但如果你有自訂標頭並希望瀏覽器端的客戶端能看見它們,你需要把這些標頭加入到 CORS 設定中(詳見 [CORS(跨來源資源共用)](../tutorial/cors.md)),使用在[Starlette 的 CORS 文件](https://www.starlette.dev/middleware/#corsmiddleware)中記載的 `expose_headers` 參數。
diff --git a/docs/zh-hant/docs/advanced/security/http-basic-auth.md b/docs/zh-hant/docs/advanced/security/http-basic-auth.md
new file mode 100644
index 0000000000000..817cf166b9960
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/security/http-basic-auth.md
@@ -0,0 +1,107 @@
+# HTTP 基本認證 { #http-basic-auth }
+
+在最簡單的情況下,你可以使用 HTTP Basic 認證。
+
+在 HTTP Basic 認證中,應用程式會期待一個包含使用者名稱與密碼的標頭。
+
+如果沒有接收到,會回傳 HTTP 401「Unauthorized」錯誤。
+
+並回傳一個 `WWW-Authenticate` 標頭,其值為 `Basic`,以及可選的 `realm` 參數。
+
+這會告訴瀏覽器顯示內建的使用者名稱與密碼提示視窗。
+
+接著,當你輸入該使用者名稱與密碼時,瀏覽器會自動在標頭中送出它們。
+
+## 簡單的 HTTP 基本認證 { #simple-http-basic-auth }
+
+- 匯入 `HTTPBasic` 與 `HTTPBasicCredentials`。
+- 使用 `HTTPBasic` 建立一個「`security` scheme」。
+- 在你的*路徑操作*中以依賴的方式使用該 `security`。
+- 它會回傳一個 `HTTPBasicCredentials` 型別的物件:
+ - 其中包含傳來的 `username` 與 `password`。
+
+{* ../../docs_src/security/tutorial006_an_py310.py hl[4,8,12] *}
+
+當你第一次嘗試開啟該 URL(或在文件中點擊 "Execute" 按鈕)時,瀏覽器會要求輸入你的使用者名稱與密碼:
+
+
+
+## 檢查使用者名稱 { #check-the-username }
+
+以下是一個更完整的範例。
+
+使用一個依賴來檢查使用者名稱與密碼是否正確。
+
+為此,使用 Python 標準模組 [`secrets`](https://docs.python.org/3/library/secrets.html) 來比對使用者名稱與密碼。
+
+`secrets.compare_digest()` 需要接收 `bytes`,或是只包含 ASCII 字元(英文字符)的 `str`。這表示它無法處理像 `á` 這樣的字元,例如 `Sebastián`。
+
+為了處理這點,我們會先將 `username` 與 `password` 以 UTF-8 編碼成 `bytes`。
+
+接著我們可以使用 `secrets.compare_digest()` 來確認 `credentials.username` 等於 `"stanleyjobson"`,而 `credentials.password` 等於 `"swordfish"`。
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[1,12:24] *}
+
+這大致等同於:
+
+```Python
+if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
+ # 回傳錯誤
+ ...
+```
+
+但藉由使用 `secrets.compare_digest()`,可以防禦一種稱為「計時攻擊」的攻擊。
+
+### 計時攻擊 { #timing-attacks }
+
+什麼是「計時攻擊」呢?
+
+想像有攻擊者在嘗試猜測使用者名稱與密碼。
+
+他們送出一個帶有使用者名稱 `johndoe` 與密碼 `love123` 的請求。
+
+接著,你的應用程式中的 Python 程式碼等同於:
+
+```Python
+if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+當 Python 比較 `johndoe` 的第一個 `j` 與 `stanleyjobson` 的第一個 `s` 時,會立刻回傳 `False`,因為已經知道兩個字串不同,覺得「沒必要浪費計算資源繼續比較剩下的字元」。你的應用程式便會回應「Incorrect username or password」。
+
+但接著攻擊者改用使用者名稱 `stanleyjobsox` 與密碼 `love123` 嘗試。
+
+你的應用程式程式碼會做類似:
+
+```Python
+if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+Python 會必須先比較完整的 `stanleyjobso`(在 `stanleyjobsox` 與 `stanleyjobson` 之中都一樣),才會發現兩個字串不同。因此回覆「Incorrect username or password」會多花一些微秒。
+
+#### 回應時間幫了攻擊者 { #the-time-to-answer-helps-the-attackers }
+
+此時,透過觀察伺服器回覆「Incorrect username or password」多花了幾個微秒,攻擊者就知道他們有某些地方猜對了,前幾個字母是正確的。
+
+接著他們會再嘗試,知道它更可能接近 `stanleyjobsox` 而不是 `johndoe`。
+
+#### 「專業」的攻擊 { #a-professional-attack }
+
+當然,攻擊者不會手動嘗試這一切,他們會寫程式來做,可能每秒進行上千或上百萬次測試,一次只多猜中一個正確字母。
+
+但這樣做,幾分鐘或幾小時內,他們就能在我們應用程式「協助」下,僅靠回應時間就猜出正確的使用者名稱與密碼。
+
+#### 用 `secrets.compare_digest()` 修正 { #fix-it-with-secrets-compare-digest }
+
+但在我們的程式碼中實際使用的是 `secrets.compare_digest()`。
+
+簡而言之,將 `stanleyjobsox` 與 `stanleyjobson` 比較所花的時間,會與將 `johndoe` 與 `stanleyjobson` 比較所花的時間相同;密碼也一樣。
+
+如此一來,在應用程式程式碼中使用 `secrets.compare_digest()`,就能安全地防禦這整類的安全攻擊。
+
+### 回傳錯誤 { #return-the-error }
+
+在偵測到憑證不正確之後,回傳一個狀態碼為 401 的 `HTTPException`(與未提供憑證時相同),並加上 `WWW-Authenticate` 標頭,讓瀏覽器再次顯示登入提示:
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[26:30] *}
diff --git a/docs/zh-hant/docs/advanced/security/index.md b/docs/zh-hant/docs/advanced/security/index.md
new file mode 100644
index 0000000000000..9ddf3567567e8
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/security/index.md
@@ -0,0 +1,19 @@
+# 進階安全性 { #advanced-security }
+
+## 額外功能 { #additional-features }
+
+除了[教學 - 使用者指南:安全性](../../tutorial/security/index.md)中涵蓋的內容外,還有一些用來處理安全性的額外功能。
+
+/// tip
+
+以下各節**不一定是「進階」**內容。
+
+而且你的情境很可能可以在其中找到解決方案。
+
+///
+
+## 請先閱讀教學 { #read-the-tutorial-first }
+
+以下各節假設你已閱讀主要的[教學 - 使用者指南:安全性](../../tutorial/security/index.md)。
+
+它們都建立在相同的概念之上,但提供一些額外的功能。
diff --git a/docs/zh-hant/docs/advanced/security/oauth2-scopes.md b/docs/zh-hant/docs/advanced/security/oauth2-scopes.md
new file mode 100644
index 0000000000000..05088be7ed6b0
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/security/oauth2-scopes.md
@@ -0,0 +1,274 @@
+# OAuth2 範圍(scopes) { #oauth2-scopes }
+
+你可以直接在 FastAPI 中使用 OAuth2 的 scopes,已整合可無縫運作。
+
+這能讓你在 OpenAPI 應用(以及 API 文件)中,依照 OAuth2 標準,實作更細粒度的權限系統。
+
+帶有 scopes 的 OAuth2 是許多大型身分驗證提供者(如 Facebook、Google、GitHub、Microsoft、X(Twitter)等)所使用的機制。他們用它來為使用者與應用程式提供特定權限。
+
+每次你「使用」Facebook、Google、GitHub、Microsoft、X(Twitter)「登入」時,那個應用就是在使用帶有 scopes 的 OAuth2。
+
+在本節中,你將看到如何在你的 FastAPI 應用中,用同樣的帶有 scopes 的 OAuth2 管理驗證與授權。
+
+/// warning
+
+這一節算是進階內容。如果你剛開始,可以先跳過。
+
+你不一定需要 OAuth2 scopes,你可以用任何你想要的方式處理驗證與授權。
+
+但帶有 scopes 的 OAuth2 可以很漂亮地整合進你的 API(透過 OpenAPI)與 API 文件。
+
+無論如何,你仍然會在程式碼中,依你的需求,強制檢查那些 scopes,或其他任何安全性/授權需求。
+
+在許多情況下,帶有 scopes 的 OAuth2 可能有點大材小用。
+
+但如果你確定需要,或是好奇,請繼續閱讀。
+
+///
+
+## OAuth2 scopes 與 OpenAPI { #oauth2-scopes-and-openapi }
+
+OAuth2 規格將「scopes」定義為以空白分隔的一串字串列表。
+
+每個字串的內容可以有任意格式,但不應包含空白。
+
+這些 scopes 代表「權限」。
+
+在 OpenAPI(例如 API 文件)中,你可以定義「security schemes」。
+
+當某個 security scheme 使用 OAuth2 時,你也可以宣告並使用 scopes。
+
+每個「scope」就是一個(不含空白的)字串。
+
+它們通常用來宣告特定的安全性權限,例如:
+
+- `users:read` 或 `users:write` 是常見的例子。
+- `instagram_basic` 是 Facebook / Instagram 使用的。
+- `https://www.googleapis.com/auth/drive` 是 Google 使用的。
+
+/// info
+
+在 OAuth2 中,「scope」只是宣告所需特定權限的一個字串。
+
+是否包含像 `:` 這樣的字元,或是否是一個 URL,都沒差。
+
+那些細節取決於實作。
+
+對 OAuth2 而言,它們就是字串。
+
+///
+
+## 全局概觀 { #global-view }
+
+先快速看看相對於主教學「使用密碼(與雜湊)、Bearer 與 JWT token 的 OAuth2」的差異([OAuth2 with Password (and hashing), Bearer with JWT tokens](../../tutorial/security/oauth2-jwt.md))。現在加入了 OAuth2 scopes:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}
+
+接著我們一步一步檢視這些變更。
+
+## OAuth2 安全性方案 { #oauth2-security-scheme }
+
+第一個變更是:我們現在宣告了帶有兩個可用 scope 的 OAuth2 安全性方案,`me` 與 `items`。
+
+參數 `scopes` 接收一個 `dict`,以各 scope 為鍵、其描述為值:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *}
+
+由於現在宣告了這些 scopes,當你登入/授權時,它們會出現在 API 文件中。
+
+你可以選擇要授予哪些 scopes 存取權:`me` 與 `items`。
+
+這與你使用 Facebook、Google、GitHub 等登入時所授與權限的機制相同:
+
+
+
+## 內含 scopes 的 JWT token { #jwt-token-with-scopes }
+
+現在,修改 token 的路徑操作以回傳所請求的 scopes。
+
+我們仍然使用相同的 `OAuth2PasswordRequestForm`。它包含屬性 `scopes`,其為 `list` 的 `str`,列出請求中收到的每個 scope。
+
+並且我們將這些 scopes 作為 JWT token 的一部分回傳。
+
+/// danger
+
+為了簡化,這裡我們只是直接把接收到的 scopes 加進 token。
+
+但在你的應用中,為了安全性,你應確保只加入該使用者實際可擁有或你預先定義的 scopes。
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}
+
+## 在路徑操作與相依性中宣告 scopes { #declare-scopes-in-path-operations-and-dependencies }
+
+現在我們宣告 `/users/me/items/` 這個路徑操作需要 `items` 這個 scope。
+
+為此,我們從 `fastapi` 匯入並使用 `Security`。
+
+你可以使用 `Security` 來宣告相依性(就像 `Depends`),但 `Security` 也能接收參數 `scopes`,其為 scopes(字串)的列表。
+
+在這裡,我們將相依函式 `get_current_active_user` 傳給 `Security`(就像使用 `Depends` 一樣)。
+
+但同時也傳入一個 `list` 的 scopes,這裡只有一個 scope:`items`(當然也可以有更多)。
+
+而相依函式 `get_current_active_user` 也能宣告子相依性,不只用 `Depends`,也能用 `Security`。它宣告了自己的子相依函式(`get_current_user`),並加入更多 scope 要求。
+
+在這個例子中,它要求 `me` 這個 scope(也可以要求多個)。
+
+/// note
+
+你不一定需要在不同地方加上不同的 scopes。
+
+我們在這裡這樣做,是為了示範 FastAPI 如何處理在不同層級宣告的 scopes。
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}
+
+/// info | 技術細節
+
+`Security` 其實是 `Depends` 的子類別,僅多了一個我們稍後會看到的參數。
+
+改用 `Security` 而不是 `Depends`,能讓 FastAPI 知道可以宣告安全性 scopes、在內部使用它們,並用 OpenAPI 文件化 API。
+
+另外,當你從 `fastapi` 匯入 `Query`、`Path`、`Depends`、`Security` 等時,實際上它們是回傳特殊類別的函式。
+
+///
+
+## 使用 `SecurityScopes` { #use-securityscopes }
+
+現在更新相依性 `get_current_user`。
+
+上面的相依性就是使用它。
+
+這裡我們使用先前建立的相同 OAuth2 scheme,並將其宣告為相依性:`oauth2_scheme`。
+
+因為此相依函式本身沒有任何 scope 要求,所以我們可以用 `Depends` 搭配 `oauth2_scheme`,當不需要指定安全性 scopes 時就不必用 `Security`。
+
+我們也宣告了一個型別為 `SecurityScopes` 的特殊參數,從 `fastapi.security` 匯入。
+
+這個 `SecurityScopes` 類似於 `Request`(`Request` 用來直接取得請求物件)。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}
+
+## 使用這些 `scopes` { #use-the-scopes }
+
+參數 `security_scopes` 的型別是 `SecurityScopes`。
+
+它會有屬性 `scopes`,包含一個列表,內含此函式本身與所有使用它為子相依性的相依性所要求的所有 scopes。也就是所有「相依者(dependants)」... 這聽起來可能有點混亂,下面會再解釋。
+
+`security_scopes` 物件(類別 `SecurityScopes`)也提供 `scope_str` 屬性,為一個字串,包含那些以空白分隔的 scopes(我們會用到)。
+
+我們建立一個可在多處重複丟出(`raise`)的 `HTTPException`。
+
+在這個例外中,我們把所需的 scopes(若有)以空白分隔的字串形式(透過 `scope_str`)加入,並將該包含 scopes 的字串放在 `WWW-Authenticate` 標頭中(這是規格的一部分)。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}
+
+## 驗證 `username` 與資料結構 { #verify-the-username-and-data-shape }
+
+我們先確認取得了 `username`,並取出 scopes。
+
+接著用 Pydantic 模型驗證這些資料(捕捉 `ValidationError` 例外),若在讀取 JWT token 或用 Pydantic 驗證資料時出錯,就丟出先前建立的 `HTTPException`。
+
+為此,我們更新了 Pydantic 模型 `TokenData`,加入新屬性 `scopes`。
+
+透過 Pydantic 驗證資料,我們可以確保,例如,scopes 正好是 `list` 的 `str`,而 `username` 是 `str`。
+
+否則若是 `dict` 或其他型別,可能在後續某處使應用壞掉,造成安全風險。
+
+我們也會確認該 `username` 對應的使用者是否存在,否則同樣丟出之前建立的例外。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}
+
+## 驗證 `scopes` { #verify-the-scopes }
+
+我們現在要驗證,此相依性與所有相依者(包含路徑操作)所要求的所有 scopes,是否都包含在收到的 token 內所提供的 scopes 中;否則就丟出 `HTTPException`。
+
+為此,我們使用 `security_scopes.scopes`,其中包含一個 `list`,列出所有這些 `str` 形式的 scopes。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}
+
+## 相依性樹與 scopes { #dependency-tree-and-scopes }
+
+我們再回顧一次這個相依性樹與 scopes。
+
+由於 `get_current_active_user` 相依於 `get_current_user`,因此在 `get_current_active_user` 宣告的 `"me"` 這個 scope 會包含在傳給 `get_current_user` 的 `security_scopes.scopes` 的必須 scopes 清單中。
+
+路徑操作本身也宣告了 `"items"` 這個 scope,因此它也會包含在傳給 `get_current_user` 的 `security_scopes.scopes` 中。
+
+以下是相依性與 scopes 的階層關係:
+
+- 路徑操作 `read_own_items` 具有:
+ - 需要的 scopes `["items"]`,並有相依性:
+ - `get_current_active_user`:
+ - 相依函式 `get_current_active_user` 具有:
+ - 需要的 scopes `["me"]`,並有相依性:
+ - `get_current_user`:
+ - 相依函式 `get_current_user` 具有:
+ - 自身沒有需要的 scopes。
+ - 一個使用 `oauth2_scheme` 的相依性。
+ - 一個型別為 `SecurityScopes` 的 `security_scopes` 參數:
+ - 這個 `security_scopes` 參數有屬性 `scopes`,其為一個 `list`,包含了上面宣告的所有 scopes,因此:
+ - 對於路徑操作 `read_own_items`,`security_scopes.scopes` 會包含 `["me", "items"]`。
+ - 對於路徑操作 `read_users_me`,因為它在相依性 `get_current_active_user` 中被宣告,`security_scopes.scopes` 會包含 `["me"]`。
+ - 對於路徑操作 `read_system_status`,因為它沒有宣告任何帶 `scopes` 的 `Security`,且其相依性 `get_current_user` 也未宣告任何 `scopes`,所以 `security_scopes.scopes` 會包含 `[]`(空)。
+
+/// tip
+
+這裡重要且「神奇」的是:`get_current_user` 在每個路徑操作中,會有不同的 `scopes` 清單需要檢查。
+
+這完全取決於該路徑操作與其相依性樹中每個相依性所宣告的 `scopes`。
+
+///
+
+## 更多關於 `SecurityScopes` 的細節 { #more-details-about-securityscopes }
+
+你可以在任意位置、多個地方使用 `SecurityScopes`,它不需要位於「根」相依性。
+
+它會永遠帶有對於「該特定」路徑操作與「該特定」相依性樹中,目前 `Security` 相依性所宣告的安全性 scopes(以及所有相依者):
+
+因為 `SecurityScopes` 會擁有由相依者宣告的所有 scopes,你可以在一個集中式相依函式中用它來驗證 token 是否具有所需 scopes,然後在不同路徑操作中宣告不同的 scope 要求。
+
+它們會在每個路徑操作被各自獨立檢查。
+
+## 試用看看 { #check-it }
+
+如果你打開 API 文件,你可以先驗證並指定你要授權的 scopes。
+
+
+
+如果你沒有選任何 scope,你仍會「通過驗證」,但當你嘗試存取 `/users/me/` 或 `/users/me/items/` 時,會收到沒有足夠權限的錯誤。你仍能存取 `/status/`。
+
+若你只選了 `me` 而未選 `items`,你能存取 `/users/me/`,但無法存取 `/users/me/items/`。
+
+這就是第三方應用在取得使用者提供的 token 後,嘗試存取上述路徑操作時,會依使用者授與該應用的權限多寡而有不同結果。
+
+## 關於第三方整合 { #about-third-party-integrations }
+
+在這個範例中,我們使用 OAuth2 的「password」流程。
+
+當我們登入自己的應用(可能也有自己的前端)時,這是合適的。
+
+因為我們可以信任它接收 `username` 與 `password`,因為我們掌控它。
+
+但如果你要打造一個讓他人連接的 OAuth2 應用(也就是你要建立一個相當於 Facebook、Google、GitHub 等的身分驗證提供者),你應該使用其他流程之一。
+
+最常見的是 Implicit Flow(隱式流程)。
+
+最安全的是 Authorization Code Flow(授權碼流程),但它需要更多步驟、實作也更複雜。因為較複雜,許多提供者最後會建議使用隱式流程。
+
+/// note
+
+很常見的是,每個身分驗證提供者會用不同的方式命名他們的流程,讓它成為品牌的一部分。
+
+但最終,他們實作的都是相同的 OAuth2 標準。
+
+///
+
+FastAPI 在 `fastapi.security.oauth2` 中提供了所有這些 OAuth2 驗證流程的工具。
+
+## 在裝飾器 `dependencies` 中使用 `Security` { #security-in-decorator-dependencies }
+
+就像你可以在裝飾器的 `dependencies` 參數中定義一個 `Depends` 的 `list` 一樣(詳見[路徑操作裝飾器中的相依性](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md)),你也可以在那裡使用帶有 `scopes` 的 `Security`。
diff --git a/docs/zh-hant/docs/advanced/settings.md b/docs/zh-hant/docs/advanced/settings.md
new file mode 100644
index 0000000000000..9892f8f000be4
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/settings.md
@@ -0,0 +1,302 @@
+# 設定與環境變數 { #settings-and-environment-variables }
+
+在許多情況下,你的應用程式可能需要一些外部設定或組態,例如密鑰、資料庫憑證、電子郵件服務的憑證等。
+
+這些設定大多是可變的(可能會改變),像是資料庫 URL。也有許多可能是敏感資訊,例如密鑰。
+
+因此,通常會透過環境變數提供這些設定,讓應用程式去讀取。
+
+/// tip
+
+若想了解環境變數,你可以閱讀[環境變數](../environment-variables.md)。
+
+///
+
+## 型別與驗證 { #types-and-validation }
+
+這些環境變數只能處理文字字串,因為它們在 Python 之外,必須與其他程式與系統的其餘部分相容(甚至跨作業系統,如 Linux、Windows、macOS)。
+
+這表示在 Python 中自環境變數讀取到的任何值都會是 `str`,而任何轉型成其他型別或驗證都必須在程式碼中完成。
+
+## Pydantic `Settings` { #pydantic-settings }
+
+幸好,Pydantic 提供了很好的工具,可用來處理由環境變數而來的設定:[Pydantic:設定管理](https://docs.pydantic.dev/latest/concepts/pydantic_settings/)。
+
+### 安裝 `pydantic-settings` { #install-pydantic-settings }
+
+首先,請先建立你的[虛擬環境](../virtual-environments.md),啟用它,然後安裝 `pydantic-settings` 套件:
+
+
+
+接著,開啟子應用程式的文件:[http://127.0.0.1:8000/subapi/docs](http://127.0.0.1:8000/subapi/docs)。
+
+你會看到子應用程式的自動 API 文件,只包含它自己的*路徑操作*,而且都在正確的子路徑前綴 `/subapi` 之下:
+
+
+
+如果你嘗試在任一介面中互動,它們都會正常運作,因為瀏覽器能與各自的應用程式或子應用程式通訊。
+
+### 技術細節:`root_path` { #technical-details-root-path }
+
+當你像上面那樣掛載子應用程式時,FastAPI 會使用 ASGI 規範中的一個機制 `root_path`,將子應用程式的掛載路徑告知它。
+
+如此一來,子應用程式就會知道在文件 UI 使用該路徑前綴。
+
+而且子應用程式也能再掛載自己的子應用程式,一切都能正確運作,因為 FastAPI 會自動處理所有這些 `root_path`。
+
+你可以在[在代理伺服器之後](behind-a-proxy.md)一節中進一步了解 `root_path` 與如何顯式使用它。
diff --git a/docs/zh-hant/docs/advanced/templates.md b/docs/zh-hant/docs/advanced/templates.md
new file mode 100644
index 0000000000000..6e622d5a77423
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/templates.md
@@ -0,0 +1,126 @@
+# 模板 { #templates }
+
+你可以在 **FastAPI** 中使用任意你想要的模板引擎。
+
+常見的選擇是 Jinja2,與 Flask 與其他工具所使用的一樣。
+
+有一些工具可讓你輕鬆設定,並可直接在你的 **FastAPI** 應用程式中使用(由 Starlette 提供)。
+
+## 安裝相依套件 { #install-dependencies }
+
+請先建立一個[虛擬環境](../virtual-environments.md)、啟用它,然後安裝 `jinja2`:
+
+
+
+你可以在輸入框輸入訊息並送出:
+
+
+
+你的 **FastAPI** 應用會透過 WebSockets 回應:
+
+
+
+你可以傳送(與接收)多則訊息:
+
+
+
+而且它們都會使用同一個 WebSocket 連線。
+
+## 使用 `Depends` 與其他功能 { #using-depends-and-others }
+
+在 WebSocket 端點中,你可以從 `fastapi` 匯入並使用:
+
+* `Depends`
+* `Security`
+* `Cookie`
+* `Header`
+* `Path`
+* `Query`
+
+它們的運作方式與其他 FastAPI 端點/*路徑操作* 相同:
+
+{* ../../docs_src/websockets_/tutorial002_an_py310.py hl[68:69,82] *}
+
+/// info
+
+因為這是 WebSocket,拋出 `HTTPException` 並沒有意義,因此我們改為拋出 `WebSocketException`。
+
+你可以使用規範中定義的[有效關閉代碼](https://tools.ietf.org/html/rfc6455#section-7.4.1)之一。
+
+///
+
+### 用依賴試用 WebSocket { #try-the-websockets-with-dependencies }
+
+執行你的應用:
+
+
+
+## 處理斷線與多個用戶端 { #handling-disconnections-and-multiple-clients }
+
+當 WebSocket 連線關閉時,`await websocket.receive_text()` 會拋出 `WebSocketDisconnect` 例外,你可以像範例中那樣捕捉並處理。
+
+{* ../../docs_src/websockets_/tutorial003_py310.py hl[79:81] *}
+
+試用方式:
+
+* 用多個瀏覽器分頁開啟該應用。
+* 從每個分頁傳送訊息。
+* 然後關閉其中一個分頁。
+
+這會引發 `WebSocketDisconnect` 例外,其他所有用戶端都會收到類似以下的訊息:
+
+```
+Client #1596980209979 left the chat
+```
+
+/// tip
+
+上面的應用是一個極簡範例,用來示範如何處理並向多個 WebSocket 連線廣播訊息。
+
+但請注意,因為所有狀態都在記憶體中的單一 list 裡管理,它只會在該程序執行期間生效,且僅適用於單一程序。
+
+如果你需要一個容易與 FastAPI 整合、但更健壯,且可由 Redis、PostgreSQL 等後端支援的方案,請參考 [encode/broadcaster](https://github.com/encode/broadcaster)。
+
+///
+
+## 更多資訊 { #more-info }
+
+想了解更多選項,請參考 Starlette 的文件:
+
+* [`WebSocket` 類別](https://www.starlette.dev/websockets/)。
+* [以類別為基礎的 WebSocket 處理](https://www.starlette.dev/endpoints/#websocketendpoint)。
diff --git a/docs/zh-hant/docs/advanced/wsgi.md b/docs/zh-hant/docs/advanced/wsgi.md
new file mode 100644
index 0000000000000..c1baff34ed3ac
--- /dev/null
+++ b/docs/zh-hant/docs/advanced/wsgi.md
@@ -0,0 +1,51 @@
+# 包含 WSGI:Flask、Django 等 { #including-wsgi-flask-django-others }
+
+你可以像在 [子應用程式 - 掛載](sub-applications.md)、[在 Proxy 後方](behind-a-proxy.md) 中所見那樣掛載 WSGI 應用。
+
+為此,你可以使用 `WSGIMiddleware` 來包住你的 WSGI 應用,例如 Flask、Django 等。
+
+## 使用 `WSGIMiddleware` { #using-wsgimiddleware }
+
+/// info
+
+這需要先安裝 `a2wsgi`,例如使用 `pip install a2wsgi`。
+
+///
+
+你需要從 `a2wsgi` 匯入 `WSGIMiddleware`。
+
+然後用該 middleware 包住 WSGI(例如 Flask)應用。
+
+接著把它掛載到某個路徑下。
+
+{* ../../docs_src/wsgi/tutorial001_py310.py hl[1,3,23] *}
+
+/// note
+
+先前建議使用來自 `fastapi.middleware.wsgi` 的 `WSGIMiddleware`,但現在已棄用。
+
+建議改用 `a2wsgi` 套件。用法保持相同。
+
+只要確保已安裝 `a2wsgi`,並從 `a2wsgi` 正確匯入 `WSGIMiddleware` 即可。
+
+///
+
+## 試試看 { #check-it }
+
+現在,位於路徑 `/v1/` 底下的所有請求都會由 Flask 應用處理。
+
+其餘則由 **FastAPI** 處理。
+
+如果你啟動它並前往 [http://localhost:8000/v1/](http://localhost:8000/v1/),你會看到來自 Flask 的回應:
+
+```txt
+Hello, World from Flask!
+```
+
+如果你前往 [http://localhost:8000/v2](http://localhost:8000/v2),你會看到來自 FastAPI 的回應:
+
+```JSON
+{
+ "message": "Hello World"
+}
+```
diff --git a/docs/zh-hant/docs/alternatives.md b/docs/zh-hant/docs/alternatives.md
new file mode 100644
index 0000000000000..ee99faf99f7ea
--- /dev/null
+++ b/docs/zh-hant/docs/alternatives.md
@@ -0,0 +1,485 @@
+# 替代方案、靈感與比較 { #alternatives-inspiration-and-comparisons }
+
+啟發 FastAPI 的來源、與其他方案的比較,以及從中學到的內容。
+
+## 介紹 { #intro }
+
+沒有前人的工作,就不會有 **FastAPI**。
+
+在它誕生之前,已經有許多工具啟發了它的設計。
+
+我多年來一直避免打造新框架。起初我嘗試用許多不同的框架、外掛與工具,來實作 **FastAPI** 涵蓋的所有功能。
+
+但在某個時間點,除了創建一個能提供所有這些功能、汲取前人工具的優點,並以最佳方式組合起來、同時運用過去甚至不存在的語言特性(Python 3.6+ 的型別提示)之外,已別無他法。
+
+## 先前的工具 { #previous-tools }
+
+### [Django](https://www.djangoproject.com/) { #django }
+
+它是最受歡迎且廣受信任的 Python 框架。像 Instagram 等系統就是用它打造的。
+
+它與關聯式資料庫(如 MySQL 或 PostgreSQL)相對緊密耦合,因此要以 NoSQL 資料庫(如 Couchbase、MongoDB、Cassandra 等)作為主要儲存引擎並不容易。
+
+它一開始是為在後端產生 HTML 而設計,而非為了建立提供現代前端(如 React、Vue.js、Angular)或其他系統(如 IoT 裝置)使用的 API。
+
+### [Django REST Framework](https://www.django-rest-framework.org/) { #django-rest-framework }
+
+Django REST framework 的目標是成為一套在 Django 之上構建 Web API 的彈性工具組,以強化其 API 能力。
+
+它被 Mozilla、Red Hat、Eventbrite 等眾多公司使用。
+
+它是「自動 API 文件」的早期典範之一,而這正是啟發我「尋找」**FastAPI** 的第一個想法。
+
+/// note
+
+Django REST Framework 由 Tom Christie 創建。他同時也是 Starlette 與 Uvicorn 的作者,而 **FastAPI** 就是建立在它們之上。
+
+///
+
+/// check | 啟發 **FastAPI**
+
+提供自動化的 API 文件網頁使用者介面。
+
+///
+
+### [Flask](https://flask.palletsprojects.com) { #flask }
+
+Flask 是一個「微框架」,它不包含資料庫整合,也沒有像 Django 那樣內建許多功能。
+
+這種簡單與彈性,讓你可以把 NoSQL 資料庫作為主要的資料儲存系統。
+
+由於它非常簡單,學起來相對直觀,儘管文件在某些地方會變得較技術性。
+
+它也常用於其他不一定需要資料庫、使用者管理或 Django 內建眾多功能的應用程式。雖然這些功能中的許多都可以用外掛新增。
+
+這種元件的解耦,以及作為可擴充以精準滿足需求的「微框架」,是我想要保留的關鍵特性。
+
+基於 Flask 的簡潔,它看起來很適合用來構建 API。接下來要找的,就是 Flask 世界裡的「Django REST Framework」。
+
+/// check | 啟發 **FastAPI**
+
+成為一個微框架,讓所需的工具與元件能輕鬆搭配組合。
+
+具備簡單、易用的路由系統。
+
+///
+
+### [Requests](https://requests.readthedocs.io) { #requests }
+
+**FastAPI** 其實不是 **Requests** 的替代品。兩者的範疇截然不同。
+
+在 FastAPI 應用程式「內部」使用 Requests 其實很常見。
+
+儘管如此,FastAPI 仍從 Requests 得到了不少啟發。
+
+**Requests** 是一個「與 API 互動」(作為用戶端)的程式庫,而 **FastAPI** 是一個「建立 API」(作為伺服端)的程式庫。
+
+它們大致位於相反兩端,彼此互補。
+
+Requests 設計非常簡單直觀、容易使用,且有合理的預設值。同時它也非常強大且可自訂。
+
+因此,如其官網所言:
+
+> Requests is one of the most downloaded Python packages of all time
+
+用法非常簡單。例如,發出一個 `GET` 請求,你會寫:
+
+```Python
+response = requests.get("http://example.com/some/url")
+```
+
+相對地,FastAPI 的 API 路徑操作(path operation)可能像這樣:
+
+```Python hl_lines="1"
+@app.get("/some/url")
+def read_url():
+ return {"message": "Hello World"}
+```
+
+看看 `requests.get(...)` 與 `@app.get(...)` 的相似之處。
+
+/// check | 啟發 **FastAPI**
+
+* 擁有簡單直觀的 API。
+* 直接使用 HTTP 方法名稱(操作),以直接、直觀的方式表達。
+* 具備合理的預設值,同時提供強大的自訂能力。
+
+///
+
+### [Swagger](https://swagger.io/) / [OpenAPI](https://github.com/OAI/OpenAPI-Specification/) { #swagger-openapi }
+
+我想從 Django REST Framework 得到的主要功能是自動 API 文件。
+
+後來我發現有一個使用 JSON(或 YAML,JSON 的延伸)來描述 API 的標準,叫做 Swagger。
+
+而且已有對 Swagger API 的網頁使用者介面。因此,只要能為 API 產生 Swagger 文件,就可以自動使用這個網頁介面。
+
+之後 Swagger 交由 Linux 基金會管理,並更名為 OpenAPI。
+
+因此,談到 2.0 版時常說「Swagger」,而 3+ 版則是「OpenAPI」。
+
+/// check | 啟發 **FastAPI**
+
+採用並使用開放的 API 規格標準,而非自訂格式。
+
+並整合基於標準的使用者介面工具:
+
+* [Swagger UI](https://github.com/swagger-api/swagger-ui)
+* [ReDoc](https://github.com/Rebilly/ReDoc)
+
+選擇這兩個是因為它們相當受歡迎且穩定,但稍加搜尋,你會發現有數十種 OpenAPI 的替代使用者介面(都能與 **FastAPI** 一起使用)。
+
+///
+
+### Flask 的 REST 框架 { #flask-rest-frameworks }
+
+有幾個 Flask 的 REST 框架,但在投入時間調查後,我發現許多已停止維護或被棄置,且存在一些關鍵問題使之不適用。
+
+### [Marshmallow](https://marshmallow.readthedocs.io/en/stable/) { #marshmallow }
+
+API 系統需要的主要功能之一是資料「序列化」,也就是把程式中的資料(Python)轉成能透過網路傳輸的形式。例如,將含有資料庫資料的物件轉成 JSON 物件、把 `datetime` 物件轉成字串等等。
+
+API 需要的另一個重要功能是資料驗證,確保資料在特定條件下有效。例如,某個欄位必須是 `int`,而不是隨便的字串。這對於輸入資料特別有用。
+
+沒有資料驗證系統的話,你就得在程式碼中手動逐一檢查。
+
+這些功能正是 Marshmallow 所要提供的。它是很棒的函式庫,我之前也大量使用。
+
+但它誕生於 Python 型別提示出現之前。因此,為了定義每個 結構(schema),你需要使用 Marshmallow 提供的特定工具與類別。
+
+/// check | 啟發 **FastAPI**
+
+用程式碼定義能自動提供資料型別與驗證的「schemas」。
+
+///
+
+### [Webargs](https://webargs.readthedocs.io/en/latest/) { #webargs }
+
+API 所需的另一項大功能,是從傳入請求中解析資料。
+
+Webargs 是在多個框架(包含 Flask)之上提供該功能的工具。
+
+它底層使用 Marshmallow 來做資料驗證,且由同一群開發者建立。
+
+它是一個很棒的工具,在有 **FastAPI** 之前我也經常使用。
+
+/// info
+
+Webargs 由與 Marshmallow 相同的開發者創建。
+
+///
+
+/// check | 啟發 **FastAPI**
+
+自動驗證傳入請求資料。
+
+///
+
+### [APISpec](https://apispec.readthedocs.io/en/stable/) { #apispec }
+
+Marshmallow 與 Webargs 以外掛提供驗證、解析與序列化。
+
+但文件仍然缺失,於是 APISpec 出現了。
+
+它是多個框架的外掛(Starlette 也有對應外掛)。
+
+它的作法是:你在處理路由的每個函式的 docstring 中,用 YAML 格式撰寫結構定義。
+
+然後它會產生 OpenAPI schemas。
+
+在 Flask、Starlette、Responder 等框架中都是這樣運作。
+
+但這又帶來一個問題:在 Python 字串中(大型 YAML)加入一段微語法。
+
+編輯器幫不上太多忙。而且如果我們修改了參數或 Marshmallow 的 schemas 卻忘了同步修改 YAML docstring,產生的結構就會過時。
+
+/// info
+
+APISpec 由與 Marshmallow 相同的開發者創建。
+
+///
+
+/// check | 啟發 **FastAPI**
+
+支援 API 的開放標準 OpenAPI。
+
+///
+
+### [Flask-apispec](https://flask-apispec.readthedocs.io/en/latest/) { #flask-apispec }
+
+這是一個 Flask 外掛,把 Webargs、Marshmallow 與 APISpec 串在一起。
+
+它使用 Webargs 與 Marshmallow 的資訊,透過 APISpec 自動產生 OpenAPI 結構。
+
+它是個很棒但被低估的工具。它理應比許多 Flask 外掛更受歡迎,可能因為它的文件過於簡潔與抽象。
+
+這解決了在 Python 文件字串中撰寫 YAML(另一種語法)的问题。
+
+在打造 **FastAPI** 前,我最喜歡的後端技術組合就是 Flask、Flask-apispec、Marshmallow 與 Webargs。
+
+使用它促成了數個 Flask 全端(full-stack)產生器。這些是我(以及若干外部團隊)至今主要使用的技術組合:
+
+* [https://github.com/tiangolo/full-stack](https://github.com/tiangolo/full-stack)
+* [https://github.com/tiangolo/full-stack-flask-couchbase](https://github.com/tiangolo/full-stack-flask-couchbase)
+* [https://github.com/tiangolo/full-stack-flask-couchdb](https://github.com/tiangolo/full-stack-flask-couchdb)
+
+而這些全端產生器,也成為了 [**FastAPI** 專案產生器](project-generation.md) 的基礎。
+
+/// info
+
+Flask-apispec 由與 Marshmallow 相同的開發者創建。
+
+///
+
+/// check | 啟發 **FastAPI**
+
+從定義序列化與驗證的相同程式碼,自動產生 OpenAPI 結構(schema)。
+
+///
+
+### [NestJS](https://nestjs.com/)(與 [Angular](https://angular.io/)) { #nestjs-and-angular }
+
+這甚至不是 Python。NestJS 是受 Angular 啟發的 JavaScript(TypeScript)NodeJS 框架。
+
+它達成的效果與 Flask-apispec 能做的有點相似。
+
+它有一套受 Angular 2 啟發的整合式相依性注入(Dependency Injection)系統。需要預先註冊「可注入」元件(就像我所知的其他相依性注入系統一樣),因此會增加冗長與重複程式碼。
+
+由於參數以 TypeScript 型別描述(與 Python 型別提示相似),編輯器支援相當不錯。
+
+但因為 TypeScript 的型別在編譯成 JavaScript 後不會被保留,它無法僅靠型別同時定義驗證、序列化與文件。由於這點以及部分設計決定,若要取得驗證、序列化與自動結構產生,就需要在許多地方加上裝飾器,因此會相當冗長。
+
+它無法很好地處理巢狀模型。若請求的 JSON 主體中有內層欄位,且這些內層欄位又是巢狀 JSON 物件,就無法被妥善地文件化與驗證。
+
+/// check | 啟發 **FastAPI**
+
+使用 Python 型別以獲得優秀的編輯器支援。
+
+提供強大的相依性注入系統,並想辦法將重複程式碼降到最低。
+
+///
+
+### [Sanic](https://sanic.readthedocs.io/en/latest/) { #sanic }
+
+它是最早基於 `asyncio` 的極高速 Python 框架之一,並做得很像 Flask。
+
+/// note | 技術細節
+
+它使用 [`uvloop`](https://github.com/MagicStack/uvloop) 取代預設的 Python `asyncio` 事件圈。這也是它如此之快的原因。
+
+它明顯啟發了 Uvicorn 與 Starlette,而在公開的基準測試中,它們目前比 Sanic 更快。
+
+///
+
+/// check | 啟發 **FastAPI**
+
+想辦法達到瘋狂的效能。
+
+這就是為什麼 **FastAPI** 建立於 Starlette 之上,因為它是可用的最快框架(由第三方評測)。
+
+///
+
+### [Falcon](https://falconframework.org/) { #falcon }
+
+Falcon 是另一個高效能 Python 框架,設計上極簡,並作為其他框架(如 Hug)的基礎。
+
+它設計為函式接收兩個參數,一個是「request」,一個是「response」。然後你從 request「讀取」資料、往 response「寫入」資料。由於這種設計,無法使用標準的 Python 型別提示,直接以函式參數宣告請求參數與主體。
+
+因此,資料驗證、序列化與文件必須以程式碼手動完成,無法自動化。或者需在 Falcon 之上實作另一層框架(如 Hug)。其他受 Falcon 設計啟發的框架也有同樣的區別:將 request 與 response 物件作為參數。
+
+/// check | 啟發 **FastAPI**
+
+設法取得優秀的效能。
+
+連同 Hug(Hug 建立於 Falcon 之上)一起,也啟發 **FastAPI** 在函式中宣告一個 `response` 參數。
+
+不過在 FastAPI 中它是可選的,主要用來設定標頭、Cookie 與替代狀態碼。
+
+///
+
+### [Molten](https://moltenframework.com/) { #molten }
+
+我在 **FastAPI** 打造的早期發現了 Molten。它有一些相當類似的想法:
+
+* 基於 Python 型別提示。
+* 從這些型別取得驗證與文件。
+* 相依性注入系統。
+
+它沒有使用像 Pydantic 這樣的第三方資料驗證、序列化與文件庫,而是有自己的。因此,這些資料型別定義較不容易重複使用。
+
+它需要更為冗長的設定。而且因為它基於 WSGI(而非 ASGI),並未設計來享受如 Uvicorn、Starlette、Sanic 等工具所提供的高效能。
+
+其相依性注入系統需要預先註冊依賴,並且依據宣告的型別來解析依賴。因此,無法宣告多個能提供相同型別的「元件」。
+
+路由需要在單一地方宣告,使用在其他地方宣告的函式(而不是用可以直接放在端點處理函式上方的裝飾器)。這更接近 Django 的作法,而不是 Flask(與 Starlette)的作法。它在程式碼中分離了其實相當緊密耦合的事物。
+
+/// check | 啟發 **FastAPI**
+
+用模型屬性的「預設值」來定義資料型別的額外驗證。這提升了編輯器支援,而這在當時的 Pydantic 還不支援。
+
+這實際上也啟發了 Pydantic 的部分更新,以支援相同的驗證宣告風格(這些功能現在已在 Pydantic 中可用)。
+
+///
+
+### [Hug](https://github.com/hugapi/hug) { #hug }
+
+Hug 是最早使用 Python 型別提示來宣告 API 參數型別的框架之一。這是個很棒的點子,也啟發了其他工具。
+
+它在宣告中使用自訂型別而非標準 Python 型別,但仍然是巨大的一步。
+
+它也是最早能以 JSON 產出自訂結構、描述整個 API 的框架之一。
+
+它不是基於 OpenAPI 與 JSON Schema 等標準。因此,與其他工具(如 Swagger UI)的整合並不直覺。但它仍是一個非常創新的想法。
+
+它有個有趣、少見的功能:同一個框架可同時建立 API 與 CLI。
+
+由於它基於同步 Python 網頁框架的舊標準(WSGI),無法處理 WebSocket 與其他功能,儘管效能仍然很高。
+
+/// info
+
+Hug 由 Timothy Crosley 創建,他同時也是 [`isort`](https://github.com/timothycrosley/isort) 的作者,一個自動排序 Python 匯入的好工具。
+
+///
+
+/// check | 啟發 **FastAPI** 的想法
+
+Hug 啟發了 APIStar 的部分設計,也是我覺得最有前景的工具之一,與 APIStar 並列。
+
+Hug 啟發 **FastAPI** 使用 Python 型別提示宣告參數,並自動產生定義 API 的結構。
+
+Hug 啟發 **FastAPI** 在函式中宣告 `response` 參數以設定標頭與 Cookie。
+
+///
+
+### [APIStar](https://github.com/encode/apistar) (<= 0.5) { #apistar-0-5 }
+
+在決定打造 **FastAPI** 之前,我找到了 **APIStar** 伺服器。它幾乎具備我所尋找的一切,而且設計很出色。
+
+它是我見過最早使用 Python 型別提示來宣告參數與請求的框架實作之一(早於 NestJS 與 Molten)。我與 Hug 幾乎在同時間發現它。不過 APIStar 使用的是 OpenAPI 標準。
+
+它基於相同的型別提示,在多處自動進行資料驗證、資料序列化與 OpenAPI 結構產生。
+
+主體結構(body schema)的定義並未使用像 Pydantic 那樣的 Python 型別提示,更像 Marshmallow,因此編輯器支援沒有那麼好,但整體而言,APIStar 是當時最好的選擇。
+
+它在當時的效能評測中名列前茅(僅被 Starlette 超越)。
+
+一開始它沒有自動 API 文件的網頁 UI,但我知道我可以替它加上 Swagger UI。
+
+它有相依性注入系統。需要預先註冊元件,與上面提到的其他工具相同。不過這仍是很棒的功能。
+
+我從未能在完整專案中使用它,因為它沒有安全性整合,所以無法取代我用 Flask-apispec 全端產生器所擁有的全部功能。我曾把新增該功能的 pull request 放在待辦清單中。
+
+但之後,專案的重心改變了。
+
+它不再是 API 網頁框架,因為作者需要專注於 Starlette。
+
+現在的 APIStar 是一套用於驗證 OpenAPI 規格的工具,不是網頁框架。
+
+/// info
+
+APIStar 由 Tom Christie 創建。他也創建了:
+
+* Django REST Framework
+* Starlette(**FastAPI** 建立於其上)
+* Uvicorn(Starlette 與 **FastAPI** 使用)
+
+///
+
+/// check | 啟發 **FastAPI**
+
+存在。
+
+用相同的 Python 型別同時宣告多件事(資料驗證、序列化與文件),並同時提供出色的編輯器支援,這是一個極好的點子。
+
+在長時間尋找並測試多種不同替代方案後,APIStar 是最好的可用選擇。
+
+當 APIStar 不再作為伺服器存在,而 Starlette 誕生並成為更好的基礎時,這成為打造 **FastAPI** 的最後一個靈感。
+
+我將 **FastAPI** 視為 APIStar 的「精神繼承者」,同時基於所有這些先前工具的經驗,改進並擴增了功能、型別系統與其他部分。
+
+///
+
+## **FastAPI** 所採用的工具 { #used-by-fastapi }
+
+### [Pydantic](https://docs.pydantic.dev/) { #pydantic }
+
+Pydantic 是基於 Python 型別提示,定義資料驗證、序列化與文件(使用 JSON Schema)的函式庫。
+
+這讓它非常直覺。
+
+它可與 Marshmallow 相提並論。儘管在效能測試中它比 Marshmallow 更快。而且因為它基於相同的 Python 型別提示,編輯器支援也很出色。
+
+/// check | **FastAPI** 用於
+
+處理所有資料驗證、資料序列化與自動模型文件(基於 JSON Schema)。
+
+**FastAPI** 接著會把這些 JSON Schema 資料放入 OpenAPI 中,此外還有其他許多功能。
+
+///
+
+### [Starlette](https://www.starlette.dev/) { #starlette }
+
+Starlette 是一個輕量的 ASGI 框架/工具集,非常適合用來建構高效能的 asyncio 服務。
+
+它非常簡單直觀。設計上易於擴充,且元件化。
+
+它具備:
+
+* 令人印象深刻的效能。
+* WebSocket 支援。
+* 行程內(in-process)背景任務。
+* 啟動與關閉事件。
+* 建立在 HTTPX 上的測試用戶端。
+* CORS、GZip、靜態檔案、串流回應。
+* Session 與 Cookie 支援。
+* 100% 測試涵蓋率。
+* 100% 型別註解的程式碼庫。
+* 幾乎沒有硬性相依。
+
+Starlette 目前是測試中最快的 Python 框架。僅次於 Uvicorn(它不是框架,而是伺服器)。
+
+Starlette 提供所有網頁微框架的基礎功能。
+
+但它不提供自動的資料驗證、序列化或文件。
+
+這正是 **FastAPI** 在其上方加入的主要功能之一,且全部基於 Python 型別提示(使用 Pydantic)。此外還有相依性注入系統、安全性工具、OpenAPI 結構產生等。
+
+/// note | 技術細節
+
+ASGI 是由 Django 核心團隊成員正在開發的新「標準」。它尚未成為「Python 標準」(PEP),但他們正著手進行中。
+
+儘管如此,它已被多個工具作為「標準」採用。這大幅提升了互通性,例如你可以把 Uvicorn 換成其他 ASGI 伺服器(如 Daphne 或 Hypercorn),或加入相容 ASGI 的工具,如 `python-socketio`。
+
+///
+
+/// check | **FastAPI** 用於
+
+處理所有核心網頁部分,並在其上加上功能。
+
+`FastAPI` 這個類別本身直接繼承自 `Starlette` 類別。
+
+因此,凡是你能用 Starlette 做的事,你都能直接用 **FastAPI** 完成,因為它基本上就是加強版的 Starlette。
+
+///
+
+### [Uvicorn](https://www.uvicorn.dev/) { #uvicorn }
+
+Uvicorn 是基於 uvloop 與 httptools 的極速 ASGI 伺服器。
+
+它不是網頁框架,而是伺服器。例如,它不提供依據路徑路由的工具。這是像 Starlette(或 **FastAPI**)這樣的框架在其上方提供的功能。
+
+它是 Starlette 與 **FastAPI** 推薦使用的伺服器。
+
+/// check | **FastAPI** 建議用作
+
+執行 **FastAPI** 應用的主要網頁伺服器。
+
+你也可以使用 `--workers` 命令列選項,取得非同步的多製程伺服器。
+
+更多細節請見[部署](deployment/index.md)章節。
+
+///
+
+## 效能與速度 { #benchmarks-and-speed }
+
+想了解、比較並看出 Uvicorn、Starlette 與 FastAPI 之間的差異,請參考[效能評測](benchmarks.md)。
diff --git a/docs/zh-hant/docs/async.md b/docs/zh-hant/docs/async.md
new file mode 100644
index 0000000000000..9a08938ca5c0b
--- /dev/null
+++ b/docs/zh-hant/docs/async.md
@@ -0,0 +1,444 @@
+# 並行與 async / await { #concurrency-and-async-await }
+
+有關*路徑操作函式*的 `async def` 語法的細節與非同步 (asynchronous) 程式碼、並行 (concurrency) 與平行 (parallelism) 的一些背景知識。
+
+## 趕時間嗎? { #in-a-hurry }
+
+TL;DR:
+
+如果你正在使用要求你以 `await` 語法呼叫的第三方函式庫,例如:
+
+```Python
+results = await some_library()
+```
+
+然後,使用 `async def` 宣告你的*路徑操作函式*:
+
+
+```Python hl_lines="2"
+@app.get('/')
+async def read_results():
+ results = await some_library()
+ return results
+```
+
+/// note | 注意
+
+你只能在 `async def` 建立的函式內使用 `await`。
+
+///
+
+---
+
+如果你使用的是第三方函式庫並且它需要與某些外部資源(例如資料庫、API、檔案系統等)進行通訊,但不支援 `await`(目前大多數資料庫函式庫都是這樣),在這種情況下,你可以像平常一樣使用 `def` 宣告*路徑操作函式*,如下所示:
+
+```Python hl_lines="2"
+@app.get('/')
+def results():
+ results = some_library()
+ return results
+```
+
+---
+
+如果你的應用程式不需要與外部資源進行任何通訊並等待其回應,請使用 `async def`,即使內部不需要使用 `await` 也可以。
+
+---
+
+如果你不確定該用哪個,直接用 `def` 就好。
+
+---
+
+**注意**:你可以在*路徑操作函式*中混合使用 `def` 和 `async def` ,並使用最適合你需求的方式來定義每個函式。FastAPI 會幫你做正確的處理。
+
+無論如何,在上述哪種情況下,FastAPI 仍將以非同步方式運行,並且速度非常快。
+
+但透過遵循上述步驟,它將能進行一些效能最佳化。
+
+## 技術細節 { #technical-details }
+
+現代版本的 Python 支援使用 **「協程」** 的 **`async` 和 `await`** 語法來寫 **「非同步程式碼」**。
+
+接下來我們逐一介紹:
+
+* **非同步程式碼**
+* **`async` 和 `await`**
+* **協程**
+
+## 非同步程式碼 { #asynchronous-code }
+
+非同步程式碼僅意味著程式語言 💬 有辦法告訴電腦/程式 🤖 在程式碼中的某個點,它 🤖 需要等待某些事情完成。讓我們假設這些事情被稱為「慢速檔案」📝。
+
+因此,在等待「慢速檔案」📝 完成的這段時間,電腦可以去處理一些其他工作。
+
+接著程式 🤖 會在有空檔時回來查看是否有等待的工作已經完成,並執行必要的後續操作。
+
+接下來,它 🤖 完成第一個工作(例如我們的「慢速檔案」📝)並繼續執行相關的所有操作。
+這個「等待其他事情」通常指的是一些相對較慢的(與處理器和 RAM 記憶體的速度相比)的 I/O 操作,比如說:
+
+* 透過網路傳送來自用戶端的資料
+* 從網路接收來自用戶端的資料
+* 從磁碟讀取檔案內容
+* 將內容寫入磁碟
+* 遠端 API 操作
+* 資料庫操作
+* 資料庫查詢
+* 等等
+
+由於大部分的執行時間都消耗在等待 I/O 操作上,因此這些操作被稱為 "I/O 密集型" 操作。
+
+之所以稱為「非同步」,是因為電腦/程式不需要與那些耗時的任務「同步」,等待任務完成的精確時間,然後才能取得結果並繼續工作。
+
+相反地,非同步系統在任務完成後,可以讓任務稍微等一下(幾微秒),等待電腦/程式完成手頭上的其他工作,然後再回來取得結果繼續進行。
+
+相對於「非同步」(asynchronous),「同步」(synchronous)也常被稱作「順序性」(sequential),因為電腦/程式會依序執行所有步驟,即便這些步驟涉及等待,才會切換到其他任務。
+
+### 並行與漢堡 { #concurrency-and-burgers }
+
+上述非同步程式碼的概念有時也被稱為「並行」,它不同於「平行」。
+
+並行和平行都與 "不同的事情或多或少同時發生" 有關。
+
+但並行和平行之間的細節是完全不同的。
+
+為了理解差異,請想像以下有關漢堡的故事:
+
+### 並行漢堡 { #concurrent-burgers }
+
+你和你的戀人去速食店,排隊等候時,收銀員正在幫排在你前面的人點餐。😍
+
+
+
+輪到你了,你給你與你的戀人點了兩個豪華漢堡。🍔🍔
+
+
+
+收銀員通知廚房準備你的漢堡(儘管他們還在為前面其他顧客準備食物)。
+
+
+
+之後你完成付款。💸
+
+收銀員給你一個號碼牌。
+
+
+
+在等待漢堡的同時,你可以與戀人選一張桌子,然後坐下來聊很長一段時間(因為漢堡十分豪華,準備特別費工。)
+
+這段時間,你還能欣賞你的戀人有多麼的可愛、聰明與迷人。✨😍✨
+
+
+
+當你和戀人邊聊天邊等待時,你會不時地查看櫃檯上的顯示的號碼,確認是否已經輪到你了。
+
+然後在某個時刻,終於輪到你了。你走到櫃檯,拿了漢堡,然後回到桌子上。
+
+
+
+你和戀人享用這頓大餐,整個過程十分開心✨
+
+
+
+/// info
+
+漂亮的插畫來自 [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot)。 🎨
+
+///
+
+---
+
+想像你是故事中的電腦或程式 🤖。
+
+當你排隊時,你在放空😴,等待輪到你,沒有做任何「生產性」的事情。但這沒關係,因為收銀員只是接單(而不是準備食物),所以排隊速度很快。
+
+然後,當輪到你時,你開始做真正「有生產力」的工作,處理菜單,決定你想要什麼,替戀人選擇餐點,付款,確認你給了正確的帳單或信用卡,檢查你是否被正確收費,確認訂單中的項目是否正確等等。
+
+但是,即使你還沒有拿到漢堡,你與收銀員的工作已經「暫停」了 ⏸,因為你必須等待 🕙 漢堡準備好。
+
+但當你離開櫃檯,坐到桌子旁,拿著屬於你的號碼等待時,你可以把注意力 🔀 轉移到戀人身上,並開始「工作」⏯ 🤓——也就是和戀人調情 😍。這時你又開始做一些非常「有生產力」的事情。
+
+接著,收銀員 💁 將你的號碼顯示在櫃檯螢幕上,並告訴你「漢堡已經做好了」。但你不會瘋狂地立刻跳起來,因為顯示的號碼變成了你的。你知道沒有人會搶走你的漢堡,因為你有自己的號碼,他們也有他們的號碼。
+
+所以你會等戀人講完故事(完成當前的工作 ⏯/正在進行的任務 🤓),然後微笑著溫柔地說你要去拿漢堡了 ⏸。
+
+然後你走向櫃檯 🔀,回到已經完成的最初任務 ⏯,拿起漢堡,說聲謝謝,並帶回桌上。這就結束了與櫃檯的互動步驟/任務 ⏹,接下來會產生一個新的任務,「吃漢堡」 🔀 ⏯,而先前的「拿漢堡」任務已經完成了 ⏹。
+
+### 平行漢堡 { #parallel-burgers }
+
+現在,讓我們來想像這裡不是「並行漢堡」,而是「平行漢堡」。
+
+你和戀人一起去吃平行的速食餐。
+
+你們站在隊伍中,前面有幾位(假設有 8 位)既是收銀員又是廚師的員工,他們同時接單並準備餐點。
+
+所有排在你前面的人都在等著他們的漢堡準備好後才會離開櫃檯,因為每位收銀員在接完單後,馬上會去準備漢堡,然後才回來處理下一個訂單。
+
+
+
+終於輪到你了,你為你和你的戀人點了兩個非常豪華的漢堡。
+
+你付款了 💸。
+
+
+
+收銀員走進廚房準備食物。
+
+你站在櫃檯前等待 🕙,以免其他人先拿走你的漢堡,因為這裡沒有號碼牌系統。
+
+
+
+由於你和戀人都忙著不讓別人搶走你的漢堡,等漢堡準備好時,你根本無法專心和戀人互動。😞
+
+這是「同步」(synchronous)工作,你和收銀員/廚師 👨🍳 是「同步化」的。你必須等到 🕙 收銀員/廚師 👨🍳 完成漢堡並交給你的那一刻,否則別人可能會拿走你的餐點。
+
+
+
+最終,經過長時間的等待 🕙,收銀員/廚師 👨🍳 拿著漢堡回來了。
+
+
+
+你拿著漢堡,和你的戀人回到餐桌。
+
+你們僅僅是吃完漢堡,然後就結束了。⏹
+
+
+
+整個過程中沒有太多的談情說愛,因為大部分時間 🕙 都花在櫃檯前等待。😞
+
+/// info
+
+漂亮的插畫來自 [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot)。 🎨
+
+///
+
+---
+
+在這個平行漢堡的情境下,你是一個程式 🤖 且有兩個處理器(你和戀人),兩者都在等待 🕙 並專注於等待櫃檯上的餐點 🕙,等待的時間非常長。
+
+這家速食店有 8 個處理器(收銀員/廚師)。而並行漢堡店可能只有 2 個處理器(一位收銀員和一位廚師)。
+
+儘管如此,最終的體驗並不是最理想的。😞
+
+---
+
+這是與漢堡類似的故事。🍔
+
+一個更「現實」的例子,想像一間銀行。
+
+直到最近,大多數銀行都有多位出納員 👨💼👨💼👨💼👨💼,以及一條長長的隊伍 🕙🕙🕙🕙🕙🕙🕙🕙。
+
+所有的出納員都在一個接一個地滿足每位客戶的所有需求 👨💼⏯。
+
+你必須長時間排隊 🕙,不然就會失去機會。
+
+所以,你不會想帶你的戀人 😍 一起去銀行辦事 🏦。
+
+### 漢堡結論 { #burger-conclusion }
+
+在「和戀人一起吃速食漢堡」的這個場景中,由於有大量的等待 🕙,使用並行系統 ⏸🔀⏯ 更有意義。
+
+這也是大多數 Web 應用的情況。
+
+許多用戶正在使用你的應用程式,而你的伺服器則在等待 🕙 這些用戶不那麼穩定的網路來傳送請求。
+
+接著,再次等待 🕙 回應。
+
+這種「等待」 🕙 通常以微秒來衡量,但累加起來,最終還是花費了很多等待時間。
+
+這就是為什麼對於 Web API 來說,使用非同步程式碼 ⏸🔀⏯ 是非常有意味的。
+
+這種類型的非同步性正是 NodeJS 成功的原因(儘管 NodeJS 不是平行的),這也是 Go 語言作為程式語言的一個強大優勢。
+
+這與 **FastAPI** 所能提供的性能水平相同。
+
+你可以同時利用並行性和平行性,進一步提升效能,這比大多數已測試的 NodeJS 框架都更快,並且與 Go 語言相當,而 Go 是一種更接近 C 的編譯語言([感謝 Starlette](https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=query&l=zijmkf-1))。
+
+### 並行比平行更好嗎? { #is-concurrency-better-than-parallelism }
+
+不是的!這不是故事的本意。
+
+並行與平行不同。並行在某些 **特定** 的需要大量等待的情境下表現更好。正因如此,並行在 Web 應用程式開發中通常比平行更有優勢。但並不是所有情境都如此。
+
+因此,為了平衡報導,想像下面這個短故事
+
+> 你需要打掃一間又大又髒的房子。
+
+*是的,這就是全部的故事。*
+
+---
+
+這裡沒有任何需要等待 🕙 的地方,只需要在房子的多個地方進行大量的工作。
+
+你可以像漢堡的例子那樣輪流進行,先打掃客廳,再打掃廚房,但由於你不需要等待 🕙 任何事情,只需要持續地打掃,輪流並不會影響任何結果。
+
+無論輪流執行與否(並行),你都需要相同的工時完成任務,同時需要執行相同工作量。
+
+但是,在這種情境下,如果你可以邀請8位前收銀員/廚師(現在是清潔工)來幫忙,每個人(加上你)負責房子的某個區域,這樣你就可以 **平行** 地更快完成工作。
+
+在這個場景中,每個清潔工(包括你)都是一個處理器,完成工作的一部分。
+
+由於大多數的執行時間都花在實際的工作上(而不是等待),而電腦中的工作由 CPU 完成,因此這些問題被稱為「CPU 密集型」。
+
+---
+
+常見的 CPU 密集型操作範例包括那些需要進行複雜數學計算的任務。
+
+例如:
+
+* **音訊**或**圖像處理**;
+* **電腦視覺**:一張圖片由數百萬個像素組成,每個像素有 3 個值/顏色,處理這些像素通常需要同時進行大量計算;
+* **機器學習**: 通常需要大量的「矩陣」和「向量」運算。想像一個包含數字的巨大電子表格,並所有的數字同時相乘;
+* **深度學習**: 這是機器學習的子領域,同樣適用。只不過這不僅僅是一張數字表格,而是大量的數據集合,並且在很多情況下,你會使用特殊的處理器來構建或使用這些模型。
+
+### 並行 + 平行: Web + 機器學習 { #concurrency-parallelism-web-machine-learning }
+
+使用 **FastAPI**,你可以利用並行的優勢,這在 Web 開發中非常常見(這也是 NodeJS 的最大吸引力)。
+
+但你也可以利用平行與多行程 (multiprocessing)(讓多個行程同時運行) 的優勢來處理機器學習系統中的 **CPU 密集型**工作。
+
+這一點,再加上 Python 是 **資料科學**、機器學習,尤其是深度學習的主要語言,讓 **FastAPI** 成為資料科學/機器學習 Web API 和應用程式(以及許多其他應用程式)的絕佳選擇。
+
+想了解如何在生產環境中實現這種平行性,請參見 [部屬](deployment/index.md)。
+
+## `async` 和 `await` { #async-and-await }
+
+現代 Python 版本提供一種非常直觀的方式定義非同步程式碼。這使得它看起來就像正常的「順序」程式碼,並在適當的時機替你「等待」。
+
+當某個操作需要等待才能回傳結果,並且支援這些新的 Python 特性時,你可以像這樣編寫程式碼:
+
+```Python
+burgers = await get_burgers(2)
+```
+
+這裡的關鍵是 `await`。它告訴 Python 必須等待 ⏸ `get_burgers(2)` 完成它的工作 🕙, 然後將結果儲存在 `burgers` 中。如此,Python 就可以在此期間去處理其他事情 🔀 ⏯ (例如接收另一個請求)。
+
+要讓 `await` 運作,它必須位於支持非同步功能的函式內。為此,只需使用 `async def` 宣告函式:
+
+```Python hl_lines="1"
+async def get_burgers(number: int):
+ # Do some asynchronous stuff to create the burgers
+ return burgers
+```
+
+...而不是 `def`:
+
+```Python hl_lines="2"
+# This is not asynchronous
+def get_sequential_burgers(number: int):
+ # Do some sequential stuff to create the burgers
+ return burgers
+```
+
+使用 `async def`,Python 知道在該函式內需要注意 `await`,並且它可以「暫停」 ⏸ 執行該函式,然後執行其他任務 🔀 後回來。
+
+當你想要呼叫 `async def` 函式時,必須使用「await」。因此,這樣寫將無法運行:
+
+```Python
+# This won't work, because get_burgers was defined with: async def
+burgers = get_burgers(2)
+```
+
+---
+
+如果你正在使用某個函式庫,它告訴你可以使用 `await` 呼叫它,那麼你需要用 `async def` 定義*路徑操作函式*,如:
+
+```Python hl_lines="2-3"
+@app.get('/burgers')
+async def read_burgers():
+ burgers = await get_burgers(2)
+ return burgers
+```
+
+### 更多技術細節 { #more-technical-details }
+
+你可能已經注意到,`await` 只能在 `async def` 定義的函式內使用。
+
+但同時,使用 `async def` 定義的函式本身也必須被「等待」。所以,帶有 `async def` 的函式只能在其他使用 `async def` 定義的函式內呼叫。
+
+那麼,這就像「先有雞還是先有蛋」的問題,要如何呼叫第一個 `async` 函式呢?
+
+如果你使用 FastAPI,無需擔心這個問題,因為「第一個」函式將是你的*路徑操作函式*,FastAPI 會知道如何正確處理這個問題。
+
+但如果你想在沒有 FastAPI 的情況下使用 `async` / `await`,你也可以這樣做。
+
+### 編寫自己的非同步程式碼 { #write-your-own-async-code }
+
+Starlette(和 **FastAPI**)是基於 [AnyIO](https://anyio.readthedocs.io/en/stable/) 實作的,這使得它們與 Python 標準函式庫 [asyncio](https://docs.python.org/3/library/asyncio-task.html) 和 [Trio](https://trio.readthedocs.io/en/stable/) 相容。
+
+特別是,你可以直接使用 [AnyIO](https://anyio.readthedocs.io/en/stable/) 來處理更複雜的並行使用案例,這些案例需要你在自己的程式碼中使用更高階的模式。
+
+即使你不使用 **FastAPI**,你也可以使用 [AnyIO](https://anyio.readthedocs.io/en/stable/) 來撰寫自己的非同步應用程式,並獲得高相容性及一些好處(例如「結構化並行」)。
+
+我另外在 AnyIO 之上做了一個薄封裝的函式庫,稍微改進型別註解以獲得更好的**自動補全**、**即時錯誤**等。同時它也提供友善的介紹與教學,幫助你**理解**並撰寫**自己的非同步程式碼**:[Asyncer](https://asyncer.tiangolo.com/)。當你需要**將非同步程式碼與一般**(阻塞/同步)**程式碼整合**時,它特別實用。
+
+### 其他形式的非同步程式碼 { #other-forms-of-asynchronous-code }
+
+使用 `async` 和 `await` 的風格在語言中相對較新。
+
+但它使處理非同步程式碼變得更加容易。
+
+相同的語法(或幾乎相同的語法)最近也被包含在現代 JavaScript(無論是瀏覽器還是 NodeJS)中。
+
+但在此之前,處理非同步程式碼要更加複雜和困難。
+
+在較舊的 Python 版本中,你可能會使用多執行緒或 [Gevent](https://www.gevent.org/)。但這些程式碼要更難以理解、調試和思考。
+
+在較舊的 NodeJS / 瀏覽器 JavaScript 中,你會使用「回呼」,這可能會導致“回呼地獄”。
+
+## 協程 { #coroutines }
+
+「協程」只是 `async def` 函式所回傳的非常特殊的事物名稱。Python 知道它是一個類似函式的東西,可以啟動它,並且在某個時刻它會結束,但它也可能在內部暫停 ⏸,只要遇到 `await`。
+
+這種使用 `async` 和 `await` 的非同步程式碼功能通常被概括為「協程」。這與 Go 語言的主要特性「Goroutines」相似。
+
+## 結論 { #conclusion }
+
+讓我們再次回顧之前的句子:
+
+> 現代版本的 Python 支持使用 **"協程"** 的 **`async` 和 `await`** 語法來寫 **"非同步程式碼"**。
+
+現在應該能明白其含意了。✨
+
+這些就是驅動 FastAPI(透過 Starlette)運作的原理,也讓它擁有如此驚人的效能。
+
+## 非常技術性的細節 { #very-technical-details }
+
+/// warning
+
+你大概可以跳過這段。
+
+這裡是有關 FastAPI 內部技術細節。
+
+如果你有相當多的技術背景(例如協程、執行緒、阻塞等),並且對 FastAPI 如何處理 `async def` 與常規 `def` 感到好奇,請繼續閱讀。
+
+///
+
+### 路徑操作函式 { #path-operation-functions }
+
+當你使用 `def` 而不是 `async def` 宣告*路徑操作函式*時,該函式會在外部的執行緒池(threadpool)中執行,然後等待結果,而不是直接呼叫(因為這樣會阻塞伺服器)。
+
+如果你來自於其他不以這種方式運作的非同步框架,而且你習慣於使用普通的 `def` 定義僅進行簡單計算的*路徑操作函式*,目的是獲得微小的性能增益(大約 100 奈秒),請注意,在 FastAPI 中,效果會完全相反。在這些情況下,最好使用 `async def`,除非你的*路徑操作函式*執行阻塞的 I/O 的程式碼。
+
+不過,在這兩種情況下,**FastAPI** [仍然很快](index.md#performance),至少與你之前的框架相當(或者更快)。
+
+### 依賴項(Dependencies) { #dependencies }
+
+同樣適用於[依賴項](tutorial/dependencies/index.md)。如果依賴項是一個標準的 `def` 函式,而不是 `async def`,那麼它在外部的執行緒池被運行。
+
+### 子依賴項 { #sub-dependencies }
+
+你可以擁有多個相互依賴的依賴項和[子依賴項](tutorial/dependencies/sub-dependencies.md)(作為函式定義的參數),其中一些可能是用 `async def` 宣告,也可能是用 `def` 宣告。它們仍然可以正常運作,用 `def` 定義的那些將會在外部的執行緒中呼叫(來自執行緒池),而不是被「等待」。
+
+### 其他輔助函式 { #other-utility-functions }
+
+你可以直接呼叫任何使用 `def` 或 `async def` 建立的其他輔助函式,FastAPI 不會影響你呼叫它們的方式。
+
+這與 FastAPI 為你呼叫*路徑操作函式*和依賴項的邏輯有所不同。
+
+如果你的輔助函式是用 `def` 宣告的,它將會被直接呼叫(按照你在程式碼中撰寫的方式),而不是在執行緒池中。如果該函式是用 `async def` 宣告,那麼你在呼叫時應該使用 `await` 等待其結果。
+
+---
+
+再一次強調,這些都是非常技術性的細節,如果你特地在尋找這些資訊,這些內容可能會對你有幫助。
+
+否則,只需遵循上面提到的指引即可:趕時間嗎?。
diff --git a/docs/zh-hant/docs/benchmarks.md b/docs/zh-hant/docs/benchmarks.md
new file mode 100644
index 0000000000000..2b5b3f7ee1a90
--- /dev/null
+++ b/docs/zh-hant/docs/benchmarks.md
@@ -0,0 +1,34 @@
+# 基準測試 { #benchmarks }
+
+由第三方機構 TechEmpower 的基準測試表明在 Uvicorn 下運行的 **FastAPI** 應用程式是 [最快的 Python 可用框架之一](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7),僅次於 Starlette 和 Uvicorn 本身(於 FastAPI 內部使用)。
+
+但是在查看基準得分和對比時,請注意以下幾點。
+
+## 基準測試和速度 { #benchmarks-and-speed }
+
+當你查看基準測試時,常見到不同類型的多個工具被視為等同來比較。
+
+具體來說,是將 Uvicorn、Starlette 和 FastAPI 同時進行比較(以及許多其他工具)。
+
+該工具解決的問題越簡單,其效能就越好。而且大多數基準測試不會測試該工具提供的附加功能。
+
+層次結構如下:
+
+* **Uvicorn**:ASGI 伺服器
+ * **Starlette**:(使用 Uvicorn)一個網頁微框架
+ * **FastAPI**:(使用 Starlette)一個 API 微框架,具有用於建立 API 的多個附加功能、資料驗證等。
+
+* **Uvicorn**:
+ * 具有最佳效能,因為除了伺服器本身之外,它沒有太多額外的程式碼。
+ * 你不會直接在 Uvicorn 中編寫應用程式。這意味著你的程式碼必須或多或少地包含 Starlette(或 **FastAPI**)提供的所有程式碼。如果你這樣做,你的最終應用程式將具有與使用框架相同的開銷,且無法像使用框架那樣減少應用程式程式碼與錯誤。
+ * 如果你要比較 Uvicorn,請將其與 Daphne、Hypercorn、uWSGI 等應用程式伺服器進行比較。
+* **Starlette**:
+ * 繼 Uvicorn 之後的次佳表現。事實上,Starlette 使用 Uvicorn 來運行。因此它將可能只透過執行更多程式碼而變得比 Uvicorn「慢」。
+ * 但它為你提供了建立簡單網頁應用程式的工具,以及基於路徑的路由等。
+ * 如果你要比較 Starlette,請將其與 Sanic、Flask、Django 等網頁框架(或微框架)進行比較。
+* **FastAPI**:
+ * 就像 Starlette 使用 Uvicorn 並不能比它更快一樣, **FastAPI** 使用 Starlette,所以它不能比它更快。
+ * FastAPI 在 Starlette 基礎之上提供了更多功能。包含建構 API 時所需要的功能,例如資料驗證和序列化。FastAPI 可以幫助你自動產生 API 文件,(應用程式啟動時將會自動生成文件,所以不會增加應用程式運行時的開銷)。
+ * 如果你沒有使用 FastAPI 而是直接使用 Starlette(或其他工具,如 Sanic、Flask、Responder 等),你將必須自行實現所有資料驗證和序列化。因此,你的最終應用程式仍然具有與使用 FastAPI 建置相同的開銷。在許多情況下,這種資料驗證和序列化是應用程式中編寫最大量的程式碼。
+ * 因此透過使用 FastAPI,你可以節省開發時間、錯誤與程式碼數量,並且相比不使用 FastAPI 你很大可能會獲得相同或更好的效能(因為那樣你必須在程式碼中實現所有相同的功能)。
+ * 如果你要與 FastAPI 比較,請將其與能夠提供資料驗證、序列化和文件的網頁應用程式框架(或工具集)進行比較,例如 Flask-apispec、NestJS、Molten 等框架。具備整合式自動資料驗證、序列化與文件的框架。
diff --git a/docs/zh-hant/docs/deployment/cloud.md b/docs/zh-hant/docs/deployment/cloud.md
new file mode 100644
index 0000000000000..86d216ca6f43d
--- /dev/null
+++ b/docs/zh-hant/docs/deployment/cloud.md
@@ -0,0 +1,24 @@
+# 在雲端供應商上部署 FastAPI { #deploy-fastapi-on-cloud-providers }
+
+你幾乎可以使用**任何雲端供應商**來部署你的 FastAPI 應用程式。
+
+在大多數情況下,主要的雲端供應商都有部署 FastAPI 的指南。
+
+## FastAPI Cloud { #fastapi-cloud }
+
+**[FastAPI Cloud](https://fastapicloud.com)** 由 **FastAPI** 的同一位作者與團隊打造。
+
+它讓你以最少的投入,簡化 **建置**、**部署** 與 **存取** API 的流程。
+
+它把使用 FastAPI 開發應用的同樣**優秀的開發者體驗**,帶到將它們**部署**到雲端的過程中。🎉
+
+FastAPI Cloud 是 *FastAPI and friends* 開源專案的主要贊助與資金提供者。✨
+
+## 雲端供應商 - 贊助商 { #cloud-providers-sponsors }
+
+其他一些雲端供應商也會 ✨ [**贊助 FastAPI**](../help-fastapi.md#sponsor-the-author) ✨。🙇
+
+你也可以參考他們的指南並試用其服務:
+
+* [Render](https://docs.render.com/deploy-fastapi?utm_source=deploydoc&utm_medium=referral&utm_campaign=fastapi)
+* [Railway](https://docs.railway.com/guides/fastapi?utm_medium=integration&utm_source=docs&utm_campaign=fastapi)
diff --git a/docs/zh-hant/docs/deployment/concepts.md b/docs/zh-hant/docs/deployment/concepts.md
new file mode 100644
index 0000000000000..0b8677bfd339b
--- /dev/null
+++ b/docs/zh-hant/docs/deployment/concepts.md
@@ -0,0 +1,321 @@
+# 部署概念 { #deployments-concepts }
+
+當你要部署一個 FastAPI 應用,或其實任何類型的 Web API 時,有幾個你可能在意的概念。掌握這些概念後,你就能找出最適合部署你應用的方式。
+
+一些重要的概念包括:
+
+- 安全性 - HTTPS
+- 開機自動執行
+- 重新啟動
+- 複本(執行中的行程數量)
+- 記憶體
+- 啟動前的前置步驟
+
+我們將看看它們如何影響部署。
+
+最終目標是能夠以安全、避免中斷,並盡可能高效使用運算資源(例如遠端伺服器/虛擬機)的方式來服務你的 API 用戶端。🚀
+
+我會在這裡多介紹一些這些觀念,希望能幫你建立必要的直覺,讓你能在非常不同、甚至尚未出現的未來環境中決定要如何部署你的 API。
+
+在思考這些概念之後,你將能夠評估與設計最適合部署你自己 API 的方式。
+
+在接下來的章節,我會提供更具體的部署 FastAPI 應用的食譜。
+
+但現在,先來看看這些重要的概念想法。這些概念同樣適用於任何其他類型的 Web API。💡
+
+## 安全性 - HTTPS { #security-https }
+
+在[前一章關於 HTTPS](https.md) 中,我們學到 HTTPS 如何為你的 API 提供加密。
+
+我們也看到,HTTPS 通常由應用伺服器外部的元件提供,即 TLS Termination Proxy。
+
+而且必須有某個東西負責續期 HTTPS 憑證,可能是同一個元件,也可能是不同的東西。
+
+### HTTPS 工具範例 { #example-tools-for-https }
+
+你可以用來作為 TLS Termination Proxy 的工具包括:
+
+- Traefik
+ - 自動處理憑證續期 ✨
+- Caddy
+ - 自動處理憑證續期 ✨
+- Nginx
+ - 搭配像 Certbot 這類外部元件進行憑證續期
+- HAProxy
+ - 搭配像 Certbot 這類外部元件進行憑證續期
+- Kubernetes,使用如 Nginx 的 Ingress Controller
+ - 搭配像 cert-manager 這類外部元件進行憑證續期
+- 由雲端供應商在其服務內部處理(見下文 👇)
+
+另一個選項是使用能幫你做更多事情的雲端服務(包含設定 HTTPS)。它可能有一些限制或要額外付費等。但在那種情況下,你就不必自己設定 TLS Termination Proxy。
+
+我會在後續章節展示一些具體例子。
+
+---
+
+接下來要考慮的概念都與實際執行你的 API 的程式(例如 Uvicorn)有關。
+
+## 程式與行程 { #program-and-process }
+
+我們會常提到執行中的「行程(process)」,因此先釐清它的意思,以及與「程式(program)」的差異很有幫助。
+
+### 什麼是程式 { #what-is-a-program }
+
+「程式(program)」一詞常用來描述許多東西:
+
+- 你寫的原始碼,也就是 Python 檔案。
+- 可由作業系統執行的檔案,例如:`python`、`python.exe` 或 `uvicorn`。
+- 在作業系統上執行中的特定程式,使用 CPU 並將資料存於記憶體。這也稱為「行程」。
+
+### 什麼是行程 { #what-is-a-process }
+
+「行程(process)」通常以更特定的方式使用,只指作業系統中正在執行的東西(如上面最後一點):
+
+- 在作業系統上「執行中」的特定程式。
+ - 這不是指檔案或原始碼,而是特指正在被作業系統執行並管理的那個東西。
+- 任何程式、任何程式碼,只有在「被執行」時才能做事。所以,當有「行程在執行」時才能運作。
+- 行程可以被你或作業系統終止(kill)。此時它就停止執行,無法再做任何事。
+- 你電腦上執行的每個應用程式、每個視窗等,背後都有一些行程。而且在電腦開機時,通常會同時有許多行程在跑。
+- 同一個程式可以同時有多個行程在執行。
+
+如果你打開作業系統的「工作管理員」或「系統監控器」(或類似工具),就能看到許多正在執行的行程。
+
+例如,你大概會看到同一個瀏覽器(Firefox、Chrome、Edge 等)會有多個行程在執行。它們通常每個分頁一個行程,外加其他一些額外行程。
+
+
+
+---
+
+現在我們知道「行程」與「程式」的差異了,繼續談部署。
+
+## 開機自動執行 { #running-on-startup }
+
+多數情況下,當你建立一個 Web API,你會希望它「一直在執行」,不中斷,讓客戶端隨時可用。除非你有特定理由只在某些情況下才執行,但大部分時候你會希望它持續運作並且可用。
+
+### 在遠端伺服器上 { #in-a-remote-server }
+
+當你設定一台遠端伺服器(雲端伺服器、虛擬機等),最簡單的作法就是像本機開發時一樣,手動使用 `fastapi run`(它使用 Uvicorn)或類似的方式。
+
+這在「開發期間」會運作良好而且有用。
+
+但如果你與伺服器的連線中斷,正在執行的行程很可能會死掉。
+
+而如果伺服器被重新啟動(例如更新後、或雲端供應商進行遷移),你大概「不會注意到」。因此你甚至不知道要手動重啟行程。你的 API 就會一直掛著。😱
+
+### 開機自動啟動 { #run-automatically-on-startup }
+
+通常你會希望伺服器程式(例如 Uvicorn)在伺服器開機時自動啟動,且不需任何「人工介入」,讓你的 API(例如 Uvicorn 執行你的 FastAPI 應用)總是有行程在跑。
+
+### 獨立程式 { #separate-program }
+
+為了達成這點,你通常會有一個「獨立的程式」來確保你的應用在開機時會被啟動。很多情況下,它也會確保其他元件或應用一併啟動,例如資料庫。
+
+### 開機自動啟動的工具範例 { #example-tools-to-run-at-startup }
+
+能做到這件事的工具包括:
+
+- Docker
+- Kubernetes
+- Docker Compose
+- Docker 的 Swarm 模式
+- Systemd
+- Supervisor
+- 由雲端供應商在其服務內部處理
+- 其他...
+
+我會在後續章節給出更具體的例子。
+
+## 重新啟動 { #restarts }
+
+和確保你的應用在開機時會執行一樣,你大概也會希望在發生失敗之後,它能「自動重新啟動」。
+
+### 人都會犯錯 { #we-make-mistakes }
+
+我們身為人,常常會犯錯。軟體幾乎總是有藏在各處的「臭蟲(bugs)」🐛
+
+而我們開發者會在發現這些 bug 後持續改進程式碼、實作新功能(也可能順便加進新的 bug 😅)。
+
+### 小錯誤自動處理 { #small-errors-automatically-handled }
+
+使用 FastAPI 建構 Web API 時,如果我們的程式碼出錯,FastAPI 通常會把它限制在觸發該錯誤的單次請求之中。🛡
+
+用戶端會收到「500 Internal Server Error」,但應用會繼續處理之後的請求,而不是整個崩潰。
+
+### 更嚴重的錯誤 - 當機 { #bigger-errors-crashes }
+
+然而,仍可能有一些情況,我們寫的程式碼「讓整個應用當機」,使 Uvicorn 與 Python 都崩潰。💥
+
+即便如此,你大概也不會希望應用因為某處錯誤就一直處於死亡狀態,你可能會希望它「繼續運作」,至少讓沒有壞掉的「路徑操作(path operations)」能持續服務。
+
+### 當機後重新啟動 { #restart-after-crash }
+
+在這些會讓「執行中行程」整個崩潰的嚴重錯誤案例裡,你會希望有個外部元件負責「重新啟動」該行程,至少嘗試幾次...
+
+/// tip
+
+...不過,如果整個應用「一啟動就立刻」崩潰,那持續無止境地重啟大概沒有意義。但在這類情況下,你很可能會在開發過程中就發現,或至少在部署後馬上注意到。
+
+所以讓我們專注在主要情境:應用在未來某些特定案例中可能會整體崩潰,但此時重新啟動仍然是有意義的。
+
+///
+
+你大概會希望把負責重新啟動應用的東西放在「外部元件」,因為那個時候,應用本身連同 Uvicorn 與 Python 都已經掛了,在同一個應用的程式碼裡也無法做什麼。
+
+### 自動重新啟動的工具範例 { #example-tools-to-restart-automatically }
+
+多數情況下,用來「在開機時啟動程式」的同一套工具,也會負責處理自動「重新啟動」。
+
+例如,可以由下列工具處理:
+
+- Docker
+- Kubernetes
+- Docker Compose
+- Docker 的 Swarm 模式
+- Systemd
+- Supervisor
+- 由雲端供應商在其服務內部處理
+- 其他...
+
+## 複本:行程與記憶體 { #replication-processes-and-memory }
+
+在 FastAPI 應用中,使用像 `fastapi` 指令(執行 Uvicorn)的伺服器程式,即使只在「一個行程」中執行,也能同時服務多個客戶端。
+
+但很多情況下,你會想同時執行多個工作行程(workers)。
+
+### 多個行程 - Workers { #multiple-processes-workers }
+
+如果你的客戶端比單一行程所能處理的更多(例如虛擬機規格不大),而伺服器 CPU 有「多核心」,那你可以同時執行「多個行程」載入相同的應用,並把所有請求分散給它們。
+
+當你執行同一個 API 程式的「多個行程」時,通常稱為「workers(工作行程)」。
+
+### 工作行程與連接埠 { #worker-processes-and-ports }
+
+還記得文件中[關於 HTTPS](https.md) 的說明嗎:在一台伺服器上,一組 IP 與連接埠的組合只能由「一個行程」監聽?
+
+這裡同樣適用。
+
+因此,若要同時擁有「多個行程」,就必須有「單一行程」在該連接埠上監聽,然後以某種方式把通信傳遞給各個工作行程。
+
+### 每個行程的記憶體 { #memory-per-process }
+
+當程式把東西載入記憶體時,例如把機器學習模型存到變數中,或把大型檔案內容讀到變數中,這些都會「消耗一些伺服器的記憶體(RAM)」。
+
+而多個行程通常「不共享記憶體」。這表示每個執行中的行程都有自己的東西、變數與記憶體。如果你的程式碼會用掉大量記憶體,「每個行程」都會消耗等量的記憶體。
+
+### 伺服器記憶體 { #server-memory }
+
+例如,如果你的程式碼載入一個「1 GB 大小」的機器學習模型,當你用一個行程執行你的 API,它就會至少吃掉 1 GB 的 RAM。若你啟動「4 個行程」(4 個 workers),每個會吃 1 GB RAM。總計你的 API 會吃掉「4 GB RAM」。
+
+如果你的遠端伺服器或虛擬機只有 3 GB RAM,嘗試載入超過 4 GB 的 RAM 就會出問題。🚨
+
+### 多個行程 - 範例 { #multiple-processes-an-example }
+
+在這個例子中,有一個「管理行程(Manager Process)」會啟動並控制兩個「工作行程(Worker Processes)」。
+
+這個管理行程大概就是在 IP 的「連接埠」上監聽的那個。它會把所有通信轉發到各個工作行程。
+
+那些工作行程才是實際執行你的應用的,它們會完成主要的計算,接收「請求」並回傳「回應」,也會把你放在變數中的東西載入 RAM。
+
++ +若沒有他人的前期成果,就不會有 **FastAPI**。 + +先前已有許多工具啟發了它的誕生。 + +我曾經多年避免再去打造一個新框架。起初我嘗試用各種不同的框架、外掛與工具,來滿足 **FastAPI** 涵蓋的所有功能。 + +但在某個時刻,別無選擇,只能打造一個同時提供所有這些功能的東西,取過去工具之長,並以可能的最佳方式加以結合,還運用了以往甚至不存在的語言功能(Python 3.6+ 的型別提示)。 + ++ +## 調研 { #investigation } + +透過實際使用這些替代方案,我得以向它們學習、汲取想法,並以我能為自己與合作開發團隊找到的最佳方式加以整合。 + +例如,很清楚理想上應以標準的 Python 型別提示為基礎。 + +同時,最佳做法就是採用現有標準。 + +因此,在開始撰寫 **FastAPI** 之前,我花了好幾個月研究 OpenAPI、JSON Schema、OAuth2 等規範,了解它們之間的關係、重疊與差異。 + +## 設計 { #design } + +接著,我花時間設計作為使用者(作為使用 FastAPI 的開發者)時希望擁有的開發者「API」。 + +我在最受歡迎的 Python 編輯器中測試了多個想法:PyCharm、VS Code、基於 Jedi 的編輯器。 + +根據最新的 [Python 開發者調查](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools),這些工具涵蓋約 80% 的使用者。 + +這表示 **FastAPI** 已針對 80% 的 Python 開發者所使用的編輯器進行過專門測試。而由於其他多數編輯器的行為也類似,這些優點擴及實際上幾乎所有編輯器。 + +藉此我找到了盡可能減少程式碼重複、在各處提供自動補全、型別與錯誤檢查等的最佳方式。 + +一切都是為了讓所有開發者都能擁有最佳的開發體驗。 + +## 需求 { #requirements } + +在測試多種替代方案後,我決定採用 [**Pydantic**](https://docs.pydantic.dev/),因為它的優勢。 + +隨後我也對它做出貢獻,使其完全符合 JSON Schema、支援以不同方式定義約束,並依據在多款編輯器中的測試結果改進編輯器支援(型別檢查、自動補全)。 + +在開發過程中,我也對 [**Starlette**](https://www.starlette.dev/)(另一個關鍵依賴)做出貢獻。 + +## 開發 { #development } + +當我開始著手實作 **FastAPI** 本身時,多數拼圖已經就緒,設計已定,需求與工具已備齊,對各項標準與規範的理解也清晰且新鮮。 + +## 未來 { #future } + +到目前為止,**FastAPI** 及其理念已經對許多人有幫助。 + +相較先前的替代方案,它更適合許多使用情境,因而被選用。 + +許多開發者與團隊(包括我和我的團隊)已經在他們的專案中依賴 **FastAPI**。 + +但仍有許多改進與功能即將到來。 + +**FastAPI** 的前景非常光明。 + +也非常感謝[你的幫助](help-fastapi.md)。 diff --git a/docs/zh-hant/docs/how-to/authentication-error-status-code.md b/docs/zh-hant/docs/how-to/authentication-error-status-code.md new file mode 100644 index 0000000000000..beea430707174 --- /dev/null +++ b/docs/zh-hant/docs/how-to/authentication-error-status-code.md @@ -0,0 +1,15 @@ +# 使用舊的 403 身分驗證錯誤狀態碼 { #use-old-403-authentication-error-status-codes } + +在 FastAPI 版本 `0.122.0` 之前,當內建的安全工具在身分驗證失敗後回傳錯誤給用戶端時,會使用 HTTP 狀態碼 `403 Forbidden`。 + +從 FastAPI 版本 `0.122.0` 起,改為使用更合適的 HTTP 狀態碼 `401 Unauthorized`,並在回應中依據 HTTP 規範加上合理的 `WWW-Authenticate` 標頭,參考 [RFC 7235](https://datatracker.ietf.org/doc/html/rfc7235#section-3.1)、[RFC 9110](https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized)。 + +但如果你的用戶端因某些原因依賴於舊行為,你可以在你的 security 類別中覆寫 `make_not_authenticated_error` 方法以恢復舊的行為。 + +例如,你可以建立 `HTTPBearer` 的子類別,讓它回傳 `403 Forbidden` 錯誤,而不是預設的 `401 Unauthorized` 錯誤: + +{* ../../docs_src/authentication_error_status_code/tutorial001_an_py310.py hl[9:13] *} + +/// tip +注意這個函式回傳的是例外物件本身,而不是直接拋出它。拋出的動作會在其餘的內部程式碼中處理。 +/// diff --git a/docs/zh-hant/docs/how-to/conditional-openapi.md b/docs/zh-hant/docs/how-to/conditional-openapi.md new file mode 100644 index 0000000000000..485a7d11d72c7 --- /dev/null +++ b/docs/zh-hant/docs/how-to/conditional-openapi.md @@ -0,0 +1,56 @@ +# 條件式 OpenAPI { #conditional-openapi } + +如果需要,你可以用設定與環境變數,依據執行環境有條件地調整 OpenAPI,甚至完全停用它。 + +## 關於安全性、API 與文件 { #about-security-apis-and-docs } + +在正式環境中隱藏文件 UI *不應該* 是用來保護 API 的方式。 + +這並不會為你的 API 增添任何額外的安全性,*路徑操作* 仍舊照常可用。 + +若你的程式碼有安全性缺陷,它依然會存在。 + +隱藏文件只會讓他人更難理解如何與你的 API 互動,也可能讓你在正式環境除錯更困難。這通常僅被視為一種 [以隱匿求安全](https://en.wikipedia.org/wiki/Security_through_obscurity)。 + +如果你想保護 API,有許多更好的作法,例如: + +- 確保針對請求本文與回應,具備定義良好的 Pydantic 模型。 +- 透過依賴設定所需的權限與角色。 +- 切勿儲存明文密碼,只儲存密碼雜湊。 +- 實作並使用成熟且廣為人知的密碼學工具,例如 pwdlib 與 JWT 權杖等。 +- 視需要以 OAuth2 scopes 新增更細緻的權限控管。 +- ...等。 + +儘管如此,在某些特定情境下,你可能確實需要在某些環境(例如正式環境)停用 API 文件,或依據環境變數的設定來決定是否啟用。 + +## 透過設定與環境變數的條件式 OpenAPI { #conditional-openapi-from-settings-and-env-vars } + +你可以用相同的 Pydantic 設定,來配置產生的 OpenAPI 與文件 UI。 + +例如: + +{* ../../docs_src/conditional_openapi/tutorial001_py310.py hl[6,11] *} + +這裡我們宣告 `openapi_url` 設定,預設值同樣是 `"/openapi.json"`。 + +接著在建立 `FastAPI` 應用時使用它。 + +然後你可以將環境變數 `OPENAPI_URL` 設為空字串,以停用 OpenAPI(包含文件 UI),如下: + +
+
+但你可以將 `syntaxHighlight` 設為 `False` 來停用它:
+
+{* ../../docs_src/configure_swagger_ui/tutorial001_py310.py hl[3] *}
+
+...然後 Swagger UI 就不會再顯示語法醒目提示:
+
+
+
+## 更換主題 { #change-the-theme }
+
+同樣地,你可以用鍵 `"syntaxHighlight.theme"` 設定語法醒目提示主題(注意中間有一個點):
+
+{* ../../docs_src/configure_swagger_ui/tutorial002_py310.py hl[3] *}
+
+這個設定會變更語法醒目提示的配色主題:
+
+
+
+## 更改預設的 Swagger UI 參數 { #change-default-swagger-ui-parameters }
+
+FastAPI 內建一些預設參數,適用於大多數情境。
+
+包含以下預設設定:
+
+{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}
+
+你可以在 `swagger_ui_parameters` 參數中提供不同的值來覆蓋其中任一項。
+
+例如,要停用 `deepLinking`,可以在 `swagger_ui_parameters` 傳入以下設定:
+
+{* ../../docs_src/configure_swagger_ui/tutorial003_py310.py hl[3] *}
+
+## 其他 Swagger UI 參數 { #other-swagger-ui-parameters }
+
+若要查看所有可用的設定,請參考官方的 [Swagger UI 參數文件](https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/)。
+
+## 僅限 JavaScript 的設定 { #javascript-only-settings }
+
+Swagger UI 也允許某些設定是**僅限 JavaScript** 的物件(例如 JavaScript 函式)。
+
+FastAPI 也包含以下僅限 JavaScript 的 `presets` 設定:
+
+```JavaScript
+presets: [
+ SwaggerUIBundle.presets.apis,
+ SwaggerUIBundle.SwaggerUIStandalonePreset
+]
+```
+
+這些是 JavaScript 物件,而不是字串,因此無法直接從 Python 程式碼傳遞。
+
+若需要使用這類僅限 JavaScript 的設定,你可以使用上面介紹的方法:覆寫所有 Swagger UI 的路徑操作(path operation),並手動撰寫所需的 JavaScript。
diff --git a/docs/zh-hant/docs/how-to/custom-docs-ui-assets.md b/docs/zh-hant/docs/how-to/custom-docs-ui-assets.md
new file mode 100644
index 0000000000000..e690e55c96189
--- /dev/null
+++ b/docs/zh-hant/docs/how-to/custom-docs-ui-assets.md
@@ -0,0 +1,185 @@
+# 自訂文件 UI 靜態資源(自我託管) { #custom-docs-ui-static-assets-self-hosting }
+
+API 文件使用 Swagger UI 與 ReDoc,它們各自需要一些 JavaScript 與 CSS 檔案。
+
+預設情況下,這些檔案會從 CDN 提供。
+
+但你可以自訂:你可以指定特定的 CDN,或自行提供這些檔案。
+
+## 為 JavaScript 和 CSS 使用自訂 CDN { #custom-cdn-for-javascript-and-css }
+
+假設你想使用不同的 CDN,例如使用 `https://unpkg.com/`。
+
+若你所在的國家限制部分網址,這會很有用。
+
+### 停用自動產生的文件 { #disable-the-automatic-docs }
+
+第一步是停用自動文件,因為預設會使用預設的 CDN。
+
+要停用它們,建立 `FastAPI` 應用時把相關 URL 設為 `None`:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[8] *}
+
+### 加入自訂文件 { #include-the-custom-docs }
+
+現在你可以為自訂文件建立「路徑操作(path operation)」。
+
+你可以重用 FastAPI 的內部函式來建立文件的 HTML 頁面,並傳入所需參數:
+
+* `openapi_url`:文件 HTML 頁面用來取得你 API 的 OpenAPI schema 的 URL。可使用屬性 `app.openapi_url`。
+* `title`:你的 API 標題。
+* `oauth2_redirect_url`:可使用 `app.swagger_ui_oauth2_redirect_url` 以沿用預設值。
+* `swagger_js_url`:Swagger UI 文件 HTML 用來取得「JavaScript」檔案的 URL。這是你的自訂 CDN 位址。
+* `swagger_css_url`:Swagger UI 文件 HTML 用來取得「CSS」檔案的 URL。這是你的自訂 CDN 位址。
+
+ReDoc 也類似...
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[2:6,11:19,22:24,27:33] *}
+
+/// tip
+
+當你使用 OAuth2 時,`swagger_ui_redirect` 的路徑操作是個輔助端點。
+
+如果你把 API 與 OAuth2 提供者整合,便能完成認證並帶著取得的憑證回到 API 文件,接著以真正的 OAuth2 驗證與之互動。
+
+Swagger UI 會在背後幫你處理,不過它需要這個「redirect」輔助端點。
+
+///
+
+### 建立路徑操作以進行測試 { #create-a-path-operation-to-test-it }
+
+現在,為了測試一切是否正常,建立一個路徑操作:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[36:38] *}
+
+### 測試 { #test-it }
+
+現在你應該能造訪 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs),重新載入頁面後,資源會從新的 CDN 載入。
+
+## 自行託管文件所需的 JavaScript 與 CSS { #self-hosting-javascript-and-css-for-docs }
+
+若你需要應用在離線、無公共網路或僅在區域網路中也能運作,自行託管 JavaScript 與 CSS 會很實用。
+
+以下示範如何在同一個 FastAPI 應用中自行提供這些檔案,並設定文件使用它們。
+
+### 專案檔案結構 { #project-file-structure }
+
+假設你的專案檔案結構如下:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+```
+
+現在建立一個目錄來存放這些靜態檔案。
+
+新的檔案結構可能如下:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static/
+```
+
+### 下載檔案 { #download-the-files }
+
+下載文件所需的靜態檔案並放到 `static/` 目錄中。
+
+你可以在各連結上按右鍵,選擇類似「另存連結為...」的選項。
+
+Swagger UI 需要以下檔案:
+
+* [`swagger-ui-bundle.js`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js)
+* [`swagger-ui.css`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css)
+
+而 ReDoc 需要以下檔案:
+
+* [`redoc.standalone.js`](https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js)
+
+之後,你的檔案結構可能如下:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static
+ ├── redoc.standalone.js
+ ├── swagger-ui-bundle.js
+ └── swagger-ui.css
+```
+
+### 提供靜態檔案 { #serve-the-static-files }
+
+* 匯入 `StaticFiles`。
+* 在特定路徑「掛載」一個 `StaticFiles()` 實例。
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[7,11] *}
+
+### 測試靜態檔案 { #test-the-static-files }
+
+啟動你的應用並前往 [http://127.0.0.1:8000/static/redoc.standalone.js](http://127.0.0.1:8000/static/redoc.standalone.js)。
+
+你應該會看到一個很長的 **ReDoc** JavaScript 檔案。
+
+它可能會以如下內容開頭:
+
+```JavaScript
+/*! For license information please see redoc.standalone.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")):
+...
+```
+
+這表示你的應用已能提供靜態檔案,且文件用的靜態檔已放在正確位置。
+
+接著把應用設定為讓文件使用這些靜態檔。
+
+### 為靜態檔案停用自動文件 { #disable-the-automatic-docs-for-static-files }
+
+和使用自訂 CDN 一樣,第一步是停用自動文件,因為預設會使用 CDN。
+
+要停用它們,建立 `FastAPI` 應用時把相關 URL 設為 `None`:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[9] *}
+
+### 加入使用靜態檔案的自訂文件 { #include-the-custom-docs-for-static-files }
+
+同樣地,現在你可以為自訂文件建立路徑操作。
+
+再次重用 FastAPI 的內部函式來建立文件的 HTML 頁面,並傳入所需參數:
+
+* `openapi_url`:文件 HTML 頁面用來取得你 API 的 OpenAPI schema 的 URL。可使用屬性 `app.openapi_url`。
+* `title`:你的 API 標題。
+* `oauth2_redirect_url`:可使用 `app.swagger_ui_oauth2_redirect_url` 以沿用預設值。
+* `swagger_js_url`:Swagger UI 文件 HTML 用來取得「JavaScript」檔案的 URL。這就是你的應用現在提供的檔案。
+* `swagger_css_url`:Swagger UI 文件 HTML 用來取得「CSS」檔案的 URL。這就是你的應用現在提供的檔案。
+
+ReDoc 也類似...
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[2:6,14:22,25:27,30:36] *}
+
+/// tip
+
+當你使用 OAuth2 時,`swagger_ui_redirect` 的路徑操作是個輔助端點。
+
+如果你把 API 與 OAuth2 提供者整合,便能完成認證並帶著取得的憑證回到 API 文件,接著以真正的 OAuth2 驗證與之互動。
+
+Swagger UI 會在背後幫你處理,不過它需要這個「redirect」輔助端點。
+
+///
+
+### 建立路徑操作以測試靜態檔案 { #create-a-path-operation-to-test-static-files }
+
+現在,為了測試一切是否正常,建立一個路徑操作:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[39:41] *}
+
+### 測試使用靜態檔案的 UI { #test-static-files-ui }
+
+現在,你應該可以關閉 WiFi,造訪你的文件 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs),並重新載入頁面。
+
+即使沒有網際網路,也能看到你的 API 文件並與之互動。
diff --git a/docs/zh-hant/docs/how-to/custom-request-and-route.md b/docs/zh-hant/docs/how-to/custom-request-and-route.md
new file mode 100644
index 0000000000000..00031fcaad53c
--- /dev/null
+++ b/docs/zh-hant/docs/how-to/custom-request-and-route.md
@@ -0,0 +1,109 @@
+# 自訂 Request 與 APIRoute 類別 { #custom-request-and-apiroute-class }
+
+在某些情況下,你可能想要覆寫 `Request` 與 `APIRoute` 類別所使用的邏輯。
+
+特別是,這可能是替代中介軟體(middleware)中實作邏輯的一個好方法。
+
+例如,如果你想在應用程式處理之前讀取或操作請求本文(request body)。
+
+/// danger
+
+這是進階功能。
+
+如果你剛開始使用 **FastAPI**,可以先跳過本節。
+
+///
+
+## 使用情境 { #use-cases }
+
+可能的使用情境包括:
+
+* 將非 JSON 的請求本文轉換為 JSON(例如 [`msgpack`](https://msgpack.org/index.html))。
+* 解壓縮以 gzip 壓縮的請求本文。
+* 自動記錄所有請求本文。
+
+## 處理自訂請求本文編碼 { #handling-custom-request-body-encodings }
+
+讓我們看看如何使用自訂的 `Request` 子類別來解壓縮 gzip 請求。
+
+並透過 `APIRoute` 子類別來使用該自訂的請求類別。
+
+### 建立自訂的 `GzipRequest` 類別 { #create-a-custom-gziprequest-class }
+
+/// tip
+
+這是一個示範用的簡化範例;如果你需要 Gzip 支援,可以直接使用提供的 [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware)。
+
+///
+
+首先,我們建立 `GzipRequest` 類別,它會覆寫 `Request.body()` 方法,當存在對應的標頭時解壓縮本文。
+
+如果標頭中沒有 `gzip`,它就不會嘗試解壓縮本文。
+
+如此一來,相同的路由類別即可同時處理經 gzip 壓縮與未壓縮的請求。
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[9:16] *}
+
+### 建立自訂的 `GzipRoute` 類別 { #create-a-custom-gziproute-class }
+
+接著,我們建立 `fastapi.routing.APIRoute` 的自訂子類別,讓它使用 `GzipRequest`。
+
+這次,它會覆寫 `APIRoute.get_route_handler()` 方法。
+
+這個方法會回傳一個函式,而該函式會接收請求並回傳回應。
+
+在這裡,我們用它將原始的請求包裝成 `GzipRequest`。
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[19:27] *}
+
+/// note | 技術細節
+
+`Request` 具有 `request.scope` 屬性,它其實就是一個 Python 的 `dict`,包含與該請求相關的中繼資料。
+
+`Request` 也有 `request.receive`,那是一個用來「接收」請求本文的函式。
+
+`scope` 這個 `dict` 與 `receive` 函式都是 ASGI 規格的一部分。
+
+而 `scope` 與 `receive` 這兩者,就是建立一個新的 `Request` 實例所需的資料。
+
+想了解更多 `Request`,請參考 [Starlette 的 Request 文件](https://www.starlette.dev/requests/)。
+
+///
+
+由 `GzipRequest.get_route_handler` 回傳的函式,唯一不同之處在於它會把 `Request` 轉換成 `GzipRequest`。
+
+這麼做之後,`GzipRequest` 會在把資料交給 *路徑操作* 之前(若有需要)先負責解壓縮。
+
+之後的處理邏輯完全相同。
+
+但由於我們修改了 `GzipRequest.body`,在 **FastAPI** 需要讀取本文時,請求本文會自動解壓縮。
+
+## 在例外處理器中存取請求本文 { #accessing-the-request-body-in-an-exception-handler }
+
+/// tip
+
+要解決相同問題,使用針對 `RequestValidationError` 的自訂處理器來讀取 `body` 通常更簡單([處理錯誤](../tutorial/handling-errors.md#use-the-requestvalidationerror-body))。
+
+但本範例仍然有效,並示範了如何與內部元件互動。
+
+///
+
+我們也可以用同樣的方法,在例外處理器中存取請求本文。
+
+我們只需要在 `try`/`except` 區塊中處理請求即可:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[14,16] *}
+
+若發生例外,`Request` 實例依然在作用域內,因此在處理錯誤時我們仍可讀取並使用請求本文:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[17:19] *}
+
+## 在路由器中自訂 `APIRoute` 類別 { #custom-apiroute-class-in-a-router }
+
+你也可以在 `APIRouter` 上設定 `route_class` 參數:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[26] *}
+
+在此範例中,`router` 底下的路徑操作會使用自訂的 `TimedRoute` 類別,並在回應中多加上一個 `X-Response-Time` 標頭,標示產生該回應所花費的時間:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[13:20] *}
diff --git a/docs/zh-hant/docs/how-to/extending-openapi.md b/docs/zh-hant/docs/how-to/extending-openapi.md
new file mode 100644
index 0000000000000..b5adca0f76097
--- /dev/null
+++ b/docs/zh-hant/docs/how-to/extending-openapi.md
@@ -0,0 +1,80 @@
+# 擴充 OpenAPI { #extending-openapi }
+
+有些情況你可能需要修改自動產生的 OpenAPI 結構(schema)。
+
+本章將示範如何做。
+
+## 一般流程 { #the-normal-process }
+
+一般(預設)的流程如下。
+
+`FastAPI` 應用程式(實例)有一個 `.openapi()` 方法,會回傳 OpenAPI 結構。
+
+在建立應用物件時,會同時註冊一個 `/openapi.json`(或你在 `openapi_url` 設定的路徑)的路徑操作(path operation)。
+
+這個路徑只會回傳一個 JSON 回應,內容就是應用的 `.openapi()` 方法結果。
+
+預設情況下,`.openapi()` 會先檢查 `.openapi_schema` 屬性是否已有內容,有的話就直接回傳。
+
+若沒有,則會呼叫 `fastapi.openapi.utils.get_openapi` 這個工具函式來產生。
+
+`get_openapi()` 函式會接收以下參數:
+
+* `title`:OpenAPI 的標題,會顯示在文件中。
+* `version`:你的 API 版本,例如 `2.5.0`。
+* `openapi_version`:所使用的 OpenAPI 規格版本。預設為最新版本:`3.1.0`。
+* `summary`:API 的簡短摘要。
+* `description`:API 的描述,可包含 Markdown,會顯示在文件中。
+* `routes`:路由列表,也就是所有已註冊的路徑操作。來源為 `app.routes`。
+
+/// info
+
+`summary` 參數在 OpenAPI 3.1.0 以上可用,且需 FastAPI 0.99.0 以上版本支援。
+
+///
+
+## 覆寫預設行為 { #overriding-the-defaults }
+
+基於上述資訊,你可以用相同的工具函式來產生 OpenAPI 結構,並覆寫你需要客製的部分。
+
+例如,我們要加入 [ReDoc 的 OpenAPI 擴充,插入自訂 logo](https://github.com/Rebilly/ReDoc/blob/master/docs/redoc-vendor-extensions.md#x-logo)。
+
+### 一般的 **FastAPI** { #normal-fastapi }
+
+先照常撰寫你的 **FastAPI** 應用:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[1,4,7:9] *}
+
+### 產生 OpenAPI 結構 { #generate-the-openapi-schema }
+
+接著,在 `custom_openapi()` 函式內,使用相同的工具函式來產生 OpenAPI 結構:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[2,15:21] *}
+
+### 修改 OpenAPI 結構 { #modify-the-openapi-schema }
+
+現在可以加入 ReDoc 擴充,在 OpenAPI 結構的 `info`「物件」中新增自訂的 `x-logo`:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[22:24] *}
+
+### 快取 OpenAPI 結構 { #cache-the-openapi-schema }
+
+你可以把 `.openapi_schema` 屬性當作「快取」來儲存已產生的結構。
+
+這樣使用者每次開啟 API 文件時,應用就不必重複產生結構。
+
+結構只會產生一次,之後的請求都會使用相同的快取結果。
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[13:14,25:26] *}
+
+### 覆寫方法 { #override-the-method }
+
+現在你可以用新的函式取代 `.openapi()` 方法。
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[29] *}
+
+### 檢查看看 { #check-it }
+
+造訪 [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) 後,你會看到自訂的 logo(此例為 **FastAPI** 的 logo):
+
+
diff --git a/docs/zh-hant/docs/how-to/general.md b/docs/zh-hant/docs/how-to/general.md
new file mode 100644
index 0000000000000..13d4d7d3eebf9
--- /dev/null
+++ b/docs/zh-hant/docs/how-to/general.md
@@ -0,0 +1,43 @@
+# 通用 - 操作指南 - 實用範例 { #general-how-to-recipes }
+
+以下是文件中其他位置的指引連結,適用於一般或常見問題。
+
+## 篩選資料 - 安全性 { #filter-data-security }
+
+為確保你不會回傳超出應有的資料,請參閱[教學 - 回應模型 - 回傳型別](../tutorial/response-model.md)。
+
+## 最佳化回應效能 - 回應模型 - 回傳型別 { #optimize-response-performance-response-model-return-type }
+
+為了在回傳 JSON 資料時最佳化效能,請使用回傳型別或回應模型,如此 Pydantic 會在 Rust 端處理序列化為 JSON,而不經過 Python。更多內容請參閱[教學 - 回應模型 - 回傳型別](../tutorial/response-model.md)。
+
+## 文件標籤 - OpenAPI { #documentation-tags-openapi }
+
+要在你的*路徑操作(path operation)*加入標籤,並在文件 UI 中分組,請參閱[教學 - 路徑操作設定 - 標籤](../tutorial/path-operation-configuration.md#tags)。
+
+## 文件摘要與描述 - OpenAPI { #documentation-summary-and-description-openapi }
+
+要為你的*路徑操作*加入摘要與描述,並在文件 UI 中顯示,請參閱[教學 - 路徑操作設定 - 摘要與描述](../tutorial/path-operation-configuration.md#summary-and-description)。
+
+## 文件回應描述 - OpenAPI { #documentation-response-description-openapi }
+
+要定義在文件 UI 中顯示的回應描述,請參閱[教學 - 路徑操作設定 - 回應描述](../tutorial/path-operation-configuration.md#response-description)。
+
+## 文件將*路徑操作*標記為已棄用 - OpenAPI { #documentation-deprecate-a-path-operation-openapi }
+
+要將*路徑操作*標記為已棄用,並在文件 UI 中顯示,請參閱[教學 - 路徑操作設定 - 棄用](../tutorial/path-operation-configuration.md#deprecate-a-path-operation)。
+
+## 將任意資料轉換為 JSON 相容格式 { #convert-any-data-to-json-compatible }
+
+要將任意資料轉換為 JSON 相容格式,請參閱[教學 - JSON 相容編碼器](../tutorial/encoder.md)。
+
+## OpenAPI 中繼資料 - 文件 { #openapi-metadata-docs }
+
+要在你的 OpenAPI 綱要中加入中繼資料(包含授權、版本、聯絡方式等),請參閱[教學 - 中繼資料與文件 URL](../tutorial/metadata.md)。
+
+## 自訂 OpenAPI URL { #openapi-custom-url }
+
+要自訂(或移除)OpenAPI 的 URL,請參閱[教學 - 中繼資料與文件 URL](../tutorial/metadata.md#openapi-url)。
+
+## OpenAPI 文件 URL { #openapi-docs-urls }
+
+要更新自動產生的文件使用者介面所使用的 URL,請參閱[教學 - 中繼資料與文件 URL](../tutorial/metadata.md#docs-urls)。
diff --git a/docs/zh-hant/docs/how-to/graphql.md b/docs/zh-hant/docs/how-to/graphql.md
new file mode 100644
index 0000000000000..24e4d89792eec
--- /dev/null
+++ b/docs/zh-hant/docs/how-to/graphql.md
@@ -0,0 +1,60 @@
+# GraphQL { #graphql }
+
+由於 FastAPI 基於 ASGI 標準,整合任何與 ASGI 相容的 GraphQL 函式庫都很容易。
+
+你可以在同一個應用程式中同時使用一般的 FastAPI 路徑操作 (path operation) 與 GraphQL。
+
+/// tip
+
+GraphQL 解決某些非常特定的使用情境。
+
+與一般的 Web API 相比,它有優點也有缺點。
+
+請確認在你的使用情境中,這些效益是否足以彌補其限制。 🤓
+
+///
+
+## GraphQL 函式庫 { #graphql-libraries }
+
+下面是支援 ASGI 的部分 GraphQL 函式庫,你可以與 FastAPI 一起使用:
+
+* [Strawberry](https://strawberry.rocks/) 🍓
+ * 提供 [FastAPI 文件](https://strawberry.rocks/docs/integrations/fastapi)
+* [Ariadne](https://ariadnegraphql.org/)
+ * 提供 [FastAPI 文件](https://ariadnegraphql.org/docs/fastapi-integration)
+* [Tartiflette](https://tartiflette.io/)
+ * 使用 [Tartiflette ASGI](https://tartiflette.github.io/tartiflette-asgi/) 提供 ASGI 整合
+* [Graphene](https://graphene-python.org/)
+ * 搭配 [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3)
+
+## 使用 Strawberry 的 GraphQL { #graphql-with-strawberry }
+
+如果你需要或想使用 GraphQL,[Strawberry](https://strawberry.rocks/) 是推薦的函式庫,因為它的設計與 FastAPI 最接近,全部都基於型別註解 (type annotations)。
+
+視你的使用情境而定,你可能會偏好其他函式庫,但如果你問我,我大概會建議你先試試 Strawberry。
+
+以下是如何將 Strawberry 與 FastAPI 整合的一個小例子:
+
+{* ../../docs_src/graphql_/tutorial001_py310.py hl[3,22,25] *}
+
+你可以在 [Strawberry 文件](https://strawberry.rocks/) 中進一步了解 Strawberry。
+
+也可以參考關於 [Strawberry 與 FastAPI](https://strawberry.rocks/docs/integrations/fastapi) 的文件。
+
+## 來自 Starlette 的較舊 `GraphQLApp` { #older-graphqlapp-from-starlette }
+
+早期版本的 Starlette 提供 `GraphQLApp` 類別以整合 [Graphene](https://graphene-python.org/)。
+
+它已在 Starlette 中被棄用,但如果你的程式碼使用了它,可以輕鬆遷移到 [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3),涵蓋相同的使用情境,且介面幾乎相同。
+
+/// tip
+
+如果你需要 GraphQL,我仍建議你看看 [Strawberry](https://strawberry.rocks/),因為它基於型別註解,而不是自訂的類別與型別。
+
+///
+
+## 進一步了解 { #learn-more }
+
+你可以在 [官方 GraphQL 文件](https://graphql.org/) 中進一步了解 GraphQL。
+
+你也可以透過上述連結閱讀各個函式庫的更多內容。
diff --git a/docs/zh-hant/docs/how-to/index.md b/docs/zh-hant/docs/how-to/index.md
new file mode 100644
index 0000000000000..c08bd3d663962
--- /dev/null
+++ b/docs/zh-hant/docs/how-to/index.md
@@ -0,0 +1,13 @@
+# 使用指南 - 範例集 { #how-to-recipes }
+
+在這裡,你將會看到**不同主題**的範例或「如何使用」的指南。
+
+大多數這些想法都是**獨立**的,在大多數情況下,你只需要研究那些直接適用於**你的專案**的東西。
+
+如果有些東西看起來很有趣且對你的專案很有用的話再去讀它,否則你可能可以跳過它們。
+
+/// tip
+
+如果你想要以結構化的方式**學習 FastAPI**(推薦),請前往[教學 - 使用者指南](../tutorial/index.md)逐章閱讀。
+
+///
diff --git a/docs/zh-hant/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/zh-hant/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
new file mode 100644
index 0000000000000..4495e3dd70ae3
--- /dev/null
+++ b/docs/zh-hant/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -0,0 +1,135 @@
+# 從 Pydantic v1 遷移到 Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 }
+
+如果你有一個舊的 FastAPI 應用,可能正在使用 Pydantic 1 版。
+
+FastAPI 0.100.0 同時支援 Pydantic v1 或 v2,會使用你已安裝的那個版本。
+
+FastAPI 0.119.0 透過 Pydantic v2 內的 `pydantic.v1` 提供對 Pydantic v1 的部分支援,以便遷移到 v2。
+
+FastAPI 0.126.0 移除了對 Pydantic v1 的支援,但在一段時間內仍支援 `pydantic.v1`。
+
+/// warning
+
+Pydantic 團隊自 **Python 3.14** 起,已停止在最新的 Python 版本中支援 Pydantic v1。
+
+這也包含 `pydantic.v1`,在 Python 3.14 及以上版本不再支援。
+
+如果你想使用最新的 Python 功能,就需要確保使用 Pydantic v2。
+
+///
+
+如果你的舊 FastAPI 應用仍使用 Pydantic v1,這裡會示範如何遷移到 Pydantic v2,並介紹 **FastAPI 0.119.0** 中可協助你逐步遷移的功能。
+
+## 官方指南 { #official-guide }
+
+Pydantic 提供從 v1 遷移到 v2 的官方[遷移指南](https://docs.pydantic.dev/latest/migration/)。
+
+其中包含變更內容、驗證如何更正確且更嚴格、可能的注意事項等。
+
+你可以先閱讀以更好理解具體變更。
+
+## 測試 { #tests }
+
+確保你的應用有[測試](../tutorial/testing.md),並在 CI(持續整合)上執行。
+
+如此一來,你可以升級後確認一切仍如預期運作。
+
+## `bump-pydantic` { #bump-pydantic }
+
+在許多情況下,若你使用的是未自訂的標準 Pydantic 模型,多數遷移步驟都能自動化完成。
+
+你可以使用 Pydantic 團隊提供的 [`bump-pydantic`](https://github.com/pydantic/bump-pydantic)。
+
+這個工具會自動修改大部分需要變更的程式碼。
+
+之後執行測試確認一切正常即可完成。😎
+
+## v2 中的 Pydantic v1 { #pydantic-v1-in-v2 }
+
+Pydantic v2 內含子模組 `pydantic.v1`,提供 Pydantic v1 的所有內容。但在 Python 3.13 以上版本不再支援。
+
+這表示你可以安裝最新的 Pydantic v2,並從該子模組匯入並使用舊的 Pydantic v1 元件,就像安裝了舊版 Pydantic v1 一樣。
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}
+
+### FastAPI 對 v2 中 Pydantic v1 的支援 { #fastapi-support-for-pydantic-v1-in-v2 }
+
+自 FastAPI 0.119.0 起,也支援透過 Pydantic v2 內的 Pydantic v1(部分)以協助遷移至 v2。
+
+因此,你可以先升級到最新的 Pydantic v2,並將匯入改為使用 `pydantic.v1` 子模組,在多數情況下即可正常運作。
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py hl[2,5,15] *}
+
+/// warning
+
+請注意,由於 Pydantic 團隊自 Python 3.14 起不再支援 Pydantic v1,因此在 Python 3.14 及以上版本中也不支援使用 `pydantic.v1`。
+
+///
+
+### 同一應用同時使用 Pydantic v1 與 v2 { #pydantic-v1-and-v2-on-the-same-app }
+
+Pydantic 不支援在 Pydantic v2 模型的欄位中使用 Pydantic v1 模型,反之亦然。
+
+```mermaid
+graph TB
+ subgraph "❌ Not Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+...但你可以在同一應用中同時存在分開的 Pydantic v1 與 v2 模型。
+
+```mermaid
+graph TB
+ subgraph "✅ Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+在某些情況下,你甚至可以在同一個 FastAPI 路徑操作(path operation)中同時使用 Pydantic v1 與 v2 模型:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}
+
+在上面的範例中,輸入模型是 Pydantic v1,輸出模型(於 `response_model=ItemV2` 定義)是 Pydantic v2。
+
+### Pydantic v1 參數 { #pydantic-v1-parameters }
+
+若你需要在 Pydantic v1 模型上使用 FastAPI 的參數工具(例如 `Body`、`Query`、`Form` 等),在完成遷移到 Pydantic v2 之前,可以從 `fastapi.temp_pydantic_v1_params` 匯入:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py hl[4,18] *}
+
+### 分步遷移 { #migrate-in-steps }
+
+/// tip
+
+先嘗試使用 `bump-pydantic`,如果測試通過且一切正常,你就能用一條指令完成遷移。✨
+
+///
+
+若 `bump-pydantic` 不適用於你的情境,可以利用在同一應用同時支援 Pydantic v1 與 v2 的能力,逐步完成遷移。
+
+你可以先升級 Pydantic 到最新 v2,並將所有模型的匯入改為使用 `pydantic.v1`。
+
+接著按群組逐步把模型從 Pydantic v1 遷移到 v2。🚶
diff --git a/docs/zh-hant/docs/how-to/separate-openapi-schemas.md b/docs/zh-hant/docs/how-to/separate-openapi-schemas.md
new file mode 100644
index 0000000000000..2ecb6afbc1c00
--- /dev/null
+++ b/docs/zh-hant/docs/how-to/separate-openapi-schemas.md
@@ -0,0 +1,102 @@
+# 是否將輸入與輸出使用不同的 OpenAPI 結構描述 { #separate-openapi-schemas-for-input-and-output-or-not }
+
+自從 Pydantic v2 發佈後,生成的 OpenAPI 比以往更精確也更正確。😎
+
+實際上,在某些情況下,同一個 Pydantic 模型在 OpenAPI 中會同時有兩個 JSON Schema:分別用於輸入與輸出,這取決於它是否有預設值。
+
+來看看它如何運作,以及若需要時該如何調整。
+
+## 作為輸入與輸出的 Pydantic 模型 { #pydantic-models-for-input-and-output }
+
+假設你有一個帶有預設值的 Pydantic 模型,如下所示:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *}
+
+### 輸入用模型 { #model-for-input }
+
+如果你把這個模型用作輸入,如下所示:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *}
+
+...則 `description` 欄位將不是必填。因為它的預設值是 `None`。
+
+### 文件中的輸入模型 { #input-model-in-docs }
+
+你可以在文件中確認,`description` 欄位沒有紅色星號,表示不是必填:
+
+
+
+
+
+
++ FastAPI 框架,高效能,易於學習,快速開發,適用於生產環境 +
+ + +--- + +**文件**: [https://fastapi.tiangolo.com/zh-hant](https://fastapi.tiangolo.com/zh-hant) + +**程式碼**: [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi) + +--- + +FastAPI 是一個現代、快速(高效能)的 Web 框架,用於以 Python 並基於標準的 Python 型別提示來構建 API。 + +主要特點包含: + +* **快速**:非常高的效能,可與 **NodeJS** 和 **Go** 相當(歸功於 Starlette 和 Pydantic)。[最快的 Python 框架之一](#performance)。 +* **極速開發**:開發功能的速度可提升約 200% 至 300%。* +* **更少的 Bug**:減少約 40% 的人為(開發者)錯誤。* +* **直覺**:具有出色的編輯器支援,處處都有 自動補全。更少的偵錯時間。 +* **簡單**:設計上易於使用與學習。更少的讀文件時間。 +* **簡潔**:最小化程式碼重複性。每個參數宣告可帶來多個功能。更少的錯誤。 +* **穩健**:立即獲得可投入生產的程式碼,並自動生成互動式文件。 +* **標準化**:基於(且完全相容於)API 的開放標準:[OpenAPI](https://github.com/OAI/OpenAPI-Specification)(之前稱為 Swagger)和 [JSON Schema](https://json-schema.org/)。 + +* 基於內部開發團隊在建立生產應用程式時的測試預估。 + +## 贊助 { #sponsors } + + + +### 基石贊助商 { #keystone-sponsor } + +{% for sponsor in sponsors.keystone -%} +
+
+## **Typer**,命令列的 FastAPI { #typer-the-fastapi-of-clis }
+
+async def...fastapi dev...
+
+### 加上型別 { #add-types }
+
+我們來修改前一版中的一行。
+
+我們只要把函式參數這一段,從:
+
+```Python
+ first_name, last_name
+```
+
+改成:
+
+```Python
+ first_name: str, last_name: str
+```
+
+就這樣。
+
+那些就是「型別提示」:
+
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
+
+這和宣告預設值不同,例如:
+
+```Python
+ first_name="john", last_name="doe"
+```
+
+這是不同的東西。
+
+我們使用的是冒號(`:`),不是等號(`=`)。
+
+而且加上型別提示通常不會改變執行結果,和不加時是一樣的。
+
+不過現在,想像你又在撰寫那個函式,但這次有型別提示。
+
+在同樣的地方,你按 `Ctrl+Space` 嘗試自動完成,然後你會看到:
+
+
+
+有了這些,你可以往下捲動查看選項,直到找到一個「看起來眼熟」的:
+
+
+
+## 更多動機 { #more-motivation }
+
+看這個函式,它已經有型別提示了:
+
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
+
+因為編輯器知道變數的型別,你不只會得到自動完成,還會得到錯誤檢查:
+
+
+
+現在你知道要修正它,把 `age` 用 `str(age)` 轉成字串:
+
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
+
+## 宣告型別 { #declaring-types }
+
+你剛剛看到宣告型別提示的主要位置:函式參數。
+
+這也是你在 **FastAPI** 中最常使用它們的地方。
+
+### 簡單型別 { #simple-types }
+
+你可以宣告所有標準的 Python 型別,不只 `str`。
+
+例如你可以用:
+
+* `int`
+* `float`
+* `bool`
+* `bytes`
+
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
+
+### `typing` 模組 { #typing-module }
+
+在一些其他情境中,你可能需要從標準程式庫的 `typing` 模組匯入一些東西,比如當你想宣告某個東西可以是「任何型別」時,可以用 `typing` 裡的 `Any`:
+
+```python
+from typing import Any
+
+
+def some_function(data: Any):
+ print(data)
+```
+
+### 泛型(Generic types) { #generic-types }
+
+有些型別可以在方括號中接收「型別參數」,以定義其內部元素的型別,例如「字串的 list」可以宣告為 `list[str]`。
+
+這些能接收型別參數的型別稱為「泛型(Generic types)」或「Generics」。
+
+你可以將相同的內建型別用作泛型(使用方括號並在裡面放型別):
+
+* `list`
+* `tuple`
+* `set`
+* `dict`
+
+#### List { #list }
+
+例如,讓我們定義一個變數是 `str` 的 `list`。
+
+宣告變數,使用相同的冒號(`:`)語法。
+
+型別填 `list`。
+
+由於 list 是一種包含內部型別的型別,你要把內部型別放在方括號中:
+
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
+
+/// info | 資訊
+
+方括號裡的那些內部型別稱為「型別參數」。
+
+在這個例子中,`str` 是傳給 `list` 的型別參數。
+
+///
+
+這表示:「變數 `items` 是一個 `list`,而這個清單中的每個元素都是 `str`」。
+
+這麼做之後,你的編輯器甚至在處理清單裡的項目時也能提供支援:
+
+
+
+沒有型別時,幾乎不可能做到這點。
+
+請注意,變數 `item` 是清單 `items` 中的一個元素。
+
+即便如此,編輯器仍然知道它是 `str`,並提供相應的支援。
+
+#### Tuple 與 Set { #tuple-and-set }
+
+你也可以用相同方式來宣告 `tuple` 與 `set`:
+
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
+
+這代表:
+
+* 變數 `items_t` 是一個有 3 個項目的 `tuple`,分別是 `int`、`int` 和 `str`。
+* 變數 `items_s` 是一個 `set`,而其中每個項目都是 `bytes` 型別。
+
+#### Dict { #dict }
+
+定義 `dict` 時,你需要傳入 2 個以逗號分隔的型別參數。
+
+第一個型別參數是 `dict` 的鍵(key)。
+
+第二個型別參數是 `dict` 的值(value):
+
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
+
+這代表:
+
+* 變數 `prices` 是個 `dict`:
+ * 這個 `dict` 的鍵是 `str`(例如每個項目的名稱)。
+ * 這個 `dict` 的值是 `float`(例如每個項目的價格)。
+
+#### Union { #union }
+
+你可以宣告一個變數可以是「多種型別」中的任一種,例如 `int` 或 `str`。
+
+要這麼定義,你使用豎線(`|`)來分隔兩種型別。
+
+這稱為「union」,因為變數可以是這兩種型別集合的聯集中的任一種。
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
+```
+
+這表示 `item` 可以是 `int` 或 `str`。
+
+#### 可能為 `None` { #possibly-none }
+
+你可以宣告某個值可以是某個型別(例如 `str`),但它也可能是 `None`。
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
+```
+
+////
+
+使用 `str | None` 而不是單純的 `str`,可以讓編輯器幫你偵測錯誤,例如你以為某個值一定是 `str`,但它其實也可能是 `None`。
+
+### 類別作為型別 { #classes-as-types }
+
+你也可以用類別來宣告變數的型別。
+
+假設你有一個 `Person` 類別,帶有名稱:
+
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
+
+接著你可以宣告一個變數為 `Person` 型別:
+
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
+
+然後,你一樣會得到完整的編輯器支援:
+
+
+
+請注意,這表示「`one_person` 是類別 `Person` 的『實例(instance)』」。
+
+並不是「`one_person` 就是名為 `Person` 的『類別(class)』」。
+
+## Pydantic 模型 { #pydantic-models }
+
+[Pydantic](https://docs.pydantic.dev/) 是一個用來做資料驗證的 Python 程式庫。
+
+你以帶有屬性的類別來宣告資料的「形狀」。
+
+而每個屬性都有其型別。
+
+接著你用一些值建立這個類別的實例,它會驗證這些值、在需要時把它們轉換成適當的型別,然後回給你一個包含所有資料的物件。
+
+你也會對這個產生的物件得到完整的編輯器支援。
+
+以下是來自 Pydantic 官方文件的例子:
+
+{* ../../docs_src/python_types/tutorial011_py310.py *}
+
+/// info | 資訊
+
+想了解更多 [Pydantic,請查看它的文件](https://docs.pydantic.dev/)。
+
+///
+
+**FastAPI** 完全是以 Pydantic 為基礎。
+
+你會在[教學 - 使用者指南](tutorial/index.md)中看到更多實際範例。
+
+## 含中繼資料的型別提示 { #type-hints-with-metadata-annotations }
+
+Python 也有一個功能,允許使用 `Annotated` 在這些型別提示中放入額外的中繼資料。
+
+你可以從 `typing` 匯入 `Annotated`。
+
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
+
+Python 本身不會對這個 `Annotated` 做任何事。對編輯器與其他工具而言,該型別仍然是 `str`。
+
+但你可以利用 `Annotated` 這個空間,來提供 **FastAPI** 額外的中繼資料,告訴它你希望應用程式如何運作。
+
+重要的是要記住,傳給 `Annotated` 的「第一個型別參數」才是「真正的型別」。其餘的,都是給其他工具用的中繼資料。
+
+目前你只需要知道 `Annotated` 的存在,而且它是標準的 Python。😎
+
+之後你會看到它有多「強大」。
+
+/// tip | 提示
+
+因為這是「標準 Python」,所以你在編輯器、分析與重構程式碼的工具等方面,仍然能獲得「最佳的開發體驗」。✨
+
+而且你的程式碼也會與許多其他 Python 工具與程式庫非常相容。🚀
+
+///
+
+## 在 **FastAPI** 中的型別提示 { #type-hints-in-fastapi }
+
+**FastAPI** 善用這些型別提示來完成多項工作。
+
+在 **FastAPI** 中,你用型別提示來宣告參數,然後你會得到:
+
+* 編輯器支援
+* 型別檢查
+
+...而 **FastAPI** 也會用同樣的宣告來:
+
+* 定義需求:來自請求的路徑參數、查詢參數、標頭、主體(body)、相依性等
+* 轉換資料:把請求中的資料轉成所需型別
+* 驗證資料:來自每個請求的資料:
+ * 當資料無效時,自動產生錯誤並回傳給用戶端
+* 使用 OpenAPI 書寫 API 文件:
+ * 之後會由自動的互動式文件介面所使用
+
+這些現在聽起來可能有點抽象。別擔心。你會在[教學 - 使用者指南](tutorial/index.md)中看到它們的實際運作。
+
+重點是,透過在單一位置使用標準的 Python 型別(而不是新增更多類別、裝飾器等),**FastAPI** 會幫你完成很多工作。
+
+/// info | 資訊
+
+如果你已經完整讀完整個教學,並回來想多看一些關於型別的內容,一個不錯的資源是 [`mypy` 的「小抄」](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html)。
+
+///
diff --git a/docs/zh-hant/docs/resources/index.md b/docs/zh-hant/docs/resources/index.md
new file mode 100644
index 0000000000000..ea77cb728ea11
--- /dev/null
+++ b/docs/zh-hant/docs/resources/index.md
@@ -0,0 +1,3 @@
+# 資源 { #resources }
+
+額外的資源、外部連結等。 ✈️
diff --git a/docs/zh-hant/docs/translation-banner.md b/docs/zh-hant/docs/translation-banner.md
new file mode 100644
index 0000000000000..58b49965a9b82
--- /dev/null
+++ b/docs/zh-hant/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 AI 與人類共同完成的翻譯
+
+此翻譯由人類指導的 AI 完成。🤝
+
+可能會有對原意的誤解,或讀起來不自然等問題。🤖
+
+你可以透過[協助我們更好地引導 AI LLM](https://fastapi.tiangolo.com/zh-hant/contributing/#translations)來改進此翻譯。
+
+[英文版](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/zh-hant/docs/tutorial/background-tasks.md b/docs/zh-hant/docs/tutorial/background-tasks.md
new file mode 100644
index 0000000000000..216ec88689fdb
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/background-tasks.md
@@ -0,0 +1,84 @@
+# 背景任務 { #background-tasks }
+
+你可以定義背景任務,讓它們在傳回回應之後執行。
+
+這對於那些需要在請求之後發生、但用戶端其實不必在收到回應前等它完成的操作很有用。
+
+例如:
+
+* 在執行某個動作後發送電子郵件通知:
+ * 由於連線到郵件伺服器並寄送郵件通常較「慢」(數秒),你可以先立即回應,並在背景中發送郵件通知。
+* 處理資料:
+ * 例如,收到一個需要經過較慢處理流程的檔案時,你可以先回應「Accepted」(HTTP 202),再在背景處理該檔案。
+
+## 使用 `BackgroundTasks` { #using-backgroundtasks }
+
+首先,匯入 `BackgroundTasks`,並在你的路徑操作函式中定義一個型別為 `BackgroundTasks` 的參數:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
+
+**FastAPI** 會為你建立 `BackgroundTasks` 物件,並以該參數傳入。
+
+## 建立任務函式 { #create-a-task-function }
+
+建立一個作為背景任務執行的函式。
+
+它只是個可接收參數的一般函式。
+
+它可以是 `async def`,也可以是一般的 `def`,**FastAPI** 都能正確處理。
+
+在此例中,任務函式會寫入檔案(模擬寄送電子郵件)。
+
+由於寫入操作未使用 `async` 與 `await`,因此以一般的 `def` 定義該函式:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
+
+## 新增背景任務 { #add-the-background-task }
+
+在路徑操作函式內,使用 `.add_task()` 將任務函式加入背景任務物件:
+
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
+
+`.add_task()` 的引數包括:
+
+* 要在背景執行的任務函式(`write_notification`)。
+* 依序傳給任務函式的位置引數(`email`)。
+* 要傳給任務函式的關鍵字引數(`message="some notification"`)。
+
+## 相依性注入 { #dependency-injection }
+
+在相依性注入系統中也可使用 `BackgroundTasks`。你可以在多個層級宣告 `BackgroundTasks` 型別的參數:路徑操作函式、相依項(dependable)、次級相依項等。
+
+**FastAPI** 會在各種情況下正確處理並重用同一個物件,將所有背景任務合併,並在之後於背景執行:
+
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
+
+在此範例中,訊息會在回應送出之後寫入 `log.txt` 檔案。
+
+如果請求中有查詢參數,會以背景任務寫入日誌。
+
+接著,在路徑操作函式中建立的另一個背景任務會使用 `email` 路徑參數寫入訊息。
+
+## 技術細節 { #technical-details }
+
+類別 `BackgroundTasks` 直接來自 [`starlette.background`](https://www.starlette.dev/background/)。
+
+它被直接匯入/包含到 FastAPI 中,因此你可以從 `fastapi` 匯入它,並避免不小心從 `starlette.background` 匯入另一個同名的 `BackgroundTask`(結尾沒有 s)。
+
+只使用 `BackgroundTasks`(而非 `BackgroundTask`)時,你就能把它當作路徑操作函式的參數,並讓 **FastAPI** 幫你處理其餘部分,就像直接使用 `Request` 物件一樣。
+
+在 FastAPI 中仍可單獨使用 `BackgroundTask`,但你需要在程式碼中自行建立該物件,並回傳包含它的 Starlette `Response`。
+
+更多細節請參閱 [Starlette 官方的 Background Tasks 文件](https://www.starlette.dev/background/)。
+
+## 注意事項 { #caveat }
+
+如果你需要執行繁重的背景計算,且不一定要由同一個行程執行(例如不需要共用記憶體、變數等),可以考慮使用更大型的工具,例如 [Celery](https://docs.celeryq.dev)。
+
+這類工具通常需要較複雜的設定,以及訊息/工作佇列管理器(如 RabbitMQ 或 Redis),但它們允許你在多個行程,甚至多台伺服器上執行背景任務。
+
+但如果你需要存取同一個 **FastAPI** 應用中的變數與物件,或只需執行小型的背景任務(例如寄送郵件通知),僅使用 `BackgroundTasks` 即可。
+
+## 重點回顧 { #recap }
+
+在路徑操作函式與相依項中匯入並使用 `BackgroundTasks` 參數,以新增背景任務。
diff --git a/docs/zh-hant/docs/tutorial/bigger-applications.md b/docs/zh-hant/docs/tutorial/bigger-applications.md
new file mode 100644
index 0000000000000..a37c16c39ea65
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/bigger-applications.md
@@ -0,0 +1,535 @@
+# 更大型的應用程式 - 多個檔案 { #bigger-applications-multiple-files }
+
+如果你正在建置一個應用程式或 Web API,很少會把所有東西都放在單一檔案裡。
+
+FastAPI 提供了一個方便的工具,讓你在維持彈性的同時,幫你組織應用程式的結構。
+
+/// info | 資訊
+
+如果你來自 Flask,這相當於 Flask 的 Blueprints。
+
+///
+
+## 範例檔案結構 { #an-example-file-structure }
+
+假設你有如下的檔案結構:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ ├── dependencies.py
+│ └── routers
+│ │ ├── __init__.py
+│ │ ├── items.py
+│ │ └── users.py
+│ └── internal
+│ ├── __init__.py
+│ └── admin.py
+```
+
+/// tip | 提示
+
+有好幾個 `__init__.py` 檔案:每個目錄或子目錄各一個。
+
+這讓我們可以把一個檔案中的程式碼匯入到另一個檔案。
+
+例如,在 `app/main.py` 你可以有一行:
+
+```
+from app.routers import items
+```
+
+///
+
+* `app` 目錄包含所有內容。它有一個空的 `app/__init__.py` 檔案,所以它是一個「Python 套件」(「Python 模組」的集合):`app`。
+* 它包含一個 `app/main.py` 檔案。因為它在一個 Python 套件中(有 `__init__.py` 檔案的目錄),它是該套件的一個「模組」:`app.main`。
+* 還有一個 `app/dependencies.py` 檔案,就像 `app/main.py` 一樣,它是一個「模組」:`app.dependencies`。
+* 有一個子目錄 `app/routers/`,裡面有另一個 `__init__.py` 檔案,所以它是一個「Python 子套件」:`app.routers`。
+* 檔案 `app/routers/items.py` 在一個套件 `app/routers/` 內,因此它是一個子模組:`app.routers.items`。
+* 同樣地,`app/routers/users.py` 是另一個子模組:`app.routers.users`。
+* 還有一個子目錄 `app/internal/`,裡面有另一個 `__init__.py` 檔案,所以它又是一個「Python 子套件」:`app.internal`。
+* 檔案 `app/internal/admin.py` 是另一個子模組:`app.internal.admin`。
+
+
+
+## 以不同的 `prefix` 多次納入同一個 router { #include-the-same-router-multiple-times-with-different-prefix }
+
+你也可以用不同的前綴,對同一個 router 多次呼叫 `.include_router()`。
+
+例如,這對於在不同前綴下提供相同的 API 很有用,如 `/api/v1` 與 `/api/latest`。
+
+這是進階用法,你可能不會需要,但若有需要它就在那裡。
+
+## 在另一個 `APIRouter` 中納入一個 `APIRouter` { #include-an-apirouter-in-another }
+
+就像你可以在 `FastAPI` 應用中納入一個 `APIRouter` 一樣,你也可以在另一個 `APIRouter` 中納入一個 `APIRouter`,用法如下:
+
+```Python
+router.include_router(other_router)
+```
+
+請確保在把 `router` 納入 `FastAPI` 應用之前先這麼做,這樣 `other_router` 的路徑操作也會被包含進去。
diff --git a/docs/zh-hant/docs/tutorial/body-fields.md b/docs/zh-hant/docs/tutorial/body-fields.md
new file mode 100644
index 0000000000000..a16e756b7c4e7
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/body-fields.md
@@ -0,0 +1,61 @@
+# Body - 欄位 { #body-fields }
+
+就像你可以在「路徑操作函式 (path operation function)」的參數中用 `Query`、`Path` 和 `Body` 宣告額外的驗證與中繼資料一樣,你也可以在 Pydantic 模型中使用 Pydantic 的 `Field` 來宣告驗證與中繼資料。
+
+## 匯入 `Field` { #import-field }
+
+首先,你需要匯入它:
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}
+
+
+/// warning
+
+請注意,`Field` 是直接從 `pydantic` 匯入的,不像其他(如 `Query`、`Path`、`Body` 等)是從 `fastapi` 匯入。
+
+///
+
+## 宣告模型屬性 { #declare-model-attributes }
+
+接著你可以在模型屬性上使用 `Field`:
+
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}
+
+`Field` 的用法與 `Query`、`Path`、`Body` 相同,擁有相同的參數等。
+
+/// note | 技術細節
+
+實際上,你接下來會看到的 `Query`、`Path` 等,會建立共同父類別 `Param` 的子類別物件,而 `Param` 本身是 Pydantic 的 `FieldInfo` 類別的子類別。
+
+而 Pydantic 的 `Field` 也會回傳一個 `FieldInfo` 的實例。
+
+`Body` 也會直接回傳 `FieldInfo` 子類別的物件。稍後你會看到還有其他類別是 `Body` 類別的子類別。
+
+記得,當你從 `fastapi` 匯入 `Query`、`Path` 等時,它們其實是回傳特殊類別的函式。
+
+///
+
+/// tip
+
+注意,每個帶有型別、預設值與 `Field` 的模型屬性,其結構和「路徑操作函式」的參數相同,只是把 `Path`、`Query`、`Body` 換成了 `Field`。
+
+///
+
+## 加入額外資訊 { #add-extra-information }
+
+你可以在 `Field`、`Query`、`Body` 等中宣告額外資訊。這些資訊會被包含在產生的 JSON Schema 中。
+
+你會在後續文件中學到更多關於加入額外資訊的內容,特別是在宣告範例時。
+
+/// warning
+
+傳入 `Field` 的額外鍵也會出現在你的應用程式所產生的 OpenAPI schema 中。
+由於這些鍵不一定屬於 OpenAPI 規格的一部分,一些 OpenAPI 工具(例如 [OpenAPI 驗證器](https://validator.swagger.io/))可能無法處理你產生的 schema。
+
+///
+
+## 回顧 { #recap }
+
+你可以使用 Pydantic 的 `Field` 為模型屬性宣告額外的驗證與中繼資料。
+
+你也可以使用額外的關鍵字引數來傳遞額外的 JSON Schema 中繼資料。
diff --git a/docs/zh-hant/docs/tutorial/body-multiple-params.md b/docs/zh-hant/docs/tutorial/body-multiple-params.md
new file mode 100644
index 0000000000000..1c334f51f5ec5
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/body-multiple-params.md
@@ -0,0 +1,165 @@
+# Body - 多個參數 { #body-multiple-parameters }
+
+現在我們已經知道如何使用 `Path` 與 `Query`,接下來看看更進階的請求主體(request body)宣告用法。
+
+## 混用 `Path`、`Query` 與 Body 參數 { #mix-path-query-and-body-parameters }
+
+首先,當然你可以自由混用 `Path`、`Query` 與請求 Body 參數的宣告,**FastAPI** 會知道該怎麼做。
+
+你也可以將 Body 參數宣告為可選,方法是將預設值設為 `None`:
+
+{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
+
+/// note | 注意
+
+請注意,在此情況下,從 body 取得的 `item` 是可選的,因為它的預設值是 `None`。
+
+///
+
+## 多個 Body 參數 { #multiple-body-parameters }
+
+在前一個範例中,路徑操作(path operation)會期望一個包含 `Item` 屬性的 JSON 主體,例如:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+}
+```
+
+但你也可以宣告多個 Body 參數,例如 `item` 與 `user`:
+
+{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}
+
+在此情況下,**FastAPI** 會注意到函式中有多個 Body 參數(有兩個參數是 Pydantic 模型)。
+
+因此,它會使用參數名稱作為 body 中的鍵(欄位名稱),並期望如下的主體:
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ }
+}
+```
+
+/// note | 注意
+
+儘管 `item` 的宣告方式與先前相同,現在預期它會位於 body 內,且鍵為 `item`。
+
+///
+
+**FastAPI** 會自動從請求中進行轉換,讓參數 `item` 收到對應內容,`user` 亦同。
+
+它會對複合資料進行驗證,並在 OpenAPI 結構與自動文件中如此描述。
+
+## Body 中的單一值 { #singular-values-in-body }
+
+就像你可以用 `Query` 與 `Path` 為查詢與路徑參數定義額外資訊一樣,**FastAPI** 也提供對應的 `Body`。
+
+例如,延伸前述模型,你可以決定在相同的 Body 中,除了 `item` 與 `user` 外,還要有另一個鍵 `importance`。
+
+如果直接這樣宣告,因為它是單一值,**FastAPI** 會將其視為查詢參數。
+
+但你可以使用 `Body` 指示 **FastAPI** 將其視為另一個 Body 鍵:
+
+{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
+
+在此情況下,**FastAPI** 會期望如下的主體:
+
+```JSON
+{
+ "item": {
+ "name": "Foo",
+ "description": "The pretender",
+ "price": 42.0,
+ "tax": 3.2
+ },
+ "user": {
+ "username": "dave",
+ "full_name": "Dave Grohl"
+ },
+ "importance": 5
+}
+```
+
+同樣地,它會進行型別轉換、驗證、文件化等。
+
+## 多個 Body 參數與 Query { #multiple-body-params-and-query }
+
+當然,你也可以在任何 Body 參數之外,視需要宣告額外的查詢參數。
+
+由於預設情況下,單一值會被解讀為查詢參數,你不必明確使用 `Query`,直接這樣寫即可:
+
+```Python
+q: str | None = None
+```
+
+例如:
+
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
+
+/// info | 注意
+
+`Body` 也具有與 `Query`、`Path` 以及之後你會看到的其他工具相同的額外驗證與中繼資料參數。
+
+///
+
+## 嵌入單一 Body 參數 { #embed-a-single-body-parameter }
+
+假設你只有一個來自 Pydantic 模型 `Item` 的單一 `item` Body 參數。
+
+預設情況下,**FastAPI** 會直接期望該模型的內容作為請求主體。
+
+但如果你想讓它像宣告多個 Body 參數時那樣,期望一個帶有 `item` 鍵、其內含模型內容的 JSON,你可以使用 `Body` 的特殊參數 `embed`:
+
+```Python
+item: Item = Body(embed=True)
+```
+
+如下:
+
+{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}
+
+在此情況下 **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
+}
+```
+
+## 小結 { #recap }
+
+即便一個請求只能有單一主體,你仍可在你的路徑操作函式中宣告多個 Body 參數。
+
+但 **FastAPI** 會處理好這一切,在你的函式中提供正確的資料,並在路徑操作中驗證與文件化正確的結構。
+
+你也可以將單一值宣告為 Body 的一部分來接收。
+
+即使只宣告了一個參數,也可以指示 **FastAPI** 將 Body 以某個鍵進行嵌入。
diff --git a/docs/zh-hant/docs/tutorial/body-nested-models.md b/docs/zh-hant/docs/tutorial/body-nested-models.md
new file mode 100644
index 0000000000000..f7b8627b4b80c
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/body-nested-models.md
@@ -0,0 +1,220 @@
+# Body - 巢狀模型 { #body-nested-models }
+
+使用 **FastAPI**,你可以定義、驗證、文件化,並使用任意深度的巢狀模型(感謝 Pydantic)。
+
+## 列表欄位 { #list-fields }
+
+你可以將屬性定義為某個子型別。例如,Python 的 `list`:
+
+{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}
+
+這會讓 `tags` 成為一個列表,儘管尚未宣告列表元素的型別。
+
+## 具有型別參數的列表欄位 { #list-fields-with-type-parameter }
+
+不過,Python 有一種專門的方式來宣告具有內部型別(「型別參數」)的列表:
+
+### 宣告帶有型別參數的 `list` { #declare-a-list-with-a-type-parameter }
+
+要宣告具有型別參數(內部型別)的型別,例如 `list`、`dict`、`tuple`,使用方括號 `[` 與 `]` 傳入內部型別作為「型別參數」:
+
+```Python
+my_list: list[str]
+```
+
+以上都是標準的 Python 型別宣告語法。
+
+對於具有內部型別的模型屬性,也使用相同的標準語法。
+
+因此,在我們的範例中,可以讓 `tags` 明確成為「字串的列表」:
+
+{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}
+
+## 集合型別 { #set-types }
+
+但進一步思考後,我們會意識到 `tags` 不應該重覆,應該是唯一的字串。
+
+而 Python 有一種用於唯一元素集合的特殊資料型別:`set`。
+
+因此我們可以將 `tags` 宣告為字串的 `set`:
+
+{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}
+
+這樣一來,即使收到包含重覆資料的請求,也會被轉換為由唯一元素組成的 `set`。
+
+之後只要輸出該資料,即使來源有重覆,也會以唯一元素的 `set` 輸出。
+
+並且也會在註解/文件中相應標示。
+
+## 巢狀模型 { #nested-models }
+
+每個 Pydantic 模型的屬性都有型別。
+
+而該型別本身也可以是另一個 Pydantic 模型。
+
+因此,你可以宣告具有特定屬性名稱、型別與驗證的深度巢狀 JSON「物件」。
+
+而且可以任意深度巢狀。
+
+### 定義子模型 { #define-a-submodel }
+
+例如,我們可以定義一個 `Image` 模型:
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}
+
+### 將子模型作為型別使用 { #use-the-submodel-as-a-type }
+
+然後把它作為某個屬性的型別使用:
+
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}
+
+這表示 **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** 你就能獲得:
+
+- 編輯器支援(自動完成等),即使是巢狀模型
+- 資料轉換
+- 資料驗證
+- 自動產生文件
+
+## 特殊型別與驗證 { #special-types-and-validation }
+
+除了 `str`、`int`、`float` 等一般的單一型別外,你也可以使用繼承自 `str` 的更複雜單一型別。
+
+若要查看所有可用選項,請參閱 [Pydantic 的型別總覽](https://docs.pydantic.dev/latest/concepts/types/)。你會在下一章看到一些範例。
+
+例如,在 `Image` 模型中有一個 `url` 欄位,我們可以將其宣告為 Pydantic 的 `HttpUrl`,而不是 `str`:
+
+{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}
+
+該字串會被檢查是否為有效的 URL,並在 JSON Schema / OpenAPI 中相應註記。
+
+## 具有子模型列表的屬性 { #attributes-with-lists-of-submodels }
+
+你也可以將 Pydantic 模型作為 `list`、`set` 等的子型別使用:
+
+{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}
+
+這會期望(並進行轉換、驗證、文件化等)如下的 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` 鍵現在是一個由 image 物件組成的列表。
+
+///
+
+## 深度巢狀模型 { #deeply-nested-models }
+
+你可以定義任意深度的巢狀模型:
+
+{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}
+
+/// info
+
+請注意,`Offer` 具有一個 `Item` 的列表,而每個 `Item` 又有一個可選的 `Image` 列表。
+
+///
+
+## 純列表的本文 { #bodies-of-pure-lists }
+
+如果你期望的 JSON 本文頂層值是一個 JSON `array`(Python 的 `list`),可以像在 Pydantic 模型中那樣,直接在函式參數上宣告其型別:
+
+```Python
+images: list[Image]
+```
+
+如下所示:
+
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
+
+## 隨處可得的編輯器支援 { #editor-support-everywhere }
+
+你將在各處獲得編輯器支援。
+
+即使是列表中的項目也一樣:
+
+
+
+若直接操作 `dict` 而不是使用 Pydantic 模型,就無法獲得這種等級的編輯器支援。
+
+但你也不必擔心,傳入的 dict 會自動被轉換,而你的輸出也會自動轉換為 JSON。
+
+## 任意 `dict` 的本文 { #bodies-of-arbitrary-dicts }
+
+你也可以將本文宣告為一個 `dict`,其鍵為某種型別、值為另一種型別。
+
+如此一來,你無需事先知道有效的欄位/屬性名稱為何(不像使用 Pydantic 模型時需要)。
+
+這在你想接收尚未預知的鍵時很有用。
+
+---
+
+另一個實用情境是當你希望鍵是其他型別(例如,`int`)時。
+
+這正是我們在此要示範的。
+
+在此情況下,只要是擁有 `int` 鍵且對應 `float` 值的 `dict` 都會被接受:
+
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
+
+/// tip
+
+請記住,JSON 只支援 `str` 作為鍵。
+
+但 Pydantic 具有自動資料轉換。
+
+這表示即使你的 API 用戶端只能以字串作為鍵,只要這些字串是純整數,Pydantic 會自動轉換並驗證它們。
+
+而你作為 `weights` 所接收的 `dict`,實際上會擁有 `int` 鍵與 `float` 值。
+
+///
+
+## 總結 { #recap }
+
+使用 **FastAPI**,你在保持程式碼簡潔優雅的同時,亦可擁有 Pydantic 模型所提供的高度彈性。
+
+同時還具備以下優點:
+
+- 編輯器支援(到處都有自動完成!)
+- 資料轉換(亦即 parsing/serialization)
+- 資料驗證
+- 結構描述(Schema)文件
+- 自動產生文件
diff --git a/docs/zh-hant/docs/tutorial/body-updates.md b/docs/zh-hant/docs/tutorial/body-updates.md
new file mode 100644
index 0000000000000..0d48e28424fa2
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/body-updates.md
@@ -0,0 +1,100 @@
+# Body - 更新 { #body-updates }
+
+## 使用 `PUT` 取代式更新 { #update-replacing-with-put }
+
+要更新一個項目,你可以使用 [HTTP `PUT`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) 操作。
+
+你可以使用 `jsonable_encoder` 將輸入資料轉換為可儲存為 JSON 的資料(例如用於 NoSQL 資料庫)。例如把 `datetime` 轉成 `str`。
+
+{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}
+
+`PUT` 用於接收應該取代現有資料的資料。
+
+### 關於取代的警告 { #warning-about-replacing }
+
+這表示,如果你想用 `PUT` 並在 body 中包含以下內容來更新項目 `bar`:
+
+```Python
+{
+ "name": "Barz",
+ "price": 3,
+ "description": None,
+}
+```
+
+由於這裡沒有包含已儲存的屬性 `"tax": 20.2`,輸入的模型會採用預設值 `"tax": 10.5`。
+
+最終資料會以這個「新的」 `tax` 值 `10.5` 被儲存。
+
+## 使用 `PATCH` 進行部分更新 { #partial-updates-with-patch }
+
+你也可以使用 [HTTP `PATCH`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) 操作來進行*部分*更新。
+
+這表示你只需傳送想要更新的資料,其餘保持不變。
+
+/// note | 注意
+
+`PATCH` 相較於 `PUT` 較少被使用、也較不為人知。
+
+許多團隊甚至在部分更新時也只用 `PUT`。
+
+你可以依需求自由選用,**FastAPI** 不會強制規範。
+
+但本指南會大致示範它們各自的設計用法。
+
+///
+
+### 使用 Pydantic 的 `exclude_unset` 參數 { #using-pydantics-exclude-unset-parameter }
+
+如果要接收部分更新,在 Pydantic 模型的 `.model_dump()` 中使用 `exclude_unset` 參數非常實用。
+
+例如 `item.model_dump(exclude_unset=True)`。
+
+這會產生一個只包含建立 `item` 模型時實際設定過之欄位的 `dict`,不含預設值。
+
+接著你可以用它來生成只包含實際設定(請求中傳來)的資料之 `dict`,省略預設值:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}
+
+### 使用 Pydantic 的 `update` 參數 { #using-pydantics-update-parameter }
+
+接著,你可以用 `.model_copy()` 建立現有模型的副本,並傳入含有要更新資料之 `dict` 到 `update` 參數。
+
+例如 `stored_item_model.model_copy(update=update_data)`:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}
+
+### 部分更新摘要 { #partial-updates-recap }
+
+總結一下,若要套用部分更新,你可以:
+
+*(可選)使用 `PATCH` 取代 `PUT`。
+* 取回已儲存的資料。
+* 將該資料放入一個 Pydantic 模型。
+* 從輸入模型產生一個不含預設值的 `dict`(使用 `exclude_unset`)。
+ * 如此即可只更新使用者實際設定的值,而不會以模型的預設值覆寫已儲存的值。
+* 建立已儲存模型的副本,並以收到的部分更新值更新其屬性(使用 `update` 參數)。
+* 將該副本模型轉成可儲存到資料庫的型別(例如使用 `jsonable_encoder`)。
+ * 這與再次使用模型的 `.model_dump()` 類似,但它會確保(並轉換)所有值為可轉為 JSON 的資料型別,例如把 `datetime` 轉為 `str`。
+* 將資料儲存到資料庫。
+* 回傳更新後的模型。
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *}
+
+/// tip | 提示
+
+其實你也可以在 HTTP `PUT` 操作中使用同一套技巧。
+
+但此處示例使用 `PATCH`,因為它正是為這類情境設計的。
+
+///
+
+/// note | 注意
+
+請注意,輸入的模型依然會被驗證。
+
+因此,如果你希望接收可以省略所有屬性的部分更新,你需要一個所有屬性皆為可選(具預設值或為 `None`)的模型。
+
+為了區分用於更新(全部可選)與用於建立(欄位為必填)的模型,你可以參考 [額外模型](extra-models.md) 中的做法。
+
+///
diff --git a/docs/zh-hant/docs/tutorial/body.md b/docs/zh-hant/docs/tutorial/body.md
new file mode 100644
index 0000000000000..08246f513b9dd
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/body.md
@@ -0,0 +1,164 @@
+# 請求本文 { #request-body }
+
+當你需要從用戶端(例如瀏覽器)將資料傳送到你的 API 時,會把它作為**請求本文**送出。
+
+**請求**本文是用戶端傳給你的 API 的資料。**回應**本文是你的 API 傳回給用戶端的資料。
+
+你的 API 幾乎總是需要傳回**回應**本文。但用戶端不一定每次都要送出**請求本文**,有時只會請求某個路徑,可能帶一些查詢參數,但不會傳送本文。
+
+要宣告**請求**本文,你會使用 [Pydantic](https://docs.pydantic.dev/) 模型,享受其完整的功能與優點。
+
+/// info
+
+要傳送資料,應使用下列其中一種方法:`POST`(最常見)、`PUT`、`DELETE` 或 `PATCH`。
+
+在規範中,於 `GET` 請求中攜帶本文的行為是未定義的。不過,FastAPI 仍支援它,但僅適用於非常複雜/極端的情境。
+
+由於不建議這麼做,使用 Swagger UI 的互動式文件在使用 `GET` 時不會顯示本文的文件,而且中間的代理伺服器也可能不支援。
+
+///
+
+## 匯入 Pydantic 的 `BaseModel` { #import-pydantics-basemodel }
+
+首先,從 `pydantic` 匯入 `BaseModel`:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[2] *}
+
+## 建立你的資料模型 { #create-your-data-model }
+
+接著,你將資料模型宣告為繼承自 `BaseModel` 的類別。
+
+對所有屬性使用標準的 Python 型別:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}
+
+就和宣告查詢參數時一樣,當模型屬性有預設值時,它就不是必填;否則就是必填。使用 `None` 可使其成為選填。
+
+例如,上述模型對應的 JSON「`object`」(或 Python `dict`)如下:
+
+```JSON
+{
+ "name": "Foo",
+ "description": "An optional description",
+ "price": 45.2,
+ "tax": 3.5
+}
+```
+
+...由於 `description` 與 `tax` 是選填(預設為 `None`),以下這個 JSON「`object`」也有效:
+
+```JSON
+{
+ "name": "Foo",
+ "price": 45.2
+}
+```
+
+## 將它宣告為參數 { #declare-it-as-a-parameter }
+
+要把它加到你的*路徑操作(path operation)*中,宣告方式與路徑與查詢參數相同:
+
+{* ../../docs_src/body/tutorial001_py310.py hl[16] *}
+
+...並將其型別宣告為你建立的模型 `Item`。
+
+## 效果 { #results }
+
+只靠這樣的 Python 型別宣告,**FastAPI** 會:
+
+- 將請求本文讀取為 JSON。
+- (必要時)轉換為對應的型別。
+- 驗證資料。
+ - 若資料無效,會回傳清楚易懂的錯誤,指出哪裡、哪筆資料不正確。
+- 把接收到的資料放在參數 `item` 中提供給你。
+ - 由於你在函式中將其宣告為 `Item` 型別,你也會獲得完整的編輯器支援(自動完成等)以及所有屬性與其型別。
+- 為你的模型產生 [JSON Schema](https://json-schema.org) 定義,如有需要,你也可以在專案中的其他地方使用。
+- 這些 schema 會成為產生的 OpenAPI schema 的一部分,並由自動文件 UIs 使用。
+
+## 自動文件 { #automatic-docs }
+
+你的模型的 JSON Schema 會納入產生的 OpenAPI schema,並顯示在互動式 API 文件中:
+
+
+
+也會用於每個需要它們的*路徑操作*內的 API 文件:
+
+
+
+## 編輯器支援 { #editor-support }
+
+在編輯器裡、於你的函式中,你會在各處獲得型別提示與自動完成(如果你接收的是 `dict` 而不是 Pydantic 模型,就不會有這些):
+
+
+
+你也會獲得對不正確型別操作的錯誤檢查:
+
+
+
+這不是偶然,整個框架就是圍繞這個設計而建。
+
+而且在實作之前的設計階段就已徹底測試,確保能在各種編輯器中運作良好。
+
+甚至為了支援這點,Pydantic 本身也做了些修改。
+
+前面的螢幕截圖是使用 [Visual Studio Code](https://code.visualstudio.com) 拍的。
+
+但你在 [PyCharm](https://www.jetbrains.com/pycharm/) 與大多數其它 Python 編輯器中也會得到相同的編輯器支援:
+
+
+
+/// tip
+
+如果你使用 [PyCharm](https://www.jetbrains.com/pycharm/) 作為編輯器,可以安裝 [Pydantic PyCharm Plugin](https://github.com/koxudaxi/pydantic-pycharm-plugin/)。
+
+它能增強 Pydantic 模型的編輯器支援,包含:
+
+- 自動完成
+- 型別檢查
+- 重構
+- 搜尋
+- 程式碼檢查
+
+///
+
+## 使用該模型 { #use-the-model }
+
+在函式內,你可以直接存取模型物件的所有屬性:
+
+{* ../../docs_src/body/tutorial002_py310.py *}
+
+## 請求本文 + 路徑參數 { #request-body-path-parameters }
+
+你可以同時宣告路徑參數與請求本文。
+
+**FastAPI** 會辨識出與路徑參數相符的函式參數應該從**路徑**取得,而宣告為 Pydantic 模型的函式參數應該從**請求本文**取得。
+
+{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}
+
+## 請求本文 + 路徑 + 查詢參數 { #request-body-path-query-parameters }
+
+你也可以同時宣告**本文**、**路徑**與**查詢**參數。
+
+**FastAPI** 會分別辨識並從正確的位置取得資料。
+
+{* ../../docs_src/body/tutorial004_py310.py hl[16] *}
+
+函式參數的辨識方式如下:
+
+- 如果參數同時在**路徑**中宣告,則作為路徑參數。
+- 如果參數是**單一型別**(像是 `int`、`float`、`str`、`bool` 等),會被視為**查詢**參數。
+- 如果參數宣告為 **Pydantic 模型** 型別,會被視為請求**本文**。
+
+/// note
+
+FastAPI 會因為預設值 `= None` 而知道 `q` 的值不是必填。
+
+`str | None` 並非 FastAPI 用來判斷是否必填的依據;它會因為有預設值 `= None` 而知道不是必填。
+
+但加入這些型別註解能讓你的編輯器提供更好的支援與錯誤偵測。
+
+///
+
+## 不使用 Pydantic { #without-pydantic }
+
+若你不想使用 Pydantic 模型,也可以使用 **Body** 參數。請參考[Body - 多個參數:本文中的單一值](body-multiple-params.md#singular-values-in-body)。
diff --git a/docs/zh-hant/docs/tutorial/cookie-param-models.md b/docs/zh-hant/docs/tutorial/cookie-param-models.md
new file mode 100644
index 0000000000000..8997903e38cfc
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/cookie-param-models.md
@@ -0,0 +1,76 @@
+# Cookie 參數模型 { #cookie-parameter-models }
+
+如果你有一組彼此相關的「**Cookie**」,你可以建立一個「**Pydantic 模型**」來宣告它們。🍪
+
+這樣你就能在**多處**重複使用該模型,並且能一次性為所有參數宣告**驗證**與**中繼資料**。😎
+
+/// note | 注意
+
+自 FastAPI 版本 `0.115.0` 起支援。🤓
+
+///
+
+/// tip
+
+同樣的技巧也適用於 `Query`、`Cookie` 與 `Header`。😎
+
+///
+
+## 以 Pydantic 模型宣告 Cookie { #cookies-with-a-pydantic-model }
+
+在 **Pydantic 模型**中宣告所需的 **Cookie** 參數,接著將參數宣告為 `Cookie`:
+
+{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}
+
+**FastAPI** 會從請求收到的 **Cookie** 中擷取 **每個欄位** 的資料,並交給你定義的 Pydantic 模型。
+
+## 查看文件 { #check-the-docs }
+
+你可以在 `/docs` 的文件介面中看到已定義的 Cookie:
+
+
+
+
+---
+
+如果你使用 PyCharm,你可以:
+
+* 開啟 "Run" 選單
+* 選擇 "Debug..."
+* 會出現一個情境選單
+* 選擇要偵錯的檔案(此例為 `main.py`)
+
+接著它會用你的 **FastAPI** 程式碼啟動伺服器、在你的中斷點停下等。
+
+可能會長這樣:
+
+
diff --git a/docs/zh-hant/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/zh-hant/docs/tutorial/dependencies/classes-as-dependencies.md
new file mode 100644
index 0000000000000..34b873210983b
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/dependencies/classes-as-dependencies.md
@@ -0,0 +1,288 @@
+# 以類別作為相依性 { #classes-as-dependencies }
+
+在更深入了解 **相依性注入(Dependency Injection)** 系統之前,我們先把前一個範例升級一下。
+
+## 前一個範例中的 `dict` { #a-dict-from-the-previous-example }
+
+在前一個範例中,我們從相依項("dependable")回傳了一個 `dict`:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *}
+
+但接著我們在路徑操作函式(*path operation function*)的參數 `commons` 中取得的是一個 `dict`。
+
+而我們知道,編輯器對 `dict` 無法提供太多輔助(例如自動完成),因為它無法預先知道其中的鍵與值的型別。
+
+我們可以做得更好...
+
+## 什麼算是相依性 { #what-makes-a-dependency }
+
+到目前為止,你看到的相依性都是宣告成函式。
+
+但那不是宣告相依性的唯一方式(雖然那大概是最常見的)。
+
+關鍵在於,相依性應該要是「callable」。
+
+在 Python 中,「**callable**」指的是任何可以像函式一樣被 Python「呼叫」的東西。
+
+因此,如果你有一個物件 `something`(它可能不是函式),而你可以像這樣「呼叫」(執行)它:
+
+```Python
+something()
+```
+
+或是
+
+```Python
+something(some_argument, some_keyword_argument="foo")
+```
+
+那它就是一個「callable」。
+
+## 以類別作為相依性 { #classes-as-dependencies_1 }
+
+你可能已經注意到,建立一個 Python 類別的實例時,你用的語法也是一樣的。
+
+例如:
+
+```Python
+class Cat:
+ def __init__(self, name: str):
+ self.name = name
+
+
+fluffy = Cat(name="Mr Fluffy")
+```
+
+在這個例子中,`fluffy` 是 `Cat` 類別的一個實例。
+
+而要建立 `fluffy`,你其實是在「呼叫」`Cat`。
+
+所以,Python 類別本身也是一種 **callable**。
+
+因此,在 **FastAPI** 中,你可以將 Python 類別作為相依性。
+
+FastAPI 其實檢查的是它是否為「callable」(函式、類別或其他),以及它所定義的參數。
+
+如果你在 **FastAPI** 中傳入一個「callable」作為相依性,FastAPI 會分析該「callable」的參數,並以與路徑操作函式參數相同的方式來處理它們,包括子相依性。
+
+這也適用於完全沒有參數的 callable,就和沒有參數的路徑操作函式一樣。
+
+接著,我們可以把上面的相依項(dependable)`common_parameters` 改成類別 `CommonQueryParams`:
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *}
+
+注意用來建立該類別實例的 `__init__` 方法:
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *}
+
+...它的參數與我們之前的 `common_parameters` 相同:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *}
+
+**FastAPI** 會用這些參數來「解析」該相依性。
+
+兩種情況下都會有:
+
+- 一個可選的查詢參數 `q`,型別為 `str`。
+- 一個查詢參數 `skip`,型別為 `int`,預設為 `0`。
+- 一個查詢參數 `limit`,型別為 `int`,預設為 `100`。
+
+兩種情況下,資料都會被轉換、驗證,並記錄到 OpenAPI schema 中等。
+
+## 如何使用 { #use-it }
+
+現在你可以用這個類別來宣告你的相依性。
+
+{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *}
+
+**FastAPI** 會呼叫 `CommonQueryParams` 類別。這會建立該類別的一個「實例」,而該實例會以參數 `commons` 的形式傳給你的函式。
+
+## 型別註解與 `Depends` { #type-annotation-vs-depends }
+
+注意上面程式碼裡我們寫了兩次 `CommonQueryParams`:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ 非 Annotated
+
+/// tip
+
+如有可能,優先使用 `Annotated` 版本。
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+最後面的 `CommonQueryParams`,在:
+
+```Python
+... Depends(CommonQueryParams)
+```
+
+...才是 **FastAPI** 實際用來知道相依性是什麼的依據。
+
+FastAPI 會從這個物件中提取宣告的參數,並且實際呼叫它。
+
+---
+
+在這個例子中,前面的 `CommonQueryParams`,於:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, ...
+```
+
+////
+
+//// tab | Python 3.10+ 非 Annotated
+
+/// tip
+
+如有可能,優先使用 `Annotated` 版本。
+
+///
+
+```Python
+commons: CommonQueryParams ...
+```
+
+////
+
+...對 **FastAPI** 來說沒有任何特殊意義。FastAPI 不會用它來做資料轉換、驗證等(因為這部分由 `Depends(CommonQueryParams)` 處理)。
+
+其實你可以只寫:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[Any, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ 非 Annotated
+
+/// tip
+
+如有可能,優先使用 `Annotated` 版本。
+
+///
+
+```Python
+commons = Depends(CommonQueryParams)
+```
+
+////
+
+...像是:
+
+{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *}
+
+但仍建議宣告型別,這樣你的編輯器就知道會以何種型別作為參數 `commons` 傳入,進而幫助你做自動完成、型別檢查等:
+
+
+
+## 捷徑 { #shortcut }
+
+不過你會發現這裡有些重複程式碼,我們寫了兩次 `CommonQueryParams`:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ 非 Annotated
+
+/// tip
+
+如有可能,優先使用 `Annotated` 版本。
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+**FastAPI** 為這類情況提供了一個捷徑:當相依性「明確」是一個類別,且 **FastAPI** 會「呼叫」它來建立該類別的實例時。
+
+對這些特定情況,你可以這樣做:
+
+不要寫:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ 非 Annotated
+
+/// tip
+
+如有可能,優先使用 `Annotated` 版本。
+
+///
+
+```Python
+commons: CommonQueryParams = Depends(CommonQueryParams)
+```
+
+////
+
+...而是改為:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends()]
+```
+
+////
+
+//// tab | Python 3.10+ 非 Annotated
+
+/// tip
+
+如有可能,優先使用 `Annotated` 版本。
+
+///
+
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
+
+你把相依性宣告為參數的型別,並使用不帶任何參數的 `Depends()`,而不用在 `Depends(CommonQueryParams)` 裡「再」寫一次整個類別。
+
+整個範例就會變成:
+
+{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *}
+
+...而 **FastAPI** 會知道該怎麼做。
+
+/// tip
+
+如果你覺得這樣比幫助更令人困惑,那就忽略它吧,你並不「需要」這個技巧。
+
+這只是個捷徑。因為 **FastAPI** 在意幫你減少重複的程式碼。
+
+///
diff --git a/docs/zh-hant/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/zh-hant/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
new file mode 100644
index 0000000000000..bd5711624581f
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -0,0 +1,69 @@
+# 路徑操作裝飾器中的依賴 { #dependencies-in-path-operation-decorators }
+
+有時在你的路徑操作函式中,其實不需要某個依賴的回傳值。
+
+或是該依賴根本沒有回傳值。
+
+但你仍需要它被執行/解析。
+
+這種情況下,你可以不在路徑操作函式的參數上使用 `Depends`,而是在路徑操作裝飾器加入一個 `dependencies` 的 `list`。
+
+## 在路徑操作裝飾器加入 `dependencies` { #add-dependencies-to-the-path-operation-decorator }
+
+路徑操作裝飾器可接受一個可選參數 `dependencies`。
+
+它應該是由 `Depends()` 組成的 `list`:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
+
+這些依賴會以與一般依賴相同的方式被執行/解析。但它們的值(如果有回傳)不會傳遞給你的路徑操作函式。
+
+/// tip
+
+有些編輯器會檢查未使用的函式參數,並將其標示為錯誤。
+
+把這些依賴放在路徑操作裝飾器中,可以確保它們被執行,同時避免編輯器/工具報錯。
+
+這也有助於避免讓新加入的開發者看到未使用的參數時,以為它是不必要的而感到困惑。
+
+///
+
+/// info
+
+在這個範例中我們使用了自訂的(虛構的)標頭 `X-Key` 與 `X-Token`。
+
+但在實際情況下,當你實作安全機制時,使用整合的 [Security utilities(下一章)](../security/index.md) 會獲得更多好處。
+
+///
+
+## 依賴的錯誤與回傳值 { #dependencies-errors-and-return-values }
+
+你可以使用與平常相同的依賴函式。
+
+### 依賴的需求 { #dependency-requirements }
+
+它們可以宣告請求需求(例如標頭(headers))或其他子依賴:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
+
+### 拋出例外 { #raise-exceptions }
+
+這些依賴可以 `raise` 例外,與一般依賴相同:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
+
+### 回傳值 { #return-values }
+
+它們可以回傳值,也可以不回傳;無論如何,回傳值都不會被使用。
+
+因此,你可以重複使用在其他地方已使用過的一般依賴(會回傳值),即使回傳值不會被使用,該依賴仍會被執行:
+
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
+
+## 一組路徑操作的依賴 { #dependencies-for-a-group-of-path-operations }
+
+之後在閱讀如何組織較大的應用程式([較大型應用程式——多個檔案](../../tutorial/bigger-applications.md))時,你會學到如何為一組路徑操作宣告一個共同的 `dependencies` 參數。
+
+## 全域依賴 { #global-dependencies }
+
+接著我們會看看如何把依賴加到整個 `FastAPI` 應用程式,使其套用到每個路徑操作。
diff --git a/docs/zh-hant/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh-hant/docs/tutorial/dependencies/dependencies-with-yield.md
new file mode 100644
index 0000000000000..8174dca40bd8d
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -0,0 +1,288 @@
+# 使用 yield 的相依 { #dependencies-with-yield }
+
+FastAPI 支援在完成後執行一些額外步驟的相依。
+
+要做到這點,使用 `yield` 取代 `return`,並把額外步驟(程式碼)寫在其後。
+
+/// tip
+
+請確保每個相依內只使用一次 `yield`。
+
+///
+
+/// note | 技術細節
+
+任何可用於下列裝飾器的函式:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) 或
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+都可以作為 **FastAPI** 的相依。
+
+事實上,FastAPI 內部就是使用這兩個裝飾器。
+
+///
+
+## 使用 `yield` 的資料庫相依 { #a-database-dependency-with-yield }
+
+例如,你可以用它建立一個資料庫 session,並在完成後關閉。
+
+只有 `yield` 之前(含 `yield` 本身)的程式碼會在產生回應之前執行:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
+
+由 `yield` 產生的值會被注入到路徑操作(path operation)與其他相依中:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
+
+位於 `yield` 之後的程式碼會在回應之後執行:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
+
+/// tip
+
+你可以使用 `async` 或一般函式。
+
+**FastAPI** 都會正確處理,和一般相依相同。
+
+///
+
+## 同時使用 `yield` 與 `try` 的相依 { #a-dependency-with-yield-and-try }
+
+如果在含 `yield` 的相依中使用 `try` 區塊,你會接收到使用該相依時拋出的任何例外。
+
+例如,如果在中途的某段程式碼、其他相依,或某個路徑操作中,讓資料庫交易「rollback」或產生了任何例外,你都會在你的相依中接收到該例外。
+
+因此,你可以在相依內用 `except SomeException` 來攔截特定例外。
+
+同樣地,你可以使用 `finally` 來確保無論是否有例外都會執行結束步驟。
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
+
+## 含 `yield` 的子相依 { #sub-dependencies-with-yield }
+
+你可以擁有任何大小與形狀的子相依與相依樹,而它們都可以(或不)使用 `yield`。
+
+**FastAPI** 會確保每個使用 `yield` 的相依,其「結束程式碼」會以正確的順序執行。
+
+例如,`dependency_c` 可以相依於 `dependency_b`,而 `dependency_b` 相依於 `dependency_a`:
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
+
+而且它們都可以使用 `yield`。
+
+在這個例子中,`dependency_c` 為了執行它的結束程式碼,需要來自 `dependency_b`(此處命名為 `dep_b`)的值仍然可用。
+
+同理,`dependency_b` 為了執行它的結束程式碼,需要來自 `dependency_a`(此處命名為 `dep_a`)的值可用。
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
+
+同樣地,你可以同時擁有使用 `yield` 的相依與使用 `return` 的相依,並讓其中一些相依彼此相依。
+
+你也可以有一個相依同時需要多個使用 `yield` 的其他相依,等等。
+
+你可以擁有任何你需要的相依組合。
+
+**FastAPI** 會確保一切都以正確的順序執行。
+
+/// note | 技術細節
+
+這能運作,多虧了 Python 的 [Context Managers](https://docs.python.org/3/library/contextlib.html)。
+
+**FastAPI** 在內部使用它們來達成這點。
+
+///
+
+## 含 `yield` 與 `HTTPException` 的相依 { #dependencies-with-yield-and-httpexception }
+
+你已看到可以在含 `yield` 的相依中使用 `try` 區塊,嘗試執行一些程式碼,然後在 `finally` 後執行結束程式碼。
+
+你也可以用 `except` 來攔截被拋出的例外並加以處理。
+
+例如,你可以拋出不同的例外,如 `HTTPException`。
+
+/// tip
+
+這算是進階技巧;多數情況你並不需要,因為你可以在應用程式其他程式碼中(例如在路徑操作函式(path operation function)中)直接拋出例外(包含 `HTTPException`)。
+
+但如果你需要,它就在這裡。🤓
+
+///
+
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
+
+如果你想攔截例外並據此回傳自訂回應,請建立一個[自訂例外處理器](../handling-errors.md#install-custom-exception-handlers)。
+
+## 含 `yield` 與 `except` 的相依 { #dependencies-with-yield-and-except }
+
+如果你在含 `yield` 的相依中用 `except` 攔截了例外,且沒有再次拋出它(或拋出新的例外),FastAPI 將無法察覺有例外發生,就像在一般的 Python 中一樣:
+
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
+
+在這種情況下,客戶端會如預期地看到一個 *HTTP 500 Internal Server Error* 回應(因為我們沒有拋出 `HTTPException` 或類似的東西),但伺服器將不會有任何日誌或其他錯誤線索。😱
+
+### 在含 `yield` 與 `except` 的相依中務必 `raise` { #always-raise-in-dependencies-with-yield-and-except }
+
+如果你在含 `yield` 的相依中攔截到了例外,除非你要拋出另一個 `HTTPException` 或類似的例外,否則**你應該重新拋出原本的例外**。
+
+你可以使用 `raise` 重新拋出同一個例外:
+
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
+
+現在客戶端仍會獲得同樣的 *HTTP 500 Internal Server Error* 回應,但伺服器的日誌中會有我們自訂的 `InternalError`。😎
+
+## 含 `yield` 的相依執行順序 { #execution-of-dependencies-with-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,operation: Can raise exceptions, including HTTPException
+ client ->> dep: Start request
+ Note over dep: Run code up to yield
+ opt raise Exception
+ dep -->> handler: Raise Exception
+ handler -->> client: HTTP error response
+ end
+ dep ->> operation: Run dependency, e.g. DB session
+ opt raise
+ operation -->> dep: Raise Exception (e.g. HTTPException)
+ opt handle
+ dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception
+ end
+ handler -->> client: HTTP error response
+ 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 -->> tasks: Handle exceptions in the background task code
+ end
+```
+
+/// info
+
+只會向用戶端送出「一個回應」。可能是其中一個錯誤回應,或是來自該路徑操作的回應。
+
+一旦送出了其中一個回應,就不能再送出其他回應。
+
+///
+
+/// tip
+
+如果你在路徑操作函式的程式碼中拋出任何例外,它會被傳遞到使用 `yield` 的相依中(包含 `HTTPException`)。大多數情況你會想在該使用 `yield` 的相依中重新拋出相同的例外或一個新的例外,以確保它被正確處理。
+
+///
+
+## 提早關閉與 `scope` { #early-exit-and-scope }
+
+通常,含 `yield` 的相依之結束程式碼會在回應送出給用戶端之後才執行。
+
+但如果你確定在從路徑操作函式返回後就不會再使用該相依,你可以使用 `Depends(scope="function")`,告訴 FastAPI 應在路徑操作函式返回之後、但在回應送出之前關閉該相依。
+
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
+
+`Depends()` 接受一個 `scope` 參數,可以是:
+
+* `"function"`:在處理請求的路徑操作函式之前啟動相依,在路徑操作函式結束之後結束相依,但在回應送回用戶端之前。所以,相依函式會在路徑操作**函式**的「周圍」執行。
+* `"request"`:在處理請求的路徑操作函式之前啟動相依(與使用 `"function"` 類似),但在回應送回用戶端之後才結束相依。所以,相依函式會在整個**請求**與回應循環的「周圍」執行。
+
+如果未指定且相依使用了 `yield`,則預設 `scope` 為 `"request"`。
+
+### 子相依的 `scope` { #scope-for-sub-dependencies }
+
+當你宣告一個 `scope="request"`(預設值)的相依時,任何子相依也需要有 `"request"` 的 `scope`。
+
+但一個 `scope` 為 `"function"` 的相依,可以擁有 `scope` 為 `"function"` 或 `"request"` 的子相依。
+
+這是因為任何相依都需要能在子相依之前執行其結束程式碼,因為它可能在結束程式碼中仍需要使用那些子相依。
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant dep_req as Dep scope="request"
+participant dep_func as Dep scope="function"
+participant operation as Path Operation
+
+ client ->> dep_req: Start request
+ Note over dep_req: Run code up to yield
+ dep_req ->> dep_func: Pass dependency
+ Note over dep_func: Run code up to yield
+ dep_func ->> operation: Run path operation with dependency
+ operation ->> dep_func: Return from path operation
+ Note over dep_func: Run code after yield
+ Note over dep_func: ✅ Dependency closed
+ dep_func ->> client: Send response to client
+ Note over client: Response sent
+ Note over dep_req: Run code after yield
+ Note over dep_req: ✅ Dependency closed
+```
+
+## 含 `yield`、`HTTPException`、`except` 與背景任務的相依 { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+含 `yield` 的相依隨時間演進,以涵蓋不同的使用情境並修正一些問題。
+
+如果你想了解在不同 FastAPI 版本中改了哪些內容,可以在進階指南中閱讀:[進階相依 — 含 `yield`、`HTTPException`、`except` 與背景任務的相依](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks)。
+## 情境管理器 { #context-managers }
+
+### 什麼是「情境管理器」 { #what-are-context-managers }
+
+「情境管理器」是那些你可以在 `with` 陳述式中使用的 Python 物件。
+
+例如,[你可以用 `with` 來讀取檔案](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files):
+
+```Python
+with open("./somefile.txt") as f:
+ contents = f.read()
+ print(contents)
+```
+
+在底層,`open("./somefile.txt")` 會建立一個稱為「情境管理器」的物件。
+
+當 `with` 區塊結束時,它會確保關閉檔案,即使發生了例外也一樣。
+
+當你建立一個含 `yield` 的相依時,**FastAPI** 會在內部為它建立一個情境管理器,並與其他相關工具結合。
+
+### 在含 `yield` 的相依中使用情境管理器 { #using-context-managers-in-dependencies-with-yield }
+
+/// warning
+
+這大致算是一個「進階」概念。
+
+如果你剛開始學習 **FastAPI**,此處可以先跳過。
+
+///
+
+在 Python 中,你可以透過[建立一個擁有 `__enter__()` 與 `__exit__()` 兩個方法的類別](https://docs.python.org/3/reference/datamodel.html#context-managers)來建立情境管理器。
+
+你也可以在 **FastAPI** 的含 `yield` 相依中,於相依函式內使用 `with` 或 `async with` 陳述式來使用它們:
+
+{* ../../docs_src/dependencies/tutorial010_py310.py hl[1:9,13] *}
+
+/// tip
+
+建立情境管理器的另一種方式是:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) 或
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+用它們裝飾一個只包含單一 `yield` 的函式。
+
+這正是 **FastAPI** 在內部為含 `yield` 的相依所使用的方法。
+
+但你不需要(而且也不該)在 FastAPI 的相依上使用這些裝飾器。
+
+FastAPI 會在內部替你處理好。
+
+///
diff --git a/docs/zh-hant/docs/tutorial/dependencies/global-dependencies.md b/docs/zh-hant/docs/tutorial/dependencies/global-dependencies.md
new file mode 100644
index 0000000000000..e73cf935e23ab
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/dependencies/global-dependencies.md
@@ -0,0 +1,15 @@
+# 全域依賴 { #global-dependencies }
+
+在某些類型的應用程式中,你可能想為整個應用程式新增依賴。
+
+類似於你可以在[路徑操作(path operation)的裝飾器中新增 `dependencies`](dependencies-in-path-operation-decorators.md) 的方式,你也可以把它們加到 `FastAPI` 應用程式上。
+
+在這種情況下,它們會套用到應用程式中的所有路徑操作:
+
+{* ../../docs_src/dependencies/tutorial012_an_py310.py hl[17] *}
+
+而且,在[將 `dependencies` 新增到路徑操作裝飾器](dependencies-in-path-operation-decorators.md) 那一節中的所有概念依然適用,只是這裡是套用到整個應用中的所有路徑操作。
+
+## 路徑操作群組的依賴 { #dependencies-for-groups-of-path-operations }
+
+之後,在閱讀如何組織更大的應用程式([更大的應用程式 - 多個檔案](../../tutorial/bigger-applications.md))時,可能會有多個檔案,你將會學到如何為一組路徑操作宣告單一的 `dependencies` 參數。
diff --git a/docs/zh-hant/docs/tutorial/dependencies/index.md b/docs/zh-hant/docs/tutorial/dependencies/index.md
new file mode 100644
index 0000000000000..86aea50f0a694
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/dependencies/index.md
@@ -0,0 +1,248 @@
+# 依賴 { #dependencies }
+
+**FastAPI** 內建一套強大且直覺的 **依賴注入** 系統。
+
+它被設計為易於使用,使任何開發者都能輕鬆將其他元件與 **FastAPI** 整合。
+
+## 什麼是「依賴注入」 { #what-is-dependency-injection }
+
+在程式設計中,「依賴注入」的意思是:你的程式碼(此處指你的「路徑操作函式 (path operation functions)」)可以宣告它為了正常運作所需要的各種東西:也就是「依賴」。
+
+接著,這個系統(此處是 **FastAPI**)會負責做任何必要的事,將這些所需的依賴提供給你的程式碼(「注入」依賴)。
+
+當你需要以下情境時,這特別有用:
+
+* 共享邏輯(相同的邏輯一次又一次地使用)。
+* 共用資料庫連線。
+* 強制套用安全性、驗證、角色要求等。
+* 以及許多其他事情...
+
+同時把重複的程式碼降到最低。
+
+## 入門 { #first-steps }
+
+先看一個非常簡單的範例。它現在還不太實用,但夠簡單,讓我們能專注在 **依賴注入** 的運作方式。
+
+### 建立一個依賴,或稱「dependable」 { #create-a-dependency-or-dependable }
+
+先專注在依賴本身。
+
+它就是一個函式,可以接受與「路徑操作函式」相同的各種參數:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}
+
+就這樣。
+
+僅僅兩行。
+
+而且它的外觀與結構和你的所有「路徑操作函式」一樣。
+
+你可以把它想成一個沒有「裝飾器」(沒有 `@app.get("/some-path")`)的「路徑操作函式」。
+
+它可以回傳你想要的任何東西。
+
+在這個例子中,這個依賴會期望:
+
+* 一個選用的查詢參數 `q`,型別為 `str`。
+* 一個選用的查詢參數 `skip`,型別為 `int`,預設為 `0`。
+* 一個選用的查詢參數 `limit`,型別為 `int`,預設為 `100`。
+
+然後它只會回傳一個包含這些值的 `dict`。
+
+/// info | 說明
+
+FastAPI 在 0.95.0 版新增了對 `Annotated` 的支援(並開始建議使用)。
+
+如果你使用較舊的版本,嘗試使用 `Annotated` 時會出現錯誤。
+
+在使用 `Annotated` 之前,請先[升級 FastAPI 版本](../../deployment/versions.md#upgrading-the-fastapi-versions)到至少 0.95.1。
+
+///
+
+### 匯入 `Depends` { #import-depends }
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}
+
+### 在「被依賴者」(dependant)中宣告依賴 { #declare-the-dependency-in-the-dependant }
+
+和你在「路徑操作函式」參數上使用 `Body`、`Query` 等方式一樣,針對新參數使用 `Depends`:
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}
+
+雖然你在函式參數上使用 `Depends` 的方式和 `Body`、`Query` 等相同,但 `Depends` 的運作方式有點不同。
+
+你只需要傳給 `Depends` 一個參數。
+
+這個參數必須是類似函式的東西。
+
+你不需要直接呼叫它(不要在後面加上括號),只要把它作為參數傳給 `Depends()` 即可。
+
+而該函式的參數宣告方式與「路徑操作函式」相同。
+
+/// tip | 提示
+
+除了函式之外,還有其他「東西」也能當作依賴,會在下一章介紹。
+
+///
+
+當有新的請求到達時,**FastAPI** 會負責:
+
+* 以正確的參數呼叫你的依賴(dependable)函式。
+* 取得該函式的回傳結果。
+* 將結果指定給你的「路徑操作函式」中的對應參數。
+
+```mermaid
+graph TB
+
+common_parameters(["common_parameters"])
+read_items["/items/"]
+read_users["/users/"]
+
+common_parameters --> read_items
+common_parameters --> read_users
+```
+
+如此一來,你只需撰寫一次共用程式碼,**FastAPI** 會替你的各個「路徑操作」呼叫它。
+
+/// check | 檢查
+
+注意,你不必建立特殊的類別並把它傳到 **FastAPI** 去「註冊」或做類似的事。
+
+只要把它傳給 `Depends`,**FastAPI** 就知道該怎麼處理其餘的部分。
+
+///
+
+## 共用 `Annotated` 依賴 { #share-annotated-dependencies }
+
+在上面的範例中,可以看到有一點點的「重複程式碼」。
+
+當你要使用 `common_parameters()` 這個依賴時,你得寫出完整的型別註解搭配 `Depends()`:
+
+```Python
+commons: Annotated[dict, Depends(common_parameters)]
+```
+
+但因為我們在使用 `Annotated`,我們可以把這個 `Annotated` 的值存到一個變數中,並在多個地方重複使用:
+
+{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}
+
+/// tip | 提示
+
+這只是標準的 Python,用的是所謂的「型別別名 (type alias)」,其實和 **FastAPI** 本身無關。
+
+但因為 **FastAPI** 是建立在 Python 標準之上(包含 `Annotated`),你就可以在程式碼中使用這個技巧。😎
+
+///
+
+這些依賴依然會如預期運作,而最棒的是「型別資訊會被保留」,代表你的編輯器仍能提供「自動完成」、「即時錯誤」等功能,像 `mypy` 等其他工具也一樣受益。
+
+當你在「大型程式碼庫」中,於許多「路徑操作」反覆使用「相同的依賴」時,這會特別有用。
+
+## 要不要使用 `async` { #to-async-or-not-to-async }
+
+因為依賴也會由 **FastAPI** 呼叫(就像你的「路徑操作函式」),所以在定義函式時套用相同的規則。
+
+你可以使用 `async def` 或一般的 `def`。
+
+而且你可以在一般 `def` 的「路徑操作函式」中宣告 `async def` 的依賴,或在 `async def` 的「路徑操作函式」中宣告 `def` 的依賴,等等。
+
+都沒關係。**FastAPI** 會知道該怎麼做。
+
+/// note | 注意
+
+如果你不熟悉,請參考文件中的 [Async: "In a hurry?"](../../async.md#in-a-hurry) 一節,瞭解 `async` 與 `await`。
+
+///
+
+## 與 OpenAPI 整合 { #integrated-with-openapi }
+
+你的依賴(以及其子依賴)所宣告的所有請求參數、驗證與需求,都會整合進同一份 OpenAPI 結構中。
+
+因此,互動式文件也會包含來自這些依賴的所有資訊:
+
+
+
+## 簡單用法 { #simple-usage }
+
+想一想,「路徑操作函式」是宣告好讓框架在「路徑」與「操作」符合時使用的,然後 **FastAPI** 會負責帶入正確的參數、從請求中擷取資料,並呼叫該函式。
+
+其實,所有(或大多數)Web 框架都是這樣運作。
+
+你從不會直接呼叫這些函式。它們是由框架(此處是 **FastAPI**)呼叫的。
+
+透過依賴注入系統,你也可以告訴 **FastAPI**:你的「路徑操作函式」還「依賴」其他東西,應在你的「路徑操作函式」之前執行,**FastAPI** 會負責執行它並「注入」其結果。
+
+這個「依賴注入」概念的其他常見稱呼包括:
+
+* 資源
+* 提供者
+* 服務
+* 可注入項
+* 元件
+
+## **FastAPI** 外掛 { #fastapi-plug-ins }
+
+各種整合與「外掛」都能以 **依賴注入** 系統來構建。但事實上,並不需要真的去打造「外掛」,因為透過依賴,你可以宣告無數的整合與互動,並讓它們供你的「路徑操作函式」使用。
+
+而且依賴可以用非常簡單直覺的方式建立,你只需要匯入所需的 Python 套件,然後用幾行程式碼就能把它們與你的 API 函式整合,真的是「只要幾行」。
+
+在接下來的章節中你會看到這方面的例子,例如關聯式與 NoSQL 資料庫、安全性等。
+
+## **FastAPI** 相容性 { #fastapi-compatibility }
+
+依賴注入系統的簡潔,使 **FastAPI** 能與以下事物相容:
+
+* 所有關聯式資料庫
+* NoSQL 資料庫
+* 外部套件
+* 外部 API
+* 驗證與授權系統
+* API 使用監控系統
+* 回應資料注入系統
+* 等等
+
+## 簡單而強大 { #simple-and-powerful }
+
+雖然階層式的依賴注入系統相當容易定義與使用,但它依然非常強大。
+
+你可以定義會進一步依賴其他依賴的依賴。
+
+最終會形成一棵階層式的依賴樹,而 **依賴注入** 系統會負責為你解決所有這些依賴(以及它們的子依賴),並在每一步提供(注入)對應的結果。
+
+例如,假設你有 4 個 API 端點(「路徑操作」):
+
+* `/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** 整合 { #integrated-with-openapi_1 }
+
+所有這些依賴在宣告其需求的同時,也會為你的「路徑操作」新增參數、驗證等。
+
+**FastAPI** 會負責把這一切加入 OpenAPI 結構中,讓它們顯示在互動式文件系統裡。
diff --git a/docs/zh-hant/docs/tutorial/dependencies/sub-dependencies.md b/docs/zh-hant/docs/tutorial/dependencies/sub-dependencies.md
new file mode 100644
index 0000000000000..50c4e17908e1b
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/dependencies/sub-dependencies.md
@@ -0,0 +1,105 @@
+# 子相依 { #sub-dependencies }
+
+你可以建立具有「子相依」的相依項。
+
+它們可以按你的需要,層級任意加深。
+
+**FastAPI** 會負責解析它們。
+
+## 第一個相依項 "dependable" { #first-dependency-dependable }
+
+你可以建立第一個相依項("dependable")如下:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}
+
+它宣告了一個可選的查詢參數 `q`(型別為 `str`),然後直接回傳它。
+
+這很簡單(不太實用),但有助於我們專注於子相依如何運作。
+
+## 第二個相依,同時是 "dependable" 也是 "dependant" { #second-dependency-dependable-and-dependant }
+
+接著你可以建立另一個相依函式("dependable"),同時它也宣告了自己的相依(因此它同時也是 "dependant"):
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}
+
+來看它所宣告的參數:
+
+- 即使這個函式本身是個相依項("dependable"),它也宣告了另一個相依(它「相依於」其他東西)。
+ - 它相依 `query_extractor`,並把其回傳值指定給參數 `q`。
+- 它還宣告了一個可選的 `last_query` cookie,型別為 `str`。
+ - 如果使用者沒有提供查詢 `q`,我們就使用先前儲存在 cookie 中的最後一次查詢值。
+
+## 使用相依項 { #use-the-dependency }
+
+然後我們可以這樣使用這個相依項:
+
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}
+
+/// info
+
+注意,在路徑操作函式中我們只宣告了一個相依項 `query_or_cookie_extractor`。
+
+但 **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
+```
+
+## 多次使用同一個相依項 { #using-the-same-dependency-multiple-times }
+
+如果你的某個相依項在同一個路徑操作中被宣告了多次,例如多個相依共用同一個子相依,**FastAPI** 會知道只需在每次請求中呼叫該子相依一次。
+
+它會把回傳值儲存在一個 「快取」 中,並在該次請求中傳遞給所有需要它的「相依者」,而不是為同一個請求多次呼叫相同的相依項。
+
+在進階情境下,如果你確定需要在同一次請求的每個步驟都呼叫該相依(可能呼叫多次),而不是使用「快取」的值,你可以在使用 `Depends` 時設定參數 `use_cache=False`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+//// tab | Python 3.10+ 未使用 Annotated
+
+/// tip
+
+若可行,建議使用 `Annotated` 的版本。
+
+///
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+## 回顧 { #recap }
+
+撇開這裡用到的術語不談,**相依性注入(Dependency Injection)** 系統其實很簡單。
+
+它只是一些與路徑操作函式外觀相同的函式。
+
+但它非常強大,允許你宣告任意深度巢狀的相依「圖」(樹)。
+
+/// tip
+
+用這些簡單的例子看起來可能不那麼有用。
+
+但在關於安全性的章節中,你會看到它有多實用。
+
+你也會看到它能為你省下多少程式碼。
+
+///
diff --git a/docs/zh-hant/docs/tutorial/encoder.md b/docs/zh-hant/docs/tutorial/encoder.md
new file mode 100644
index 0000000000000..9b541adce61ef
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/encoder.md
@@ -0,0 +1,35 @@
+# JSON 相容編碼器 { #json-compatible-encoder }
+
+在某些情況下,你可能需要將某種資料型別(例如 Pydantic 模型)轉換為與 JSON 相容的類型(例如 `dict`、`list` 等)。
+
+例如,當你需要把它儲存在資料庫中。
+
+為此,**FastAPI** 提供了 `jsonable_encoder()` 函式。
+
+## 使用 `jsonable_encoder` { #using-the-jsonable-encoder }
+
+想像你有一個只接受與 JSON 相容資料的資料庫 `fake_db`。
+
+例如,它不接受 `datetime` 物件,因為那與 JSON 不相容。
+
+因此,必須將 `datetime` 物件轉為一個以 [ISO 格式](https://en.wikipedia.org/wiki/ISO_8601) 表示資料的 `str`。
+
+同樣地,這個資料庫不會接受 Pydantic 模型(帶有屬性的物件),只接受 `dict`。
+
+你可以使用 `jsonable_encoder` 來處理。
+
+它接收一個物件(例如 Pydantic 模型),並回傳一個與 JSON 相容的版本:
+
+{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *}
+
+在此範例中,它會把 Pydantic 模型轉成 `dict`,並將 `datetime` 轉成 `str`。
+
+呼叫後的結果可以用 Python 標準的 [`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps) 進行編碼。
+
+它不會回傳一個包含 JSON 內容的大型 `str`(字串)。它會回傳 Python 標準的資料結構(例如 `dict`),其中的值與子值都與 JSON 相容。
+
+/// note
+
+事實上,`jsonable_encoder` 在 **FastAPI** 內部也被用來轉換資料。不過在許多其他情境中它同樣實用。
+
+///
diff --git a/docs/zh-hant/docs/tutorial/extra-data-types.md b/docs/zh-hant/docs/tutorial/extra-data-types.md
new file mode 100644
index 0000000000000..a5573379d829d
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/extra-data-types.md
@@ -0,0 +1,62 @@
+# 額外的資料型別 { #extra-data-types }
+
+到目前為止,你一直在使用常見的資料型別,例如:
+
+* `int`
+* `float`
+* `str`
+* `bool`
+
+但你也可以使用更複雜的資料型別。
+
+而且你仍然會擁有目前為止所見的同樣功能:
+
+* 極佳的編輯器支援。
+* 將傳入請求的資料轉換。
+* 回應資料的轉換。
+* 資料驗證。
+* 自動產生註解與文件。
+
+## 其他資料型別 { #other-data-types }
+
+以下是你可以使用的一些其他資料型別:
+
+* `UUID`:
+ * 一種標準的「通用唯一識別碼 (Universally Unique Identifier)」,常見於許多資料庫與系統的 ID。
+ * 在請求與回應中會以 `str` 表示。
+* `datetime.datetime`:
+ * Python 的 `datetime.datetime`。
+ * 在請求與回應中會以 ISO 8601 格式的 `str` 表示,例如:`2008-09-15T15:53:00+05:00`。
+* `datetime.date`:
+ * Python 的 `datetime.date`。
+ * 在請求與回應中會以 ISO 8601 格式的 `str` 表示,例如:`2008-09-15`。
+* `datetime.time`:
+ * Python 的 `datetime.time`。
+ * 在請求與回應中會以 ISO 8601 格式的 `str` 表示,例如:`14:23:55.003`。
+* `datetime.timedelta`:
+ * Python 的 `datetime.timedelta`。
+ * 在請求與回應中會以總秒數的 `float` 表示。
+ * Pydantic 也允許用「ISO 8601 time diff encoding」來表示,[詳情見文件](https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers)。
+* `frozenset`:
+ * 在請求與回應中與 `set` 相同處理:
+ * 在請求中,會讀取一個 list,去除重複並轉為 `set`。
+ * 在回應中,`set` 會被轉為 `list`。
+ * 生成的 schema 會指定 `set` 的值為唯一(使用 JSON Schema 的 `uniqueItems`)。
+* `bytes`:
+ * 標準的 Python `bytes`。
+ * 在請求與回應中會被當作 `str` 處理。
+ * 生成的 schema 會指定其為 `str`,且 "format" 為 `binary`。
+* `Decimal`:
+ * 標準的 Python `Decimal`。
+ * 在請求與回應中,與 `float` 的處理方式相同。
+* 你可以在此查閱所有可用的 Pydantic 資料型別:[Pydantic 資料型別](https://docs.pydantic.dev/latest/usage/types/types/)。
+
+## 範例 { #example }
+
+以下是一個帶有參數、使用上述部分型別的 *路徑操作 (path operation)* 範例。
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *}
+
+請注意,函式內的參數會是它們的自然資料型別,因此你可以進行一般的日期運算,例如:
+
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *}
diff --git a/docs/zh-hant/docs/tutorial/extra-models.md b/docs/zh-hant/docs/tutorial/extra-models.md
new file mode 100644
index 0000000000000..f5509f531f659
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/extra-models.md
@@ -0,0 +1,211 @@
+# 額外的模型 { #extra-models }
+
+延續前一個範例,通常會有不只一個彼此相關的模型。
+
+對使用者模型尤其如此,因為:
+
+* 「輸入模型」需要能包含密碼。
+* 「輸出模型」不應包含密碼。
+* 「資料庫模型」通常需要儲存雜湊後的密碼。
+
+/// danger
+
+切勿儲存使用者的明文密碼。務必只儲存可供驗證的「安全雜湊」。
+
+若你還不清楚,稍後會在[安全性章節](security/simple-oauth2.md#password-hashing)學到什麼是「密碼雜湊」。
+
+///
+
+## 多個模型 { #multiple-models }
+
+以下是模型大致長相、與其密碼欄位以及它們被使用的位置:
+
+{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}
+
+### 關於 `**user_in.model_dump()` { #about-user-in-model-dump }
+
+#### Pydantic 的 `.model_dump()` { #pydantics-model-dump }
+
+`user_in` 是一個 `UserIn` 類別的 Pydantic 模型。
+
+Pydantic 模型有 `.model_dump()` 方法,會回傳包含該模型資料的 `dict`。
+
+因此,若我們建立一個 Pydantic 物件 `user_in` 如:
+
+```Python
+user_in = UserIn(username="john", password="secret", email="john.doe@example.com")
+```
+
+接著呼叫:
+
+```Python
+user_dict = user_in.model_dump()
+```
+
+此時變數 `user_dict` 會是一個承載資料的 `dict`(也就是 `dict`,而非 Pydantic 模型物件)。
+
+若再呼叫:
+
+```Python
+print(user_dict)
+```
+
+我們會得到一個 Python `dict`:
+
+```Python
+{
+ 'username': 'john',
+ 'password': 'secret',
+ 'email': 'john.doe@example.com',
+ 'full_name': None,
+}
+```
+
+#### 解包 `dict` { #unpacking-a-dict }
+
+若將像 `user_dict` 這樣的 `dict` 以 `**user_dict` 傳給函式(或類別),Python 會將其「解包」,把 `user_dict` 的鍵和值直接當作具名引數傳入。
+
+因此,延續上面的 `user_dict`,寫成:
+
+```Python
+UserInDB(**user_dict)
+```
+
+效果等同於:
+
+```Python
+UserInDB(
+ username="john",
+ password="secret",
+ email="john.doe@example.com",
+ 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 模型 { #a-pydantic-model-from-the-contents-of-another }
+
+如上例我們從 `user_in.model_dump()` 得到 `user_dict`,以下程式碼:
+
+```Python
+user_dict = user_in.model_dump()
+UserInDB(**user_dict)
+```
+
+等同於:
+
+```Python
+UserInDB(**user_in.model_dump())
+```
+
+...因為 `user_in.model_dump()` 回傳的是 `dict`,接著在傳給 `UserInDB` 時以 `**` 前綴讓 Python 進行解包。
+
+因此,我們可以用一個 Pydantic 模型的資料建立另一個 Pydantic 模型。
+
+#### 解包 `dict` 並加入額外參數 { #unpacking-a-dict-and-extra-keywords }
+
+接著加入額外的具名引數 `hashed_password=hashed_password`,如下:
+
+```Python
+UserInDB(**user_in.model_dump(), 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
+
+輔助函式 `fake_password_hasher` 與 `fake_save_user` 只是用來示範資料流程,並不提供任何實際的安全性。
+
+///
+
+## 減少重複 { #reduce-duplication }
+
+減少程式碼重複是 FastAPI 的核心理念之一。
+
+因為重複的程式碼會提高發生錯誤、安全性問題、程式不同步(某處更新但其他處未更新)等風險。
+
+而這些模型共享大量資料,重複了屬性名稱與型別。
+
+我們可以做得更好。
+
+我們可以宣告一個作為基底的 `UserBase` 模型,其他模型繼承它成為子類別,沿用其屬性(型別宣告、驗證等)。
+
+所有資料轉換、驗證、文件產生等仍可正常運作。
+
+如此一來,我們只需要宣告模型之間的差異(含明文 `password`、含 `hashed_password`、或不含密碼):
+
+{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}
+
+## `Union` 或 `anyOf` { #union-or-anyof }
+
+你可以將回應宣告為多個型別的 `Union`,表示回應可能是其中任一型別。
+
+在 OpenAPI 中會以 `anyOf` 定義。
+
+要達成這點,使用標準的 Python 型別提示 [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union):
+
+/// note
+
+在定義 [`Union`](https://docs.pydantic.dev/latest/concepts/types/#unions) 時,請先放置「更具體」的型別,再放「較不具體」的型別。以下範例中,較具體的 `PlaneItem` 置於 `CarItem` 之前:`Union[PlaneItem, CarItem]`。
+
+///
+
+{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}
+
+### Python 3.10 中的 `Union` { #union-in-python-3-10 }
+
+此範例中,我們將 `Union[PlaneItem, CarItem]` 作為引數 `response_model` 的值。
+
+由於這裡是把它當作引數的「值」傳入,而非用於型別註記,因此即使在 Python 3.10 也必須使用 `Union`。
+
+若用於型別註記,則可以使用直線(|),如下:
+
+```Python
+some_variable: PlaneItem | CarItem
+```
+
+但若寫成指定值 `response_model=PlaneItem | CarItem` 會發生錯誤,因為 Python 會嘗試在 `PlaneItem` 與 `CarItem` 之間執行「無效運算」,而非將其視為型別註記。
+
+## 模型的清單 { #list-of-models }
+
+同樣地,你可以將回應宣告為物件的 `list`。
+
+為此,使用標準的 Python `list`:
+
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
+
+## 以任意 `dict` 作為回應 { #response-with-arbitrary-dict }
+
+你也可以用一般的任意 `dict` 宣告回應,只需指定鍵和值的型別,而不必使用 Pydantic 模型。
+
+當你事先不知道可用的欄位/屬性名稱(定義 Pydantic 模型所需)時,這很實用。
+
+此時可使用 `dict`:
+
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
+
+## 重點回顧 { #recap }
+
+依情境使用多個 Pydantic 模型並靈活繼承。
+
+當一個實體需要呈現不同「狀態」時,不必侷限於一個資料模型。例如使用者這個實體,可能有包含 `password`、包含 `password_hash`,或不含密碼等不同狀態。
diff --git a/docs/zh-hant/docs/tutorial/first-steps.md b/docs/zh-hant/docs/tutorial/first-steps.md
new file mode 100644
index 0000000000000..d6b1a72e321c6
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/first-steps.md
@@ -0,0 +1,429 @@
+# 第一步 { #first-steps }
+
+最簡單的 FastAPI 檔案可能看起來像這樣:
+
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
+
+將其複製到一個名為 `main.py` 的文件中。
+
+執行即時重新載入伺服器(live server):
+
+get 操作
+
+/// info | `@decorator` 說明
+
+Python 中的 `@something` 語法被稱為「裝飾器」。
+
+你把它放在一個函式上面。像一個漂亮的裝飾帽子(我猜這是術語的來源)。
+
+一個「裝飾器」會對下面的函式做一些事情。
+
+在這種情況下,這個裝飾器告訴 **FastAPI** 那個函式對應於 **路徑** `/` 和 **操作** `get`。
+
+這就是「**路徑操作裝飾器**」。
+
+///
+
+你也可以使用其他的操作:
+
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+
+以及更少見的:
+
+* `@app.options()`
+* `@app.head()`
+* `@app.patch()`
+* `@app.trace()`
+
+/// tip
+
+你可以自由地使用每個操作(HTTP 方法)。
+
+**FastAPI** 不強制任何特定的意義。
+
+這裡的資訊作為一個指南,而不是要求。
+
+例如,當使用 GraphQL 時,你通常只使用 `POST` 操作。
+
+///
+
+### 第四步:定義「路徑操作函式」 { #step-4-define-the-path-operation-function }
+
+這是我們的「**路徑操作函式**」:
+
+* **path**:是 `/`。
+* **operation**:是 `get`。
+* **function**:是裝飾器下面的函式(在 `@app.get("/")` 下面)。
+
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
+
+這就是一個 Python 函式。
+
+它將會在 **FastAPI** 收到一個使用 `GET` 操作、網址為「`/`」的請求時被呼叫。
+
+在這種情況下,它是一個 `async` 函式。
+
+---
+
+你也可以將它定義為一般函式,而不是 `async def`:
+
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
+
+/// note
+
+如果你不知道差別,請查看 [Async: *"In a hurry?"*](../async.md#in-a-hurry)。
+
+///
+
+### 第五步:回傳內容 { #step-5-return-the-content }
+
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
+
+你可以返回一個 `dict`、`list`、單個值作為 `str`、`int` 等。
+
+你也可以返回 Pydantic 模型(稍後你會看到更多關於這方面的內容)。
+
+有很多其他物件和模型會自動轉換為 JSON(包括 ORMs,等等)。試用你最喜歡的,很有可能它們已經有支援。
+
+### 第六步:部署 { #step-6-deploy-it }
+
+用一行指令將你的應用程式部署到 **[FastAPI Cloud](https://fastapicloud.com)**:`fastapi deploy`。🎉
+
+#### 關於 FastAPI Cloud { #about-fastapi-cloud }
+
+**[FastAPI Cloud](https://fastapicloud.com)** 由 **FastAPI** 的作者與團隊打造。
+
+它讓你以最小的成本完成 API 的**建置**、**部署**與**存取**流程。
+
+它把用 FastAPI 開發應用的同樣**開發者體驗**帶到將應用**部署**到雲端的流程中。🎉
+
+FastAPI Cloud 也是「FastAPI 與其好友」這些開源專案的主要贊助與資金提供者。✨
+
+#### 部署到其他雲端供應商 { #deploy-to-other-cloud-providers }
+
+FastAPI 是開源並基於標準的。你可以把 FastAPI 應用部署到你選擇的任何雲端供應商。
+
+依照你的雲端供應商的指南部署 FastAPI 應用吧。🤓
+
+## 回顧 { #recap }
+
+* 引入 `FastAPI`。
+* 建立一個 `app` 實例。
+* 寫一個「路徑操作裝飾器」,像是 `@app.get("/")`。
+* 定義一個「路徑操作函式」;例如,`def root(): ...`。
+* 使用命令 `fastapi dev` 執行開發伺服器。
+* 可選:使用 `fastapi deploy` 部署你的應用程式。
diff --git a/docs/zh-hant/docs/tutorial/handling-errors.md b/docs/zh-hant/docs/tutorial/handling-errors.md
new file mode 100644
index 0000000000000..b1ffd3e0387f8
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/handling-errors.md
@@ -0,0 +1,244 @@
+# 錯誤處理 { #handling-errors }
+
+在許多情況下,你需要通知使用你 API 的用戶端發生錯誤。
+
+這個用戶端可能是帶有前端的瀏覽器、他人的程式碼、IoT 裝置等。
+
+你可能需要告訴用戶端:
+
+* 用戶端沒有足夠權限執行該操作。
+* 用戶端沒有權限存取該資源。
+* 用戶端嘗試存取的項目不存在。
+* 等等。
+
+在這些情況下,通常會回傳範圍為 400(400 到 499)的 HTTP 狀態碼。
+
+這類似於 200 範圍的 HTTP 狀態碼(200 到 299)。那些「200」狀態碼表示請求在某種程度上是「成功」的。
+
+400 範圍的狀態碼表示用戶端錯誤。
+
+還記得那些「404 Not Found」錯誤(和梗)嗎?
+
+## 使用 `HTTPException` { #use-httpexception }
+
+要向用戶端回傳帶有錯誤的 HTTP 回應,使用 `HTTPException`。
+
+### 匯入 `HTTPException` { #import-httpexception }
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
+
+### 在程式中 raise 一個 `HTTPException` { #raise-an-httpexception-in-your-code }
+
+`HTTPException` 是一般的 Python 例外,但包含與 API 相關的附加資料。
+
+因為它是 Python 的例外,你不是 `return`,而是 `raise`。
+
+這也表示,如果你在某個工具函式中(該函式被你的「路徑操作函式」呼叫),並在該工具函式裡 raise `HTTPException`,那麼「路徑操作函式」剩下的程式碼將不會執行;該請求會立刻被終止,並將 `HTTPException` 的 HTTP 錯誤傳回給用戶端。
+
+為何選擇 raise 例外而非回傳值的好處,會在相依性與安全性章節更為明顯。
+
+在這個範例中,當用戶端以不存在的 ID 請求項目時,raise 一個狀態碼為 `404` 的例外:
+
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
+
+### 回應結果 { #the-resulting-response }
+
+如果用戶端請求 `http://example.com/items/foo`(`item_id` 為 `"foo"`),會收到 200 的 HTTP 狀態碼,以及以下 JSON 回應:
+
+```JSON
+{
+ "item": "The Foo Wrestlers"
+}
+```
+
+但如果用戶端請求 `http://example.com/items/bar`(不存在的 `item_id` `"bar"`),會收到 404("not found")的 HTTP 狀態碼,以及以下 JSON 回應:
+
+```JSON
+{
+ "detail": "Item not found"
+}
+```
+
+/// tip
+
+在 raise 一個 `HTTPException` 時,你可以將任何可轉為 JSON 的值作為 `detail` 參數,不只限於 `str`。
+
+你可以傳入 `dict`、`list` 等。
+
+**FastAPI** 會自動處理並轉為 JSON。
+
+///
+
+## 新增自訂標頭 { #add-custom-headers }
+
+有些情況需要在 HTTP 錯誤回應中加入自訂標頭,例如某些安全性情境。
+
+你大概不需要在程式碼中直接使用。
+
+但若你在進階情境中需要,可以這樣加入自訂標頭:
+
+{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
+
+## 安裝自訂例外處理器 { #install-custom-exception-handlers }
+
+你可以使用 [Starlette 的相同例外工具](https://www.starlette.dev/exceptions/) 來加入自訂例外處理器。
+
+假設你有一個自訂例外 `UnicornException`,你(或你使用的函式庫)可能會 `raise` 它。
+
+而你想用 FastAPI 全域處理這個例外。
+
+你可以使用 `@app.exception_handler()` 加入自訂例外處理器:
+
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
+
+在這裡,如果你請求 `/unicorns/yolo`,該「路徑操作」會 `raise` 一個 `UnicornException`。
+
+但它會被 `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** 以便利性為由,提供和 `starlette.responses` 相同的介面於 `fastapi.responses`。但大多數可用的回應類型其實直接來自 Starlette。`Request` 也一樣。
+
+///
+
+## 覆寫預設例外處理器 { #override-the-default-exception-handlers }
+
+**FastAPI** 內建了一些預設例外處理器。
+
+這些處理器負責在你 `raise` 一個 `HTTPException` 或請求帶有無效資料時,回傳預設的 JSON 回應。
+
+你可以用自己的處理器來覆寫它們。
+
+### 覆寫請求驗證例外 { #override-request-validation-exceptions }
+
+當請求包含無效資料時,**FastAPI** 會在內部 raise 一個 `RequestValidationError`。
+
+它同時也包含了對應的預設例外處理器。
+
+要覆寫它,匯入 `RequestValidationError`,並用 `@app.exception_handler(RequestValidationError)` 來裝飾你的例外處理器。
+
+例外處理器會接收一個 `Request` 和該例外。
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
+
+現在,如果你前往 `/items/foo`,預設的 JSON 錯誤本應為:
+
+```JSON
+{
+ "detail": [
+ {
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "value is not a valid integer",
+ "type": "type_error.integer"
+ }
+ ]
+}
+```
+
+你將會改而得到文字版:
+
+```
+Validation errors:
+Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer
+```
+
+### 覆寫 `HTTPException` 的錯誤處理器 { #override-the-httpexception-error-handler }
+
+同樣地,你也可以覆寫 `HTTPException` 的處理器。
+
+例如,你可能想在這些錯誤時回傳純文字而非 JSON:
+
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
+
+/// note | 技術細節
+
+你也可以使用 `from starlette.responses import PlainTextResponse`。
+
+**FastAPI** 以便利性為由,提供和 `starlette.responses` 相同的介面於 `fastapi.responses`。但大多數可用的回應類型其實直接來自 Starlette。
+
+///
+
+/// warning
+
+請注意,`RequestValidationError` 內含驗證錯誤發生的檔名與行號,如果你願意,可以在日誌中顯示這些相關資訊。
+
+但這也代表如果你只是把它轉成字串並直接回傳,可能會洩漏一些關於你系統的資訊。因此這裡的程式碼會分別擷取並顯示每個錯誤。
+
+///
+
+### 使用 `RequestValidationError` 的 body { #use-the-requestvalidationerror-body }
+
+`RequestValidationError` 包含它收到的(但無效的)`body`。
+
+在開發應用時,你可以用它來記錄 body 並除錯、回傳給使用者等。
+
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
+
+現在嘗試送出一個無效的項目,例如:
+
+```JSON
+{
+ "title": "towel",
+ "size": "XL"
+}
+```
+
+你會收到一個告知資料無效、且包含所收到 body 的回應:
+
+```JSON hl_lines="12-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` { #fastapis-httpexception-vs-starlettes-httpexception }
+
+**FastAPI** 有自己定義的 `HTTPException`。
+
+而 **FastAPI** 的 `HTTPException` 錯誤類別是繼承自 Starlette 的 `HTTPException` 錯誤類別。
+
+唯一的差異是,**FastAPI** 的 `HTTPException` 在 `detail` 欄位接受任何可轉為 JSON 的資料,而 Starlette 的 `HTTPException` 只接受字串。
+
+因此,在你的程式碼中,你可以一如往常地 raise **FastAPI** 的 `HTTPException`。
+
+但當你註冊例外處理器時,應該針對 Starlette 的 `HTTPException` 來註冊。
+
+如此一來,如果 Starlette 的內部程式碼,或任何 Starlette 擴充/外掛 raise 了 Starlette 的 `HTTPException`,你的處理器就能攔截並處理它。
+
+在這個範例中,為了能在同一份程式碼中同時使用兩種 `HTTPException`,我們把 Starlette 的例外重新命名為 `StarletteHTTPException`:
+
+```Python
+from starlette.exceptions import HTTPException as StarletteHTTPException
+```
+
+### 重用 **FastAPI** 的例外處理器 { #reuse-fastapis-exception-handlers }
+
+如果你想在使用例外的同時,沿用 **FastAPI** 的預設例外處理器,你可以從 `fastapi.exception_handlers` 匯入並重用預設的處理器:
+
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
+
+在這個範例中,你只是用一段很生動的訊息把錯誤印出來,不過重點是:你可以使用該例外,然後直接重用預設的例外處理器。
diff --git a/docs/zh-hant/docs/tutorial/header-param-models.md b/docs/zh-hant/docs/tutorial/header-param-models.md
new file mode 100644
index 0000000000000..ca2b1f8dee602
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/header-param-models.md
@@ -0,0 +1,72 @@
+# 標頭參數模型 { #header-parameter-models }
+
+如果你有一組相關的標頭參數,可以建立一個 Pydantic 模型來宣告它們。
+
+這能讓你在多處重複使用該模型,並一次性為所有參數宣告驗證與中繼資料。😎
+
+/// note | 注意
+
+自 FastAPI 版本 `0.115.0` 起支援。🤓
+
+///
+
+## 以 Pydantic 模型宣告標頭參數 { #header-parameters-with-a-pydantic-model }
+
+在 Pydantic 模型中宣告你需要的標頭參數,然後將參數宣告為 `Header`:
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+FastAPI 會從請求的標頭為每個欄位擷取資料,並交給你已定義的 Pydantic 模型實例。
+
+## 檢視文件 { #check-the-docs }
+
+你可以在 `/docs` 的文件介面看到所需的標頭:
+
+
+contact 欄位| 參數 | 型別 | 說明 |
|---|---|---|
name | str | 聯絡人/組織的識別名稱。 |
url | str | 指向聯絡資訊的 URL。必須是 URL 格式。 |
email | str | 聯絡人/組織的電子郵件地址。必須是電子郵件格式。 |
license_info 欄位| 參數 | 型別 | 說明 |
|---|---|---|
name | str | 必填(若有設定 license_info)。API 使用的授權名稱。 |
identifier | str | API 的 [SPDX](https://spdx.org/licenses/) 授權表示式。identifier 欄位與 url 欄位互斥。自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。 |
url | str | API 所採用授權的 URL。必須是 URL 格式。 |
+
+## 授權識別碼 { #license-identifier }
+
+自 OpenAPI 3.1.0 與 FastAPI 0.99.0 起,你也可以在 `license_info` 中使用 `identifier` 來取代 `url`。
+
+例如:
+
+{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}
+
+## 標籤的中繼資料 { #metadata-for-tags }
+
+你也可以透過 `openapi_tags` 參數,為用來分組你的路徑操作(path operation)的各個標籤加入額外中繼資料。
+
+它接收一個 list,其中每個標籤對應一個 dictionary。
+
+每個 dictionary 可包含:
+
+* `name`(**必填**):一個 `str`,其值需與你在路徑操作與 `APIRouter`s 的 `tags` 參數中使用的標籤名稱相同。
+* `description`:一個 `str`,為該標籤的簡短描述。可使用 Markdown,並會顯示在文件介面中。
+* `externalDocs`:一個 `dict`,描述外部文件,包含:
+ * `description`:一個 `str`,外部文件的簡短描述。
+ * `url`(**必填**):一個 `str`,外部文件的 URL。
+
+### 建立標籤的中繼資料 { #create-metadata-for-tags }
+
+我們用 `users` 與 `items` 兩個標籤來示範。
+
+先為你的標籤建立中繼資料,然後將它傳給 `openapi_tags` 參數:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}
+
+注意你可以在描述中使用 Markdown,例如「login」會以粗體(**login**)顯示,而「fancy」會以斜體(_fancy_)顯示。
+
+/// tip | 提示
+
+你不必為你使用到的每個標籤都加入中繼資料。
+
+///
+
+### 使用你的標籤 { #use-your-tags }
+
+在你的路徑操作(以及 `APIRouter`s)上使用 `tags` 參數,將它們歸類到不同標籤下:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}
+
+/// info | 資訊
+
+在 [Path Operation Configuration](path-operation-configuration.md#tags) 中閱讀更多關於標籤的內容。
+
+///
+
+### 檢視文件 { #check-the-docs }
+
+現在檢視文件時,會看到所有額外的中繼資料:
+
+
+
+### 標籤順序 { #order-of-tags }
+
+每個標籤中繼資料 dictionary 在清單中的順序,也會決定它們在文件介面中的顯示順序。
+
+例如,雖然按字母排序時 `users` 會排在 `items` 之後,但因為我們在清單中將它的中繼資料放在第一個,所以它會先顯示。
+
+## OpenAPI URL { #openapi-url }
+
+預設情況下,OpenAPI 綱要(schema)會提供在 `/openapi.json`。
+
+但你可以用 `openapi_url` 參數來調整。
+
+例如,將它設定為提供在 `/api/v1/openapi.json`:
+
+{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}
+
+如果你想完全停用 OpenAPI 綱要,可以設定 `openapi_url=None`,同時也會停用依賴它的文件使用者介面。
+
+## 文件 URL { #docs-urls }
+
+你可以設定內建的兩個文件使用者介面:
+
+* Swagger UI:提供於 `/docs`。
+ * 可用 `docs_url` 參數設定其 URL。
+ * 設定 `docs_url=None` 可停用。
+* ReDoc:提供於 `/redoc`。
+ * 可用 `redoc_url` 參數設定其 URL。
+ * 設定 `redoc_url=None` 可停用。
+
+例如,將 Swagger UI 提供於 `/documentation`,並停用 ReDoc:
+
+{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}
diff --git a/docs/zh-hant/docs/tutorial/middleware.md b/docs/zh-hant/docs/tutorial/middleware.md
new file mode 100644
index 0000000000000..42a922d35441b
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/middleware.md
@@ -0,0 +1,95 @@
+# 中介軟體 { #middleware }
+
+你可以在 **FastAPI** 應用程式中加入中介軟體。
+
+「中介軟體」是一個函式,在任何特定的*路徑操作*處理之前先處理每個**請求**;在回傳之前,也會處理每個**回應**。
+
+- 它會攔截進到應用程式的每個**請求**。
+- 然後可以對該**請求**做一些處理或執行所需的程式碼。
+- 接著把**請求**傳遞給應用程式的其餘部分(某個*路徑操作*)處理。
+- 之後再接收應用程式(某個*路徑操作*)所產生的**回應**。
+- 可以對該**回應**做一些處理或執行所需的程式碼。
+- 然後回傳**回應**。
+
+/// note | 技術細節
+
+如果你有使用帶有 `yield` 的相依性,其釋放階段的程式碼會在中介軟體之後執行。
+
+若有背景工作(在[背景工作](background-tasks.md)一節會介紹,你稍後會看到),它們會在所有中介軟體之後執行。
+
+///
+
+## 建立中介軟體 { #create-a-middleware }
+
+要建立中介軟體,將裝飾器 `@app.middleware("http")` 加在函式上方。
+
+中介軟體函式會接收:
+
+- `request`。
+- 一個函式 `call_next`,會以 `request` 作為參數。
+ - 這個函式會把 `request` 傳給對應的*路徑操作*。
+ - 然後回傳對應*路徑操作*所產生的 `response`。
+- 然後你可以在回傳之前進一步修改 `response`。
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}
+
+/// tip
+
+請記得,自訂的非標準標頭可以[使用 `X-` 前綴](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers)。
+
+但如果你有自訂標頭並希望瀏覽器端的用戶端能看到它們,你需要在 CORS 設定([CORS(跨來源資源共用)](cors.md))中使用 [Starlette 的 CORS 文件](https://www.starlette.dev/middleware/#corsmiddleware)所記載的參數 `expose_headers` 將它們加入。
+
+///
+
+/// note | 技術細節
+
+你也可以使用 `from starlette.requests import Request`。
+
+**FastAPI** 為了方便開發者而提供了它,但實際上它直接來自 Starlette。
+
+///
+
+### 在 `response` 之前與之後 { #before-and-after-the-response }
+
+你可以在任何*路徑操作*接收 `request` 之前,加入要執行的程式碼。
+
+也可以在產生出 `response` 之後、回傳之前執行程式碼。
+
+例如,你可以新增一個自訂標頭 `X-Process-Time`,其內容為處理請求並產生回應所花費的秒數:
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}
+
+/// tip
+
+這裡我們使用 [`time.perf_counter()`](https://docs.python.org/3/library/time.html#time.perf_counter) 而不是 `time.time()`,因為在這些用例中它可能更精確。🤓
+
+///
+
+## 多個中介軟體的執行順序 { #multiple-middleware-execution-order }
+
+當你使用 `@app.middleware()` 裝飾器或 `app.add_middleware()` 方法加入多個中介軟體時,每個新的中介軟體都會包裹應用程式,形成一個堆疊。最後加入的中介軟體位於最外層,最先加入的位於最內層。
+
+在請求路徑上,最外層的中介軟體最先執行。
+
+在回應路徑上,它最後執行。
+
+例如:
+
+```Python
+app.add_middleware(MiddlewareA)
+app.add_middleware(MiddlewareB)
+```
+
+執行順序如下:
+
+- **請求**:MiddlewareB → MiddlewareA → 路由
+
+- **回應**:路由 → MiddlewareA → MiddlewareB
+
+這種堆疊行為可確保中介軟體以可預期且可控制的順序執行。
+
+## 其他中介軟體 { #other-middlewares }
+
+你之後可以在[進階使用者指南:進階中介軟體](../advanced/middleware.md)閱讀更多關於其他中介軟體的內容。
+
+下一節你將會讀到如何使用中介軟體處理 CORS。
diff --git a/docs/zh-hant/docs/tutorial/path-operation-configuration.md b/docs/zh-hant/docs/tutorial/path-operation-configuration.md
new file mode 100644
index 0000000000000..9ca738a98d334
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/path-operation-configuration.md
@@ -0,0 +1,107 @@
+# 路徑操作設定 { #path-operation-configuration }
+
+你可以在你的「路徑操作裝飾器」中傳入多個參數來進行設定。
+
+/// warning | 警告
+
+請注意,這些參數是直接傳給「路徑操作裝飾器」,而不是傳給你的「路徑操作函式」。
+
+///
+
+## 回應狀態碼 { #response-status-code }
+
+你可以為「路徑操作」的回應設定 (HTTP) `status_code`。
+
+你可以直接傳入整數代碼,例如 `404`。
+
+如果不記得每個數字代碼代表什麼,你可以使用 `status` 中的速記常數:
+
+{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *}
+
+該狀態碼會用於回應,並被加入至 OpenAPI 結構描述中。
+
+/// note | 技術細節
+
+你也可以使用 `from starlette import status`。
+
+**FastAPI** 提供與 `starlette.status` 相同的 `fastapi.status`,僅為了方便你這位開發者,但它其實直接來自 Starlette。
+
+///
+
+## 標籤 { #tags }
+
+你可以為「路徑操作」加入標籤,傳入參數 `tags`,其值為由 `str` 組成的 `list`(通常只是一個 `str`):
+
+{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *}
+
+這些標籤會被加入到 OpenAPI 結構描述,並由自動化文件介面使用:
+
+
+
+### 含 Enum 的標籤 { #tags-with-enums }
+
+如果你的應用很大,可能會累積數個標籤,你會希望對相關的「路徑操作」始終使用相同的標籤。
+
+在這種情況下,可以考慮把標籤存放在 `Enum` 中。
+
+**FastAPI** 對此的支援方式與使用普通字串相同:
+
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
+
+## 摘要與描述 { #summary-and-description }
+
+你可以加入 `summary` 與 `description`:
+
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *}
+
+## 從 docstring 取得描述 { #description-from-docstring }
+
+由於描述常常較長、跨越多行,你可以在函式的 文件字串(docstring) 中宣告「路徑操作」的描述,**FastAPI** 會從那裡讀取。
+
+你可以在 docstring 中書寫 [Markdown](https://en.wikipedia.org/wiki/Markdown),它會被正確解析並顯示(會考慮 docstring 的縮排)。
+
+{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}
+
+這會用於互動式文件:
+
+
+
+## 回應描述 { #response-description }
+
+你可以用參數 `response_description` 指定回應的描述:
+
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
+
+/// info | 資訊
+
+請注意,`response_description` 專指回應,而 `description` 則是針對整個「路徑操作」的一般描述。
+
+///
+
+/// check | 檢查
+
+OpenAPI 規範要求每個「路徑操作」都必須有一個回應描述。
+
+因此,如果你未提供,**FastAPI** 會自動產生 "Successful response"。
+
+///
+
+
+
+## 將「路徑操作」標記為已棄用 { #deprecate-a-path-operation }
+
+若需要將「路徑操作」標記為 已棄用,但不移除它,請傳入參數 `deprecated`:
+
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
+
+在互動式文件中,它會被清楚標示為已棄用:
+
+
+
+比較已棄用與未棄用的「路徑操作」在文件中的呈現:
+
+
+
+## 總結 { #recap }
+
+你可以透過將參數傳給「路徑操作裝飾器」,輕鬆地設定並為你的「路徑操作」加入中繼資料。
diff --git a/docs/zh-hant/docs/tutorial/path-params-numeric-validations.md b/docs/zh-hant/docs/tutorial/path-params-numeric-validations.md
new file mode 100644
index 0000000000000..68eb837e943d4
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/path-params-numeric-validations.md
@@ -0,0 +1,154 @@
+# 路徑參數與數值驗證 { #path-parameters-and-numeric-validations }
+
+就像使用 `Query` 為查詢參數宣告更多驗證與中繼資料一樣,你也可以用 `Path` 為路徑參數宣告相同類型的驗證與中繼資料。
+
+## 匯入 `Path` { #import-path }
+
+首先,從 `fastapi` 匯入 `Path`,並匯入 `Annotated`:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
+
+/// info
+
+FastAPI 在 0.95.0 版加入並開始推薦使用 `Annotated`。
+
+如果你使用更舊的版本,嘗試使用 `Annotated` 會出錯。
+
+請確保在使用 `Annotated` 前,先[升級 FastAPI 版本](../deployment/versions.md#upgrading-the-fastapi-versions)到至少 0.95.1。
+
+///
+
+## 宣告中繼資料 { #declare-metadata }
+
+你可以宣告與 `Query` 相同的所有參數。
+
+例如,若要為路徑參數 `item_id` 宣告 `title` 中繼資料,可以這樣寫:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *}
+
+/// note
+
+路徑參數一定是必填,因為它必須是路徑的一部分。即使你將其宣告為 `None` 或設定預設值,也不會有任何影響,它仍然是必填。
+
+///
+
+## 依需求調整參數順序 { #order-the-parameters-as-you-need }
+
+/// tip
+
+如果你使用 `Annotated`,這點大概沒那麼重要或必要。
+
+///
+
+假設你想把查詢參數 `q` 宣告為必要的 `str`。
+
+而你不需要為該參數宣告其他內容,所以其實不需要用 `Query`。
+
+但你仍需要為路徑參數 `item_id` 使用 `Path`,而且基於某些理由你不想用 `Annotated`。
+
+如果你把有「預設值」的參數放在沒有「預設值」的參數之前,Python 會抱怨。
+
+但你可以調整它們的順序,先放沒有預設值(查詢參數 `q`)的參數。
+
+對 **FastAPI** 來說沒差。它會依參數名稱、型別與預設宣告(`Query`、`Path` 等)來辨識參數,並不在意順序。
+
+因此,你可以這樣宣告你的函式:
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
+
+但請記住,若使用 `Annotated`,你就不會有這個問題,因為你不是用函式參數預設值來放 `Query()` 或 `Path()`。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
+
+## 依需求調整參數順序的技巧 { #order-the-parameters-as-you-need-tricks }
+
+/// tip
+
+如果你使用 `Annotated`,這點大概沒那麼重要或必要。
+
+///
+
+這裡有個小技巧偶爾很好用,不過你大概不常需要。
+
+如果你想要:
+
+* 不用 `Query`、也不給預設值就宣告查詢參數 `q`
+* 使用 `Path` 宣告路徑參數 `item_id`
+* 讓它們的順序不同
+* 不使用 `Annotated`
+
+…Python 有個小語法可以做到。
+
+在函式的參數列表最前面放一個 `*`。
+
+Python 不會對這個 `*` 做任何事,但它會知道後續的所有參數都必須以關鍵字引數(key-value pairs)方式呼叫,也就是所謂的 kwargs。即便它們沒有預設值也一樣。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
+
+### 使用 `Annotated` 更好 { #better-with-annotated }
+
+記住,如果你使用 `Annotated`,因為不是用函式參數預設值,所以你不會遇到這個問題,也可能不需要使用 `*`。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
+
+## 數值驗證:大於或等於 { #number-validations-greater-than-or-equal }
+
+使用 `Query` 和 `Path`(以及你之後會看到的其他類別)可以宣告數值限制。
+
+這裡用 `ge=1`,代表 `item_id` 必須是「大於(`g`reater)或等於(`e`qual)」`1` 的整數。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
+
+## 數值驗證:大於與小於或等於 { #number-validations-greater-than-and-less-than-or-equal }
+
+同樣也適用於:
+
+* `gt`:大於(`g`reater `t`han)
+* `le`:小於或等於(`l`ess than or `e`qual)
+
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
+
+## 數值驗證:浮點數、大於與小於 { #number-validations-floats-greater-than-and-less-than }
+
+數值驗證也適用於 `float`。
+
+這時就能看出能宣告 gt(不只是 ge)的重要性。因為你可以要求數值必須大於 `0`,即便它小於 `1`。
+
+所以,`0.5` 是有效的值,但 `0.0` 或 `0` 則無效。
+
+lt 也是同樣的道理。
+
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
+
+## 小結 { #recap }
+
+使用 `Query`、`Path`(以及你尚未看到的其他類別)時,你可以像在[查詢參數與字串驗證](query-params-str-validations.md)中一樣,宣告中繼資料與字串驗證。
+
+你也可以宣告數值驗證:
+
+* `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` 類別實例。
+
+這些函式之所以存在(而不是直接使用類別),是為了避免編輯器標記它們的型別錯誤。
+
+如此一來,你就能使用一般的編輯器與開發工具,而不需要額外設定來忽略那些錯誤。
+
+///
diff --git a/docs/zh-hant/docs/tutorial/path-params.md b/docs/zh-hant/docs/tutorial/path-params.md
new file mode 100644
index 0000000000000..d46e32bb140b6
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/path-params.md
@@ -0,0 +1,251 @@
+# 路徑參數 { #path-parameters }
+
+你可以用與 Python 格式化字串相同的語法來宣告路徑「參數」或「變數」:
+
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
+
+路徑參數 `item_id` 的值會作為引數 `item_id` 傳入你的函式。
+
+所以,如果你執行這個範例並前往 [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo),你會看到這樣的回應:
+
+```JSON
+{"item_id":"foo"}
+```
+
+## 具型別的路徑參數 { #path-parameters-with-types }
+
+你可以在函式中使用標準的 Python 型別註記為路徑參數宣告型別:
+
+{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}
+
+在這個例子裡,`item_id` 被宣告為 `int`。
+
+/// check
+
+這會在你的函式中提供編輯器支援,包括錯誤檢查、自動完成等。
+
+///
+
+## 資料 轉換 { #data-conversion }
+
+如果你執行這個範例並在瀏覽器開啟 [http://127.0.0.1:8000/items/3](http://127.0.0.1:8000/items/3),你會看到這樣的回應:
+
+```JSON
+{"item_id":3}
+```
+
+/// check
+
+注意你的函式接收(並回傳)的值是 `3`,也就是 Python 的 `int`,而不是字串 `"3"`。
+
+因此,有了這個型別宣告,**FastAPI** 會自動為你處理請求的 「解析」。
+
+///
+
+## 資料驗證 { #data-validation }
+
+但如果你在瀏覽器前往 [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo),你會看到漂亮的 HTTP 錯誤:
+
+```JSON
+{
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo"
+ }
+ ]
+}
+```
+
+因為路徑參數 `item_id` 的值是 `"foo"`,它不是 `int`。
+
+同樣的錯誤也會在你提供 `float` 而不是 `int` 時出現,例如:[http://127.0.0.1:8000/items/4.2](http://127.0.0.1:8000/items/4.2)
+
+/// check
+
+因此,搭配相同的 Python 型別宣告,**FastAPI** 會為你進行資料驗證。
+
+注意錯誤也清楚指出驗證未通過的確切位置。
+
+這在開發與除錯與你的 API 互動的程式碼時非常有幫助。
+
+///
+
+## 文件 { #documentation }
+
+當你在瀏覽器開啟 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs),你會看到自動產生、可互動的 API 文件,例如:
+
+
+
+/// check
+
+同樣地,只要使用那個 Python 型別宣告,**FastAPI** 就會提供自動、互動式的文件(整合 Swagger UI)。
+
+注意路徑參數被宣告為整數。
+
+///
+
+## 基於標準的優勢與替代文件 { #standards-based-benefits-alternative-documentation }
+
+而且因為產生的 schema 來自 [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md) 標準,有很多相容的工具可用。
+
+因此,**FastAPI** 本身也提供另一種 API 文件(使用 ReDoc),你可以在 [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) 存取:
+
+
+
+同樣地,也有許多相容工具可用,包括支援多種語言的程式碼產生工具。
+
+## Pydantic { #pydantic }
+
+所有資料驗證都由 [Pydantic](https://docs.pydantic.dev/) 在底層處理,因此你能直接受惠。而且你可以放心使用。
+
+你可以用相同的型別宣告搭配 `str`、`float`、`bool` 與許多更複雜的資料型別。
+
+這些之中的好幾個會在接下來的教學章節中介紹。
+
+## 順序很重要 { #order-matters }
+
+在建立「路徑操作」時,你可能會遇到有固定路徑的情況。
+
+像是 `/users/me`,假設它用來取得目前使用者的資料。
+
+然後你也可能有一個路徑 `/users/{user_id}` 用來依使用者 ID 取得特定使用者的資料。
+
+因為「路徑操作」會依宣告順序來比對,你必須確保 `/users/me` 的路徑在 `/users/{user_id}` 之前宣告:
+
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
+
+否則,`/users/{user_id}` 的路徑也會匹配 `/users/me`,並「認為」它收到一個值為 `"me"` 的 `user_id` 參數。
+
+同樣地,你不能重新定義同一路徑操作:
+
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
+
+因為第一個會被優先使用(路徑先匹配到)。
+
+## 預先定義的值 { #predefined-values }
+
+如果你有一個接收「路徑參數」的「路徑操作」,但你希望可用的「路徑參數」值是預先定義好的,你可以使用標準的 Python `Enum`。
+
+### 建立 `Enum` 類別 { #create-an-enum-class }
+
+匯入 `Enum` 並建立一個同時繼承自 `str` 與 `Enum` 的子類別。
+
+繼承自 `str` 之後,API 文件就能知道這些值的型別必須是 `string`,並能正確地呈現。
+
+然後建立具有固定值的類別屬性,這些就是可用的有效值:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
+
+/// tip
+
+如果你在想,「AlexNet」、「ResNet」和「LeNet」只是一些機器學習 模型 的名字。
+
+///
+
+### 宣告一個「路徑參數」 { #declare-a-path-parameter }
+
+接著使用你建立的列舉類別(`ModelName`)作為型別註記,建立一個「路徑參數」:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
+
+### 查看文件 { #check-the-docs }
+
+因為「路徑參數」的可用值是預先定義的,互動式文件可以很漂亮地顯示它們:
+
+
+
+### 使用 Python「列舉」 { #working-with-python-enumerations }
+
+「路徑參數」的值會是一個「列舉成員」。
+
+#### 比較「列舉成員」 { #compare-enumeration-members }
+
+你可以把它與你建立的列舉 `ModelName` 中的「列舉成員」比較:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}
+
+#### 取得「列舉值」 { #get-the-enumeration-value }
+
+你可以用 `model_name.value` 取得實際的值(在這個例子中是 `str`),一般而言就是 `your_enum_member.value`:
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}
+
+/// tip
+
+你也可以用 `ModelName.lenet.value` 取得值 `"lenet"`。
+
+///
+
+#### 回傳「列舉成員」 { #return-enumeration-members }
+
+你可以從「路徑操作」回傳「列舉成員」,即使是巢狀在 JSON 主體(例如 `dict`)裡。
+
+在回傳給用戶端之前,它們會被轉成對應的值(此例為字串):
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}
+
+你的用戶端會收到像這樣的 JSON 回應:
+
+```JSON
+{
+ "model_name": "alexnet",
+ "message": "Deep Learning FTW!"
+}
+```
+
+## 包含路徑的路徑參數 { #path-parameters-containing-paths }
+
+假設你有一個路徑為 `/files/{file_path}` 的「路徑操作」。
+
+但你需要 `file_path` 本身就包含一個「路徑」,像是 `home/johndoe/myfile.txt`。
+
+所以,該檔案的 URL 會是:`/files/home/johndoe/myfile.txt`。
+
+### OpenAPI 支援 { #openapi-support }
+
+OpenAPI 並不支援直接宣告一個「路徑參數」內再包含一個「路徑」,因為那會導致難以測試與定義的情況。
+
+然而,你仍可在 **FastAPI** 中這樣做,方法是使用 Starlette 的其中一個內部工具。
+
+而文件依然能運作,只是它不會額外說明該參數應該包含一個路徑。
+
+### 路徑轉換器 { #path-convertor }
+
+使用 Starlette 提供的選項,你可以用像這樣的 URL 來宣告一個包含「路徑」的「路徑參數」:
+
+```
+/files/{file_path:path}
+```
+
+在這個例子裡,參數名稱是 `file_path`,而最後面的 `:path` 表示該參數應該匹配任意「路徑」。
+
+所以你可以這樣使用它:
+
+{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}
+
+/// tip
+
+你可能需要這個參數包含 `/home/johndoe/myfile.txt`,也就是前面帶有斜線(`/`)。
+
+在那種情況下,URL 會是:`/files//home/johndoe/myfile.txt`,在 `files` 與 `home` 之間有兩個斜線(`//`)。
+
+///
+
+## 回顧 { #recap }
+
+使用 **FastAPI**,只要撰寫簡短、直覺且標準的 Python 型別宣告,你就能獲得:
+
+* 編輯器支援:錯誤檢查、自動完成等
+* 資料 "解析"
+* 資料驗證
+* API 註解與自動產生文件
+
+而且你只要宣告一次就好。
+
+這大概是 **FastAPI** 相較於其他框架最明顯的優勢之一(除了原始效能之外)。
diff --git a/docs/zh-hant/docs/tutorial/query-param-models.md b/docs/zh-hant/docs/tutorial/query-param-models.md
new file mode 100644
index 0000000000000..e360281990f76
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/query-param-models.md
@@ -0,0 +1,68 @@
+# 查詢參數模型 { #query-parameter-models }
+
+如果你有一組具有相關性的**查詢參數**,你可以建立一個 **Pydantic 模型**來聲明它們。
+
+這將允許你在**多個地方**去**重複使用模型**,並且一次性為所有參數聲明驗證和元資料 (metadata)。😎
+
+/// note
+
+FastAPI 從 `0.115.0` 版本開始支援這個特性。🤓
+
+///
+
+## 使用 Pydantic 模型的查詢參數 { #query-parameters-with-a-pydantic-model }
+
+在一個 **Pydantic 模型**中聲明你需要的**查詢參數**,然後將參數聲明為 `Query`:
+
+{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}
+
+**FastAPI** 將會從請求的**查詢參數**中**提取**出**每個欄位**的資料,並將其提供給你定義的 Pydantic 模型。
+
+## 查看文件 { #check-the-docs }
+
+你可以在 `/docs` 頁面的 UI 中查看查詢參數:
+
+
+
+
+### 查詢參數清單/多個值的預設值 { #query-parameter-list-multiple-values-with-defaults }
+
+也可以在未提供任何值時,定義 `list` 型別的預設值:
+
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
+
+如果你前往:
+
+```
+http://localhost:8000/items/
+```
+
+`q` 的預設值會是:`["foo", "bar"]`,而回應會是:
+
+```JSON
+{
+ "q": [
+ "foo",
+ "bar"
+ ]
+}
+```
+
+#### 只使用 `list` { #using-just-list }
+
+你也可以直接使用 `list`,而不是 `list[str]`:
+
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
+
+/// note | 注意
+
+注意,在這種情況下,FastAPI 不會檢查清單的內容。
+
+例如,`list[int]` 會檢查(並文件化)清單內容為整數;但單獨使用 `list` 則不會。
+
+///
+
+## 宣告更多中繼資料 { #declare-more-metadata }
+
+你可以為參數加入更多資訊。
+
+這些資訊會被包含在產生的 OpenAPI 中,供文件 UI 與外部工具使用。
+
+/// note | 注意
+
+請留意,不同工具對 OpenAPI 的支援程度可能不同。
+
+有些工具可能暫時還不會顯示所有額外資訊;不過多半這些缺漏功能已在開發規劃中。
+
+///
+
+你可以加入 `title`:
+
+{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *}
+
+以及 `description`:
+
+{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *}
+
+## 別名參數 { #alias-parameters }
+
+想像你希望參數名稱是 `item-query`。
+
+像這樣:
+
+```
+http://127.0.0.1:8000/items/?item-query=foobaritems
+```
+
+但 `item-query` 不是合法的 Python 變數名稱。
+
+最接近的大概是 `item_query`。
+
+但你仍然需要它就是 `item-query`...
+
+那你可以宣告一個 `alias`,實際上就會用這個別名來讀取參數值:
+
+{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *}
+
+## 棄用參數 { #deprecating-parameters }
+
+現在假設你不再喜歡這個參數了。
+
+你必須暫時保留它,因為還有用戶端在用,但你希望文件能清楚標示它是已棄用。
+
+接著把參數 `deprecated=True` 傳給 `Query`:
+
+{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *}
+
+文件會這樣顯示:
+
+
+
+## 從 OpenAPI 排除參數 { #exclude-parameters-from-openapi }
+
+若要把某個查詢參數從產生的 OpenAPI(以及自動文件系統)中排除,將 `Query` 的 `include_in_schema` 設為 `False`:
+
+{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *}
+
+## 自訂驗證 { #custom-validation }
+
+有時你需要做一些上述參數無法處理的「自訂驗證」。
+
+這種情況下,你可以使用「自訂驗證函式」,它會在一般驗證之後套用(例如先確認值是 `str` 之後)。
+
+你可以在 `Annotated` 中使用 [Pydantic 的 `AfterValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-after-validator) 來達成。
+
+/// tip | 提示
+
+Pydantic 也有 [`BeforeValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-before-validator) 等等。🤓
+
+///
+
+例如,以下自訂驗證器會檢查項目 ID 是否以 `isbn-` 開頭(ISBN 書籍編號),或以 `imdb-` 開頭(IMDB 電影 URL 的 ID):
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
+
+/// info | 說明
+
+這需搭配 Pydantic 2 或以上版本。😎
+
+///
+
+/// tip | 提示
+
+如果你需要做任何需要與「外部元件」溝通的驗證(例如資料庫或其他 API),應該改用「FastAPI 依賴」(FastAPI Dependencies),你稍後會學到。
+
+這些自訂驗證器適用於只需使用請求中「同一份資料」即可完成的檢查。
+
+///
+
+### 理解這段程式碼 { #understand-that-code }
+
+重點就是在 `Annotated` 中使用「`AfterValidator` 搭配函式」。如果你願意,可以略過這一節。🤸
+
+---
+
+但如果你對這個範例感到好奇且仍有興致,以下是一些額外細節。
+
+#### 使用 `value.startswith()` 的字串 { #string-with-value-startswith }
+
+你注意到了嗎?字串的 `value.startswith()` 可以接收一個 tuple,並逐一檢查 tuple 中的每個值:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *}
+
+#### 隨機項目 { #a-random-item }
+
+透過 `data.items()` 我們會得到一個包含每個字典項目鍵值對 tuple 的 iterable object。
+
+我們用 `list(data.items())` 把這個可疊代物件轉成正式的 `list`。
+
+接著用 `random.choice()` 從清單中取得一個「隨機值」,也就是一個 `(id, name)` 的 tuple。可能像是 `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")`。
+
+然後把這個 tuple 的兩個值分別指定給變數 `id` 和 `name`。
+
+因此,即使使用者沒有提供 item ID,仍然會收到一個隨機建議。
+
+……而這全部只用一行簡單的程式碼完成。🤯 你不愛 Python 嗎?🐍
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *}
+
+## 重點回顧 { #recap }
+
+你可以為參數宣告額外的驗證與中繼資料。
+
+通用的驗證與中繼資料:
+
+- `alias`
+- `title`
+- `description`
+- `deprecated`
+
+字串專用的驗證:
+
+- `min_length`
+- `max_length`
+- `pattern`
+
+使用 `AfterValidator` 的自訂驗證。
+
+在這些範例中,你看到了如何為 `str` 值宣告驗證。
+
+接下來的章節會示範如何為其他型別(像是數字)宣告驗證。
diff --git a/docs/zh-hant/docs/tutorial/query-params.md b/docs/zh-hant/docs/tutorial/query-params.md
new file mode 100644
index 0000000000000..89c0834565a48
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/query-params.md
@@ -0,0 +1,187 @@
+# 查詢參數 { #query-parameters }
+
+當你宣告不是路徑參數的其他函式參數時,會自動被視為「查詢(query)」參數。
+
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
+
+查詢是出現在 URL 中 `?` 之後的一組鍵值對,以 `&` 字元分隔。
+
+例如,URL:
+
+```
+http://127.0.0.1:8000/items/?skip=0&limit=10
+```
+
+...查詢參數為:
+
+* `skip`:值為 `0`
+* `limit`:值為 `10`
+
+因為它們是 URL 的一部分,天生是字串。
+
+但當你以 Python 型別宣告它們(如上例中的 `int`),它們會被轉換成該型別並據此驗證。
+
+對於查詢參數,會套用與路徑參數相同的處理流程:
+
+* 編輯器支援(當然)
+* 資料 「解析」
+* 資料驗證
+* 自動文件
+
+## 預設值 { #defaults }
+
+由於查詢參數不是路徑的固定部分,因此可以是選填並具有預設值。
+
+在上面的例子中,預設值為 `skip=0` 與 `limit=10`。
+
+因此,造訪下列 URL:
+
+```
+http://127.0.0.1:8000/items/
+```
+
+等同於造訪:
+
+```
+http://127.0.0.1:8000/items/?skip=0&limit=10
+```
+
+但如果你改為造訪:
+
+```
+http://127.0.0.1:8000/items/?skip=20
+```
+
+函式中的參數值會是:
+
+* `skip=20`:因為你在 URL 中設定了它
+* `limit=10`:因為那是預設值
+
+## 選用參數 { #optional-parameters }
+
+同樣地,你可以將預設值設為 `None` 來宣告選用的查詢參數:
+
+{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *}
+
+在這種情況下,函式參數 `q` 為選用,且預設為 `None`。
+
+/// check | 注意
+
+另外請注意,FastAPI 能辨識出路徑參數 `item_id` 是路徑參數,而 `q` 不是,因此 `q` 會被當作查詢參數。
+
+///
+
+## 查詢參數型別轉換 { #query-parameter-type-conversion }
+
+你也可以宣告 `bool` 型別,值會被自動轉換:
+
+{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *}
+
+在這種情況下,如果你造訪:
+
+```
+http://127.0.0.1:8000/items/foo?short=1
+```
+
+或
+
+```
+http://127.0.0.1:8000/items/foo?short=True
+```
+
+或
+
+```
+http://127.0.0.1:8000/items/foo?short=true
+```
+
+或
+
+```
+http://127.0.0.1:8000/items/foo?short=on
+```
+
+或
+
+```
+http://127.0.0.1:8000/items/foo?short=yes
+```
+
+或任何其他大小寫變化(全大寫、首字母大寫等),你的函式會將參數 `short` 視為 `bool` 值 `True`。否則為 `False`。
+
+## 多個路徑與查詢參數 { #multiple-path-and-query-parameters }
+
+你可以同時宣告多個路徑參數與查詢參數,FastAPI 會自動分辨。
+
+而且不必按特定順序宣告。
+
+會依名稱辨識:
+
+{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *}
+
+## 必填查詢參數 { #required-query-parameters }
+
+當你為非路徑參數(目前我們只看到查詢參數)宣告了預設值時,它就不是必填。
+
+若你不想提供特定預設值、只想讓它為選填,將預設值設為 `None`。
+
+但若你要讓查詢參數成為必填,只要不要宣告任何預設值:
+
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
+
+此處查詢參數 `needy` 是必填的 `str`。
+
+如果你在瀏覽器中開啟如下的 URL:
+
+```
+http://127.0.0.1:8000/items/foo-item
+```
+
+...沒有加上必填的 `needy` 參數,你會看到類似這樣的錯誤:
+
+```JSON
+{
+ "detail": [
+ {
+ "type": "missing",
+ "loc": [
+ "query",
+ "needy"
+ ],
+ "msg": "Field required",
+ "input": null
+ }
+ ]
+}
+```
+
+由於 `needy` 是必填參數,你需要在 URL 中設定它:
+
+```
+http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
+```
+
+...這樣就會成功:
+
+```JSON
+{
+ "item_id": "foo-item",
+ "needy": "sooooneedy"
+}
+```
+
+當然,你可以同時定義部分參數為必填、部分有預設值、部分為選填:
+
+{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *}
+
+在此例中,有 3 個查詢參數:
+
+* `needy`,必填的 `str`。
+* `skip`,具有預設值 `0` 的 `int`。
+* `limit`,選填的 `int`。
+
+/// tip | 提示
+
+你也可以像在[路徑參數](path-params.md#predefined-values)中一樣使用 `Enum`。
+
+///
diff --git a/docs/zh-hant/docs/tutorial/request-files.md b/docs/zh-hant/docs/tutorial/request-files.md
new file mode 100644
index 0000000000000..4e20544ea4aa4
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/request-files.md
@@ -0,0 +1,176 @@
+# 請求中的檔案 { #request-files }
+
+你可以使用 `File` 定義由用戶端上傳的檔案。
+
+/// info
+
+若要接收上傳的檔案,請先安裝 [`python-multipart`](https://github.com/Kludex/python-multipart)。
+
+請先建立並啟用一個[虛擬環境](../virtual-environments.md),然後安裝,例如:
+
+```console
+$ pip install python-multipart
+```
+
+因為上傳的檔案是以「表單資料」送出的。
+
+///
+
+## 匯入 `File` { #import-file }
+
+從 `fastapi` 匯入 `File` 與 `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
+
+## 定義 `File` 參數 { #define-file-parameters }
+
+和 `Body` 或 `Form` 一樣的方式建立檔案參數:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
+
+/// info
+
+`File` 是直接繼承自 `Form` 的類別。
+
+但請記住,當你從 `fastapi` 匯入 `Query`、`Path`、`File` 等時,它們其實是回傳特殊類別的函式。
+
+///
+
+/// tip
+
+要宣告檔案本文,必須使用 `File`,否則參數會被解讀為查詢參數或本文(JSON)參數。
+
+///
+
+檔案會以「表單資料」上傳。
+
+如果你將路徑操作函式(path operation function)的參數型別宣告為 `bytes`,**FastAPI** 會替你讀取檔案,你會以 `bytes` 取得內容。
+
+請注意,這表示整個內容會存放在記憶體中,適合小檔案。
+
+但在許多情況下,使用 `UploadFile` 會更好。
+
+## 使用 `UploadFile` 的檔案參數 { #file-parameters-with-uploadfile }
+
+將檔案參數型別設為 `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
+
+使用 `UploadFile` 相較於 `bytes` 有數個優點:
+
+* 你不必在參數的預設值使用 `File()`。
+* 它使用「spooled」檔案:
+ * 檔案在記憶體中保存到某個大小上限,超過上限後會存到磁碟。
+* 因此適合處理大型檔案(例如圖片、影片、大型二進位檔等),而不會耗盡記憶體。
+* 你可以取得上傳檔案的中繼資料。
+* 它提供一個[file-like](https://docs.python.org/3/glossary.html#term-file-like-object) 的 `async` 介面。
+* 它會提供實際的 Python [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) 物件,你可以直接傳給需要類檔案物件的其他函式或函式庫。
+
+### `UploadFile` { #uploadfile }
+
+`UploadFile` 具有以下屬性:
+
+* `filename`:一個 `str`,為上傳的原始檔名(例如 `myimage.jpg`)。
+* `content_type`:一個 `str`,為內容類型(MIME type / media type)(例如 `image/jpeg`)。
+* `file`:一個 [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile)(一個[file-like](https://docs.python.org/3/glossary.html#term-file-like-object) 物件)。這是真正的 Python 檔案物件,你可以直接傳給期待「類檔案」物件的其他函式或函式庫。
+
+`UploadFile` 有以下 `async` 方法。它們底層會呼叫對應的檔案方法(使用內部的 `SpooledTemporaryFile`)。
+
+* `write(data)`:將 `data` (`str` 或 `bytes`) 寫入檔案。
+* `read(size)`:讀取檔案的 `size` (`int`) 個位元組/字元。
+* `seek(offset)`:移動到檔案中的位元組位置 `offset` (`int`)。
+ * 例如,`await myfile.seek(0)` 會移到檔案開頭。
+ * 當你已經執行過 `await myfile.read()`,之後需要再次讀取內容時特別有用。
+* `close()`:關閉檔案。
+
+由於這些都是 `async` 方法,你需要以 await 呼叫它們。
+
+例如,在 `async` 的路徑操作函式中可這樣讀取內容:
+
+```Python
+contents = await myfile.read()
+```
+
+若是在一般的 `def` 路徑操作函式中,你可以直接存取 `UploadFile.file`,例如:
+
+```Python
+contents = myfile.file.read()
+```
+
+/// note | `async` 技術細節
+
+當你使用這些 `async` 方法時,**FastAPI** 會在執行緒池中執行對應的檔案方法並等待結果。
+
+///
+
+/// note | Starlette 技術細節
+
+**FastAPI** 的 `UploadFile` 直接繼承自 **Starlette** 的 `UploadFile`,但新增了一些必要部分,使其與 **Pydantic** 及 FastAPI 其他部分相容。
+
+///
+
+## 什麼是「表單資料」 { #what-is-form-data }
+
+HTML 表單(``)送到伺服器的資料通常使用一種「特殊」編碼,與 JSON 不同。
+
+**FastAPI** 會從正確的位置讀取該資料,而不是當作 JSON。
+
+/// note | 技術細節
+
+表單資料在不包含檔案時,通常使用媒體型別 `application/x-www-form-urlencoded` 編碼。
+
+但當表單包含檔案時,會使用 `multipart/form-data` 編碼。若你使用 `File`,**FastAPI** 會知道要從請求本文的正確部分取得檔案。
+
+若想進一步了解這些編碼與表單欄位,請參考 [MDN web docs 的 `POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)。
+
+///
+
+/// warning
+
+你可以在一個路徑操作中宣告多個 `File` 與 `Form` 參數,但不能同時宣告預期以 JSON 接收的 `Body` 欄位,因為此請求的本文會使用 `multipart/form-data` 而不是 `application/json`。
+
+這不是 **FastAPI** 的限制,而是 HTTP 協定本身的規範。
+
+///
+
+## 可選的檔案上傳 { #optional-file-upload }
+
+可透過一般型別註解並將預設值設為 `None` 使檔案成為可選:
+
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
+
+## `UploadFile` 搭配額外中繼資料 { #uploadfile-with-additional-metadata }
+
+你也可以在 `UploadFile` 上搭配 `File()`,例如用來設定額外的中繼資料:
+
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
+
+## 多檔案上傳 { #multiple-file-uploads }
+
+可以同時上傳多個檔案。
+
+它們會同屬於以「表單資料」送出的同一個表單欄位。
+
+要這麼做,將型別宣告為 `bytes` 或 `UploadFile` 的 `list`:
+
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
+
+你會如宣告所示,收到由 `bytes` 或 `UploadFile` 組成的 `list`。
+
+/// note | 技術細節
+
+你也可以使用 `from starlette.responses import HTMLResponse`。
+
+**FastAPI** 為了讓你(開發者)更方便,提供與 `starlette.responses` 相同的內容作為 `fastapi.responses`。但大多數可用的回應類型其實直接來自 Starlette。
+
+///
+
+### 多檔案上傳且包含額外中繼資料 { #multiple-file-uploads-with-additional-metadata }
+
+同樣地,即使對 `UploadFile`,你也可以用 `File()` 設定額外參數:
+
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
+
+## 小結 { #recap }
+
+使用 `File`、`bytes` 與 `UploadFile` 來宣告請求中要上傳的檔案,這些檔案會以表單資料送出。
diff --git a/docs/zh-hant/docs/tutorial/request-form-models.md b/docs/zh-hant/docs/tutorial/request-form-models.md
new file mode 100644
index 0000000000000..f8a0e8c6c5368
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# 表單模型 { #form-models }
+
+你可以使用 **Pydantic 模型** 在 FastAPI 中宣告 **表單欄位**。
+
+/// info | 說明
+
+要使用表單,首先安裝 [`python-multipart`](https://github.com/Kludex/python-multipart)。
+
+請先建立[虛擬環境](../virtual-environments.md)、啟用後再安裝,例如:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | 注意
+
+此功能自 FastAPI 版本 `0.113.0` 起支援。🤓
+
+///
+
+## 針對表單的 Pydantic 模型 { #pydantic-models-for-forms }
+
+你只需要宣告一個 **Pydantic 模型**,包含你要接收為 **表單欄位** 的欄位,然後將參數宣告為 `Form`:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
+
+**FastAPI** 會從請求中的 **表單資料** 擷取 **各欄位** 的資料,並將這些資料組成你定義的 Pydantic 模型實例。
+
+## 檢視文件 { #check-the-docs }
+
+你可以在 `/docs` 的文件 UI 中驗證:
+
+
+
+
+而且兩個模型都會用在互動式 API 文件中:
+
+
+
+## 其他回傳型別註解 { #other-return-type-annotations }
+
+有時你回傳的東西不是有效的 Pydantic 欄位,你仍會在函式上加上註解,只為了獲得工具(編輯器、mypy 等)提供的支援。
+
+### 直接回傳 Response { #return-a-response-directly }
+
+最常見的情況是[直接回傳 Response(在進階文件中稍後會解釋)](../advanced/response-directly.md)。
+
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
+
+這個簡單情境會由 FastAPI 自動處理,因為回傳型別註解是 `Response` 類別(或其子類別)。
+
+而工具也會滿意,因為 `RedirectResponse` 與 `JSONResponse` 都是 `Response` 的子類別,所以型別註解是正確的。
+
+### 註解為某個 Response 的子類別 { #annotate-a-response-subclass }
+
+你也可以在型別註解中使用 `Response` 的子類別:
+
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
+
+這同樣可行,因為 `RedirectResponse` 是 `Response` 的子類別,而 FastAPI 會自動處理這種簡單情況。
+
+### 無效的回傳型別註解 { #invalid-return-type-annotations }
+
+但當你回傳其他任意物件(例如資料庫物件),它不是有效的 Pydantic 型別,並且你在函式上也這樣註解時,FastAPI 會嘗試從該型別註解建立一個 Pydantic 回應模型,因而失敗。
+
+如果你有像是多種型別的聯集,其中一個或多個不是有效的 Pydantic 型別,也會發生相同的事情,例如這個就會失敗 💥:
+
+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
+
+...這會失敗,因為該型別註解不是 Pydantic 型別,且它也不只是一個單一的 `Response` 類別或其子類別,而是 `Response` 與 `dict` 的聯集(兩者任一)。
+
+### 停用回應模型 { #disable-response-model }
+
+延續上面的例子,你可能不想要 FastAPI 執行預設的資料驗證、文件化、過濾等動作。
+
+但你可能仍想在函式上保留回傳型別註解,以獲得編輯器與型別檢查工具(例如 mypy)的支援。
+
+這種情況下,你可以設定 `response_model=None` 來停用回應模型的產生:
+
+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}
+
+這會讓 FastAPI 略過回應模型的產生,如此你就能使用任何你需要的回傳型別註解,而不會影響你的 FastAPI 應用程式。🤓
+
+## 回應模型編碼參數 { #response-model-encoding-parameters }
+
+你的回應模型可能有預設值,例如:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}
+
+* `description: Union[str, None] = None`(或在 Python 3.10 中的 `str | None = None`)預設為 `None`。
+* `tax: float = 10.5` 預設為 `10.5`。
+* `tags: List[str] = []` 預設為空的 list:`[]`。
+
+但如果這些值其實沒有被儲存,你可能想要在結果中省略它們。
+
+例如,如果你在 NoSQL 資料庫中有包含許多選擇性屬性的模型,但你不想傳送充滿預設值的冗長 JSON 回應。
+
+### 使用 `response_model_exclude_unset` 參數 { #use-the-response-model-exclude-unset-parameter }
+
+你可以在「路徑操作裝飾器」上設定 `response_model_exclude_unset=True`:
+
+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}
+
+如此這些預設值就不會被包含在回應中,只有實際被設定的值才會包含。
+
+因此,如果你對該「路徑操作」發送針對 ID 為 `foo` 的項目的請求,回應(不包含預設值)會是:
+
+```JSON
+{
+ "name": "Foo",
+ "price": 50.2
+}
+```
+
+/// info | 說明
+
+你也可以使用:
+
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
+
+如 [Pydantic 文件](https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict)中對 `exclude_defaults` 與 `exclude_none` 的說明。
+
+///
+
+#### 對於有預設值欄位也有實際值的資料 { #data-with-values-for-fields-with-defaults }
+
+但如果你的資料在模型中對於有預設值的欄位也有實際值,例如 ID 為 `bar` 的項目:
+
+```Python hl_lines="3 5"
+{
+ "name": "Bar",
+ "description": "The bartenders",
+ "price": 62,
+ "tax": 20.2
+}
+```
+
+它們會被包含在回應中。
+
+#### 與預設值相同的資料 { #data-with-the-same-values-as-the-defaults }
+
+如果資料的值與預設值相同,例如 ID 為 `baz` 的項目:
+
+```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`。
+
+它們可以是一個 list(`[]`)、一個 `float` 的 `10.5`,等等。
+
+///
+
+### `response_model_include` 與 `response_model_exclude` { #response-model-include-and-response-model-exclude }
+
+你也可以使用「路徑操作裝飾器」參數 `response_model_include` 與 `response_model_exclude`。
+
+它們接受一個由屬性名稱字串所組成的 `set`,分別用來包含(省略其他)或排除(包含其他)屬性。
+
+如果你只有一個 Pydantic 模型並且想從輸出移除部分資料,這可以作為一個快速捷徑。
+
+/// tip | 提示
+
+但仍建議使用上面提到的作法,使用多個類別,而不是這些參數。
+
+因為在你的應用程式 OpenAPI(與文件)中所產生的 JSON Schema 仍會是完整模型的,即便你使用 `response_model_include` 或 `response_model_exclude` 省略了一些屬性。
+
+`response_model_by_alias` 也有類似的情況。
+
+///
+
+{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}
+
+/// tip | 提示
+
+語法 `{"name", "description"}` 會建立一個包含這兩個值的 `set`。
+
+它等同於 `set(["name", "description"])`。
+
+///
+
+#### 使用 `list` 來代替 `set` { #using-lists-instead-of-sets }
+
+如果你忘了使用 `set` 而用了 `list` 或 `tuple`,FastAPI 仍會把它轉換成 `set`,並能正確運作:
+
+{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}
+
+## 重點回顧 { #recap }
+
+使用「路徑操作裝飾器」的 `response_model` 參數來定義回應模型,特別是為了確保私有資料被過濾掉。
+
+使用 `response_model_exclude_unset` 僅回傳被明確設定的值。
diff --git a/docs/zh-hant/docs/tutorial/response-status-code.md b/docs/zh-hant/docs/tutorial/response-status-code.md
new file mode 100644
index 0000000000000..9ac2e41dab67d
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/response-status-code.md
@@ -0,0 +1,101 @@
+# 回應狀態碼 { #response-status-code }
+
+就像你可以指定回應模型一樣,你也可以在任一個「路徑操作(path operation)」的參數 `status_code` 中宣告回應所使用的 HTTP 狀態碼:
+
+* `@app.get()`
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+* 等等
+
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
+
+/// note | 注意
+
+請注意,`status_code` 是「裝飾器(decorator)」方法(`get`、`post` 等等)的參數,而不是你的「路徑操作函式」的參數,就像所有的參數與 body 一樣。
+
+///
+
+參數 `status_code` 接受一個數字作為 HTTP 狀態碼。
+
+/// info | 資訊
+
+`status_code` 也可以接收一個 `IntEnum`,例如 Python 的 [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus)。
+
+///
+
+它會:
+
+* 在回應中傳回該狀態碼。
+* 在 OpenAPI 結構中如此記錄(因此也會反映在使用者介面中):
+
+
+
+/// note | 注意
+
+有些回應碼(見下一節)表示回應不包含本文(body)。
+
+FastAPI 知道這點,並會產生聲明「無回應本文」的 OpenAPI 文件。
+
+///
+
+## 關於 HTTP 狀態碼 { #about-http-status-codes }
+
+/// note | 注意
+
+如果你已經知道什麼是 HTTP 狀態碼,可以直接跳到下一節。
+
+///
+
+在 HTTP 中,你會在回應的一部分傳回 3 位數的狀態碼。
+
+這些狀態碼有對應的名稱以便辨識,但重點是數字本身。
+
+簡而言之:
+
+* `100 - 199` 表示「資訊」。你很少會直接使用它們。這些狀態碼的回應不可包含本文。
+* **`200 - 299`** 表示「成功」。這是你最常使用的一組。
+ * `200` 是預設狀態碼,表示一切「OK」。
+ * 另一個例子是 `201`,代表「已建立」。常用於在資料庫中建立新紀錄之後。
+ * 一個特殊情況是 `204`,代表「無內容」。當沒有內容要回傳給用戶端時使用,因此回應不得有本文。
+* **`300 - 399`** 表示「重新導向」。這些狀態碼的回應可能有或沒有本文,唯獨 `304`(「未修改」)必須沒有本文。
+* **`400 - 499`** 表示「用戶端錯誤」。這大概是你第二常用的一組。
+ * 例如 `404`,代表「找不到」。
+ * 對於一般性的用戶端錯誤,你可以使用 `400`。
+* `500 - 599` 表示伺服器錯誤。你幾乎不會直接使用它們。當你的應用程式或伺服器某處出錯時,會自動回傳其中一個狀態碼。
+
+/// tip | 提示
+
+想深入瞭解各狀態碼與其用途,請參考 [MDN 關於 HTTP 狀態碼的文件](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)。
+
+///
+
+## 快速記住名稱 { #shortcut-to-remember-the-names }
+
+再看一次前面的範例:
+
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
+
+`201` 是「已建立(Created)」的狀態碼。
+
+但你不需要背下每個代碼代表什麼。
+
+你可以使用 `fastapi.status` 提供的便利變數。
+
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
+
+它們只是方便用的常數,值與數字相同,但這樣你可以用編輯器的自動完成來找到它們:
+
+
+
+/// note | 技術細節
+
+你也可以使用 `from starlette import status`。
+
+**FastAPI** 將同一個 `starlette.status` 以 `fastapi.status` 形式提供,純粹是為了讓你(開發者)方便。但它直接來自 Starlette。
+
+///
+
+## 變更預設值 { #changing-the-default }
+
+稍後在 [進階使用者指南](../advanced/response-change-status-code.md) 中,你會看到如何回傳一個不同於此處所宣告預設值的狀態碼。
diff --git a/docs/zh-hant/docs/tutorial/schema-extra-example.md b/docs/zh-hant/docs/tutorial/schema-extra-example.md
new file mode 100644
index 0000000000000..1c2caef85b193
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/schema-extra-example.md
@@ -0,0 +1,202 @@
+# 宣告請求範例資料 { #declare-request-example-data }
+
+你可以宣告你的應用程式可接收資料的 examples。
+
+以下有數種方式可達成。
+
+## Pydantic 模型中的額外 JSON Schema 資料 { #extra-json-schema-data-in-pydantic-models }
+
+你可以為 Pydantic 模型宣告 `examples`,它們會加入到產生出的 JSON Schema 中。
+
+{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}
+
+這些額外資訊會原封不動加入該模型輸出的 JSON Schema,並且會用在 API 文件裡。
+
+你可以使用屬性 `model_config`(接收一個 `dict`),詳見 [Pydantic 文件:Configuration](https://docs.pydantic.dev/latest/api/config/)。
+
+你可以將 `"json_schema_extra"` 設為一個 `dict`,其中包含你想在產生的 JSON Schema 中出現的任何額外資料,包括 `examples`。
+
+/// tip
+
+你可以用相同技巧擴充 JSON Schema,加入你自己的自訂額外資訊。
+
+例如,你可以用它為前端使用者介面新增中繼資料等。
+
+///
+
+/// info
+
+OpenAPI 3.1.0(自 FastAPI 0.99.0 起使用)新增了對 `examples` 的支援,這是 **JSON Schema** 標準的一部分。
+
+在那之前,只支援使用單一範例的關鍵字 `example`。OpenAPI 3.1.0 仍然支援 `example`,但它已被棄用,且不是 JSON Schema 標準的一部分。因此建議你將 `example` 遷移為 `examples`。🤓
+
+你可以在本頁結尾閱讀更多。
+
+///
+
+## `Field` 其他參數 { #field-additional-arguments }
+
+在 Pydantic 模型中使用 `Field()` 時,你也可以宣告額外的 `examples`:
+
+{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}
+
+## JSON Schema 的 `examples` - OpenAPI { #examples-in-json-schema-openapi }
+
+當使用下列任一項:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+你也可以宣告一組 `examples`,包含會加入到 **OpenAPI** 中它們各自 **JSON Schemas** 的額外資訊。
+
+### `Body` 搭配 `examples` { #body-with-examples }
+
+這裡我們傳入 `examples`,其中包含 `Body()` 預期資料的一個範例:
+
+{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *}
+
+### 文件 UI 中的範例 { #example-in-the-docs-ui }
+
+使用以上任一方法,在 `/docs` 中看起來會像這樣:
+
+
+
+### `Body` 搭配多個 `examples` { #body-with-multiple-examples }
+
+當然,你也可以傳入多個 `examples`:
+
+{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *}
+
+這麼做時,這些範例會成為該 body 資料內部 **JSON Schema** 的一部分。
+
+然而,撰寫本文時,負責呈現文件 UI 的工具 Swagger UI 並不支援在 **JSON Schema** 中顯示多個範例。不過請繼續往下閱讀以取得變通方式。
+
+### OpenAPI 特定的 `examples` { #openapi-specific-examples }
+
+在 **JSON Schema** 支援 `examples` 之前,OpenAPI 就已支援另一個同名的欄位 `examples`。
+
+這個「OpenAPI 特定」的 `examples` 位於 OpenAPI 規範的另一個區塊:在每個「路徑操作」的詳細資訊中,而不是在各個 JSON Schema 內。
+
+而 Swagger UI 早已支援這個欄位,因此你可以用它在文件 UI 中顯示不同的範例。
+
+這個 OpenAPI 特定欄位 `examples` 的結構是一個包含「多個範例」的 `dict`(而非 `list`),每個範例都可包含會一併加入到 **OpenAPI** 的額外資訊。
+
+它不會出現在 OpenAPI 所含的各個 JSON Schema 內,而是直接放在對應的「路徑操作」上。
+
+### 使用 `openapi_examples` 參數 { #using-the-openapi-examples-parameter }
+
+你可以在 FastAPI 中透過參數 `openapi_examples` 為下列項目宣告 OpenAPI 特定的 `examples`:
+
+* `Path()`
+* `Query()`
+* `Header()`
+* `Cookie()`
+* `Body()`
+* `Form()`
+* `File()`
+
+該 `dict` 的鍵用來識別各個範例,而每個值則是另一個 `dict`。
+
+在 `examples` 中,每個範例的 `dict` 可以包含:
+
+* `summary`:範例的簡短描述。
+* `description`:較長的描述,可包含 Markdown 文字。
+* `value`:實際顯示的範例,例如一個 `dict`。
+* `externalValue`:`value` 的替代方案,為指向範例的 URL。儘管這可能不如 `value` 被工具廣泛支援。
+
+你可以這樣使用:
+
+{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *}
+
+### 文件 UI 中的 OpenAPI 範例 { #openapi-examples-in-the-docs-ui }
+
+當在 `Body()` 加上 `openapi_examples`,`/docs` 會顯示為:
+
+
+
+## 技術細節 { #technical-details }
+
+/// tip
+
+如果你已經在使用 **FastAPI** **0.99.0 或以上**的版本,大概可以略過這些細節。
+
+這些內容比較與舊版(在 OpenAPI 3.1.0 可用之前)相關。
+
+你可以把這段當作一小堂 OpenAPI 與 JSON Schema 的歷史課。🤓
+
+///
+
+/// warning
+
+以下是關於 **JSON Schema** 與 **OpenAPI** 標準的技術細節。
+
+如果上面的做法對你已經足夠可用,就不需要這些細節,儘管直接跳過。
+
+///
+
+在 OpenAPI 3.1.0 之前,OpenAPI 使用的是較舊且經過修改的 **JSON Schema** 版本。
+
+當時 JSON Schema 沒有 `examples`,因此 OpenAPI 在它自訂修改的版本中新增了自己的 `example` 欄位。
+
+OpenAPI 也在規範的其他部分新增了 `example` 與 `examples` 欄位:
+
+* [`Parameter Object`(規範)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object),對應到 FastAPI 的:
+ * `Path()`
+ * `Query()`
+ * `Header()`
+ * `Cookie()`
+* [`Request Body Object` 中的 `content` 欄位裡的 `Media Type Object`(規範)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object),對應到 FastAPI 的:
+ * `Body()`
+ * `File()`
+ * `Form()`
+
+/// info
+
+這個舊的、OpenAPI 特定的 `examples` 參數,從 FastAPI `0.103.0` 起改名為 `openapi_examples`。
+
+///
+
+### JSON Schema 的 `examples` 欄位 { #json-schemas-examples-field }
+
+後來 JSON Schema 在新版本規範中新增了 [`examples`](https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.9.5) 欄位。
+
+接著新的 OpenAPI 3.1.0 以最新版本(JSON Schema 2020-12)為基礎,該版本就包含這個新的 `examples` 欄位。
+
+現在這個新的 `examples` 欄位優先於舊的單一(且客製)`example` 欄位,後者已被棄用。
+
+JSON Schema 中新的 `examples` 欄位「就是一個 `list`」的範例集合,而不是像 OpenAPI 其他地方(如上所述)那樣附帶額外中繼資料的 `dict`。
+
+/// info
+
+即使 OpenAPI 3.1.0 已發佈並與 JSON Schema 有更簡潔的整合,一段時間內提供自動文件的 Swagger UI 並不支援 OpenAPI 3.1.0(自 5.0.0 版起支援 🎉)。
+
+因此,FastAPI 0.99.0 之前的版本仍使用 3.1.0 以下的 OpenAPI 版本。
+
+///
+
+### Pydantic 與 FastAPI 的 `examples` { #pydantic-and-fastapi-examples }
+
+當你在 Pydantic 模型中加入 `examples`,不論是用 `schema_extra` 或 `Field(examples=["something"])`,該範例都會被加入該 Pydantic 模型的 **JSON Schema**。
+
+而該 Pydantic 模型的 **JSON Schema** 會被包含到你的 API 的 **OpenAPI** 中,接著用於文件 UI。
+
+在 FastAPI 0.99.0 之前的版本(0.99.0 起使用較新的 OpenAPI 3.1.0)中,當你對其他工具(`Query()`、`Body()` 等)使用 `example` 或 `examples` 時,這些範例不會被加入描述該資料的 JSON Schema(甚至不會加入到 OpenAPI 自己版本的 JSON Schema 中),而是直接加入到 OpenAPI 中的「路徑操作」宣告(在 OpenAPI 使用 JSON Schema 的那些部分之外)。
+
+但現在 FastAPI 0.99.0 以上使用的 OpenAPI 3.1.0 搭配 JSON Schema 2020-12,以及 Swagger UI 5.0.0 以上版本,整體更加一致,範例會包含在 JSON Schema 中。
+
+### Swagger UI 與 OpenAPI 特定的 `examples` { #swagger-ui-and-openapi-specific-examples }
+
+由於在(2023-08-26 時)Swagger UI 不支援多個 JSON Schema 範例,使用者無法在文件中顯示多個範例。
+
+為了解決此問題,FastAPI `0.103.0` 透過新參數 `openapi_examples` **新增支援** 宣告舊的「OpenAPI 特定」`examples` 欄位。🤓
+
+### 總結 { #summary }
+
+我以前常說我不太喜歡歷史……結果現在在這裡講「科技史」。😅
+
+簡而言之,**升級到 FastAPI 0.99.0 或以上**,事情會更**簡單、一致又直覺**,而且你不需要了解這些歷史細節。😎
diff --git a/docs/zh-hant/docs/tutorial/security/first-steps.md b/docs/zh-hant/docs/tutorial/security/first-steps.md
new file mode 100644
index 0000000000000..7f12ec1a3a478
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/security/first-steps.md
@@ -0,0 +1,203 @@
+# 安全性 - 入門 { #security-first-steps }
+
+想像你有一個部署在某個網域的後端 API。
+
+還有一個前端在另一個網域,或同一網域的不同路徑(或是行動應用程式)。
+
+你希望前端能用使用者名稱與密碼向後端進行身分驗證。
+
+我們可以用 OAuth2 搭配 FastAPI 來實作。
+
+但不必通讀整份冗長規格只為了找出你需要的幾個重點。
+
+就用 FastAPI 提供的工具處理安全性。
+
+## 看起來如何 { #how-it-looks }
+
+先直接跑範例看效果,再回頭理解其原理。
+
+## 建立 `main.py` { #create-main-py }
+
+將範例複製到檔案 `main.py`:
+
+{* ../../docs_src/security/tutorial001_an_py310.py *}
+
+## 執行 { #run-it }
+
+/// info
+
+當你使用 `pip install "fastapi[standard]"` 指令安裝時,[`python-multipart`](https://github.com/Kludex/python-multipart) 套件會隨 FastAPI 自動安裝。
+
+不過若只執行 `pip install fastapi`,預設不會包含 `python-multipart`。
+
+若要手動安裝,請先建立並啟用一個[虛擬環境](../../virtual-environments.md),接著執行:
+
+```console
+$ pip install python-multipart
+```
+
+因為 OAuth2 會以「form data」傳送 `username` 與 `password`。
+
+///
+
+用以下指令執行範例:
+
+
+
+/// check | Authorize 按鈕!
+
+你會看到一個新的「Authorize」按鈕。
+
+而你的「路徑操作」右上角也會出現一個小鎖頭可以點擊。
+
+///
+
+點擊後會跳出一個小視窗,讓你輸入 `username` 與 `password`(以及其他可選欄位):
+
+
+
+/// note | 注意
+
+不管你在表單輸入什麼,現在都還不會成功;等等我們會把它完成。
+
+///
+
+這當然不是給最終使用者用的前端,但它是用來互動式文件化整個 API 的極佳自動化工具。
+
+前端團隊(也可能就是你)可以使用它。
+
+第三方應用或系統也能使用它。
+
+你也能用它來除錯、檢查與測試同一個應用。
+
+## `password` 流程 { #the-password-flow }
+
+現在回頭理解剛剛那些是什麼。
+
+在 OAuth2 中,`password` 是處理安全與身分驗證的其中一種「流程」(flow)。
+
+OAuth2 的設計讓後端或 API 可以獨立於執行使用者驗證的伺服器。
+
+但在這個例子中,同一個 FastAPI 應用會同時處理 API 與驗證。
+
+簡化來看流程如下:
+
+- 使用者在前端輸入 `username` 與 `password`,按下 `Enter`。
+- 前端(在使用者的瀏覽器中執行)把 `username` 與 `password` 傳到我們 API 的特定 URL(在程式中宣告為 `tokenUrl="token"`)。
+- API 檢查 `username` 與 `password`,並回傳一個「token(權杖)」(我們還沒實作這部分)。
+ - 「token(權杖)」就是一段字串,之後可用來識別並驗證此使用者。
+ - 通常 token 會設定一段時間後失效。
+ - 因此使用者之後需要重新登入。
+ - 若 token 被竊取,風險也較低;它不像永遠有效的萬用鑰匙(多數情況下)。
+- 前端會暫存這個 token。
+- 使用者在前端點擊前往其他頁面/區段。
+- 前端需要再向 API 取得資料。
+ - 但該端點需要驗證。
+ - 因此為了向 API 驗證,請求會帶上一個 `Authorization` 標頭,值為 `Bearer ` 加上 token。
+ - 例如 token 是 `foobar`,則 `Authorization` 標頭內容為:`Bearer foobar`。
+
+## FastAPI 的 `OAuth2PasswordBearer` { #fastapis-oauth2passwordbearer }
+
+FastAPI 提供多層抽象的工具來實作這些安全機制。
+
+本例將使用 OAuth2 的 Password 流程,並以 Bearer token 進行驗證;我們會用 `OAuth2PasswordBearer` 類別來完成。
+
+/// info
+
+「Bearer」token 不是唯一選項。
+
+但對本例最合適。
+
+通常對多數情境也足夠,除非你是 OAuth2 專家並確信有更適合你的選項。
+
+在那種情況下,FastAPI 也提供相應工具讓你自行組合。
+
+///
+
+當我們建立 `OAuth2PasswordBearer` 類別的實例時,會傳入 `tokenUrl` 參數。這個參數包含了客戶端(在使用者瀏覽器中執行的前端)用來送出 `username` 與 `password` 以取得 token 的 URL。
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
+
+/// tip
+
+這裡的 `tokenUrl="token"` 指的是尚未建立的相對 URL `token`。因為是相對 URL,所以等同於 `./token`。
+
+由於使用了相對 URL,若你的 API 位於 `https://example.com/`,那它會指向 `https://example.com/token`;但若你的 API 位於 `https://example.com/api/v1/`,那它會指向 `https://example.com/api/v1/token`。
+
+使用相對 URL 很重要,能確保你的應用在像是[在 Proxy 後方](../../advanced/behind-a-proxy.md)這類進階情境中仍能正常運作。
+
+///
+
+這個參數不會建立該端點/「路徑操作」,而是宣告 `/token` 將是客戶端用來取得 token 的 URL。這些資訊會出現在 OpenAPI,並被互動式 API 文件系統使用。
+
+我們很快也會建立實際的路徑操作。
+
+/// info
+
+如果你是非常嚴格的「Pythonista」,可能不喜歡參數名稱用 `tokenUrl` 而不是 `token_url`。
+
+那是因為它沿用了 OpenAPI 規格中的名稱。如此一來,若你要深入查閱這些安全方案,便能直接複製貼上去搜尋更多資訊。
+
+///
+
+變數 `oauth2_scheme` 是 `OAuth2PasswordBearer` 的實例,但同時它也是「可呼叫的」(callable)。
+
+它可以這樣被呼叫:
+
+```Python
+oauth2_scheme(some, parameters)
+```
+
+因此它可以配合 `Depends` 使用。
+
+### 如何使用 { #use-it }
+
+現在你可以在相依性中傳入 `oauth2_scheme` 與 `Depends` 搭配。
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+此相依性會提供一個 `str`,指派給「路徑操作函式」的參數 `token`。
+
+FastAPI 會知道可以使用這個相依性,在 OpenAPI(以及自動產生的 API 文件)中定義一個「安全性方案」。
+
+/// info | 技術細節
+
+FastAPI 之所以知道可以用(相依性中宣告的)`OAuth2PasswordBearer` 類別,在 OpenAPI 中定義安全性方案,是因為它繼承自 `fastapi.security.oauth2.OAuth2`,而後者又繼承自 `fastapi.security.base.SecurityBase`。
+
+所有能與 OpenAPI(以及自動 API 文件)整合的安全工具都繼承自 `SecurityBase`,FastAPI 才能知道如何把它們整合進 OpenAPI。
+
+///
+
+## 它做了什麼 { #what-it-does }
+
+它會從請求中尋找 `Authorization` 標頭,檢查其值是否為 `Bearer ` 加上一段 token,並將該 token 以 `str` 回傳。
+
+若未找到 `Authorization` 標頭,或其值不是 `Bearer ` token,則會直接回傳 401(`UNAUTHORIZED`)錯誤。
+
+你不必再自行檢查 token 是否存在;你可以確信只要你的函式被執行,該 token 參數就一定會是 `str`。
+
+你可以在互動式文件中試試看:
+
+
+
+我們還沒驗證 token 是否有效,但這已是個開始。
+
+## 小結 { #recap }
+
+只需多寫 3、4 行,就能有一個基本的安全機制。
diff --git a/docs/zh-hant/docs/tutorial/security/get-current-user.md b/docs/zh-hant/docs/tutorial/security/get-current-user.md
new file mode 100644
index 0000000000000..b223d4823b1c9
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/security/get-current-user.md
@@ -0,0 +1,105 @@
+# 取得目前使用者 { #get-current-user }
+
+在前一章,基於依賴注入系統的安全機制會把一個 `token`(作為 `str`)提供給*路徑操作函式*:
+
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+但這還不太有用。
+
+讓它改為回傳目前使用者吧。
+
+## 建立使用者模型 { #create-a-user-model }
+
+先建立一個 Pydantic 的使用者模型。
+
+就像用 Pydantic 宣告請求體一樣,我們也可以在其他地方使用它:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *}
+
+## 建立 `get_current_user` 依賴 { #create-a-get-current-user-dependency }
+
+讓我們建立一個依賴 `get_current_user`。
+
+記得依賴可以有子依賴嗎?
+
+`get_current_user` 會依賴我們先前建立的相同 `oauth2_scheme`。
+
+如同先前在*路徑操作*中直接做的一樣,新的依賴 `get_current_user` 會從子依賴 `oauth2_scheme` 接收一個作為 `str` 的 `token`:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *}
+
+## 取得使用者 { #get-the-user }
+
+`get_current_user` 會使用我們建立的(假的)工具函式,它接收一個作為 `str` 的 token,並回傳我們的 Pydantic `User` 模型:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *}
+
+## 注入目前使用者 { #inject-the-current-user }
+
+現在我們可以在*路徑操作*中用相同的 `Depends` 來使用 `get_current_user`:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *}
+
+注意我們把 `current_user` 的型別宣告為 Pydantic 的 `User` 模型。
+
+這能在函式內提供自動補全與型別檢查的協助。
+
+/// tip | 提示
+
+你可能記得,請求體也會用 Pydantic 模型宣告。
+
+這裡因為你使用了 `Depends`,**FastAPI** 不會混淆。
+
+///
+
+/// check | 檢查
+
+這個依賴系統的設計讓我們可以有不同的依賴(不同的 "dependables"),都回傳 `User` 模型。
+
+我們不受限於只能有一個能回傳該類型資料的依賴。
+
+///
+
+## 其他模型 { #other-models }
+
+現在你可以在*路徑操作函式*中直接取得目前使用者,並在**依賴注入**層處理安全機制,使用 `Depends`。
+
+而且你可以為安全需求使用任意模型或資料(本例中是 Pydantic 模型 `User`)。
+
+但你不受限於某個特定的資料模型、類別或型別。
+
+想在模型中只有 `id` 與 `email` 而沒有任何 `username`?當然可以。你可以用同樣的工具達成。
+
+想只用一個 `str`?或只用一個 `dict`?或直接使用資料庫類別的模型實例?都可以,一樣運作。
+
+你的應用其實沒有真人使用者登入,而是機器人、bot,或其他系統,只持有 access token?同樣沒有問題。
+
+只要用任何你的應用需要的模型、類別或資料庫即可。**FastAPI** 的依賴注入系統都支援。
+
+## 程式碼大小 { #code-size }
+
+這個範例看起來可能有點冗長。記住我們把安全、資料模型、工具函式與*路徑操作*混在同一個檔案中。
+
+但重點在這裡。
+
+安全與依賴注入相關的內容只需要寫一次。
+
+你可以把它設計得再複雜都沒問題,仍然只需在單一位置寫一次,依然具備完整的彈性。
+
+但你可以有成千上萬個端點(*路徑操作*)共用同一套安全系統。
+
+而且它們全部(或你想要的一部分)都可以重用這些依賴,或你建立的其他依賴。
+
+而所有這些上千個*路徑操作*都可以小到只要 3 行:
+
+{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *}
+
+## 回顧 { #recap }
+
+現在你可以在*路徑操作函式*中直接取得目前使用者。
+
+我們已經完成一半了。
+
+我們只需要再新增一個*路徑操作*,讓使用者/用戶端實際送出 `username` 與 `password`。
+
+下一步就會做。
diff --git a/docs/zh-hant/docs/tutorial/security/index.md b/docs/zh-hant/docs/tutorial/security/index.md
new file mode 100644
index 0000000000000..b5e3738bcd07e
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/security/index.md
@@ -0,0 +1,101 @@
+# 安全性 { #security }
+
+有許多方式可以處理安全性、身分驗證與授權。
+
+而且這通常是一個複雜且「困難」的主題。
+
+在許多框架與系統中,光是處理安全性與身分驗證就要花費大量心力與程式碼(很多情況下可能佔了全部程式碼的 50% 以上)。
+
+**FastAPI** 提供多種工具,讓你能以標準方式輕鬆、快速地處理「安全性」,而不必先研究並學會所有安全性規範。
+
+但在此之前,先釐清幾個小概念。
+
+## 急著上手? { #in-a-hurry }
+
+如果你不在意這些術語,只需要立刻加入以使用者名稱與密碼為基礎的身分驗證與安全性,就直接跳到後續章節。
+
+## OAuth2 { #oauth2 }
+
+OAuth2 是一套規範,定義了多種處理身分驗證與授權的方法。
+
+它相當龐大,涵蓋許多複雜的使用情境。
+
+它也包含使用「第三方」進行身分驗證的方式。
+
+這正是各種「使用 Facebook、Google、X(Twitter)、GitHub 登入」系統在底層採用的機制。
+
+### OAuth 1 { #oauth-1 }
+
+過去有 OAuth 1,和 OAuth2 非常不同,也更複雜,因為它直接規範了如何加密通訊。
+
+它現在並不流行,也很少被使用。
+
+OAuth2 不規範通訊如何加密,而是假設你的應用會透過 HTTPS 提供服務。
+
+/// tip | 提示
+在部署相關章節中,你會看到如何使用 Traefik 與 Let's Encrypt 免費設定 HTTPS。
+///
+
+## OpenID Connect { #openid-connect }
+
+OpenID Connect 是基於 **OAuth2** 的另一套規範。
+
+它只是擴充了 OAuth2,釐清了 OAuth2 中相對模糊的部份,以提升互通性。
+
+例如,Google 登入使用的是 OpenID Connect(其底層使用 OAuth2)。
+
+但 Facebook 登入不支援 OpenID Connect,它有自己風格的 OAuth2。
+
+### OpenID(不是「OpenID Connect」) { #openid-not-openid-connect }
+
+過去也有一個「OpenID」規範。它試圖解決與 **OpenID Connect** 相同的問題,但不是建立在 OAuth2 之上。
+
+因此,它是一套完全額外、獨立的系統。
+
+它現在並不流行,也很少被使用。
+
+## OpenAPI { #openapi }
+
+OpenAPI(先前稱為 Swagger)是一套用於構建 API 的開放規範(現為 Linux 基金會的一部分)。
+
+**FastAPI** 建立在 **OpenAPI** 之上。
+
+這使得它能提供多種自動化的互動式文件介面、程式碼產生等功能。
+
+OpenAPI 提供定義多種安全性「方案」。
+
+透過使用它們,你可以善用這些基於標準的工具,包括這些互動式文件系統。
+
+OpenAPI 定義了下列安全性方案:
+
+* `apiKey`:應用程式特定的金鑰,來源可以是:
+ * 查詢參數。
+ * 標頭(header)。
+ * Cookie。
+* `http`:標準的 HTTP 驗證系統,包括:
+ * `bearer`:使用 `Authorization` 標頭,值為 `Bearer ` 加上一個 token。這是從 OAuth2 延伸而來。
+ * HTTP Basic 驗證。
+ * HTTP Digest 等。
+* `oauth2`:所有 OAuth2 的安全性處理方式(稱為「flows」)。
+ * 其中數個 flow 適合用來建立 OAuth 2.0 身分驗證提供者(如 Google、Facebook、X(Twitter)、GitHub 等):
+ * `implicit`
+ * `clientCredentials`
+ * `authorizationCode`
+ * 但有一個特定的 flow 可直接在同一個應用中處理身分驗證:
+ * `password`:後續幾個章節會示範這個。
+* `openIdConnect`:提供一種方式來定義如何自動發現 OAuth2 的身分驗證資訊。
+ * 這種自動探索機制即由 OpenID Connect 規範定義。
+
+/// tip | 提示
+整合像 Google、Facebook、X(Twitter)、GitHub 等其他身分驗證/授權提供者也是可行而且相對容易。
+
+最複雜的部分其實是打造一個類似那樣的身分驗證/授權提供者,但 **FastAPI** 提供了工具,能替你處理繁重工作,讓你更輕鬆完成。
+///
+
+## **FastAPI** 工具 { #fastapi-utilities }
+
+FastAPI 在 `fastapi.security` 模組中為上述各種安全性方案提供了多種工具,讓這些機制更容易使用。
+
+接下來的章節會示範如何使用這些 **FastAPI** 提供的工具,為你的 API 加入安全性。
+
+你也會看到它如何自動整合到互動式文件系統中。
diff --git a/docs/zh-hant/docs/tutorial/security/oauth2-jwt.md b/docs/zh-hant/docs/tutorial/security/oauth2-jwt.md
new file mode 100644
index 0000000000000..abd920ce6fbcf
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/security/oauth2-jwt.md
@@ -0,0 +1,277 @@
+# 使用密碼(與雜湊)的 OAuth2、以 Bearer 搭配 JWT 權杖 { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
+
+現在我們已經有完整的安全流程了,接下來用 JWT 權杖與安全的密碼雜湊,讓應用真正安全。
+
+這份程式碼可以直接用在你的應用中,把密碼雜湊存進資料庫等等。
+
+我們會從上一章的內容繼續往下擴充。
+
+## 關於 JWT { #about-jwt }
+
+JWT 的意思是「JSON Web Tokens」。
+
+它是一種把 JSON 物件編碼成一段長且緊密(沒有空白)的字串的標準。看起來像這樣:
+
+```
+eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
+```
+
+它不是加密的,所以任何人都可以從內容還原出資訊。
+
+但它是簽名過的。因此當你收到一個你所簽發的權杖時,你可以驗證確實是你簽發的。
+
+如此一來,你可以建立一個(例如)有效期為 1 週的權杖。當使用者隔天帶著這個權杖回來時,你就知道該使用者仍然登入在你的系統中。
+
+一週後,權杖會過期,使用者就不再被授權,需要再次登入以取得新的權杖。而如果使用者(或第三方)試圖修改權杖來改變有效期,你也能發現,因為簽名不會相符。
+
+如果你想玩玩看 JWT 權杖並了解其運作,請參考 [https://jwt.io](https://jwt.io/)。
+
+## 安裝 `PyJWT` { #install-pyjwt }
+
+我們需要安裝 `PyJWT` 才能在 Python 中產生與驗證 JWT 權杖。
+
+請先建立並啟用一個[虛擬環境](../../virtual-environments.md),然後安裝 `pyjwt`:
+
+
+
+用和先前相同的方式授權應用。
+
+使用下列認證資訊:
+
+Username: `johndoe`
+Password: `secret`
+
+/// check | 檢查
+
+注意在程式碼中完全沒有明文密碼「`secret`」,我們只有雜湊後的版本。
+
+///
+
+
+
+呼叫端點 `/users/me/`,你會得到類似這樣的回應:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false
+}
+```
+
+
+
+如果你打開開發者工具,可以看到送出的資料只包含權杖;密碼只會在第一次請求(用來驗證使用者並取得 access token)時送出,之後就不會再送:
+
+
+
+/// note | 注意
+
+留意標頭 `Authorization`,其值是以 `Bearer ` 開頭。
+
+///
+
+## 進階用法:`scopes` { #advanced-usage-with-scopes }
+
+OAuth2 有「scopes」的概念。
+
+你可以用它們替 JWT 權杖加上一組特定的權限。
+
+接著你可以把這個權杖直接交給某個使用者或第三方,讓他們在一組受限條件下與你的 API 互動。
+
+你可以在之後的「進階使用者指南」學到如何使用它們,以及它們如何整合進 **FastAPI**。
+
+## 小結 { #recap }
+
+依照你目前學到的內容,你可以用 OAuth2 與 JWT 等標準,設定一個安全的 **FastAPI** 應用。
+
+在幾乎任何框架中,安全性處理都會很快變得相當複雜。
+
+許多能大幅簡化工作的套件,往往必須在資料模型、資料庫與可用功能上做出很多取捨。而有些過度簡化的套件底層其實存在安全弱點。
+
+---
+
+**FastAPI** 不會在任何資料庫、資料模型或工具上做妥協。
+
+它給你完全的彈性,讓你挑選最適合你專案的組合。
+
+而且你可以直接使用許多維護良好且被廣泛採用的套件,例如 `pwdlib` 與 `PyJWT`,因為 **FastAPI** 不需要任何複雜機制就能整合外部套件。
+
+同時它也提供工具來在不犧牲彈性、穩健或安全的前提下,盡可能地簡化流程。
+
+你可以用相對簡單的方式使用並實作像 OAuth2 這樣的安全標準協定。
+
+你可以在「進階使用者指南」進一步了解如何使用 OAuth2 的「scopes」,以實作更細緻的權限系統,並遵循相同的標準。帶有 scopes 的 OAuth2 是許多大型身份驗證供應商(如 Facebook、Google、GitHub、Microsoft、X(Twitter)等)用來授權第三方應用代表其使用者與其 API 互動的機制。
diff --git a/docs/zh-hant/docs/tutorial/security/simple-oauth2.md b/docs/zh-hant/docs/tutorial/security/simple-oauth2.md
new file mode 100644
index 0000000000000..251848aa5a015
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/security/simple-oauth2.md
@@ -0,0 +1,289 @@
+# 簡易 OAuth2:Password 與 Bearer { #simple-oauth2-with-password-and-bearer }
+
+現在從上一章延伸,補上缺少的部分,完成整個安全流程。
+
+## 取得 `username` 與 `password` { #get-the-username-and-password }
+
+我們要使用 **FastAPI** 提供的安全性工具來取得 `username` 與 `password`。
+
+OAuth2 規範中,當使用「password flow」(我們現在使用的)時,用戶端/使用者必須以表單資料送出 `username` 與 `password` 欄位。
+
+而且規範要求欄位名稱必須就是這兩個,所以像是 `user-name` 或 `email` 都不行。
+
+但別擔心,你在前端要怎麼呈現給最終使用者都可以。
+
+而你的資料庫模型也可以使用任何你想要的欄位名稱。
+
+不過在登入的路徑操作(path operation)裡,我們需要使用這些名稱,才能符合規範(例如才能使用整合的 API 文件系統)。
+
+規範也說明 `username` 與 `password` 必須以表單資料傳送(也就是這裡不能用 JSON)。
+
+### `scope` { #scope }
+
+規範也說用戶端可以再送一個表單欄位「`scope`」。
+
+欄位名稱是單數的 `scope`,但實際上是由多個以空白分隔的「scopes」組成的一長串字串。
+
+每個「scope」就是一個(不含空白的)字串。
+
+它們通常用來宣告特定的權限,例如:
+
+- `users:read` 或 `users:write` 是常見的例子
+- `instagram_basic` 用在 Facebook / Instagram
+- `https://www.googleapis.com/auth/drive` 用在 Google
+
+/// info
+
+在 OAuth2 裡,「scope」只是用來宣告特定所需權限的一個字串。
+
+不論裡面是否包含像 `:` 之類的字元,或是否是一個 URL,都沒差。
+
+那些都是實作細節。
+
+對 OAuth2 而言,它們就是字串而已。
+
+///
+
+## 取得 `username` 與 `password` 的程式碼 { #code-to-get-the-username-and-password }
+
+現在用 **FastAPI** 提供的工具來處理。
+
+### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform }
+
+先匯入 `OAuth2PasswordRequestForm`,並在 `/token` 的路徑操作中,搭配 `Depends` 當作依賴使用:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}
+
+`OAuth2PasswordRequestForm` 是一個類別型依賴,它宣告了一個表單本文,包含:
+
+- `username`
+- `password`
+- 可選的 `scope` 欄位,內容是一個由空白分隔的長字串
+- 可選的 `grant_type`
+
+/// tip
+
+依規範,實際上需要一個 `grant_type` 欄位且固定值為 `password`,但 `OAuth2PasswordRequestForm` 並不會強制檢查。
+
+如果你需要強制檢查,請改用 `OAuth2PasswordRequestFormStrict` 取代 `OAuth2PasswordRequestForm`。
+
+///
+
+- 可選的 `client_id`(本例不需要)
+- 可選的 `client_secret`(本例不需要)
+
+/// info
+
+`OAuth2PasswordRequestForm` 並不是像 `OAuth2PasswordBearer` 那樣對 **FastAPI** 來說的特殊類別。
+
+`OAuth2PasswordBearer` 會讓 **FastAPI** 知道它是一個 security scheme,因此會以那種方式加入 OpenAPI。
+
+但 `OAuth2PasswordRequestForm` 只是你也可以自己撰寫的一個類別型依賴,或是你也可以直接宣告 `Form` 參數。
+
+只是因為這是很常見的用例,所以 **FastAPI** 直接內建提供,讓事情更簡單。
+
+///
+
+### 使用表單資料 { #use-the-form-data }
+
+/// tip
+
+`OAuth2PasswordRequestForm` 這個依賴類別的實例不會有以空白分隔長字串的 `scope` 屬性,而是會有一個 `scopes` 屬性,裡面是各個 scope 的實際字串清單。
+
+本示例沒有使用 `scopes`,但如果你需要,功能已經在那裡了。
+
+///
+
+現在,從(假的)資料庫裡用表單欄位的 `username` 取得使用者資料。
+
+如果沒有該使用者,就回傳「Incorrect username or password」的錯誤。
+
+我們用 `HTTPException` 這個例外來回傳錯誤:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}
+
+### 檢查密碼 { #check-the-password }
+
+這時我們已經有來自資料庫的使用者資料,但還沒檢查密碼。
+
+先把那些資料放進 Pydantic 的 `UserInDB` 模型。
+
+你絕對不要以純文字儲存密碼,所以我們會使用(假的)密碼雜湊系統。
+
+如果密碼不匹配,我們回傳同樣的錯誤。
+
+#### 密碼雜湊(hashing) { #password-hashing }
+
+「雜湊」的意思是:把一些內容(這裡是密碼)轉換成一串看起來像亂碼的位元組序列(就是字串)。
+
+只要你輸入完全相同的內容(完全相同的密碼),就會得到完全相同的亂碼。
+
+但你無法從這串亂碼還原回原本的密碼。
+
+##### 為何要做密碼雜湊 { #why-use-password-hashing }
+
+如果你的資料庫被竊取,攻擊者拿到的不是使用者的純文字密碼,而只是雜湊值。
+
+因此攻擊者無法嘗試把那些密碼用在其他系統上(因為很多使用者在各處都用同一組密碼,這會很危險)。
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}
+
+#### 關於 `**user_dict**` { #about-user-dict }
+
+`UserInDB(**user_dict)` 的意思是:
+
+把 `user_dict` 的鍵和值直接當作具名參數傳入,等同於:
+
+```Python
+UserInDB(
+ username = user_dict["username"],
+ email = user_dict["email"],
+ full_name = user_dict["full_name"],
+ disabled = user_dict["disabled"],
+ hashed_password = user_dict["hashed_password"],
+)
+```
+
+/// info
+
+想更完整地了解 `**user_dict`,請回到[**額外模型** 的文件](../extra-models.md#about-user-in-dict)。
+
+///
+
+## 回傳 token { #return-the-token }
+
+`token` 端點的回應必須是 JSON 物件。
+
+它應該有一個 `token_type`。在本例中,我們使用「Bearer」tokens,token 類型應該是「`bearer`」。
+
+而且它還應該有一個 `access_token`,其值為包含我們存取權杖的字串。
+
+在這個簡單示例中,我們會不安全地直接回傳相同的 `username` 當作 token。
+
+/// tip
+
+下一章你會看到真正安全的實作,包含密碼雜湊與 JWT tokens。
+
+但現在先把注意力放在我們需要的這些細節上。
+
+///
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}
+
+/// tip
+
+依照規範,你應該回傳一個包含 `access_token` 與 `token_type` 的 JSON,就像這個範例。
+
+這部分需要你自己在程式中完成,並確保使用這些 JSON key。
+
+這幾乎是你為了符合規範而必須自行記得正確處理的唯一事情。
+
+其餘的 **FastAPI** 都會幫你處理。
+
+///
+
+## 更新依賴項 { #update-the-dependencies }
+
+接著我們要更新依賴項。
+
+我們只想在使用者為啟用狀態時取得 `current_user`。
+
+所以,我們新增一個依賴 `get_current_active_user`,而它本身又依賴 `get_current_user`。
+
+這兩個依賴會在使用者不存在或未啟用時回傳 HTTP 錯誤。
+
+因此,在端點中,只有在使用者存在、已正確驗證且為啟用狀態時,我們才會取得使用者:
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}
+
+/// info
+
+這裡我們一併回傳值為 `Bearer` 的額外標頭 `WWW-Authenticate`,這也是規範的一部分。
+
+任何 HTTP(錯誤)狀態碼 401「UNAUTHORIZED」都應該同時回傳 `WWW-Authenticate` 標頭。
+
+在 bearer tokens(我們的情況)下,該標頭的值應該是 `Bearer`。
+
+其實你可以省略這個額外標頭,功能仍會正常。
+
+但此處加上它是為了遵循規範。
+
+同時也可能有工具會期待並使用它(現在或未來),而這可能對你或你的使用者有幫助,現在或未來皆然。
+
+這就是標準的好處...
+
+///
+
+## 實際操作看看 { #see-it-in-action }
+
+開啟互動式文件:[http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)。
+
+### 驗證身分 { #authenticate }
+
+點選「Authorize」按鈕。
+
+使用下列帳密:
+
+User: `johndoe`
+
+Password: `secret`
+
+
+
+在系統中完成驗證後,你會看到如下畫面:
+
+
+
+### 取得自己的使用者資料 { #get-your-own-user-data }
+
+現在使用 `GET` 方法呼叫路徑 `/users/me`。
+
+你會取得自己的使用者資料,如:
+
+```JSON
+{
+ "username": "johndoe",
+ "email": "johndoe@example.com",
+ "full_name": "John Doe",
+ "disabled": false,
+ "hashed_password": "fakehashedsecret"
+}
+```
+
+
+
+如果你點擊鎖頭圖示登出,然後再次嘗試相同操作,你會得到 HTTP 401 錯誤:
+
+```JSON
+{
+ "detail": "Not authenticated"
+}
+```
+
+### 未啟用的使用者 { #inactive-user }
+
+現在改用一個未啟用的使用者,使用以下帳密驗證:
+
+User: `alice`
+
+Password: `secret2`
+
+然後再呼叫 `GET` 方法的 `/users/me`。
+
+你會得到「Inactive user」的錯誤,例如:
+
+```JSON
+{
+ "detail": "Inactive user"
+}
+```
+
+## 小結 { #recap }
+
+你現在已經有足夠的工具,能為你的 API 以 `username` 與 `password` 實作一個完整的安全性系統。
+
+使用這些工具,你可以讓安全性系統相容於任何資料庫,以及任何使用者或資料模型。
+
+唯一尚未補上的細節是:它現在其實還不「安全」。
+
+在下一章,你會看到如何使用安全的密碼雜湊函式庫與 JWT tokens。
diff --git a/docs/zh-hant/docs/tutorial/server-sent-events.md b/docs/zh-hant/docs/tutorial/server-sent-events.md
new file mode 100644
index 0000000000000..ced91e358afe4
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/server-sent-events.md
@@ -0,0 +1,120 @@
+# Server-Sent Events(SSE) { #server-sent-events-sse }
+
+你可以使用 Server-Sent Events(SSE)把資料串流傳送給用戶端。
+
+這與[串流 JSON Lines](stream-json-lines.md)類似,但使用瀏覽器原生支援、透過 [`EventSource` API](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) 的 `text/event-stream` 格式。
+
+/// info
+
+在 FastAPI 0.135.0 新增。
+
+///
+
+## 什麼是 Server-Sent Events? { #what-are-server-sent-events }
+
+SSE 是一種透過 HTTP 從伺服器向用戶端串流傳送資料的標準。
+
+每個事件都是一個小型文字區塊,包含 `data`、`event`、`id` 和 `retry` 等「欄位」,並以空白行分隔。
+
+看起來像這樣:
+
+```
+data: {"name": "Portal Gun", "price": 999.99}
+
+data: {"name": "Plumbus", "price": 32.99}
+
+```
+
+SSE 常用於 AI 聊天串流、即時通知、日誌與可觀察性,以及其他由伺服器主動推送更新給用戶端的情境。
+
+/// tip
+
+如果你要串流二進位資料,例如影片或音訊,請參考進階指南:[串流資料](../advanced/stream-data.md)。
+
+///
+
+## 使用 FastAPI 串流 SSE { #stream-sse-with-fastapi }
+
+要在 FastAPI 中串流 SSE,請在你的路徑操作函式(path operation function)中使用 `yield`,並設定 `response_class=EventSourceResponse`。
+
+從 `fastapi.sse` 匯入 `EventSourceResponse`:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[4,22] *}
+
+每個 `yield` 的項目都會以 JSON 編碼並放在 SSE 事件的 `data:` 欄位中送出。
+
+如果你把回傳型別宣告為 `AsyncIterable[Item]`,FastAPI 會用它來透過 Pydantic 進行**驗證**、**文件化**與**序列化**。
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[10:12,23] *}
+
+/// tip
+
+因為 Pydantic 會在 **Rust** 端進行序列化,如果你有宣告回傳型別,效能會比未宣告時高很多。
+
+///
+
+### 非 async 的路徑操作函式 { #non-async-path-operation-functions }
+
+你也可以使用一般的 `def` 函式(沒有 `async`),並同樣使用 `yield`。
+
+FastAPI 會確保正確執行,不會阻塞事件迴圈。
+
+由於此函式不是 async,正確的回傳型別是 `Iterable[Item]`:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[28:31] hl[29] *}
+
+### 無回傳型別 { #no-return-type }
+
+你也可以省略回傳型別。FastAPI 會使用 [`jsonable_encoder`](./encoder.md) 轉換資料並送出。
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[34:37] hl[35] *}
+
+## `ServerSentEvent` { #serversentevent }
+
+如果你需要設定 `event`、`id`、`retry` 或 `comment` 等 SSE 欄位,你可以改為 `yield` 出 `ServerSentEvent` 物件,而不是單純的資料。
+
+從 `fastapi.sse` 匯入 `ServerSentEvent`:
+
+{* ../../docs_src/server_sent_events/tutorial002_py310.py hl[4,26] *}
+
+`data` 欄位一律會以 JSON 編碼。你可以傳入任何可序列化為 JSON 的值,包括 Pydantic 模型。
+
+## 原始資料 { #raw-data }
+
+如果你需要在**不**進行 JSON 編碼的情況下傳送資料,請使用 `raw_data` 取代 `data`。
+
+這對於傳送已格式化的文字、日誌行或特殊的 "哨兵" 值(例如 `[DONE]`)很有用。
+
+{* ../../docs_src/server_sent_events/tutorial003_py310.py hl[17] *}
+
+/// note
+
+`data` 與 `raw_data` 互斥。每個 `ServerSentEvent` 只能設定其中一個。
+
+///
+
+## 使用 `Last-Event-ID` 繼續 { #resuming-with-last-event-id }
+
+當瀏覽器在連線中斷後重新連線時,會在 `Last-Event-ID` 標頭中傳送最後接收到的 `id`。
+
+你可以將它作為標頭參數讀取,並用來從用戶端中斷處繼續串流:
+
+{* ../../docs_src/server_sent_events/tutorial004_py310.py hl[25,27,31] *}
+
+## 使用 POST 的 SSE { #sse-with-post }
+
+SSE 可搭配**任何 HTTP 方法**,不僅限於 `GET`。
+
+這對於像是透過 `POST` 串流 SSE 的協定(例如 [MCP](https://modelcontextprotocol.io))很有用:
+
+{* ../../docs_src/server_sent_events/tutorial005_py310.py hl[14] *}
+
+## 技術細節 { #technical-details }
+
+FastAPI 內建實作了一些 SSE 的最佳實務。
+
+- 當 15 秒內沒有任何訊息時,傳送一次**「保活」`ping` 註解**,以避免某些代理伺服器關閉連線;此作法源自於[HTML 規範:Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes)中的建議。
+- 設定 `Cache-Control: no-cache` 標頭,以**防止快取**串流內容。
+- 設定特殊標頭 `X-Accel-Buffering: no`,以**避免**在像 Nginx 這類代理中被**緩衝**。
+
+你不需要做任何事,開箱即用。🤓
diff --git a/docs/zh-hant/docs/tutorial/sql-databases.md b/docs/zh-hant/docs/tutorial/sql-databases.md
new file mode 100644
index 0000000000000..a37e164321ffc
--- /dev/null
+++ b/docs/zh-hant/docs/tutorial/sql-databases.md
@@ -0,0 +1,357 @@
+# SQL(關聯式)資料庫 { #sql-relational-databases }
+
+FastAPI 不強制你使用 SQL(關聯式)資料庫。你可以使用任何你想要的資料庫。
+
+這裡我們會用 [SQLModel](https://sqlmodel.tiangolo.com/) 作為範例。
+
+SQLModel 建立在 [SQLAlchemy](https://www.sqlalchemy.org/) 與 Pydantic 之上。它由 FastAPI 的作者開發,非常適合需要使用 SQL 資料庫的 FastAPI 應用。
+
+/// tip | 提示
+
+你可以使用任何你想用的 SQL 或 NoSQL 資料庫函式庫(有時稱為 "ORMs"),FastAPI 不會強迫你使用特定工具。😎
+
+///
+
+因為 SQLModel 建立在 SQLAlchemy 之上,你可以輕鬆使用 SQLAlchemy 所支援的任何資料庫(因此 SQLModel 也支援),例如:
+
+* PostgreSQL
+* MySQL
+* SQLite
+* Oracle
+* Microsoft SQL Server,等等。
+
+在這個範例中,我們會使用 SQLite,因為它只用到單一檔案,而且 Python 內建支援。你可以直接複製這個範例並原樣執行。
+
+之後,在你的正式環境應用中,你可能會想使用像 PostgreSQL 這類的資料庫伺服器。
+
+/// tip | 提示
+
+有一個包含 FastAPI 與 PostgreSQL 的官方專案腳手架,還有前端與更多工具:[https://github.com/fastapi/full-stack-fastapi-template](https://github.com/fastapi/full-stack-fastapi-template)
+
+///
+
+這是一份非常簡短的教學,如果你想更全面學習資料庫、SQL,或更進階的功能,請參考 [SQLModel 文件](https://sqlmodel.tiangolo.com/)。
+
+## 安裝 `SQLModel` { #install-sqlmodel }
+
+首先,請先建立你的[虛擬環境](../virtual-environments.md)、啟用它,然後安裝 `sqlmodel`:
+
+
+
+lt
+* XWT
+* PSGI
+
+### abbr 提供了完整短语与解释 { #the-abbr-gives-a-full-phrase-and-an-explanation }
+
+* MDN
+* I/O.
+
+////
+
+//// tab | 信息
+
+"abbr" 元素的 "title" 属性需要按照特定规则进行翻译。
+
+译文可以自行添加 "abbr" 元素以解释英语单词,LLM 不应删除这些元素。
+
+参见 `scripts/translate.py` 中通用提示的 `### HTML abbr elements` 部分。
+
+////
+
+## HTML "dfn" 元素 { #html-dfn-elements }
+
+* 集群
+* 深度学习
+
+## 标题 { #headings }
+
+//// tab | 测试
+
+### 开发 Web 应用——教程 { #develop-a-webapp-a-tutorial }
+
+Hello.
+
+### 类型提示与注解 { #type-hints-and-annotations }
+
+Hello again.
+
+### 超类与子类 { #super-and-subclasses }
+
+Hello again.
+
+////
+
+//// tab | 信息
+
+关于标题的唯一硬性规则是:LLM 必须保持花括号内的哈希部分不变,以确保链接不会失效。
+
+参见 `scripts/translate.py` 中通用提示的 `### Headings` 部分。
+
+语言特定的说明可参见例如 `docs/de/llm-prompt.md` 中的 `### Headings` 部分。
+
+////
+
+## 文档中使用的术语 { #terms-used-in-the-docs }
+
+//// tab | 测试
+
+* you
+* your
+
+* e.g.
+* etc.
+
+* `foo` as an `int`
+* `bar` as a `str`
+* `baz` as a `list`
+
+* the Tutorial - User guide
+* the Advanced User Guide
+* the SQLModel docs
+* the API docs
+* the automatic docs
+
+* Data Science
+* Deep Learning
+* Machine Learning
+* Dependency Injection
+* HTTP Basic authentication
+* HTTP Digest
+* ISO format
+* the JSON Schema standard
+* the JSON schema
+* the schema definition
+* Password Flow
+* Mobile
+
+* deprecated
+* designed
+* invalid
+* on the fly
+* standard
+* default
+* case-sensitive
+* case-insensitive
+
+* to serve the application
+* to serve the page
+
+* the app
+* the application
+
+* the request
+* the response
+* the error response
+
+* the path operation
+* the path operation decorator
+* the path operation function
+
+* the body
+* the request body
+* the response body
+* the JSON body
+* the form body
+* the file body
+* the function body
+
+* the parameter
+* the body parameter
+* the path parameter
+* the query parameter
+* the cookie parameter
+* the header parameter
+* the form parameter
+* the function parameter
+
+* the event
+* the startup event
+* the startup of the server
+* the shutdown event
+* the lifespan event
+
+* the handler
+* the event handler
+* the exception handler
+* to handle
+
+* the model
+* the Pydantic model
+* the data model
+* the database model
+* the form model
+* the model object
+
+* the class
+* the base class
+* the parent class
+* the subclass
+* the child class
+* the sibling class
+* the class method
+
+* the header
+* the headers
+* the authorization header
+* the `Authorization` header
+* the forwarded header
+
+* the dependency injection system
+* the dependency
+* the dependable
+* the dependant
+
+* I/O bound
+* CPU bound
+* concurrency
+* parallelism
+* multiprocessing
+
+* the env var
+* the environment variable
+* the `PATH`
+* the `PATH` variable
+
+* the authentication
+* the authentication provider
+* the authorization
+* the authorization form
+* the authorization provider
+* the user authenticates
+* the system authenticates the user
+
+* the CLI
+* the command line interface
+
+* the server
+* the client
+
+* the cloud provider
+* the cloud service
+
+* the development
+* the development stages
+
+* the dict
+* the dictionary
+* the enumeration
+* the enum
+* the enum member
+
+* the encoder
+* the decoder
+* to encode
+* to decode
+
+* the exception
+* to raise
+
+* the expression
+* the statement
+
+* the frontend
+* the backend
+
+* the GitHub discussion
+* the GitHub issue
+
+* the performance
+* the performance optimization
+
+* the return type
+* the return value
+
+* the security
+* the security scheme
+
+* the task
+* the background task
+* the task function
+
+* the template
+* the template engine
+
+* the type annotation
+* the type hint
+
+* the server worker
+* the Uvicorn worker
+* the Gunicorn Worker
+* the worker process
+* the worker class
+* the workload
+
+* the deployment
+* to deploy
+
+* the SDK
+* the software development kit
+
+* the `APIRouter`
+* the `requirements.txt`
+* the Bearer Token
+* the breaking change
+* the bug
+* the button
+* the callable
+* the code
+* the commit
+* the context manager
+* the coroutine
+* the database session
+* the disk
+* the domain
+* the engine
+* the fake X
+* the HTTP GET method
+* the item
+* the library
+* the lifespan
+* the lock
+* the middleware
+* the mobile application
+* the module
+* the mounting
+* the network
+* the origin
+* the override
+* the payload
+* the processor
+* the property
+* the proxy
+* the pull request
+* the query
+* the RAM
+* the remote machine
+* the status code
+* the string
+* the tag
+* the web framework
+* the wildcard
+* to return
+* to validate
+
+////
+
+//// tab | 信息
+
+这是一份不完整且非规范性的(主要是)技术术语清单,取自文档中常见的词汇。它可能有助于提示词设计者判断哪些术语需要对 LLM 提供额外指引。例如当它总是把一个好的译法改回次优译法,或在你的语言中对某个术语的词形变化有困难时。
+
+参见例如 `docs/de/llm-prompt.md` 中的 `### List of English terms and their preferred German translations` 部分。
+
+////
diff --git a/docs/zh/docs/about/index.md b/docs/zh/docs/about/index.md
new file mode 100644
index 0000000000000..9b73533f7fdf2
--- /dev/null
+++ b/docs/zh/docs/about/index.md
@@ -0,0 +1,3 @@
+# 关于 { #about }
+
+关于 FastAPI、其设计、灵感等。🤓
diff --git a/docs/zh/docs/advanced/additional-responses.md b/docs/zh/docs/advanced/additional-responses.md
new file mode 100644
index 0000000000000..365ba3db4fa31
--- /dev/null
+++ b/docs/zh/docs/advanced/additional-responses.md
@@ -0,0 +1,247 @@
+# OpenAPI 中的附加响应 { #additional-responses-in-openapi }
+
+/// warning | 警告
+
+这是一个相对高级的话题。
+
+如果你刚开始使用 **FastAPI**,可能暂时用不到。
+
+///
+
+你可以声明附加响应,包括额外的状态码、媒体类型、描述等。
+
+这些附加响应会被包含在 OpenAPI 模式中,因此它们也会出现在 API 文档中。
+
+但是对于这些附加响应,你必须确保直接返回一个 `Response`(例如 `JSONResponse`),并携带你的状态码和内容。
+
+## 带有 `model` 的附加响应 { #additional-response-with-model }
+
+你可以向你的*路径操作装饰器*传入参数 `responses`。
+
+它接收一个 `dict`:键是每个响应的状态码(例如 `200`),值是包含该响应信息的另一个 `dict`。
+
+这些响应的每个 `dict` 都可以有一个键 `model`,包含一个 Pydantic 模型,就像 `response_model` 一样。
+
+**FastAPI** 会获取该模型,生成它的 JSON Schema,并将其放在 OpenAPI 中的正确位置。
+
+例如,要声明另一个状态码为 `404` 且具有 Pydantic 模型 `Message` 的响应,你可以这样写:
+
+{* ../../docs_src/additional_responses/tutorial001_py310.py hl[18,22] *}
+
+/// note | 注意
+
+记住你需要直接返回 `JSONResponse`。
+
+///
+
+/// info | 信息
+
+`model` 键不是 OpenAPI 的一部分。
+
+**FastAPI** 会从这里获取 Pydantic 模型,生成 JSON Schema,并把它放到正确的位置。
+
+正确的位置是:
+
+* 在键 `content` 中,它的值是另一个 JSON 对象(`dict`),该对象包含:
+ * 一个媒体类型作为键,例如 `application/json`,它的值是另一个 JSON 对象,该对象包含:
+ * 一个键 `schema`,它的值是来自该模型的 JSON Schema,这里就是正确的位置。
+ * **FastAPI** 会在这里添加一个引用,指向你 OpenAPI 中另一个位置的全局 JSON Schemas,而不是直接内联。这样,其他应用和客户端可以直接使用这些 JSON Schemas,提供更好的代码生成工具等。
+
+///
+
+为该*路径操作*在 OpenAPI 中生成的响应将是:
+
+```JSON hl_lines="3-12"
+{
+ "responses": {
+ "404": {
+ "description": "Additional Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Message"
+ }
+ }
+ }
+ },
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Item"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+这些模式在 OpenAPI 模式中被引用到另一个位置:
+
+```JSON hl_lines="4-16"
+{
+ "components": {
+ "schemas": {
+ "Message": {
+ "title": "Message",
+ "required": [
+ "message"
+ ],
+ "type": "object",
+ "properties": {
+ "message": {
+ "title": "Message",
+ "type": "string"
+ }
+ }
+ },
+ "Item": {
+ "title": "Item",
+ "required": [
+ "id",
+ "value"
+ ],
+ "type": "object",
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
+ },
+ "value": {
+ "title": "Value",
+ "type": "string"
+ }
+ }
+ },
+ "ValidationError": {
+ "title": "ValidationError",
+ "required": [
+ "loc",
+ "msg",
+ "type"
+ ],
+ "type": "object",
+ "properties": {
+ "loc": {
+ "title": "Location",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "msg": {
+ "title": "Message",
+ "type": "string"
+ },
+ "type": {
+ "title": "Error Type",
+ "type": "string"
+ }
+ }
+ },
+ "HTTPValidationError": {
+ "title": "HTTPValidationError",
+ "type": "object",
+ "properties": {
+ "detail": {
+ "title": "Detail",
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+## 主响应的其他媒体类型 { #additional-media-types-for-the-main-response }
+
+你可以使用同一个 `responses` 参数为同一个主响应添加不同的媒体类型。
+
+例如,你可以添加一个额外的媒体类型 `image/png`,声明你的*路径操作*可以返回 JSON 对象(媒体类型为 `application/json`)或 PNG 图片:
+
+{* ../../docs_src/additional_responses/tutorial002_py310.py hl[17:22,26] *}
+
+/// note | 注意
+
+请注意,你必须直接使用 `FileResponse` 返回图片。
+
+///
+
+/// info | 信息
+
+除非你在 `responses` 参数中明确指定不同的媒体类型,否则 FastAPI 会假设响应与主响应类具有相同的媒体类型(默认是 `application/json`)。
+
+但是如果你指定了一个媒体类型为 `None` 的自定义响应类,FastAPI 会对任何具有关联模型的附加响应使用 `application/json`。
+
+///
+
+## 组合信息 { #combining-information }
+
+你也可以把来自多个位置的响应信息组合在一起,包括 `response_model`、`status_code` 和 `responses` 参数。
+
+你可以声明一个 `response_model`,使用默认状态码 `200`(或根据需要使用自定义状态码),然后在 `responses` 中直接在 OpenAPI 模式里为同一个响应声明附加信息。
+
+**FastAPI** 会保留来自 `responses` 的附加信息,并把它与你的模型生成的 JSON Schema 合并。
+
+例如,你可以声明一个状态码为 `404` 的响应,它使用一个 Pydantic 模型并带有自定义的 `description`。
+
+以及一个状态码为 `200` 的响应,它使用你的 `response_model`,但包含自定义的 `example`:
+
+{* ../../docs_src/additional_responses/tutorial003_py310.py hl[20:31] *}
+
+所有这些都会被合并并包含到你的 OpenAPI 中,并显示在 API 文档里:
+
+
+
+## 组合预定义响应和自定义响应 { #combine-predefined-responses-and-custom-ones }
+
+你可能希望有一些适用于许多*路径操作*的预定义响应,但同时又想把它们与每个*路径操作*所需的自定义响应组合在一起。
+
+在这些情况下,你可以使用 Python 的“解包”`dict` 的技巧 `**dict_to_unpack`:
+
+```Python
+old_dict = {
+ "old key": "old value",
+ "second old key": "second old value",
+}
+new_dict = {**old_dict, "new key": "new value"}
+```
+
+这里,`new_dict` 将包含来自 `old_dict` 的所有键值对,再加上新的键值对:
+
+```Python
+{
+ "old key": "old value",
+ "second old key": "second old value",
+ "new key": "new value",
+}
+```
+
+你可以使用该技巧在*路径操作*中重用一些预定义响应,并把它们与额外的自定义响应组合在一起。
+
+例如:
+
+{* ../../docs_src/additional_responses/tutorial004_py310.py hl[11:15,24] *}
+
+## 关于 OpenAPI 响应的更多信息 { #more-information-about-openapi-responses }
+
+要查看响应中究竟可以包含什么,你可以查看 OpenAPI 规范中的以下部分:
+
+* [OpenAPI Responses 对象](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responses-object),它包含 `Response Object`。
+* [OpenAPI Response 对象](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#response-object),你可以把这里的任何内容直接包含到 `responses` 参数中的每个响应里。包括 `description`、`headers`、`content`(在这里声明不同的媒体类型和 JSON Schemas),以及 `links`。
diff --git a/docs/zh/docs/advanced/additional-status-codes.md b/docs/zh/docs/advanced/additional-status-codes.md
index 54ec9775b6204..af212ad8b1be1 100644
--- a/docs/zh/docs/advanced/additional-status-codes.md
+++ b/docs/zh/docs/advanced/additional-status-codes.md
@@ -1,10 +1,10 @@
-# 额外的状态码
+# 额外的状态码 { #additional-status-codes }
**FastAPI** 默认使用 `JSONResponse` 返回一个响应,将你的 *路径操作* 中的返回内容放到该 `JSONResponse` 中。
**FastAPI** 会自动使用默认的状态码或者使用你在 *路径操作* 中设置的状态码。
-## 额外的状态码
+## 额外的状态码 { #additional-status-codes_1 }
如果你想要返回主要状态码之外的状态码,你可以通过直接返回一个 `Response` 来实现,比如 `JSONResponse`,然后直接设置额外的状态码。
@@ -12,26 +12,30 @@
但是你也希望它能够接受新的条目。并且当这些条目不存在时,会自动创建并返回 201 「创建」的 HTTP 状态码。
-要实现它,导入 `JSONResponse`,然后在其中直接返回你的内容,并将 `status_code` 设置为为你要的值。
+要实现它,导入 `JSONResponse`,然后在其中直接返回你的内容,并将 `status_code` 设置为你要的值。
-```Python hl_lines="4 25"
-{!../../../docs_src/additional_status_codes/tutorial001.py!}
-```
+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
-!!! warning "警告"
- 当你直接返回一个像上面例子中的 `Response` 对象时,它会直接返回。
+/// warning
- FastAPI 不会用模型等对该响应进行序列化。
+当你直接返回一个像上面例子中的 `Response` 对象时,它会直接返回。
- 确保其中有你想要的数据,且返回的值为合法的 JSON(如果你使用 `JSONResponse` 的话)。
+它不会用模型等进行序列化。
-!!! note "技术细节"
- 你也可以使用 `from starlette.responses import JSONResponse`。
+确保其中有你想要的数据,且返回的值为合法的 JSON(如果你使用 `JSONResponse` 的话)。
- 出于方便,**FastAPI** 为开发者提供同 `starlette.responses` 一样的 `fastapi.responses`。但是大多数可用的响应都是直接来自 Starlette。`status` 也是一样。
+///
-## OpenAPI 和 API 文档
+/// note | 技术细节
+
+你也可以使用 `from starlette.responses import JSONResponse`。
+
+出于方便,**FastAPI** 为开发者提供同 `starlette.responses` 一样的 `fastapi.responses`。但是大多数可用的响应都是直接来自 Starlette。`status` 也是一样。
+
+///
+
+## OpenAPI 和 API 文档 { #openapi-and-api-docs }
如果你直接返回额外的状态码和响应,它们不会包含在 OpenAPI 方案(API 文档)中,因为 FastAPI 没办法预先知道你要返回什么。
-但是你可以使用 [额外的响应](additional-responses.md){.internal-link target=_blank} 在代码中记录这些内容。
+但是你可以使用 [额外的响应](additional-responses.md) 在代码中记录这些内容。
diff --git a/docs/zh/docs/advanced/advanced-dependencies.md b/docs/zh/docs/advanced/advanced-dependencies.md
new file mode 100644
index 0000000000000..edaf964c93445
--- /dev/null
+++ b/docs/zh/docs/advanced/advanced-dependencies.md
@@ -0,0 +1,163 @@
+# 高级依赖项 { #advanced-dependencies }
+
+## 参数化的依赖项 { #parameterized-dependencies }
+
+目前我们看到的依赖项都是固定的函数或类。
+
+但有时你可能希望为依赖项设置参数,而不必声明许多不同的函数或类。
+
+假设我们要有一个依赖项,用来检查查询参数 `q` 是否包含某个固定内容。
+
+但我们希望能够把这个固定内容参数化。
+
+## “可调用”的实例 { #a-callable-instance }
+
+在 Python 中,可以让某个类的实例变成“可调用对象”(callable)。
+
+这里指的是类的实例(类本身已经是可调用的),而不是类本身。
+
+为此,声明一个 `__call__` 方法:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[12] *}
+
+在这种情况下,**FastAPI** 会使用这个 `__call__` 来检查附加参数和子依赖,并且稍后会调用它,把返回值传递给你的*路径操作函数*中的参数。
+
+## 参数化实例 { #parameterize-the-instance }
+
+现在,我们可以用 `__init__` 声明实例的参数,用来“参数化”这个依赖项:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[9] *}
+
+在本例中,**FastAPI** 不会接触或关心 `__init__`,我们会在自己的代码中直接使用它。
+
+## 创建实例 { #create-an-instance }
+
+我们可以这样创建该类的实例:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[18] *}
+
+这样就把依赖项“参数化”了,现在它内部带有属性 `checker.fixed_content` 的值 `"bar"`。
+
+## 把实例作为依赖项 { #use-the-instance-as-a-dependency }
+
+然后,我们可以在 `Depends(checker)` 中使用这个 `checker`,而不是 `Depends(FixedContentQueryChecker)`,因为依赖项是实例 `checker`,不是类本身。
+
+解析依赖项时,**FastAPI** 会像这样调用 `checker`:
+
+```Python
+checker(q="somequery")
+```
+
+...并将其返回值作为依赖项的值,传给我们的*路径操作函数*中的参数 `fixed_content_included`:
+
+{* ../../docs_src/dependencies/tutorial011_an_py310.py hl[22] *}
+
+/// tip | 提示
+
+这些看起来可能有些牵强,目前它的用处也许还不太明显。
+
+这些示例刻意保持简单,但展示了整体的工作方式。
+
+在安全相关的章节里,有一些工具函数就是以相同的方式实现的。
+
+如果你理解了这里的内容,你就已经知道那些安全工具在底层是如何工作的。
+
+///
+
+## 带 `yield` 的依赖项、`HTTPException`、`except` 与后台任务 { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+/// warning | 警告
+
+你很可能不需要了解这些技术细节。
+
+这些细节主要在你的 FastAPI 应用版本低于 0.121.0 且你正遇到带 `yield` 的依赖项问题时才有用。
+
+///
+
+带 `yield` 的依赖项随着时间演进以覆盖不同用例并修复一些问题,下面是变更摘要。
+
+### 带 `yield` 的依赖项与 `scope` { #dependencies-with-yield-and-scope }
+
+在 0.121.0 版本中,FastAPI 为带 `yield` 的依赖项新增了 `Depends(scope="function")` 的支持。
+
+使用 `Depends(scope="function")` 时,`yield` 之后的退出代码会在*路径操作函数*结束后、响应发送给客户端之前立即执行。
+
+而当使用默认的 `Depends(scope="request")` 时,`yield` 之后的退出代码会在响应发送之后执行。
+
+你可以在文档 [带 `yield` 的依赖项 - 提前退出与 `scope`](../tutorial/dependencies/dependencies-with-yield.md#early-exit-and-scope) 中了解更多。
+
+### 带 `yield` 的依赖项与 `StreamingResponse`(技术细节) { #dependencies-with-yield-and-streamingresponse-technical-details }
+
+在 FastAPI 0.118.0 之前,如果你使用带 `yield` 的依赖项,它会在*路径操作函数*返回后、发送响应之前运行 `yield` 之后的退出代码。
+
+这样做的目的是避免在等待响应通过网络传输期间不必要地占用资源。
+
+这也意味着,如果你返回的是 `StreamingResponse`,那么该带 `yield` 的依赖项的退出代码会在开始发送响应前就已经执行完毕。
+
+例如,如果你在带 `yield` 的依赖项中持有一个数据库会话,那么 `StreamingResponse` 在流式发送数据时将无法使用该会话,因为会话已经在 `yield` 之后的退出代码里被关闭了。
+
+在 0.118.0 中,这一行为被回退为:让 `yield` 之后的退出代码在响应发送之后再执行。
+
+/// info | 信息
+
+如你在下文所见,这与 0.106.0 之前的行为非常相似,但对若干边界情况做了改进和修复。
+
+///
+
+#### 需要提前执行退出代码的用例 { #use-cases-with-early-exit-code }
+
+在某些特定条件下,旧的行为(在发送响应之前执行带 `yield` 依赖项的退出代码)会更有利。
+
+例如,设想你在带 `yield` 的依赖项中仅用数据库会话来校验用户,而在*路径操作函数*中并不会再次使用该会话;同时,响应需要很长时间才能发送完,比如一个缓慢发送数据的 `StreamingResponse`,且它出于某种原因并不使用数据库。
+
+这种情况下,会一直持有数据库会话直到响应发送完毕;但如果并不再使用它,就没有必要一直占用。
+
+代码可能如下:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py *}
+
+退出代码(自动关闭 `Session`)位于:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
+
+...会在响应把慢速数据发送完之后才运行:
+
+{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
+
+但由于 `generate_stream()` 并不使用数据库会话,因此在发送响应期间保持会话打开并非必要。
+
+如果你使用的是 SQLModel(或 SQLAlchemy)并碰到这种特定用例,你可以在不再需要时显式关闭会话:
+
+{* ../../docs_src/dependencies/tutorial014_an_py310.py ln[24:28] hl[28] *}
+
+这样会话会释放数据库连接,让其他请求可以使用。
+
+如果你还有其他需要在 `yield` 依赖项中提前退出的用例,请创建一个 [GitHub 讨论问题](https://github.com/fastapi/fastapi/discussions/new?category=questions),说明你的具体用例以及为何提前关闭会对你有帮助。
+
+如果确有有力的用例需要提前关闭,我会考虑新增一种选择性启用提前关闭的方式。
+
+### 带 `yield` 的依赖项与 `except`(技术细节) { #dependencies-with-yield-and-except-technical-details }
+
+在 FastAPI 0.110.0 之前,如果你在带 `yield` 的依赖项中用 `except` 捕获了一个异常,并且没有再次抛出它,那么该异常会被自动抛出/转发给任意异常处理器或内部服务器错误处理器。
+
+在 0.110.0 中对此作出了变更,以修复将异常转发为未处理(内部服务器错误)时造成的内存消耗问题,并使其与常规 Python 代码的行为保持一致。
+
+### 后台任务与带 `yield` 的依赖项(技术细节) { #background-tasks-and-dependencies-with-yield-technical-details }
+
+在 FastAPI 0.106.0 之前,`yield` 之后抛出异常是不可行的,因为带 `yield` 的依赖项中的退出代码会在响应发送之后才执行,此时[异常处理器](../tutorial/handling-errors.md#install-custom-exception-handlers)已经运行完毕。
+
+之所以这样设计,主要是为了允许在后台任务中继续使用依赖项通过 `yield`“产出”的对象,因为退出代码会在后台任务完成之后才执行。
+
+在 FastAPI 0.106.0 中,这一行为被修改,目的是避免在等待响应通过网络传输时一直占用资源。
+
+/// tip | 提示
+
+另外,后台任务通常是一段独立的逻辑,应该单独处理,并使用它自己的资源(例如它自己的数据库连接)。
+
+因此,这样做你的代码通常会更清晰。
+
+///
+
+如果你过去依赖于旧行为,现在应在后台任务内部自行创建所需资源,并且只在内部使用不依赖于带 `yield` 依赖项资源的数据。
+
+例如,不要复用相同的数据库会话,而是在后台任务内部创建一个新的会话,并用这个新会话从数据库获取对象。然后,不是把数据库对象本身作为参数传给后台任务函数,而是传递该对象的 ID,并在后台任务函数内部再次获取该对象。
diff --git a/docs/zh/docs/advanced/advanced-python-types.md b/docs/zh/docs/advanced/advanced-python-types.md
new file mode 100644
index 0000000000000..bbc9302e861ce
--- /dev/null
+++ b/docs/zh/docs/advanced/advanced-python-types.md
@@ -0,0 +1,61 @@
+# 高级 Python 类型 { #advanced-python-types }
+
+这里有一些在使用 Python 类型时可能有用的额外想法。
+
+## 使用 `Union` 或 `Optional` { #using-union-or-optional }
+
+如果你的代码因为某些原因不能使用 `|`,例如它不是在类型注解里,而是在 `response_model=` 之类的参数中,那么你可以使用 `typing` 中的 `Union` 来代替竖线(`|`)。
+
+例如,你可以声明某个值可以是 `str` 或 `None`:
+
+```python
+from typing import Union
+
+
+def say_hi(name: Union[str, None]):
+ print(f"Hi {name}!")
+```
+
+`typing` 也提供了一个声明“可能为 `None`”的快捷方式:`Optional`。
+
+从我非常主观的角度给个小建议:
+
+- 🚨 避免使用 `Optional[SomeType]`
+- 改用 ✨`Union[SomeType, None]`✨。
+
+两者是等价的,底层其实也是一样的。但我更推荐使用 `Union` 而不是 `Optional`,因为单词“optional”(可选)看起来会暗示该值是可选的,而它真正的含义是“它可以是 `None`”,即使它并不是可选的,仍然是必填的。
+
+我认为 `Union[SomeType, None]` 更能明确表达其含义。
+
+这只是关于词语和命名的问题,但这些词语会影响你和你的队友如何看待代码。
+
+举个例子,看这段函数:
+
+```python
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+ print(f"Hey {name}!")
+```
+
+参数 `name` 被定义为 `Optional[str]`,但它并不是“可选”的,你不能不传这个参数就调用函数:
+
+```Python
+say_hi() # 哎呀,这会报错!😱
+```
+
+参数 `name` 仍然是必填的(不是“可选”),因为它没有默认值。不过,`name` 接受 `None` 作为取值:
+
+```Python
+say_hi(name=None) # 这样可以,None 是有效的 🎉
+```
+
+好消息是,在大多数情况下,你可以直接使用 `|` 来定义类型联合:
+
+```python
+def say_hi(name: str | None):
+ print(f"Hey {name}!")
+```
+
+因此,通常你不必为像 `Optional` 和 `Union` 这样的名字而操心。😎
diff --git a/docs/zh/docs/advanced/async-tests.md b/docs/zh/docs/advanced/async-tests.md
new file mode 100644
index 0000000000000..2030bb11e2b0c
--- /dev/null
+++ b/docs/zh/docs/advanced/async-tests.md
@@ -0,0 +1,99 @@
+# 异步测试 { #async-tests }
+
+您已经了解了如何使用 `TestClient` 测试 **FastAPI** 应用程序。但是到目前为止,您只了解了如何编写同步测试,而没有使用 `async` 异步函数。
+
+在测试中能够使用异步函数可能会很有用,比如当您需要异步查询数据库的时候。想象一下,您想要测试向 FastAPI 应用程序发送请求,然后验证您的后端是否成功在数据库中写入了正确的数据,与此同时您使用了异步的数据库的库。
+
+让我们看看如何才能实现这一点。
+
+## pytest.mark.anyio { #pytest-mark-anyio }
+
+如果我们想在测试中调用异步函数,那么我们的测试函数必须是异步的。 AnyIO 为此提供了一个简洁的插件,它允许我们指定一些测试函数要异步调用。
+
+## HTTPX { #httpx }
+
+即使您的 **FastAPI** 应用程序使用普通的 `def` 函数而不是 `async def` ,它本质上仍是一个 `async` 异步应用程序。
+
+`TestClient` 在内部通过一些“魔法”操作,使得您可以在普通的 `def` 测试函数中调用异步的 FastAPI 应用程序,并使用标准的 pytest。但当我们在异步函数中使用它时,这种“魔法”就不再生效了。由于测试以异步方式运行,我们无法在测试函数中继续使用 `TestClient`。
+
+`TestClient` 是基于 [HTTPX](https://www.python-httpx.org) 的。幸运的是,我们可以直接使用它来测试 API。
+
+## 示例 { #example }
+
+举个简单的例子,让我们来看一个与[更大的应用](../tutorial/bigger-applications.md)和[测试](../tutorial/testing.md)中描述的类似文件结构:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+│ └── test_main.py
+```
+
+文件 `main.py` 将包含:
+
+{* ../../docs_src/async_tests/app_a_py310/main.py *}
+
+文件 `test_main.py` 将包含针对 `main.py` 的测试,现在它可能看起来如下:
+
+{* ../../docs_src/async_tests/app_a_py310/test_main.py *}
+
+## 运行测试 { #run-it }
+
+您可以通过以下方式照常运行测试:
+
+
+
+但如果我们在“官方”URL(代理端口为 `9999`)的 `/api/v1/docs` 访问文档界面,它就能正常工作!🎉
+
+你可以在 [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs) 查看:
+
+
+
+完全符合我们的预期。✔️
+
+这是因为 FastAPI 使用该 `root_path` 在 OpenAPI 中创建默认的 `server`,其 URL 来自 `root_path`。
+
+## 附加的服务器 { #additional-servers }
+
+/// warning | 警告
+
+这是一个更高级的用例,可以跳过。
+
+///
+
+默认情况下,**FastAPI** 会在 OpenAPI 模式中使用 `root_path` 的 URL 创建一个 `server`。
+
+但你也可以提供其他备选的 `servers`,例如你希望让“同一个”文档界面同时与预发布环境和生产环境交互。
+
+如果你传入了自定义的 `servers` 列表,并且存在 `root_path`(因为你的 API 位于代理后面),**FastAPI** 会在列表开头插入一个使用该 `root_path` 的“server”。
+
+例如:
+
+{* ../../docs_src/behind_a_proxy/tutorial003_py310.py hl[4:7] *}
+
+会生成如下的 OpenAPI 模式:
+
+```JSON hl_lines="5-7"
+{
+ "openapi": "3.1.0",
+ // More stuff here
+ "servers": [
+ {
+ "url": "/api/v1"
+ },
+ {
+ "url": "https://stag.example.com",
+ "description": "Staging environment"
+ },
+ {
+ "url": "https://prod.example.com",
+ "description": "Production environment"
+ }
+ ],
+ "paths": {
+ // More stuff here
+ }
+}
+```
+
+/// tip | 提示
+
+注意这个自动生成的服务器,`url` 的值为 `/api/v1`,取自 `root_path`。
+
+///
+
+在文档界面 [http://127.0.0.1:9999/api/v1/docs](http://127.0.0.1:9999/api/v1/docs) 中,它看起来是这样的:
+
+
+
+/// tip | 提示
+
+文档界面会与你所选择的服务器交互。
+
+///
+
+/// note | 技术细节
+
+OpenAPI 规范中的 `servers` 属性是可选的。
+
+如果你没有指定 `servers` 参数,并且 `root_path` 等于 `/`,则默认情况下,生成的 OpenAPI 模式中会完全省略 `servers` 属性,这等价于只有一个 `url` 值为 `/` 的服务器。
+
+///
+
+### 从 `root_path` 禁用自动服务器 { #disable-automatic-server-from-root-path }
+
+如果你不希望 **FastAPI** 包含一个使用 `root_path` 的自动服务器,可以使用参数 `root_path_in_servers=False`:
+
+{* ../../docs_src/behind_a_proxy/tutorial004_py310.py hl[9] *}
+
+这样它就不会被包含到 OpenAPI 模式中。
+
+## 挂载子应用 { #mounting-a-sub-application }
+
+如果你需要在使用带有 `root_path` 的代理时挂载一个子应用(参见 [子应用 - 挂载](sub-applications.md)),你可以像预期的那样正常操作。
+
+FastAPI 会在内部智能地使用 `root_path`,因此它可以直接正常工作。✨
diff --git a/docs/zh/docs/advanced/custom-response.md b/docs/zh/docs/advanced/custom-response.md
index 155ce28828b0b..ce595572dd06e 100644
--- a/docs/zh/docs/advanced/custom-response.md
+++ b/docs/zh/docs/advanced/custom-response.md
@@ -1,110 +1,111 @@
-# 自定义响应 - HTML,流,文件和其他
+# 自定义响应 - HTML、流、文件等 { #custom-response-html-stream-file-others }
-**FastAPI** 默认会使用 `JSONResponse` 返回响应。
+默认情况下,**FastAPI** 会返回 JSON 响应。
-你可以通过直接返回 `Response` 来重载它,参见 [直接返回响应](response-directly.md){.internal-link target=_blank}。
+你可以像在 [直接返回响应](response-directly.md) 中那样,直接返回 `Response` 来重载它。
-但如果你直接返回 `Response`,返回数据不会自动转换,也不会自动生成文档(例如,在 HTTP 头 `Content-Type` 中包含特定的「媒体类型」作为生成的 OpenAPI 的一部分)。
+但如果你直接返回一个 `Response`(或其任意子类,比如 `JSONResponse`),返回的数据不会自动转换(即使你声明了 `response_model`),也不会自动生成文档(例如,在生成的 OpenAPI 中,HTTP 头 `Content-Type` 里的特定「媒体类型」不会被包含)。
-你还可以在 *路径操作装饰器* 中声明你想用的 `Response`。
+你还可以在 *路径操作装饰器* 中通过 `response_class` 参数声明要使用的 `Response`(例如任意 `Response` 子类)。
你从 *路径操作函数* 中返回的内容将被放在该 `Response` 中。
-并且如果该 `Response` 有一个 JSON 媒体类型(`application/json`),比如使用 `JSONResponse` 或者 `UJSONResponse` 的时候,返回的数据将使用你在路径操作装饰器中声明的任何 Pydantic 的 `response_model` 自动转换(和过滤)。
+/// note | 注意
-!!! note "说明"
- 如果你使用不带有任何媒体类型的响应类,FastAPI 认为你的响应没有任何内容,所以不会在生成的OpenAPI文档中记录响应格式。
+如果你使用不带有媒体类型的响应类,FastAPI 会认为你的响应没有任何内容,所以不会在生成的 OpenAPI 文档中记录响应格式。
-## 使用 `ORJSONResponse`
+///
-例如,如果你需要压榨性能,你可以安装并使用 `orjson` 并将响应设置为 `ORJSONResponse`。
+## JSON 响应 { #json-responses }
-导入你想要使用的 `Response` 类(子类)然后在 *路径操作装饰器* 中声明它。
+默认情况下 FastAPI 返回 JSON 响应。
-```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001b.py!}
-```
-
-!!! info "提示"
- 参数 `response_class` 也会用来定义响应的「媒体类型」。
+如果你声明了一个[响应模型](../tutorial/response-model.md),FastAPI 会使用 Pydantic 将数据序列化为 JSON。
- 在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `application/json`。
+如果你没有声明响应模型,FastAPI 会使用 [JSON 兼容编码器](../tutorial/encoder.md) 中解释的 `jsonable_encoder`,并把结果放进一个 `JSONResponse`。
- 并且在 OpenAPI 文档中也会这样记录。
+如果你在 `response_class` 中声明了一个 JSON 媒体类型(`application/json`)的类(比如 `JSONResponse`),你返回的数据会使用你在 *路径操作装饰器* 中声明的任意 Pydantic `response_model` 自动转换(和过滤)。但数据不会由 Pydantic 序列化为 JSON 字节;而是先用 `jsonable_encoder` 转换后传给 `JSONResponse`,由它使用 Python 标准 JSON 库序列化为字节。
-!!! tip "小贴士"
- `ORJSONResponse` 目前只在 FastAPI 中可用,而在 Starlette 中不可用。
+### JSON 性能 { #json-performance }
+简而言之,如果你想要获得最大性能,请使用[响应模型](../tutorial/response-model.md),并且不要在 *路径操作装饰器* 中声明 `response_class`。
+{* ../../docs_src/response_model/tutorial001_01_py310.py ln[15:17] hl[16] *}
-## HTML 响应
+## HTML 响应 { #html-response }
使用 `HTMLResponse` 来从 **FastAPI** 中直接返回一个 HTML 响应。
* 导入 `HTMLResponse`。
* 将 `HTMLResponse` 作为你的 *路径操作* 的 `response_class` 参数传入。
-```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial002.py!}
-```
+{* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *}
+
+/// info | 信息
-!!! info "提示"
- 参数 `response_class` 也会用来定义响应的「媒体类型」。
+参数 `response_class` 也会用来定义响应的「媒体类型」。
- 在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `text/html`。
+在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `text/html`。
- 并且在 OpenAPI 文档中也会这样记录。
+并且在 OpenAPI 文档中也会这样记录。
-### 返回一个 `Response`
+///
-正如你在 [直接返回响应](response-directly.md){.internal-link target=_blank} 中了解到的,你也可以通过直接返回响应在 *路径操作* 中直接重载响应。
+### 返回一个 `Response` { #return-a-response }
+
+正如你在 [直接返回响应](response-directly.md) 中了解到的,你也可以通过直接返回响应在 *路径操作* 中直接重载响应。
和上面一样的例子,返回一个 `HTMLResponse` 看起来可能是这样:
-```Python hl_lines="2 7 19"
-{!../../../docs_src/custom_response/tutorial003.py!}
-```
+{* ../../docs_src/custom_response/tutorial003_py310.py hl[2,7,19] *}
+
+/// warning | 警告
-!!! warning "警告"
- *路径操作函数* 直接返回的 `Response` 不会被 OpenAPI 的文档记录(比如,`Content-Type` 不会被文档记录),并且在自动化交互文档中也是不可见的。
+*路径操作函数* 直接返回的 `Response` 不会被 OpenAPI 的文档记录(比如,`Content-Type` 不会被文档记录),并且在自动化交互文档中也是不可见的。
-!!! info "提示"
- 当然,实际的 `Content-Type` 头,状态码等等,将来自于你返回的 `Response` 对象。
+///
-### OpenAPI 中的文档和重载 `Response`
+/// info | 信息
+
+当然,实际的 `Content-Type` 头、状态码等等,将来自于你返回的 `Response` 对象。
+
+///
+
+### 在 OpenAPI 中文档化并重载 `Response` { #document-in-openapi-and-override-response }
如果你想要在函数内重载响应,但是同时在 OpenAPI 中文档化「媒体类型」,你可以使用 `response_class` 参数并返回一个 `Response` 对象。
接着 `response_class` 参数只会被用来文档化 OpenAPI 的 *路径操作*,你的 `Response` 用来返回响应。
-### 直接返回 `HTMLResponse`
+#### 直接返回 `HTMLResponse` { #return-an-htmlresponse-directly }
比如像这样:
-```Python hl_lines="7 23 21"
-{!../../../docs_src/custom_response/tutorial004.py!}
-```
+{* ../../docs_src/custom_response/tutorial004_py310.py hl[7,21,23] *}
在这个例子中,函数 `generate_html_response()` 已经生成并返回 `Response` 对象而不是在 `str` 中返回 HTML。
-通过返回函数 `generate_html_response()` 的调用结果,你已经返回一个重载 **FastAPI** 默认行为的 `Response` 对象,
+通过返回函数 `generate_html_response()` 的调用结果,你已经返回一个重载 **FastAPI** 默认行为的 `Response` 对象。
-但如果你在 `response_class` 中也传入了 `HTMLResponse`,**FastAPI** 会知道如何在 OpenAPI 和交互式文档中使用 `text/html` 将其文档化为 HTML。
+但如果你在 `response_class` 中也传入了 `HTMLResponse`,**FastAPI** 会知道如何在 OpenAPI 和交互式文档中使用 `text/html` 将其文档化为 HTML:
-## 可用响应
+## 可用响应 { #available-responses }
这里有一些可用的响应。
要记得你可以使用 `Response` 来返回任何其他东西,甚至创建一个自定义的子类。
-!!! note "技术细节"
- 你也可以使用 `from starlette.responses import HTMLResponse`。
+/// note | 技术细节
- **FastAPI** 提供了同 `fastapi.responses` 相同的 `starlette.responses` 只是为了方便开发者。但大多数可用的响应都直接来自 Starlette。
+你也可以使用 `from starlette.responses import HTMLResponse`。
-### `Response`
+**FastAPI** 提供了同 `fastapi.responses` 相同的 `starlette.responses` 只是为了方便开发者。但大多数可用的响应都直接来自 Starlette。
+
+///
+
+### `Response` { #response }
其他全部的响应都继承自主类 `Response`。
@@ -117,80 +118,83 @@
* `headers` - 一个由字符串组成的 `dict`。
* `media_type` - 一个给出媒体类型的 `str`,比如 `"text/html"`。
-FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它还将包含一个基于 media_type 的 Content-Type 头,并为文本类型附加一个字符集。
-
+FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它还将包含一个基于 `media_type` 的 Content-Type 头,并为文本类型附加一个字符集。
-```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
-```
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
-### `HTMLResponse`
+### `HTMLResponse` { #htmlresponse }
如上文所述,接受文本或字节并返回 HTML 响应。
-### `PlainTextResponse`
+### `PlainTextResponse` { #plaintextresponse }
接受文本或字节并返回纯文本响应。
-```Python hl_lines="2 7 9"
-{!../../../docs_src/custom_response/tutorial005.py!}
-```
+{* ../../docs_src/custom_response/tutorial005_py310.py hl[2,7,9] *}
-### `JSONResponse`
+### `JSONResponse` { #jsonresponse }
接受数据并返回一个 `application/json` 编码的响应。
如上文所述,这是 **FastAPI** 中使用的默认响应。
-### `ORJSONResponse`
+/// note | 技术细节
-如上文所述,`ORJSONResponse` 是一个使用 `orjson` 的快速的可选 JSON 响应。
+但如果你声明了响应模型或返回类型,将直接使用它来把数据序列化为 JSON,并直接返回一个具备正确 JSON 媒体类型的响应,而不会使用 `JSONResponse` 类。
+这是获得最佳性能的理想方式。
-### `UJSONResponse`
+///
-`UJSONResponse` 是一个使用 `ujson` 的可选 JSON 响应。
+### `RedirectResponse` { #redirectresponse }
-!!! warning "警告"
- 在处理某些边缘情况时,`ujson` 不如 Python 的内置实现那么谨慎。
+返回 HTTP 重定向。默认情况下使用 307 状态码(临时重定向)。
-```Python hl_lines="2 7"
-{!../../../docs_src/custom_response/tutorial001.py!}
-```
+你可以直接返回一个 `RedirectResponse`:
-!!! tip "小贴士"
- `ORJSONResponse` 可能是一个更快的选择。
+{* ../../docs_src/custom_response/tutorial006_py310.py hl[2,9] *}
-### `RedirectResponse`
+---
-返回 HTTP 重定向。默认情况下使用 307 状态代码(临时重定向)。
+或者你可以把它用于 `response_class` 参数:
-```Python hl_lines="2 9"
-{!../../../docs_src/custom_response/tutorial006.py!}
-```
+{* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *}
-### `StreamingResponse`
+如果你这么做,那么你可以在 *路径操作* 函数中直接返回 URL。
-采用异步生成器或普通生成器/迭代器,然后流式传输响应主体。
+在这种情况下,将使用 `RedirectResponse` 的默认 `status_code`,即 `307`。
-```Python hl_lines="2 14"
-{!../../../docs_src/custom_response/tutorial007.py!}
-```
+---
-#### 对类似文件的对象使用 `StreamingResponse`
+你也可以将 `status_code` 参数和 `response_class` 参数结合使用:
-如果您有类似文件的对象(例如,由 `open()` 返回的对象),则可以在 `StreamingResponse` 中将其返回。
+{* ../../docs_src/custom_response/tutorial006c_py310.py hl[2,7,9] *}
-包括许多与云存储,视频处理等交互的库。
+### `StreamingResponse` { #streamingresponse }
-```Python hl_lines="2 10-12 14"
-{!../../../docs_src/custom_response/tutorial008.py!}
-```
+采用异步生成器或普通生成器/迭代器(带有 `yield` 的函数),然后流式传输响应主体。
+
+{* ../../docs_src/custom_response/tutorial007_py310.py hl[3,16] *}
+
+/// note | 技术细节
+
+一个 `async` 任务只有在到达 `await` 时才能被取消。如果没有 `await`,生成器(带有 `yield` 的函数)无法被正确取消,即使已请求取消也可能继续运行。
+
+由于这个小示例不需要任何 `await` 语句,我们添加 `await anyio.sleep(0)`,给事件循环一个处理取消的机会。
+
+对于大型或无限流,这一点更为重要。
+
+///
+
+/// tip | 提示
+
+与其直接返回 `StreamingResponse`,更推荐遵循 [流式数据](./stream-data.md) 的写法,它更方便并在幕后为你处理取消。
-!!! tip "小贴士"
- 注意在这里,因为我们使用的是不支持 `async` 和 `await` 的标准 `open()`,我们使用普通的 `def` 声明了路径操作。
+如果你在流式传输 JSON Lines,请参阅教程:[流式传输 JSON Lines](../tutorial/stream-json-lines.md)。
-### `FileResponse`
+///
+
+### `FileResponse` { #fileresponse }
异步传输文件作为响应。
@@ -201,12 +205,68 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它
* `media_type` - 给出媒体类型的字符串。如果未设置,则文件名或路径将用于推断媒体类型。
* `filename` - 如果给出,它将包含在响应的 `Content-Disposition` 中。
-文件响应将包含适当的 `Content-Length`,`Last-Modified` 和 `ETag` 的响应头。
+文件响应将包含适当的 `Content-Length`、`Last-Modified` 和 `ETag` 响应头。
+
+{* ../../docs_src/custom_response/tutorial009_py310.py hl[2,10] *}
+
+你也可以使用 `response_class` 参数:
+
+{* ../../docs_src/custom_response/tutorial009b_py310.py hl[2,8,10] *}
+
+在这种情况下,你可以在 *路径操作* 函数中直接返回文件路径。
+
+## 自定义响应类 { #custom-response-class }
+
+你可以创建你自己的自定义响应类,继承自 `Response` 并使用它。
+
+例如,假设你想用一些设置来使用 [`orjson`](https://github.com/ijl/orjson)。
+
+假设你想让它返回带缩进、格式化的 JSON,因此你想使用 orjson 选项 `orjson.OPT_INDENT_2`。
+
+你可以创建一个 `CustomORJSONResponse`。你需要做的主要事情是实现一个 `Response.render(content)` 方法,并返回 `bytes`:
+
+{* ../../docs_src/custom_response/tutorial009c_py310.py hl[9:14,17] *}
+
+现在,不再是返回:
+
+```json
+{"message": "Hello World"}
+```
+
+...这个响应将返回:
-```Python hl_lines="2 10"
-{!../../../docs_src/custom_response/tutorial009.py!}
+```json
+{
+ "message": "Hello World"
+}
```
-## 额外文档
+当然,你很可能会找到比格式化 JSON 更好的方式来利用这一点。😉
+
+### `orjson` 或响应模型 { #orjson-or-response-model }
+
+如果你追求的是性能,使用[响应模型](../tutorial/response-model.md) 往往比返回 `orjson` 响应更好。
+
+使用响应模型时,FastAPI 会使用 Pydantic 直接把数据序列化为 JSON,不需要诸如通过 `jsonable_encoder` 转换这样的中间步骤(其他情况下会发生)。
+
+并且在底层,Pydantic 使用与 `orjson` 相同的 Rust 机制来序列化 JSON,所以使用响应模型你已经可以获得最佳性能。
+
+## 默认响应类 { #default-response-class }
+
+在创建 **FastAPI** 类实例或 `APIRouter` 时,你可以指定默认要使用的响应类。
+
+用于定义它的参数是 `default_response_class`。
+
+在下面的示例中,**FastAPI** 会在所有 *路径操作* 中默认使用 `HTMLResponse`,而不是 JSON。
+
+{* ../../docs_src/custom_response/tutorial010_py310.py hl[2,4] *}
+
+/// tip | 提示
+
+你仍然可以像之前一样在 *路径操作* 中重载 `response_class`。
+
+///
+
+## 额外文档 { #additional-documentation }
-您还可以使用 `response` 在 OpenAPI 中声明媒体类型和许多其他详细信息:[OpenAPI 中的额外文档](additional-responses.md){.internal-link target=_blank}。
+你还可以使用 `responses` 在 OpenAPI 中声明媒体类型和许多其他详细信息:[OpenAPI 中的额外响应](additional-responses.md)。
diff --git a/docs/zh/docs/advanced/dataclasses.md b/docs/zh/docs/advanced/dataclasses.md
new file mode 100644
index 0000000000000..42b4e4cc4d3f4
--- /dev/null
+++ b/docs/zh/docs/advanced/dataclasses.md
@@ -0,0 +1,87 @@
+# 使用数据类 { #using-dataclasses }
+
+FastAPI 基于 **Pydantic** 构建,我已经向你展示过如何使用 Pydantic 模型声明请求与响应。
+
+但 FastAPI 也支持以相同方式使用 [`dataclasses`](https://docs.python.org/3/library/dataclasses.html):
+
+{* ../../docs_src/dataclasses_/tutorial001_py310.py hl[1,6:11,18:19] *}
+
+这仍然得益于 **Pydantic**,因为它对 [`dataclasses` 的内置支持](https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel)。
+
+因此,即便上面的代码没有显式使用 Pydantic,FastAPI 也会使用 Pydantic 将那些标准数据类转换为 Pydantic 风格的 dataclasses。
+
+并且,它仍然支持以下功能:
+
+* 数据验证
+* 数据序列化
+* 数据文档等
+
+这与使用 Pydantic 模型时的工作方式相同。而且底层实际上也是借助 Pydantic 实现的。
+
+/// info | 信息
+
+请注意,数据类不能完成 Pydantic 模型能做的所有事情。
+
+因此,你可能仍然需要使用 Pydantic 模型。
+
+但如果你已有一堆数据类,这个技巧可以让它们很好地为使用 FastAPI 的 Web API 所用。🤓
+
+///
+
+## 在 `response_model` 中使用数据类 { #dataclasses-in-response-model }
+
+你也可以在 `response_model` 参数中使用 `dataclasses`:
+
+{* ../../docs_src/dataclasses_/tutorial002_py310.py hl[1,6:12,18] *}
+
+该数据类会被自动转换为 Pydantic 的数据类。
+
+这样,它的模式会显示在 API 文档界面中:
+
+
+
+## 在嵌套数据结构中使用数据类 { #dataclasses-in-nested-data-structures }
+
+你也可以把 `dataclasses` 与其它类型注解组合在一起,创建嵌套数据结构。
+
+在某些情况下,你可能仍然需要使用 Pydantic 的 `dataclasses` 版本。例如,如果自动生成的 API 文档出现错误。
+
+在这种情况下,你可以直接把标准的 `dataclasses` 替换为 `pydantic.dataclasses`,它是一个可直接替换的实现:
+
+{* ../../docs_src/dataclasses_/tutorial003_py310.py hl[1,4,7:10,13:16,22:24,27] *}
+
+1. 我们仍然从标准库的 `dataclasses` 导入 `field`。
+2. `pydantic.dataclasses` 是 `dataclasses` 的可直接替换版本。
+3. `Author` 数据类包含一个由 `Item` 数据类组成的列表。
+4. `Author` 数据类被用作 `response_model` 参数。
+5. 你可以将其它标准类型注解与数据类一起用作请求体。
+
+ 在本例中,它是一个 `Item` 数据类列表。
+6. 这里我们返回一个字典,里面的 `items` 是一个数据类列表。
+
+ FastAPI 仍然能够将数据序列化为 JSON。
+7. 这里的 `response_model` 使用了 “`Author` 数据类列表” 的类型注解。
+
+ 同样,你可以将 `dataclasses` 与标准类型注解组合使用。
+8. 注意,这个 *路径操作函数* 使用的是常规的 `def` 而不是 `async def`。
+
+ 一如既往,在 FastAPI 中你可以按需组合 `def` 和 `async def`。
+
+ 如果需要回顾何时用哪一个,请查看关于 [`async` 和 `await`](../async.md#in-a-hurry) 的文档中的 _“急不可待?”_ 一节。
+9. 这个 *路径操作函数* 返回的不是数据类(当然也可以返回数据类),而是包含内部数据的字典列表。
+
+ FastAPI 会使用(包含数据类的)`response_model` 参数来转换响应。
+
+你可以将 `dataclasses` 与其它类型注解以多种不同方式组合,来构建复杂的数据结构。
+
+更多细节请参考上面代码中的内联注释提示。
+
+## 深入学习 { #learn-more }
+
+你还可以把 `dataclasses` 与其它 Pydantic 模型组合、从它们继承、把它们包含到你自己的模型中等。
+
+想了解更多,请查看 [Pydantic 关于 dataclasses 的文档](https://docs.pydantic.dev/latest/concepts/dataclasses/)。
+
+## 版本 { #version }
+
+自 FastAPI 版本 `0.67.0` 起可用。🔖
diff --git a/docs/zh/docs/advanced/events.md b/docs/zh/docs/advanced/events.md
new file mode 100644
index 0000000000000..0b647a4388309
--- /dev/null
+++ b/docs/zh/docs/advanced/events.md
@@ -0,0 +1,165 @@
+# 生命周期事件 { #lifespan-events }
+
+你可以定义在应用**启动**前执行的逻辑(代码)。这意味着在应用**开始接收请求**之前,这些代码只会被执行**一次**。
+
+同样地,你可以定义在应用**关闭**时应执行的逻辑。在这种情况下,这段代码将在**处理可能的多次请求后**执行**一次**。
+
+因为这段代码在应用开始接收请求**之前**执行,也会在处理可能的若干请求**之后**执行,它覆盖了整个应用程序的**生命周期**(“生命周期”这个词很重要😉)。
+
+这对于设置你需要在整个应用中使用的**资源**非常有用,这些资源在请求之间**共享**,你可能需要在之后进行**释放**。例如,数据库连接池,或加载一个共享的机器学习模型。
+
+## 用例 { #use-case }
+
+让我们从一个示例**用例**开始,看看如何用它来解决问题。
+
+假设你有几个**机器学习的模型**,你想要用它们来处理请求。🤖
+
+相同的模型在请求之间是共享的,因此并非每个请求或每个用户各自拥有一个模型。
+
+假设加载模型可能**需要相当长的时间**,因为它必须从**磁盘**读取大量数据。因此你不希望每个请求都加载它。
+
+你可以在模块/文件的顶部加载它,但这也意味着即使你只是在运行一个简单的自动化测试,它也会**加载模型**,这样测试将**变慢**,因为它必须在能够独立运行代码的其他部分之前等待模型加载完成。
+
+这就是我们要解决的问题——在处理请求前加载模型,但只是在应用开始接收请求前,而不是在代码被加载时。
+
+## Lifespan { #lifespan }
+
+你可以使用 `FastAPI` 应用的 `lifespan` 参数和一个“上下文管理器”(稍后我将为你展示)来定义**启动**和**关闭**的逻辑。
+
+让我们从一个例子开始,然后详细介绍。
+
+我们使用 `yield` 创建了一个异步函数 `lifespan()` 像这样:
+
+{* ../../docs_src/events/tutorial003_py310.py hl[16,19] *}
+
+在这里,我们在 `yield` 之前将(虚拟的)模型函数放入机器学习模型的字典中,以此模拟加载模型的耗时**启动**操作。这段代码将在应用程序**开始处理请求之前**执行,即**启动**期间。
+
+然后,在 `yield` 之后,我们卸载模型。这段代码将会在应用程序**完成处理请求后**执行,即在**关闭**之前。这可以释放诸如内存或 GPU 之类的资源。
+
+/// tip | 提示
+
+**关闭**事件会在你**停止**应用时发生。
+
+可能你需要启动一个新版本,或者你只是厌倦了运行它。 🤷
+
+///
+
+### 生命周期函数 { #lifespan-function }
+
+首先要注意的是,我们定义了一个带有 `yield` 的异步函数。这与带有 `yield` 的依赖项非常相似。
+
+{* ../../docs_src/events/tutorial003_py310.py hl[14:19] *}
+
+这个函数在 `yield` 之前的部分,会在应用启动前执行。
+
+剩下的部分在 `yield` 之后,会在应用完成后执行。
+
+### 异步上下文管理器 { #async-context-manager }
+
+如你所见,这个函数有一个装饰器 `@asynccontextmanager`。
+
+它将函数转化为所谓的“**异步上下文管理器**”。
+
+{* ../../docs_src/events/tutorial003_py310.py hl[1,13] *}
+
+在 Python 中,**上下文管理器**是一个你可以在 `with` 语句中使用的东西,例如,`open()` 可以作为上下文管理器使用。
+
+```Python
+with open("file.txt") as file:
+ file.read()
+```
+
+Python 的最近几个版本也有了一个**异步上下文管理器**,你可以通过 `async with` 来使用:
+
+```Python
+async with lifespan(app):
+ await do_stuff()
+```
+
+你可以像上面一样创建一个上下文管理器或者异步上下文管理器,它的作用是在进入 `with` 块时,执行 `yield` 之前的代码,并且在离开 `with` 块时,执行 `yield` 后面的代码。
+
+但在我们上面的例子里,我们并不是直接使用,而是传递给 FastAPI 来供其使用。
+
+`FastAPI` 的 `lifespan` 参数接受一个**异步上下文管理器**,所以我们可以把我们新定义的异步上下文管理器 `lifespan` 传给它。
+
+{* ../../docs_src/events/tutorial003_py310.py hl[22] *}
+
+## 替代事件(弃用) { #alternative-events-deprecated }
+
+/// warning | 警告
+
+配置**启动**和**关闭**的推荐方法是使用 `FastAPI` 应用的 `lifespan` 参数,如前所示。如果你提供了一个 `lifespan` 参数,启动(`startup`)和关闭(`shutdown`)事件处理器将不再生效。要么使用 `lifespan`,要么配置所有事件,两者不能共用。
+
+你可以跳过这一部分。
+
+///
+
+有一种替代方法可以定义在**启动**和**关闭**期间执行的逻辑。
+
+你可以定义在应用启动前或应用关闭时需要执行的事件处理器(函数)。
+
+事件函数既可以声明为异步函数(`async def`),也可以声明为普通函数(`def`)。
+
+### `startup` 事件 { #startup-event }
+
+使用事件 `"startup"` 声明一个在应用启动前运行的函数:
+
+{* ../../docs_src/events/tutorial001_py310.py hl[8] *}
+
+本例中,`startup` 事件处理器函数为项目“数据库”(只是一个 `dict`)提供了一些初始值。
+
+**FastAPI** 支持多个事件处理器函数。
+
+只有所有 `startup` 事件处理器运行完毕,**FastAPI** 应用才开始接收请求。
+
+### `shutdown` 事件 { #shutdown-event }
+
+使用事件 `"shutdown"` 声明一个在应用关闭时运行的函数:
+
+{* ../../docs_src/events/tutorial002_py310.py hl[6] *}
+
+此处,`shutdown` 事件处理器函数会向文件 `log.txt` 写入一行文本 `"Application shutdown"`。
+
+/// info | 信息
+
+在 `open()` 函数中,`mode="a"` 指的是“追加”。因此这行文本会添加在文件已有内容之后,不会覆盖之前的内容。
+
+///
+
+/// tip | 提示
+
+注意,本例使用 Python 标准的 `open()` 函数与文件交互。
+
+这个函数执行 I/O(输入/输出)操作,需要“等待”内容写进磁盘。
+
+但 `open()` 不使用 `async` 和 `await`。
+
+因此,声明事件处理函数要使用 `def`,而不是 `async def`。
+
+///
+
+### `startup` 和 `shutdown` 一起使用 { #startup-and-shutdown-together }
+
+启动和关闭的逻辑很可能是连接在一起的,你可能希望启动某个东西然后结束它,获取一个资源然后释放它等等。
+
+在不共享逻辑或变量的不同函数中处理这些逻辑比较困难,因为你需要在全局变量中存储值或使用类似的方式。
+
+因此,推荐使用上面所述的 `lifespan`。
+
+## 技术细节 { #technical-details }
+
+只是为好奇者提供的技术细节。🤓
+
+在底层,这部分是 ASGI 技术规范中的 [Lifespan 协议](https://asgi.readthedocs.io/en/latest/specs/lifespan.html)的一部分,定义了称为 `startup` 和 `shutdown` 的事件。
+
+/// info | 信息
+
+你可以在 [Starlette 的 Lifespan 文档](https://www.starlette.dev/lifespan/) 中阅读更多关于 `lifespan` 处理器的内容。
+
+包括如何处理生命周期状态,以便在代码的其他部分使用。
+
+///
+
+## 子应用 { #sub-applications }
+
+🚨 请注意,这些生命周期事件(startup 和 shutdown)只会在主应用上执行,不会在[子应用 - 挂载](sub-applications.md)上执行。
diff --git a/docs/zh/docs/advanced/generate-clients.md b/docs/zh/docs/advanced/generate-clients.md
index f3a58c062811d..5f53aa4347505 100644
--- a/docs/zh/docs/advanced/generate-clients.md
+++ b/docs/zh/docs/advanced/generate-clients.md
@@ -1,266 +1,208 @@
-# 生成客户端
+# 生成 SDK { #generating-sdks }
-因为 **FastAPI** 是基于OpenAPI规范的,自然您可以使用许多相匹配的工具,包括自动生成API文档 (由 Swagger UI 提供)。
+因为 **FastAPI** 基于 **OpenAPI** 规范,它的 API 可以用许多工具都能理解的标准格式来描述。
-一个不太明显而又特别的优势是,你可以为你的API针对不同的**编程语言**来**生成客户端**(有时候被叫做 **SDKs** )。
+这让你可以轻松生成最新的**文档**、多语言的客户端库(**SDKs**),以及与代码保持同步的**测试**或**自动化工作流**。
-## OpenAPI 客户端生成
+本指南将带你为 FastAPI 后端生成一个 **TypeScript SDK**。
-有许多工具可以从**OpenAPI**生成客户端。
+## 开源 SDK 生成器 { #open-source-sdk-generators }
-一个常见的工具是 OpenAPI Generator。
+一个功能多样的选择是 [OpenAPI Generator](https://openapi-generator.tech/),它支持**多种编程语言**,可以根据你的 OpenAPI 规范生成 SDK。
-如果您正在开发**前端**,一个非常有趣的替代方案是 openapi-typescript-codegen。
+对于 **TypeScript 客户端**,[Hey API](https://heyapi.dev/) 是为 TypeScript 生态打造的专用方案,提供优化的使用体验。
-## 生成一个 TypeScript 前端客户端
+你还可以在 [OpenAPI.Tools](https://openapi.tools/#sdk) 上发现更多 SDK 生成器。
-让我们从一个简单的 FastAPI 应用开始:
+/// tip | 提示
-=== "Python 3.9+"
+FastAPI 会自动生成 **OpenAPI 3.1** 规范,因此你使用的任何工具都必须支持该版本。
- ```Python hl_lines="7-9 12-13 16-17 21"
- {!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
- ```
+///
-=== "Python 3.6+"
+## 来自 FastAPI 赞助商的 SDK 生成器 { #sdk-generators-from-fastapi-sponsors }
- ```Python hl_lines="9-11 14-15 18 19 23"
- {!> ../../../docs_src/generate_clients/tutorial001.py!}
- ```
+本节介绍的是由赞助 FastAPI 的公司提供的、具备**风险投资背景**或**公司支持**的方案。这些产品在高质量生成的 SDK 之上,提供了**更多特性**和**集成**。
-请注意,*路径操作* 定义了他们所用于请求数据和回应数据的模型,所使用的模型是`Item` 和 `ResponseMessage`。
+通过 ✨ [**赞助 FastAPI**](../help-fastapi.md#sponsor-the-author) ✨,这些公司帮助确保框架及其**生态**保持健康并且**可持续**。
-### API 文档
+他们的赞助也体现了对 FastAPI **社区**(也就是你)的高度承诺,不仅关注提供**优秀的服务**,也支持一个**健壮且繁荣的框架**——FastAPI。🙇
-如果您访问API文档,您将看到它具有在请求中发送和在响应中接收数据的**模式(schemas)**:
+例如,你可以尝试:
-
-
-您可以看到这些模式,因为它们是用程序中的模型声明的。
-
-那些信息可以在应用的 **OpenAPI模式** 被找到,然后显示在API文档中(通过Swagger UI)。
+* [Speakeasy](https://speakeasy.com/editor?utm_source=fastapi+repo&utm_medium=github+sponsorship)
+* [Stainless](https://www.stainless.com/?utm_source=fastapi&utm_medium=referral)
+* [liblab](https://developers.liblab.com/tutorials/sdk-for-fastapi?utm_source=fastapi)
-OpenAPI中所包含的模型里有相同的信息可以用于 **生成客户端代码**。
+其中一些方案也可能是开源的或提供免费层级,你可以不花钱就先试用。其他商业 SDK 生成器也可在网上找到。🤓
-### 生成一个TypeScript 客户端
+## 创建一个 TypeScript SDK { #create-a-typescript-sdk }
-现在我们有了带有模型的应用,我们可以为前端生成客户端代码。
+先从一个简单的 FastAPI 应用开始:
-#### 安装 `openapi-typescript-codegen`
+{* ../../docs_src/generate_clients/tutorial001_py310.py hl[7:9,12:13,16:17,21] *}
-您可以使用以下工具在前端代码中安装 `openapi-typescript-codegen`:
+请注意,这些*路径操作*使用 `Item` 和 `ResponseMessage` 模型来定义它们的请求载荷和响应载荷。
-
-因为它安装在本地项目中,所以您可能无法直接使用此命令,但您可以将其放在 `package.json` 文件中。
+之所以能看到这些模式,是因为它们在应用中用模型声明了。
-它可能看起来是这样的:
+这些信息会包含在应用的 **OpenAPI 模式** 中,并显示在 API 文档里。
-```JSON hl_lines="7"
-{
- "name": "frontend-app",
- "version": "1.0.0",
- "description": "",
- "main": "index.js",
- "scripts": {
- "generate-client": "openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios"
- },
- "author": "",
- "license": "",
- "devDependencies": {
- "openapi-typescript-codegen": "^0.20.1",
- "typescript": "^4.6.2"
- }
-}
-```
+OpenAPI 中包含的这些模型信息就是用于**生成客户端代码**的基础。
-在这里添加 NPM `generate-client` 脚本后,您可以使用以下命令运行它:
+### Hey API { #hey-api }
-
-您还将自动补全要发送的数据:
+要发送的载荷也会有自动补全:
-!!! tip
- 请注意, `name` 和 `price` 的自动补全,是通过其在`Item`模型(FastAPI)中的定义实现的。
-
-如果发送的数据字段不符,你也会看到编辑器的错误提示:
+/// tip | 提示
-
+请注意 `name` 和 `price` 的自动补全,它们是在 FastAPI 应用中的 `Item` 模型里定义的。
-响应(response)对象也拥有自动补全:
+///
-
+你发送的数据如果不符合要求,会在编辑器中显示内联错误:
-## 带有标签的 FastAPI 应用
+
-在许多情况下,你的FastAPI应用程序会更复杂,你可能会使用标签来分隔不同组的*路径操作(path operations)*。
+响应对象同样有自动补全:
-例如,您可以有一个用 `items` 的部分和另一个用于 `users` 的部分,它们可以用标签来分隔:
+
-=== "Python 3.9+"
+## 带有标签的 FastAPI 应用 { #fastapi-app-with-tags }
- ```Python hl_lines="21 26 34"
- {!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
- ```
+很多情况下,你的 FastAPI 应用会更大,你可能会用标签来划分不同组的*路径操作*。
-=== "Python 3.6+"
+例如,你可以有一个 **items** 相关的部分和另一个 **users** 相关的部分,它们可以用标签来分隔:
- ```Python hl_lines="23 28 36"
- {!> ../../../docs_src/generate_clients/tutorial002.py!}
- ```
+{* ../../docs_src/generate_clients/tutorial002_py310.py hl[21,26,34] *}
-### 生成带有标签的 TypeScript 客户端
+### 生成带标签的 TypeScript 客户端 { #generate-a-typescript-client-with-tags }
-如果您使用标签为FastAPI应用生成客户端,它通常也会根据标签分割客户端代码。
+如果你为使用了标签的 FastAPI 应用生成客户端,通常也会根据标签来拆分客户端代码。
-通过这种方式,您将能够为客户端代码进行正确地排序和分组:
+这样你就可以在客户端代码中把内容正确地组织和分组:
-在这个案例中,您有:
+在这个例子中,你会有:
* `ItemsService`
* `UsersService`
-### 客户端方法名称
+### 客户端方法名 { #client-method-names }
-现在生成的方法名像 `createItemItemsPost` 看起来不太简洁:
+现在,像 `createItemItemsPost` 这样的生成方法名看起来不太简洁:
```TypeScript
ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
```
-...这是因为客户端生成器为每个 *路径操作* 使用OpenAPI的内部 **操作 ID(operation ID)**。
+...这是因为客户端生成器会把每个*路径操作*的 OpenAPI 内部**操作 ID(operation ID)**用作方法名的一部分。
-OpenAPI要求每个操作 ID 在所有 *路径操作* 中都是唯一的,因此 FastAPI 使用**函数名**、**路径**和**HTTP方法/操作**来生成此操作ID,因为这样可以确保这些操作 ID 是唯一的。
+OpenAPI 要求每个操作 ID 在所有*路径操作*中都是唯一的,因此 FastAPI 会使用**函数名**、**路径**和**HTTP 方法/操作**来生成操作 ID,以确保其唯一性。
-但接下来我会告诉你如何改进。 🤓
+接下来我会告诉你如何改进。🤓
-## 自定义操作ID和更好的方法名
+## 自定义操作 ID 与更好的方法名 { #custom-operation-ids-and-better-method-names }
-您可以**修改**这些操作ID的**生成**方式,以使其更简洁,并在客户端中具有**更简洁的方法名称**。
+你可以**修改**这些操作 ID 的**生成**方式,使之更简单,从而在客户端中得到**更简洁的方法名**。
-在这种情况下,您必须确保每个操作ID在其他方面是**唯一**的。
+在这种情况下,你需要用其他方式确保每个操作 ID 依然是**唯一**的。
-例如,您可以确保每个*路径操作*都有一个标签,然后根据**标签**和*路径操作***名称**(函数名)来生成操作ID。
+例如,你可以确保每个*路径操作*都有一个标签,然后基于**标签**和*路径操作***名称**(函数名)来生成操作 ID。
-### 自定义生成唯一ID函数
+### 自定义唯一 ID 生成函数 { #custom-generate-unique-id-function }
-FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID**,也用于任何所需自定义模型的名称,用于请求或响应。
+FastAPI 为每个*路径操作*使用一个**唯一 ID**,它既用于**操作 ID**,也用于请求或响应里任何需要的自定义模型名称。
-你可以自定义该函数。它接受一个 `APIRoute` 对象作为输入,并输出一个字符串。
+你可以自定义这个函数。它接收一个 `APIRoute` 并返回一个字符串。
-例如,以下是一个示例,它使用第一个标签(你可能只有一个标签)和*路径操作*名称(函数名)。
+例如,这里使用第一个标签(你很可能只有一个标签)和*路径操作*名称(函数名)。
-然后,你可以将这个自定义函数作为 `generate_unique_id_function` 参数传递给 **FastAPI**:
+然后你可以把这个自定义函数通过 `generate_unique_id_function` 参数传给 **FastAPI**:
-=== "Python 3.9+"
+{* ../../docs_src/generate_clients/tutorial003_py310.py hl[6:7,10] *}
- ```Python hl_lines="6-7 10"
- {!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
- ```
+### 使用自定义操作 ID 生成 TypeScript 客户端 { #generate-a-typescript-client-with-custom-operation-ids }
-=== "Python 3.6+"
+现在再次生成客户端,你会看到方法名已经改进:
- ```Python hl_lines="8-9 12"
- {!> ../../../docs_src/generate_clients/tutorial003.py!}
- ```
+
-### 使用自定义操作ID生成TypeScript客户端
+如你所见,方法名现在由标签和函数名组成,不再包含 URL 路径和 HTTP 操作的信息。
-现在,如果你再次生成客户端,你会发现它具有改善的方法名称:
+### 为客户端生成器预处理 OpenAPI 规范 { #preprocess-the-openapi-specification-for-the-client-generator }
-
+生成的代码中仍有一些**重复信息**。
-正如你所见,现在方法名称中只包含标签和函数名,不再包含URL路径和HTTP操作的信息。
+我们已经知道这个方法与 **items** 有关,因为它位于 `ItemsService`(来自标签),但方法名里仍然带有标签名前缀。😕
-### 预处理用于客户端生成器的OpenAPI规范
+通常我们仍然希望在 OpenAPI 中保留它,以确保操作 ID 的**唯一性**。
-生成的代码仍然存在一些**重复的信息**。
+但对于生成的客户端,我们可以在生成之前**修改** OpenAPI 的操作 ID,只是为了让方法名更美观、更**简洁**。
-我们已经知道该方法与 **items** 相关,因为它在 `ItemsService` 中(从标签中获取),但方法名中仍然有标签名作为前缀。😕
+我们可以把 OpenAPI JSON 下载到 `openapi.json` 文件中,然后用如下脚本**移除这个标签前缀**:
-一般情况下对于OpenAPI,我们可能仍然希望保留它,因为这将确保操作ID是**唯一的**。
+{* ../../docs_src/generate_clients/tutorial004_py310.py *}
-但对于生成的客户端,我们可以在生成客户端之前**修改** OpenAPI 操作ID,以使方法名称更加美观和**简洁**。
+//// tab | Node.js
-我们可以将 OpenAPI JSON 下载到一个名为`openapi.json`的文件中,然后使用以下脚本**删除此前缀的标签**:
-
-```Python
-{!../../../docs_src/generate_clients/tutorial004.py!}
+```Javascript
+{!> ../../docs_src/generate_clients/tutorial004.js!}
```
-通过这样做,操作ID将从类似于 `items-get_items` 的名称重命名为 `get_items` ,这样客户端生成器就可以生成更简洁的方法名称。
-
-### 使用预处理的OpenAPI生成TypeScript客户端
-
-现在,由于最终结果保存在文件openapi.json中,你可以修改 package.json 文件以使用此本地文件,例如:
-
-```JSON hl_lines="7"
-{
- "name": "frontend-app",
- "version": "1.0.0",
- "description": "",
- "main": "index.js",
- "scripts": {
- "generate-client": "openapi --input ./openapi.json --output ./src/client --client axios"
- },
- "author": "",
- "license": "",
- "devDependencies": {
- "openapi-typescript-codegen": "^0.20.1",
- "typescript": "^4.6.2"
- }
-}
+////
+
+这样,操作 ID 会从 `items-get_items` 之类的名字重命名为 `get_items`,从而让客户端生成器生成更简洁的方法名。
+
+### 使用预处理后的 OpenAPI 生成 TypeScript 客户端 { #generate-a-typescript-client-with-the-preprocessed-openapi }
+
+因为最终结果现在保存在 `openapi.json` 中,你需要更新输入位置:
+
+```sh
+npx @hey-api/openapi-ts -i ./openapi.json -o src/client
```
-生成新的客户端之后,你现在将拥有**清晰的方法名称**,具备**自动补全**、**错误提示**等功能:
+生成新客户端后,你将拥有**简洁的方法名**,并具备**自动补全**、**内联错误**等功能:
-## 优点
+## 优点 { #benefits }
-当使用自动生成的客户端时,你将获得以下的自动补全功能:
+使用自动生成的客户端时,你会获得以下内容的**自动补全**:
-* 方法。
-* 请求体中的数据、查询参数等。
-* 响应数据。
+* 方法
+* 请求体中的数据、查询参数等
+* 响应数据
-你还将获得针对所有内容的错误提示。
+你还会为所有内容获得**内联错误**。
-每当你更新后端代码并**重新生成**前端代码时,新的*路径操作*将作为方法可用,旧的方法将被删除,并且其他任何更改将反映在生成的代码中。 🤓
+每当你更新后端代码并**重新生成**前端时,新的*路径操作*会作为方法可用,旧的方法会被移除,其他任何更改都会反映到生成的代码中。🤓
-这也意味着如果有任何更改,它将自动**反映**在客户端代码中。如果你**构建**客户端,在使用的数据上存在**不匹配**时,它将报错。
+这也意味着如果有任何变更,它会自动**反映**到客户端代码中。而当你**构建**客户端时,如果所用数据存在任何**不匹配**,它会直接报错。
-因此,你将在开发周期的早期**检测到许多错误**,而不必等待错误在生产环境中向最终用户展示,然后尝试调试问题所在。 ✨
+因此,你可以在开发周期的早期就**发现许多错误**,而不必等到错误在生产环境中暴露给最终用户后再去调试问题所在。✨
diff --git a/docs/zh/docs/advanced/index.md b/docs/zh/docs/advanced/index.md
index 824f91f47ba90..24b4d076fc39e 100644
--- a/docs/zh/docs/advanced/index.md
+++ b/docs/zh/docs/advanced/index.md
@@ -1,18 +1,21 @@
-# 高级用户指南
+# 高级用户指南 { #advanced-user-guide }
-## 额外特性
+## 附加功能 { #additional-features }
-主要的教程 [教程 - 用户指南](../tutorial/){.internal-link target=_blank} 应该足以让你了解 **FastAPI** 的所有主要特性。
+主要的[教程 - 用户指南](../tutorial/index.md)足以带你了解 **FastAPI** 的所有主要特性。
-你会在接下来的章节中了解到其他的选项、配置以及额外的特性。
+在接下来的章节中,你将看到其他选项、配置和附加功能。
-!!! tip
- 接下来的章节**并不一定是**「高级的」。
+/// tip | 提示
- 而且对于你的使用场景来说,解决方案很可能就在其中。
+接下来的章节**不一定是“高级”的**。
-## 先阅读教程
+对于你的用例,解决方案很可能就在其中之一。
-你可能仍会用到 **FastAPI** 主教程 [教程 - 用户指南](../tutorial/){.internal-link target=_blank} 中的大多数特性。
+///
-接下来的章节我们认为你已经读过 [教程 - 用户指南](../tutorial/){.internal-link target=_blank},并且假设你已经知晓其中主要思想。
+## 先阅读教程 { #read-the-tutorial-first }
+
+仅凭主要[教程 - 用户指南](../tutorial/index.md)中的知识,你已经可以使用 **FastAPI** 的大多数功能。
+
+接下来的章节默认你已经读过它,并理解其中的核心概念。
diff --git a/docs/zh/docs/advanced/json-base64-bytes.md b/docs/zh/docs/advanced/json-base64-bytes.md
new file mode 100644
index 0000000000000..7792282c72b15
--- /dev/null
+++ b/docs/zh/docs/advanced/json-base64-bytes.md
@@ -0,0 +1,63 @@
+# 在 JSON 中使用 Base64 表示字节 { #json-with-bytes-as-base64 }
+
+如果你的应用需要接收和发送 JSON 数据,但其中需要包含二进制数据,可以将其编码为 base64。
+
+## Base64 与文件 { #base64-vs-files }
+
+请先考虑是否可以使用 [请求文件](../tutorial/request-files.md) 来上传二进制数据,并使用 [自定义响应 - FileResponse](./custom-response.md#fileresponse--fileresponse-) 来发送二进制数据,而不是把它编码进 JSON。
+
+JSON 只能包含 UTF-8 编码的字符串,因此无法直接包含原始字节。
+
+Base64 可以把二进制数据编码为字符串,但为此会使用比原始二进制更多的字符,因此通常比直接使用文件的效率更低。
+
+仅当你确实需要在 JSON 中包含二进制数据且无法使用文件时,才使用 base64。
+
+## Pydantic `bytes` { #pydantic-bytes }
+
+你可以声明带有 `bytes` 字段的 Pydantic 模型,然后在模型配置中使用 `val_json_bytes` 指定用 base64 来验证输入的 JSON 数据;作为验证的一部分,它会将该 base64 字符串解码为字节。
+
+{* ../../docs_src/json_base64_bytes/tutorial001_py310.py ln[1:9,29:35] hl[9] *}
+
+查看 `/docs` 时,你会看到字段 `data` 期望接收 base64 编码的字节:
+
+
+
diff --git a/docs/zh/docs/advanced/openapi-webhooks.md b/docs/zh/docs/advanced/openapi-webhooks.md
new file mode 100644
index 0000000000000..3d6bcc9bc26f7
--- /dev/null
+++ b/docs/zh/docs/advanced/openapi-webhooks.md
@@ -0,0 +1,55 @@
+# OpenAPI 网络钩子 { #openapi-webhooks }
+
+有些情况下,您可能想告诉您的 API **用户**,您的应用程序可以携带一些数据调用*他们的*应用程序(给它们发送请求),通常是为了**通知**某种**事件**。
+
+这意味着,与通常由您的用户向您的 API 发送请求的流程相反,是**您的 API**(或您的应用)可以**向他们的系统**(他们的 API、他们的应用)**发送请求**。
+
+这通常被称为**网络钩子**(Webhook)。
+
+## 使用网络钩子的步骤 { #webhooks-steps }
+
+通常的过程是**您**在代码中**定义**要发送的消息,即**请求的主体**。
+
+您还需要以某种方式定义您的应用程序将在**何时**发送这些请求或事件。
+
+**用户**会以某种方式(例如在某个网页仪表板上)定义您的应用程序发送这些请求应该使用的 **URL**。
+
+所有关于注册网络钩子的 URL 的**逻辑**以及发送这些请求的实际代码都由您决定。您可以在**自己的代码**中以任何想要的方式来编写它。
+
+## 使用 `FastAPI` 和 OpenAPI 文档化网络钩子 { #documenting-webhooks-with-fastapi-and-openapi }
+
+使用 **FastAPI**,您可以利用 OpenAPI 来自定义这些网络钩子的名称、您的应用可以发送的 HTTP 操作类型(例如 `POST`、`PUT` 等)以及您的应用将发送的**请求体**。
+
+这能让您的用户更轻松地**实现他们的 API** 来接收您的**网络钩子**请求,他们甚至可能能够自动生成一些自己的 API 代码。
+
+/// info | 信息
+
+网络钩子在 OpenAPI 3.1.0 及以上版本中可用,FastAPI `0.99.0` 及以上版本支持。
+
+///
+
+## 带有网络钩子的应用程序 { #an-app-with-webhooks }
+
+当您创建一个 **FastAPI** 应用程序时,有一个 `webhooks` 属性可以用来定义网络钩子,方式与您定义*路径操作*的时候相同,例如使用 `@app.webhooks.post()` 。
+
+{* ../../docs_src/openapi_webhooks/tutorial001_py310.py hl[9:12,15:20] *}
+
+您定义的网络钩子将被包含在 `OpenAPI` 的架构中,并出现在自动生成的**文档 UI** 中。
+
+/// info | 信息
+
+`app.webhooks` 对象实际上只是一个 `APIRouter` ,与您在使用多个文件来构建应用程序时所使用的类型相同。
+
+///
+
+请注意,使用网络钩子时,您实际上并没有声明一个*路径*(比如 `/items/` ),您传递的文本只是这个网络钩子的**标识符**(事件的名称)。例如在 `@app.webhooks.post("new-subscription")` 中,网络钩子的名称是 `new-subscription` 。
+
+这是因为我们预计**您的用户**会以其他方式(例如通过网页仪表板)来定义他们希望接收网络钩子的请求的实际 **URL 路径**。
+
+### 查看文档 { #check-the-docs }
+
+现在您可以启动您的应用程序并访问 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)。
+
+您会看到您的文档不仅有正常的*路径操作*显示,现在还多了一些**网络钩子**:
+
+
diff --git a/docs/zh/docs/advanced/path-operation-advanced-configuration.md b/docs/zh/docs/advanced/path-operation-advanced-configuration.md
index 7da9f251e30db..67f3bd7e9ae6d 100644
--- a/docs/zh/docs/advanced/path-operation-advanced-configuration.md
+++ b/docs/zh/docs/advanced/path-operation-advanced-configuration.md
@@ -1,53 +1,172 @@
-# 路径操作的高级配置
+# 路径操作的高级配置 { #path-operation-advanced-configuration }
-## OpenAPI 的 operationId
+## OpenAPI 的 operationId { #openapi-operationid }
-!!! warning
- 如果你并非 OpenAPI 的「专家」,你可能不需要这部分内容。
+/// warning
-你可以在路径操作中通过参数 `operation_id` 设置要使用的 OpenAPI `operationId`。
+如果你并非 OpenAPI 的“专家”,你可能不需要这部分内容。
-务必确保每个操作路径的 `operation_id` 都是唯一的。
+///
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
-```
+你可以在 *路径操作* 中通过参数 `operation_id` 设置要使用的 OpenAPI `operationId`。
+
+务必确保每个操作的 `operation_id` 都是唯一的。
-### 使用 *路径操作函数* 的函数名作为 operationId
+{* ../../docs_src/path_operation_advanced_configuration/tutorial001_py310.py hl[6] *}
-如果你想用你的 API 的函数名作为 `operationId` 的名字,你可以遍历一遍 API 的函数名,然后使用他们的 `APIRoute.name` 重写每个 *路径操作* 的 `operation_id`。
+### 使用 *路径操作函数* 的函数名作为 operationId { #using-the-path-operation-function-name-as-the-operationid }
+
+如果你想用 API 的函数名作为 `operationId`,你可以遍历所有路径操作,并使用它们的 `APIRoute.name` 重写每个 *路径操作* 的 `operation_id`。
你应该在添加了所有 *路径操作* 之后执行此操作。
-```Python hl_lines="2 12 13 14 15 16 17 18 19 20 21 24"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
-```
+{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *}
-!!! tip
- 如果你手动调用 `app.openapi()`,你应该在此之前更新 `operationId`。
+/// tip
-!!! warning
- 如果你这样做,务必确保你的每个 *路径操作函数* 的名字唯一。
+如果你手动调用 `app.openapi()`,你应该在此之前更新 `operationId`。
- 即使它们在不同的模块中(Python 文件)。
+///
-## 从 OpenAPI 中排除
+/// warning
-使用参数 `include_in_schema` 并将其设置为 `False` ,来从生成的 OpenAPI 方案中排除一个 *路径操作*(这样一来,就从自动化文档系统中排除掉了)。
+如果你这样做,务必确保你的每个 *路径操作函数* 的名字唯一。
-```Python hl_lines="6"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
-```
+即使它们在不同的模块中(Python 文件)。
+
+///
+
+## 从 OpenAPI 中排除 { #exclude-from-openapi }
-## docstring 的高级描述
+使用参数 `include_in_schema` 并将其设置为 `False`,来从生成的 OpenAPI 方案中排除一个 *路径操作*(这样一来,就从自动化文档系统中排除掉了):
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial003_py310.py hl[6] *}
+
+## 来自 docstring 的高级描述 { #advanced-description-from-docstring }
你可以限制 *路径操作函数* 的 `docstring` 中用于 OpenAPI 的行数。
-添加一个 `\f` (一个「换页」的转义字符)可以使 **FastAPI** 在那一位置截断用于 OpenAPI 的输出。
+添加一个 `\f`(一个“换页”的转义字符)可以使 **FastAPI** 在那一位置截断用于 OpenAPI 的输出。
剩余部分不会出现在文档中,但是其他工具(比如 Sphinx)可以使用剩余部分。
+{* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}
+
+## 附加响应 { #additional-responses }
+
+你可能已经见过如何为一个 *路径操作* 声明 `response_model` 和 `status_code`。
+
+这定义了该 *路径操作* 主响应的元数据。
+
+你也可以为它声明带有各自模型、状态码等的附加响应。
+
+文档中有一个完整章节,你可以阅读这里的[OpenAPI 中的附加响应](additional-responses.md)。
+
+## OpenAPI Extra { #openapi-extra }
+
+当你在应用中声明一个 *路径操作* 时,**FastAPI** 会自动生成与该 *路径操作* 相关的元数据,以包含到 OpenAPI 方案中。
+
+/// note | 技术细节
+
+在 OpenAPI 规范中,这被称为 [Operation 对象](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object)。
+
+///
+
+它包含关于该 *路径操作* 的所有信息,并用于生成自动文档。
+
+它包括 `tags`、`parameters`、`requestBody`、`responses` 等。
+
+这个特定于 *路径操作* 的 OpenAPI 方案通常由 **FastAPI** 自动生成,但你也可以扩展它。
+
+/// tip
+
+这是一个较低层级的扩展点。
+
+如果你只需要声明附加响应,更方便的方式是使用[OpenAPI 中的附加响应](additional-responses.md)。
+
+///
+
+你可以使用参数 `openapi_extra` 扩展某个 *路径操作* 的 OpenAPI 方案。
-```Python hl_lines="19 20 21 22 23 24 25 26 27 28 29"
-{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
+### OpenAPI 扩展 { #openapi-extensions }
+
+例如,这个 `openapi_extra` 可用于声明 [OpenAPI 扩展](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions):
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial005_py310.py hl[6] *}
+
+当你打开自动 API 文档时,你的扩展会显示在该 *路径操作* 的底部。
+
+
+
+如果你查看最终生成的 OpenAPI(在你的 API 的 `/openapi.json`),你也会看到你的扩展作为该 *路径操作* 的一部分:
+
+```JSON hl_lines="22"
+{
+ "openapi": "3.1.0",
+ "info": {
+ "title": "FastAPI",
+ "version": "0.1.0"
+ },
+ "paths": {
+ "/items/": {
+ "get": {
+ "summary": "Read Items",
+ "operationId": "read_items_items__get",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ }
+ }
+ },
+ "x-aperture-labs-portal": "blue"
+ }
+ }
+ }
+}
```
+
+### 自定义 OpenAPI 路径操作方案 { #custom-openapi-path-operation-schema }
+
+`openapi_extra` 中的字典会与该 *路径操作* 自动生成的 OpenAPI 方案进行深度合并。
+
+因此,你可以在自动生成的方案上添加额外数据。
+
+例如,你可以决定用自己的代码读取并验证请求,而不使用 FastAPI 与 Pydantic 的自动功能,但你仍然希望在 OpenAPI 方案中定义该请求。
+
+你可以用 `openapi_extra` 来做到:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial006_py310.py hl[19:36, 39:40] *}
+
+在这个示例中,我们没有声明任何 Pydantic 模型。事实上,请求体甚至没有被 解析 为 JSON,而是直接以 `bytes` 读取,并由函数 `magic_data_reader()` 以某种方式负责解析。
+
+尽管如此,我们仍然可以声明请求体的预期方案。
+
+### 自定义 OpenAPI 内容类型 { #custom-openapi-content-type }
+
+使用同样的技巧,你可以用一个 Pydantic 模型来定义 JSON Schema,然后把它包含到该 *路径操作* 的自定义 OpenAPI 方案部分中。
+
+即使请求中的数据类型不是 JSON,你也可以这样做。
+
+例如,在这个应用中我们不使用 FastAPI 集成的从 Pydantic 模型提取 JSON Schema 的功能,也不使用对 JSON 的自动校验。实际上,我们将请求的内容类型声明为 YAML,而不是 JSON:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[15:20, 22] *}
+
+尽管我们没有使用默认的集成功能,我们仍然使用 Pydantic 模型手动生成我们想以 YAML 接收的数据的 JSON Schema。
+
+然后我们直接使用请求并将请求体提取为 `bytes`。这意味着 FastAPI 甚至不会尝试将请求负载解析为 JSON。
+
+接着在我们的代码中,我们直接解析该 YAML 内容,然后再次使用同一个 Pydantic 模型来验证该 YAML 内容:
+
+{* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *}
+
+/// tip
+
+这里我们复用了同一个 Pydantic 模型。
+
+但同样地,我们也可以用其他方式对其进行验证。
+
+///
diff --git a/docs/zh/docs/advanced/response-change-status-code.md b/docs/zh/docs/advanced/response-change-status-code.md
index a289cf20178f0..379afd4eb9fc5 100644
--- a/docs/zh/docs/advanced/response-change-status-code.md
+++ b/docs/zh/docs/advanced/response-change-status-code.md
@@ -1,10 +1,10 @@
-# 响应 - 更改状态码
+# 响应 - 更改状态码 { #response-change-status-code }
-你可能之前已经了解到,你可以设置默认的[响应状态码](../tutorial/response-status-code.md){.internal-link target=_blank}。
+你可能之前已经了解到,你可以设置默认的[响应状态码](../tutorial/response-status-code.md)。
但在某些情况下,你需要返回一个不同于默认值的状态码。
-## 使用场景
+## 使用场景 { #use-case }
例如,假设你想默认返回一个HTTP状态码为“OK”`200`。
@@ -14,18 +14,18 @@
对于这些情况,你可以使用一个`Response`参数。
-## 使用 `Response` 参数
+## 使用 `Response` 参数 { #use-a-response-parameter }
你可以在你的*路径操作函数*中声明一个`Response`类型的参数(就像你可以为cookies和头部做的那样)。
然后你可以在这个*临时*响应对象中设置`status_code`。
-```Python hl_lines="1 9 12"
-{!../../../docs_src/response_change_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_change_status_code/tutorial001_py310.py hl[1,9,12] *}
-然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。
+然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。
-**FastAPI**将使用这个临时响应来提取状态码(也包括cookies和头部),并将它们放入包含你返回的值的最终响应中,该响应由任何`response_model`过滤。
+如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。
+
+**FastAPI**将使用这个*临时*响应来提取状态码(也包括cookies和头部),并将它们放入包含你返回的值的最终响应中,该响应由任何`response_model`过滤。
你也可以在依赖项中声明`Response`参数,并在其中设置状态码。但请注意,最后设置的状态码将会生效。
diff --git a/docs/zh/docs/advanced/response-cookies.md b/docs/zh/docs/advanced/response-cookies.md
index 3e53c53191a4c..7fad89e5c631a 100644
--- a/docs/zh/docs/advanced/response-cookies.md
+++ b/docs/zh/docs/advanced/response-cookies.md
@@ -1,12 +1,10 @@
-# 响应Cookies
+# 响应Cookies { #response-cookies }
-## 使用 `Response` 参数
+## 使用 `Response` 参数 { #use-a-response-parameter }
-你可以在 *路径函数* 中定义一个类型为 `Response`的参数,这样你就可以在这个临时响应对象中设置cookie了。
+你可以在 *路径操作函数* 中定义一个类型为 `Response` 的参数,这样你就可以在这个临时响应对象中设置cookie了。
-```Python hl_lines="1 8-9"
-{!../../../docs_src/response_cookies/tutorial002.py!}
-```
+{* ../../docs_src/response_cookies/tutorial002_py310.py hl[1, 8:9] *}
而且你还可以根据你的需要响应不同的对象,比如常用的 `dict`,数据库model等。
@@ -14,34 +12,38 @@
**FastAPI** 会使用这个 *临时* 响应对象去装在这些cookies信息 (同样还有headers和状态码等信息), 最终会将这些信息和通过`response_model`转化过的数据合并到最终的响应里。
-你也可以在depend中定义`Response`参数,并设置cookie和header。
+你也可以在依赖中定义`Response`参数,并设置cookie和header。
-## 直接响应 `Response`
+## 直接响应 `Response` { #return-a-response-directly }
你还可以在直接响应`Response`时直接创建cookies。
-你可以参考[Return a Response Directly](response-directly.md){.internal-link target=_blank}来创建response
+为此,你可以按照[直接返回 Response](response-directly.md)中的说明创建一个响应。
然后设置Cookies,并返回:
-```Python hl_lines="10-12"
-{!../../../docs_src/response_cookies/tutorial001.py!}
-```
+{* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *}
-!!! tip
- 需要注意,如果你直接反馈一个response对象,而不是使用`Response`入参,FastAPI则会直接反馈你封装的response对象。
+/// tip | 提示
- 所以你需要确保你响应数据类型的正确性,如:你可以使用`JSONResponse`来兼容JSON的场景。
+需要注意,如果你直接反馈一个response对象,而不是使用`Response`入参,FastAPI则会直接反馈你封装的response对象。
- 同时,你也应当仅反馈通过`response_model`过滤过的数据。
+所以你需要确保你响应数据类型的正确性,如:你可以使用`JSONResponse`来兼容JSON的场景。
-### 更多信息
+同时,你也应当仅反馈通过`response_model`过滤过的数据。
-!!! note "技术细节"
- 你也可以使用`from starlette.responses import Response` 或者 `from starlette.responses import JSONResponse`。
+///
- 为了方便开发者,**FastAPI** 封装了相同数据类型,如`starlette.responses` 和 `fastapi.responses`。不过大部分response对象都是直接引用自Starlette。
+### 更多信息 { #more-info }
- 因为`Response`对象可以非常便捷的设置headers和cookies,所以 **FastAPI** 同时也封装了`fastapi.Response`。
+/// note | 技术细节
-如果你想查看所有可用的参数和选项,可以参考 Starlette帮助文档
+你也可以使用`from starlette.responses import Response` 或者 `from starlette.responses import JSONResponse`。
+
+为了方便开发者,**FastAPI** 封装了相同数据类型,如`starlette.responses` 和 `fastapi.responses`。不过大部分response对象都是直接引用自Starlette。
+
+因为`Response`对象可以非常便捷的设置headers和cookies,所以 **FastAPI** 同时也封装了`fastapi.Response`。
+
+///
+
+如果你想查看所有可用的参数和选项,可以参考 [Starlette 文档](https://www.starlette.dev/responses/#set-cookie)。
diff --git a/docs/zh/docs/advanced/response-directly.md b/docs/zh/docs/advanced/response-directly.md
index 797a878eb923b..1966221467943 100644
--- a/docs/zh/docs/advanced/response-directly.md
+++ b/docs/zh/docs/advanced/response-directly.md
@@ -1,21 +1,29 @@
-# 直接返回响应
+# 直接返回响应 { #return-a-response-directly }
当你创建一个 **FastAPI** *路径操作* 时,你可以正常返回以下任意一种数据:`dict`,`list`,Pydantic 模型,数据库模型等等。
-**FastAPI** 默认会使用 `jsonable_encoder` 将这些类型的返回值转换成 JSON 格式,`jsonable_encoder` 在 [JSON 兼容编码器](../tutorial/encoder.md){.internal-link target=_blank} 中有阐述。
+如果你声明了 [响应模型](../tutorial/response-model.md),FastAPI 会使用它通过 Pydantic 将数据序列化为 JSON。
+如果你没有声明响应模型,**FastAPI** 会使用在 [JSON 兼容编码器](../tutorial/encoder.md) 中阐述的 `jsonable_encoder`。
然后,**FastAPI** 会在后台将这些兼容 JSON 的数据(比如字典)放到一个 `JSONResponse` 中,该 `JSONResponse` 会用来发送响应给客户端。
但是你可以在你的 *路径操作* 中直接返回一个 `JSONResponse`。
-直接返回响应可能会有用处,比如返回自定义的响应头和 cookies。
+/// tip | 提示
-## 返回 `Response`
+通常使用 [响应模型](../tutorial/response-model.md) 会比直接返回 `JSONResponse` 拥有更好的性能,因为它会在 Rust 中使用 Pydantic 序列化数据。
+
+///
+
+## 返回 `Response` { #return-a-response }
事实上,你可以返回任意 `Response` 或者任意 `Response` 的子类。
-!!! tip "小贴士"
- `JSONResponse` 本身是一个 `Response` 的子类。
+/// info | 信息
+
+`JSONResponse` 本身是一个 `Response` 的子类。
+
+///
当你返回一个 `Response` 时,**FastAPI** 会直接传递它。
@@ -23,42 +31,54 @@
这种特性给你极大的可扩展性。你可以返回任何数据类型,重写任何数据声明或者校验,等等。
-## 在 `Response` 中使用 `jsonable_encoder`
+这也带来了很大的责任。你必须确保你返回的数据是正确的、格式正确、可被序列化,等等。
+
+## 在 `Response` 中使用 `jsonable_encoder` { #using-the-jsonable-encoder-in-a-response }
由于 **FastAPI** 并未对你返回的 `Response` 做任何改变,你必须确保你已经准备好响应内容。
-例如,如果不首先将 Pydantic 模型转换为 `dict`,并将所有数据类型(如 `datetime`、`UUID` 等)转换为兼容 JSON 的类型,则不能将其放入JSONResponse中。
+例如,如果不首先将 Pydantic 模型转换为 `dict`,并将所有数据类型(如 `datetime`、`UUID` 等)转换为兼容 JSON 的类型,则不能将其放入 `JSONResponse` 中。
+
+对于这些情况,在将数据传递给响应之前,你可以使用 `jsonable_encoder` 来转换你的数据:
-对于这些情况,在将数据传递给响应之前,你可以使用 `jsonable_encoder` 来转换你的数据。
+{* ../../docs_src/response_directly/tutorial001_py310.py hl[5:6,20:21] *}
+/// note | 技术细节
-```Python hl_lines="4 6 20 21"
-{!../../../docs_src/response_directly/tutorial001.py!}
-```
+你也可以使用 `from starlette.responses import JSONResponse`。
-!!! note "技术细节"
- 你也可以使用 `from starlette.responses import JSONResponse`。
+出于方便,**FastAPI** 会提供与 `starlette.responses` 相同的 `fastapi.responses` 给开发者。但是大多数可用的响应都直接来自 Starlette。
- 出于方便,**FastAPI** 会提供与 `starlette.responses` 相同的 `fastapi.responses` 给开发者。但是大多数可用的响应都直接来自 Starlette。
+///
-## 返回自定义 `Response`
+## 返回自定义 `Response` { #returning-a-custom-response }
-上面的例子展示了需要的所有部分,但还不够实用,因为你本可以只是直接返回 `item`,而**FastAPI** 默认帮你把这个 `item` 放到 `JSONResponse` 中,又默认将其转换成了 `dict`等等。
+上面的例子展示了需要的所有部分,但还不够实用,因为你本可以只是直接返回 `item`,而 **FastAPI** 默认帮你把这个 `item` 放到 `JSONResponse` 中,又默认将其转换成了 `dict` 等等。
现在,让我们看看你如何才能返回一个自定义的响应。
-假设你想要返回一个 XML 响应。
+假设你想要返回一个 [XML](https://en.wikipedia.org/wiki/XML) 响应。
+
+你可以把你的 XML 内容放到一个字符串中,放到一个 `Response` 中,然后返回:
+
+{* ../../docs_src/response_directly/tutorial002_py310.py hl[1,18] *}
+
+## 响应模型如何工作 { #how-a-response-model-works }
+
+当你在路径操作中声明一个 [响应模型 - 返回类型](../tutorial/response-model.md) 时,**FastAPI** 会使用它通过 Pydantic 将数据序列化为 JSON。
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+由于这些工作会在 Rust 侧完成,性能将比在常规 Python 中配合 `JSONResponse` 类完成要好得多。
-你可以把你的 XML 内容放到一个字符串中,放到一个 `Response` 中,然后返回。
+当使用 `response_model` 或返回类型时,FastAPI 不会使用 `jsonable_encoder` 来转换数据(那样会更慢),也不会使用 `JSONResponse` 类。
-```Python hl_lines="1 18"
-{!../../../docs_src/response_directly/tutorial002.py!}
-```
+相反,它会采用使用该响应模型(或返回类型)由 Pydantic 生成的 JSON 字节,并直接返回一个具有正确 JSON 媒体类型(`application/json`)的 `Response`。
-## 说明
+## 说明 { #notes }
当你直接返回 `Response` 时,它的数据既没有校验,又不会进行转换(序列化),也不会自动生成文档。
-但是你仍可以参考 [OpenApI 中的额外响应](additional-responses.md){.internal-link target=_blank} 给响应编写文档。
+但是你仍可以参考 [OpenAPI 中的额外响应](additional-responses.md) 给响应编写文档。
在后续的章节中你可以了解到如何使用/声明这些自定义的 `Response` 的同时还保留自动化的数据转换和文档等。
diff --git a/docs/zh/docs/advanced/response-headers.md b/docs/zh/docs/advanced/response-headers.md
index 85dab15ac092f..ab99a4ece143f 100644
--- a/docs/zh/docs/advanced/response-headers.md
+++ b/docs/zh/docs/advanced/response-headers.md
@@ -1,39 +1,41 @@
-# 响应头
+# 响应头 { #response-headers }
-## 使用 `Response` 参数
+## 使用 `Response` 参数 { #use-a-response-parameter }
-你可以在你的*路径操作函数*中声明一个`Response`类型的参数(就像你可以为cookies做的那样)。
+你可以在你的*路径操作函数*中声明一个 `Response` 类型的参数(就像你可以为 cookies 做的那样)。
然后你可以在这个*临时*响应对象中设置头部。
-```Python hl_lines="1 7-8"
-{!../../../docs_src/response_headers/tutorial002.py!}
-```
-然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。
+{* ../../docs_src/response_headers/tutorial002_py310.py hl[1, 7:8] *}
-**FastAPI**将使用这个临时响应来提取头部(也包括cookies和状态码),并将它们放入包含你返回的值的最终响应中,该响应由任何`response_model`过滤。
+然后你可以像平常一样返回任何你需要的对象(例如一个 `dict` 或者一个数据库模型)。
-你也可以在依赖项中声明`Response`参数,并在其中设置头部(和cookies)。
+如果你声明了一个 `response_model`,它仍然会被用来过滤和转换你返回的对象。
-## 直接返回 `Response`
+**FastAPI** 将使用这个*临时*响应来提取头部(也包括 cookies 和状态码),并将它们放入包含你返回的值的最终响应中,该响应由任何 `response_model` 过滤。
-你也可以在直接返回`Response`时添加头部。
+你也可以在依赖项中声明 `Response` 参数,并在其中设置头部(和 cookies)。
-按照[直接返回响应](response-directly.md){.internal-link target=_blank}中所述创建响应,并将头部作为附加参数传递:
-```Python hl_lines="10-12"
-{!../../../docs_src/response_headers/tutorial001.py!}
-```
+## 直接返回 `Response` { #return-a-response-directly }
+你也可以在直接返回 `Response` 时添加头部。
-!!! 注意 "技术细节"
- 你也可以使用`from starlette.responses import Response`或`from starlette.responses import JSONResponse`。
+按照[直接返回响应](response-directly.md)中所述创建响应,并将头部作为附加参数传递:
- **FastAPI**提供了与`fastapi.responses`相同的`starlette.responses`,只是为了方便开发者。但是,大多数可用的响应都直接来自Starlette。
+{* ../../docs_src/response_headers/tutorial001_py310.py hl[10:12] *}
- 由于`Response`经常用于设置头部和cookies,因此**FastAPI**还在`fastapi.Response`中提供了它。
+/// note | 技术细节
-## 自定义头部
+你也可以使用 `from starlette.responses import Response` 或 `from starlette.responses import JSONResponse`。
-请注意,可以使用'X-'前缀添加自定义专有头部。
+**FastAPI** 提供了与 `fastapi.responses` 相同的 `starlette.responses`,只是为了方便你(开发者)。但是,大多数可用的响应都直接来自 Starlette。
-但是,如果你有自定义头部,你希望浏览器中的客户端能够看到它们,你需要将它们添加到你的CORS配置中(在[CORS(跨源资源共享)](../tutorial/cors.md){.internal-link target=_blank}中阅读更多),使用在Starlette的CORS文档中记录的`expose_headers`参数。
+由于 `Response` 经常用于设置头部和 cookies,**FastAPI** 还在 `fastapi.Response` 中提供了它。
+
+///
+
+## 自定义头部 { #custom-headers }
+
+请注意,可以通过[使用 `X-` 前缀](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers)添加自定义专有头部。
+
+但是,如果你有自定义头部,并希望浏览器中的客户端能够看到它们,你需要将它们添加到你的 CORS 配置中(在 [CORS(跨源资源共享)](../tutorial/cors.md) 中阅读更多),使用在 [Starlette 的 CORS 文档](https://www.starlette.dev/middleware/#corsmiddleware)中记录的 `expose_headers` 参数。
diff --git a/docs/zh/docs/advanced/security/http-basic-auth.md b/docs/zh/docs/advanced/security/http-basic-auth.md
new file mode 100644
index 0000000000000..37e4b5abcbf8b
--- /dev/null
+++ b/docs/zh/docs/advanced/security/http-basic-auth.md
@@ -0,0 +1,107 @@
+# HTTP 基础授权 { #http-basic-auth }
+
+最简单的用例是使用 HTTP 基础授权(HTTP Basic Auth)。
+
+在 HTTP 基础授权中,应用需要请求头包含用户名与密码。
+
+如果没有接收到 HTTP 基础授权,就返回 HTTP 401 `"Unauthorized"` 错误。
+
+并返回响应头 `WWW-Authenticate`,其值为 `Basic`,以及可选的 `realm` 参数。
+
+HTTP 基础授权让浏览器显示内置的用户名与密码提示。
+
+输入用户名与密码后,浏览器会把它们自动发送至请求头。
+
+## 简单的 HTTP 基础授权 { #simple-http-basic-auth }
+
+* 导入 `HTTPBasic` 与 `HTTPBasicCredentials`
+* 使用 `HTTPBasic` 创建**安全方案**
+* 在*路径操作*的依赖项中使用 `security`
+* 返回类型为 `HTTPBasicCredentials` 的对象:
+ * 包含发送的 `username` 与 `password`
+
+{* ../../docs_src/security/tutorial006_an_py310.py hl[4,8,12] *}
+
+第一次打开 URL(或在 API 文档中点击 **Execute** 按钮)时,浏览器要求输入用户名与密码:
+
+
+
+## 检查用户名 { #check-the-username }
+
+以下是更完整的示例。
+
+使用依赖项检查用户名与密码是否正确。
+
+为此要使用 Python 标准模块 [`secrets`](https://docs.python.org/3/library/secrets.html) 检查用户名与密码。
+
+`secrets.compare_digest()` 需要仅包含 ASCII 字符(英语字符)的 `bytes` 或 `str`,这意味着它不适用于像`á`一样的字符,如 `Sebastián`。
+
+为了解决这个问题,我们首先将 `username` 和 `password` 转换为使用 UTF-8 编码的 `bytes` 。
+
+然后我们可以使用 `secrets.compare_digest()` 来确保 `credentials.username` 是 `"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[1,12:24] *}
+
+这类似于:
+
+```Python
+if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
+ # Return some error
+ ...
+```
+
+但使用 `secrets.compare_digest()`,可以防御**时差攻击**,更加安全。
+
+### 时差攻击 { #timing-attacks }
+
+什么是**时差攻击**?
+
+假设攻击者试图猜出用户名与密码。
+
+他们发送用户名为 `johndoe`,密码为 `love123` 的请求。
+
+然后,Python 代码执行如下操作:
+
+```Python
+if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+但就在 Python 比较完 `johndoe` 的第一个字母 `j` 与 `stanleyjobson` 的 `s` 时,Python 就已经知道这两个字符串不相同了,它会这么想,**没必要浪费更多时间执行剩余字母的对比计算了**。应用立刻就会返回**错误的用户或密码**。
+
+但接下来,攻击者继续尝试 `stanleyjobsox` 和 密码 `love123`。
+
+应用代码会执行类似下面的操作:
+
+```Python
+if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
+ ...
+```
+
+此时,Python 要对比 `stanleyjobsox` 与 `stanleyjobson` 中的 `stanleyjobso`,才能知道这两个字符串不一样。因此会多花费几微秒来返回**错误的用户或密码**。
+
+#### 反应时间对攻击者的帮助 { #the-time-to-answer-helps-the-attackers }
+
+通过服务器花费了更多微秒才发送**错误的用户或密码**响应,攻击者会知道猜对了一些内容,起码开头字母是正确的。
+
+然后,他们就可以放弃 `johndoe`,再用类似 `stanleyjobsox` 的内容进行尝试。
+
+#### **专业**攻击 { #a-professional-attack }
+
+当然,攻击者不用手动操作,而是编写每秒能执行成千上万次测试的攻击程序,每次都会找到更多正确字符。
+
+但是,在您的应用的**帮助**下,攻击者利用时间差,就能在几分钟或几小时内,以这种方式猜出正确的用户名和密码。
+
+#### 使用 `secrets.compare_digest()` 修补 { #fix-it-with-secrets-compare-digest }
+
+在此,代码中使用了 `secrets.compare_digest()`。
+
+简单的说,它使用相同的时间对比 `stanleyjobsox` 和 `stanleyjobson`,还有 `johndoe` 和 `stanleyjobson`。对比密码时也一样。
+
+在代码中使用 `secrets.compare_digest()` ,就可以安全地防御这整类安全攻击。
+
+### 返回错误 { #return-the-error }
+
+检测到凭证不正确后,返回 `HTTPException` 及状态码 401(与无凭证时返回的内容一样),并添加响应头 `WWW-Authenticate`,让浏览器再次显示登录提示:
+
+{* ../../docs_src/security/tutorial007_an_py310.py hl[26:30] *}
diff --git a/docs/zh/docs/advanced/security/index.md b/docs/zh/docs/advanced/security/index.md
index fdc8075c765ba..e3a3ba9cea9b3 100644
--- a/docs/zh/docs/advanced/security/index.md
+++ b/docs/zh/docs/advanced/security/index.md
@@ -1,16 +1,19 @@
-# 高级安全
+# 高级安全 { #advanced-security }
-## 附加特性
+## 附加特性 { #additional-features }
-除 [教程 - 用户指南: 安全性](../../tutorial/security/){.internal-link target=_blank} 中涵盖的功能之外,还有一些额外的功能来处理安全性.
+除 [教程 - 用户指南: 安全性](../../tutorial/security/index.md) 中涵盖的功能之外,还有一些额外的功能来处理安全性。
-!!! tip "小贴士"
- 接下来的章节 **并不一定是 "高级的"**.
+/// tip | 提示
- 而且对于你的使用场景来说,解决方案很可能就在其中。
+接下来的章节**并不一定是 "高级的"**。
-## 先阅读教程
+而且对于你的使用场景来说,解决方案很可能就在其中。
-接下来的部分假设你已经阅读了主要的 [教程 - 用户指南: 安全性](../../tutorial/security/){.internal-link target=_blank}.
+///
-它们都基于相同的概念,但支持一些额外的功能.
+## 先阅读教程 { #read-the-tutorial-first }
+
+接下来的部分假设你已经阅读了主要的 [教程 - 用户指南: 安全性](../../tutorial/security/index.md)。
+
+它们都基于相同的概念,但支持一些额外的功能。
diff --git a/docs/zh/docs/advanced/security/oauth2-scopes.md b/docs/zh/docs/advanced/security/oauth2-scopes.md
new file mode 100644
index 0000000000000..a1ecc641ca226
--- /dev/null
+++ b/docs/zh/docs/advanced/security/oauth2-scopes.md
@@ -0,0 +1,274 @@
+# OAuth2 作用域 { #oauth2-scopes }
+
+你可以在 **FastAPI** 中直接使用 OAuth2 作用域(Scopes),它们已无缝集成。
+
+这样你就可以按照 OAuth2 标准,构建更精细的权限系统,并将其集成进你的 OpenAPI 应用(以及 API 文档)中。
+
+带作用域的 OAuth2 是很多大型身份验证提供商使用的机制,例如 Facebook、Google、GitHub、Microsoft、X (Twitter) 等。它们用它来为用户和应用授予特定权限。
+
+每次你“使用” Facebook、Google、GitHub、Microsoft、X (Twitter) “登录”时,该应用就在使用带作用域的 OAuth2。
+
+本节将介绍如何在你的 **FastAPI** 应用中,使用相同的带作用域的 OAuth2 管理认证与授权。
+
+/// warning | 警告
+
+本节内容相对进阶,如果你刚开始,可以先跳过。
+
+你并不一定需要 OAuth2 作用域,你也可以用你自己的方式处理认证与授权。
+
+但带作用域的 OAuth2 能很好地集成进你的 API(通过 OpenAPI)和 API 文档。
+
+不过,无论如何,你都可以在代码中按需强制这些作用域,或任何其它安全/授权需求。
+
+很多情况下,带作用域的 OAuth2 可能有点“大材小用”。
+
+但如果你确实需要它,或者只是好奇,请继续阅读。
+
+///
+
+## OAuth2 作用域与 OpenAPI { #oauth2-scopes-and-openapi }
+
+OAuth2 规范将“作用域”定义为由空格分隔的字符串列表。
+
+这些字符串的内容可以是任意格式,但不应包含空格。
+
+这些作用域表示“权限”。
+
+在 OpenAPI(例如 API 文档)中,你可以定义“安全方案”(security schemes)。
+
+当这些安全方案使用 OAuth2 时,你还可以声明并使用作用域。
+
+每个“作用域”只是一个(不带空格的)字符串。
+
+它们通常用于声明特定的安全权限,例如:
+
+* 常见示例:`users:read` 或 `users:write`
+* Facebook / Instagram 使用 `instagram_basic`
+* Google 使用 `https://www.googleapis.com/auth/drive`
+
+/// info | 信息
+
+在 OAuth2 中,“作用域”只是一个声明所需特定权限的字符串。
+
+是否包含像 `:` 这样的字符,或者是不是一个 URL,并不重要。
+
+这些细节取决于具体实现。
+
+对 OAuth2 而言,它们都只是字符串。
+
+///
+
+## 全局纵览 { #global-view }
+
+首先,让我们快速看看与**用户指南**中 [OAuth2 实现密码(含哈希)、Bearer + JWT 令牌](../../tutorial/security/oauth2-jwt.md) 示例相比有哪些变化。现在开始使用 OAuth2 作用域:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:126,130:136,141,157] *}
+
+下面我们逐步回顾这些更改。
+
+## OAuth2 安全方案 { #oauth2-security-scheme }
+
+第一个变化是:我们在声明 OAuth2 安全方案时,添加了两个可用的作用域 `me` 和 `items`。
+
+参数 `scopes` 接收一个 `dict`,以作用域为键、描述为值:
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *}
+
+因为我们现在声明了这些作用域,所以当你登录/授权时,它们会显示在 API 文档里。
+
+你可以选择要授予访问权限的作用域:`me` 和 `items`。
+
+这与使用 Facebook、Google、GitHub 等登录时授予权限的机制相同:
+
+
+
+## 带作用域的 JWT 令牌 { #jwt-token-with-scopes }
+
+现在,修改令牌的*路径操作*以返回请求的作用域。
+
+我们仍然使用 `OAuth2PasswordRequestForm`。它包含 `scopes` 属性,其值是 `list[str]`,包含请求中接收到的每个作用域。
+
+我们把这些作用域作为 JWT 令牌的一部分返回。
+
+/// danger | 危险
+
+为简单起见,此处我们只是把接收到的作用域直接添加到了令牌中。
+
+但在你的应用里,为了安全起见,你应该只添加该用户实际能够拥有的作用域,或你预先定义的作用域。
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[157] *}
+
+## 在*路径操作*与依赖项中声明作用域 { #declare-scopes-in-path-operations-and-dependencies }
+
+现在我们声明,路径操作 `/users/me/items/` 需要作用域 `items`。
+
+为此,从 `fastapi` 导入并使用 `Security`。
+
+你可以用 `Security` 来声明依赖(就像 `Depends` 一样),但 `Security` 还接收一个 `scopes` 参数,其值是作用域(字符串)列表。
+
+在这里,我们把依赖函数 `get_current_active_user` 传给 `Security`(就像用 `Depends` 一样)。
+
+同时还传入一个作用域 `list`,此处仅包含一个作用域:`items`(也可以包含更多)。
+
+依赖函数 `get_current_active_user` 也可以声明子依赖,不仅可以用 `Depends`,也可以用 `Security`。它声明了自己的子依赖函数(`get_current_user`),并添加了更多的作用域需求。
+
+在这个例子里,它需要作用域 `me`(也可以需要多个作用域)。
+
+/// note | 注意
+
+不必在不同位置添加不同的作用域。
+
+这里这样做,是为了演示 **FastAPI** 如何处理在不同层级声明的作用域。
+
+///
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *}
+
+/// info | 技术细节
+
+`Security` 实际上是 `Depends` 的子类,它只多了一个我们稍后会看到的参数。
+
+但当你使用 `Security` 而不是 `Depends` 时,**FastAPI** 会知道它可以声明安全作用域,在内部使用它们,并用 OpenAPI 文档化 API。
+
+另外,从 `fastapi` 导入的 `Query`、`Path`、`Depends`、`Security` 等,实际上都是返回特殊类的函数。
+
+///
+
+## 使用 `SecurityScopes` { #use-securityscopes }
+
+现在更新依赖项 `get_current_user`。
+
+上面那些依赖会用到它。
+
+这里我们使用之前创建的同一个 OAuth2 方案,并把它声明为依赖:`oauth2_scheme`。
+
+因为这个依赖函数本身没有任何作用域需求,所以我们可以用 `Depends(oauth2_scheme)`,当不需要指定安全作用域时,不必使用 `Security`。
+
+我们还声明了一个从 `fastapi.security` 导入的特殊参数 `SecurityScopes` 类型。
+
+这个 `SecurityScopes` 类类似于 `Request`(`Request` 用来直接获取请求对象)。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *}
+
+## 使用 `scopes` { #use-the-scopes }
+
+参数 `security_scopes` 的类型是 `SecurityScopes`。
+
+它会有一个 `scopes` 属性,包含一个列表,里面是它自身以及所有把它作为子依赖的依赖项所需要的所有作用域。也就是说,所有“依赖者”……这可能有点绕,下面会再次解释。
+
+`security_scopes` 对象(类型为 `SecurityScopes`)还提供了一个 `scope_str` 属性,它是一个用空格分隔这些作用域的单个字符串(我们将会用到它)。
+
+我们创建一个 `HTTPException`,后面可以在多个位置复用(`raise`)它。
+
+在这个异常中,我们包含所需的作用域(如果有的话),以空格分隔的字符串(使用 `scope_str`)。我们把这个包含作用域的字符串放在 `WWW-Authenticate` 响应头中(这是规范要求的一部分)。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *}
+
+## 校验 `username` 与数据形状 { #verify-the-username-and-data-shape }
+
+我们校验是否获取到了 `username`,并提取作用域。
+
+然后使用 Pydantic 模型验证这些数据(捕获 `ValidationError` 异常),如果读取 JWT 令牌或用 Pydantic 验证数据时出错,就抛出我们之前创建的 `HTTPException`。
+
+为此,我们给 Pydantic 模型 `TokenData` 添加了一个新属性 `scopes`。
+
+通过用 Pydantic 验证数据,我们可以确保确实得到了例如一个由作用域组成的 `list[str]`,以及一个 `str` 类型的 `username`。
+
+而不是,例如得到一个 `dict` 或其它什么,这可能会在后续某个时刻破坏应用,形成安全风险。
+
+我们还验证是否存在该用户名的用户,如果没有,就抛出前面创建的同一个异常。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:129] *}
+
+## 校验 `scopes` { #verify-the-scopes }
+
+现在我们要验证,这个依赖以及所有依赖者(包括*路径操作*)所需的所有作用域,是否都包含在接收到的令牌里的作用域中,否则就抛出 `HTTPException`。
+
+为此,我们使用 `security_scopes.scopes`,它包含一个由这些作用域组成的 `list[str]`。
+
+{* ../../docs_src/security/tutorial005_an_py310.py hl[130:136] *}
+
+## 依赖树与作用域 { #dependency-tree-and-scopes }
+
+再次回顾这个依赖树与作用域。
+
+由于 `get_current_active_user` 依赖把 `get_current_user` 作为子依赖,因此在 `get_current_active_user` 中声明的作用域 `"me"` 会被包含在传给 `get_current_user` 的 `security_scopes.scopes` 所需作用域列表中。
+
+*路径操作*本身也声明了一个作用域 `"items"`,它也会包含在传给 `get_current_user` 的 `security_scopes.scopes` 列表中。
+
+依赖与作用域的层级结构如下:
+
+* *路径操作* `read_own_items` 包含:
+ * 带有依赖的必需作用域 `["items"]`:
+ * `get_current_active_user`:
+ * 依赖函数 `get_current_active_user` 包含:
+ * 带有依赖的必需作用域 `["me"]`:
+ * `get_current_user`:
+ * 依赖函数 `get_current_user` 包含:
+ * 自身不需要任何作用域。
+ * 一个使用 `oauth2_scheme` 的依赖。
+ * 一个类型为 `SecurityScopes` 的 `security_scopes` 参数:
+ * 该 `security_scopes` 参数有一个 `scopes` 属性,它是一个包含上面所有已声明作用域的 `list`,因此:
+ * 对于*路径操作* `read_own_items`,`security_scopes.scopes` 将包含 `["me", "items"]`。
+ * 对于*路径操作* `read_users_me`,`security_scopes.scopes` 将包含 `["me"]`,因为它在依赖 `get_current_active_user` 中被声明。
+ * 对于*路径操作* `read_system_status`,`security_scopes.scopes` 将包含 `[]`(空列表),因为它既没有声明任何带 `scopes` 的 `Security`,其依赖 `get_current_user` 也没有声明任何 `scopes`。
+
+/// tip | 提示
+
+这里重要且“神奇”的地方是,`get_current_user` 在检查每个*路径操作*时会得到不同的 `scopes` 列表。
+
+这一切都取决于为该特定*路径操作*在其自身以及依赖树中的每个依赖里声明的 `scopes`。
+
+///
+
+## 关于 `SecurityScopes` 的更多细节 { #more-details-about-securityscopes }
+
+你可以在任意位置、多个位置使用 `SecurityScopes`,不一定非得在“根”依赖里。
+
+它总会包含当前 `Security` 依赖中以及所有依赖者在“该特定”*路径操作*和“该特定”依赖树里声明的安全作用域。
+
+因为 `SecurityScopes` 会包含依赖者声明的所有作用域,你可以在一个核心依赖函数里用它验证令牌是否具有所需作用域,然后在不同的*路径操作*里声明不同的作用域需求。
+
+它们会针对每个*路径操作*分别检查。
+
+## 查看文档 { #check-it }
+
+打开 API 文档,你可以进行身份验证,并指定要授权的作用域。
+
+
+
+如果你不选择任何作用域,你依然会“通过认证”,但当你访问 `/users/me/` 或 `/users/me/items/` 时,会收到一个错误,提示你没有足够的权限。你仍然可以访问 `/status/`。
+
+如果你选择了作用域 `me`,但没有选择作用域 `items`,你可以访问 `/users/me/`,但不能访问 `/users/me/items/`。
+
+当第三方应用使用用户提供的令牌访问这些*路径操作*时,也会发生同样的情况,取决于用户授予该应用了多少权限。
+
+## 关于第三方集成 { #about-third-party-integrations }
+
+在这个示例中我们使用的是 OAuth2 的“password”流。
+
+当我们登录自己的应用(很可能还有我们自己的前端)时,这是合适的。
+
+因为我们可以信任它来接收 `username` 和 `password`,毕竟我们掌控它。
+
+但如果你在构建一个 OAuth2 应用,让其它应用来连接(也就是说,你在构建等同于 Facebook、Google、GitHub 等的身份验证提供商),你应该使用其它的流。
+
+最常见的是隐式流(implicit flow)。
+
+最安全的是代码流(authorization code flow),但实现更复杂,需要更多步骤。也因为更复杂,很多提供商最终会建议使用隐式流。
+
+/// note | 注意
+
+每个身份验证提供商常常会用不同的方式给它们的流命名,以融入自己的品牌。
+
+但归根结底,它们实现的都是同一个 OAuth2 标准。
+
+///
+
+**FastAPI** 在 `fastapi.security.oauth2` 中为所有这些 OAuth2 身份验证流提供了工具。
+
+## 装饰器 `dependencies` 中的 `Security` { #security-in-decorator-dependencies }
+
+就像你可以在装饰器的 `dependencies` 参数中定义 `Depends` 的 `list`(详见[路径操作装饰器依赖项](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md)),你也可以在那儿配合 `Security` 使用 `scopes`。
diff --git a/docs/zh/docs/advanced/settings.md b/docs/zh/docs/advanced/settings.md
index 597e99a7793c3..31a7cc82de705 100644
--- a/docs/zh/docs/advanced/settings.md
+++ b/docs/zh/docs/advanced/settings.md
@@ -1,326 +1,213 @@
-# 设置和环境变量
+# 设置和环境变量 { #settings-and-environment-variables }
-在许多情况下,您的应用程序可能需要一些外部设置或配置,例如密钥、数据库凭据、电子邮件服务的凭据等等。
+在许多情况下,你的应用可能需要一些外部设置或配置,例如密钥、数据库凭据、电子邮件服务的凭据等。
-这些设置中的大多数是可变的(可以更改的),比如数据库的 URL。而且许多设置可能是敏感的,比如密钥。
+这些设置中的大多数是可变的(可能会改变),例如数据库 URL。并且很多可能是敏感的,比如密钥。
因此,通常会将它们提供为由应用程序读取的环境变量。
-## 环境变量
+/// tip | 提示
-!!! tip
- 如果您已经知道什么是"环境变量"以及如何使用它们,请随意跳到下面的下一节。
+要理解环境变量,你可以阅读[环境变量](../environment-variables.md)。
-环境变量(也称为"env var")是一种存在于 Python 代码之外、存在于操作系统中的变量,可以被您的 Python 代码(或其他程序)读取。
+///
-您可以在 shell 中创建和使用环境变量,而无需使用 Python:
+## 类型和验证 { #types-and-validation }
-=== "Linux、macOS、Windows Bash"
+这些环境变量只能处理文本字符串,因为它们在 Python 之外,并且必须与其他程序及系统的其余部分兼容(甚至与不同的操作系统,如 Linux、Windows、macOS)。
-
+
+然后查看子应用文档 [http://127.0.0.1:8000/subapi/docs](http://127.0.0.1:8000/subapi/docs)。
+
+下图显示的是子应用的 API 文档,也是只包括其自有的*路径操作*,所有这些路径操作都在 `/subapi` 子路径前缀下。
+
+
+
+两个用户界面都可以正常运行,因为浏览器能够与每个指定的应用或子应用会话。
+
+### 技术细节:`root_path` { #technical-details-root-path }
+
+以上述方式挂载子应用时,FastAPI 使用 ASGI 规范中的 `root_path` 机制处理挂载子应用路径之间的通信。
+
+这样,子应用就可以为自动文档使用路径前缀。
+
+并且子应用还可以再挂载子应用,一切都会正常运行,FastAPI 可以自动处理所有 `root_path`。
+
+关于 `root_path` 及如何显式使用 `root_path` 的内容,详见[使用代理](behind-a-proxy.md)一章。
diff --git a/docs/zh/docs/advanced/templates.md b/docs/zh/docs/advanced/templates.md
new file mode 100644
index 0000000000000..952f438c73013
--- /dev/null
+++ b/docs/zh/docs/advanced/templates.md
@@ -0,0 +1,125 @@
+# 模板 { #templates }
+
+**FastAPI** 支持多种模板引擎。
+
+Flask 等工具使用的 Jinja2 是最用的模板引擎。
+
+在 Starlette 的支持下,**FastAPI** 应用可以直接使用工具轻易地配置 Jinja2。
+
+## 安装依赖项 { #install-dependencies }
+
+确保你创建一个[虚拟环境](../virtual-environments.md),激活它,并安装 `jinja2`:
+
+
-您的 **FastAPI** 应用程序将回复:
+您的 **FastAPI** 应用程序将通过 WebSockets 回复:
@@ -89,11 +94,9 @@ $ uvicorn main:app --reload
-所有这些消息都将使用同一个 WebSocket 连
-
-接。
+所有这些消息都将使用同一个 WebSocket 连接。
-## 使用 `Depends` 和其他依赖项
+## 使用 `Depends` 和其他依赖项 { #using-depends-and-others }
在 WebSocket 端点中,您可以从 `fastapi` 导入并使用以下内容:
@@ -104,88 +107,54 @@ $ uvicorn main:app --reload
* `Path`
* `Query`
-它们的工作方式与其他 FastAPI 端点/ *路径操作* 相同:
-
-=== "Python 3.10+"
-
- ```Python hl_lines="68-69 82"
- {!> ../../../docs_src/websockets/tutorial002_an_py310.py!}
- ```
-
-=== "Python 3.9+"
+它们的工作方式与其他 FastAPI 端点/*路径操作* 相同:
- ```Python hl_lines="68-69 82"
- {!> ../../../docs_src/websockets/tutorial002_an_py39.py!}
- ```
+{* ../../docs_src/websockets_/tutorial002_an_py310.py hl[68:69,82] *}
-=== "Python 3.6+"
+/// info
- ```Python hl_lines="69-70 83"
- {!> ../../../docs_src/websockets/tutorial002_an.py!}
- ```
+由于这是一个 WebSocket,抛出 `HTTPException` 并不是很合理,而是抛出 `WebSocketException`。
-=== "Python 3.10+ 非带注解版本"
+您可以使用[规范中定义的有效代码](https://tools.ietf.org/html/rfc6455#section-7.4.1)。
- !!! tip
- 如果可能,请尽量使用 `Annotated` 版本。
+///
- ```Python hl_lines="66-67 79"
- {!> ../../../docs_src/websockets/tutorial002_py310.py!}
- ```
+### 尝试带有依赖项的 WebSockets { #try-the-websockets-with-dependencies }
-=== "Python 3.6+ 非带注解版本"
+运行你的应用程序:
- !!! tip
- 如果可能,请尽量使用 `Annotated` 版本。
-
- ```Python hl_lines="68-69 81"
- {!> ../../../docs_src/websockets/tutorial002.py!}
- ```
-
-!!! info
- 由于这是一个 WebSocket,抛出 `HTTPException` 并不是很合理,而是抛出 `WebSocketException`。
-
- 您可以使用规范中定义的有效代码。
-
-### 尝试带有依赖项的 WebSockets
-
-如果您的文件名为 `main.py`,请使用以下命令运行应用程序:
+
-## 处理断开连接和多个客户端
+## 处理断开连接和多个客户端 { #handling-disconnections-and-multiple-clients }
当 WebSocket 连接关闭时,`await websocket.receive_text()` 将引发 `WebSocketDisconnect` 异常,您可以捕获并处理该异常,就像本示例中的示例一样。
-=== "Python 3.9+"
-
- ```Python hl_lines="79-81"
- {!> ../../../docs_src/websockets/tutorial003_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="81-83"
- {!> ../../../docs_src/websockets/tutorial003.py!}
- ```
+{* ../../docs_src/websockets_/tutorial003_py310.py hl[79:81] *}
尝试以下操作:
@@ -199,16 +168,19 @@ $ uvicorn main:app --reload
Client #1596980209979 left the chat
```
-!!! tip
- 上面的应用程序是一个最小和简单的示例,用于演示如何处理和向多个 WebSocket 连接广播消息。
+/// tip
+
+上面的应用程序是一个最小和简单的示例,用于演示如何处理和向多个 WebSocket 连接广播消息。
+
+但请记住,由于所有内容都在内存中以单个列表的形式处理,因此它只能在进程运行时工作,并且只能使用单个进程。
- 但请记住,由于所有内容都在内存中以单个列表的形式处理,因此它只能在进程运行时工作,并且只能使用单个进程。
+如果您需要与 FastAPI 集成更简单但更强大的功能,支持 Redis、PostgreSQL 或其他功能,请查看 [encode/broadcaster](https://github.com/encode/broadcaster)。
- 如果您需要与 FastAPI 集成更简单但更强大的功能,支持 Redis、PostgreSQL 或其他功能,请查看 [encode/broadcaster](https://github.com/encode/broadcaster)。
+///
-## 更多信息
+## 更多信息 { #more-info }
要了解更多选项,请查看 Starlette 的文档:
-* [WebSocket 类](https://www.starlette.io/websockets/)
-* [基于类的 WebSocket 处理](https://www.starlette.io/endpoints/#websocketendpoint)。
+* [`WebSocket` 类](https://www.starlette.dev/websockets/)。
+* [基于类的 WebSocket 处理](https://www.starlette.dev/endpoints/#websocketendpoint)。
diff --git a/docs/zh/docs/advanced/wsgi.md b/docs/zh/docs/advanced/wsgi.md
index ad71280fc6180..038b672f8a2fa 100644
--- a/docs/zh/docs/advanced/wsgi.md
+++ b/docs/zh/docs/advanced/wsgi.md
@@ -1,34 +1,48 @@
-# 包含 WSGI - Flask,Django,其它
+# 包含 WSGI - Flask,Django,其它 { #including-wsgi-flask-django-others }
-您可以挂载多个 WSGI 应用,正如您在 [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](./behind-a-proxy.md){.internal-link target=_blank} 中所看到的那样。
+您可以挂载 WSGI 应用,正如您在 [子应用 - 挂载](sub-applications.md)、[在代理之后](behind-a-proxy.md) 中所看到的那样。
为此, 您可以使用 `WSGIMiddleware` 来包装你的 WSGI 应用,如:Flask,Django,等等。
-## 使用 `WSGIMiddleware`
+## 使用 `WSGIMiddleware` { #using-wsgimiddleware }
-您需要导入 `WSGIMiddleware`。
+/// info | 信息
+
+需要安装 `a2wsgi`,例如使用 `pip install a2wsgi`。
+
+///
+
+您需要从 `a2wsgi` 导入 `WSGIMiddleware`。
然后使用该中间件包装 WSGI 应用(例如 Flask)。
之后将其挂载到某一个路径下。
-```Python hl_lines="2-3 22"
-{!../../../docs_src/wsgi/tutorial001.py!}
-```
+{* ../../docs_src/wsgi/tutorial001_py310.py hl[1,3,23] *}
+
+/// note | 注意
+
+之前推荐使用 `fastapi.middleware.wsgi` 中的 `WSGIMiddleware`,但它现在已被弃用。
+
+建议改用 `a2wsgi` 包,使用方式保持不变。
+
+只要确保已安装 `a2wsgi` 包,并且从 `a2wsgi` 正确导入 `WSGIMiddleware` 即可。
+
+///
-## 检查
+## 检查 { #check-it }
现在,所有定义在 `/v1/` 路径下的请求将会被 Flask 应用处理。
其余的请求则会被 **FastAPI** 处理。
-如果您使用 Uvicorn 运行应用实例并且访问 http://localhost:8000/v1/,您将会看到由 Flask 返回的响应:
+如果你运行它并访问 [http://localhost:8000/v1/](http://localhost:8000/v1/),你将会看到由 Flask 返回的响应:
```txt
Hello, World from Flask!
```
-并且如果您访问 http://localhost:8000/v2,您将会看到由 FastAPI 返回的响应:
+如果你访问 [http://localhost:8000/v2](http://localhost:8000/v2),你将会看到由 FastAPI 返回的响应:
```JSON
{
diff --git a/docs/zh/docs/alternatives.md b/docs/zh/docs/alternatives.md
new file mode 100644
index 0000000000000..fe7aa98698c67
--- /dev/null
+++ b/docs/zh/docs/alternatives.md
@@ -0,0 +1,482 @@
+# 替代方案、灵感与对比 { #alternatives-inspiration-and-comparisons }
+
+是什么启发了 **FastAPI**,它与替代方案的比较,以及它从中学到的东西。
+
+## 介绍 { #intro }
+
+没有前人的工作,就不会有 **FastAPI**。
+
+在它诞生之前,已经有许多工具为其提供了灵感。
+
+我曾经多年避免创建一个新框架。起初,我尝试用许多不同的框架、插件和工具来解决 **FastAPI** 所覆盖的全部功能。
+
+但在某个时刻,除了创造一个能提供所有这些功能的东西之外,别无选择;它要吸收以往工具的最佳理念,并以尽可能好的方式组合起来,利用之前都不存在的语言特性(Python 3.6+ 类型提示)。
+
+## 先前的工具 { #previous-tools }
+
+### [Django](https://www.djangoproject.com/) { #django }
+
+它是最流行且被广泛信任的 Python 框架。被用于构建 Instagram 等系统。
+
+它与关系型数据库(如 MySQL、PostgreSQL)耦合相对紧密,因此若要以 NoSQL 数据库(如 Couchbase、MongoDB、Cassandra 等)作为主要存储引擎并不容易。
+
+它最初用于在后端生成 HTML,而不是创建由现代前端(如 React、Vue.js、Angular)或与之通信的其他系统(如 IoT 设备)使用的 API。
+
+### [Django REST Framework](https://www.django-rest-framework.org/) { #django-rest-framework }
+
+Django REST framework 作为一个灵活工具箱而创建,用于在底层使用 Django 构建 Web API,从而增强其 API 能力。
+
+它被包括 Mozilla、Red Hat、Eventbrite 在内的许多公司使用。
+
+它是最早的“自动 API 文档”的范例之一,这正是启发“寻找” **FastAPI** 的最初想法之一。
+
+/// note | 注意
+
+Django REST Framework 由 Tom Christie 创建。他也是 Starlette 和 Uvicorn 的作者,**FastAPI** 就是基于它们构建的。
+
+///
+
+/// check | 启发 **FastAPI**:
+
+提供自动化的 API 文档 Web 界面。
+
+///
+
+### [Flask](https://flask.palletsprojects.com) { #flask }
+
+Flask 是一个“微框架”,它不包含数据库集成,也没有像 Django 那样的许多默认内建功能。
+
+这种简单与灵活使得可以将 NoSQL 数据库作为主要的数据存储系统。
+
+由于非常简单,它相对直观易学,尽管文档在某些部分略显偏技术。
+
+它也常用于不一定需要数据库、用户管理,或任何 Django 预构建功能的应用;当然,许多这类功能可以通过插件添加。
+
+这种组件解耦、可按需扩展的“微框架”特性,是我想保留的关键点。
+
+鉴于 Flask 的简洁,它似乎非常适合构建 API。接下来要找的,就是 Flask 版的 “Django REST Framework”。
+
+/// check | 启发 **FastAPI**:
+
+- 成为微框架,便于按需组合所需的工具与组件。
+- 提供简单易用的路由系统。
+
+///
+
+### [Requests](https://requests.readthedocs.io) { #requests }
+
+**FastAPI** 实际上不是 **Requests** 的替代品。它们的作用范围完全不同。
+
+在 FastAPI 应用程序内部使用 Requests 其实非常常见。
+
+尽管如此,FastAPI 依然从 Requests 中获得了不少灵感。
+
+**Requests** 是一个用于与 API 交互(作为客户端)的库,而 **FastAPI** 是一个用于构建 API(作为服务端)的库。
+
+它们处在某种意义上的“对立端”,彼此互补。
+
+Requests 设计非常简单直观,易于使用,且有合理的默认值。同时它也非常强大、可定制。
+
+这就是为什么,正如其官网所说:
+
+> Requests 是有史以来下载量最高的 Python 包之一
+
+它的用法非常简单。例如,进行一次 `GET` 请求,你会这样写:
+
+```Python
+response = requests.get("http://example.com/some/url")
+```
+
+对应地,FastAPI 的 API 路径操作可能看起来是这样的:
+
+```Python hl_lines="1"
+@app.get("/some/url")
+def read_url():
+ return {"message": "Hello World"}
+```
+
+可以看到 `requests.get(...)` 与 `@app.get(...)` 的相似之处。
+
+/// check | 启发 **FastAPI**:
+
+* 提供简单直观的 API。
+* 直接、自然地使用 HTTP 方法名(操作)。
+* 具备合理默认值,同时支持强大定制能力。
+
+///
+
+### [Swagger](https://swagger.io/) / [OpenAPI](https://github.com/OAI/OpenAPI-Specification/) { #swagger-openapi }
+
+我想从 Django REST Framework 得到的主要特性之一是自动 API 文档。
+
+随后我发现有一个用于用 JSON(或 YAML,JSON 的扩展)来描述 API 的标准,称为 Swagger。
+
+并且已经有了用于 Swagger API 的 Web 用户界面。因此,只要能为 API 生成 Swagger 文档,就能自动使用这个 Web 界面。
+
+后来,Swagger 交由 Linux 基金会管理,并更名为 OpenAPI。
+
+因此,在谈到 2.0 版本时人们常说 “Swagger”,而 3+ 版本则称为 “OpenAPI”。
+
+/// check | 启发 **FastAPI**:
+
+采用并使用开放的 API 规范标准,而非自定义模式。
+
+并集成基于标准的用户界面工具:
+
+* [Swagger UI](https://github.com/swagger-api/swagger-ui)
+* [ReDoc](https://github.com/Rebilly/ReDoc)
+
+选择这两者是因为它们相当流行且稳定;但稍作搜索,你就能找到数十种 OpenAPI 的替代用户界面(都可以与 **FastAPI** 搭配使用)。
+
+///
+
+### Flask REST 框架 { #flask-rest-frameworks }
+
+有若干基于 Flask 的 REST 框架,但在投入时间精力深入调研后,我发现许多已停止维护或被弃用,并存在多处未解决问题,不太适合采用。
+
+### [Marshmallow](https://marshmallow.readthedocs.io/en/stable/) { #marshmallow }
+
+API 系统所需的主要特性之一是数据“序列化”,即将代码(Python)中的数据转换为可通过网络发送的形式。例如,将包含数据库数据的对象转换为 JSON 对象、将 `datetime` 对象转换为字符串等。
+
+API 的另一个重要特性是数据校验,确保数据在给定约束下是有效的。例如,某个字段必须是 `int` 而不是任意字符串。这对传入数据尤其有用。
+
+没有数据校验系统的话,你就得在代码里手写所有检查。
+
+这些正是 Marshmallow 要提供的功能。它是个很棒的库,我之前大量使用过。
+
+但它诞生于 Python 类型提示出现之前。因此,定义每个模式都需要使用 Marshmallow 提供的特定工具和类。
+
+/// check | 启发 **FastAPI**:
+
+使用代码定义“模式”,自动提供数据类型与校验。
+
+///
+
+### [Webargs](https://webargs.readthedocs.io/en/latest/) { #webargs }
+
+API 的另一个重要需求是从传入请求中解析数据。
+
+Webargs 是一个在多个框架(包括 Flask)之上提供该功能的工具。
+
+它在底层使用 Marshmallow 进行数据校验,并且由相同的开发者创建。
+
+在拥有 **FastAPI** 之前,我也大量使用过它,这是个很棒的工具。
+
+/// info | 信息
+
+Webargs 由与 Marshmallow 相同的开发者创建。
+
+///
+
+/// check | 启发 **FastAPI**:
+
+对传入请求数据进行自动校验。
+
+///
+
+### [APISpec](https://apispec.readthedocs.io/en/stable/) { #apispec }
+
+Marshmallow 与 Webargs 通过插件提供了校验、解析与序列化。
+
+但文档仍然缺失,于是出现了 APISpec。
+
+它为许多框架提供插件(Starlette 也有插件)。
+
+它的工作方式是:你在处理路由的每个函数的文档字符串里,用 YAML 格式编写模式定义。
+
+然后它会生成 OpenAPI 模式。
+
+这正是它在 Flask、Starlette、Responder 等框架里的工作方式。
+
+但这样我们又回到了在 Python 字符串中维护一套“微语法”(一大段 YAML)的问题上。
+
+编辑器很难为此提供帮助;而且如果我们修改了参数或 Marshmallow 模式,却忘了同步更新那个 YAML 文档字符串,生成的模式就会过时。
+
+/// info | 信息
+
+APISpec 由与 Marshmallow 相同的开发者创建。
+
+///
+
+/// check | 启发 **FastAPI**:
+
+支持开放的 API 标准 OpenAPI。
+
+///
+
+### [Flask-apispec](https://flask-apispec.readthedocs.io/en/latest/) { #flask-apispec }
+
+这是一个 Flask 插件,将 Webargs、Marshmallow 与 APISpec 结合在一起。
+
+它利用 Webargs 与 Marshmallow 的信息,通过 APISpec 自动生成 OpenAPI 模式。
+
+这是个很棒却被低估的工具;它理应比许多 Flask 插件更流行。或许是因为它的文档过于简洁与抽象。
+
+这解决了在 Python 文档字符串里书写 YAML(另一套语法)的问题。
+
+在构建 **FastAPI** 之前,Flask + Flask-apispec + Marshmallow + Webargs 的组合是我最喜欢的后端技术栈。
+
+使用它促成了若干 Flask 全栈脚手架的诞生。以下是我(以及若干外部团队)至今使用的主要技术栈:
+
+* [https://github.com/tiangolo/full-stack](https://github.com/tiangolo/full-stack)
+* [https://github.com/tiangolo/full-stack-flask-couchbase](https://github.com/tiangolo/full-stack-flask-couchbase)
+* [https://github.com/tiangolo/full-stack-flask-couchdb](https://github.com/tiangolo/full-stack-flask-couchdb)
+
+这些全栈脚手架也成为了[**FastAPI** 项目脚手架](project-generation.md)的基础。
+
+/// info | 信息
+
+Flask-apispec 由与 Marshmallow 相同的开发者创建。
+
+///
+
+/// check | 启发 **FastAPI**:
+
+从定义序列化与校验的同一份代码自动生成 OpenAPI 模式。
+
+///
+
+### [NestJS](https://nestjs.com/)(以及 [Angular](https://angular.io/)) { #nestjs-and-angular }
+
+这甚至不是 Python。NestJS 是一个 JavaScript(TypeScript)的 NodeJS 框架,受 Angular 启发。
+
+它实现了与 Flask-apispec 有些类似的效果。
+
+它集成了受 Angular 2 启发的依赖注入系统。与我所知的其他依赖注入系统一样,需要预先注册“可注入项”,因此会增加冗长与重复。
+
+由于参数用 TypeScript 类型描述(类似 Python 类型提示),编辑器支持相当好。
+
+但由于 TypeScript 的类型在编译为 JavaScript 后不会保留,无法只依赖这些类型同时定义校验、序列化与文档。受此以及一些设计决策影响,为了获得校验、序列化与自动 schema 生成,需要在许多位置添加装饰器,因此代码会相当冗长。
+
+它对嵌套模型的支持并不好。如果请求的 JSON 体是包含嵌套 JSON 对象的 JSON 对象,则无法被正确文档化和校验。
+
+/// check | 启发 **FastAPI**:
+
+使用 Python 类型以获得出色的编辑器支持。
+
+拥有强大的依赖注入系统,并设法尽量减少代码重复。
+
+///
+
+### [Sanic](https://sanic.readthedocs.io/en/latest/) { #sanic }
+
+它是最早的一批基于 `asyncio` 的极速 Python 框架之一,且做得与 Flask 很相似。
+
+/// note | 技术细节
+
+它使用了 [`uvloop`](https://github.com/MagicStack/uvloop) 来替代 Python 默认的 `asyncio` 循环。这正是它如此之快的原因。
+
+它显然启发了 Uvicorn 和 Starlette;在公开的基准测试中,它们目前比 Sanic 更快。
+
+///
+
+/// check | 启发 **FastAPI**:
+
+找到实现疯狂性能的路径。
+
+这就是 **FastAPI** 基于 Starlette 的原因,因为它是目前可用的最快框架(由第三方基准测试验证)。
+
+///
+
+### [Falcon](https://falconframework.org/) { #falcon }
+
+Falcon 是另一个高性能 Python 框架,它被设计为精简且可作为 Hug 等其他框架的基础。
+
+它设计为接收两个参数的函数:一个“request”和一个“response”。然后从 request 中“读取”,向 response 中“写入”。由于这种设计,无法用标准的 Python 类型提示将请求参数和请求体声明为函数形参。
+
+因此,数据校验、序列化与文档要么需要手写完成,无法自动化;要么需要在 Falcon 之上实现一个框架,例如 Hug。其他受 Falcon 设计启发、采用“一个 request 对象 + 一个 response 对象作为参数”的框架也有同样的区别。
+
+/// check | 启发 **FastAPI**:
+
+寻找获得卓越性能的方法。
+
+与 Hug(Hug 基于 Falcon)一起,启发 **FastAPI** 在函数中声明一个 `response` 参数。尽管在 FastAPI 中它是可选的,主要用于设置 headers、cookies 和可选的状态码。
+
+///
+
+### [Molten](https://moltenframework.com/) { #molten }
+
+我在构建 **FastAPI** 的早期阶段发现了 Molten。它有不少相似的想法:
+
+* 基于 Python 类型提示。
+* 从这些类型获得校验与文档。
+* 依赖注入系统。
+
+它没有使用像 Pydantic 这样的第三方数据校验、序列化与文档库,而是有自己的实现。因此这些数据类型定义不太容易在其他地方复用。
+
+它需要稍微冗长一些的配置。并且由于基于 WSGI(而非 ASGI),它并未设计为充分利用 Uvicorn、Starlette、Sanic 等工具所提供的高性能。
+
+其依赖注入系统需要预先注册依赖,且依赖根据声明的类型来解析。因此无法为同一类型声明多于一个“组件”。
+
+路由在一个地方集中声明,使用在其他地方声明的函数(而不是使用可以直接放在处理端点函数之上的装饰器)。这更接近 Django 的做法,而不是 Flask(和 Starlette)。它在代码中割裂了相对紧耦合的内容。
+
+/// check | 启发 **FastAPI**:
+
+通过模型属性的“默认值”为数据类型定义额外校验。这提升了编辑器支持,而这在当时的 Pydantic 中尚不可用。
+
+这实际上促成了对 Pydantic 的部分更新,以支持这种校验声明风格(这些功能现已在 Pydantic 中可用)。
+
+///
+
+### [Hug](https://github.com/hugapi/hug) { #hug }
+
+Hug 是最早使用 Python 类型提示来声明 API 参数类型的框架之一。这一绝妙想法也启发了其他工具。
+
+它在声明中使用自定义类型而不是标准的 Python 类型,但这依然是巨大的进步。
+
+它也是最早生成一个自定义 JSON 模式来声明整个 API 的框架之一。
+
+它并不基于 OpenAPI 与 JSON Schema 这类标准。因此与其他工具(如 Swagger UI)的集成并非一帆风顺。但它仍是非常有创新性的想法。
+
+它有一个有趣且少见的特性:使用同一框架,可以同时创建 API 与 CLI。
+
+由于基于同步 Python Web 框架的上一代标准(WSGI),它无法处理 WebSocket 等,尽管它的性能仍然很高。
+
+/// info | 信息
+
+Hug 由 Timothy Crosley 创建,他也是 [`isort`](https://github.com/timothycrosley/isort) 的作者,这是一个能自动排序 Python 文件中导入的优秀工具。
+
+///
+
+/// check | 启发 **FastAPI** 的想法:
+
+Hug 启发了 APIStar 的部分设计,也是我当时最看好的工具之一,与 APIStar 并列。
+
+Hug 促使 **FastAPI** 使用 Python 类型提示来声明参数,并自动生成定义整个 API 的模式。
+
+Hug 启发 **FastAPI** 在函数中声明 `response` 参数,用于设置 headers 与 cookies。
+
+///
+
+### [APIStar](https://github.com/encode/apistar) (<= 0.5) { #apistar-0-5 }
+
+就在决定动手构建 **FastAPI** 之前,我找到了 **APIStar** 服务器。它几乎具备我想要的一切,设计也很出色。
+
+在我见过的框架中,它是最早使用 Python 类型提示来声明参数和请求的实现之一(早于 NestJS 与 Molten)。我与 Hug 几乎同时发现了它。但 APIStar 使用了 OpenAPI 标准。
+
+它基于相同的类型提示,在多处自动进行数据校验、序列化并生成 OpenAPI 模式。
+
+请求体模式定义并未使用与 Pydantic 相同的 Python 类型提示,它更接近 Marshmallow,因此编辑器支持不如 Pydantic 好,但即便如此,APIStar 仍是当时可用的最佳选择。
+
+它在当时拥有最好的性能基准(仅被 Starlette 超越)。
+
+起初它没有自动 API 文档 Web 界面,但我知道我可以把 Swagger UI 加进去。
+
+它有一个依赖注入系统。与上文提到的其他工具一样,需要预先注册组件。但这依然是很棒的特性。
+
+我从未在完整项目中使用过它,因为它没有安全集成,因此我无法用它替代基于 Flask-apispec 的全栈脚手架所具备的全部功能。我曾把“提交一个增加该功能的 PR”放在了待办里。
+
+但随后,项目的重心发生了变化。
+
+它不再是一个 API Web 框架,因为作者需要专注于 Starlette。
+
+现在 APIStar 是一组用于校验 OpenAPI 规范的工具,而不是 Web 框架。
+
+/// info | 信息
+
+APIStar 由 Tom Christie 创建。他还创建了:
+
+* Django REST Framework
+* Starlette(**FastAPI** 基于其之上)
+* Uvicorn(被 Starlette 与 **FastAPI** 使用)
+
+///
+
+/// check | 启发 **FastAPI**:
+
+诞生。
+
+用同一套 Python 类型同时声明多件事(数据校验、序列化与文档),并且还能提供出色的编辑器支持——我认为这是个极其巧妙的想法。
+
+在长时间寻找与测试多种替代之后,APIStar 是当时最好的选择。
+
+随后 APIStar 不再作为服务器存在,而 Starlette 出现,成为实现该体系的更佳基础。这成为构建 **FastAPI** 的最终灵感来源。
+
+我把 **FastAPI** 视为 APIStar 的“精神续作”,并在此基础上,结合前述工具的经验,改进并增强了功能、类型系统及其他各方面。
+
+///
+
+## **FastAPI** 所使用的组件 { #used-by-fastapi }
+
+### [Pydantic](https://docs.pydantic.dev/) { #pydantic }
+
+Pydantic 是一个基于 Python 类型提示来定义数据校验、序列化与文档(使用 JSON Schema)的库。
+
+这使得它极其直观。
+
+它可与 Marshmallow 类比。尽管在基准测试中它比 Marshmallow 更快。并且由于同样基于 Python 类型提示,编辑器支持优秀。
+
+/// check | **FastAPI** 用它来:
+
+处理所有数据校验、数据序列化与自动模型文档(基于 JSON Schema)。
+
+随后 **FastAPI** 会把这些 JSON Schema 数据纳入 OpenAPI(以及完成其他所有工作)。
+
+///
+
+### [Starlette](https://www.starlette.dev/) { #starlette }
+
+Starlette 是一个轻量级的 ASGI 框架/工具集,非常适合构建高性能的 asyncio 服务。
+
+它非常简单直观。被设计为易于扩展,且具有模块化组件。
+
+它具备:
+
+* 性能极其出色。
+* 支持 WebSocket。
+* 进程内后台任务。
+* 启动与停止事件。
+* 基于 HTTPX 的测试客户端。
+* CORS、GZip、静态文件、流式响应。
+* 会话与 Cookie 支持。
+* 100% 测试覆盖率。
+* 100% 类型注解的代码库。
+* 极少的强依赖。
+
+Starlette 目前是测试中最快的 Python 框架。仅次于 Uvicorn,它不是框架,而是服务器。
+
+Starlette 提供了 Web 微框架的全部基础能力。
+
+但它不提供自动的数据校验、序列化或文档。
+
+这正是 **FastAPI** 在其之上增加的主要内容之一,全部基于 Python 类型提示(通过 Pydantic)。此外还有依赖注入系统、安全工具、OpenAPI 模式生成等。
+
+/// note | 技术细节
+
+ASGI 是由 Django 核心团队成员推动的新“标准”。它尚不是正式的“Python 标准”(PEP),尽管正朝此方向推进。
+
+尽管如此,已有多种工具将其作为“标准”使用。这极大提升了互操作性:你可以把 Uvicorn 换成其他 ASGI 服务器(如 Daphne 或 Hypercorn),或添加 ASGI 兼容的工具,如 `python-socketio`。
+
+///
+
+/// check | **FastAPI** 用它来:
+
+处理所有核心 Web 部分,并在其之上扩展功能。
+
+`FastAPI` 类本身直接继承自 `Starlette`。
+
+因此,凡是你能用 Starlette 完成的事,也能直接用 **FastAPI** 完成;可以把它看作“加速版”的 Starlette。
+
+///
+
+### [Uvicorn](https://www.uvicorn.dev/) { #uvicorn }
+
+Uvicorn 是一个基于 uvloop 与 httptools 构建的极速 ASGI 服务器。
+
+它不是 Web 框架,而是服务器。例如它不提供按路径路由的工具——这是 Starlette(或 **FastAPI**)这类框架在其之上提供的功能。
+
+它是 Starlette 与 **FastAPI** 推荐的服务器。
+
+/// check | **FastAPI** 推荐将其作为:
+
+运行 **FastAPI** 应用的主要 Web 服务器。
+
+你也可以使用 `--workers` 命令行选项以获得异步的多进程服务器。
+
+更多细节见[部署](deployment/index.md)一节。
+
+///
+
+## 基准与速度 { #benchmarks-and-speed }
+
+要理解、比较并查看 Uvicorn、Starlette 与 FastAPI 之间的差异,请查看[基准](benchmarks.md)一节。
diff --git a/docs/zh/docs/async.md b/docs/zh/docs/async.md
index 7cc76fc8644f1..92ee5ef22f534 100644
--- a/docs/zh/docs/async.md
+++ b/docs/zh/docs/async.md
@@ -1,10 +1,10 @@
-# 并发 async / await
+# 并发 async / await { #concurrency-and-async-await }
有关路径操作函数的 `async def` 语法以及异步代码、并发和并行的一些背景知识。
-## 赶时间吗?
+## 赶时间吗? { #in-a-hurry }
-TL;DR:
+TL;DR:
如果你正在使用第三方库,它们会告诉你使用 `await` 关键字来调用它们,就像这样:
@@ -21,8 +21,11 @@ async def read_results():
return results
```
-!!! note
- 你只能在被 `async def` 创建的函数内使用 `await`
+/// note | 注意
+
+你只能在被 `async def` 创建的函数内使用 `await`
+
+///
---
@@ -37,7 +40,7 @@ def results():
---
-如果你的应用程序不需要与其他任何东西通信而等待其响应,请使用 `async def`。
+如果你的应用程序不需要与其他任何东西通信而等待其响应,请使用 `async def`,即使函数内部不需要使用 `await`。
---
@@ -51,7 +54,7 @@ def results():
但是,通过遵循上述步骤,它将能够进行一些性能优化。
-## 技术细节
+## 技术细节 { #technical-details }
Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和 `await` 语法的东西来写**”异步代码“**。
@@ -61,7 +64,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
* **`async` 和 `await`**
* **协程**
-## 异步代码
+## 异步代码 { #asynchronous-code }
异步代码仅仅意味着编程语言 💬 有办法告诉计算机/程序 🤖 在代码中的某个点,它 🤖 将不得不等待在某些地方完成一些事情。让我们假设一些事情被称为 "慢文件"📝.
@@ -71,7 +74,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
接下来,它 🤖 完成第一个任务(比如是我们的"慢文件"📝) 并继续与之相关的一切。
-这个"等待其他事情"通常指的是一些相对较慢(与处理器和 RAM 存储器的速度相比)的 I/O 操作,比如说:
+这个"等待其他事情"通常指的是一些相对较慢(与处理器和 RAM 存储器的速度相比)的 I/O 操作,比如说:
* 通过网络发送来自客户端的数据
* 客户端接收来自网络中的数据
@@ -82,7 +85,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
* 一个数据库查询,直到返回结果
* 等等.
-这个执行的时间大多是在等待 I/O 操作,因此它们被叫做 "I/O 密集型" 操作。
+这个执行的时间大多是在等待 I/O 操作,因此它们被叫做 "I/O 密集型" 操作。
它被称为"异步"的原因是因为计算机/程序不必与慢任务"同步",去等待任务完成的确切时刻,而在此期间不做任何事情直到能够获取任务结果才继续工作。
@@ -90,7 +93,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
对于"同步"(与"异步"相反),他们通常也使用"顺序"一词,因为计算机程序在切换到另一个任务之前是按顺序执行所有步骤,即使这些步骤涉及到等待。
-### 并发与汉堡
+### 并发与汉堡 { #concurrency-and-burgers }
上述异步代码的思想有时也被称为“并发”,它不同于“并行”。
@@ -100,7 +103,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
要了解差异,请想象以下关于汉堡的故事:
-### 并发汉堡
+### 并发汉堡 { #concurrent-burgers }
你和你的恋人一起去快餐店,你排队在后面,收银员从你前面的人接单。😍
@@ -136,8 +139,11 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
-!!! info
- 漂亮的插画来自 Ketrina Thompson. 🎨
+/// info | 信息
+
+漂亮的插画来自 [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot)。🎨
+
+///
---
@@ -157,7 +163,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
然后你去柜台🔀, 到现在初始任务已经完成⏯, 拿起汉堡,说声谢谢,然后把它们送到桌上。这就完成了与计数器交互的步骤/任务⏹. 这反过来又产生了一项新任务,即"吃汉堡"🔀 ⏯, 上一个"拿汉堡"的任务已经结束了⏹.
-### 并行汉堡
+### 并行汉堡 { #parallel-burgers }
现在让我们假设不是"并发汉堡",而是"并行汉堡"。
@@ -199,8 +205,11 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
没有太多的交谈或调情,因为大部分时间 🕙 都在柜台前等待😞。
-!!! info
- 漂亮的插画来自 Ketrina Thompson. 🎨
+/// info | 信息
+
+漂亮的插画来自 [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot)。🎨
+
+///
---
@@ -224,7 +233,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
你可不会想带你的恋人 😍 和你一起去银行办事🏦.
-### 汉堡结论
+### 汉堡结论 { #burger-conclusion }
在"你与恋人一起吃汉堡"的这个场景中,因为有很多人在等待🕙, 使用并发系统更有意义⏸🔀⏯.
@@ -242,9 +251,9 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
这与 **FastAPI** 的性能水平相同。
-您可以同时拥有并行性和异步性,您可以获得比大多数经过测试的 NodeJS 框架更高的性能,并且与 Go 不相上下, Go 是一种更接近于 C 的编译语言(全部归功于 Starlette)。
+你可以同时拥有并行性和异步性,你可以获得比大多数经过测试的 NodeJS 框架更高的性能,并且与 Go 不相上下, Go 是一种更接近于 C 的编译语言([全部归功于 Starlette](https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=query&l=zijmkf-1))。
-### 并发比并行好吗?
+### 并发比并行好吗? { #is-concurrency-better-than-parallelism }
不!这不是故事的本意。
@@ -266,9 +275,9 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和
但在这种情况下,如果你能带上 8 名前收银员/厨师,现在是清洁工一起清扫,他们中的每一个人(加上你)都能占据房子的一个区域来清扫,你就可以在额外的帮助下并行的更快地完成所有工作。
-在这个场景中,每个清洁工(包括您)都将是一个处理器,完成这个工作的一部分。
+在这个场景中,每个清洁工(包括你)都将是一个处理器,完成这个工作的一部分。
-由于大多数执行时间是由实际工作(而不是等待)占用的,并且计算机中的工作是由 CPU 完成的,所以他们称这些问题为"CPU 密集型"。
+由于大多数执行时间是由实际工作(而不是等待)占用的,并且计算机中的工作是由 CPU 完成的,所以他们称这些问题为"CPU 密集型"。
---
@@ -281,21 +290,21 @@ CPU 密集型操作的常见示例是需要复杂的数学处理。
* **机器学习**: 它通常需要大量的"矩阵"和"向量"乘法。想象一个包含数字的巨大电子表格,并同时将所有数字相乘;
* **深度学习**: 这是机器学习的一个子领域,同样适用。只是没有一个数字的电子表格可以相乘,而是一个庞大的数字集合,在很多情况下,你需要使用一个特殊的处理器来构建和使用这些模型。
-### 并发 + 并行: Web + 机器学习
+### 并发 + 并行: Web + 机器学习 { #concurrency-parallelism-web-machine-learning }
-使用 **FastAPI**,您可以利用 Web 开发中常见的并发机制的优势(NodeJS 的主要吸引力)。
+使用 **FastAPI**,你可以利用 Web 开发中常见的并发机制的优势(NodeJS 的主要吸引力)。
-并且,您也可以利用并行和多进程(让多个进程并行运行)的优点来处理与机器学习系统中类似的 **CPU 密集型** 工作。
+并且,你也可以利用并行和多进程(让多个进程并行运行)的优点来处理与机器学习系统中类似的 **CPU 密集型** 工作。
这一点,再加上 Python 是**数据科学**、机器学习(尤其是深度学习)的主要语言这一简单事实,使得 **FastAPI** 与数据科学/机器学习 Web API 和应用程序(以及其他许多应用程序)非常匹配。
-了解如何在生产环境中实现这种并行性,可查看此文 [Deployment](deployment/index.md){.internal-link target=_blank}。
+了解如何在生产环境中实现这种并行性,可查看此文 [部署](deployment/index.md)。
-## `async` 和 `await`
+## `async` 和 `await` { #async-and-await }
现代版本的 Python 有一种非常直观的方式来定义异步代码。这使它看起来就像正常的"顺序"代码,并在适当的时候"等待"。
-当有一个操作需要等待才能给出结果,且支持这个新的 Python 特性时,您可以编写如下代码:
+当有一个操作需要等待才能给出结果,且支持这个新的 Python 特性时,你可以编写如下代码:
```Python
burgers = await get_burgers(2)
@@ -307,16 +316,16 @@ burgers = await get_burgers(2)
```Python hl_lines="1"
async def get_burgers(number: int):
- # Do some asynchronous stuff to create the burgers
+ # 执行一些异步操作来制作汉堡
return burgers
```
...而不是 `def`:
```Python hl_lines="2"
-# This is not asynchronous
+# 这不是异步的
def get_sequential_burgers(number: int):
- # Do some sequential stuff to create the burgers
+ # 执行一些顺序操作来制作汉堡
return burgers
```
@@ -325,13 +334,13 @@ def get_sequential_burgers(number: int):
当你想调用一个 `async def` 函数时,你必须"等待"它。因此,这不会起作用:
```Python
-# This won't work, because get_burgers was defined with: async def
+# 这样不行,因为 get_burgers 是用 async def 定义的
burgers = get_burgers(2)
```
---
-因此,如果您使用的库告诉您可以使用 `await` 调用它,则需要使用 `async def` 创建路径操作函数 ,如:
+因此,如果你使用的库告诉你可以使用 `await` 调用它,则需要使用 `async def` 创建路径操作函数 ,如:
```Python hl_lines="2-3"
@app.get('/burgers')
@@ -340,27 +349,29 @@ async def read_burgers():
return burgers
```
-### 更多技术细节
+### 更多技术细节 { #more-technical-details }
-您可能已经注意到,`await` 只能在 `async def` 定义的函数内部使用。
+你可能已经注意到,`await` 只能在 `async def` 定义的函数内部使用。
但与此同时,必须"等待"通过 `async def` 定义的函数。因此,带 `async def` 的函数也只能在 `async def` 定义的函数内部调用。
那么,这关于先有鸡还是先有蛋的问题,如何调用第一个 `async` 函数?
-如果您使用 **FastAPI**,你不必担心这一点,因为"第一个"函数将是你的路径操作函数,FastAPI 将知道如何做正确的事情。
+如果你使用 **FastAPI**,你不必担心这一点,因为"第一个"函数将是你的路径操作函数,FastAPI 将知道如何做正确的事情。
+
+但如果你想在没有 FastAPI 的情况下使用 `async` / `await`,则可以这样做。
-但如果您想在没有 FastAPI 的情况下使用 `async` / `await`,则可以这样做。
+### 编写自己的异步代码 { #write-your-own-async-code }
-### 编写自己的异步代码
+Starlette (和 **FastAPI**) 是基于 [AnyIO](https://anyio.readthedocs.io/en/stable/) 实现的,这使得它们可以兼容 Python 的标准库 [asyncio](https://docs.python.org/3/library/asyncio-task.html) 和 [Trio](https://trio.readthedocs.io/en/stable/)。
-Starlette (和 **FastAPI**) 是基于 AnyIO 实现的,这使得它们可以兼容 Python 的标准库 asyncio 和 Trio。
+特别是,你可以直接使用 [AnyIO](https://anyio.readthedocs.io/en/stable/) 来处理高级的并发用例,这些用例需要在自己的代码中使用更高级的模式。
-特别是,你可以直接使用 AnyIO 来处理高级的并发用例,这些用例需要在自己的代码中使用更高级的模式。
+即使你没有使用 **FastAPI**,你也可以使用 [AnyIO](https://anyio.readthedocs.io/en/stable/) 编写自己的异步程序,使其拥有较高的兼容性并获得一些好处(例如, 结构化并发)。
-即使您没有使用 **FastAPI**,您也可以使用 AnyIO 编写自己的异步程序,使其拥有较高的兼容性并获得一些好处(例如, 结构化并发)。
+我基于 AnyIO 新建了一个库,作为一个轻量级的封装层,用来优化类型注解,同时提供了更好的**自动补全**、**内联错误提示**等功能。这个库还附带了一个友好的入门指南和教程,能帮助你**理解**并编写**自己的异步代码**:[Asyncer](https://asyncer.tiangolo.com/)。如果你有**结合使用异步代码和常规**(阻塞/同步)代码的需求,这个库会特别有用。
-### 其他形式的异步代码
+### 其他形式的异步代码 { #other-forms-of-asynchronous-code }
这种使用 `async` 和 `await` 的风格在语言中相对较新。
@@ -370,17 +381,17 @@ Starlette (和 **FastAPI**) 是基于 Gevent。但代码的理解、调试和思考都要复杂许多。
+在以前版本的 Python,你可以使用多线程或者 [Gevent](https://www.gevent.org/)。但代码的理解、调试和思考都要复杂许多。
-在以前版本的 NodeJS / 浏览器 JavaScript 中,你会使用"回调",因此也可能导致回调地狱。
+在以前版本的 NodeJS / 浏览器 JavaScript 中,你会使用"回调",因此也可能导致“回调地狱”。
-## 协程
+## 协程 { #coroutines }
**协程**只是 `async def` 函数返回的一个非常奇特的东西的称呼。Python 知道它有点像一个函数,它可以启动,也会在某个时刻结束,而且它可能会在内部暂停 ⏸ ,只要内部有一个 `await`。
通过使用 `async` 和 `await` 的异步代码的所有功能大多数被概括为"协程"。它可以与 Go 的主要关键特性 "Goroutines" 相媲美。
-## 结论
+## 结论 { #conclusion }
让我们再来回顾下上文所说的:
@@ -390,36 +401,39 @@ Starlette (和 **FastAPI**) 是基于 I/O 的代码。
+如果你使用过另一个不以上述方式工作的异步框架,并且你习惯于用普通的 `def` 定义普通的仅计算路径操作函数,以获得微小的性能增益(大约100纳秒),请注意,在 FastAPI 中,效果将完全相反。在这些情况下,最好使用 `async def`,除非路径操作函数内使用执行阻塞 I/O 的代码。
-在这两种情况下,与您之前的框架相比,**FastAPI** 可能[仍然很快](/#performance){.internal-link target=_blank}。
+在这两种情况下,与你之前的框架相比,**FastAPI** 可能[仍然很快](index.md#performance)。
-### 依赖
+### 依赖 { #dependencies }
-这同样适用于[依赖](/tutorial/dependencies/index.md){.internal-link target=_blank}。如果一个依赖是标准的 `def` 函数而不是 `async def`,它将被运行在外部线程池中。
+这同样适用于[依赖](tutorial/dependencies/index.md)。如果一个依赖是标准的 `def` 函数而不是 `async def`,它将被运行在外部线程池中。
-### 子依赖
+### 子依赖 { #sub-dependencies }
-你可以拥有多个相互依赖的依赖以及[子依赖](/tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} (作为函数的参数),它们中的一些可能是通过 `async def` 声明,也可能是通过 `def` 声明。它们仍然可以正常工作,这些通过 `def` 声明的函数将会在外部线程中调用(来自线程池),而不是"被等待"。
+你可以拥有多个相互依赖的依赖以及[子依赖](tutorial/dependencies/sub-dependencies.md) (作为函数的参数),它们中的一些可能是通过 `async def` 声明,也可能是通过 `def` 声明。它们仍然可以正常工作,这些通过 `def` 声明的函数将会在外部线程中调用(来自线程池),而不是"被等待"。
-### 其他函数
+### 其他函数 { #other-utility-functions }
-您可直接调用通过 `def` 或 `async def` 创建的任何其他函数,FastAPI 不会影响您调用它们的方式。
+你可直接调用通过 `def` 或 `async def` 创建的任何其他函数,FastAPI 不会影响你调用它们的方式。
-这与 FastAPI 为您调用*路径操作函数*和依赖项的逻辑相反。
+这与 FastAPI 为你调用*路径操作函数*和依赖项的逻辑相反。
如果你的函数是通过 `def` 声明的,它将被直接调用(在代码中编写的地方),而不会在线程池中,如果这个函数通过 `async def` 声明,当在代码中调用时,你就应该使用 `await` 等待函数的结果。
@@ -427,4 +441,4 @@ Starlette (和 **FastAPI**) 是基于 赶时间吗?.
+否则,你最好应该遵守的指导原则赶时间吗?.
diff --git a/docs/zh/docs/benchmarks.md b/docs/zh/docs/benchmarks.md
index 71e8d483822ac..d98d3de593491 100644
--- a/docs/zh/docs/benchmarks.md
+++ b/docs/zh/docs/benchmarks.md
@@ -1,10 +1,10 @@
-# 基准测试
+# 基准测试 { #benchmarks }
-第三方机构 TechEmpower 的基准测试表明在 Uvicorn 下运行的 **FastAPI** 应用程序是 可用的最快的 Python 框架之一,仅次于 Starlette 和 Uvicorn 本身 (由 FastAPI 内部使用)。(*)
+第三方机构 TechEmpower 的基准测试表明在 Uvicorn 下运行的 **FastAPI** 应用程序是 [可用的最快的 Python 框架之一](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7),仅次于 Starlette 和 Uvicorn 本身(由 FastAPI 内部使用)。
但是在查看基准得分和对比时,请注意以下几点。
-## 基准测试和速度
+## 基准测试和速度 { #benchmarks-and-speed }
当你查看基准测试时,几个不同类型的工具被等效地做比较是很常见的情况。
@@ -20,15 +20,15 @@
* **Uvicorn**:
* 具有最佳性能,因为除了服务器本身外,它没有太多额外的代码。
- * 您不会直接在 Uvicorn 中编写应用程序。这意味着您的代码至少必须包含 Starlette(或 **FastAPI**)提供的代码。如果您这样做了(即直接在 Uvicorn 中编写应用程序),最终的应用程序会和使用了框架并且最小化了应用代码和 bug 的情况具有相同的性能损耗。
- * 如果要对比与 Uvicorn 对标的服务器,请将其与 Daphne,Hypercorn,uWSGI等应用服务器进行比较。
+ * 你不会直接在 Uvicorn 中编写应用程序。这意味着你的代码至少必须包含 Starlette(或 **FastAPI**)提供的代码。如果你这样做了(即直接在 Uvicorn 中编写应用程序),最终的应用程序会和使用了框架并且最小化了应用代码和 bug 的情况具有相同的性能损耗。
+ * 如果你要对比 Uvicorn,请将其与 Daphne,Hypercorn,uWSGI 等应用服务器进行比较。
* **Starlette**:
- * 在 Uvicorn 后使用 Starlette,性能会略有下降。实际上,Starlette 使用 Uvicorn运行。因此,由于必须执行更多的代码,它只会比 Uvicorn 更慢。
- * 但它为您提供了构建简单的网络程序的工具,并具有基于路径的路由等功能。
+ * 性能仅次于 Uvicorn。实际上,Starlette 使用 Uvicorn 运行。因此,由于必须执行更多的代码,它只会比 Uvicorn 更慢。
+ * 但它为你提供了构建简单的网络程序的工具,并具有基于路径的路由等功能。
* 如果想对比与 Starlette 对标的开发框架,请将其与 Sanic,Flask,Django 等网络框架(或微框架)进行比较。
* **FastAPI**:
* 与 Starlette 使用 Uvicorn 一样,由于 **FastAPI** 使用 Starlette,因此 FastAPI 不能比 Starlette 更快。
- * FastAPI 在 Starlette 基础上提供了更多功能。例如在开发 API 时,所需的数据验证和序列化功能。FastAPI 可以帮助您自动生成 API文档,(文档在应用程序启动时自动生成,所以不会增加应用程序运行时的开销)。
- * 如果您不使用 FastAPI 而直接使用 Starlette(或诸如 Sanic,Flask,Responder 等其它工具),您则要自己实现所有的数据验证和序列化。那么最终您的应用程序会和使用 FastAPI 构建的程序有相同的开销。一般这种数据验证和序列化的操作在您应用程序的代码中会占很大比重。
- * 因此,通过使用 FastAPI 意味着您可以节省开发时间,减少编码错误,用更少的编码实现其功能,并且相比不使用 FastAPI 您很大可能会获得相同或更好的性能(因为那样您必须在代码中实现所有相同的功能)。
- * 如果您想对比与 FastAPI 对标的开发框架,请与能够提供数据验证,序列化和带有自动文档生成的网络应用程序框架(或工具集)进行对比,例如具有集成自动数据验证,序列化和自动化文档的 Flask-apispec,NestJS,Molten 等。
+ * FastAPI 在 Starlette 基础上提供了更多功能。例如在开发 API 时,所需的数据验证和序列化功能。FastAPI 可以帮助你自动生成 API文档,(文档在应用程序启动时自动生成,所以不会增加应用程序运行时的开销)。
+ * 如果你不使用 FastAPI 而直接使用 Starlette(或诸如 Sanic,Flask,Responder 等其它工具),你则要自己实现所有的数据验证和序列化。那么最终你的应用程序会和使用 FastAPI 构建的程序有相同的开销。一般这种数据验证和序列化的操作在你应用程序的代码中会占很大比重。
+ * 因此,通过使用 FastAPI 意味着你可以节省开发时间,减少编码错误,用更少的编码实现其功能,并且相比不使用 FastAPI 你很大可能会获得相同或更好的性能(因为那样你必须在代码中实现所有相同的功能)。
+ * 如果你想对比 FastAPI,请与能够提供数据验证、序列化和文档的网络应用程序框架(或工具集)进行对比,例如具有集成自动数据验证、序列化和自动化文档的 Flask-apispec,NestJS,Molten 等。
diff --git a/docs/zh/docs/contributing.md b/docs/zh/docs/contributing.md
deleted file mode 100644
index 4ebd673150b25..0000000000000
--- a/docs/zh/docs/contributing.md
+++ /dev/null
@@ -1,468 +0,0 @@
-# 开发 - 贡献
-
-首先,你最好先了解 [帮助 FastAPI 及获取帮助](help-fastapi.md){.internal-link target=_blank}的基本方式。
-
-## 开发
-
-如果你已经克隆了源码仓库,并且需要深入研究代码,下面是设置开发环境的指南。
-
-### 通过 `venv` 管理虚拟环境
-
-你可以使用 Python 的 `venv` 模块在一个目录中创建虚拟环境:
-
-
+
+---
+
+现在我们知道了术语“进程”和“程序”之间的区别,让我们继续讨论部署。
+
+## 启动时运行 { #running-on-startup }
+
+在大多数情况下,当您创建 Web API 时,您希望它**始终运行**、不间断,以便您的客户端始终可以访问它。 这是当然的,除非您有特定原因希望它仅在某些情况下运行,但大多数时候您希望它不断运行并且**可用**。
+
+### 在远程服务器中 { #in-a-remote-server }
+
+当您设置远程服务器(云服务器、虚拟机等)时,您可以做的最简单的事情就是使用 `fastapi run`(它使用 Uvicorn)或类似方式,手动运行,就像本地开发时一样。
+
+它将会在**开发过程中**发挥作用并发挥作用。
+
+但是,如果您与服务器的连接丢失,**正在运行的进程**可能会终止。
+
+如果服务器重新启动(例如更新后或从云提供商迁移后),您可能**不会注意到它**。 因此,您甚至不知道必须手动重新启动该进程。 所以,你的 API 将一直处于挂掉的状态。 😱
+
+### 启动时自动运行 { #run-automatically-on-startup }
+
+一般来说,您可能希望服务器程序(例如 Uvicorn)在服务器启动时自动启动,并且不需要任何**人为干预**,让进程始终与您的 API 一起运行(例如 Uvicorn 运行您的 FastAPI 应用程序) 。
+
+### 单独的程序 { #separate-program }
+
+为了实现这一点,您通常会有一个**单独的程序**来确保您的应用程序在启动时运行。 在许多情况下,它还可以确保其他组件或应用程序也运行,例如数据库。
+
+### 启动时运行的示例工具 { #example-tools-to-run-at-startup }
+
+可以完成这项工作的工具的一些示例是:
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Docker in Swarm Mode
+* Systemd
+* Supervisor
+* 作为其服务的一部分由云提供商内部处理
+* 其他的...
+
+我将在接下来的章节中为您提供更具体的示例。
+
+## 重新启动 { #restarts }
+
+与确保应用程序在启动时运行类似,您可能还想确保它在挂掉后**重新启动**。
+
+### 我们会犯错误 { #we-make-mistakes }
+
+作为人类,我们总是会犯**错误**。 软件几乎*总是*在不同的地方隐藏着**bug**。 🐛
+
+作为开发人员,当我们发现这些bug并实现新功能(也可能添加新bug😅)时,我们会不断改进代码。
+
+### 自动处理小错误 { #small-errors-automatically-handled }
+
+使用 FastAPI 构建 Web API 时,如果我们的代码中存在错误,FastAPI 通常会将其包含到触发错误的单个请求中。 🛡
+
+对于该请求,客户端将收到 **500 内部服务器错误**,但应用程序将继续处理下一个请求,而不是完全崩溃。
+
+### 更大的错误 - 崩溃 { #bigger-errors-crashes }
+
+尽管如此,在某些情况下,我们编写的一些代码可能会导致整个应用程序崩溃,从而导致 Uvicorn 和 Python 崩溃。 💥
+
+尽管如此,您可能不希望应用程序因为某个地方出现错误而保持死机状态,您可能希望它**继续运行**,至少对于未破坏的*路径操作*。
+
+### 崩溃后重新启动 { #restart-after-crash }
+
+但在那些严重错误导致正在运行的**进程**崩溃的情况下,您需要一个外部组件来负责**重新启动**进程,至少尝试几次...
+
+/// tip | 提示
+
+...尽管如果整个应用程序只是**立即崩溃**,那么永远重新启动它可能没有意义。 但在这些情况下,您可能会在开发过程中注意到它,或者至少在部署后立即注意到它。
+
+因此,让我们关注主要情况,在**未来**的某些特定情况下,它可能会完全崩溃,但重新启动它仍然有意义。
+
+///
+
+您可能希望让这个东西作为 **外部组件** 负责重新启动您的应用程序,因为到那时,使用 Uvicorn 和 Python 的同一应用程序已经崩溃了,因此同一应用程序的相同代码中没有东西可以对此做出什么。
+
+### 自动重新启动的示例工具 { #example-tools-to-restart-automatically }
+
+在大多数情况下,用于**启动时运行程序**的同一工具也用于处理自动**重新启动**。
+
+例如,可以通过以下方式处理:
+
+* Docker
+* Kubernetes
+* Docker Compose
+* Docker in Swarm Mode
+* Systemd
+* Supervisor
+* 作为其服务的一部分由云提供商内部处理
+* 其他的...
+
+## 复制 - 进程和内存 { #replication-processes-and-memory }
+
+对于 FastAPI 应用程序,使用像 `fastapi` 命令(运行 Uvicorn)这样的服务器程序,在**一个进程**中运行一次就可以同时为多个客户端提供服务。
+
+但在许多情况下,您会希望同时运行多个工作进程。
+
+### 多进程 - Workers { #multiple-processes-workers }
+
+如果您的客户端数量多于单个进程可以处理的数量(例如,如果虚拟机不是太大),并且服务器的 CPU 中有 **多个核心**,那么您可以让 **多个进程** 同时运行同一个应用程序,并在它们之间分发所有请求。
+
+当您运行同一 API 程序的**多个进程**时,它们通常称为 **workers**。
+
+### 工作进程和端口 { #worker-processes-and-ports }
+
+还记得文档 [关于 HTTPS](https.md) 中只有一个进程可以侦听服务器中的端口和 IP 地址的一种组合吗?
+
+现在仍然是对的。
+
+因此,为了能够同时拥有**多个进程**,必须有一个**单个进程侦听端口**,然后以某种方式将通信传输到每个工作进程。
+
+### 每个进程的内存 { #memory-per-process }
+
+现在,当程序将内容加载到内存中时,例如,将机器学习模型加载到变量中,或者将大文件的内容加载到变量中,所有这些都会消耗服务器的一点内存 (RAM) 。
+
+多个进程通常**不共享任何内存**。 这意味着每个正在运行的进程都有自己的东西、变量和内存。 如果您的代码消耗了大量内存,**每个进程**将消耗等量的内存。
+
+### 服务器内存 { #server-memory }
+
+例如,如果您的代码加载 **1 GB 大小**的机器学习模型,则当您使用 API 运行一个进程时,它将至少消耗 1 GB RAM。 如果您启动 **4 个进程**(4 个工作进程),每个进程将消耗 1 GB RAM。 因此,您的 API 总共将消耗 **4 GB RAM**。
+
+如果您的远程服务器或虚拟机只有 3 GB RAM,尝试加载超过 4 GB RAM 将导致问题。 🚨
+
+### 多进程 - 一个例子 { #multiple-processes-an-example }
+
+在此示例中,有一个 **Manager Process** 启动并控制两个 **Worker Processes**。
+
+该管理器进程可能是监听 IP 中的 **端口** 的进程。 它将所有通信传输到工作进程。
+
+这些工作进程将是运行您的应用程序的进程,它们将执行主要计算以接收 **请求** 并返回 **响应**,并且它们将加载您放入 RAM 中的变量中的任何内容。
+
++没有大家之前所做的工作,**FastAPI** 就不会存在。 + +以前创建的这些工具为它的出现提供了灵感。 + +在那几年中,我一直回避创建新的框架。首先,我尝试使用各种框架、插件、工具解决 **FastAPI** 现在的功能。 + +但到了一定程度之后,我别无选择,只能从之前的工具中汲取最优思路,并以尽量好的方式把这些思路整合在一起,使用之前甚至是不支持的语言特性(Python 3.6+ 的类型提示),从而创建一个能满足我所有需求的框架。 ++ +## 调研 { #investigation } + +通过使用之前所有的备选方案,我有机会从它们之中学到了很多东西,获取了很多想法,并以我和我的开发团队能想到的最好方式把这些思路整合成一体。 + +例如,大家都清楚,在理想状态下,它应该基于标准的 Python 类型提示。 + +而且,最好的方式是使用现有的标准。 + +因此,甚至在开发 **FastAPI** 前,我就花了几个月的时间研究 OpenAPI、JSON Schema、OAuth2 等规范。深入理解它们之间的关系、重叠及区别之处。 + +## 设计 { #design } + +然后,我又花了一些时间从用户角度(使用 FastAPI 的开发者)设计了开发者 **API**。 + +同时,我还在最流行的 Python 代码编辑器中测试了很多思路,包括 PyCharm、VS Code、基于 Jedi 的编辑器。 + +根据最新 [Python 开发者调研报告](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools)显示,这几种编辑器覆盖了约 80% 的用户。 + +也就是说,**FastAPI** 针对差不多 80% 的 Python 开发者使用的编辑器进行了测试,而且其它大多数编辑器的工作方式也与之类似,因此,**FastAPI** 的优势几乎能在所有编辑器上体现。 + +通过这种方式,我就能找到尽可能减少代码重复的最佳方式,进而实现处处都有自动补全、类型提示与错误检查等支持。 + +所有这些都是为了给开发者提供最佳的开发体验。 + +## 需求项 { #requirements } + +经过测试多种备选方案,我最终决定使用 [**Pydantic**](https://docs.pydantic.dev/),并充分利用它的优势。 + +我甚至为它做了不少贡献,让它完美兼容了 JSON Schema,支持多种方式定义约束声明,并基于多个编辑器,改进了它对编辑器支持(类型检查、自动补全)。 + +在开发期间,我还为 [**Starlette**](https://www.starlette.dev/) 做了不少贡献,这是另一个关键需求项。 + +## 开发 { #development } + +当我启动 **FastAPI** 开发的时候,绝大多数部件都已经就位,设计已经定义,需求项和工具也已经准备就绪,相关标准与规范的知识储备也非常清晰而新鲜。 + +## 未来 { #future } + +至此,**FastAPI** 及其理念已经为很多人所用。 + +对于很多用例,它比以前很多备选方案都更适用。 + +很多开发者和开发团队已经依赖 **FastAPI** 开发他们的项目(包括我和我的团队)。 + +但,**FastAPI** 仍有很多改进的余地,也还需要添加更多的功能。 + +**FastAPI** 前景光明。 + +在此,我们衷心感谢[你的帮助](help-fastapi.md)。 diff --git a/docs/zh/docs/how-to/authentication-error-status-code.md b/docs/zh/docs/how-to/authentication-error-status-code.md new file mode 100644 index 0000000000000..6f8c0a67cd047 --- /dev/null +++ b/docs/zh/docs/how-to/authentication-error-status-code.md @@ -0,0 +1,17 @@ +# 使用旧的 403 认证错误状态码 { #use-old-403-authentication-error-status-codes } + +在 FastAPI `0.122.0` 版本之前,当内置的安全工具在认证失败后向客户端返回错误时,会使用 HTTP 状态码 `403 Forbidden`。 + +从 FastAPI `0.122.0` 版本开始,它们改用更合适的 HTTP 状态码 `401 Unauthorized`,并在响应中返回合理的 `WWW-Authenticate` 头,遵循 HTTP 规范,[RFC 7235](https://datatracker.ietf.org/doc/html/rfc7235#section-3.1)、[RFC 9110](https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized)。 + +但如果由于某些原因你的客户端依赖旧行为,你可以在你的安全类中重写方法 `make_not_authenticated_error` 来回退到旧行为。 + +例如,你可以创建一个 `HTTPBearer` 的子类,使其返回 `403 Forbidden` 错误,而不是默认的 `401 Unauthorized` 错误: + +{* ../../docs_src/authentication_error_status_code/tutorial001_an_py310.py hl[9:13] *} + +/// tip | 提示 + +注意该函数返回的是异常实例,而不是直接抛出它。抛出操作由其余的内部代码完成。 + +/// diff --git a/docs/zh/docs/how-to/conditional-openapi.md b/docs/zh/docs/how-to/conditional-openapi.md new file mode 100644 index 0000000000000..b0c5d521c11cd --- /dev/null +++ b/docs/zh/docs/how-to/conditional-openapi.md @@ -0,0 +1,56 @@ +# 按条件配置 OpenAPI { #conditional-openapi } + +如果需要,你可以使用设置和环境变量,按环境有条件地配置 OpenAPI,甚至完全禁用它。 + +## 关于安全、API 和文档 { #about-security-apis-and-docs } + +在生产环境隐藏文档界面并不应该成为保护 API 的方式。 + +这并不会给你的 API 增加任何额外的安全性,*路径操作* 仍然会在原来的位置可用。 + +如果你的代码里有安全漏洞,它仍然存在。 + +隐藏文档只会让理解如何与 API 交互变得更困难,也可能让你在生产环境中调试更困难。这大体上可以被视为一种 [通过隐藏实现安全](https://en.wikipedia.org/wiki/Security_through_obscurity) 的做法。 + +如果你想保护你的 API,有很多更好的措施,例如: + +- 确保为请求体和响应定义完善的 Pydantic 模型。 +- 使用依赖配置所需的权限和角色。 +- 绝不要存储明文密码,只存储密码哈希。 +- 实现并使用成熟的密码学工具,比如 pwdlib 和 JWT 令牌等。 +- 在需要的地方使用 OAuth2 作用域添加更细粒度的权限控制。 +- ...等。 + +尽管如此,你可能确实有非常特定的用例,需要在某些环境(例如生产环境)禁用 API 文档,或根据环境变量的配置来决定。 + +## 基于设置和环境变量的条件式 OpenAPI { #conditional-openapi-from-settings-and-env-vars } + +你可以很容易地使用相同的 Pydantic 设置来配置生成的 OpenAPI 和文档 UI。 + +例如: + +{* ../../docs_src/conditional_openapi/tutorial001_py310.py hl[6,11] *} + +这里我们声明了设置项 `openapi_url`,其默认值同样是 `"/openapi.json"`。 + +然后在创建 `FastAPI` 应用时使用它。 + +接着,你可以通过把环境变量 `OPENAPI_URL` 设为空字符串来禁用 OpenAPI(包括文档 UI),例如: + +
+
+但是你可以通过设置 `syntaxHighlight` 为 `False` 来禁用 Swagger UI 中的语法高亮:
+
+{* ../../docs_src/configure_swagger_ui/tutorial001_py310.py hl[3] *}
+
+...在此之后,Swagger UI 将不会高亮代码:
+
+
+
+## 改变主题 { #change-the-theme }
+
+同样地,你也可以通过设置键 `"syntaxHighlight.theme"` 来设置语法高亮主题(注意中间有一个点):
+
+{* ../../docs_src/configure_swagger_ui/tutorial002_py310.py hl[3] *}
+
+这个配置会改变语法高亮主题:
+
+
+
+## 改变默认 Swagger UI 参数 { #change-default-swagger-ui-parameters }
+
+FastAPI 包含了一些默认配置参数,适用于大多数用例。
+
+其包括这些默认配置参数:
+
+{* ../../fastapi/openapi/docs.py ln[9:24] hl[18:24] *}
+
+你可以通过在 `swagger_ui_parameters` 中设置不同的值来覆盖它们。
+
+比如,如果要禁用 `deepLinking`,你可以像这样传递设置到 `swagger_ui_parameters` 中:
+
+{* ../../docs_src/configure_swagger_ui/tutorial003_py310.py hl[3] *}
+
+## 其他 Swagger UI 参数 { #other-swagger-ui-parameters }
+
+查看所有其他可用的配置,请阅读官方的 [Swagger UI 参数文档](https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/)。
+
+## JavaScript-only 配置 { #javascript-only-settings }
+
+Swagger UI 同样允许使用 **JavaScript-only** 配置对象(例如,JavaScript 函数)。
+
+FastAPI 包含这些 JavaScript-only 的 `presets` 设置:
+
+```JavaScript
+presets: [
+ SwaggerUIBundle.presets.apis,
+ SwaggerUIBundle.SwaggerUIStandalonePreset
+]
+```
+
+这些是 **JavaScript** 对象,而不是字符串,所以你不能直接从 Python 代码中传递它们。
+
+如果你需要像这样使用 JavaScript-only 配置,你可以使用上述方法之一。覆盖所有 Swagger UI *路径操作* 并手动编写任何你需要的 JavaScript。
diff --git a/docs/zh/docs/how-to/custom-docs-ui-assets.md b/docs/zh/docs/how-to/custom-docs-ui-assets.md
new file mode 100644
index 0000000000000..47b27b69cab0f
--- /dev/null
+++ b/docs/zh/docs/how-to/custom-docs-ui-assets.md
@@ -0,0 +1,185 @@
+# 自托管自定义文档 UI 静态资源 { #custom-docs-ui-static-assets-self-hosting }
+
+API 文档使用 Swagger UI 和 ReDoc,它们各自需要一些 JavaScript 和 CSS 文件。
+
+默认情况下,这些文件从一个 CDN 提供。
+
+不过你可以自定义:可以指定特定的 CDN,或自行提供这些文件。
+
+## 为 JavaScript 和 CSS 自定义 CDN { #custom-cdn-for-javascript-and-css }
+
+假设你想使用不同的 CDN,例如使用 `https://unpkg.com/`。
+
+如果你所在的国家/地区屏蔽了某些 URL,这会很有用。
+
+### 关闭自动文档 { #disable-the-automatic-docs }
+
+第一步是关闭自动文档,因为默认它们会使用默认的 CDN。
+
+要关闭它们,在创建 `FastAPI` 应用时将其 URL 设为 `None`:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[8] *}
+
+### 包含自定义文档 { #include-the-custom-docs }
+
+现在你可以为自定义文档创建*路径操作*。
+
+你可以复用 FastAPI 的内部函数来创建文档的 HTML 页面,并传入所需参数:
+
+- `openapi_url`:文档 HTML 页面获取你的 API 的 OpenAPI 模式的 URL。这里可以使用 `app.openapi_url` 属性。
+- `title`:你的 API 标题。
+- `oauth2_redirect_url`:这里可以使用 `app.swagger_ui_oauth2_redirect_url` 来使用默认值。
+- `swagger_js_url`:你的 Swagger UI 文档 HTML 获取**JavaScript** 文件的 URL。这里是自定义的 CDN URL。
+- `swagger_css_url`:你的 Swagger UI 文档 HTML 获取**CSS** 文件的 URL。这里是自定义的 CDN URL。
+
+ReDoc 也类似...
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[2:6,11:19,22:24,27:33] *}
+
+/// tip | 提示
+
+`swagger_ui_redirect` 的*路径操作*是在你使用 OAuth2 时的一个辅助。
+
+如果你把 API 与某个 OAuth2 提供方集成,你就可以完成认证并带着获取到的凭据回到 API 文档里。然后使用真实的 OAuth2 认证与之交互。
+
+Swagger UI 会在幕后为你处理这些,但它需要这个“重定向”辅助路径。
+
+///
+
+### 创建一个路径操作进行测试 { #create-a-path-operation-to-test-it }
+
+现在,为了测试一切是否正常,创建一个*路径操作*:
+
+{* ../../docs_src/custom_docs_ui/tutorial001_py310.py hl[36:38] *}
+
+### 测试 { #test-it }
+
+现在,你应该可以访问 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs),并刷新页面,页面会从新的 CDN 加载这些资源。
+
+## 为文档自托管 JavaScript 和 CSS { #self-hosting-javascript-and-css-for-docs }
+
+如果你需要在离线、无法访问互联网或仅在局域网内时,应用仍能工作,那么自托管 JavaScript 和 CSS 会很有用。
+
+这里你将看到如何在同一个 FastAPI 应用中自行提供这些文件,并配置文档使用它们。
+
+### 项目文件结构 { #project-file-structure }
+
+假设你的项目文件结构如下:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+```
+
+现在创建一个目录来存放这些静态文件。
+
+你的新文件结构可能如下:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static/
+```
+
+### 下载文件 { #download-the-files }
+
+下载文档需要的静态文件,并将它们放到 `static/` 目录中。
+
+你通常可以右键点击每个链接,选择类似“将链接另存为...”的选项。
+
+Swagger UI 使用以下文件:
+
+- [`swagger-ui-bundle.js`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js)
+- [`swagger-ui.css`](https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css)
+
+而 ReDoc 使用以下文件:
+
+- [`redoc.standalone.js`](https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js)
+
+之后,你的文件结构可能如下:
+
+```
+.
+├── app
+│ ├── __init__.py
+│ ├── main.py
+└── static
+ ├── redoc.standalone.js
+ ├── swagger-ui-bundle.js
+ └── swagger-ui.css
+```
+
+### 提供静态文件 { #serve-the-static-files }
+
+- 导入 `StaticFiles`。
+- 在特定路径上“挂载”一个 `StaticFiles()` 实例。
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[7,11] *}
+
+### 测试静态文件 { #test-the-static-files }
+
+启动你的应用,并访问 [http://127.0.0.1:8000/static/redoc.standalone.js](http://127.0.0.1:8000/static/redoc.standalone.js)。
+
+你应该会看到一个非常长的 **ReDoc** 的 JavaScript 文件。
+
+它可能以如下内容开头:
+
+```JavaScript
+/*! For license information please see redoc.standalone.js.LICENSE.txt */
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")):
+...
+```
+
+这就确认了你的应用能够提供静态文件,并且你把文档所需的静态文件放在了正确的位置。
+
+现在我们可以配置应用,让文档使用这些静态文件。
+
+### 为静态文件关闭自动文档 { #disable-the-automatic-docs-for-static-files }
+
+和使用自定义 CDN 一样,第一步是关闭自动文档,因为默认情况下它们会使用 CDN。
+
+要关闭它们,在创建 `FastAPI` 应用时将其 URL 设为 `None`:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[9] *}
+
+### 为静态文件包含自定义文档 { #include-the-custom-docs-for-static-files }
+
+同样地,现在你可以为自定义文档创建*路径操作*。
+
+你可以再次复用 FastAPI 的内部函数来创建文档的 HTML 页面,并传入所需参数:
+
+- `openapi_url`:文档 HTML 页面获取你的 API 的 OpenAPI 模式的 URL。这里可以使用 `app.openapi_url` 属性。
+- `title`:你的 API 标题。
+- `oauth2_redirect_url`:这里可以使用 `app.swagger_ui_oauth2_redirect_url` 来使用默认值。
+- `swagger_js_url`:你的 Swagger UI 文档 HTML 获取**JavaScript** 文件的 URL。**这是现在由你的应用自己提供的那个**。
+- `swagger_css_url`:你的 Swagger UI 文档 HTML 获取**CSS** 文件的 URL。**这是现在由你的应用自己提供的那个**。
+
+ReDoc 也类似...
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[2:6,14:22,25:27,30:36] *}
+
+/// tip | 提示
+
+`swagger_ui_redirect` 的*路径操作*是在你使用 OAuth2 时的一个辅助。
+
+如果你把 API 与某个 OAuth2 提供方集成,你就可以完成认证并带着获取到的凭据回到 API 文档里。然后使用真实的 OAuth2 认证与之交互。
+
+Swagger UI 会在幕后为你处理这些,但它需要这个“重定向”辅助路径。
+
+///
+
+### 创建一个路径操作测试静态文件 { #create-a-path-operation-to-test-static-files }
+
+现在,为了测试一切是否正常,创建一个*路径操作*:
+
+{* ../../docs_src/custom_docs_ui/tutorial002_py310.py hl[39:41] *}
+
+### 测试静态文件 UI { #test-static-files-ui }
+
+现在,你可以断开 WiFi,访问 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs),并刷新页面。
+
+即使没有互联网,你也能看到 API 的文档并与之交互。
diff --git a/docs/zh/docs/how-to/custom-request-and-route.md b/docs/zh/docs/how-to/custom-request-and-route.md
new file mode 100644
index 0000000000000..79860a56238a1
--- /dev/null
+++ b/docs/zh/docs/how-to/custom-request-and-route.md
@@ -0,0 +1,109 @@
+# 自定义 Request 和 APIRoute 类 { #custom-request-and-apiroute-class }
+
+在某些情况下,你可能想要重写 `Request` 和 `APIRoute` 类使用的逻辑。
+
+尤其是,当你本来会把这些逻辑放到中间件里时,这是一个不错的替代方案。
+
+例如,如果你想在应用处理之前读取或操作请求体。
+
+/// danger | 危险
+
+这是一个“高级”特性。
+
+如果你刚开始使用 **FastAPI**,可以先跳过本节。
+
+///
+
+## 使用场景 { #use-cases }
+
+一些使用场景包括:
+
+* 将非 JSON 的请求体转换为 JSON(例如 [`msgpack`](https://msgpack.org/index.html))。
+* 解压缩使用 gzip 压缩的请求体。
+* 自动记录所有请求体日志。
+
+## 处理自定义请求体编码 { #handling-custom-request-body-encodings }
+
+来看如何用自定义的 `Request` 子类来解压 gzip 请求。
+
+以及一个 `APIRoute` 子类来使用该自定义请求类。
+
+### 创建自定义 `GzipRequest` 类 { #create-a-custom-gziprequest-class }
+
+/// tip | 提示
+
+这是一个演示工作原理的示例。如果你需要 Gzip 支持,可以直接使用提供的 [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware)。
+
+///
+
+首先,我们创建一个 `GzipRequest` 类,它会重写 `Request.body()` 方法:当请求头中存在相应标记时对请求体进行解压。
+
+如果请求头中没有 `gzip`,则不会尝试解压。
+
+这样,同一个路由类即可同时处理 gzip 压缩和未压缩的请求。
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[9:16] *}
+
+### 创建自定义 `GzipRoute` 类 { #create-a-custom-gziproute-class }
+
+接着,我们创建 `fastapi.routing.APIRoute` 的自定义子类来使用 `GzipRequest`。
+
+这次,我们会重写 `APIRoute.get_route_handler()` 方法。
+
+该方法返回一个函数,这个函数负责接收请求并返回响应。
+
+这里我们用它把原始请求包装为 `GzipRequest`。
+
+{* ../../docs_src/custom_request_and_route/tutorial001_an_py310.py hl[19:27] *}
+
+/// note | 技术细节
+
+`Request` 拥有 `request.scope` 属性,它就是一个 Python `dict`,包含与请求相关的元数据。
+
+`Request` 还包含 `request.receive`,它是一个用于“接收”请求体的函数。
+
+`scope` 字典和 `receive` 函数都是 ASGI 规范的一部分。
+
+创建一个新的 `Request` 实例需要这两样:`scope` 和 `receive`。
+
+想了解更多关于 `Request` 的信息,请查看 [Starlette 的 Request 文档](https://www.starlette.dev/requests/)。
+
+///
+
+由 `GzipRequest.get_route_handler` 返回的函数唯一不同之处是把 `Request` 转换为 `GzipRequest`。
+
+这样,在传给我们的路径操作之前,`GzipRequest` 会(在需要时)负责解压数据。
+
+之后,其余处理逻辑完全相同。
+
+但由于我们修改了 `GzipRequest.body`,在 **FastAPI** 需要读取时,请求体会被自动解压。
+
+## 在异常处理器中访问请求体 { #accessing-the-request-body-in-an-exception-handler }
+
+/// tip | 提示
+
+要解决类似问题,使用 `RequestValidationError` 的自定义处理器中的 `body` 往往更简单([处理错误](../tutorial/handling-errors.md#use-the-requestvalidationerror-body))。
+
+但本示例同样有效,并展示了如何与内部组件交互。
+
+///
+
+我们也可以用相同的方法在异常处理器中访问请求体。
+
+所需仅是在 `try`/`except` 块中处理请求:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[14,16] *}
+
+如果发生异常,`Request` 实例仍在作用域内,因此我们可以在处理错误时读取并使用请求体:
+
+{* ../../docs_src/custom_request_and_route/tutorial002_an_py310.py hl[17:19] *}
+
+## 在路由器中自定义 `APIRoute` 类 { #custom-apiroute-class-in-a-router }
+
+你也可以设置 `APIRouter` 的 `route_class` 参数:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[26] *}
+
+在此示例中,`router` 下的路径操作将使用自定义的 `TimedRoute` 类,响应中会多一个 `X-Response-Time` 头,包含生成响应所用的时间:
+
+{* ../../docs_src/custom_request_and_route/tutorial003_py310.py hl[13:20] *}
diff --git a/docs/zh/docs/how-to/extending-openapi.md b/docs/zh/docs/how-to/extending-openapi.md
new file mode 100644
index 0000000000000..fd39e439fadf6
--- /dev/null
+++ b/docs/zh/docs/how-to/extending-openapi.md
@@ -0,0 +1,80 @@
+# 扩展 OpenAPI { #extending-openapi }
+
+在某些情况下,你可能需要修改生成的 OpenAPI 架构(schema)。
+
+本节将介绍如何实现。
+
+## 常规流程 { #the-normal-process }
+
+常规(默认)流程如下。
+
+`FastAPI` 应用(实例)有一个 `.openapi()` 方法,预期返回 OpenAPI 架构。
+
+在创建应用对象时,会注册一个用于 `/openapi.json`(或你在 `openapi_url` 中设置的路径)的路径操作。
+
+它只会返回一个 JSON 响应,内容是应用 `.openapi()` 方法的结果。
+
+默认情况下,`.openapi()` 方法会检查属性 `.openapi_schema` 是否已有内容,若有则直接返回。
+
+如果没有,则使用 `fastapi.openapi.utils.get_openapi` 工具函数生成。
+
+该 `get_openapi()` 函数接收以下参数:
+
+- `title`:OpenAPI 标题,显示在文档中。
+- `version`:你的 API 版本,例如 `2.5.0`。
+- `openapi_version`:使用的 OpenAPI 规范版本。默认是最新的 `3.1.0`。
+- `summary`:API 的简短摘要。
+- `description`:API 的描述,可包含 Markdown,并会展示在文档中。
+- `routes`:路由列表,即已注册的每个路径操作。来自 `app.routes`。
+
+/// info | 信息
+
+参数 `summary` 仅在 OpenAPI 3.1.0 及更高版本中可用,FastAPI 0.99.0 及以上版本支持。
+
+///
+
+## 覆盖默认值 { #overriding-the-defaults }
+
+基于以上信息,你可以用同一个工具函数生成 OpenAPI 架构,并按需覆盖其中的各个部分。
+
+例如,让我们添加 [ReDoc 的 OpenAPI 扩展以包含自定义 Logo](https://github.com/Rebilly/ReDoc/blob/master/docs/redoc-vendor-extensions.md#x-logo)。
+
+### 常规 **FastAPI** { #normal-fastapi }
+
+首先,像平常一样编写你的 **FastAPI** 应用:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[1,4,7:9] *}
+
+### 生成 OpenAPI 架构 { #generate-the-openapi-schema }
+
+然后,在一个 `custom_openapi()` 函数中使用同一个工具函数生成 OpenAPI 架构:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[2,15:21] *}
+
+### 修改 OpenAPI 架构 { #modify-the-openapi-schema }
+
+现在你可以添加 ReDoc 扩展,在 OpenAPI 架构的 `info` “对象”中加入自定义 `x-logo`:
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[22:24] *}
+
+### 缓存 OpenAPI 架构 { #cache-the-openapi-schema }
+
+你可以把 `.openapi_schema` 属性当作“缓存”,用来存储已生成的架构。
+
+这样一来,用户每次打开 API 文档时,应用就不必重新生成架构。
+
+它只会生成一次,后续请求都会使用同一份缓存的架构。
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[13:14,25:26] *}
+
+### 覆盖方法 { #override-the-method }
+
+现在你可以用你的新函数替换 `.openapi()` 方法。
+
+{* ../../docs_src/extending_openapi/tutorial001_py310.py hl[29] *}
+
+### 验证 { #check-it }
+
+当你访问 [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) 时,你会看到已使用你的自定义 Logo(本例中为 **FastAPI** 的 Logo):
+
+
diff --git a/docs/zh/docs/how-to/general.md b/docs/zh/docs/how-to/general.md
new file mode 100644
index 0000000000000..1526ca1872229
--- /dev/null
+++ b/docs/zh/docs/how-to/general.md
@@ -0,0 +1,43 @@
+# 通用 - 如何操作 - 诀窍 { #general-how-to-recipes }
+
+这里是一些指向文档中其他部分的链接,用于解答一般性或常见问题。
+
+## 数据过滤 - 安全性 { #filter-data-security }
+
+为确保不返回超过需要的数据,请阅读 [教程 - 响应模型 - 返回类型](../tutorial/response-model.md) 文档。
+
+## 优化响应性能 - 响应模型 - 返回类型 { #optimize-response-performance-response-model-return-type }
+
+在返回 JSON 数据时优化性能,请使用返回类型或响应模型,这样 Pydantic 会在 Rust 侧处理到 JSON 的序列化,而无需经过 Python。更多内容请阅读 [教程 - 响应模型 - 返回类型](../tutorial/response-model.md) 文档。
+
+## 文档的标签 - OpenAPI { #documentation-tags-openapi }
+
+在文档界面中添加**路径操作**的标签和进行分组,请阅读 [教程 - 路径操作配置 - Tags](../tutorial/path-operation-configuration.md#tags) 文档。
+
+## 文档的概要和描述 - OpenAPI { #documentation-summary-and-description-openapi }
+
+在文档界面中添加**路径操作**的概要和描述,请阅读 [教程 - 路径操作配置 - Summary 和 Description](../tutorial/path-operation-configuration.md#summary-and-description) 文档。
+
+## 文档的响应描述 - OpenAPI { #documentation-response-description-openapi }
+
+在文档界面中定义并显示响应描述,请阅读 [教程 - 路径操作配置 - 响应描述](../tutorial/path-operation-configuration.md#response-description) 文档。
+
+## 文档弃用**路径操作** - OpenAPI { #documentation-deprecate-a-path-operation-openapi }
+
+在文档界面中显示弃用的**路径操作**,请阅读 [教程 - 路径操作配置 - 弃用](../tutorial/path-operation-configuration.md#deprecate-a-path-operation) 文档。
+
+## 将任何数据转换为 JSON 兼容格式 { #convert-any-data-to-json-compatible }
+
+要将任何数据转换为 JSON 兼容格式,请阅读 [教程 - JSON 兼容编码器](../tutorial/encoder.md) 文档。
+
+## OpenAPI 元数据 - 文档 { #openapi-metadata-docs }
+
+要添加 OpenAPI 的元数据,包括许可证、版本、联系方式等,请阅读 [教程 - 元数据和文档 URL](../tutorial/metadata.md) 文档。
+
+## OpenAPI 自定义 URL { #openapi-custom-url }
+
+要自定义 OpenAPI 的 URL(或删除它),请阅读 [教程 - 元数据和文档 URL](../tutorial/metadata.md#openapi-url) 文档。
+
+## OpenAPI 文档 URL { #openapi-docs-urls }
+
+要更改自动生成的文档用户界面所使用的 URL,请阅读 [教程 - 元数据和文档 URL](../tutorial/metadata.md#docs-urls)。
diff --git a/docs/zh/docs/how-to/graphql.md b/docs/zh/docs/how-to/graphql.md
new file mode 100644
index 0000000000000..b33d6759fa67f
--- /dev/null
+++ b/docs/zh/docs/how-to/graphql.md
@@ -0,0 +1,60 @@
+# GraphQL { #graphql }
+
+由于 **FastAPI** 基于 **ASGI** 标准,因此很容易集成任何也兼容 ASGI 的 **GraphQL** 库。
+
+你可以在同一个应用中将常规的 FastAPI 路径操作与 GraphQL 结合使用。
+
+/// tip | 提示
+
+**GraphQL** 解决一些非常特定的用例。
+
+与常见的 **Web API** 相比,它有各自的**优点**和**缺点**。
+
+请确保评估在你的用例中,这些**好处**是否足以弥补这些**缺点**。 🤓
+
+///
+
+## GraphQL 库 { #graphql-libraries }
+
+以下是一些支持 **ASGI** 的 **GraphQL** 库。你可以将它们与 **FastAPI** 一起使用:
+
+* [Strawberry](https://strawberry.rocks/) 🍓
+ * 提供 [面向 FastAPI 的文档](https://strawberry.rocks/docs/integrations/fastapi)
+* [Ariadne](https://ariadnegraphql.org/)
+ * 提供 [面向 FastAPI 的文档](https://ariadnegraphql.org/docs/fastapi-integration)
+* [Tartiflette](https://tartiflette.io/)
+ * 提供用于 ASGI 集成的 [Tartiflette ASGI](https://tartiflette.github.io/tartiflette-asgi/)
+* [Graphene](https://graphene-python.org/)
+ * 可配合 [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3) 使用
+
+## 使用 Strawberry 的 GraphQL { #graphql-with-strawberry }
+
+如果你需要或想要使用 **GraphQL**,[**Strawberry**](https://strawberry.rocks/) 是**推荐**的库,因为它的设计与 **FastAPI** 最为接近,全部基于**类型注解**。
+
+根据你的用例,你可能会更喜欢其他库,但如果你问我,我大概率会建议你先试试 **Strawberry**。
+
+下面是一个将 Strawberry 与 FastAPI 集成的小预览:
+
+{* ../../docs_src/graphql_/tutorial001_py310.py hl[3,22,25] *}
+
+你可以在 [Strawberry 文档](https://strawberry.rocks/) 中了解更多信息。
+
+还有关于 [将 Strawberry 与 FastAPI 结合使用](https://strawberry.rocks/docs/integrations/fastapi) 的文档。
+
+## Starlette 中较早的 `GraphQLApp` { #older-graphqlapp-from-starlette }
+
+早期版本的 Starlette 包含一个 `GraphQLApp` 类,用于与 [Graphene](https://graphene-python.org/) 集成。
+
+它已在 Starlette 中被弃用,但如果你的代码使用了它,你可以轻松**迁移**到 [starlette-graphene3](https://github.com/ciscorn/starlette-graphene3),它覆盖相同的用例,且接口**几乎完全一致**。
+
+/// tip | 提示
+
+如果你需要 GraphQL,我仍然建议看看 [Strawberry](https://strawberry.rocks/),因为它基于类型注解而不是自定义类和类型。
+
+///
+
+## 了解更多 { #learn-more }
+
+你可以在 [GraphQL 官方文档](https://graphql.org/) 中了解更多关于 **GraphQL** 的内容。
+
+你也可以通过上面的链接阅读各个库的更多信息。
diff --git a/docs/zh/docs/how-to/index.md b/docs/zh/docs/how-to/index.md
new file mode 100644
index 0000000000000..ff3d8afa0ce0a
--- /dev/null
+++ b/docs/zh/docs/how-to/index.md
@@ -0,0 +1,13 @@
+# 如何操作 - 诀窍 { #how-to-recipes }
+
+在这里,你将看到关于**多个主题**的不同诀窍或“如何操作”指南。
+
+这些方法多数是**相互独立**的,在大多数情况下,你只需在这些内容适用于**你的项目**时才需要学习它们。
+
+如果某些内容看起来对你的项目有用,请继续查阅,否则请直接跳过它们。
+
+/// tip | 提示
+
+如果你想以系统的方式**学习 FastAPI**(推荐),请阅读 [教程 - 用户指南](../tutorial/index.md) 的每一章节。
+
+///
diff --git a/docs/zh/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/zh/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
new file mode 100644
index 0000000000000..3723eb03271b7
--- /dev/null
+++ b/docs/zh/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md
@@ -0,0 +1,135 @@
+# 从 Pydantic v1 迁移到 Pydantic v2 { #migrate-from-pydantic-v1-to-pydantic-v2 }
+
+如果你有一个较旧的 FastAPI 应用,可能在使用 Pydantic v1。
+
+FastAPI 0.100.0 同时支持 Pydantic v1 和 v2,会使用你已安装的任一版本。
+
+FastAPI 0.119.0 引入了在 Pydantic v2 内部以 `pydantic.v1` 形式对 Pydantic v1 的部分支持,以便于迁移到 v2。
+
+FastAPI 0.126.0 移除了对 Pydantic v1 的支持,但在一段时间内仍支持 `pydantic.v1`。
+
+/// warning | 警告
+
+从 Python 3.14 开始,Pydantic 团队不再为最新的 Python 版本提供 Pydantic v1 的支持。
+
+这也包括 `pydantic.v1`,在 Python 3.14 及更高版本中不再受支持。
+
+如果你想使用 Python 的最新特性,需要确保使用 Pydantic v2。
+
+///
+
+如果你的旧 FastAPI 应用在用 Pydantic v1,这里将向你展示如何迁移到 Pydantic v2,以及 FastAPI 0.119.0 中可帮助你渐进式迁移的功能。
+
+## 官方指南 { #official-guide }
+
+Pydantic 有一份从 v1 迁移到 v2 的官方[迁移指南](https://docs.pydantic.dev/latest/migration/)。
+
+其中包含变更内容、校验如何更准确更严格、可能的注意事项等。
+
+你可以阅读以更好地了解变更。
+
+## 测试 { #tests }
+
+请确保你的应用有[测试](../tutorial/testing.md),并在持续集成(CI)中运行它们。
+
+这样你就可以升级并确保一切仍按预期工作。
+
+## `bump-pydantic` { #bump-pydantic }
+
+在很多情况下,如果你使用的是未做自定义的常规 Pydantic 模型,可以将从 Pydantic v1 迁移到 v2 的大部分过程自动化。
+
+你可以使用同一 Pydantic 团队提供的[`bump-pydantic`](https://github.com/pydantic/bump-pydantic)。
+
+该工具会帮助你自动修改大部分需要变更的代码。
+
+之后运行测试检查是否一切正常。如果正常,你就完成了。😎
+
+## v2 中的 Pydantic v1 { #pydantic-v1-in-v2 }
+
+Pydantic v2 以子模块 `pydantic.v1` 的形式包含了 Pydantic v1 的全部内容。但在 Python 3.13 以上的版本中不再受支持。
+
+这意味着你可以安装最新的 Pydantic v2,并从该子模块导入并使用旧的 Pydantic v1 组件,就像安装了旧版 Pydantic v1 一样。
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}
+
+### FastAPI 对 v2 中 Pydantic v1 的支持 { #fastapi-support-for-pydantic-v1-in-v2 }
+
+自 FastAPI 0.119.0 起,FastAPI 也对 Pydantic v2 内的 Pydantic v1 提供了部分支持,以便迁移到 v2。
+
+因此,你可以将 Pydantic 升级到最新的 v2,并将导入改为使用 `pydantic.v1` 子模块,在很多情况下就能直接工作。
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py hl[2,5,15] *}
+
+/// warning | 警告
+
+请注意,由于 Pydantic 团队自 Python 3.14 起不再在较新的 Python 版本中支持 Pydantic v1,使用 `pydantic.v1` 在 Python 3.14 及更高版本中也不受支持。
+
+///
+
+### 同一应用中同时使用 Pydantic v1 与 v2 { #pydantic-v1-and-v2-on-the-same-app }
+
+Pydantic 不支持在一个 Pydantic v2 模型的字段中定义 Pydantic v1 模型,反之亦然。
+
+```mermaid
+graph TB
+ subgraph "❌ Not Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+...但是,你可以在同一个应用中分别使用 Pydantic v1 和 v2 的独立模型。
+
+```mermaid
+graph TB
+ subgraph "✅ Supported"
+ direction TB
+ subgraph V2["Pydantic v2 Model"]
+ V2Field["Pydantic v2 Model"]
+ end
+ subgraph V1["Pydantic v1 Model"]
+ V1Field["Pydantic v1 Model"]
+ end
+ end
+
+ style V2 fill:#f9fff3
+ style V1 fill:#fff6f0
+ style V1Field fill:#fff6f0
+ style V2Field fill:#f9fff3
+```
+
+在某些情况下,甚至可以在 FastAPI 应用的同一个路径操作中同时使用 Pydantic v1 和 v2 模型:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}
+
+在上面的示例中,输入模型是 Pydantic v1 模型,输出模型(在 `response_model=ItemV2` 中定义)是 Pydantic v2 模型。
+
+### Pydantic v1 参数 { #pydantic-v1-parameters }
+
+如果你需要在 Pydantic v1 模型中使用 FastAPI 特有的参数工具,如 `Body`、`Query`、`Form` 等,在完成向 Pydantic v2 的迁移前,可以从 `fastapi.temp_pydantic_v1_params` 导入它们:
+
+{* ../../docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py hl[4,18] *}
+
+### 分步迁移 { #migrate-in-steps }
+
+/// tip | 提示
+
+优先尝试 `bump-pydantic`,如果测试通过且可行,那么你就用一个命令完成了。✨
+
+///
+
+如果 `bump-pydantic` 不适用于你的场景,你可以在同一应用中同时支持 Pydantic v1 和 v2 模型,逐步迁移到 Pydantic v2。
+
+你可以首先将 Pydantic 升级到最新的 v2,并将所有模型的导入改为使用 `pydantic.v1`。
+
+然后按模块或分组,逐步把模型从 Pydantic v1 迁移到 v2。🚶
diff --git a/docs/zh/docs/how-to/separate-openapi-schemas.md b/docs/zh/docs/how-to/separate-openapi-schemas.md
new file mode 100644
index 0000000000000..c3efe5f1a44b7
--- /dev/null
+++ b/docs/zh/docs/how-to/separate-openapi-schemas.md
@@ -0,0 +1,102 @@
+# 是否为输入和输出分别生成 OpenAPI JSON Schema { #separate-openapi-schemas-for-input-and-output-or-not }
+
+自从发布了 **Pydantic v2**,生成的 OpenAPI 比之前更精确、更**正确**了。😎
+
+事实上,在某些情况下,对于同一个 Pydantic 模型,OpenAPI 中会根据是否带有**默认值**,为输入和输出分别生成**两个 JSON Schema**。
+
+我们来看看它如何工作,以及在需要时如何修改。
+
+## 用于输入和输出的 Pydantic 模型 { #pydantic-models-for-input-and-output }
+
+假设你有一个带有默认值的 Pydantic 模型,例如:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *}
+
+### 输入用的模型 { #model-for-input }
+
+如果你像下面这样把该模型用作输入:
+
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *}
+
+...那么 `description` 字段将**不是必填项**,因为它的默认值是 `None`。
+
+### 文档中的输入模型 { #input-model-in-docs }
+
+你可以在文档中确认,`description` 字段没有**红色星号**,也就是未被标记为必填:
+
+
+
+
+
+
+FastAPI 框架,高性能,易于学习,高效编码,生产可用
--- -**文档**: https://fastapi.tiangolo.com +**文档**: [https://fastapi.tiangolo.com/zh](https://fastapi.tiangolo.com/zh) -**源码**: https://github.com/tiangolo/fastapi +**源码**: [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi) --- -FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于标准的 Python 类型提示。 - -关键特性: +FastAPI 是一个用于构建 API 的现代、快速(高性能)的 Web 框架,使用 Python 并基于标准的 Python 类型提示。 -* **快速**:可与 **NodeJS** 和 **Go** 并肩的极高性能(归功于 Starlette 和 Pydantic)。[最快的 Python web 框架之一](#_11)。 +关键特性: -* **高效编码**:提高功能开发速度约 200% 至 300%。* -* **更少 bug**:减少约 40% 的人为(开发者)导致错误。* -* **智能**:极佳的编辑器支持。处处皆可自动补全,减少调试时间。 -* **简单**:设计的易于使用和学习,阅读文档的时间更短。 -* **简短**:使代码重复最小化。通过不同的参数声明实现丰富功能。bug 更少。 -* **健壮**:生产可用级别的代码。还有自动生成的交互式文档。 -* **标准化**:基于(并完全兼容)API 的相关开放标准:OpenAPI (以前被称为 Swagger) 和 JSON Schema。 +* **快速**:极高性能,可与 **NodeJS** 和 **Go** 并肩(归功于 Starlette 和 Pydantic)。[最快的 Python 框架之一](#performance)。 +* **高效编码**:功能开发速度提升约 200% ~ 300%。* +* **更少 bug**:人为(开发者)错误减少约 40%。* +* **直观**:极佳的编辑器支持。处处皆可自动补全。更少的调试时间。 +* **易用**:为易用和易学而设计。更少的文档阅读时间。 +* **简短**:最小化代码重复。一次参数声明即可获得多种功能。更少的 bug。 +* **健壮**:生产可用级代码。并带有自动生成的交互式文档。 +* **标准化**:基于(并完全兼容)API 的开放标准:[OpenAPI](https://github.com/OAI/OpenAPI-Specification)(以前称为 Swagger)和 [JSON Schema](https://json-schema.org/)。 -* 根据对某个构建线上应用的内部开发团队所进行的测试估算得出。 +* 基于某内部开发团队在构建生产应用时的测试估算。 -## Sponsors +## 赞助商 { #sponsors } -{% if sponsors %} +### Keystone 赞助商 { #keystone-sponsor } + +{% for sponsor in sponsors.keystone -%} +
-FastAPI 站在以下巨人的肩膀之上:
+## **Typer**,命令行中的 FastAPI { #typer-the-fastapi-of-clis }
-* Starlette 负责 web 部分。
-* Pydantic 负责数据部分。
+async def...uvicorn main:app --reload 命令......fastapi dev...email_validator - 用于 email 校验。
+### 其他可选依赖 { #additional-optional-dependencies }
-用于 Starlette:
+还有一些你可能想安装的可选依赖。
-* httpx - 使用 `TestClient` 时安装。
-* jinja2 - 使用默认模板配置时安装。
-* python-multipart - 需要通过 `request.form()` 对表单进行「解析」时安装。
-* itsdangerous - 需要 `SessionMiddleware` 支持时安装。
-* pyyaml - 使用 Starlette 提供的 `SchemaGenerator` 时安装(有 FastAPI 你可能并不需要它)。
-* graphene - 需要 `GraphQLApp` 支持时安装。
-* ujson - 使用 `UJSONResponse` 时安装。
+额外的 Pydantic 可选依赖:
-用于 FastAPI / Starlette:
+* [`pydantic-settings`](https://docs.pydantic.dev/latest/usage/pydantic_settings/) - 用于配置管理。
+* [`pydantic-extra-types`](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/) - 用于在 Pydantic 中使用的额外类型。
-* uvicorn - 用于加载和运行你的应用程序的服务器。
-* orjson - 使用 `ORJSONResponse` 时安装。
+额外的 FastAPI 可选依赖:
-你可以通过 `pip install fastapi[all]` 命令来安装以上所有依赖。
+* [`orjson`](https://github.com/ijl/orjson) - 使用 `ORJSONResponse` 时需要。
+* [`ujson`](https://github.com/esnme/ultrajson) - 使用 `UJSONResponse` 时需要。
-## 许可协议
+## 许可协议 { #license }
该项目遵循 MIT 许可协议。
diff --git a/docs/zh/docs/learn/index.md b/docs/zh/docs/learn/index.md
new file mode 100644
index 0000000000000..144d5b2a9d9d0
--- /dev/null
+++ b/docs/zh/docs/learn/index.md
@@ -0,0 +1,5 @@
+# 学习 { #learn }
+
+以下是学习 **FastAPI** 的介绍部分和教程。
+
+您可以认为这是一本 **书**,一门 **课程**,是 **官方** 且推荐的学习FastAPI的方法。😎
diff --git a/docs/zh/docs/project-generation.md b/docs/zh/docs/project-generation.md
new file mode 100644
index 0000000000000..8cc50c0963a02
--- /dev/null
+++ b/docs/zh/docs/project-generation.md
@@ -0,0 +1,28 @@
+# FastAPI全栈模板 { #full-stack-fastapi-template }
+
+模板通常带有特定的设置,但它们被设计为灵活且可定制。这样你可以根据项目需求进行修改和调整,使其成为很好的起点。🏁
+
+你可以使用此模板开始,它已经为你完成了大量的初始设置、安全性、数据库以及一些 API 端点。
+
+GitHub 仓库:[Full Stack FastAPI Template](https://github.com/tiangolo/full-stack-fastapi-template)
+
+## FastAPI全栈模板 - 技术栈和特性 { #full-stack-fastapi-template-technology-stack-and-features }
+
+- ⚡ [**FastAPI**](https://fastapi.tiangolo.com/zh) 用于 Python 后端 API。
+ - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) 用于 Python 与 SQL 数据库的交互(ORM)。
+ - 🔍 [Pydantic](https://docs.pydantic.dev),FastAPI 使用,用于数据验证与配置管理。
+ - 💾 [PostgreSQL](https://www.postgresql.org) 作为 SQL 数据库。
+- 🚀 [React](https://react.dev) 用于前端。
+ - 💃 使用 TypeScript、hooks、Vite 以及现代前端技术栈的其他部分。
+ - 🎨 [Tailwind CSS](https://tailwindcss.com) 与 [shadcn/ui](https://ui.shadcn.com) 用于前端组件。
+ - 🤖 自动生成的前端客户端。
+ - 🧪 [Playwright](https://playwright.dev) 用于端到端测试。
+ - 🦇 支持暗黑模式。
+- 🐋 [Docker Compose](https://www.docker.com) 用于开发与生产。
+- 🔒 默认启用安全的密码哈希。
+- 🔑 JWT(JSON Web Token)认证。
+- 📫 基于邮箱的密码找回。
+- ✅ 使用 [Pytest](https://pytest.org) 进行测试。
+- 📞 [Traefik](https://traefik.io) 用作反向代理/负载均衡。
+- 🚢 使用 Docker Compose 的部署指南,包括如何设置前端 Traefik 代理以自动处理 HTTPS 证书。
+- 🏭 基于 GitHub Actions 的 CI(持续集成)与 CD(持续部署)。
diff --git a/docs/zh/docs/python-types.md b/docs/zh/docs/python-types.md
index 6cdb4b58838d7..9b2fceb98e0dc 100644
--- a/docs/zh/docs/python-types.md
+++ b/docs/zh/docs/python-types.md
@@ -1,29 +1,30 @@
-# Python 类型提示简介
+# Python 类型提示简介 { #python-types-intro }
-**Python 3.6+ 版本**加入了对"类型提示"的支持。
+Python 支持可选的“类型提示”(也叫“类型注解”)。
-这些**"类型提示"**是一种新的语法(在 Python 3.6 版本加入)用来声明一个变量的类型。
+这些“类型提示”或注解是一种特殊语法,用来声明变量的类型。
-通过声明变量的类型,编辑器和一些工具能给你提供更好的支持。
+通过为变量声明类型,编辑器和工具可以为你提供更好的支持。
-这只是一个关于 Python 类型提示的**快速入门 / 复习**。它仅涵盖与 **FastAPI** 一起使用所需的最少部分...实际上只有很少一点。
+这只是一个关于 Python 类型提示的快速入门/复习。它只涵盖与 **FastAPI** 一起使用所需的最少部分...实际上非常少。
-整个 **FastAPI** 都基于这些类型提示构建,它们带来了许多优点和好处。
+**FastAPI** 完全基于这些类型提示构建,它们带来了许多优势和好处。
-但即使你不会用到 **FastAPI**,了解一下类型提示也会让你从中受益。
+但即使你从不使用 **FastAPI**,了解一些类型提示也会让你受益。
-!!! note
- 如果你已经精通 Python,并且了解关于类型提示的一切知识,直接跳到下一章节吧。
+/// note | 注意
-## 动机
+如果你已经是 Python 专家,并且对类型提示了如指掌,可以跳到下一章。
+
+///
+
+## 动机 { #motivation }
让我们从一个简单的例子开始:
-```Python
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001_py310.py *}
-运行这段程序将输出:
+运行这个程序会输出:
```
John Doe
@@ -31,39 +32,37 @@ John Doe
这个函数做了下面这些事情:
-* 接收 `first_name` 和 `last_name` 参数。
-* 通过 `title()` 将每个参数的第一个字母转换为大写形式。
-* 中间用一个空格来拼接它们。
+* 接收 `first_name` 和 `last_name`。
+* 通过 `title()` 将每个参数的第一个字母转换为大写。
+* 用一个空格将它们拼接起来。
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial001.py!}
-```
+{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *}
-### 修改示例
+### 修改它 { #edit-it }
这是一个非常简单的程序。
-现在假设你将从头开始编写这段程序。
+但现在想象你要从零开始写它。
-在某一时刻,你开始定义函数,并且准备好了参数...。
+在某个时刻你开始定义函数,并且准备好了参数……
-现在你需要调用一个"将第一个字母转换为大写形式的方法"。
+接下来你需要调用“那个把首字母变大写的方法”。
-等等,那个方法是什么来着?`upper`?还是 `uppercase`?`first_uppercase`?`capitalize`?
+是 `upper`?是 `uppercase`?`first_uppercase`?还是 `capitalize`?
-然后你尝试向程序员老手的朋友——编辑器自动补全寻求帮助。
+然后,你试试程序员的老朋友——编辑器的自动补全。
-输入函数的第一个参数 `first_name`,输入点号(`.`)然后敲下 `Ctrl+Space` 来触发代码补全。
+你输入函数的第一个参数 `first_name`,再输入一个点(`.`),然后按下 `Ctrl+Space` 触发补全。
-但遗憾的是并没有起什么作用:
+但很遗憾,没有什么有用的提示:
-
+
-### 添加类型
+### 添加类型 { #add-types }
-让我们来修改上面例子的一行代码。
+我们来改前一个版本的一行代码。
-我们将把下面这段代码中的函数参数从:
+把函数参数从:
```Python
first_name, last_name
@@ -77,210 +76,273 @@ John Doe
就是这样。
-这些就是"类型提示":
+这些就是“类型提示”:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial002.py!}
-```
+{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *}
-这和声明默认值是不同的,例如:
+这和声明默认值不同,比如:
```Python
first_name="john", last_name="doe"
```
-这两者不一样。
+这是两码事。
我们用的是冒号(`:`),不是等号(`=`)。
-而且添加类型提示一般不会改变原来的运行结果。
+而且添加类型提示通常不会改变代码本来的行为。
-现在假设我们又一次正在创建这个函数,这次添加了类型提示。
+现在,再想象你又在编写这个函数了,不过这次加上了类型提示。
-在同样的地方,通过 `Ctrl+Space` 触发自动补全,你会发现:
+在同样的位置,你用 `Ctrl+Space` 触发自动补全,就能看到:
-
+
-这样,你可以滚动查看选项,直到你找到看起来眼熟的那个:
+这样,你可以滚动查看选项,直到找到那个“看着眼熟”的:
-
+
-## 更多动机
+## 更多动机 { #more-motivation }
-下面是一个已经有类型提示的函数:
+看这个已经带有类型提示的函数:
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial003.py!}
-```
+{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *}
-因为编辑器已经知道了这些变量的类型,所以不仅能对代码进行补全,还能检查其中的错误:
+因为编辑器知道变量的类型,你不仅能得到补全,还能获得错误检查:
-
+
-现在你知道了必须先修复这个问题,通过 `str(age)` 把 `age` 转换成字符串:
+现在你知道需要修复它,用 `str(age)` 把 `age` 转成字符串:
-```Python hl_lines="2"
-{!../../../docs_src/python_types/tutorial004.py!}
-```
+{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *}
-## 声明类型
+## 声明类型 { #declaring-types }
-你刚刚看到的就是声明类型提示的主要场景。用于函数的参数。
+你刚刚看到的是声明类型提示的主要位置:函数参数。
-这也是你将在 **FastAPI** 中使用它们的主要场景。
+这也是你在 **FastAPI** 中使用它们的主要场景。
-### 简单类型
+### 简单类型 { #simple-types }
-不只是 `str`,你能够声明所有的标准 Python 类型。
+你不仅可以声明 `str`,还可以声明所有标准的 Python 类型。
-比如以下类型:
+例如:
* `int`
* `float`
* `bool`
* `bytes`
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial005.py!}
+{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *}
+
+### typing 模块 { #typing-module }
+
+在一些额外的用例中,你可能需要从标准库的 `typing` 模块导入内容。比如当你想声明“任意类型”时,可以使用 `typing` 中的 `Any`:
+
+```python
+from typing import Any
+
+
+def some_function(data: Any):
+ print(data)
```
-### 嵌套类型
+### 泛型类型 { #generic-types }
-有些容器数据结构可以包含其他的值,比如 `dict`、`list`、`set` 和 `tuple`。它们内部的值也会拥有自己的类型。
+有些类型可以在方括号中接收“类型参数”(type parameters),用于声明其内部值的类型。比如“字符串列表”可以写为 `list[str]`。
-你可以使用 Python 的 `typing` 标准库来声明这些类型以及子类型。
+这些能接收类型参数的类型称为“泛型类型”(Generic types)或“泛型”(Generics)。
-它专门用来支持这些类型提示。
+你可以把相同的内建类型作为泛型使用(带方括号和内部类型):
-#### 列表
+* `list`
+* `tuple`
+* `set`
+* `dict`
-例如,让我们来定义一个由 `str` 组成的 `list` 变量。
+#### 列表 { #list }
-从 `typing` 模块导入 `List`(注意是大写的 `L`):
+例如,我们来定义一个由 `str` 组成的 `list` 变量。
-```Python hl_lines="1"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+用同样的冒号(`:`)语法声明变量。
-同样以冒号(`:`)来声明这个变量。
+类型写 `list`。
-输入 `List` 作为类型。
+因为 list 是一种包含内部类型的类型,把内部类型写在方括号里:
-由于列表是带有"子类型"的类型,所以我们把子类型放在方括号中:
+{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *}
-```Python hl_lines="4"
-{!../../../docs_src/python_types/tutorial006.py!}
-```
+/// info | 信息
-这表示:"变量 `items` 是一个 `list`,并且这个列表里的每一个元素都是 `str`"。
+方括号中的这些内部类型称为“类型参数”(type parameters)。
-这样,即使在处理列表中的元素时,你的编辑器也可以提供支持。
+在这个例子中,`str` 是传给 `list` 的类型参数。
-没有类型,几乎是不可能实现下面这样:
+///
-
+这表示:“变量 `items` 是一个 `list`,并且列表中的每一个元素都是 `str`”。
-注意,变量 `item` 是列表 `items` 中的元素之一。
+这样,即使是在处理列表中的元素时,编辑器也能给你提供支持:
-而且,编辑器仍然知道它是一个 `str`,并为此提供了支持。
+
-#### 元组和集合
+没有类型的话,这几乎是不可能做到的。
-声明 `tuple` 和 `set` 的方法也是一样的:
+注意,变量 `item` 是列表 `items` 中的一个元素。
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial007.py!}
-```
+即便如此,编辑器仍然知道它是 `str`,并为此提供支持。
+
+#### 元组和集合 { #tuple-and-set }
+
+声明 `tuple` 和 `set` 的方式类似:
+
+{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *}
这表示:
-* 变量 `items_t` 是一个 `tuple`,其中的前两个元素都是 `int` 类型, 最后一个元素是 `str` 类型。
-* 变量 `items_s` 是一个 `set`,其中的每个元素都是 `bytes` 类型。
+* 变量 `items_t` 是一个含有 3 个元素的 `tuple`,分别是一个 `int`、另一个 `int`,以及一个 `str`。
+* 变量 `items_s` 是一个 `set`,其中每个元素的类型是 `bytes`。
-#### 字典
+#### 字典 { #dict }
-定义 `dict` 时,需要传入两个子类型,用逗号进行分隔。
+定义 `dict` 时,需要传入 2 个类型参数,用逗号分隔。
-第一个子类型声明 `dict` 的所有键。
+第一个类型参数用于字典的键。
-第二个子类型声明 `dict` 的所有值:
+第二个类型参数用于字典的值:
-```Python hl_lines="1 4"
-{!../../../docs_src/python_types/tutorial008.py!}
-```
+{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *}
这表示:
* 变量 `prices` 是一个 `dict`:
- * 这个 `dict` 的所有键为 `str` 类型(可以看作是字典内每个元素的名称)。
- * 这个 `dict` 的所有值为 `float` 类型(可以看作是字典内每个元素的价格)。
+ * 这个 `dict` 的键是 `str` 类型(比如,每个条目的名称)。
+ * 这个 `dict` 的值是 `float` 类型(比如,每个条目的价格)。
+
+#### Union { #union }
-### 类作为类型
+你可以声明一个变量可以是若干种类型中的任意一种,比如既可以是 `int` 也可以是 `str`。
-你也可以将类声明为变量的类型。
+定义时使用竖线(`|`)把两种类型分开。
-假设你有一个名为 `Person` 的类,拥有 name 属性:
+这称为“联合类型”(union),因为变量可以是这两类类型集合的并集中的任意一个。
-```Python hl_lines="1-3"
-{!../../../docs_src/python_types/tutorial010.py!}
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial008b_py310.py!}
```
-接下来,你可以将一个变量声明为 `Person` 类型:
+这表示 `item` 可以是 `int` 或 `str`。
+
+#### 可能为 `None` { #possibly-none }
-```Python hl_lines="6"
-{!../../../docs_src/python_types/tutorial010.py!}
+你可以声明一个值的类型是某种类型(比如 `str`),但它也可能是 `None`。
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+{!> ../../docs_src/python_types/tutorial009_py310.py!}
```
-然后,你将再次获得所有的编辑器支持:
+////
-
+使用 `str | None` 而不是仅仅 `str`,可以让编辑器帮助你发现把值当成总是 `str` 的错误(实际上它也可能是 `None`)。
-## Pydantic 模型
+### 类作为类型 { #classes-as-types }
-Pydantic 是一个用来用来执行数据校验的 Python 库。
+你也可以把类声明为变量的类型。
-你可以将数据的"结构"声明为具有属性的类。
+假设你有一个名为 `Person` 的类,带有 name:
-每个属性都拥有类型。
+{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *}
-接着你用一些值来创建这个类的实例,这些值会被校验,并被转换为适当的类型(在需要的情况下),返回一个包含所有数据的对象。
+然后你可以声明一个变量是 `Person` 类型:
-然后,你将获得这个对象的所有编辑器支持。
+{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *}
-下面的例子来自 Pydantic 官方文档:
+接着,你会再次获得所有的编辑器支持:
-```Python
-{!../../../docs_src/python_types/tutorial010.py!}
-```
+
+
+注意,这表示“`one_person` 是类 `Person` 的一个实例(instance)”。
+
+它并不表示“`one_person` 是名为 `Person` 的类本身(class)”。
+
+## Pydantic 模型 { #pydantic-models }
+
+[Pydantic](https://docs.pydantic.dev/) 是一个用于执行数据校验的 Python 库。
+
+你将数据的“结构”声明为带有属性的类。
+
+每个属性都有一个类型。
+
+然后你用一些值创建这个类的实例,它会校验这些值,并在需要时把它们转换为合适的类型,返回一个包含所有数据的对象。
+
+你还能对这个结果对象获得完整的编辑器支持。
+
+下面是来自 Pydantic 官方文档的一个示例:
+
+{* ../../docs_src/python_types/tutorial011_py310.py *}
+
+/// info | 信息
+
+想了解更多关于 [Pydantic](https://docs.pydantic.dev/) 的信息,请查看其文档。
+
+///
+
+**FastAPI** 完全建立在 Pydantic 之上。
+
+你会在[教程 - 用户指南](tutorial/index.md)中看到更多的实战示例。
+
+## 带元数据注解的类型提示 { #type-hints-with-metadata-annotations }
+
+Python 还提供了一个特性,可以使用 `Annotated` 在这些类型提示中放入额外的元数据。
+
+你可以从 `typing` 导入 `Annotated`。
+
+{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *}
+
+Python 本身不会对这个 `Annotated` 做任何处理。对于编辑器和其他工具,类型仍然是 `str`。
+
+但你可以在 `Annotated` 中为 **FastAPI** 提供额外的元数据,来描述你希望应用如何行为。
+
+重要的是要记住:传给 `Annotated` 的第一个类型参数才是实际类型。其余的只是给其他工具用的元数据。
+
+现在你只需要知道 `Annotated` 的存在,并且它是标准 Python。😎
+
+稍后你会看到它有多么强大。
+
+/// tip | 提示
+
+这是标准 Python,这意味着你仍然可以在编辑器里获得尽可能好的开发体验,并能和你用来分析、重构代码的工具良好协作等。✨
+
+同时你的代码也能与许多其他 Python 工具和库高度兼容。🚀
-!!! info
- 想进一步了解 Pydantic,请阅读其文档.
+///
-整个 **FastAPI** 建立在 Pydantic 的基础之上。
+## **FastAPI** 中的类型提示 { #type-hints-in-fastapi }
-实际上你将在 [教程 - 用户指南](tutorial/index.md){.internal-link target=_blank} 看到很多这种情况。
+**FastAPI** 利用这些类型提示来完成多件事情。
-## **FastAPI** 中的类型提示
+在 **FastAPI** 中,用类型提示来声明参数,你将获得:
-**FastAPI** 利用这些类型提示来做下面几件事。
+* 编辑器支持。
+* 类型检查。
-使用 **FastAPI** 时用类型提示声明参数可以获得:
+……并且 **FastAPI** 会使用相同的声明来:
-* **编辑器支持**。
-* **类型检查**。
+* 定义要求:从请求路径参数、查询参数、请求头、请求体、依赖等。
+* 转换数据:把请求中的数据转换为所需类型。
+* 校验数据:对于每个请求:
+ * 当数据无效时,自动生成错误信息返回给客户端。
+* 使用 OpenAPI 记录 API:
+ * 然后用于自动生成交互式文档界面。
-...并且 **FastAPI** 还会用这些类型声明来:
+这些听起来可能有点抽象。别担心。你会在[教程 - 用户指南](tutorial/index.md)中看到所有这些的实际效果。
-* **定义参数要求**:声明对请求路径参数、查询参数、请求头、请求体、依赖等的要求。
-* **转换数据**:将来自请求的数据转换为需要的类型。
-* **校验数据**: 对于每一个请求:
- * 当数据校验失败时自动生成**错误信息**返回给客户端。
-* 使用 OpenAPI **记录** API:
- * 然后用于自动生成交互式文档的用户界面。
+重要的是,通过使用标准的 Python 类型,而且只在一个地方声明(而不是添加更多类、装饰器等),**FastAPI** 会为你完成大量工作。
-听上去有点抽象。不过不用担心。你将在 [教程 - 用户指南](tutorial/index.md){.internal-link target=_blank} 中看到所有的实战。
+/// info | 信息
-最重要的是,通过使用标准的 Python 类型,只需要在一个地方声明(而不是添加更多的类、装饰器等),**FastAPI** 会为你完成很多的工作。
+如果你已经读完所有教程,又回来想进一步了解类型,一个不错的资源是 [`mypy` 的“速查表”](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html)。
-!!! info
- 如果你已经阅读了所有教程,回过头来想了解有关类型的更多信息,来自 `mypy` 的"速查表"是不错的资源。
+///
diff --git a/docs/zh/docs/resources/index.md b/docs/zh/docs/resources/index.md
new file mode 100644
index 0000000000000..2f55ac06f6727
--- /dev/null
+++ b/docs/zh/docs/resources/index.md
@@ -0,0 +1,3 @@
+# 资源 { #resources }
+
+更多资源、外部链接等。✈️
diff --git a/docs/zh/docs/translation-banner.md b/docs/zh/docs/translation-banner.md
new file mode 100644
index 0000000000000..76db203b0bbf5
--- /dev/null
+++ b/docs/zh/docs/translation-banner.md
@@ -0,0 +1,11 @@
+/// details | 🌐 由 AI 与人类协作翻译
+
+本翻译由人类引导的 AI 生成。🤝
+
+可能存在误解原意或不够自然等问题。🤖
+
+你可以通过[帮助我们更好地引导 AI LLM](https://fastapi.tiangolo.com/zh/contributing/#translations)来改进此翻译。
+
+[英文版本](ENGLISH_VERSION_URL)
+
+///
diff --git a/docs/zh/docs/tutorial/background-tasks.md b/docs/zh/docs/tutorial/background-tasks.md
index c8568298b14bf..975bb2688cba0 100644
--- a/docs/zh/docs/tutorial/background-tasks.md
+++ b/docs/zh/docs/tutorial/background-tasks.md
@@ -1,4 +1,4 @@
-# 后台任务
+# 后台任务 { #background-tasks }
你可以定义在返回响应后运行的后台任务。
@@ -11,17 +11,15 @@
* 处理数据:
* 例如,假设您收到的文件必须经过一个缓慢的过程,您可以返回一个"Accepted"(HTTP 202)响应并在后台处理它。
-## 使用 `BackgroundTasks`
+## 使用 `BackgroundTasks` { #using-backgroundtasks }
首先导入 `BackgroundTasks` 并在 *路径操作函数* 中使用类型声明 `BackgroundTasks` 定义一个参数:
-```Python hl_lines="1 13"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *}
**FastAPI** 会创建一个 `BackgroundTasks` 类型的对象并作为该参数传入。
-## 创建一个任务函数
+## 创建一个任务函数 { #create-a-task-function }
创建要作为后台任务运行的函数。
@@ -33,17 +31,13 @@
由于写操作不使用 `async` 和 `await`,我们用普通的 `def` 定义函数:
-```Python hl_lines="6-9"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *}
-## 添加后台任务
+## 添加后台任务 { #add-the-background-task }
在你的 *路径操作函数* 里,用 `.add_task()` 方法将任务函数传到 *后台任务* 对象中:
-```Python hl_lines="14"
-{!../../../docs_src/background_tasks/tutorial001.py!}
-```
+{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *}
`.add_task()` 接收以下参数:
@@ -51,47 +45,13 @@
* 应按顺序传递给任务函数的任意参数序列(`email`)。
* 应传递给任务函数的任意关键字参数(`message="some notification"`)。
-## 依赖注入
+## 依赖注入 { #dependency-injection }
使用 `BackgroundTasks` 也适用于依赖注入系统,你可以在多个级别声明 `BackgroundTasks` 类型的参数:在 *路径操作函数* 里,在依赖中(可依赖),在子依赖中,等等。
**FastAPI** 知道在每种情况下该做什么以及如何复用同一对象,因此所有后台任务被合并在一起并且随后在后台运行:
-=== "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.6+"
-
- ```Python hl_lines="14 16 23 26"
- {!> ../../../docs_src/background_tasks/tutorial002_an.py!}
- ```
-
-=== "Python 3.10+ 没Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="11 13 20 23"
- {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
- ```
-
-=== "Python 3.6+ 没Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="13 15 22 25"
- {!> ../../../docs_src/background_tasks/tutorial002.py!}
- ```
+{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *}
该示例中,信息会在响应发出 *之后* 被写到 `log.txt` 文件。
@@ -99,9 +59,9 @@
然后另一个在 *路径操作函数* 生成的后台任务会使用路径参数 `email` 写入一条信息。
-## 技术细节
+## 技术细节 { #technical-details }
-`BackgroundTasks` 类直接来自 `starlette.background`。
+`BackgroundTasks` 类直接来自 [`starlette.background`](https://www.starlette.dev/background/)。
它被直接导入/包含到FastAPI以便你可以从 `fastapi` 导入,并避免意外从 `starlette.background` 导入备用的 `BackgroundTask` (后面没有 `s`)。
@@ -109,18 +69,16 @@
在FastAPI中仍然可以单独使用 `BackgroundTask`,但您必须在代码中创建对象,并返回包含它的Starlette `Response`。
-更多细节查看 Starlette's official docs for Background Tasks.
+更多细节查看 [Starlette 后台任务的官方文档](https://www.starlette.dev/background/)。
-## 告诫
+## 告诫 { #caveat }
-如果您需要执行繁重的后台计算,并且不一定需要由同一进程运行(例如,您不需要共享内存、变量等),那么使用其他更大的工具(如 Celery)可能更好。
+如果您需要执行繁重的后台计算,并且不一定需要由同一进程运行(例如,您不需要共享内存、变量等),那么使用其他更大的工具(如 [Celery](https://docs.celeryq.dev))可能更好。
它们往往需要更复杂的配置,即消息/作业队列管理器,如RabbitMQ或Redis,但它们允许您在多个进程中运行后台任务,甚至是在多个服务器中。
-要查看示例,查阅 [Project Generators](../project-generation.md){.internal-link target=_blank},它们都包括已经配置的Celery。
-
但是,如果您需要从同一个**FastAPI**应用程序访问变量和对象,或者您需要执行小型后台任务(如发送电子邮件通知),您只需使用 `BackgroundTasks` 即可。
-## 回顾
+## 回顾 { #recap }
导入并使用 `BackgroundTasks` 通过 *路径操作函数* 中的参数和依赖项来添加后台任务。
diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md
index 9f0134f683c9e..74522f83843c0 100644
--- a/docs/zh/docs/tutorial/bigger-applications.md
+++ b/docs/zh/docs/tutorial/bigger-applications.md
@@ -1,13 +1,16 @@
-# 更大的应用 - 多个文件
+# 更大的应用 - 多个文件 { #bigger-applications-multiple-files }
如果你正在开发一个应用程序或 Web API,很少会将所有的内容都放在一个文件中。
**FastAPI** 提供了一个方便的工具,可以在保持所有灵活性的同时构建你的应用程序。
-!!! info
- 如果你来自 Flask,那这将相当于 Flask 的 Blueprints。
+/// info | 信息
-## 一个文件结构示例
+如果你来自 Flask,那这将相当于 Flask 的 Blueprints。
+
+///
+
+## 一个文件结构示例 { #an-example-file-structure }
假设你的文件结构如下:
@@ -26,16 +29,19 @@
│ └── admin.py
```
-!!! tip
- 上面有几个 `__init__.py` 文件:每个目录或子目录中都有一个。
+/// tip | 提示
+
+上面有几个 `__init__.py` 文件:每个目录或子目录中都有一个。
- 这就是能将代码从一个文件导入到另一个文件的原因。
+这就是能将代码从一个文件导入到另一个文件的原因。
- 例如,在 `app/main.py` 中,你可以有如下一行:
+例如,在 `app/main.py` 中,你可以有如下一行:
- ```
- from app.routers import items
- ```
+```
+from app.routers import items
+```
+
+///
* `app` 目录包含了所有内容。并且它有一个空文件 `app/__init__.py`,因此它是一个「Python 包」(「Python 模块」的集合):`app`。
* 它包含一个 `app/main.py` 文件。由于它位于一个 Python 包(一个包含 `__init__.py` 文件的目录)中,因此它是该包的一个「模块」:`app.main`。
@@ -46,11 +52,11 @@
* 还有一个子目录 `app/internal/` 包含另一个 `__init__.py` 文件,因此它是又一个「Python 子包」:`app.internal`。
* `app/internal/admin.py` 是另一个子模块:`app.internal.admin`。
-
+
-## 多次使用不同的 `prefix` 包含同一个路由器
+## 多次使用不同的 `prefix` 包含同一个路由器 { #include-the-same-router-multiple-times-with-different-prefix }
你也可以在*同一*路由器上使用不同的前缀来多次使用 `.include_router()`。
@@ -477,7 +524,7 @@ $ uvicorn app.main:app --reload
这是一个你可能并不真正需要的高级用法,但万一你有需要了就能够用上。
-## 在另一个 `APIRouter` 中包含一个 `APIRouter`
+## 在另一个 `APIRouter` 中包含一个 `APIRouter` { #include-an-apirouter-in-another }
与在 `FastAPI` 应用程序中包含 `APIRouter` 的方式相同,你也可以在另一个 `APIRouter` 中包含 `APIRouter`,通过:
@@ -485,4 +532,4 @@ $ uvicorn app.main:app --reload
router.include_router(other_router)
```
-请确保在你将 `router` 包含到 `FastAPI` 应用程序之前进行此操作,以便 `other_router` 中的`路径操作`也能被包含进来。
+请确保在你将 `router` 包含到 `FastAPI` 应用程序之前进行此操作,以便 `other_router` 中的*路径操作*也能被包含进来。
diff --git a/docs/zh/docs/tutorial/body-fields.md b/docs/zh/docs/tutorial/body-fields.md
index c153784dcd618..36be7c4191615 100644
--- a/docs/zh/docs/tutorial/body-fields.md
+++ b/docs/zh/docs/tutorial/body-fields.md
@@ -1,112 +1,60 @@
-# 请求体 - 字段
+# 请求体 - 字段 { #body-fields }
-与使用 `Query`、`Path` 和 `Body` 在*路径操作函数*中声明额外的校验和元数据的方式相同,你可以使用 Pydantic 的 `Field` 在 Pydantic 模型内部声明校验和元数据。
+与在*路径操作函数*中使用 `Query`、`Path` 、`Body` 声明校验与元数据的方式一样,可以使用 Pydantic 的 `Field` 在 Pydantic 模型内部声明校验和元数据。
-## 导入 `Field`
+## 导入 `Field` { #import-field }
-首先,你必须导入它:
+首先,从 Pydantic 中导入 `Field`:
-=== "Python 3.10+"
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *}
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+/// warning | 警告
-=== "Python 3.9+"
+注意,与从 `fastapi` 导入 `Query`,`Path`、`Body` 不同,要直接从 `pydantic` 导入 `Field` 。
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+///
-=== "Python 3.6+"
+## 声明模型属性 { #declare-model-attributes }
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+然后,使用 `Field` 定义模型的属性:
-=== "Python 3.10+ non-Annotated"
+{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *}
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+`Field` 的工作方式和 `Query`、`Path`、`Body` 相同,参数也相同。
- ```Python hl_lines="2"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+/// note | 技术细节
-=== "Python 3.6+ non-Annotated"
+实际上,`Query`、`Path` 以及你接下来会看到的其它对象,会创建公共 `Param` 类的子类的对象,而 `Param` 本身是 Pydantic 中 `FieldInfo` 的子类。
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。
- ```Python hl_lines="4"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
+`Body` 直接返回的也是 `FieldInfo` 的子类的对象。后文还会介绍一些 `Body` 的子类。
-!!! warning
- 注意,`Field` 是直接从 `pydantic` 导入的,而不是像其他的(`Query`,`Path`,`Body` 等)都从 `fastapi` 导入。
+注意,从 `fastapi` 导入的 `Query`、`Path` 等对象实际上都是返回特殊类的函数。
-## 声明模型属性
+///
-然后,你可以对模型属性使用 `Field`:
+/// tip | 提示
-=== "Python 3.10+"
+注意,模型属性的类型、默认值及 `Field` 的代码结构与*路径操作函数*的参数相同,只不过是用 `Field` 替换了`Path`、`Query`、`Body`。
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!}
- ```
+///
-=== "Python 3.9+"
+## 添加更多信息 { #add-extra-information }
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!}
- ```
+`Field`、`Query`、`Body` 等对象里可以声明更多信息,并且 JSON Schema 中也会集成这些信息。
-=== "Python 3.6+"
+*声明示例*一章中将详细介绍添加更多信息的知识。
- ```Python hl_lines="12-15"
- {!> ../../../docs_src/body_fields/tutorial001_an.py!}
- ```
+/// warning | 警告
-=== "Python 3.10+ non-Annotated"
+传递给 `Field` 的额外键也会出现在你的应用生成的 OpenAPI 架构中。
+由于这些键不一定属于 OpenAPI 规范的一部分,某些 OpenAPI 工具(例如 [OpenAPI 验证器](https://validator.swagger.io/))可能无法处理你生成的架构。
- !!! tip
- Prefer to use the `Annotated` version if possible.
+///
- ```Python hl_lines="9-12"
- {!> ../../../docs_src/body_fields/tutorial001_py310.py!}
- ```
+## 小结 { #recap }
-=== "Python 3.6+ non-Annotated"
+Pydantic 的 `Field` 可以为模型属性声明更多校验和元数据。
- !!! tip
- Prefer to use the `Annotated` version if possible.
-
- ```Python hl_lines="11-14"
- {!> ../../../docs_src/body_fields/tutorial001.py!}
- ```
-
-`Field` 的工作方式和 `Query`、`Path` 和 `Body` 相同,包括它们的参数等等也完全相同。
-
-!!! note "技术细节"
- 实际上,`Query`、`Path` 和其他你将在之后看到的类,创建的是由一个共同的 `Params` 类派生的子类的对象,该共同类本身又是 Pydantic 的 `FieldInfo` 类的子类。
-
- Pydantic 的 `Field` 也会返回一个 `FieldInfo` 的实例。
-
- `Body` 也直接返回 `FieldInfo` 的一个子类的对象。还有其他一些你之后会看到的类是 `Body` 类的子类。
-
- 请记住当你从 `fastapi` 导入 `Query`、`Path` 等对象时,他们实际上是返回特殊类的函数。
-
-!!! tip
- 注意每个模型属性如何使用类型、默认值和 `Field` 在代码结构上和*路径操作函数*的参数是相同的,区别是用 `Field` 替换`Path`、`Query` 和 `Body`。
-
-## 添加额外信息
-
-你可以在 `Field`、`Query`、`Body` 中声明额外的信息。这些信息将包含在生成的 JSON Schema 中。
-
-你将在文档的后面部分学习声明示例时,了解到更多有关添加额外信息的知识。
-
-## 总结
-
-你可以使用 Pydantic 的 `Field` 为模型属性声明额外的校验和元数据。
-
-你还可以使用额外的关键字参数来传递额外的 JSON Schema 元数据。
+传递 JSON Schema 元数据还可以使用更多关键字参数。
diff --git a/docs/zh/docs/tutorial/body-multiple-params.md b/docs/zh/docs/tutorial/body-multiple-params.md
index ee2cba6df7ca9..39b84904fcf23 100644
--- a/docs/zh/docs/tutorial/body-multiple-params.md
+++ b/docs/zh/docs/tutorial/body-multiple-params.md
@@ -1,53 +1,22 @@
-# 请求体 - 多个参数
+# 请求体 - 多个参数 { #body-multiple-parameters }
既然我们已经知道了如何使用 `Path` 和 `Query`,下面让我们来了解一下请求体声明的更高级用法。
-## 混合使用 `Path`、`Query` 和请求体参数
+## 混合使用 `Path`、`Query` 和请求体参数 { #mix-path-query-and-body-parameters }
首先,毫无疑问地,你可以随意地混合使用 `Path`、`Query` 和请求体参数声明,**FastAPI** 会知道该如何处理。
你还可以通过将默认值设置为 `None` 来将请求体参数声明为可选参数:
-=== "Python 3.10+"
+{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!}
- ```
+/// note | 注意
-=== "Python 3.9+"
+请注意,在这种情况下,将从请求体获取的 `item` 是可选的。因为它的默认值为 `None`。
- ```Python hl_lines="18-20"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!}
- ```
+///
-=== "Python 3.6+"
-
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="17-19"
- {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="19-21"
- {!> ../../../docs_src/body_multiple_params/tutorial001.py!}
- ```
-
-!!! note
- 请注意,在这种情况下,将从请求体获取的 `item` 是可选的。因为它的默认值为 `None`。
-
-## 多个请求体参数
+## 多个请求体参数 { #multiple-body-parameters }
在上面的示例中,*路径操作*将期望一个具有 `Item` 的属性的 JSON 请求体,就像:
@@ -62,17 +31,7 @@
但是你也可以声明多个请求体参数,例如 `item` 和 `user`:
-=== "Python 3.10+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial002.py!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}
在这种情况下,**FastAPI** 将注意到该函数中有多个请求体参数(两个 Pydantic 模型参数)。
@@ -93,15 +52,17 @@
}
```
-!!! note
- 请注意,即使 `item` 的声明方式与之前相同,但现在它被期望通过 `item` 键内嵌在请求体中。
+/// note | 注意
+请注意,即使 `item` 的声明方式与之前相同,但现在它被期望通过 `item` 键内嵌在请求体中。
+
+///
**FastAPI** 将自动对请求中的数据进行转换,因此 `item` 参数将接收指定的内容,`user` 参数也是如此。
它将执行对复合数据的校验,并且像现在这样为 OpenAPI 模式和自动化文档对其进行记录。
-## 请求体中的单一值
+## 请求体中的单一值 { #singular-values-in-body }
与使用 `Query` 和 `Path` 为查询参数和路径参数定义额外数据的方式相同,**FastAPI** 提供了一个同等的 `Body`。
@@ -111,46 +72,10 @@
但是你可以使用 `Body` 指示 **FastAPI** 将其作为请求体的另一个键进行处理。
-
-=== "Python 3.10+"
-
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="23"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="24"
- {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="22"
- {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}
在这种情况下,**FastAPI** 将期望像这样的请求体:
-
```JSON
{
"item": {
@@ -169,59 +94,27 @@
同样的,它将转换数据类型,校验,生成文档等。
-## 多个请求体参数和查询参数
+## 多个请求体参数和查询参数 { #multiple-body-params-and-query }
当然,除了请求体参数外,你还可以在任何需要的时候声明额外的查询参数。
-由于默认情况下单一值被解释为查询参数,因此你不必显式地添加 `Query`,你可以仅执行以下操作:
+由于默认情况下单一值会被解释为查询参数,因此你不必显式地添加 `Query`,你可以这样写:
```Python
-q: str = None
+q: str | None = None
```
比如:
-=== "Python 3.10+"
-
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="28"
- {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="25"
- {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}
- ```Python hl_lines="27"
- {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
- ```
+/// info | 信息
-!!! info
- `Body` 同样具有与 `Query`、`Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。
+`Body` 同样具有与 `Query`、`Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。
+///
-## 嵌入单个请求体参数
+## 嵌入单个请求体参数 { #embed-a-single-body-parameter }
假设你只有一个来自 Pydantic 模型 `Item` 的请求体参数 `item`。
@@ -235,41 +128,7 @@ item: Item = Body(embed=True)
比如:
-=== "Python 3.10+"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="17"
- {!> ../../../docs_src/body_multiple_params/tutorial005.py!}
- ```
+{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}
在这种情况下,**FastAPI** 将期望像这样的请求体:
@@ -295,7 +154,7 @@ item: Item = Body(embed=True)
}
```
-## 总结
+## 总结 { #recap }
你可以添加多个请求体参数到*路径操作函数*中,即使一个请求只能有一个请求体。
diff --git a/docs/zh/docs/tutorial/body-nested-models.md b/docs/zh/docs/tutorial/body-nested-models.md
index 7704d26248c06..93a34da5534b6 100644
--- a/docs/zh/docs/tutorial/body-nested-models.md
+++ b/docs/zh/docs/tutorial/body-nested-models.md
@@ -1,99 +1,44 @@
-# 请求体 - 嵌套模型
+# 请求体 - 嵌套模型 { #body-nested-models }
使用 **FastAPI**,你可以定义、校验、记录文档并使用任意深度嵌套的模型(归功于Pydantic)。
-## List 字段
+## List 字段 { #list-fields }
-你可以将一个属性定义为拥有子元素的类型。例如 Python `list`:
+你可以将一个属性定义为一个子类型。例如,Python `list`:
-=== "Python 3.10+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial001.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}
这将使 `tags` 成为一个由元素组成的列表。不过它没有声明每个元素的类型。
-## 具有子类型的 List 字段
-
-但是 Python 有一种特定的方法来声明具有子类型的列表:
-
-### 从 typing 导入 `List`
-
-首先,从 Python 的标准库 `typing` 模块中导入 `List`:
+## 带类型参数的 List 字段 { #list-fields-with-type-parameter }
-```Python hl_lines="1"
-{!> ../../../docs_src/body_nested_models/tutorial002.py!}
-```
-
-### 声明具有子类型的 List
+不过,Python 有一种用于声明具有内部类型(类型参数)的列表的特定方式:
-要声明具有子类型的类型,例如 `list`、`dict`、`tuple`:
+### 声明带类型参数的 `list` { #declare-a-list-with-a-type-parameter }
-* 从 `typing` 模块导入它们
-* 使用方括号 `[` 和 `]` 将子类型作为「类型参数」传入
+要声明具有类型参数(内部类型)的类型,例如 `list`、`dict`、`tuple`,使用方括号 `[` 和 `]` 传入内部类型作为「类型参数」:
```Python
-from typing import List
-
-my_list: List[str]
+my_list: list[str]
```
这完全是用于类型声明的标准 Python 语法。
-对具有子类型的模型属性也使用相同的标准语法。
+对具有内部类型的模型属性也使用相同的标准语法。
因此,在我们的示例中,我们可以将 `tags` 明确地指定为一个「字符串列表」:
-=== "Python 3.10+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}
-=== "Python 3.6+"
-
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial002.py!}
- ```
-
-## Set 类型
+## Set 类型 { #set-types }
但是随后我们考虑了一下,意识到标签不应该重复,它们很大可能会是唯一的字符串。
-Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `set`。
-
-然后我们可以导入 `Set` 并将 `tag` 声明为一个由 `str` 组成的 `set`:
-
-=== "Python 3.10+"
-
- ```Python hl_lines="12"
- {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!}
- ```
-
-=== "Python 3.9+"
+而 Python 有一种用于保存唯一元素集合的特殊数据类型 `set`。
- ```Python hl_lines="14"
- {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!}
- ```
+然后我们可以将 `tags` 声明为一个由字符串组成的 set:
-=== "Python 3.6+"
-
- ```Python hl_lines="1 14"
- {!> ../../../docs_src/body_nested_models/tutorial003.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}
这样,即使你收到带有重复数据的请求,这些数据也会被转换为一组唯一项。
@@ -101,7 +46,7 @@ Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `se
并且还会被相应地标注 / 记录文档。
-## 嵌套模型
+## 嵌套模型 { #nested-models }
Pydantic 模型的每个属性都具有类型。
@@ -111,49 +56,17 @@ Pydantic 模型的每个属性都具有类型。
上述这些都可以任意的嵌套。
-### 定义子模型
+### 定义子模型 { #define-a-submodel }
例如,我们可以定义一个 `Image` 模型:
-=== "Python 3.10+"
-
- ```Python hl_lines="7-9"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
-
-=== "Python 3.6+"
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}
- ```Python hl_lines="9-11"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
-
-### 将子模型用作类型
+### 将子模型用作类型 { #use-the-submodel-as-a-type }
然后我们可以将其用作一个属性的类型:
-=== "Python 3.10+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial004.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}
这意味着 **FastAPI** 将期望类似于以下内容的请求体:
@@ -178,55 +91,23 @@ Pydantic 模型的每个属性都具有类型。
* 数据校验
* 自动生成文档
-## 特殊的类型和校验
+## 特殊的类型和校验 { #special-types-and-validation }
除了普通的单一值类型(如 `str`、`int`、`float` 等)外,你还可以使用从 `str` 继承的更复杂的单一值类型。
-要了解所有的可用选项,请查看关于 来自 Pydantic 的外部类型 的文档。你将在下一章节中看到一些示例。
+要了解所有的可用选项,请查看 [Pydantic 的类型概览](https://docs.pydantic.dev/latest/concepts/types/)。你将在下一章节中看到一些示例。
例如,在 `Image` 模型中我们有一个 `url` 字段,我们可以把它声明为 Pydantic 的 `HttpUrl`,而不是 `str`:
-=== "Python 3.10+"
-
- ```Python hl_lines="2 8"
- {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="4 10"
- {!> ../../../docs_src/body_nested_models/tutorial005.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}
该字符串将被检查是否为有效的 URL,并在 JSON Schema / OpenAPI 文档中进行记录。
-## 带有一组子模型的属性
+## 带有一组子模型的属性 { #attributes-with-lists-of-submodels }
你还可以将 Pydantic 模型用作 `list`、`set` 等的子类型:
-=== "Python 3.10+"
-
- ```Python hl_lines="18"
- {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="20"
- {!> ../../../docs_src/body_nested_models/tutorial006.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}
这将期望(转换,校验,记录文档等)下面这样的 JSON 请求体:
@@ -254,69 +135,49 @@ Pydantic 模型的每个属性都具有类型。
}
```
-!!! info
- 请注意 `images` 键现在具有一组 image 对象是如何发生的。
-
-## 深度嵌套模型
+/// info | 信息
-你可以定义任意深度的嵌套模型:
+请注意 `images` 键现在具有一组 image 对象是如何发生的。
-=== "Python 3.10+"
+///
- ```Python hl_lines="7 12 18 21 25"
- {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!}
- ```
+## 深度嵌套模型 { #deeply-nested-models }
-=== "Python 3.9+"
+你可以定义任意深度的嵌套模型:
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}
-=== "Python 3.6+"
+/// info | 信息
- ```Python hl_lines="9 14 20 23 27"
- {!> ../../../docs_src/body_nested_models/tutorial007.py!}
- ```
+请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。
-!!! info
- 请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。
+///
-## 纯列表请求体
+## 纯列表请求体 { #bodies-of-pure-lists }
如果你期望的 JSON 请求体的最外层是一个 JSON `array`(即 Python `list`),则可以在路径操作函数的参数中声明此类型,就像声明 Pydantic 模型一样:
```Python
-images: List[Image]
+images: list[Image]
```
例如:
-=== "Python 3.9+"
-
- ```Python hl_lines="13"
- {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!}
- ```
-
-=== "Python 3.6+"
+{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *}
- ```Python hl_lines="15"
- {!> ../../../docs_src/body_nested_models/tutorial008.py!}
- ```
-
-## 无处不在的编辑器支持
+## 无处不在的编辑器支持 { #editor-support-everywhere }
你可以随处获得编辑器支持。
即使是列表中的元素:
-
+
如果你直接使用 `dict` 而不是 Pydantic 模型,那你将无法获得这种编辑器支持。
但是你根本不必担心这两者,传入的字典会自动被转换,你的输出也会自动被转换为 JSON。
-## 任意 `dict` 构成的请求体
+## 任意 `dict` 构成的请求体 { #bodies-of-arbitrary-dicts }
你也可以将请求体声明为使用某类型的键和其他类型值的 `dict`。
@@ -332,28 +193,21 @@ images: List[Image]
在下面的例子中,你将接受任意键为 `int` 类型并且值为 `float` 类型的 `dict`:
-=== "Python 3.9+"
-
- ```Python hl_lines="7"
- {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!}
- ```
+{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *}
-=== "Python 3.6+"
+/// tip | 提示
- ```Python hl_lines="9"
- {!> ../../../docs_src/body_nested_models/tutorial009.py!}
- ```
+请记住 JSON 仅支持将 `str` 作为键。
-!!! tip
- 请记住 JSON 仅支持将 `str` 作为键。
+但是 Pydantic 具有自动转换数据的功能。
- 但是 Pydantic 具有自动转换数据的功能。
+这意味着,即使你的 API 客户端只能将字符串作为键发送,只要这些字符串内容仅包含整数,Pydantic 就会对其进行转换并校验。
- 这意味着,即使你的 API 客户端只能将字符串作为键发送,只要这些字符串内容仅包含整数,Pydantic 就会对其进行转换并校验。
+然后你接收的名为 `weights` 的 `dict` 实际上将具有 `int` 类型的键和 `float` 类型的值。
- 然后你接收的名为 `weights` 的 `dict` 实际上将具有 `int` 类型的键和 `float` 类型的值。
+///
-## 总结
+## 总结 { #recap }
使用 **FastAPI** 你可以拥有 Pydantic 模型提供的极高灵活性,同时保持代码的简单、简短和优雅。
diff --git a/docs/zh/docs/tutorial/body-updates.md b/docs/zh/docs/tutorial/body-updates.md
index 43f20f8fcbd9c..5b181642cbc46 100644
--- a/docs/zh/docs/tutorial/body-updates.md
+++ b/docs/zh/docs/tutorial/body-updates.md
@@ -1,20 +1,18 @@
-# 请求体 - 更新数据
+# 请求体 - 更新数据 { #body-updates }
-## 用 `PUT` 更新数据
+## 用 `PUT` 替换式更新 { #update-replacing-with-put }
-更新数据请用 HTTP `PUT` 操作。
+更新数据可以使用 [HTTP `PUT`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) 操作。
把输入数据转换为以 JSON 格式存储的数据(比如,使用 NoSQL 数据库时),可以使用 `jsonable_encoder`。例如,把 `datetime` 转换为 `str`。
-```Python hl_lines="30-35"
-{!../../../docs_src/body_updates/tutorial001.py!}
-```
+{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}
`PUT` 用于接收替换现有数据的数据。
-### 关于更新数据的警告
+### 关于替换的警告 { #warning-about-replacing }
-用 `PUT` 把数据项 `bar` 更新为以下内容时:
+用 `PUT` 把数据项 `bar` 更新为以下请求体时:
```Python
{
@@ -24,78 +22,79 @@
}
```
-因为上述数据未包含已存储的属性 `"tax": 20.2`,新的输入模型会把 `"tax": 10.5` 作为默认值。
+因为其中未包含已存储的属性 `"tax": 20.2`,输入模型会取 `"tax": 10.5` 的默认值。
-因此,本次操作把 `tax` 的值「更新」为 `10.5`。
+因此,保存的数据会带有这个“新的” `tax` 值 `10.5`。
-## 用 `PATCH` 进行部分更新
+## 用 `PATCH` 进行部分更新 { #partial-updates-with-patch }
-HTTP `PATCH` 操作用于更新 *部分* 数据。
+也可以使用 [HTTP `PATCH`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) 操作对数据进行*部分*更新。
-即,只发送要更新的数据,其余数据保持不变。
+也就是说,你只需发送想要更新的数据,其余数据保持不变。
-!!! Note "笔记"
+/// note | 注意
- `PATCH` 没有 `PUT` 知名,也怎么不常用。
+`PATCH` 没有 `PUT` 知名,也没那么常用。
- 很多人甚至只用 `PUT` 实现部分更新。
+很多团队甚至只用 `PUT` 实现部分更新。
- **FastAPI** 对此没有任何限制,可以**随意**互换使用这两种操作。
+你可以**随意**选择如何使用它们,**FastAPI** 不做任何限制。
- 但本指南也会分别介绍这两种操作各自的用途。
+但本指南会大致展示它们的预期用法。
-### 使用 Pydantic 的 `exclude_unset` 参数
+///
-更新部分数据时,可以在 Pydantic 模型的 `.dict()` 中使用 `exclude_unset` 参数。
+### 使用 Pydantic 的 `exclude_unset` 参数 { #using-pydantics-exclude-unset-parameter }
-比如,`item.dict(exclude_unset=True)`。
+如果要接收部分更新,建议在 Pydantic 模型的 `.model_dump()` 中使用 `exclude_unset` 参数。
-这段代码生成的 `dict` 只包含创建 `item` 模型时显式设置的数据,而不包括默认值。
+比如,`item.model_dump(exclude_unset=True)`。
-然后再用它生成一个只含已设置(在请求中所发送)数据,且省略了默认值的 `dict`:
+这会生成一个 `dict`,只包含创建 `item` 模型时显式设置的数据,不包含默认值。
-```Python hl_lines="34"
-{!../../../docs_src/body_updates/tutorial002.py!}
-```
+然后再用它生成一个只含已设置(在请求中发送)数据、且省略默认值的 `dict`:
-### 使用 Pydantic 的 `update` 参数
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}
-接下来,用 `.copy()` 为已有模型创建调用 `update` 参数的副本,该参数为包含更新数据的 `dict`。
+### 使用 Pydantic 的 `update` 参数 { #using-pydantics-update-parameter }
-例如,`stored_item_model.copy(update=update_data)`:
+接下来,用 `.model_copy()` 为已有模型创建副本,并传入 `update` 参数,值为包含更新数据的 `dict`。
-```Python hl_lines="35"
-{!../../../docs_src/body_updates/tutorial002.py!}
-```
+例如,`stored_item_model.model_copy(update=update_data)`:
+
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}
-### 更新部分数据小结
+### 部分更新小结 { #partial-updates-recap }
-简而言之,更新部分数据应:
+简而言之,应用部分更新应当:
-* 使用 `PATCH` 而不是 `PUT` (可选,也可以用 `PUT`);
-* 提取存储的数据;
-* 把数据放入 Pydantic 模型;
-* 生成不含输入模型默认值的 `dict` (使用 `exclude_unset` 参数);
- * 只更新用户设置过的值,不用模型中的默认值覆盖已存储过的值。
-* 为已存储的模型创建副本,用接收的数据更新其属性 (使用 `update` 参数)。
+* (可选)使用 `PATCH` 而不是 `PUT`。
+* 提取已存储的数据。
+* 把该数据放入 Pydantic 模型。
+* 生成不含输入模型默认值的 `dict`(使用 `exclude_unset`)。
+ * 这样只会更新用户实际设置的值,而不会用模型中的默认值覆盖已存储的值。
+* 为已存储的模型创建副本,用接收到的部分更新数据更新其属性(使用 `update` 参数)。
* 把模型副本转换为可存入数据库的形式(比如,使用 `jsonable_encoder`)。
- * 这种方式与 Pydantic 模型的 `.dict()` 方法类似,但能确保把值转换为适配 JSON 的数据类型,例如, 把 `datetime` 转换为 `str` 。
-* 把数据保存至数据库;
+ * 这类似于再次调用模型的 `.model_dump()` 方法,但会确保(并转换)值为可转换为 JSON 的数据类型,例如把 `datetime` 转换为 `str`。
+* 把数据保存至数据库。
* 返回更新后的模型。
-```Python hl_lines="30-37"
-{!../../../docs_src/body_updates/tutorial002.py!}
-```
+{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *}
+
+/// tip | 提示
+
+实际上,HTTP `PUT` 也可以使用同样的技巧。
+
+但这里用 `PATCH` 举例,因为它就是为这种用例设计的。
-!!! tip "提示"
+///
- 实际上,HTTP `PUT` 也可以完成相同的操作。
- 但本节以 `PATCH` 为例的原因是,该操作就是为了这种用例创建的。
+/// note | 注意
-!!! note "笔记"
+注意,输入模型仍会被验证。
- 注意,输入模型仍需验证。
+因此,如果希望接收的部分更新可以省略所有属性,则需要一个所有属性都标记为可选(带默认值或 `None`)的模型。
- 因此,如果希望接收的部分更新数据可以省略其他所有属性,则要把模型中所有的属性标记为可选(使用默认值或 `None`)。
+为了区分用于**更新**(全部可选)和用于**创建**(必填)的模型,可以参考[更多模型](extra-models.md) 中介绍的思路。
- 为了区分用于**更新**所有可选值的模型与用于**创建**包含必选值的模型,请参照[更多模型](extra-models.md){.internal-link target=_blank} 一节中的思路。
+///
diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md
index d00c96dc3a81c..0a4c9c5e53111 100644
--- a/docs/zh/docs/tutorial/body.md
+++ b/docs/zh/docs/tutorial/body.md
@@ -1,55 +1,40 @@
-# 请求体
+# 请求体 { #request-body }
-当你需要将数据从客户端(例如浏览器)发送给 API 时,你将其作为「请求体」发送。
+当你需要从客户端(比如浏览器)向你的 API 发送数据时,会把它作为**请求体**发送。
-**请求**体是客户端发送给 API 的数据。**响应**体是 API 发送给客户端的数据。
+**请求体**是客户端发送给你的 API 的数据。**响应体**是你的 API 发送给客户端的数据。
-你的 API 几乎总是要发送**响应**体。但是客户端并不总是需要发送**请求**体。
+你的 API 几乎总是需要发送**响应体**。但客户端不一定总是要发送**请求体**,有时它们只请求某个路径,可能带一些查询参数,但不会发送请求体。
-我们使用 Pydantic 模型来声明**请求**体,并能够获得它们所具有的所有能力和优点。
+使用 [Pydantic](https://docs.pydantic.dev/) 模型来声明**请求体**,能充分利用它的功能和优点。
-!!! info
- 你不能使用 `GET` 操作(HTTP 方法)发送请求体。
+/// info | 信息
- 要发送数据,你必须使用下列方法之一:`POST`(较常见)、`PUT`、`DELETE` 或 `PATCH`。
+发送数据应使用以下之一:`POST`(最常见)、`PUT`、`DELETE` 或 `PATCH`。
-## 导入 Pydantic 的 `BaseModel`
+规范中没有定义用 `GET` 请求发送请求体的行为,但 FastAPI 仍支持这种方式,只用于非常复杂/极端的用例。
-首先,你需要从 `pydantic` 中导入 `BaseModel`:
+由于不推荐,在使用 `GET` 时,Swagger UI 的交互式文档不会显示请求体的文档,而且中间的代理可能也不支持它。
-=== "Python 3.10+"
+///
- ```Python hl_lines="2"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+## 导入 Pydantic 的 `BaseModel` { #import-pydantics-basemodel }
-=== "Python 3.6+"
+从 `pydantic` 中导入 `BaseModel`:
- ```Python hl_lines="4"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+{* ../../docs_src/body/tutorial001_py310.py hl[2] *}
-## 创建数据模型
+## 创建数据模型 { #create-your-data-model }
-然后,将你的数据模型声明为继承自 `BaseModel` 的类。
+把数据模型声明为继承 `BaseModel` 的类。
-使用标准的 Python 类型来声明所有属性:
+使用 Python 标准类型声明所有属性:
-=== "Python 3.10+"
+{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}
- ```Python hl_lines="5-9"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+与声明查询参数一样,包含默认值的模型属性是可选的,否则就是必选的。把默认值设为 `None` 可使其变为可选。
-=== "Python 3.6+"
-
- ```Python hl_lines="7-11"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
-
-和声明查询参数时一样,当一个模型属性具有默认值时,它不是必需的。否则它是一个必需属性。将默认值设为 `None` 可使其成为可选属性。
-
-例如,上面的模型声明了一个这样的 JSON「`object`」(或 Python `dict`):
+例如,上述模型声明如下 JSON "object"(即 Python `dict`):
```JSON
{
@@ -60,7 +45,7 @@
}
```
-...由于 `description` 和 `tax` 是可选的(它们的默认值为 `None`),下面的 JSON「`object`」也将是有效的:
+...由于 `description` 和 `tax` 是可选的(默认值为 `None`),下面的 JSON "object" 也有效:
```JSON
{
@@ -69,127 +54,111 @@
}
```
-## 声明为参数
-
-使用与声明路径和查询参数的相同方式声明请求体,即可将其添加到「路径操作」中:
+## 声明为参数 { #declare-it-as-a-parameter }
-=== "Python 3.10+"
+使用与声明路径和查询参数相同的方式,把它添加至*路径操作*:
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial001_py310.py!}
- ```
+{* ../../docs_src/body/tutorial001_py310.py hl[16] *}
-=== "Python 3.6+"
+...并把其类型声明为你创建的模型 `Item`。
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial001.py!}
- ```
+## 结果 { #results }
-...并且将它的类型声明为你创建的 `Item` 模型。
+仅使用这些 Python 类型声明,**FastAPI** 就可以:
-## 结果
-
-仅仅使用了 Python 类型声明,**FastAPI** 将会:
-
-* 将请求体作为 JSON 读取。
-* 转换为相应的类型(在需要时)。
+* 以 JSON 形式读取请求体。
+* (在必要时)把请求体转换为对应的类型。
* 校验数据。
- * 如果数据无效,将返回一条清晰易读的错误信息,指出不正确数据的确切位置和内容。
-* 将接收的数据赋值到参数 `item` 中。
- * 由于你已经在函数中将它声明为 `Item` 类型,你还将获得对于所有属性及其类型的一切编辑器支持(代码补全等)。
-* 为你的模型生成 JSON 模式 定义,你还可以在其他任何对你的项目有意义的地方使用它们。
-* 这些模式将成为生成的 OpenAPI 模式的一部分,并且被自动化文档 UI 所使用。
+ * 数据无效时返回清晰的错误信息,并指出错误数据的确切位置和内容。
+* 把接收的数据赋值给参数 `item`。
+ * 因为你把函数中的参数类型声明为 `Item`,所以还能获得所有属性及其类型的编辑器支持(补全等)。
+* 为你的模型生成 [JSON Schema](https://json-schema.org) 定义,如果对你的项目有意义,还可以在其他地方使用它们。
+* 这些 schema 会成为生成的 OpenAPI Schema 的一部分,并被自动文档的 UIs 使用。
+
+## 自动文档 { #automatic-docs }
-## 自动化文档
+你的模型的 JSON Schema 会成为生成的 OpenAPI Schema 的一部分,并显示在交互式 API 文档中:
-你所定义模型的 JSON 模式将成为生成的 OpenAPI 模式的一部分,并且在交互式 API 文档中展示:
+
-
+并且,还会用于需要它们的每个*路径操作*的 API 文档中:
-而且还将在每一个需要它们的*路径操作*的 API 文档中使用:
+
-
+## 编辑器支持 { #editor-support }
-## 编辑器支持
+在编辑器中,函数内部你会在各处得到类型提示与补全(如果接收的不是 Pydantic 模型,而是 `dict`,就不会有这样的支持):
-在你的编辑器中,你会在函数内部的任意地方得到类型提示和代码补全(如果你接收的是一个 `dict` 而不是 Pydantic 模型,则不会发生这种情况):
+
-
+还支持检查错误的类型操作:
-你还会获得对不正确的类型操作的错误检查:
+
-
+这并非偶然,整个框架都是围绕这种设计构建的。
-这并非偶然,整个框架都是围绕该设计而构建。
+并且在设计阶段、实现之前就进行了全面测试,以确保它能在所有编辑器中正常工作。
-并且在进行任何实现之前,已经在设计阶段经过了全面测试,以确保它可以在所有的编辑器中生效。
+我们甚至对 Pydantic 本身做了一些改动以支持这些功能。
-Pydantic 本身甚至也进行了一些更改以支持此功能。
+上面的截图来自 [Visual Studio Code](https://code.visualstudio.com)。
-上面的截图取自 Visual Studio Code。
+但使用 [PyCharm](https://www.jetbrains.com/pycharm/) 和大多数其他 Python 编辑器,你也会获得相同的编辑器支持:
-但是在 PyCharm 和绝大多数其他 Python 编辑器中你也会获得同样的编辑器支持:
+
-
+/// tip | 提示
-## 使用模型
+如果你使用 [PyCharm](https://www.jetbrains.com/pycharm/) 作为编辑器,可以使用 [Pydantic PyCharm 插件](https://github.com/koxudaxi/pydantic-pycharm-plugin/)。
-在函数内部,你可以直接访问模型对象的所有属性:
+它能改进对 Pydantic 模型的编辑器支持,包括:
-=== "Python 3.10+"
+* 自动补全
+* 类型检查
+* 代码重构
+* 查找
+* 代码审查
- ```Python hl_lines="19"
- {!> ../../../docs_src/body/tutorial002_py310.py!}
- ```
+///
-=== "Python 3.6+"
+## 使用模型 { #use-the-model }
- ```Python hl_lines="21"
- {!> ../../../docs_src/body/tutorial002.py!}
- ```
+在*路径操作*函数内部直接访问模型对象的所有属性:
-## 请求体 + 路径参数
+{* ../../docs_src/body/tutorial002_py310.py *}
-你可以同时声明路径参数和请求体。
+## 请求体 + 路径参数 { #request-body-path-parameters }
-**FastAPI** 将识别出与路径参数匹配的函数参数应**从路径中获取**,而声明为 Pydantic 模型的函数参数应**从请求体中获取**。
+可以同时声明路径参数和请求体。
-=== "Python 3.10+"
+**FastAPI** 能识别与**路径参数**匹配的函数参数应该**从路径中获取**,而声明为 Pydantic 模型的函数参数应该**从请求体中获取**。
- ```Python hl_lines="15-16"
- {!> ../../../docs_src/body/tutorial003_py310.py!}
- ```
+{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}
-=== "Python 3.6+"
+## 请求体 + 路径 + 查询参数 { #request-body-path-query-parameters }
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/body/tutorial003.py!}
- ```
+也可以同时声明**请求体**、**路径**和**查询**参数。
-## 请求体 + 路径参数 + 查询参数
+**FastAPI** 会分别识别它们,并从正确的位置获取数据。
-你还可以同时声明**请求体**、**路径参数**和**查询参数**。
+{* ../../docs_src/body/tutorial004_py310.py hl[16] *}
-**FastAPI** 会识别它们中的每一个,并从正确的位置获取数据。
+函数参数按如下规则进行识别:
-=== "Python 3.10+"
+* 如果该参数也在**路径**中声明了,它就是路径参数。
+* 如果该参数是(`int`、`float`、`str`、`bool` 等)**单一类型**,它会被当作**查询**参数。
+* 如果该参数的类型声明为 **Pydantic 模型**,它会被当作请求**体**。
- ```Python hl_lines="16"
- {!> ../../../docs_src/body/tutorial004_py310.py!}
- ```
+/// note | 注意
-=== "Python 3.6+"
+FastAPI 会根据默认值 `= None` 知道 `q` 的值不是必填的。
- ```Python hl_lines="18"
- {!> ../../../docs_src/body/tutorial004.py!}
- ```
+`str | None` 并不是 FastAPI 用来判断是否必填的依据;是否必填由是否有默认值 `= None` 决定。
-函数参数将依次按如下规则进行识别:
+但添加这些类型注解可以让你的编辑器提供更好的支持并检测错误。
-* 如果在**路径**中也声明了该参数,它将被用作路径参数。
-* 如果参数属于**单一类型**(比如 `int`、`float`、`str`、`bool` 等)它将被解释为**查询**参数。
-* 如果参数的类型被声明为一个 **Pydantic 模型**,它将被解释为**请求体**。
+///
-## 不使用 Pydantic
+## 不使用 Pydantic { #without-pydantic }
-如果你不想使用 Pydantic 模型,你还可以使用 **Body** 参数。请参阅文档 [请求体 - 多个参数:请求体中的单一值](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}。
+即便不使用 Pydantic 模型也能使用 **Body** 参数。详见[请求体 - 多参数:请求体中的单值](body-multiple-params.md#singular-values-in-body)。
diff --git a/docs/zh/docs/tutorial/cookie-param-models.md b/docs/zh/docs/tutorial/cookie-param-models.md
new file mode 100644
index 0000000000000..8e094c7d3ffa6
--- /dev/null
+++ b/docs/zh/docs/tutorial/cookie-param-models.md
@@ -0,0 +1,76 @@
+# Cookie 参数模型 { #cookie-parameter-models }
+
+如果您有一组相关的 **cookie**,您可以创建一个 **Pydantic 模型**来声明它们。🍪
+
+这将允许您在**多个地方**能够**重用模型**,并且可以一次性声明所有参数的验证方式和元数据。😎
+
+/// note | 注意
+
+自 FastAPI 版本 `0.115.0` 起支持此功能。🤓
+
+///
+
+/// tip | 提示
+
+此技术同样适用于 `Query` 、 `Cookie` 和 `Header` 。😎
+
+///
+
+## 带有 Pydantic 模型的 Cookie { #cookies-with-a-pydantic-model }
+
+在 **Pydantic** 模型中声明所需的 **cookie** 参数,然后将参数声明为 `Cookie` :
+
+{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}
+
+**FastAPI** 将从请求中接收到的 **cookie** 中**提取**出**每个字段**的数据,并提供您定义的 Pydantic 模型。
+
+## 查看文档 { #check-the-docs }
+
+您可以在文档 UI 的 `/docs` 中查看定义的 cookie:
+
+
+
-## 快捷方式
+## 快捷方式 { #shortcut }
-但是您可以看到,我们在这里有一些代码重复了,编写了`CommonQueryParams`两次:
+但是你可以看到,我们在这里有一些代码重复了,编写了`CommonQueryParams`两次:
+
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ 未使用 Annotated
+
+/// tip | 提示
+
+尽可能使用 `Annotated` 版本。
+
+///
```Python
commons: CommonQueryParams = Depends(CommonQueryParams)
```
+////
+
**FastAPI** 为这些情况提供了一个快捷方式,在这些情况下,依赖项 *明确地* 是一个类,**FastAPI** 将 "调用" 它来创建类本身的一个实例。
-对于这些特定的情况,您可以跟随以下操作:
+对于这些特定的情况,你可以按如下操作:
不是写成这样:
+//// tab | Python 3.10+
+
+```Python
+commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]
+```
+
+////
+
+//// tab | Python 3.10+ 未使用 Annotated
+
+/// tip | 提示
+
+尽可能使用 `Annotated` 版本。
+
+///
+
```Python
commons: CommonQueryParams = Depends(CommonQueryParams)
```
+////
+
...而是这样写:
+//// tab | Python 3.10+
+
```Python
-commons: CommonQueryParams = Depends()
+commons: Annotated[CommonQueryParams, Depends()]
```
-您声明依赖项作为参数的类型,并使用 `Depends()` 作为该函数的参数的 "默认" 值(在 `=` 之后),而在 `Depends()` 中没有任何参数,而不是在 `Depends(CommonQueryParams)` 编写完整的类。
+////
-同样的例子看起来像这样:
+//// tab | Python 3.10+ 未使用 Annotated
-=== "Python 3.10+"
+/// tip | 提示
- ```Python hl_lines="17"
- {!> ../../../docs_src/dependencies/tutorial004_py310.py!}
- ```
+尽可能使用 `Annotated` 版本。
-=== "Python 3.6+"
+///
- ```Python hl_lines="19"
- {!> ../../../docs_src/dependencies/tutorial004.py!}
- ```
+```Python
+commons: CommonQueryParams = Depends()
+```
+
+////
+
+你声明依赖项作为参数的类型,并使用 `Depends()` 作为该函数的参数的 "默认" 值(在 `=` 之后),而在 `Depends()` 中没有任何参数,而不是在 `Depends(CommonQueryParams)` 中*再次*编写完整的类。
+
+同样的例子看起来像这样:
+
+{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *}
... **FastAPI** 会知道怎么处理。
-!!! tip
- 如果这看起来更加混乱而不是更加有帮助,那么请忽略它,你不*需要*它。
+/// tip | 提示
+
+如果这看起来更加混乱而不是更加有帮助,那么请忽略它,你不*需要*它。
+
+这只是一个快捷方式。因为 **FastAPI** 关心的是帮助你减少代码重复。
- 这只是一个快捷方式。因为 **FastAPI** 关心的是帮助您减少代码重复。
+///
diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
index 61ea371e5453e..a3b2e6a41e261 100644
--- a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
+++ b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md
@@ -1,4 +1,4 @@
-# 路径操作装饰器依赖项
+# 路径操作装饰器依赖项 { #dependencies-in-path-operation-decorators }
有时,我们并不需要在*路径操作函数*中使用依赖项的返回值。
@@ -8,66 +8,62 @@
对于这种情况,不必在声明*路径操作函数*的参数时使用 `Depends`,而是可以在*路径操作装饰器*中添加一个由 `dependencies` 组成的 `list`。
-## 在*路径操作装饰器*中添加 `dependencies` 参数
+## 在*路径操作装饰器*中添加 `dependencies` 参数 { #add-dependencies-to-the-path-operation-decorator }
-*路径操作装饰器*支持可选参数 ~ `dependencies`。
+*路径操作装饰器*支持可选参数 `dependencies`。
该参数的值是由 `Depends()` 组成的 `list`:
-```Python hl_lines="17"
-{!../../../docs_src/dependencies/tutorial006.py!}
-```
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *}
-路径操作装饰器依赖项(以下简称为**“路径装饰器依赖项”**)的执行或解析方式和普通依赖项一样,但就算这些依赖项会返回值,它们的值也不会传递给*路径操作函数*。
+路径操作装饰器依赖项的执行或解析方式和普通依赖项一样,但就算这些依赖项会返回值,它们的值也不会传递给*路径操作函数*。
-!!! tip "提示"
+/// tip | 提示
- 有些编辑器会检查代码中没使用过的函数参数,并显示错误提示。
+有些编辑器会检查代码中没使用过的函数参数,并显示错误提示。
- 在*路径操作装饰器*中使用 `dependencies` 参数,可以确保在执行依赖项的同时,避免编辑器显示错误提示。
+在*路径操作装饰器*中使用 `dependencies` 参数,可以确保在执行依赖项的同时,避免编辑器/工具报错。
- 使用路径装饰器依赖项还可以避免开发新人误会代码中包含无用的未使用参数。
+使用路径装饰器依赖项还可以避免开发新人误会代码中包含无用的未使用参数。
-!!! info "说明"
+///
- 本例中,使用的是自定义响应头 `X-Key` 和 `X-Token`。
+/// info | 信息
- 但实际开发中,尤其是在实现安全措施时,最好使用 FastAPI 内置的[安全工具](../security/index.md){.internal-link target=_blank}(详见下一章)。
+本例中,使用的是自定义响应头 `X-Key` 和 `X-Token`。
-## 依赖项错误和返回值
+但实际开发中,尤其是在实现安全措施时,最好使用 FastAPI 内置的[安全工具(下一章)](../security/index.md)。
+
+///
+
+## 依赖项错误和返回值 { #dependencies-errors-and-return-values }
路径装饰器依赖项也可以使用普通的依赖项*函数*。
-### 依赖项的需求项
+### 依赖项的需求项 { #dependency-requirements }
路径装饰器依赖项可以声明请求的需求项(比如响应头)或其他子依赖项:
-```Python hl_lines="6 11"
-{!../../../docs_src/dependencies/tutorial006.py!}
-```
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *}
-### 触发异常
+### 触发异常 { #raise-exceptions }
路径装饰器依赖项与正常的依赖项一样,可以 `raise` 异常:
-```Python hl_lines="8 13"
-{!../../../docs_src/dependencies/tutorial006.py!}
-```
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *}
-### 返回值
+### 返回值 { #return-values }
无论路径装饰器依赖项是否返回值,路径操作都不会使用这些值。
因此,可以复用在其他位置使用过的、(能返回值的)普通依赖项,即使没有使用这个值,也会执行该依赖项:
-```Python hl_lines="9 14"
-{!../../../docs_src/dependencies/tutorial006.py!}
-```
+{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *}
-## 为一组路径操作定义依赖项
+## 为一组路径操作定义依赖项 { #dependencies-for-a-group-of-path-operations }
-稍后,[大型应用 - 多文件](../../tutorial/bigger-applications.md){.internal-link target=\_blank}一章中会介绍如何使用多个文件创建大型应用程序,在这一章中,您将了解到如何为一组*路径操作*声明单个 `dependencies` 参数。
+稍后,[大型应用 - 多文件](../../tutorial/bigger-applications.md)一章中会介绍如何使用多个文件创建大型应用程序,在这一章中,您将了解到如何为一组*路径操作*声明单个 `dependencies` 参数。
-## 全局依赖项
+## 全局依赖项 { #global-dependencies }
接下来,我们将学习如何为 `FastAPI` 应用程序添加全局依赖项,创建应用于每个*路径操作*的依赖项。
diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md
new file mode 100644
index 0000000000000..a365bccf04313
--- /dev/null
+++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md
@@ -0,0 +1,287 @@
+# 使用 yield 的依赖项 { #dependencies-with-yield }
+
+FastAPI 支持那些在完成后执行一些额外步骤的依赖项。
+
+为此,使用 `yield` 而不是 `return`,并把这些额外步骤(代码)写在后面。
+
+/// tip | 提示
+
+确保在每个依赖里只使用一次 `yield`。
+
+///
+
+/// note | 技术细节
+
+任何可以与以下装饰器一起使用的函数:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) 或
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+都可以作为 **FastAPI** 的依赖项。
+
+实际上,FastAPI 在内部就是用的这两个装饰器。
+
+///
+
+## 使用 `yield` 的数据库依赖项 { #a-database-dependency-with-yield }
+
+例如,你可以用这种方式创建一个数据库会话,并在完成后将其关闭。
+
+在创建响应之前,只会执行 `yield` 语句及其之前的代码:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *}
+
+`yield` 产生的值会注入到 *路径操作* 和其他依赖项中:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *}
+
+`yield` 语句后面的代码会在响应之后执行:
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *}
+
+/// tip | 提示
+
+你可以使用 `async` 或普通函数。
+
+**FastAPI** 会像处理普通依赖一样对它们进行正确处理。
+
+///
+
+## 同时使用 `yield` 和 `try` 的依赖项 { #a-dependency-with-yield-and-try }
+
+如果你在带有 `yield` 的依赖中使用了 `try` 代码块,那么当使用该依赖时抛出的任何异常你都会收到。
+
+例如,如果在中间的某处代码中(在另一个依赖或在某个 *路径操作* 中)发生了数据库事务“回滚”或产生了其他异常,你会在你的依赖中收到这个异常。
+
+因此,你可以在该依赖中用 `except SomeException` 来捕获这个特定异常。
+
+同样地,你可以使用 `finally` 来确保退出步骤一定会被执行,无论是否发生异常。
+
+{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *}
+
+## 使用 `yield` 的子依赖项 { #sub-dependencies-with-yield }
+
+你可以声明任意大小和形状的子依赖及其“树”,其中任意一个或全部都可以使用 `yield`。
+
+**FastAPI** 会确保每个带有 `yield` 的依赖中的“退出代码”按正确的顺序运行。
+
+例如,`dependency_c` 可以依赖 `dependency_b`,而 `dependency_b` 则依赖 `dependency_a`:
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *}
+
+并且它们都可以使用 `yield`。
+
+在这种情况下,`dependency_c` 在执行其退出代码时需要 `dependency_b`(此处命名为 `dep_b`)的值仍然可用。
+
+而 `dependency_b` 又需要 `dependency_a`(此处命名为 `dep_a`)的值在其退出代码中可用。
+
+{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *}
+
+同样地,你可以将一些依赖用 `yield`,另一些用 `return`,并让其中一些依赖依赖于另一些。
+
+你也可以有一个依赖需要多个带有 `yield` 的依赖,等等。
+
+你可以拥有任何你想要的依赖组合。
+
+**FastAPI** 将确保一切都按正确的顺序运行。
+
+/// note | 技术细节
+
+这要归功于 Python 的[上下文管理器](https://docs.python.org/3/library/contextlib.html)。
+
+**FastAPI** 在内部使用它们来实现这一点。
+
+///
+
+## 同时使用 `yield` 和 `HTTPException` 的依赖项 { #dependencies-with-yield-and-httpexception }
+
+你已经看到可以在带有 `yield` 的依赖中使用 `try` 块尝试执行一些代码,然后在 `finally` 之后运行一些退出代码。
+
+你也可以使用 `except` 来捕获引发的异常并对其进行处理。
+
+例如,你可以抛出一个不同的异常,如 `HTTPException`。
+
+/// tip | 提示
+
+这是一种相对高级的技巧,在大多数情况下你并不需要使用它,因为你可以在应用的其他代码中(例如在 *路径操作函数* 里)抛出异常(包括 `HTTPException`)。
+
+但是如果你需要,它就在这里。🤓
+
+///
+
+{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *}
+
+如果你想捕获异常并基于它创建一个自定义响应,请创建一个[自定义异常处理器](../handling-errors.md#install-custom-exception-handlers)。
+
+## 同时使用 `yield` 和 `except` 的依赖项 { #dependencies-with-yield-and-except }
+
+如果你在带有 `yield` 的依赖中使用 `except` 捕获了一个异常,并且你没有再次抛出它(或抛出一个新异常),FastAPI 将无法察觉发生过异常,就像普通的 Python 代码那样:
+
+{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *}
+
+在这种情况下,客户端会像预期那样看到一个 *HTTP 500 Internal Server Error* 响应,因为我们没有抛出 `HTTPException` 或类似异常,但服务器将**没有任何日志**或其他关于错误是什么的提示。😱
+
+### 在带有 `yield` 和 `except` 的依赖中务必 `raise` { #always-raise-in-dependencies-with-yield-and-except }
+
+如果你在带有 `yield` 的依赖中捕获到了一个异常,除非你抛出另一个 `HTTPException` 或类似异常,**否则你应该重新抛出原始异常**。
+
+你可以使用 `raise` 重新抛出同一个异常:
+
+{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *}
+
+现在客户端仍会得到同样的 *HTTP 500 Internal Server Error* 响应,但服务器日志中会有我们自定义的 `InternalError`。😎
+
+## 使用 `yield` 的依赖项的执行 { #execution-of-dependencies-with-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,operation: Can raise exceptions, including HTTPException
+ client ->> dep: Start request
+ Note over dep: Run code up to yield
+ opt raise Exception
+ dep -->> handler: Raise Exception
+ handler -->> client: HTTP error response
+ end
+ dep ->> operation: Run dependency, e.g. DB session
+ opt raise
+ operation -->> dep: Raise Exception (e.g. HTTPException)
+ opt handle
+ dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception
+ end
+ handler -->> client: HTTP error response
+ 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 -->> tasks: Handle exceptions in the background task code
+ end
+```
+
+/// info | 信息
+
+只会向客户端发送**一次响应**。它可能是某个错误响应,或者是来自 *路径操作* 的响应。
+
+在其中一个响应发送之后,就不能再发送其他响应了。
+
+///
+
+/// tip | 提示
+
+如果你在 *路径操作函数* 的代码中引发任何异常,它都会被传递给带有 `yield` 的依赖项,包括 `HTTPException`。在大多数情况下,你会希望在带有 `yield` 的依赖中重新抛出相同的异常或一个新的异常,以确保它被正确处理。
+
+///
+
+## 提前退出与 `scope` { #early-exit-and-scope }
+
+通常,带有 `yield` 的依赖的退出代码会在响应发送给客户端**之后**执行。
+
+但如果你知道在从 *路径操作函数* 返回之后不再需要使用该依赖,你可以使用 `Depends(scope="function")` 告诉 FastAPI:应当在 *路径操作函数* 返回后、但在**响应发送之前**关闭该依赖。
+
+{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *}
+
+`Depends()` 接收一个 `scope` 参数,可为:
+
+* `"function"`:在处理请求的 *路径操作函数* 之前启动依赖,在 *路径操作函数* 结束后结束依赖,但在响应发送给客户端**之前**。因此,依赖函数将围绕这个*路径操作函数*执行。
+* `"request"`:在处理请求的 *路径操作函数* 之前启动依赖(与使用 `"function"` 时类似),但在响应发送给客户端**之后**结束。因此,依赖函数将围绕这个**请求**与响应周期执行。
+
+如果未指定且依赖包含 `yield`,则默认 `scope` 为 `"request"`。
+
+### 子依赖的 `scope` { #scope-for-sub-dependencies }
+
+当你声明一个 `scope="request"`(默认)的依赖时,任何子依赖也需要有 `"request"` 的 `scope`。
+
+但一个 `scope` 为 `"function"` 的依赖可以有 `scope` 为 `"function"` 和 `"request"` 的子依赖。
+
+这是因为任何依赖都需要能够在子依赖之前运行其退出代码,因为它的退出代码中可能还需要使用这些子依赖。
+
+```mermaid
+sequenceDiagram
+
+participant client as Client
+participant dep_req as Dep scope="request"
+participant dep_func as Dep scope="function"
+participant operation as Path Operation
+
+ client ->> dep_req: Start request
+ Note over dep_req: Run code up to yield
+ dep_req ->> dep_func: Pass dependency
+ Note over dep_func: Run code up to yield
+ dep_func ->> operation: Run path operation with dependency
+ operation ->> dep_func: Return from path operation
+ Note over dep_func: Run code after yield
+ Note over dep_func: ✅ Dependency closed
+ dep_func ->> client: Send response to client
+ Note over client: Response sent
+ Note over dep_req: Run code after yield
+ Note over dep_req: ✅ Dependency closed
+```
+
+## 包含 `yield`、`HTTPException`、`except` 和后台任务的依赖项 { #dependencies-with-yield-httpexception-except-and-background-tasks }
+
+带有 `yield` 的依赖项随着时间演进以涵盖不同的用例并修复了一些问题。
+
+如果你想了解在不同 FastAPI 版本中发生了哪些变化,可以在进阶指南中阅读更多:[高级依赖项 —— 包含 `yield`、`HTTPException`、`except` 和后台任务的依赖项](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks)。
+
+## 上下文管理器 { #context-managers }
+
+### 什么是“上下文管理器” { #what-are-context-managers }
+
+“上下文管理器”是你可以在 `with` 语句中使用的任意 Python 对象。
+
+例如,[你可以用 `with` 来读取文件](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files):
+
+```Python
+with open("./somefile.txt") as f:
+ contents = f.read()
+ print(contents)
+```
+
+在底层,`open("./somefile.txt")` 会创建一个“上下文管理器”对象。
+
+当 `with` 代码块结束时,它会确保文件被关闭,即使期间发生了异常。
+
+当你用 `yield` 创建一个依赖时,**FastAPI** 会在内部为它创建一个上下文管理器,并与其他相关工具结合使用。
+
+### 在带有 `yield` 的依赖中使用上下文管理器 { #using-context-managers-in-dependencies-with-yield }
+
+/// warning | 警告
+
+这算是一个“高级”概念。
+
+如果你刚开始使用 **FastAPI**,现在可以先跳过。
+
+///
+
+在 Python 中,你可以通过[创建一个带有 `__enter__()` 和 `__exit__()` 方法的类](https://docs.python.org/3/reference/datamodel.html#context-managers)来创建上下文管理器。
+
+你也可以在 **FastAPI** 的带有 `yield` 的依赖中,使用依赖函数内部的 `with` 或 `async with` 语句来使用它们:
+
+{* ../../docs_src/dependencies/tutorial010_py310.py hl[1:9,13] *}
+
+/// tip | 提示
+
+另一种创建上下文管理器的方式是:
+
+* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) 或
+* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)
+
+用它们去装饰一个只包含单个 `yield` 的函数。
+
+这正是 **FastAPI** 在内部处理带有 `yield` 的依赖时所使用的方式。
+
+但你不需要(也不应该)为 FastAPI 的依赖去使用这些装饰器。FastAPI 会在内部为你处理好。
+
+///
diff --git a/docs/zh/docs/tutorial/dependencies/global-dependencies.md b/docs/zh/docs/tutorial/dependencies/global-dependencies.md
index 3f7afa32cd1b3..cf083f053d00e 100644
--- a/docs/zh/docs/tutorial/dependencies/global-dependencies.md
+++ b/docs/zh/docs/tutorial/dependencies/global-dependencies.md
@@ -1,17 +1,15 @@
-# 全局依赖项
+# 全局依赖项 { #global-dependencies }
有时,我们要为整个应用添加依赖项。
-通过与定义[*路径装饰器依赖项*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} 类似的方式,可以把依赖项添加至整个 `FastAPI` 应用。
+通过与[将 `dependencies` 添加到*路径操作装饰器*](dependencies-in-path-operation-decorators.md) 类似的方式,可以把依赖项添加至整个 `FastAPI` 应用。
这样一来,就可以为所有*路径操作*应用该依赖项:
-```Python hl_lines="15"
-{!../../../docs_src/dependencies/tutorial012.py!}
-```
+{* ../../docs_src/dependencies/tutorial012_an_py310.py hl[17] *}
-[*路径装饰器依赖项*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} 一章的思路均适用于全局依赖项, 在本例中,这些依赖项可以用于应用中的所有*路径操作*。
+[将 `dependencies` 添加到*路径操作装饰器*](dependencies-in-path-operation-decorators.md) 一章的思路均适用于全局依赖项, 在本例中,这些依赖项可以用于应用中的所有*路径操作*。
-## 为一组路径操作定义依赖项
+## 为一组路径操作定义依赖项 { #dependencies-for-groups-of-path-operations }
-稍后,[大型应用 - 多文件](../../tutorial/bigger-applications.md){.internal-link target=_blank}一章中会介绍如何使用多个文件创建大型应用程序,在这一章中,您将了解到如何为一组*路径操作*声明单个 `dependencies` 参数。
+稍后,[大型应用 - 多文件](../../tutorial/bigger-applications.md)一章中会介绍如何使用多个文件创建大型应用程序,在这一章中,你将了解到如何为一组*路径操作*声明单个 `dependencies` 参数。
diff --git a/docs/zh/docs/tutorial/dependencies/index.md b/docs/zh/docs/tutorial/dependencies/index.md
index 7a133061de797..939470f409b18 100644
--- a/docs/zh/docs/tutorial/dependencies/index.md
+++ b/docs/zh/docs/tutorial/dependencies/index.md
@@ -1,89 +1,97 @@
-# 依赖项
+# 依赖项 { #dependencies }
-FastAPI 提供了简单易用,但功能强大的**依赖注入**系统。
+**FastAPI** 提供了简单直观但功能强大的**依赖注入**系统。
-这个依赖系统设计的简单易用,可以让开发人员轻松地把组件集成至 **FastAPI**。
+它被设计得非常易用,能让任何开发者都能轻松把其他组件与 **FastAPI** 集成。
-## 什么是「依赖注入」
+## 什么是「依赖注入」 { #what-is-dependency-injection }
-编程中的**「依赖注入」**是声明代码(本文中为*路径操作函数* )运行所需的,或要使用的「依赖」的一种方式。
+在编程中,**「依赖注入」**指的是,你的代码(本文中为*路径操作函数*)声明其运行所需并要使用的东西:“依赖”。
-然后,由系统(本文中为 **FastAPI**)负责执行任意需要的逻辑,为代码提供这些依赖(「注入」依赖项)。
+然后,由该系统(本文中为 **FastAPI**)负责执行所有必要的逻辑,为你的代码提供这些所需的依赖(“注入”依赖)。
-依赖注入常用于以下场景:
+当你需要以下内容时,这非常有用:
-* 共享业务逻辑(复用相同的代码逻辑)
+* 共享业务逻辑(同一段代码逻辑反复复用)
* 共享数据库连接
-* 实现安全、验证、角色权限
-* 等……
+* 实施安全、认证、角色权限等要求
+* 以及更多其他内容...
-上述场景均可以使用**依赖注入**,将代码重复最小化。
+同时尽量减少代码重复。
-## 第一步
+## 第一步 { #first-steps }
-接下来,我们学习一个非常简单的例子,尽管它过于简单,不是很实用。
+先来看一个非常简单的例子。它现在简单到几乎没什么用。
-但通过这个例子,您可以初步了解「依赖注入」的工作机制。
+但这样我们就可以专注于**依赖注入**系统是如何工作的。
-### 创建依赖项
+### 创建依赖项,或“dependable” { #create-a-dependency-or-dependable }
-首先,要关注的是依赖项。
+首先关注依赖项。
-依赖项就是一个函数,且可以使用与*路径操作函数*相同的参数:
+它只是一个函数,且可以接收与*路径操作函数*相同的所有参数:
-```Python hl_lines="8-11"
-{!../../../docs_src/dependencies/tutorial001.py!}
-```
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *}
大功告成。
-只用了**2 行**代码。
+**2 行**。
-依赖项函数的形式和结构与*路径操作函数*一样。
+它的形式和结构与所有*路径操作函数*相同。
-因此,可以把依赖项当作没有「装饰器」(即,没有 `@app.get("/some-path")` )的路径操作函数。
+你可以把它当作没有“装饰器”(没有 `@app.get("/some-path")`)的*路径操作函数*。
-依赖项可以返回各种内容。
+而且它可以返回任何你想要的内容。
-本例中的依赖项预期接收如下参数:
+本例中的依赖项预期接收:
* 类型为 `str` 的可选查询参数 `q`
-* 类型为 `int` 的可选查询参数 `skip`,默认值是 `0`
-* 类型为 `int` 的可选查询参数 `limit`,默认值是 `100`
+* 类型为 `int` 的可选查询参数 `skip`,默认值 `0`
+* 类型为 `int` 的可选查询参数 `limit`,默认值 `100`
-然后,依赖项函数返回包含这些值的 `dict`。
+然后它只需返回一个包含这些值的 `dict`。
-### 导入 `Depends`
+/// info | 信息
-```Python hl_lines="3"
-{!../../../docs_src/dependencies/tutorial001.py!}
-```
+FastAPI 在 0.95.0 版本中新增了对 `Annotated` 的支持(并开始推荐使用)。
-### 声明依赖项
+如果你的版本较旧,尝试使用 `Annotated` 会报错。
-与在*路径操作函数*参数中使用 `Body`、`Query` 的方式相同,声明依赖项需要使用 `Depends` 和一个新的参数:
+在使用 `Annotated` 之前,请确保[升级 FastAPI 版本](../../deployment/versions.md#upgrading-the-fastapi-versions)到至少 0.95.1。
-```Python hl_lines="15 20"
-{!../../../docs_src/dependencies/tutorial001.py!}
-```
+///
+
+### 导入 `Depends` { #import-depends }
+
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *}
+
+### 在“dependant”中声明依赖项 { #declare-the-dependency-in-the-dependant }
+
+与在*路径操作函数*的参数中使用 `Body`、`Query` 等相同,给参数使用 `Depends` 来声明一个新的依赖项:
-虽然,在路径操作函数的参数中使用 `Depends` 的方式与 `Body`、`Query` 相同,但 `Depends` 的工作方式略有不同。
+{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *}
-这里只能传给 Depends 一个参数。
+虽然你在函数参数中使用 `Depends` 的方式与 `Body`、`Query` 等相同,但 `Depends` 的工作方式略有不同。
-且该参数必须是可调用对象,比如函数。
+这里只能给 `Depends` 传入一个参数。
-该函数接收的参数和*路径操作函数*的参数一样。
+这个参数必须是类似函数的可调用对象。
-!!! tip "提示"
+你不需要直接调用它(不要在末尾加括号),只需将其作为参数传给 `Depends()`。
- 下一章介绍,除了函数还有哪些「对象」可以用作依赖项。
+该函数接收的参数与*路径操作函数*的参数相同。
-接收到新的请求时,**FastAPI** 执行如下操作:
+/// tip | 提示
-* 用正确的参数调用依赖项函数(「可依赖项」)
+下一章会介绍除了函数之外,还有哪些“东西”可以用作依赖项。
+
+///
+
+接收到新的请求时,**FastAPI** 会负责:
+
+* 用正确的参数调用你的依赖项(“dependable”)函数
* 获取函数返回的结果
-* 把函数返回的结果赋值给*路径操作函数*的参数
+* 将该结果赋值给你的*路径操作函数*中的参数
```mermaid
graph TB
@@ -96,91 +104,121 @@ common_parameters --> read_items
common_parameters --> read_users
```
-这样,只编写一次代码,**FastAPI** 就可以为多个*路径操作*共享这段代码 。
+这样,你只需编写一次共享代码,**FastAPI** 会在你的*路径操作*中为你调用它。
+
+/// check | 检查
+
+注意,无需创建专门的类并传给 **FastAPI** 去“注册”之类的操作。
+
+只要把它传给 `Depends`,**FastAPI** 就知道该怎么做了。
+
+///
+
+## 共享 `Annotated` 依赖项 { #share-annotated-dependencies }
+
+在上面的示例中,你会发现这里有一点点**代码重复**。
+
+当你需要使用 `common_parameters()` 这个依赖时,你必须写出完整的带类型注解和 `Depends()` 的参数:
+
+```Python
+commons: Annotated[dict, Depends(common_parameters)]
+```
+
+但因为我们使用了 `Annotated`,可以把这个 `Annotated` 的值存到一个变量里,在多个地方复用:
+
+{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *}
+
+/// tip | 提示
+
+这只是标准的 Python,叫做“类型别名”,并不是 **FastAPI** 特有的。
+
+但因为 **FastAPI** 基于 Python 标准(包括 `Annotated`),你就可以在代码里使用这个技巧。😎
+
+///
-!!! check "检查"
+这些依赖会照常工作,而**最棒的是**,**类型信息会被保留**,这意味着你的编辑器依然能提供**自动补全**、**行内报错**等。同样适用于 `mypy` 等其他工具。
- 注意,无需创建专门的类,并将之传递给 **FastAPI** 以进行「注册」或执行类似的操作。
+当你在**大型代码库**中,在**很多*路径操作***里反复使用**相同的依赖**时,这会特别有用。
- 只要把它传递给 `Depends`,**FastAPI** 就知道该如何执行后续操作。
+## 要不要使用 `async`? { #to-async-or-not-to-async }
-## 要不要使用 `async`?
+由于依赖项也会由 **FastAPI** 调用(与*路径操作函数*相同),因此定义函数时同样的规则也适用。
-**FastAPI** 调用依赖项的方式与*路径操作函数*一样,因此,定义依赖项函数,也要应用与路径操作函数相同的规则。
+你可以使用 `async def` 或普通的 `def`。
-即,既可以使用异步的 `async def`,也可以使用普通的 `def` 定义依赖项。
+你可以在普通的 `def` *路径操作函数*中声明 `async def` 的依赖项;也可以在异步的 `async def` *路径操作函数*中声明普通的 `def` 依赖项,等等。
-在普通的 `def` *路径操作函数*中,可以声明异步的 `async def` 依赖项;也可以在异步的 `async def` *路径操作函数*中声明普通的 `def` 依赖项。
+都没关系,**FastAPI** 知道该怎么处理。
-上述这些操作都是可行的,**FastAPI** 知道该怎么处理。
+/// note | 注意
-!!! note "笔记"
+如果不了解异步,请参阅文档中关于 `async` 和 `await` 的章节:[异步:*“着急了?”*](../../async.md#in-a-hurry)。
- 如里不了解异步,请参阅[异步:*“着急了?”*](../../async.md){.internal-link target=_blank} 一章中 `async` 和 `await` 的内容。
+///
-## 与 OpenAPI 集成
+## 与 OpenAPI 集成 { #integrated-with-openapi }
-依赖项及子依赖项的所有请求声明、验证和需求都可以集成至同一个 OpenAPI 概图。
+依赖项及子依赖项中声明的所有请求、验证和需求都会集成到同一个 OpenAPI 模式中。
-所以,交互文档里也会显示依赖项的所有信息:
+因此,交互式文档中也会包含这些依赖项的所有信息:
-## 简单用法
+## 简单用法 { #simple-usage }
-观察一下就会发现,只要*路径* 和*操作*匹配,就可以使用声明的路径操作函数。然后,**FastAPI** 会用正确的参数调用函数,并提取请求中的数据。
+观察一下就会发现,只要*路径*和*操作*匹配,就会使用声明的*路径操作函数*。随后,**FastAPI** 会用正确的参数调用该函数,并从请求中提取数据。
-实际上,所有(或大多数)网络框架的工作方式都是这样的。
+事实上,所有(或大多数)Web 框架的工作方式都是这样的。
-开发人员永远都不需要直接调用这些函数,这些函数是由框架(在此为 **FastAPI** )调用的。
+你从不会直接调用这些函数。它们由你的框架(此处为 **FastAPI**)调用。
-通过依赖注入系统,只要告诉 **FastAPI** *路径操作函数* 还要「依赖」其他在*路径操作函数*之前执行的内容,**FastAPI** 就会执行函数代码,并「注入」函数返回的结果。
+通过依赖注入系统,你还可以告诉 **FastAPI**,你的*路径操作函数*还“依赖”某些应在*路径操作函数*之前执行的内容,**FastAPI** 会负责执行它并“注入”结果。
-其他与「依赖注入」概念相同的术语为:
+“依赖注入”的其他常见术语包括:
-* 资源(Resource)
-* 提供方(Provider)
-* 服务(Service)
-* 可注入(Injectable)
-* 组件(Component)
+* 资源(resources)
+* 提供方(providers)
+* 服务(services)
+* 可注入(injectables)
+* 组件(components)
-## **FastAPI** 插件
+## **FastAPI** 插件 { #fastapi-plug-ins }
-**依赖注入**系统支持构建集成和「插件」。但实际上,FastAPI 根本**不需要创建「插件」**,因为使用依赖项可以声明不限数量的、可用于*路径操作函数*的集成与交互。
+可以使用**依赖注入**系统构建集成和“插件”。但实际上,根本**不需要创建“插件”**,因为通过依赖项可以声明无限多的集成与交互,使其可用于*路径操作函数*。
-创建依赖项非常简单、直观,并且还支持导入 Python 包。毫不夸张地说,只要几行代码就可以把需要的 Python 包与 API 函数集成在一起。
+依赖项可以用非常简单直观的方式创建,你只需导入所需的 Python 包,用*字面意义上的*几行代码就能把它们与你的 API 函数集成起来。
-下一章将详细介绍在关系型数据库、NoSQL 数据库、安全等方面使用依赖项的例子。
+在接下来的章节中,你会看到关于关系型数据库、NoSQL 数据库、安全等方面的示例。
-## **FastAPI** 兼容性
+## **FastAPI** 兼容性 { #fastapi-compatibility }
-依赖注入系统如此简洁的特性,让 **FastAPI** 可以与下列系统兼容:
+依赖注入系统的简洁让 **FastAPI** 能与以下内容兼容:
-* 关系型数据库
+* 各类关系型数据库
* NoSQL 数据库
-* 外部支持库
+* 外部包
* 外部 API
-* 认证和鉴权系统
+* 认证与授权系统
* API 使用监控系统
* 响应数据注入系统
-* 等等……
+* 等等...
-## 简单而强大
+## 简单而强大 { #simple-and-powerful }
-虽然,**层级式依赖注入系统**的定义与使用十分简单,但它却非常强大。
+虽然**层级式依赖注入系统**的定义与使用非常简单,但它依然非常强大。
-比如,可以定义依赖其他依赖项的依赖项。
+你可以定义依赖其他依赖项的依赖项。
-最后,依赖项层级树构建后,**依赖注入系统**会处理所有依赖项及其子依赖项,并为每一步操作提供(注入)结果。
+最终会构建出一个依赖项的层级树,**依赖注入**系统会处理所有这些依赖(及其子依赖),并在每一步提供(注入)相应的结果。
-比如,下面有 4 个 API 路径操作(*端点*):
+例如,假设你有 4 个 API 路径操作(*端点*):
* `/items/public/`
* `/items/private/`
* `/users/{user_id}/activate`
* `/items/pro/`
-开发人员可以使用依赖项及其子依赖项为这些路径操作添加不同的权限:
+你可以仅通过依赖项及其子依赖项为它们添加不同的权限要求:
```mermaid
graph TB
@@ -205,8 +243,8 @@ admin_user --> activate_user
paying_user --> pro_items
```
-## 与 **OpenAPI** 集成
+## 与 **OpenAPI** 集成 { #integrated-with-openapi_1 }
-在声明需求时,所有这些依赖项还会把参数、验证等功能添加至路径操作。
+在声明需求的同时,所有这些依赖项也会为你的*路径操作*添加参数、验证等内容。
-**FastAPI** 负责把上述内容全部添加到 OpenAPI 概图,并显示在交互文档中。
+**FastAPI** 会负责把这些全部添加到 OpenAPI 模式中,以便它们显示在交互式文档系统里。
diff --git a/docs/zh/docs/tutorial/dependencies/sub-dependencies.md b/docs/zh/docs/tutorial/dependencies/sub-dependencies.md
index 58377bbfecd8d..1c30b43807726 100644
--- a/docs/zh/docs/tutorial/dependencies/sub-dependencies.md
+++ b/docs/zh/docs/tutorial/dependencies/sub-dependencies.md
@@ -1,4 +1,4 @@
-# 子依赖项
+# 子依赖项 { #sub-dependencies }
FastAPI 支持创建含**子依赖项**的依赖项。
@@ -6,46 +6,42 @@ FastAPI 支持创建含**子依赖项**的依赖项。
**FastAPI** 负责处理解析不同深度的子依赖项。
-### 第一层依赖项
+## 第一层依赖项 “dependable” { #first-dependency-dependable }
-下列代码创建了第一层依赖项:
+你可以创建一个第一层依赖项(“dependable”),如下:
-```Python hl_lines="8-9"
-{!../../../docs_src/dependencies/tutorial005.py!}
-```
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *}
这段代码声明了类型为 `str` 的可选查询参数 `q`,然后返回这个查询参数。
这个函数很简单(不过也没什么用),但却有助于让我们专注于了解子依赖项的工作方式。
-### 第二层依赖项
+## 第二层依赖项,“dependable”和“dependant” { #second-dependency-dependable-and-dependant }
-接下来,创建另一个依赖项函数,并同时用该依赖项自身再声明一个依赖项(所以这也是一个「依赖项」):
+接下来,创建另一个依赖项函数(一个“dependable”),并同时为它自身再声明一个依赖项(因此它同时也是一个“dependant”):
-```Python hl_lines="13"
-{!../../../docs_src/dependencies/tutorial005.py!}
-```
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *}
这里重点说明一下声明的参数:
-* 尽管该函数自身是依赖项,但还声明了另一个依赖项(它「依赖」于其他对象)
+* 尽管该函数自身是依赖项(“dependable”),但还声明了另一个依赖项(它“依赖”于其他对象)
* 该函数依赖 `query_extractor`, 并把 `query_extractor` 的返回值赋给参数 `q`
* 同时,该函数还声明了类型是 `str` 的可选 cookie(`last_query`)
* 用户未提供查询参数 `q` 时,则使用上次使用后保存在 cookie 中的查询
-### 使用依赖项
+## 使用依赖项 { #use-the-dependency }
接下来,就可以使用依赖项:
-```Python hl_lines="22"
-{!../../../docs_src/dependencies/tutorial005.py!}
-```
+{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *}
+
+/// info | 信息
-!!! info "信息"
+注意,这里在*路径操作函数*中只声明了一个依赖项,即 `query_or_cookie_extractor` 。
- 注意,这里在*路径操作函数*中只声明了一个依赖项,即 `query_or_cookie_extractor` 。
+但 **FastAPI** 必须先处理 `query_extractor`,以便在调用 `query_or_cookie_extractor` 时使用 `query_extractor` 返回的结果。
- 但 **FastAPI** 必须先处理 `query_extractor`,以便在调用 `query_or_cookie_extractor` 时使用 `query_extractor` 返回的结果。
+///
```mermaid
graph TB
@@ -58,20 +54,39 @@ read_query["/items/"]
query_extractor --> query_or_cookie_extractor --> read_query
```
-## 多次使用同一个依赖项
+## 多次使用同一个依赖项 { #using-the-same-dependency-multiple-times }
如果在同一个*路径操作* 多次声明了同一个依赖项,例如,多个依赖项共用一个子依赖项,**FastAPI** 在处理同一请求时,只调用一次该子依赖项。
-FastAPI 不会为同一个请求多次调用同一个依赖项,而是把依赖项的返回值进行「缓存」,并把它传递给同一请求中所有需要使用该返回值的「依赖项」。
+FastAPI 不会为同一个请求多次调用同一个依赖项,而是把依赖项的返回值进行「缓存」,并把它传递给同一请求中所有需要使用该返回值的「依赖项」。
+
+在高级使用场景中,如果不想使用「缓存」值,而是为需要在同一请求的每一步操作(多次)中都实际调用依赖项,可以把 `Depends` 的参数 `use_cache` 的值设置为 `False`:
+
+//// tab | Python 3.10+
+
+```Python hl_lines="1"
+async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]):
+ return {"fresh_value": fresh_value}
+```
+
+////
+
+//// tab | Python 3.10+ 非 Annotated
-在高级使用场景中,如果不想使用「缓存」值,而是为需要在同一请求的每一步操作(多次)中都实际调用依赖项,可以把 `Depends` 的参数 `use_cache` 的值设置为 `False` :
+/// tip | 提示
+
+尽可能优先使用 `Annotated` 版本。
+
+///
```Python hl_lines="1"
async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
return {"fresh_value": fresh_value}
```
-## 小结
+////
+
+## 小结 { #recap }
千万别被本章里这些花里胡哨的词藻吓倒了,其实**依赖注入**系统非常简单。
@@ -79,10 +94,12 @@ async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False
但它依然非常强大,能够声明任意嵌套深度的「图」或树状的依赖结构。
-!!! tip "提示"
+/// tip | 提示
+
+这些简单的例子现在看上去虽然没有什么实用价值,
- 这些简单的例子现在看上去虽然没有什么实用价值,
+但在**安全**一章中,您会了解到这些例子的用途,
- 但在**安全**一章中,您会了解到这些例子的用途,
+以及这些例子所能节省的代码量。
- 以及这些例子所能节省的代码量。
+///
diff --git a/docs/zh/docs/tutorial/encoder.md b/docs/zh/docs/tutorial/encoder.md
index 76ed846ce35e4..8327ab6c7c422 100644
--- a/docs/zh/docs/tutorial/encoder.md
+++ b/docs/zh/docs/tutorial/encoder.md
@@ -1,4 +1,4 @@
-# JSON 兼容编码器
+# JSON 兼容编码器 { #json-compatible-encoder }
在某些情况下,您可能需要将数据类型(如Pydantic模型)转换为与JSON兼容的数据类型(如`dict`、`list`等)。
@@ -6,13 +6,13 @@
对于这种要求, **FastAPI**提供了`jsonable_encoder()`函数。
-## 使用`jsonable_encoder`
+## 使用`jsonable_encoder` { #using-the-jsonable-encoder }
让我们假设你有一个数据库名为`fake_db`,它只能接收与JSON兼容的数据。
例如,它不接收`datetime`这类的对象,因为这些对象与JSON不兼容。
-因此,`datetime`对象必须将转换为包含ISO格式化的`str`类型对象。
+因此,`datetime`对象必须转换为包含[ISO 格式](https://en.wikipedia.org/wiki/ISO_8601)的`str`类型对象。
同样,这个数据库也不会接收Pydantic模型(带有属性的对象),而只接收`dict`。
@@ -20,23 +20,16 @@
它接收一个对象,比如Pydantic模型,并会返回一个JSON兼容的版本:
-=== "Python 3.10+"
-
- ```Python hl_lines="4 21"
- {!> ../../../docs_src/encoder/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="5 22"
- {!> ../../../docs_src/encoder/tutorial001.py!}
- ```
+{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *}
在这个例子中,它将Pydantic模型转换为`dict`,并将`datetime`转换为`str`。
-调用它的结果后就可以使用Python标准编码中的`json.dumps()`。
+调用它的结果后就可以使用Python标准编码中的[`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps)。
这个操作不会返回一个包含JSON格式(作为字符串)数据的庞大的`str`。它将返回一个Python标准数据结构(例如`dict`),其值和子值都与JSON兼容。
-!!! note
- `jsonable_encoder`实际上是FastAPI内部用来转换数据的。但是它在许多其他场景中也很有用。
+/// note | 注意
+
+`jsonable_encoder`实际上是**FastAPI**内部用来转换数据的。但是它在许多其他场景中也很有用。
+
+///
diff --git a/docs/zh/docs/tutorial/extra-data-types.md b/docs/zh/docs/tutorial/extra-data-types.md
index 76d606903a1d9..76748a7a38b06 100644
--- a/docs/zh/docs/tutorial/extra-data-types.md
+++ b/docs/zh/docs/tutorial/extra-data-types.md
@@ -1,4 +1,4 @@
-# 额外数据类型
+# 额外数据类型 { #extra-data-types }
到目前为止,您一直在使用常见的数据类型,如:
@@ -15,9 +15,9 @@
* 传入请求的数据转换。
* 响应数据转换。
* 数据验证。
-* 自动补全和文档。
+* 自动注解和文档。
-## 其他数据类型
+## 其他数据类型 { #other-data-types }
下面是一些你可以使用的其他数据类型:
@@ -36,95 +36,27 @@
* `datetime.timedelta`:
* 一个 Python `datetime.timedelta`.
* 在请求和响应中将表示为 `float` 代表总秒数。
- * Pydantic 也允许将其表示为 "ISO 8601 时间差异编码", 查看文档了解更多信息。
+ * Pydantic 也允许将其表示为 "ISO 8601 时间差异编码", [查看文档了解更多信息](https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers)。
* `frozenset`:
* 在请求和响应中,作为 `set` 对待:
* 在请求中,列表将被读取,消除重复,并将其转换为一个 `set`。
* 在响应中 `set` 将被转换为 `list` 。
- * 产生的模式将指定那些 `set` 的值是唯一的 (使用 JSON 模式的 `uniqueItems`)。
+ * 产生的模式将指定那些 `set` 的值是唯一的 (使用 JSON Schema 的 `uniqueItems`)。
* `bytes`:
* 标准的 Python `bytes`。
- * 在请求和相应中被当作 `str` 处理。
+ * 在请求和响应中被当作 `str` 处理。
* 生成的模式将指定这个 `str` 是 `binary` "格式"。
* `Decimal`:
* 标准的 Python `Decimal`。
- * 在请求和相应中被当做 `float` 一样处理。
-* 您可以在这里检查所有有效的pydantic数据类型: Pydantic data types.
+ * 在请求和响应中被当做 `float` 一样处理。
+* 您可以在这里检查所有有效的 Pydantic 数据类型: [Pydantic data types](https://docs.pydantic.dev/latest/usage/types/types/)。
-## 例子
+## 例子 { #example }
下面是一个*路径操作*的示例,其中的参数使用了上面的一些类型。
-=== "Python 3.10+"
-
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="1 3 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="1 3 13-17"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="1 2 11-15"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="1 2 12-16"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *}
注意,函数内的参数有原生的数据类型,你可以,例如,执行正常的日期操作,如:
-=== "Python 3.10+"
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="19-20"
- {!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
- ```
-
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="17-18"
- {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="18-19"
- {!> ../../../docs_src/extra_data_types/tutorial001.py!}
- ```
+{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *}
diff --git a/docs/zh/docs/tutorial/extra-models.md b/docs/zh/docs/tutorial/extra-models.md
index 32f8f9df127f5..0ad35cc4fc881 100644
--- a/docs/zh/docs/tutorial/extra-models.md
+++ b/docs/zh/docs/tutorial/extra-models.md
@@ -1,63 +1,56 @@
-# 额外的模型
+# 更多模型 { #extra-models }
-我们从前面的示例继续,拥有多个相关的模型是很常见的。
+书接上文,多个关联模型这种情况很常见。
-对用户模型来说尤其如此,因为:
+特别是用户模型,因为:
-* **输入模型**需要拥有密码属性。
-* **输出模型**不应该包含密码。
-* **数据库模型**很可能需要保存密码的哈希值。
+* **输入模型**应该含密码
+* **输出模型**不应含密码
+* **数据库模型**可能需要包含哈希后的密码
-!!! danger
- 永远不要存储用户的明文密码。始终存储一个可以用于验证的「安全哈希值」。
+/// danger | 危险
- 如果你尚未了解该知识,你可以在[安全章节](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}中学习何为「密码哈希值」。
+不要存储用户的明文密码。始终只存储之后可用于校验的“安全哈希”。
-## 多个模型
+如果你还不了解,可以在[安全性章节](security/simple-oauth2.md#password-hashing)中学习什么是“密码哈希”。
-下面是应该如何根据它们的密码字段以及使用位置去定义模型的大概思路:
+///
-=== "Python 3.10+"
+## 多个模型 { #multiple-models }
- ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39"
- {!> ../../../docs_src/extra_models/tutorial001_py310.py!}
- ```
+下面的代码展示了不同模型处理密码字段的方式,及使用位置的大致思路:
-=== "Python 3.6+"
+{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}
- ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
- {!> ../../../docs_src/extra_models/tutorial001.py!}
- ```
+### 关于 `**user_in.model_dump()` { #about-user-in-model-dump }
-### 关于 `**user_in.dict()`
+#### Pydantic 的 `.model_dump()` { #pydantics-model-dump }
-#### Pydantic 的 `.dict()`
+`user_in` 是类 `UserIn` 的 Pydantic 模型。
-`user_in` 是一个 `UserIn` 类的 Pydantic 模型.
+Pydantic 模型有 `.model_dump()` 方法,会返回包含模型数据的 `dict`。
-Pydantic 模型具有 `.dict()` 方法,该方法返回一个拥有模型数据的 `dict`。
-
-因此,如果我们像下面这样创建一个 Pydantic 对象 `user_in`:
+因此,如果使用如下方式创建 Pydantic 对象 `user_in`:
```Python
user_in = UserIn(username="john", password="secret", email="john.doe@example.com")
```
-然后我们调用:
+就能以如下方式调用:
```Python
-user_dict = user_in.dict()
+user_dict = user_in.model_dump()
```
-现在我们有了一个数据位于变量 `user_dict` 中的 `dict`(它是一个 `dict` 而不是 Pydantic 模型对象)。
+现在,变量 `user_dict` 中的是包含数据的 `dict`(它是 `dict`,不是 Pydantic 模型对象)。
-如果我们调用:
+以如下方式调用:
```Python
print(user_dict)
```
-我们将获得一个这样的 Python `dict`:
+输出的就是 Python `dict`:
```Python
{
@@ -68,17 +61,17 @@ print(user_dict)
}
```
-#### 解包 `dict`
+#### 解包 `dict` { #unpacking-a-dict }
-如果我们将 `user_dict` 这样的 `dict` 以 `**user_dict` 形式传递给一个函数(或类),Python将对其进行「解包」。它会将 `user_dict` 的键和值作为关键字参数直接传递。
+把 `dict`(如 `user_dict`)以 `**user_dict` 形式传递给函数(或类),Python 会执行“解包”。它会把 `user_dict` 的键和值作为关键字参数直接传递。
-因此,从上面的 `user_dict` 继续,编写:
+因此,接着上面的 `user_dict` 继续编写如下代码:
```Python
UserInDB(**user_dict)
```
-会产生类似于以下的结果:
+就会生成如下结果:
```Python
UserInDB(
@@ -89,7 +82,7 @@ UserInDB(
)
```
-或者更确切地,直接使用 `user_dict` 来表示将来可能包含的任何内容:
+或更精准,直接使用 `user_dict`(无论它将来包含什么字段):
```Python
UserInDB(
@@ -100,34 +93,34 @@ UserInDB(
)
```
-#### 来自于其他模型内容的 Pydantic 模型
+#### 用另一个模型的内容生成 Pydantic 模型 { #a-pydantic-model-from-the-contents-of-another }
-如上例所示,我们从 `user_in.dict()` 中获得了 `user_dict`,此代码:
+上例中 ,从 `user_in.model_dump()` 中得到了 `user_dict`,下面的代码:
```Python
-user_dict = user_in.dict()
+user_dict = user_in.model_dump()
UserInDB(**user_dict)
```
-等同于:
+等效于:
```Python
-UserInDB(**user_in.dict())
+UserInDB(**user_in.model_dump())
```
-...因为 `user_in.dict()` 是一个 `dict`,然后我们通过以`**`开头传递给 `UserInDB` 来使 Python「解包」它。
+...因为 `user_in.model_dump()` 是 `dict`,在传递给 `UserInDB` 时,把 `**` 加在 `user_in.model_dump()` 前,可以让 Python 进行解包。
-这样,我们获得了一个来自于其他 Pydantic 模型中的数据的 Pydantic 模型。
+这样,就可以用其它 Pydantic 模型中的数据生成 Pydantic 模型。
-#### 解包 `dict` 和额外关键字
+#### 解包 `dict` 并添加额外关键字参数 { #unpacking-a-dict-and-extra-keywords }
-然后添加额外的关键字参数 `hashed_password=hashed_password`,例如:
+接下来,继续添加关键字参数 `hashed_password=hashed_password`,例如:
```Python
-UserInDB(**user_in.dict(), hashed_password=hashed_password)
+UserInDB(**user_in.model_dump(), hashed_password=hashed_password)
```
-...最终的结果如下:
+...输出结果如下:
```Python
UserInDB(
@@ -139,101 +132,80 @@ UserInDB(
)
```
-!!! warning
- 辅助性的额外函数只是为了演示可能的数据流,但它们显然不能提供任何真正的安全性。
-
-## 减少重复
-
-减少代码重复是 **FastAPI** 的核心思想之一。
-
-因为代码重复会增加出现 bug、安全性问题、代码失步问题(当你在一个位置更新了代码但没有在其他位置更新)等的可能性。
+/// warning | 警告
-上面的这些模型都共享了大量数据,并拥有重复的属性名称和类型。
+配套的辅助函数 `fake_password_hasher` 和 `fake_save_user` 仅用于演示可能的数据流,当然并不提供真实的安全性。
-我们可以做得更好。
+///
-我们可以声明一个 `UserBase` 模型作为其他模型的基类。然后我们可以创建继承该模型属性(类型声明,校验等)的子类。
+## 减少重复 { #reduce-duplication }
-所有的数据转换、校验、文档生成等仍将正常运行。
+减少代码重复是 **FastAPI** 的核心思想之一。
-这样,我们可以仅声明模型之间的差异部分(具有明文的 `password`、具有 `hashed_password` 以及不包括密码)。
+代码重复会导致 bug、安全问题、代码失步等问题(更新了某个位置的代码,但没有同步更新其它位置的代码)。
-=== "Python 3.10+"
+上面的这些模型共享了大量数据,拥有重复的属性名和类型。
- ```Python hl_lines="7 13-14 17-18 21-22"
- {!> ../../../docs_src/extra_models/tutorial002_py310.py!}
- ```
+我们可以做得更好。
-=== "Python 3.6+"
+声明 `UserBase` 模型作为其它模型的基类。然后,用该类衍生出继承其属性(类型声明、校验等)的子类。
- ```Python hl_lines="9 15-16 19-20 23-24"
- {!> ../../../docs_src/extra_models/tutorial002.py!}
- ```
+所有数据转换、校验、文档等功能仍将正常运行。
-## `Union` 或者 `anyOf`
+这样,就可以仅声明模型之间的差异部分(具有明文的 `password`、具有 `hashed_password` 以及不包括密码):
-你可以将一个响应声明为两种类型的 `Union`,这意味着该响应将是两种类型中的任何一种。
+{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}
-这将在 OpenAPI 中使用 `anyOf` 进行定义。
+## `Union` 或 `anyOf` { #union-or-anyof }
-为此,请使用标准的 Python 类型提示 `typing.Union`:
+响应可以声明为两个或多个类型的 `Union`,即该响应可以是这些类型中的任意一种。
+在 OpenAPI 中会用 `anyOf` 表示。
-!!! note
- 定义一个 `Union` 类型时,首先包括最详细的类型,然后是不太详细的类型。在下面的示例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。
+为此,请使用 Python 标准类型提示 [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union):
-=== "Python 3.10+"
+/// note | 注意
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003_py310.py!}
- ```
+定义 [`Union`](https://docs.pydantic.dev/latest/concepts/types/#unions) 类型时,要把更具体的类型写在前面,然后是不太具体的类型。下例中,更具体的 `PlaneItem` 位于 `Union[PlaneItem, CarItem]` 中的 `CarItem` 之前。
-=== "Python 3.6+"
+///
- ```Python hl_lines="1 14-15 18-20 33"
- {!> ../../../docs_src/extra_models/tutorial003.py!}
- ```
+{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}
-## 模型列表
+### Python 3.10 中的 `Union` { #union-in-python-3-10 }
-你可以用同样的方式声明由对象列表构成的响应。
+在这个示例中,我们把 `Union[PlaneItem, CarItem]` 作为参数 `response_model` 的值传入。
-为此,请使用标准的 Python `typing.List`:
+因为这是作为“参数的值”而不是放在“类型注解”中,所以即使在 Python 3.10 也必须使用 `Union`。
-=== "Python 3.9+"
+如果是在类型注解中,我们就可以使用竖线:
- ```Python hl_lines="18"
- {!> ../../../docs_src/extra_models/tutorial004_py39.py!}
- ```
+```Python
+some_variable: PlaneItem | CarItem
+```
-=== "Python 3.6+"
+但如果把它写成赋值 `response_model=PlaneItem | CarItem`,就会报错,因为 Python 会尝试在 `PlaneItem` 和 `CarItem` 之间执行一个“无效的运算”,而不是把它当作类型注解来解析。
- ```Python hl_lines="1 20"
- {!> ../../../docs_src/extra_models/tutorial004.py!}
- ```
+## 模型列表 { #list-of-models }
-## 任意 `dict` 构成的响应
+同样地,你可以声明由对象列表构成的响应。
-你还可以使用一个任意的普通 `dict` 声明响应,仅声明键和值的类型,而不使用 Pydantic 模型。
+为此,请使用标准的 Python `list`:
-如果你事先不知道有效的字段/属性名称(对于 Pydantic 模型是必需的),这将很有用。
+{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *}
-在这种情况下,你可以使用 `typing.Dict`:
+## 任意 `dict` 的响应 { #response-with-arbitrary-dict }
-=== "Python 3.9+"
+你也可以使用普通的任意 `dict` 来声明响应,只需声明键和值的类型,无需使用 Pydantic 模型。
- ```Python hl_lines="6"
- {!> ../../../docs_src/extra_models/tutorial005_py39.py!}
- ```
+如果你事先不知道有效的字段/属性名(Pydantic 模型需要预先知道字段)时,这很有用。
-=== "Python 3.6+"
+此时,可以使用 `dict`:
- ```Python hl_lines="1 8"
- {!> ../../../docs_src/extra_models/tutorial005.py!}
- ```
+{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *}
-## 总结
+## 小结 { #recap }
-使用多个 Pydantic 模型,并针对不同场景自由地继承。
+针对不同场景,可以随意使用不同的 Pydantic 模型并通过继承复用。
-如果一个实体必须能够具有不同的「状态」,你无需为每个状态的实体定义单独的数据模型。以用户「实体」为例,其状态有包含 `password`、包含 `password_hash` 以及不含密码。
+当一个实体需要具备不同的“状态”时,无需只为该实体定义一个数据模型。例如,用户“实体”就可能有包含 `password`、包含 `password_hash` 以及不含密码等多种状态。
diff --git a/docs/zh/docs/tutorial/first-steps.md b/docs/zh/docs/tutorial/first-steps.md
index 30fae99cf8fc2..78db1fefc08b4 100644
--- a/docs/zh/docs/tutorial/first-steps.md
+++ b/docs/zh/docs/tutorial/first-steps.md
@@ -1,10 +1,8 @@
-# 第一步
+# 第一步 { #first-steps }
最简单的 FastAPI 文件可能像下面这样:
-```Python
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001_py310.py *}
将其复制到 `main.py` 文件中。
@@ -13,24 +11,42 @@
get 操作
+* 使用 get 操作
+
+/// info | `@decorator` 信息
-!!! info "`@decorator` Info"
- `@something` 语法在 Python 中被称为「装饰器」。
+`@something` 语法在 Python 中被称为「装饰器」。
- 像一顶漂亮的装饰帽一样,将它放在一个函数的上方(我猜测这个术语的命名就是这么来的)。
+像一顶漂亮的装饰帽一样,将它放在一个函数的上方(我猜测这个术语的命名就是这么来的)。
- 装饰器接收位于其下方的函数并且用它完成一些工作。
+装饰器接收位于其下方的函数并且用它完成一些工作。
- 在我们的例子中,这个装饰器告诉 **FastAPI** 位于其下方的函数对应着**路径** `/` 加上 `get` **操作**。
+在我们的例子中,这个装饰器告诉 **FastAPI** 位于其下方的函数对应着**路径** `/` 加上 `get` **操作**。
- 它是一个「**路径操作装饰器**」。
+它是一个「**路径操作装饰器**」。
+
+///
你也可以使用其他的操作:
@@ -276,16 +349,19 @@ https://example.com/items/foo
* `@app.patch()`
* `@app.trace()`
-!!! tip
- 您可以随意使用任何一个操作(HTTP方法)。
+/// tip
+
+你可以随意使用任何一个操作(HTTP方法)。
+
+**FastAPI** 没有强制要求操作有任何特定的含义。
- **FastAPI** 没有强制要求操作有任何特定的含义。
+此处提供的信息仅作为指导,而不是要求。
- 此处提供的信息仅作为指导,而不是要求。
+比如,当使用 GraphQL 时通常你所有的动作都通过 `POST` 一种方法执行。
- 比如,当使用 GraphQL 时通常你所有的动作都通过 `post` 一种方法执行。
+///
-### 步骤 4:定义**路径操作函数**
+### 步骤 4:定义**路径操作函数** { #step-4-define-the-path-operation-function }
这是我们的「**路径操作函数**」:
@@ -293,9 +369,7 @@ https://example.com/items/foo
* **操作**:是 `get`。
* **函数**:是位于「装饰器」下方的函数(位于 `@app.get("/")` 下方)。
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *}
这是一个 Python 函数。
@@ -307,18 +381,17 @@ https://example.com/items/foo
你也可以将其定义为常规函数而不使用 `async def`:
-```Python hl_lines="7"
-{!../../../docs_src/first_steps/tutorial003.py!}
-```
+{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *}
-!!! note
- 如果你不知道两者的区别,请查阅 [Async: *"In a hurry?"*](https://fastapi.tiangolo.com/async/#in-a-hurry){.internal-link target=_blank}。
+/// note
-### 步骤 5:返回内容
+如果你不知道两者的区别,请查阅 [并发: *赶时间吗?*](../async.md#in-a-hurry)。
-```Python hl_lines="8"
-{!../../../docs_src/first_steps/tutorial001.py!}
-```
+///
+
+### 步骤 5:返回内容 { #step-5-return-the-content }
+
+{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *}
你可以返回一个 `dict`、`list`,像 `str`、`int` 一样的单个值,等等。
@@ -326,10 +399,31 @@ https://example.com/items/foo
还有许多其他将会自动转换为 JSON 的对象和模型(包括 ORM 对象等)。尝试下使用你最喜欢的一种,它很有可能已经被支持。
-## 总结
+### 步骤 6:部署 { #step-6-deploy-it }
+
+用一条命令将你的应用部署到 **[FastAPI Cloud](https://fastapicloud.com)**:`fastapi deploy`。🎉
+
+#### 关于 FastAPI Cloud { #about-fastapi-cloud }
+
+**[FastAPI Cloud](https://fastapicloud.com)** 由 **FastAPI** 的作者和团队打造。
+
+它以最小的投入简化了 **构建**、**部署** 和 **访问** API 的流程。
+
+它把使用 FastAPI 构建应用的相同**开发者体验**带到了将应用**部署**到云端的过程。🎉
+
+FastAPI Cloud 是 *FastAPI 及其朋友们* 开源项目的主要赞助和资金提供方。✨
+
+#### 部署到其他云服务商 { #deploy-to-other-cloud-providers }
+
+FastAPI 是开源并基于标准的。你可以将 FastAPI 应用部署到你选择的任何云服务商。
+
+按照你的云服务商的指南部署 FastAPI 应用即可。🤓
+
+## 总结 { #recap }
* 导入 `FastAPI`。
* 创建一个 `app` 实例。
-* 编写一个**路径操作装饰器**(如 `@app.get("/")`)。
-* 编写一个**路径操作函数**(如上面的 `def root(): ...`)。
-* 运行开发服务器(如 `uvicorn main:app --reload`)。
+* 编写一个**路径操作装饰器**,如 `@app.get("/")`。
+* 定义一个**路径操作函数**,如 `def root(): ...`。
+* 使用命令 `fastapi dev` 运行开发服务器。
+* 可选:使用 `fastapi deploy` 部署你的应用。
diff --git a/docs/zh/docs/tutorial/handling-errors.md b/docs/zh/docs/tutorial/handling-errors.md
index a0d66e557c040..f3a23fab0a877 100644
--- a/docs/zh/docs/tutorial/handling-errors.md
+++ b/docs/zh/docs/tutorial/handling-errors.md
@@ -1,151 +1,135 @@
-# 处理错误
+# 处理错误 { #handling-errors }
-某些情况下,需要向客户端返回错误提示。
+某些情况下,需要向使用你的 API 的客户端返回错误提示。
-这里所谓的客户端包括前端浏览器、其他应用程序、物联网设备等。
+这里所谓的客户端包括前端浏览器、他人的代码、物联网设备等。
-需要向客户端返回错误提示的场景主要如下:
+你可能需要告诉客户端:
-- 客户端没有执行操作的权限
-- 客户端没有访问资源的权限
+- 客户端没有执行该操作的权限
+- 客户端没有访问该资源的权限
- 客户端要访问的项目不存在
-- 等等 ...
+- 等等
遇到这些情况时,通常要返回 **4XX**(400 至 499)**HTTP 状态码**。
-**4XX** 状态码与表示请求成功的 **2XX**(200 至 299) HTTP 状态码类似。
+这与表示请求成功的 **2XX**(200 至 299)HTTP 状态码类似。那些“200”状态码表示某种程度上的“成功”。
-只不过,**4XX** 状态码表示客户端发生的错误。
+而 **4XX** 状态码表示客户端发生了错误。
大家都知道**「404 Not Found」**错误,还有调侃这个错误的笑话吧?
-## 使用 `HTTPException`
+## 使用 `HTTPException` { #use-httpexception }
向客户端返回 HTTP 错误响应,可以使用 `HTTPException`。
-### 导入 `HTTPException`
+### 导入 `HTTPException` { #import-httpexception }
-```Python hl_lines="1"
-{!../../../docs_src/handling_errors/tutorial001.py!}
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
-```
-
-### 触发 `HTTPException`
+### 在代码中触发 `HTTPException` { #raise-an-httpexception-in-your-code }
`HTTPException` 是额外包含了和 API 有关数据的常规 Python 异常。
因为是 Python 异常,所以不能 `return`,只能 `raise`。
-如在调用*路径操作函数*里的工具函数时,触发了 `HTTPException`,FastAPI 就不再继续执行*路径操作函数*中的后续代码,而是立即终止请求,并把 `HTTPException` 的 HTTP 错误发送至客户端。
+这也意味着,如果你在*路径操作函数*里调用的某个工具函数内部触发了 `HTTPException`,那么*路径操作函数*中后续的代码将不会继续执行,请求会立刻终止,并把 `HTTPException` 的 HTTP 错误发送给客户端。
-在介绍依赖项与安全的章节中,您可以了解更多用 `raise` 异常代替 `return` 值的优势。
+在介绍依赖项与安全的章节中,你可以更直观地看到用 `raise` 异常代替 `return` 值的优势。
-本例中,客户端用 `ID` 请求的 `item` 不存在时,触发状态码为 `404` 的异常:
+本例中,客户端用不存在的 `ID` 请求 `item` 时,触发状态码为 `404` 的异常:
-```Python hl_lines="11"
-{!../../../docs_src/handling_errors/tutorial001.py!}
-
-```
+{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
-### 响应结果
+### 响应结果 { #the-resulting-response }
-请求为 `http://example.com/items/foo`(`item_id` 为 `「foo」`)时,客户端会接收到 HTTP 状态码 - 200 及如下 JSON 响应结果:
+请求为 `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(「未找到」错误)及如下 JSON 响应结果:
+但如果客户端请求 `http://example.com/items/bar`(不存在的 `item_id` `"bar"`),则会接收到 HTTP 状态码 404(“未找到”错误)及如下 JSON 响应结果:
```JSON
{
"detail": "Item not found"
}
-
```
-!!! tip "提示"
-
- 触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。
-
- 还支持传递 `dict`、`list` 等数据结构。
+/// tip | 提示
- **FastAPI** 能自动处理这些数据,并将之转换为 JSON。
+触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。
+还支持传递 `dict`、`list` 等数据结构。
-## 添加自定义响应头
+**FastAPI** 能自动处理这些数据,并将之转换为 JSON。
-有些场景下要为 HTTP 错误添加自定义响应头。例如,出于某些方面的安全需要。
+///
-一般情况下可能不会需要在代码中直接使用响应头。
+## 添加自定义响应头 { #add-custom-headers }
-但对于某些高级应用场景,还是需要添加自定义响应头:
+有些场景下要为 HTTP 错误添加自定义响应头。例如,出于某些类型的安全需要。
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial002.py!}
+一般情况下你可能不会在代码中直接使用它。
-```
+但在某些高级场景中需要时,你可以添加自定义响应头:
-## 安装自定义异常处理器
+{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
-添加自定义处理器,要使用 [Starlette 的异常工具](https://www.starlette.io/exceptions/)。
+## 安装自定义异常处理器 { #install-custom-exception-handlers }
-假设要触发的自定义异常叫作 `UnicornException`。
+可以使用[与 Starlette 相同的异常处理工具](https://www.starlette.dev/exceptions/)添加自定义异常处理器。
-且需要 FastAPI 实现全局处理该异常。
+假设有一个自定义异常 `UnicornException`(你自己或你使用的库可能会 `raise` 它)。
-此时,可以用 `@app.exception_handler()` 添加自定义异常控制器:
+并且你希望用 FastAPI 在全局处理该异常。
-```Python hl_lines="5-7 13-18 24"
-{!../../../docs_src/handling_errors/tutorial003.py!}
+此时,可以用 `@app.exception_handler()` 添加自定义异常处理器:
-```
+{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
-请求 `/unicorns/yolo` 时,路径操作会触发 `UnicornException`。
+这里,请求 `/unicorns/yolo` 时,路径操作会触发 `UnicornException`。
但该异常将会被 `unicorn_exception_handler` 处理。
-接收到的错误信息清晰明了,HTTP 状态码为 `418`,JSON 内容如下:
+你会收到清晰的错误信息,HTTP 状态码为 `418`,JSON 内容如下:
```JSON
{"message": "Oops! yolo did something. There goes a rainbow..."}
-
```
-!!! note "技术细节"
+/// note | 技术细节
- `from starlette.requests import Request` 和 `from starlette.responses import JSONResponse` 也可以用于导入 `Request` 和 `JSONResponse`。
+也可以使用 `from starlette.requests import Request` 和 `from starlette.responses import JSONResponse`。
- **FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应操作都可以直接从 Starlette 导入。同理,`Request` 也是如此。
+**FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为便捷方式,但大多数可用的响应都直接来自 Starlette。`Request` 也是如此。
+///
-## 覆盖默认异常处理器
+## 覆盖默认异常处理器 { #override-the-default-exception-handlers }
**FastAPI** 自带了一些默认异常处理器。
-触发 `HTTPException` 或请求无效数据时,这些处理器返回默认的 JSON 响应结果。
+当你触发 `HTTPException`,或者请求中包含无效数据时,这些处理器负责返回默认的 JSON 响应。
-不过,也可以使用自定义处理器覆盖默认异常处理器。
+你也可以用自己的处理器覆盖它们。
-### 覆盖请求验证异常
+### 覆盖请求验证异常 { #override-request-validation-exceptions }
请求中包含无效数据时,**FastAPI** 内部会触发 `RequestValidationError`。
-该异常也内置了默认异常处理器。
-
-覆盖默认异常处理器时需要导入 `RequestValidationError`,并用 `@app.excption_handler(RequestValidationError)` 装饰异常处理器。
+它也内置了该异常的默认处理器。
-这样,异常处理器就可以接收 `Request` 与异常。
+要覆盖它,导入 `RequestValidationError`,并用 `@app.exception_handler(RequestValidationError)` 装饰你的异常处理器。
-```Python hl_lines="2 14-16"
-{!../../../docs_src/handling_errors/tutorial004.py!}
+异常处理器会接收 `Request` 和该异常。
-```
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
-访问 `/items/foo`,可以看到默认的 JSON 错误信息:
+现在,访问 `/items/foo` 时,默认的 JSON 错误为:
```JSON
{
@@ -160,63 +144,46 @@
}
]
}
-
```
-被替换为了以下文本格式的错误信息:
+将得到如下文本内容:
```
-1 validation error
-path -> item_id
- value is not a valid integer (type=type_error.integer)
-
+Validation errors:
+Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer
```
-### `RequestValidationError` vs `ValidationError`
-
-!!! warning "警告"
+### 覆盖 `HTTPException` 错误处理器 { #override-the-httpexception-error-handler }
- 如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。
+同理,也可以覆盖 `HTTPException` 的处理器。
+例如,只为这些错误返回纯文本响应,而不是 JSON:
-`RequestValidationError` 是 Pydantic 的 `ValidationError` 的子类。
+{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
-**FastAPI** 调用的就是 `RequestValidationError` 类,因此,如果在 `response_model` 中使用 Pydantic 模型,且数据有错误时,在日志中就会看到这个错误。
+/// note | 技术细节
-但客户端或用户看不到这个错误。反之,客户端接收到的是 HTTP 状态码为 `500` 的「内部服务器错误」。
+还可以使用 `from starlette.responses import PlainTextResponse`。
-这是因为在*响应*或代码(不是在客户端的请求里)中出现的 Pydantic `ValidationError` 是代码的 bug。
+**FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为便捷方式,但大多数可用的响应都直接来自 Starlette。
-修复错误时,客户端或用户不能访问错误的内部信息,否则会造成安全隐患。
+///
-### 覆盖 `HTTPException` 错误处理器
+/// warning | 警告
-同理,也可以覆盖 `HTTPException` 处理器。
+请注意,`RequestValidationError` 包含发生验证错误的文件名和行号信息,你可以在需要时将其记录到日志中以提供相关信息。
-例如,只为错误返回纯文本响应,而不是返回 JSON 格式的内容:
+但这也意味着,如果你只是将其直接转换为字符串并返回,可能会泄露一些关于系统的细节信息。因此,这里的代码会提取并分别显示每个错误。
-```Python hl_lines="3-4 9-11 22"
-{!../../../docs_src/handling_errors/tutorial004.py!}
+///
-```
-
-!!! note "技术细节"
-
- 还可以使用 `from starlette.responses import PlainTextResponse`。
-
- **FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应都可以直接从 Starlette 导入。
+### 使用 `RequestValidationError` 的请求体 { #use-the-requestvalidationerror-body }
+`RequestValidationError` 包含其接收到的带有无效数据的请求体 `body`。
-### 使用 `RequestValidationError` 的请求体
+开发时,你可以用它来记录请求体、调试错误,或返回给用户等。
-`RequestValidationError` 包含其接收到的无效数据请求的 `body` 。
-
-开发时,可以用这个请求体生成日志、调试错误,并返回给用户。
-
-```Python hl_lines="14"
-{!../../../docs_src/handling_errors/tutorial005.py!}
-
-```
+{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
现在试着发送一个无效的 `item`,例如:
@@ -225,10 +192,9 @@ path -> item_id
"title": "towel",
"size": "XL"
}
-
```
-收到的响应包含 `body` 信息,并说明数据是无效的:
+收到的响应会告诉你数据无效,并包含收到的请求体:
```JSON hl_lines="12-15"
{
@@ -247,43 +213,32 @@ path -> item_id
"size": "XL"
}
}
-
```
-### FastAPI `HTTPException` vs Starlette `HTTPException`
+#### FastAPI 的 `HTTPException` vs Starlette 的 `HTTPException` { #fastapis-httpexception-vs-starlettes-httpexception }
**FastAPI** 也提供了自有的 `HTTPException`。
-**FastAPI** 的 `HTTPException` 继承自 Starlette 的 `HTTPException` 错误类。
+**FastAPI** 的 `HTTPException` 错误类继承自 Starlette 的 `HTTPException` 错误类。
-它们之间的唯一区别是,**FastAPI** 的 `HTTPException` 可以在响应中添加响应头。
+它们之间的唯一区别是,**FastAPI** 的 `HTTPException` 在 `detail` 字段中接受任意可转换为 JSON 的数据,而 Starlette 的 `HTTPException` 只接受字符串。
-OAuth 2.0 等安全工具需要在内部调用这些响应头。
-
-因此你可以继续像平常一样在代码中触发 **FastAPI** 的 `HTTPException` 。
+因此,你可以继续像平常一样在代码中触发 **FastAPI** 的 `HTTPException`。
但注册异常处理器时,应该注册到来自 Starlette 的 `HTTPException`。
-这样做是为了,当 Starlette 的内部代码、扩展或插件触发 Starlette `HTTPException` 时,处理程序能够捕获、并处理此异常。
+这样做是为了,当 Starlette 的内部代码、扩展或插件触发 Starlette `HTTPException` 时,你的处理器能够捕获并处理它。
-注意,本例代码中同时使用了这两个 `HTTPException`,此时,要把 Starlette 的 `HTTPException` 命名为 `StarletteHTTPException`:
+本例中,为了在同一份代码中同时使用两个 `HTTPException`,将 Starlette 的异常重命名为 `StarletteHTTPException`:
```Python
from starlette.exceptions import HTTPException as StarletteHTTPException
-
```
-### 复用 **FastAPI** 异常处理器
+### 复用 **FastAPI** 的异常处理器 { #reuse-fastapis-exception-handlers }
-FastAPI 支持先对异常进行某些处理,然后再使用 **FastAPI** 中处理该异常的默认异常处理器。
-
-从 `fastapi.exception_handlers` 中导入要复用的默认异常处理器:
-
-```Python hl_lines="2-5 15 21"
-{!../../../docs_src/handling_errors/tutorial006.py!}
-
-```
+如果你想在自定义处理后仍复用 **FastAPI** 的默认异常处理器,可以从 `fastapi.exception_handlers` 导入并复用这些默认处理器:
-虽然,本例只是输出了夸大其词的错误信息。
+{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
-但也足以说明,可以在处理异常之后再复用默认的异常处理器。
+虽然本例只是用非常夸张的信息打印了错误,但足以说明:你可以先处理异常,然后再复用默认的异常处理器。
diff --git a/docs/zh/docs/tutorial/header-param-models.md b/docs/zh/docs/tutorial/header-param-models.md
new file mode 100644
index 0000000000000..e7d54831737e1
--- /dev/null
+++ b/docs/zh/docs/tutorial/header-param-models.md
@@ -0,0 +1,72 @@
+# Header 参数模型 { #header-parameter-models }
+
+如果您有一组相关的 **header 参数**,您可以创建一个 **Pydantic 模型**来声明它们。
+
+这将允许您在**多个地方**能够**重用模型**,并且可以一次性声明所有参数的验证和元数据。😎
+
+/// note | 注意
+
+自 FastAPI 版本 `0.115.0` 起支持此功能。🤓
+
+///
+
+## 使用 Pydantic 模型的 Header 参数 { #header-parameters-with-a-pydantic-model }
+
+在 **Pydantic 模型**中声明所需的 **header 参数**,然后将参数声明为 `Header` :
+
+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}
+
+**FastAPI** 将从请求中接收到的 **headers** 中**提取**出**每个字段**的数据,并提供您定义的 Pydantic 模型。
+
+## 查看文档 { #check-the-docs }
+
+您可以在文档 UI 的 `/docs` 中查看所需的 headers:
+
+
+
-
-## 标签元数据
-
-你也可以使用参数 `openapi_tags`,为用于分组路径操作的不同标签添加额外的元数据。
-
-它接受一个列表,这个列表包含每个标签对应的一个字典。
-
-每个字典可以包含:
-
-* `name`(**必要**):一个 `str`,它与*路径操作*和 `APIRouter` 中使用的 `tags` 参数有相同的标签名。
-* `description`:一个用于简短描述标签的 `str`。它支持 Markdown 并且会在文档用户界面中显示。
-* `externalDocs`:一个描述外部文档的 `dict`:
- * `description`:用于简短描述外部文档的 `str`。
- * `url`(**必要**):外部文档的 URL `str`。
-
-### 创建标签元数据
-
-让我们在带有标签的示例中为 `users` 和 `items` 试一下。
-
-创建标签元数据并把它传递给 `openapi_tags` 参数:
-
-```Python hl_lines="3-16 18"
-{!../../../docs_src/metadata/tutorial004.py!}
-```
-
-注意你可以在描述内使用 Markdown,例如「login」会显示为粗体(**login**)以及「fancy」会显示为斜体(_fancy_)。
-
-!!! 提示
- 不必为你使用的所有标签都添加元数据。
-
-### 使用你的标签
-
-将 `tags` 参数和*路径操作*(以及 `APIRouter`)一起使用,将其分配给不同的标签:
-
-```Python hl_lines="21 26"
-{!../../../docs_src/metadata/tutorial004.py!}
-```
-
-!!! 信息
- 阅读更多关于标签的信息[路径操作配置](../path-operation-configuration/#tags){.internal-link target=_blank}。
-
-### 查看文档
-
-如果你现在查看文档,它们会显示所有附加的元数据:
-
-
-
-### 标签顺序
-
-每个标签元数据字典的顺序也定义了在文档用户界面显示的顺序。
-
-例如按照字母顺序,即使 `users` 排在 `items` 之后,它也会显示在前面,因为我们将它的元数据添加为列表内的第一个字典。
-
-## OpenAPI URL
-
-默认情况下,OpenAPI 模式服务于 `/openapi.json`。
-
-但是你可以通过参数 `openapi_url` 对其进行配置。
-
-例如,将其设置为服务于 `/api/v1/openapi.json`:
-
-```Python hl_lines="3"
-{!../../../docs_src/metadata/tutorial002.py!}
-```
-
-如果你想完全禁用 OpenAPI 模式,可以将其设置为 `openapi_url=None`,这样也会禁用使用它的文档用户界面。
-
-## 文档 URLs
-
-你可以配置两个文档用户界面,包括:
-
-* **Swagger UI**:服务于 `/docs`。
- * 可以使用参数 `docs_url` 设置它的 URL。
- * 可以通过设置 `docs_url=None` 禁用它。
-* ReDoc:服务于 `/redoc`。
- * 可以使用参数 `redoc_url` 设置它的 URL。
- * 可以通过设置 `redoc_url=None` 禁用它。
-
-例如,设置 Swagger UI 服务于 `/documentation` 并禁用 ReDoc:
-
-```Python hl_lines="3"
-{!../../../docs_src/metadata/tutorial003.py!}
-```
+# 元数据和文档 URL { #metadata-and-docs-urls }
+
+你可以在 FastAPI 应用程序中自定义多个元数据配置。
+
+## API 元数据 { #metadata-for-api }
+
+你可以在设置 OpenAPI 规范和自动 API 文档 UI 中使用的以下字段:
+
+| 参数 | 类型 | 描述 |
+|------------|------|-------------|
+| `title` | `str` | API 的标题。 |
+| `summary` | `str` | API 的简短摘要。 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。 |
+| `description` | `str` | API 的简短描述。可以使用 Markdown。 |
+| `version` | `string` | API 的版本。这是您自己的应用程序的版本,而不是 OpenAPI 的版本。例如 `2.5.0`。 |
+| `terms_of_service` | `str` | API 服务条款的 URL。如果提供,则必须是 URL。 |
+| `contact` | `dict` | 公开的 API 的联系信息。它可以包含多个字段。contact 字段| 参数 | 类型 | 描述 |
|---|---|---|
name | str | 联系人/组织的识别名称。 |
url | str | 指向联系信息的 URL。必须采用 URL 格式。 |
email | str | 联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。 |
license_info 字段| 参数 | 类型 | 描述 |
|---|---|---|
name | str | 必须(如果设置了 license_info)。用于 API 的许可证名称。 |
identifier | str | API 的 [SPDX](https://spdx.org/licenses/) 许可证表达式。字段 identifier 与字段 url 互斥。自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。 |
url | str | 用于 API 的许可证的 URL。必须采用 URL 格式。 |
+
+## 许可证标识符 { #license-identifier }
+
+自 OpenAPI 3.1.0 和 FastAPI 0.99.0 起,你还可以在 `license_info` 中使用 `identifier` 而不是 `url`。
+
+例如:
+
+{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *}
+
+## 标签元数据 { #metadata-for-tags }
+
+你也可以通过参数 `openapi_tags` 为用于分组路径操作的不同标签添加额外的元数据。
+
+它接收一个列表,列表中每个标签对应一个字典。
+
+每个字典可以包含:
+
+- `name`(必填):一个 `str`,与在你的*路径操作*和 `APIRouter` 的 `tags` 参数中使用的标签名相同。
+- `description`:一个 `str`,该标签的简短描述。可以使用 Markdown,并会显示在文档 UI 中。
+- `externalDocs`:一个 `dict`,描述外部文档,包含:
+ - `description`:一个 `str`,该外部文档的简短描述。
+ - `url`(必填):一个 `str`,该外部文档的 URL。
+
+### 创建标签元数据 { #create-metadata-for-tags }
+
+让我们在带有标签的示例中为 `users` 和 `items` 试一下。
+
+创建标签元数据并把它传递给 `openapi_tags` 参数:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *}
+
+注意你可以在描述内使用 Markdown,例如「login」会显示为粗体(**login**)以及「fancy」会显示为斜体(_fancy_)。
+
+/// tip | 提示
+
+不必为你使用的所有标签都添加元数据。
+
+///
+
+### 使用你的标签 { #use-your-tags }
+
+将 `tags` 参数和*路径操作*(以及 `APIRouter`)一起使用,将其分配给不同的标签:
+
+{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *}
+
+/// info | 信息
+
+阅读更多关于标签的信息[路径操作配置](path-operation-configuration.md#tags)。
+
+///
+
+### 查看文档 { #check-the-docs }
+
+如果你现在查看文档,它们会显示所有附加的元数据:
+
+
+
+### 标签顺序 { #order-of-tags }
+
+每个标签元数据字典的顺序也定义了在文档用户界面显示的顺序。
+
+例如按照字母顺序,即使 `users` 排在 `items` 之后,它也会显示在前面,因为我们将它的元数据添加为列表内的第一个字典。
+
+## OpenAPI URL { #openapi-url }
+
+默认情况下,OpenAPI 模式服务于 `/openapi.json`。
+
+但是你可以通过参数 `openapi_url` 对其进行配置。
+
+例如,将其设置为服务于 `/api/v1/openapi.json`:
+
+{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *}
+
+如果你想完全禁用 OpenAPI 模式,可以将其设置为 `openapi_url=None`,这样也会禁用使用它的文档用户界面。
+
+## 文档 URLs { #docs-urls }
+
+你可以配置两个文档用户界面,包括:
+
+- **Swagger UI**:服务于 `/docs`。
+ - 可以使用参数 `docs_url` 设置它的 URL。
+ - 可以通过设置 `docs_url=None` 禁用它。
+- **ReDoc**:服务于 `/redoc`。
+ - 可以使用参数 `redoc_url` 设置它的 URL。
+ - 可以通过设置 `redoc_url=None` 禁用它。
+
+例如,设置 Swagger UI 服务于 `/documentation` 并禁用 ReDoc:
+
+{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *}
diff --git a/docs/zh/docs/tutorial/middleware.md b/docs/zh/docs/tutorial/middleware.md
index c9a7e7725a120..e7586132f21a4 100644
--- a/docs/zh/docs/tutorial/middleware.md
+++ b/docs/zh/docs/tutorial/middleware.md
@@ -1,61 +1,95 @@
-# 中间件
+# 中间件 { #middleware }
-你可以向 **FastAPI** 应用添加中间件.
+你可以向 **FastAPI** 应用添加中间件。
-"中间件"是一个函数,它在每个**请求**被特定的*路径操作*处理之前,以及在每个**响应**返回之前工作.
+“中间件”是一个函数,它会在每个特定的*路径操作*处理每个**请求**之前运行,也会在返回每个**响应**之前运行。
-* 它接收你的应用程序的每一个**请求**.
-* 然后它可以对这个**请求**做一些事情或者执行任何需要的代码.
-* 然后它将**请求**传递给应用程序的其他部分 (通过某种*路径操作*).
-* 然后它获取应用程序生产的**响应** (通过某种*路径操作*).
-* 它可以对该**响应**做些什么或者执行任何需要的代码.
-* 然后它返回这个 **响应**.
+* 它接收你的应用的每一个**请求**。
+* 然后它可以对这个**请求**做一些事情或者执行任何需要的代码。
+* 然后它将这个**请求**传递给应用程序的其他部分(某个*路径操作*)处理。
+* 之后它获取应用程序生成的**响应**(由某个*路径操作*产生)。
+* 它可以对该**响应**做一些事情或者执行任何需要的代码。
+* 然后它返回这个**响应**。
-!!! note "技术细节"
- 如果你使用了 `yield` 关键字依赖, 依赖中的退出代码将在执行中间件*后*执行.
+/// note | 技术细节
- 如果有任何后台任务(稍后记录), 它们将在执行中间件*后*运行.
+如果你有使用 `yield` 的依赖,依赖中的退出代码会在中间件之后运行。
-## 创建中间件
+如果有任何后台任务(会在[后台任务](background-tasks.md)一节中介绍,你稍后会看到),它们会在所有中间件之后运行。
-要创建中间件你可以在函数的顶部使用装饰器 `@app.middleware("http")`.
+///
-中间件参数接收如下参数:
+## 创建中间件 { #create-a-middleware }
-* `request`.
-* 一个函数 `call_next` 它将接收 `request` 作为参数.
- * 这个函数将 `request` 传递给相应的 *路径操作*.
- * 然后它将返回由相应的*路径操作*生成的 `response`.
-* 然后你可以在返回 `response` 前进一步修改它.
+要创建中间件,你可以在函数的顶部使用装饰器 `@app.middleware("http")`。
-```Python hl_lines="8-9 11 14"
-{!../../../docs_src/middleware/tutorial001.py!}
-```
+中间件函数会接收:
+
+* `request`。
+* 一个函数 `call_next`,它会把 `request` 作为参数接收。
+ * 这个函数会把 `request` 传递给相应的*路径操作*。
+ * 然后它返回由相应*路径操作*生成的 `response`。
+* 在返回之前,你可以进一步修改 `response`。
+
+{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *}
+
+/// tip
+
+请记住可以[使用 `X-` 前缀](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers)添加专有自定义请求头。
+
+但是如果你有希望让浏览器中的客户端可见的自定义请求头,你需要把它们加到你的 CORS 配置([CORS(跨域资源共享)](cors.md))的 `expose_headers` 参数中,参见 [Starlette 的 CORS 文档](https://www.starlette.dev/middleware/#corsmiddleware)。
+
+///
+
+/// note | 技术细节
+
+你也可以使用 `from starlette.requests import Request`。
+
+**FastAPI** 为了开发者方便提供了该对象,但它直接来自 Starlette。
-!!! tip
- 请记住可以 用'X-' 前缀添加专有自定义请求头.
+///
- 但是如果你想让浏览器中的客户端看到你的自定义请求头, 你需要把它们加到 CORS 配置 ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) 的 `expose_headers` 参数中,在 Starlette's CORS docs文档中.
+### 在 `response` 之前与之后 { #before-and-after-the-response }
-!!! note "技术细节"
- 你也可以使用 `from starlette.requests import Request`.
+你可以在任何*路径操作*接收 `request` 之前,添加要与该 `request` 一起运行的代码。
- **FastAPI** 为了开发者方便提供了该对象. 但其实它直接来自于 Starlette.
+也可以在生成 `response` 之后、返回之前添加代码。
-### 在 `response` 的前和后
+例如,你可以添加一个自定义请求头 `X-Process-Time`,其值为处理请求并生成响应所花费的秒数:
-在任何*路径操作*收到`request`前,可以添加要和请求一起运行的代码.
+{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *}
-也可以在*响应*生成但是返回之前添加代码.
+/// tip
-例如你可以添加自定义请求头 `X-Process-Time` 包含以秒为单位的接收请求和生成响应的时间:
+这里我们使用 [`time.perf_counter()`](https://docs.python.org/3/library/time.html#time.perf_counter) 而不是 `time.time()`,因为在这类场景中它可能更精确。🤓
-```Python hl_lines="10 12-13"
-{!../../../docs_src/middleware/tutorial001.py!}
+///
+
+## 多个中间件的执行顺序 { #multiple-middleware-execution-order }
+
+当你使用 `@app.middleware()` 装饰器或 `app.add_middleware()` 方法添加多个中间件时,每个新中间件都会包裹应用,形成一个栈。最后添加的中间件是“最外层”的,最先添加的是“最内层”的。
+
+在请求路径上,最外层的中间件先运行。
+
+在响应路径上,它最后运行。
+
+例如:
+
+```Python
+app.add_middleware(MiddlewareA)
+app.add_middleware(MiddlewareB)
```
-## 其他中间件
+这会产生如下执行顺序:
+
+* 请求:MiddlewareB → MiddlewareA → 路由
+
+* 响应:路由 → MiddlewareA → MiddlewareB
+
+这种栈式行为确保中间件按可预测且可控的顺序执行。
+
+## 其他中间件 { #other-middlewares }
-你可以稍后在 [Advanced User Guide: Advanced Middleware](../advanced/middleware.md){.internal-link target=_blank}阅读更多关于中间件的教程.
+你可以稍后在[高级用户指南:高级中间件](../advanced/middleware.md)中阅读更多关于其他中间件的内容。
-你将在下一节中学习如何使用中间件处理 CORS .
+你将在下一节中了解如何使用中间件处理 CORS。
diff --git a/docs/zh/docs/tutorial/path-operation-configuration.md b/docs/zh/docs/tutorial/path-operation-configuration.md
index f79b0e692d8cd..b9046a13be120 100644
--- a/docs/zh/docs/tutorial/path-operation-configuration.md
+++ b/docs/zh/docs/tutorial/path-operation-configuration.md
@@ -1,92 +1,98 @@
-# 路径操作配置
+# 路径操作配置 { #path-operation-configuration }
*路径操作装饰器*支持多种配置参数。
-!!! warning "警告"
+/// warning | 警告
- 注意:以下参数应直接传递给**路径操作装饰器**,不能传递给*路径操作函数*。
+注意:以下参数应直接传递给*路径操作装饰器*,不能传递给*路径操作函数*。
-## `status_code` 状态码
+///
-`status_code` 用于定义*路径操作*响应中的 HTTP 状态码。
+## 响应状态码 { #response-status-code }
-可以直接传递 `int` 代码, 比如 `404`。
+可以在*路径操作*的响应中定义(HTTP)`status_code`。
-如果记不住数字码的涵义,也可以用 `status` 的快捷常量:
+可以直接传递 `int` 代码,比如 `404`。
-```Python hl_lines="3 17"
-{!../../../docs_src/path_operation_configuration/tutorial001.py!}
-```
+如果记不住数字码的含义,也可以用 `status` 的快捷常量:
-状态码在响应中使用,并会被添加到 OpenAPI 概图。
+{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *}
-!!! note "技术细节"
+该状态码会用于响应中,并会被添加到 OpenAPI 概图。
- 也可以使用 `from starlette import status` 导入状态码。
+/// note | 技术细节
- **FastAPI** 的`fastapi.status` 和 `starlette.status` 一样,只是快捷方式。实际上,`fastapi.status` 直接继承自 Starlette。
+也可以使用 `from starlette import status` 导入状态码。
-## `tags` 参数
+**FastAPI** 提供的 `fastapi.status` 与 `starlette.status` 相同,方便你作为开发者使用。实际上它直接来自 Starlette。
-`tags` 参数的值是由 `str` 组成的 `list` (一般只有一个 `str` ),`tags` 用于为*路径操作*添加标签:
+///
-```Python hl_lines="17 22 27"
-{!../../../docs_src/path_operation_configuration/tutorial002.py!}
-```
+## 标签 { #tags }
+
+可以通过传入由 `str` 组成的 `list`(通常只有一个 `str`)的参数 `tags`,为*路径操作*添加标签:
+
+{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *}
OpenAPI 概图会自动添加标签,供 API 文档接口使用:
-## `summary` 和 `description` 参数
+### 使用 Enum 的标签 { #tags-with-enums }
+
+如果你的应用很大,可能会积累出很多标签,你会希望确保相关的*路径操作*始终使用相同的标签。
+
+这种情况下,把标签存放在 `Enum` 中会更合适。
+
+**FastAPI** 对此的支持与使用普通字符串相同:
-路径装饰器还支持 `summary` 和 `description` 这两个参数:
+{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *}
-```Python hl_lines="20-21"
-{!../../../docs_src/path_operation_configuration/tutorial003.py!}
-```
+## 摘要和描述 { #summary-and-description }
-## 文档字符串(`docstring`)
+可以添加 `summary` 和 `description`:
-描述内容比较长且占用多行时,可以在函数的 docstring 中声明*路径操作*的描述,**FastAPI** 支持从文档字符串中读取描述内容。
+{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *}
-文档字符串支持 Markdown,能正确解析和显示 Markdown 的内容,但要注意文档字符串的缩进。
+## 从 docstring 获取描述 { #description-from-docstring }
-```Python hl_lines="19-27"
-{!../../../docs_src/path_operation_configuration/tutorial004.py!}
-```
+描述内容比较长且占用多行时,可以在函数的 docstring 中声明*路径操作*的描述,**FastAPI** 会从中读取。
-下图为 Markdown 文本在 API 文档中的显示效果:
+文档字符串支持 [Markdown](https://en.wikipedia.org/wiki/Markdown),能正确解析和显示 Markdown 的内容,但要注意文档字符串的缩进。
+
+{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *}
+
+它会在交互式文档中使用:
-## 响应描述
+## 响应描述 { #response-description }
`response_description` 参数用于定义响应的描述说明:
-```Python hl_lines="21"
-{!../../../docs_src/path_operation_configuration/tutorial005.py!}
-```
+{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *}
+
+/// info | 信息
+
+注意,`response_description` 只用于描述响应,`description` 一般则用于描述*路径操作*。
-!!! info "说明"
+///
- 注意,`response_description` 只用于描述响应,`description` 一般则用于描述*路径操作*。
+/// check | 检查
-!!! check "检查"
+OpenAPI 规定每个*路径操作*都要有响应描述。
- OpenAPI 规定每个*路径操作*都要有响应描述。
+如果没有定义响应描述,**FastAPI** 则自动生成内容为 "Successful response" 的响应描述。
- 如果没有定义响应描述,**FastAPI** 则自动生成内容为 "Successful response" 的响应描述。
+///
-## 弃用*路径操作*
+## 弃用*路径操作* { #deprecate-a-path-operation }
-`deprecated` 参数可以把*路径操作*标记为弃用,无需直接删除:
+如果需要把*路径操作*标记为弃用,但不删除它,可以传入 `deprecated` 参数:
-```Python hl_lines="16"
-{!../../../docs_src/path_operation_configuration/tutorial006.py!}
-```
+{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *}
API 文档会把该路径操作标记为弃用:
@@ -96,6 +102,6 @@ API 文档会把该路径操作标记为弃用:
-## 小结
+## 小结 { #recap }
-通过传递参数给*路径操作装饰器* ,即可轻松地配置*路径操作*、添加元数据。
+通过传递参数给*路径操作装饰器*,即可轻松地配置*路径操作*、添加元数据。
diff --git a/docs/zh/docs/tutorial/path-params-numeric-validations.md b/docs/zh/docs/tutorial/path-params-numeric-validations.md
index 78fa922b49ee7..26b91c1d731b1 100644
--- a/docs/zh/docs/tutorial/path-params-numeric-validations.md
+++ b/docs/zh/docs/tutorial/path-params-numeric-validations.md
@@ -1,171 +1,128 @@
-# 路径参数和数值校验
+# 路径参数和数值校验 { #path-parameters-and-numeric-validations }
与使用 `Query` 为查询参数声明更多的校验和元数据的方式相同,你也可以使用 `Path` 为路径参数声明相同类型的校验和元数据。
-## 导入 Path
+## 导入 `Path` { #import-path }
-首先,从 `fastapi` 导入 `Path`:
+首先,从 `fastapi` 导入 `Path`,并导入 `Annotated`:
-=== "Python 3.10+"
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *}
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+/// info | 信息
-=== "Python 3.9+"
+FastAPI 在 0.95.0 版本添加了对 `Annotated` 的支持(并开始推荐使用它)。
- ```Python hl_lines="1 3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+如果你使用的是更旧的版本,尝试使用 `Annotated` 会报错。
-=== "Python 3.6+"
+请确保在使用 `Annotated` 之前,将 FastAPI 版本[升级](../deployment/versions.md#upgrading-the-fastapi-versions)到至少 0.95.1。
- ```Python hl_lines="3-4"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+///
-=== "Python 3.10+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="1"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
-
-=== "Python 3.6+ non-Annotated"
-
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
-
- ```Python hl_lines="3"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
-
-## 声明元数据
+## 声明元数据 { #declare-metadata }
你可以声明与 `Query` 相同的所有参数。
-例如,要声明路径参数 `item_id`的 `title` 元数据值,你可以输入:
+例如,要为路径参数 `item_id` 声明 `title` 元数据值,你可以这样写:
-=== "Python 3.10+"
+{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *}
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!}
- ```
+/// note | 注意
-=== "Python 3.9+"
+路径参数总是必需的,因为它必须是路径的一部分。即使你将其声明为 `None` 或设置了默认值,也不会产生任何影响,它依然始终是必需参数。
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!}
- ```
+///
-=== "Python 3.6+"
+## 按需对参数排序 { #order-the-parameters-as-you-need }
- ```Python hl_lines="11"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!}
- ```
+/// tip | 提示
-=== "Python 3.10+ non-Annotated"
+如果你使用 `Annotated`,这点可能不那么重要或必要。
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+///
- ```Python hl_lines="8"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!}
- ```
+假设你想要将查询参数 `q` 声明为必需的 `str`。
-=== "Python 3.6+ non-Annotated"
+并且你不需要为该参数声明其他内容,所以实际上不需要用到 `Query`。
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+但是你仍然需要为路径参数 `item_id` 使用 `Path`。并且出于某些原因你不想使用 `Annotated`。
- ```Python hl_lines="10"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!}
- ```
+如果你将带有“默认值”的参数放在没有“默认值”的参数之前,Python 会报错。
-!!! note
- 路径参数总是必需的,因为它必须是路径的一部分。
+不过你可以重新排序,让没有默认值的参数(查询参数 `q`)放在最前面。
- 所以,你应该在声明时使用 `...` 将其标记为必需参数。
+对 **FastAPI** 来说这无关紧要。它会通过参数的名称、类型和默认值声明(`Query`、`Path` 等)来检测参数,而不关心顺序。
- 然而,即使你使用 `None` 声明路径参数或设置一个其他默认值也不会有任何影响,它依然会是必需参数。
+因此,你可以将函数声明为:
-## 按需对参数排序
+{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *}
-假设你想要声明一个必需的 `str` 类型查询参数 `q`。
+但请记住,如果你使用 `Annotated`,你就不会遇到这个问题,因为你没有使用 `Query()` 或 `Path()` 作为函数参数的默认值。
-而且你不需要为该参数声明任何其他内容,所以实际上你并不需要使用 `Query`。
+{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *}
-但是你仍然需要使用 `Path` 来声明路径参数 `item_id`。
+## 按需对参数排序的技巧 { #order-the-parameters-as-you-need-tricks }
-如果你将带有「默认值」的参数放在没有「默认值」的参数之前,Python 将会报错。
+/// tip | 提示
-但是你可以对其重新排序,并将不带默认值的值(查询参数 `q`)放到最前面。
+如果你使用 `Annotated`,这点可能不那么重要或必要。
-对 **FastAPI** 来说这无关紧要。它将通过参数的名称、类型和默认值声明(`Query`、`Path` 等)来检测参数,而不在乎参数的顺序。
+///
-因此,你可以将函数声明为:
+这里有一个小技巧,可能会很方便,但你并不会经常需要它。
+
+如果你想要:
-=== "Python 3.6 non-Annotated"
+* 在没有 `Query` 且没有任何默认值的情况下声明查询参数 `q`
+* 使用 `Path` 声明路径参数 `item_id`
+* 让它们的顺序与上面不同
+* 不使用 `Annotated`
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+...Python 为此有一个小的特殊语法。
- ```Python hl_lines="7"
- {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
- ```
+在函数的第一个参数位置传入 `*`。
-## 按需对参数排序的技巧
+Python 不会对这个 `*` 做任何事,但它会知道之后的所有参数都应该作为关键字参数(键值对)来调用,也被称为 kwargs。即使它们没有默认值。
-如果你想不使用 `Query` 声明没有默认值的查询参数 `q`,同时使用 `Path` 声明路径参数 `item_id`,并使它们的顺序与上面不同,Python 对此有一些特殊的语法。
+{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *}
-传递 `*` 作为函数的第一个参数。
+### 使用 `Annotated` 更好 { #better-with-annotated }
-Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参数都应作为关键字参数(键值对),也被称为 kwargs,来调用。即使它们没有默认值。
+请记住,如果你使用 `Annotated`,因为你没有使用函数参数的默认值,所以你不会有这个问题,你大概率也不需要使用 `*`。
-```Python hl_lines="7"
-{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *}
-## 数值校验:大于等于
+## 数值校验:大于等于 { #number-validations-greater-than-or-equal }
-使用 `Query` 和 `Path`(以及你将在后面看到的其他类)可以声明字符串约束,但也可以声明数值约束。
+使用 `Query` 和 `Path`(以及你稍后会看到的其他类)你可以声明数值约束。
-像下面这样,添加 `ge=1` 后,`item_id` 将必须是一个大于(`g`reater than)或等于(`e`qual)`1` 的整数。
+在这里,使用 `ge=1` 后,`item_id` 必须是一个整数,值要「`g`reater than or `e`qual」1。
-```Python hl_lines="8"
-{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *}
-## 数值校验:大于和小于等于
+## 数值校验:大于和小于等于 { #number-validations-greater-than-and-less-than-or-equal }
-同样的规则适用于:
+同样适用于:
* `gt`:大于(`g`reater `t`han)
* `le`:小于等于(`l`ess than or `e`qual)
-```Python hl_lines="9"
-{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *}
-## 数值校验:浮点数、大于和小于
+## 数值校验:浮点数、大于和小于 { #number-validations-floats-greater-than-and-less-than }
数值校验同样适用于 `float` 值。
-能够声明 gt 而不仅仅是 ge 在这个前提下变得重要起来。例如,你可以要求一个值必须大于 `0`,即使它小于 `1`。
+能够声明 gt 而不仅仅是 ge 在这里变得很重要。例如,你可以要求一个值必须大于 `0`,即使它小于 `1`。
-因此,`0.5` 将是有效值。但是 `0.0`或 `0` 不是。
+因此,`0.5` 将是有效值。但是 `0.0` 或 `0` 不是。
-对于 lt 也是一样的。
+对于 lt 也是一样的。
-```Python hl_lines="11"
-{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
-```
+{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *}
-## 总结
+## 总结 { #recap }
-你能够以与 [查询参数和字符串校验](query-params-str-validations.md){.internal-link target=_blank} 相同的方式使用 `Query`、`Path`(以及其他你还没见过的类)声明元数据和字符串校验。
+你能够以与[查询参数和字符串校验](query-params-str-validations.md)相同的方式使用 `Query`、`Path`(以及其他你还没见过的类)声明元数据和字符串校验。
而且你还可以声明数值校验:
@@ -174,18 +131,24 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参
* `lt`:小于(`l`ess `t`han)
* `le`:小于等于(`l`ess than or `e`qual)
-!!! info
- `Query`、`Path` 以及你后面会看到的其他类继承自一个共同的 `Param` 类(不需要直接使用它)。
+/// info | 信息
+
+`Query`、`Path` 以及你后面会看到的其他类,都是一个通用 `Param` 类的子类。
+
+它们都共享相同的参数,用于你已看到的额外校验和元数据。
+
+///
+
+/// note | 注意
- 而且它们都共享相同的所有你已看到并用于添加额外校验和元数据的参数。
+当你从 `fastapi` 导入 `Query`、`Path` 和其他对象时,它们实际上是函数。
-!!! note "技术细节"
- 当你从 `fastapi` 导入 `Query`、`Path` 和其他同类对象时,它们实际上是函数。
+当被调用时,它们会返回同名类的实例。
- 当被调用时,它们返回同名类的实例。
+也就是说,你导入的是函数 `Query`。当你调用它时,它会返回一个同名的 `Query` 类的实例。
- 如此,你导入 `Query` 这个函数。当你调用它时,它将返回一个同样命名为 `Query` 的类的实例。
+之所以使用这些函数(而不是直接使用类),是为了让你的编辑器不要因为它们的类型而标记错误。
- 因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。
+这样你就可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。
- 这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。
+///
diff --git a/docs/zh/docs/tutorial/path-params.md b/docs/zh/docs/tutorial/path-params.md
index 1b428d6627112..df9210673c498 100644
--- a/docs/zh/docs/tutorial/path-params.md
+++ b/docs/zh/docs/tutorial/path-params.md
@@ -1,234 +1,251 @@
-# 路径参数
+# 路径参数 { #path-parameters }
-你可以使用与 Python 格式化字符串相同的语法来声明路径"参数"或"变量":
+你可以使用与 Python 字符串格式化相同的语法声明路径“参数”或“变量”:
-```Python hl_lines="6-7"
-{!../../../docs_src/path_params/tutorial001.py!}
-```
+{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *}
-路径参数 `item_id` 的值将作为参数 `item_id` 传递给你的函数。
+路径参数 `item_id` 的值会作为参数 `item_id` 传递给你的函数。
-所以,如果你运行示例并访问 http://127.0.0.1:8000/items/foo,将会看到如下响应:
+运行示例并访问 [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo),可获得如下响应:
```JSON
{"item_id":"foo"}
```
-## 有类型的路径参数
+## 声明路径参数的类型 { #path-parameters-with-types }
-你可以使用标准的 Python 类型标注为函数中的路径参数声明类型。
+使用 Python 标准类型注解,声明路径操作函数中路径参数的类型:
-```Python hl_lines="7"
-{!../../../docs_src/path_params/tutorial002.py!}
-```
+{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *}
+
+本例把 `item_id` 的类型声明为 `int`。
+
+/// check | 检查
-在这个例子中,`item_id` 被声明为 `int` 类型。
+类型声明将为函数提供错误检查、代码补全等编辑器支持。
-!!! check
- 这将为你的函数提供编辑器支持,包括错误检查、代码补全等等。
+///
-## 数据转换
+## 数据转换 { #data-conversion }
-如果你运行示例并打开浏览器访问 http://127.0.0.1:8000/items/3,将得到如下响应:
+运行示例并访问 [http://127.0.0.1:8000/items/3](http://127.0.0.1:8000/items/3),返回的响应如下:
```JSON
{"item_id":3}
```
-!!! check
- 注意函数接收(并返回)的值为 3,是一个 Python `int` 值,而不是字符串 `"3"`。
+/// check | 检查
- 所以,**FastAPI** 通过上面的类型声明提供了对请求的自动"解析"。
+注意,函数接收并返回的值是 `3`( `int`),不是 `"3"`(`str`)。
-## 数据校验
+**FastAPI** 通过类型声明自动进行请求的解析。
-但如果你通过浏览器访问 http://127.0.0.1:8000/items/foo,你会看到一个清晰可读的 HTTP 错误:
+///
+
+## 数据校验 { #data-validation }
+
+通过浏览器访问 [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo),接收如下 HTTP 错误信息:
```JSON
{
- "detail": [
- {
- "loc": [
- "path",
- "item_id"
- ],
- "msg": "value is not a valid integer",
- "type": "type_error.integer"
- }
- ]
+ "detail": [
+ {
+ "type": "int_parsing",
+ "loc": [
+ "path",
+ "item_id"
+ ],
+ "msg": "Input should be a valid integer, unable to parse string as an integer",
+ "input": "foo"
+ }
+ ]
}
```
-因为路径参数 `item_id` 传入的值为 `"foo"`,它不是一个 `int`。
+这是因为路径参数 `item_id` 的值(`"foo"`)的类型不是 `int`。
-如果你提供的是 `float` 而非整数也会出现同样的错误,比如: http://127.0.0.1:8000/items/4.2
+值的类型不是 `int` 而是浮点数(`float`)时也会显示同样的错误,比如: [http://127.0.0.1:8000/items/4.2](http://127.0.0.1:8000/items/4.2)
-!!! check
- 所以,通过同样的 Python 类型声明,**FastAPI** 提供了数据校验功能。
+/// check | 检查
- 注意上面的错误同样清楚地指出了校验未通过的具体原因。
+**FastAPI** 使用同样的 Python 类型声明实现了数据校验。
- 在开发和调试与你的 API 进行交互的代码时,这非常有用。
+注意,上面的错误清晰地指出了未通过校验的具体位置。
-## 文档
+这在开发调试与 API 交互的代码时非常有用。
-当你打开浏览器访问 http://127.0.0.1:8000/docs,你将看到自动生成的交互式 API 文档:
+///
-
+## 文档 { #documentation }
-!!! check
- 再一次,还是通过相同的 Python 类型声明,**FastAPI** 为你提供了自动生成的交互式文档(集成 Swagger UI)。
+访问 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs),查看自动生成的交互式 API 文档:
- 注意这里的路径参数被声明为一个整数。
+
-## 基于标准的好处:可选文档
+/// check | 检查
-由于生成的 API 模式来自于 OpenAPI 标准,所以有很多工具与其兼容。
+还是使用 Python 类型声明,**FastAPI** 提供了(集成 Swagger UI 的)自动交互式文档。
-正因如此,**FastAPI** 内置了一个可选的 API 文档(使用 Redoc):
+注意,路径参数的类型是整数。
-
+///
-同样的,还有很多其他兼容的工具,包括适用于多种语言的代码生成工具。
+## 基于标准的好处,备选文档 { #standards-based-benefits-alternative-documentation }
-## Pydantic
+**FastAPI** 使用 [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md) 生成概图,所以能兼容很多工具。
-所有的数据校验都由 Pydantic 在幕后完成,所以你可以从它所有的优点中受益。并且你知道它在这方面非常胜任。
+因此,**FastAPI** 还内置了 ReDoc 生成的备选 API 文档,可在此查看 [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc):
-你可以使用同样的类型声明来声明 `str`、`float`、`bool` 以及许多其他的复合数据类型。
+
-本教程的下一章节将探讨其中的一些内容。
+同样,还有很多兼容工具,包括多种语言的代码生成工具。
-## 顺序很重要
+## Pydantic { #pydantic }
-在创建*路径操作*时,你会发现有些情况下路径是固定的。
+FastAPI 充分地利用了 [Pydantic](https://docs.pydantic.dev/) 的优势,用它在后台校验数据。众所周知,Pydantic 擅长的就是数据校验。
-比如 `/users/me`,我们假设它用来获取关于当前用户的数据.
+同样,`str`、`float`、`bool` 以及很多复合数据类型都可以使用类型声明。
-然后,你还可以使用路径 `/users/{user_id}` 来通过用户 ID 获取关于特定用户的数据。
+接下来的章节会介绍其中的好几种。
-由于*路径操作*是按顺序依次运行的,你需要确保路径 `/users/me` 声明在路径 `/users/{user_id}`之前:
-```Python hl_lines="6 11"
-{!../../../docs_src/path_params/tutorial003.py!}
-```
+## 顺序很重要 { #order-matters }
-否则,`/users/{user_id}` 的路径还将与 `/users/me` 相匹配,"认为"自己正在接收一个值为 `"me"` 的 `user_id` 参数。
+有时,*路径操作*中的路径是写死的。
-## 预设值
+比如要使用 `/users/me` 获取当前用户的数据。
-如果你有一个接收路径参数的路径操作,但你希望预先设定可能的有效参数值,则可以使用标准的 Python `Enum` 类型。
+然后还要使用 `/users/{user_id}`,通过用户 ID 获取指定用户的数据。
-### 创建一个 `Enum` 类
+由于*路径操作*是按顺序依次运行的,因此,一定要在 `/users/{user_id}` 之前声明 `/users/me` :
-导入 `Enum` 并创建一个继承自 `str` 和 `Enum` 的子类。
+{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *}
-通过从 `str` 继承,API 文档将能够知道这些值必须为 `string` 类型并且能够正确地展示出来。
+否则,`/users/{user_id}` 将匹配 `/users/me`,FastAPI 会**认为**正在接收值为 `"me"` 的 `user_id` 参数。
-然后创建具有固定值的类属性,这些固定值将是可用的有效值:
+同样,你不能重复定义一个路径操作:
-```Python hl_lines="1 6-9"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *}
-!!! info
- 枚举(或 enums)从 3.4 版本起在 Python 中可用。
+由于路径首先匹配,始终会使用第一个定义的。
-!!! tip
- 如果你想知道,"AlexNet"、"ResNet" 和 "LeNet" 只是机器学习中的模型名称。
+## 预设值 { #predefined-values }
-### 声明*路径参数*
+路径操作使用 Python 的 `Enum` 类型接收预设的路径参数。
-然后使用你定义的枚举类(`ModelName`)创建一个带有类型标注的*路径参数*:
+### 创建 `Enum` 类 { #create-an-enum-class }
-```Python hl_lines="16"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+导入 `Enum` 并创建继承自 `str` 和 `Enum` 的子类。
-### 查看文档
+通过从 `str` 继承,API 文档就能把值的类型定义为**字符串**,并且能正确渲染。
-因为已经指定了*路径参数*的可用值,所以交互式文档可以恰当地展示它们:
+然后,创建包含固定值的类属性,这些固定值是可用的有效值:
-
+{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *}
-### 使用 Python *枚举类型*
+/// tip | 提示
-*路径参数*的值将是一个*枚举成员*。
+**AlexNet**、**ResNet**、**LeNet** 是机器学习模型的名字。
-#### 比较*枚举成员*
+///
-你可以将它与你创建的枚举类 `ModelName` 中的*枚举成员*进行比较:
+### 声明路径参数 { #declare-a-path-parameter }
-```Python hl_lines="17"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+使用 Enum 类(`ModelName`)创建使用类型注解的路径参数:
-#### 获取*枚举值*
+{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *}
-你可以使用 `model_name.value` 或通常来说 `your_enum_member.value` 来获取实际的值(在这个例子中为 `str`):
+### 查看文档 { #check-the-docs }
-```Python hl_lines="19"
-{!../../../docs_src/path_params/tutorial005.py!}
-```
+API 文档会显示预定义路径参数的可用值:
+
+
+
+### 使用 Python 枚举 { #working-with-python-enumerations }
+
+路径参数的值是一个枚举成员。
+
+#### 比较枚举成员 { #compare-enumeration-members }
-!!! tip
- 你也可以通过 `ModelName.lenet.value` 来获取值 `"lenet"`。
+可以将其与枚举类 `ModelName` 中的枚举成员进行比较:
-#### 返回*枚举成员*
+{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *}
-你可以从*路径操作*中返回*枚举成员*,即使嵌套在 JSON 结构中(例如一个 `dict` 中)。
+#### 获取枚举值 { #get-the-enumeration-value }
-在返回给客户端之前,它们将被转换为对应的值:
+使用 `model_name.value` 或通用的 `your_enum_member.value` 获取实际的值(本例中为 `str`):
-```Python hl_lines="18-21"
-{!../../../docs_src/path_params/tutorial005.py!}
+{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *}
+
+/// tip | 提示
+
+使用 `ModelName.lenet.value` 也能获取值 `"lenet"`。
+
+///
+
+#### 返回枚举成员 { #return-enumeration-members }
+
+即使嵌套在 JSON 请求体里(例如,`dict`),也可以从路径操作返回枚举成员。
+
+返回给客户端之前,会把枚举成员转换为对应的值(本例中为字符串):
+
+{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *}
+
+客户端中的 JSON 响应如下:
+
+```JSON
+{
+ "model_name": "alexnet",
+ "message": "Deep Learning FTW!"
+}
```
-## 包含路径的路径参数
+## 包含路径的路径参数 { #path-parameters-containing-paths }
-假设你有一个*路径操作*,它的路径为 `/files/{file_path}`。
+假设路径操作的路径为 `/files/{file_path}`。
-但是你需要 `file_path` 自身也包含*路径*,比如 `home/johndoe/myfile.txt`。
+但需要 `file_path` 中也包含路径,比如,`home/johndoe/myfile.txt`。
-因此,该文件的URL将类似于这样:`/files/home/johndoe/myfile.txt`。
+此时,该文件的 URL 是这样的:`/files/home/johndoe/myfile.txt`。
-### OpenAPI 支持
+### OpenAPI 支持 { #openapi-support }
-OpenAPI 不支持任何方式去声明*路径参数*以在其内部包含*路径*,因为这可能会导致难以测试和定义的情况出现。
+OpenAPI 不支持声明包含路径的路径参数,因为这会导致测试和定义更加困难。
-不过,你仍然可以通过 Starlette 的一个内部工具在 **FastAPI** 中实现它。
+不过,仍可使用 Starlette 内置工具在 **FastAPI** 中实现这一功能。
-而且文档依旧可以使用,但是不会添加任何该参数应包含路径的说明。
+而且不影响文档正常运行,但是不会添加该参数包含路径的说明。
-### 路径转换器
+### 路径转换器 { #path-convertor }
-你可以使用直接来自 Starlette 的选项来声明一个包含*路径*的*路径参数*:
+直接使用 Starlette 的选项声明包含路径的路径参数:
```
/files/{file_path:path}
```
-在这种情况下,参数的名称为 `file_path`,结尾部分的 `:path` 说明该参数应匹配任意的*路径*。
+本例中,参数名为 `file_path`,结尾部分的 `:path` 说明该参数应匹配路径。
-因此,你可以这样使用它:
+用法如下:
-```Python hl_lines="6"
-{!../../../docs_src/path_params/tutorial004.py!}
-```
+{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *}
+
+/// tip | 提示
+
+注意,包含 `/home/johndoe/myfile.txt` 的路径参数要以斜杠(`/`)开头。
-!!! tip
- 你可能会需要参数包含 `/home/johndoe/myfile.txt`,以斜杠(`/`)开头。
+本例中的 URL 是 `/files//home/johndoe/myfile.txt`。注意,`files` 和 `home` 之间要使用双斜杠(`//`)。
- 在这种情况下,URL 将会是 `/files//home/johndoe/myfile.txt`,在`files` 和 `home` 之间有一个双斜杠(`//`)。
+///
-## 总结
+## 小结 { #recap }
-使用 **FastAPI**,通过简短、直观和标准的 Python 类型声明,你将获得:
+通过简短、直观的 Python 标准类型声明,**FastAPI** 可以获得:
-* 编辑器支持:错误检查,代码补全等
-* 数据 "解析"
-* 数据校验
-* API 标注和自动生成的文档
+- 编辑器支持:错误检查,代码自动补全等
+- 数据 "解析"
+- 数据校验
+- API 注解和自动文档
-而且你只需要声明一次即可。
+只需要声明一次即可。
-这可能是 **FastAPI** 与其他框架相比主要的明显优势(除了原始性能以外)。
+这可能是除了性能以外,**FastAPI** 与其它框架相比的主要优势。
diff --git a/docs/zh/docs/tutorial/query-param-models.md b/docs/zh/docs/tutorial/query-param-models.md
new file mode 100644
index 0000000000000..fc691839d5a91
--- /dev/null
+++ b/docs/zh/docs/tutorial/query-param-models.md
@@ -0,0 +1,68 @@
+# 查询参数模型 { #query-parameter-models }
+
+如果你有一组具有相关性的**查询参数**,你可以创建一个 **Pydantic 模型**来声明它们。
+
+这将允许你在**多个地方**去**复用模型**,并且一次性为所有参数声明验证和元数据。😎
+
+/// note | 注意
+
+FastAPI 从 `0.115.0` 版本开始支持这个特性。🤓
+
+///
+
+## 使用 Pydantic 模型的查询参数 { #query-parameters-with-a-pydantic-model }
+
+在一个 **Pydantic 模型**中声明你需要的**查询参数**,然后将参数声明为 `Query`:
+
+{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}
+
+**FastAPI** 将会从请求的**查询参数**中**提取**出**每个字段**的数据,并将其提供给你定义的 Pydantic 模型。
+
+## 查看文档 { #check-the-docs }
+
+你可以在 `/docs` 页面的 UI 中查看查询参数:
+
+
+
+///
-### 具有默认值的查询参数列表 / 多个值
+交互式 API 文档会相应更新,以支持多个值:
-你还可以定义在没有任何给定值时的默认 `list` 值:
+
-```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial012.py!}
-```
+### 具有默认值的查询参数列表 / 多个值 { #query-parameter-list-multiple-values-with-defaults }
+
+你还可以定义在没有给定值时的默认 `list`:
+
+{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *}
如果你访问:
@@ -227,97 +287,163 @@ http://localhost:8000/items/
}
```
-#### 使用 `list`
+#### 只使用 `list` { #using-just-list }
-你也可以直接使用 `list` 代替 `List [str]`:
+你也可以直接使用 `list`,而不是 `list[str]`:
-```Python hl_lines="7"
-{!../../../docs_src/query_params_str_validations/tutorial013.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *}
+
+/// note | 注意
-!!! note
- 请记住,在这种情况下 FastAPI 将不会检查列表的内容。
+请记住,在这种情况下 FastAPI 不会检查列表的内容。
- 例如,`List[int]` 将检查(并记录到文档)列表的内容必须是整数。但是单独的 `list` 不会。
+例如,`list[int]` 会检查(并记录到文档)列表的内容必须是整数。但仅用 `list` 不会。
-## 声明更多元数据
+///
+
+## 声明更多元数据 { #declare-more-metadata }
你可以添加更多有关该参数的信息。
-这些信息将包含在生成的 OpenAPI 模式中,并由文档用户界面和外部工具所使用。
+这些信息会包含在生成的 OpenAPI 中,并被文档用户界面和外部工具使用。
+
+/// note | 注意
+
+请记住,不同的工具对 OpenAPI 的支持程度可能不同。
-!!! note
- 请记住,不同的工具对 OpenAPI 的支持程度可能不同。
+其中一些可能还不会展示所有已声明的额外信息,尽管在大多数情况下,缺失的功能已经在计划开发中。
- 其中一些可能不会展示所有已声明的额外信息,尽管在大多数情况下,缺少的这部分功能已经计划进行开发。
+///
你可以添加 `title`:
-```Python hl_lines="10"
-{!../../../docs_src/query_params_str_validations/tutorial007.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *}
以及 `description`:
-```Python hl_lines="13"
-{!../../../docs_src/query_params_str_validations/tutorial008.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *}
-## 别名参数
+## 别名参数 { #alias-parameters }
-假设你想要查询参数为 `item-query`。
+假设你想要参数名为 `item-query`。
-像下面这样:
+像这样:
```
http://127.0.0.1:8000/items/?item-query=foobaritems
```
-但是 `item-query` 不是一个有效的 Python 变量名称。
+但 `item-query` 不是有效的 Python 变量名。
最接近的有效名称是 `item_query`。
-但是你仍然要求它在 URL 中必须是 `item-query`...
+但你仍然需要它在 URL 中就是 `item-query`...
-这时你可以用 `alias` 参数声明一个别名,该别名将用于在 URL 中查找查询参数值:
+这时可以用 `alias` 参数声明一个别名,FastAPI 会用该别名在 URL 中查找参数值:
-```Python hl_lines="9"
-{!../../../docs_src/query_params_str_validations/tutorial009.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *}
-## 弃用参数
+## 弃用参数 { #deprecating-parameters }
-现在假设你不再喜欢此参数。
+现在假设你不再喜欢这个参数了。
-你不得不将其保留一段时间,因为有些客户端正在使用它,但你希望文档清楚地将其展示为已弃用。
+由于还有客户端在使用它,你不得不保留一段时间,但你希望文档清楚地将其展示为已弃用。
-那么将参数 `deprecated=True` 传入 `Query`:
+那么将参数 `deprecated=True` 传给 `Query`:
-```Python hl_lines="18"
-{!../../../docs_src/query_params_str_validations/tutorial010.py!}
-```
+{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *}
文档将会像下面这样展示它:
-
+
+
+## 从 OpenAPI 中排除参数 { #exclude-parameters-from-openapi }
+
+要把某个查询参数从生成的 OpenAPI 模式中排除(从而也不会出现在自动文档系统中),将 `Query` 的参数 `include_in_schema` 设为 `False`:
+
+{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *}
+
+## 自定义校验 { #custom-validation }
+
+有些情况下你需要做一些无法通过上述参数完成的**自定义校验**。
+
+在这些情况下,你可以使用**自定义校验函数**,该函数会在正常校验之后应用(例如,在先校验值是 `str` 之后)。
+
+你可以在 `Annotated` 中使用 [Pydantic 的 `AfterValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-after-validator) 来实现。
+
+/// tip | 提示
+
+Pydantic 还有 [`BeforeValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-before-validator) 等。🤓
-## 总结
+///
-你可以为查询参数声明额外的校验和元数据。
+例如,这个自定义校验器会检查条目 ID 是否以 `isbn-`(用于 ISBN 书号)或 `imdb-`(用于 IMDB 电影 URL 的 ID)开头:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}
+
+/// info | 信息
+
+这在 Pydantic 2 或更高版本中可用。😎
+
+///
+
+/// tip | 提示
+
+如果你需要进行任何需要与**外部组件**通信的校验,例如数据库或其他 API,你应该改用 **FastAPI 依赖项**,稍后你会学到它们。
+
+这些自定义校验器用于只需检查请求中**同一份数据**即可完成的事情。
+
+///
+
+### 理解这段代码 { #understand-that-code }
+
+关键点仅仅是:在 `Annotated` 中使用带函数的 **`AfterValidator`**。不感兴趣可以跳过这一节。🤸
+
+---
+
+但如果你对这个具体示例好奇,并且还愿意继续看,这里有一些额外细节。
+
+#### 字符串与 `value.startswith()` { #string-with-value-startswith }
+
+注意到了吗?字符串的 `value.startswith()` 可以接收一个元组,它会检查元组中的每个值:
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *}
+
+#### 一个随机条目 { #a-random-item }
+
+使用 `data.items()` 我们会得到一个包含每个字典项键和值的元组的 可迭代对象。
+
+我们用 `list(data.items())` 把这个可迭代对象转换成一个真正的 `list`。
+
+然后用 `random.choice()` 可以从该列表中获取一个**随机值**,也就是一个 `(id, name)` 的元组。它可能像 `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")` 这样。
+
+接着我们把这个元组的**两个值**分别赋给变量 `id` 和 `name`。
+
+所以,即使用户没有提供条目 ID,他们仍然会收到一个随机推荐。
+
+...而我们把这些都放在**一行简单的代码**里完成。🤯 你不爱 Python 吗?🐍
+
+{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *}
+
+## 总结 { #recap }
+
+你可以为参数声明额外的校验和元数据。
通用的校验和元数据:
-* `alias`
-* `title`
-* `description`
-* `deprecated`
+- `alias`
+- `title`
+- `description`
+- `deprecated`
+
+字符串特有的校验:
-特定于字符串的校验:
+- `min_length`
+- `max_length`
+- `pattern`
-* `min_length`
-* `max_length`
-* `regex`
+也可以使用 `AfterValidator` 进行自定义校验。
-在这些示例中,你了解了如何声明对 `str` 值的校验。
+在这些示例中,你看到了如何为 `str` 值声明校验。
-请参阅下一章节,以了解如何声明对其他类型例如数值的校验。
+参阅下一章节,了解如何为其他类型(例如数值)声明校验。
diff --git a/docs/zh/docs/tutorial/query-params.md b/docs/zh/docs/tutorial/query-params.md
index b1668a2d2523f..9d6c05fbb76ec 100644
--- a/docs/zh/docs/tutorial/query-params.md
+++ b/docs/zh/docs/tutorial/query-params.md
@@ -1,14 +1,12 @@
-# 查询参数
+# 查询参数 { #query-parameters }
-声明不属于路径参数的其他函数参数时,它们将被自动解释为"查询字符串"参数
+声明的参数不是路径参数时,路径操作函数会把该参数自动解释为“查询”参数。
-```Python hl_lines="9"
-{!../../../docs_src/query_params/tutorial001.py!}
-```
+{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *}
-查询字符串是键值对的集合,这些键值对位于 URL 的 `?` 之后,并以 `&` 符号分隔。
+查询字符串是键值对的集合,这些键值对位于 URL 的 `?` 之后,以 `&` 分隔。
-例如,在以下 url 中:
+例如,以下 URL 中:
```
http://127.0.0.1:8000/items/?skip=0&limit=10
@@ -16,71 +14,70 @@ http://127.0.0.1:8000/items/?skip=0&limit=10
...查询参数为:
-* `skip`:对应的值为 `0`
-* `limit`:对应的值为 `10`
+* `skip`:值为 `0`
+* `limit`:值为 `10`
-由于它们是 URL 的一部分,因此它们的"原始值"是字符串。
+这些值都是 URL 的组成部分,因此,它们的类型“本应”是字符串。
-但是,当你为它们声明了 Python 类型(在上面的示例中为 `int`)时,它们将转换为该类型并针对该类型进行校验。
+但声明 Python 类型(上例中为 `int`)之后,这些值就会转换为声明的类型,并进行类型校验。
-应用于路径参数的所有相同过程也适用于查询参数:
+所有应用于路径参数的流程也适用于查询参数:
-* (很明显的)编辑器支持
-* 数据"解析"
+* (显而易见的)编辑器支持
+* 数据"解析"
* 数据校验
-* 自动生成文档
+* 自动文档
-## 默认值
+## 默认值 { #defaults }
-由于查询参数不是路径的固定部分,因此它们可以是可选的,并且可以有默认值。
+查询参数不是路径的固定内容,它是可选的,还支持默认值。
-在上面的示例中,它们具有 `skip=0` 和 `limit=10` 的默认值。
+上例用 `skip=0` 和 `limit=10` 设定默认值。
-因此,访问 URL:
+访问 URL:
```
http://127.0.0.1:8000/items/
```
-将与访问以下地址相同:
+与访问以下地址相同:
```
http://127.0.0.1:8000/items/?skip=0&limit=10
```
-但是,如果你访问的是:
+但如果访问:
```
http://127.0.0.1:8000/items/?skip=20
```
-函数中的参数值将会是:
+查询参数的值就是:
* `skip=20`:在 URL 中设定的值
* `limit=10`:使用默认值
-## 可选参数
+## 可选参数 { #optional-parameters }
-通过同样的方式,你可以将它们的默认值设置为 `None` 来声明可选查询参数:
+同理,把默认值设为 `None` 即可声明可选的查询参数:
-```Python hl_lines="7"
-{!../../../docs_src/query_params/tutorial002.py!}
-```
+{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *}
-在这个例子中,函数参数 `q` 将是可选的,并且默认值为 `None`。
+本例中,查询参数 `q` 是可选的,默认值为 `None`。
-!!! check
- 还要注意的是,**FastAPI** 足够聪明,能够分辨出参数 `item_id` 是路径参数而 `q` 不是,因此 `q` 是一个查询参数。
+/// check | 检查
-## 查询参数类型转换
+注意,**FastAPI** 可以识别出 `item_id` 是路径参数,`q` 不是路径参数,而是查询参数。
-你还可以声明 `bool` 类型,它们将被自动转换:
+///
-```Python hl_lines="7"
-{!../../../docs_src/query_params/tutorial003.py!}
-```
+## 查询参数类型转换 { #query-parameter-type-conversion }
+
+参数还可以声明为 `bool` 类型,FastAPI 会自动转换参数类型:
+
+{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *}
-这个例子中,如果你访问:
+本例中,访问:
```
http://127.0.0.1:8000/items/foo?short=1
@@ -110,59 +107,56 @@ http://127.0.0.1:8000/items/foo?short=on
http://127.0.0.1:8000/items/foo?short=yes
```
-或任何其他的变体形式(大写,首字母大写等等),你的函数接收的 `short` 参数都会是布尔值 `True`。对于值为 `False` 的情况也是一样的。
+或其它任意大小写形式(大写、首字母大写等),函数接收的 `short` 参数都是布尔值 `True`。否则为 `False`。
-## 多个路径和查询参数
+## 多个路径和查询参数 { #multiple-path-and-query-parameters }
-你可以同时声明多个路径参数和查询参数,**FastAPI** 能够识别它们。
+**FastAPI** 可以识别同时声明的多个路径参数和查询参数。
-而且你不需要以任何特定的顺序来声明。
+而且声明查询参数的顺序并不重要。
-它们将通过名称被检测到:
+FastAPI 通过参数名进行检测:
-```Python hl_lines="6 8"
-{!../../../docs_src/query_params/tutorial004.py!}
-```
+{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *}
-## 必需查询参数
+## 必选查询参数 { #required-query-parameters }
-当你为非路径参数声明了默认值时(目前而言,我们所知道的仅有查询参数),则该参数不是必需的。
+为不是路径参数的参数声明默认值(至此,仅有查询参数),该参数就不是必选的了。
-如果你不想添加一个特定的值,而只是想使该参数成为可选的,则将默认值设置为 `None`。
+如果只想把参数设为可选,但又不想指定参数的值,则要把默认值设为 `None`。
-但当你想让一个查询参数成为必需的,不声明任何默认值就可以:
+如果要把查询参数设置为必选,就不要声明默认值:
-```Python hl_lines="6-7"
-{!../../../docs_src/query_params/tutorial005.py!}
-```
+{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *}
-这里的查询参数 `needy` 是类型为 `str` 的必需查询参数。
+这里的查询参数 `needy` 是类型为 `str` 的必选查询参数。
-如果你在浏览器中打开一个像下面的 URL:
+在浏览器中打开如下 URL:
```
http://127.0.0.1:8000/items/foo-item
```
-...因为没有添加必需的参数 `needy`,你将看到类似以下的错误:
+...因为路径中没有必选参数 `needy`,返回的响应中会显示如下错误信息:
```JSON
{
- "detail": [
- {
- "loc": [
- "query",
- "needy"
- ],
- "msg": "field required",
- "type": "value_error.missing"
- }
- ]
+ "detail": [
+ {
+ "type": "missing",
+ "loc": [
+ "query",
+ "needy"
+ ],
+ "msg": "Field required",
+ "input": null
+ }
+ ]
}
```
-由于 `needy` 是必需参数,因此你需要在 URL 中设置它的值:
+`needy` 是必选参数,因此要在 URL 中设置值:
```
http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
@@ -177,17 +171,18 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
}
```
-当然,你也可以定义一些参数为必需的,一些具有默认值,而某些则完全是可选的:
+当然,把一些参数定义为必选,为另一些参数设置默认值,再把其它参数定义为可选,这些操作都是可以的:
-```Python hl_lines="7"
-{!../../../docs_src/query_params/tutorial006.py!}
-```
+{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *}
+
+本例中有 3 个查询参数:
+
+* `needy`,必选的 `str` 类型参数
+* `skip`,默认值为 `0` 的 `int` 类型参数
+* `limit`,可选的 `int` 类型参数
-在这个例子中,有3个查询参数:
+/// tip | 提示
-* `needy`,一个必需的 `str` 类型参数。
-* `skip`,一个默认值为 `0` 的 `int` 类型参数。
-* `limit`,一个可选的 `int` 类型参数。
+还可以像在[路径参数](path-params.md#predefined-values)中那样使用 `Enum`。
-!!! tip
- 你还可以像在 [路径参数](path-params.md#predefined-values){.internal-link target=_blank} 中那样使用 `Enum`。
+///
diff --git a/docs/zh/docs/tutorial/request-files.md b/docs/zh/docs/tutorial/request-files.md
index 03474907ee94b..6569e1715ab0c 100644
--- a/docs/zh/docs/tutorial/request-files.md
+++ b/docs/zh/docs/tutorial/request-files.md
@@ -1,194 +1,176 @@
-# 请求文件
+# 请求文件 { #request-files }
-`File` 用于定义客户端的上传文件。
+你可以使用 `File` 定义由客户端上传的文件。
-!!! info "说明"
+/// info | 信息
- 因为上传文件以「表单数据」形式发送。
+要接收上传的文件,请先安装 [`python-multipart`](https://github.com/Kludex/python-multipart)。
- 所以接收上传文件,要预先安装 `python-multipart`。
+请确保你创建一个[虚拟环境](../virtual-environments.md)、激活它,然后安装,例如:
- 例如: `pip install python-multipart`。
+```console
+$ pip install python-multipart
+```
+
+这是因为上传文件是以「表单数据」发送的。
-## 导入 `File`
+///
+
+## 导入 `File` { #import-file }
从 `fastapi` 导入 `File` 和 `UploadFile`:
-```Python hl_lines="1"
-{!../../../docs_src/request_files/tutorial001.py!}
-```
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *}
-## 定义 `File` 参数
+## 定义 `File` 参数 { #define-file-parameters }
-创建文件(`File`)参数的方式与 `Body` 和 `Form` 一样:
+像为 `Body` 或 `Form` 一样创建文件参数:
-```Python hl_lines="7"
-{!../../../docs_src/request_files/tutorial001.py!}
-```
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *}
-!!! info "说明"
+/// info | 信息
- `File` 是直接继承自 `Form` 的类。
+`File` 是直接继承自 `Form` 的类。
- 注意,从 `fastapi` 导入的 `Query`、`Path`、`File` 等项,实际上是返回特定类的函数。
+但要注意,从 `fastapi` 导入的 `Query`、`Path`、`File` 等项,实际上是返回特定类的函数。
-!!! tip "提示"
+///
- 声明文件体必须使用 `File`,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。
+/// tip | 提示
-文件作为「表单数据」上传。
+声明文件体必须使用 `File`,否则,这些参数会被当作查询参数或请求体(JSON)参数。
-如果把*路径操作函数*参数的类型声明为 `bytes`,**FastAPI** 将以 `bytes` 形式读取和接收文件内容。
+///
-这种方式把文件的所有内容都存储在内存里,适用于小型文件。
+文件将作为「表单数据」上传。
-不过,很多情况下,`UploadFile` 更好用。
+如果把*路径操作函数*参数的类型声明为 `bytes`,**FastAPI** 会为你读取文件,并以 `bytes` 的形式接收其内容。
-## 含 `UploadFile` 的文件参数
+请注意,这意味着整个内容会存储在内存中,适用于小型文件。
-定义文件参数时使用 `UploadFile`:
+不过,在很多情况下,使用 `UploadFile` 会更有优势。
-```Python hl_lines="12"
-{!../../../docs_src/request_files/tutorial001.py!}
-```
+## 含 `UploadFile` 的文件参数 { #file-parameters-with-uploadfile }
+
+将文件参数的类型声明为 `UploadFile`:
+
+{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *}
-`UploadFile` 与 `bytes` 相比有更多优势:
+与 `bytes` 相比,使用 `UploadFile` 有多项优势:
-* 使用 `spooled` 文件:
- * 存储在内存的文件超出最大上限时,FastAPI 会把文件存入磁盘;
-* 这种方式更适于处理图像、视频、二进制文件等大型文件,好处是不会占用所有内存;
-* 可获取上传文件的元数据;
-* 自带 file-like `async` 接口;
-* 暴露的 Python `SpooledTemporaryFile` 对象,可直接传递给其他预期「file-like」对象的库。
+* 无需在参数的默认值中使用 `File()`。
+* 它使用“spooled”文件:
+ * 文件会先存储在内存中,直到达到最大上限,超过该上限后会写入磁盘。
+* 因此,非常适合处理图像、视频、大型二进制等大文件,而不会占用所有内存。
+* 你可以获取上传文件的元数据。
+* 它提供 [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) 的 `async` 接口。
+* 它暴露了一个实际的 Python [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) 对象,你可以直接传给期望「file-like」对象的其他库。
-### `UploadFile`
+### `UploadFile` { #uploadfile }
`UploadFile` 的属性如下:
-* `filename`:上传文件名字符串(`str`),例如, `myimage.jpg`;
-* `content_type`:内容类型(MIME 类型 / 媒体类型)字符串(`str`),例如,`image/jpeg`;
-* `file`: `SpooledTemporaryFile`( file-like 对象)。其实就是 Python文件,可直接传递给其他预期 `file-like` 对象的函数或支持库。
+* `filename`:上传的原始文件名字符串(`str`),例如 `myimage.jpg`。
+* `content_type`:内容类型(MIME 类型 / 媒体类型)的字符串(`str`),例如 `image/jpeg`。
+* `file`:[`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile)(一个 [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) 对象)。这是实际的 Python 文件对象,你可以直接传递给其他期望「file-like」对象的函数或库。
-`UploadFile` 支持以下 `async` 方法,(使用内部 `SpooledTemporaryFile`)可调用相应的文件方法。
+`UploadFile` 具有以下 `async` 方法。它们都会在底层调用对应的文件方法(使用内部的 `SpooledTemporaryFile`)。
-* `write(data)`:把 `data` (`str` 或 `bytes`)写入文件;
-* `read(size)`:按指定数量的字节或字符(`size` (`int`))读取文件内容;
-* `seek(offset)`:移动至文件 `offset` (`int`)字节处的位置;
- * 例如,`await myfile.seek(0) ` 移动到文件开头;
- * 执行 `await myfile.read()` 后,需再次读取已读取内容时,这种方法特别好用;
+* `write(data)`:将 `data` (`str` 或 `bytes`) 写入文件。
+* `read(size)`:读取文件中 `size` (`int`) 个字节/字符。
+* `seek(offset)`:移动到文件中字节位置 `offset` (`int`)。
+ * 例如,`await myfile.seek(0)` 会移动到文件开头。
+ * 如果你先运行过 `await myfile.read()`,然后需要再次读取内容时,这尤其有用。
* `close()`:关闭文件。
-因为上述方法都是 `async` 方法,要搭配「await」使用。
+由于这些方法都是 `async` 方法,你需要对它们使用 await。
-例如,在 `async` *路径操作函数* 内,要用以下方式读取文件内容:
+例如,在 `async` *路径操作函数* 内,你可以这样获取内容:
```Python
contents = await myfile.read()
```
-在普通 `def` *路径操作函数* 内,则可以直接访问 `UploadFile.file`,例如:
+如果是在普通 `def` *路径操作函数* 内,你可以直接访问 `UploadFile.file`,例如:
```Python
contents = myfile.file.read()
```
-!!! note "`async` 技术细节"
+/// note | `async` 技术细节
- 使用 `async` 方法时,**FastAPI** 在线程池中执行文件方法,并 `await` 操作完成。
+当你使用这些 `async` 方法时,**FastAPI** 会在线程池中运行相应的文件方法并等待其完成。
-!!! note "Starlette 技术细节"
+///
- **FastAPI** 的 `UploadFile` 直接继承自 **Starlette** 的 `UploadFile`,但添加了一些必要功能,使之与 **Pydantic** 及 FastAPI 的其它部件兼容。
+/// note | Starlette 技术细节
-## 什么是 「表单数据」
+**FastAPI** 的 `UploadFile` 直接继承自 **Starlette** 的 `UploadFile`,但添加了一些必要的部分,使其与 **Pydantic** 以及 FastAPI 的其他部分兼容。
-与 JSON 不同,HTML 表单(``)向服务器发送数据通常使用「特殊」的编码。
+///
-**FastAPI** 要确保从正确的位置读取数据,而不是读取 JSON。
+## 什么是「表单数据」 { #what-is-form-data }
-!!! note "技术细节"
+HTML 表单(``)向服务器发送数据的方式通常会对数据使用一种「特殊」的编码,这与 JSON 不同。
- 不包含文件时,表单数据一般用 `application/x-www-form-urlencoded`「媒体类型」编码。
+**FastAPI** 会确保从正确的位置读取这些数据,而不是从 JSON 中读取。
- 但表单包含文件时,编码为 `multipart/form-data`。使用了 `File`,**FastAPI** 就知道要从请求体的正确位置获取文件。
+/// note | 技术细节
- 编码和表单字段详见 MDN Web 文档的 POST 小节。
+当不包含文件时,来自表单的数据通常使用「媒体类型」`application/x-www-form-urlencoded` 编码。
-!!! warning "警告"
+但当表单包含文件时,会编码为 `multipart/form-data`。如果你使用 `File`,**FastAPI** 会知道需要从请求体的正确位置获取文件。
- 可在一个*路径操作*中声明多个 `File` 和 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `multipart/form-data`,不是 `application/json`。
+如果你想进一步了解这些编码和表单字段,请参阅 [MDN 关于 `POST` 的 Web 文档](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)。
- 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
+///
-## 可选文件上传
+/// warning | 警告
-您可以通过使用标准类型注解并将 None 作为默认值的方式将一个文件参数设为可选:
+你可以在一个*路径操作*中声明多个 `File` 和 `Form` 参数,但不能同时声明希望以 JSON 接收的 `Body` 字段,因为此时请求体会使用 `multipart/form-data` 编码,而不是 `application/json`。
-=== "Python 3.9+"
+这不是 **FastAPI** 的限制,而是 HTTP 协议的一部分。
- ```Python hl_lines="7 14"
- {!> ../../../docs_src/request_files/tutorial001_02_py310.py!}
- ```
+///
-=== "Python 3.6+"
+## 可选文件上传 { #optional-file-upload }
- ```Python hl_lines="9 17"
- {!> ../../../docs_src/request_files/tutorial001_02.py!}
- ```
+你可以通过使用标准类型注解并将 `None` 作为默认值的方式将一个文件参数设为可选:
-## 带有额外元数据的 `UploadFile`
+{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *}
-您也可以将 `File()` 与 `UploadFile` 一起使用,例如,设置额外的元数据:
+## 带有额外元数据的 `UploadFile` { #uploadfile-with-additional-metadata }
-```Python hl_lines="13"
-{!../../../docs_src/request_files/tutorial001_03.py!}
-```
-
-## 多文件上传
-
-FastAPI 支持同时上传多个文件。
+你也可以将 `File()` 与 `UploadFile` 一起使用,例如,设置额外的元数据:
-可用同一个「表单字段」发送含多个文件的「表单数据」。
+{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *}
-上传多个文件时,要声明含 `bytes` 或 `UploadFile` 的列表(`List`):
+## 多文件上传 { #multiple-file-uploads }
-=== "Python 3.9+"
+FastAPI 支持同时上传多个文件。
- ```Python hl_lines="8 13"
- {!> ../../../docs_src/request_files/tutorial002_py39.py!}
- ```
+它们会被关联到同一个通过「表单数据」发送的「表单字段」。
-=== "Python 3.6+"
+要实现这一点,声明一个由 `bytes` 或 `UploadFile` 组成的列表(`List`):
- ```Python hl_lines="10 15"
- {!> ../../../docs_src/request_files/tutorial002.py!}
- ```
+{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *}
接收的也是含 `bytes` 或 `UploadFile` 的列表(`list`)。
+/// note | 技术细节
-!!! note "技术细节"
-
- 也可以使用 `from starlette.responses import HTMLResponse`。
-
- `fastapi.responses` 其实与 `starlette.responses` 相同,只是为了方便开发者调用。实际上,大多数 **FastAPI** 的响应都直接从 Starlette 调用。
-
-### 带有额外元数据的多文件上传
+也可以使用 `from starlette.responses import HTMLResponse`。
-和之前的方式一样, 您可以为 `File()` 设置额外参数, 即使是 `UploadFile`:
+`fastapi.responses` 其实与 `starlette.responses` 相同,只是为了方便开发者调用。实际上,大多数 **FastAPI** 的响应都直接从 Starlette 调用。
-=== "Python 3.9+"
+///
- ```Python hl_lines="16"
- {!> ../../../docs_src/request_files/tutorial003_py39.py!}
- ```
+### 带有额外元数据的多文件上传 { #multiple-file-uploads-with-additional-metadata }
-=== "Python 3.6+"
+和之前的方式一样,你可以为 `File()` 设置额外参数,即使是 `UploadFile`:
- ```Python hl_lines="18"
- {!> ../../../docs_src/request_files/tutorial003.py!}
- ```
+{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *}
-## 小结
+## 小结 { #recap }
-本节介绍了如何用 `File` 把上传文件声明为(表单数据的)输入参数。
+使用 `File`、`bytes` 和 `UploadFile` 来声明在请求中上传的文件,它们以表单数据发送。
diff --git a/docs/zh/docs/tutorial/request-form-models.md b/docs/zh/docs/tutorial/request-form-models.md
new file mode 100644
index 0000000000000..ec52710a8f83a
--- /dev/null
+++ b/docs/zh/docs/tutorial/request-form-models.md
@@ -0,0 +1,78 @@
+# 表单模型 { #form-models }
+
+你可以在 FastAPI 中使用 **Pydantic 模型**声明**表单字段**。
+
+/// info | 信息
+
+要使用表单,首先安装 [`python-multipart`](https://github.com/Kludex/python-multipart)。
+
+确保你创建一个[虚拟环境](../virtual-environments.md),激活它,然后再安装,例如:
+
+```console
+$ pip install python-multipart
+```
+
+///
+
+/// note | 注意
+
+自 FastAPI 版本 `0.113.0` 起支持此功能。🤓
+
+///
+
+## 表单的 Pydantic 模型 { #pydantic-models-for-forms }
+
+你只需声明一个 **Pydantic 模型**,其中包含你希望接收的**表单字段**,然后将参数声明为 `Form`:
+
+{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *}
+
+**FastAPI** 将从请求中的**表单数据**中**提取**出**每个字段**的数据,并提供你定义的 Pydantic 模型。
+
+## 检查文档 { #check-the-docs }
+
+你可以在文档 UI 中验证它,地址为 `/docs`:
+
+
+POST小节。
+/// warning
-!!! warning "警告"
+你可以在一个路径操作中声明多个 `Form` 参数,但不能同时再声明要接收为 JSON 的 `Body` 字段,因为此时请求体会使用 `application/x-www-form-urlencoded` 而不是 `application/json` 进行编码。
- 可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。
+这不是 **FastAPI** 的限制,而是 HTTP 协议的一部分。
- 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。
+///
-## 小结
+## 小结 { #recap }
-本节介绍了如何使用 `Form` 声明表单数据输入参数。
+使用 `Form` 来声明表单数据输入参数。
diff --git a/docs/zh/docs/tutorial/response-model.md b/docs/zh/docs/tutorial/response-model.md
index f529cb0d8b195..9b4e0382e989a 100644
--- a/docs/zh/docs/tutorial/response-model.md
+++ b/docs/zh/docs/tutorial/response-model.md
@@ -1,6 +1,36 @@
-# 响应模型
+# 响应模型 - 返回类型 { #response-model-return-type }
-你可以在任意的*路径操作*中使用 `response_model` 参数来声明用于响应的模型:
+你可以通过为*路径操作函数*的**返回类型**添加注解来声明用于响应的类型。
+
+和为输入数据在函数**参数**里做类型注解的方式相同,你可以使用 Pydantic 模型、`list`、`dict`、以及整数、布尔值等标量类型。
+
+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}
+
+FastAPI 会使用这个返回类型来:
+
+* 对返回数据进行**校验**。
+ * 如果数据无效(例如缺少某个字段),这意味着你的应用代码有问题,没有返回应有的数据,FastAPI 将返回服务器错误而不是返回错误的数据。这样你和你的客户端都可以确定会收到期望的数据及其结构。
+* 在 OpenAPI 的*路径操作*中为响应添加**JSON Schema**。
+ * 它会被**自动文档**使用。
+ * 它也会被自动客户端代码生成工具使用。
+* 使用 Pydantic 将返回数据**序列化**为 JSON。Pydantic 使用**Rust**编写,因此会**快很多**。
+
+但更重要的是:
+
+* 它会将输出数据**限制并过滤**为返回类型中定义的内容。
+ * 这对**安全性**尤为重要,下面会进一步介绍。
+
+## `response_model` 参数 { #response-model-parameter }
+
+在一些情况下,你需要或希望返回的数据与声明的类型不完全一致。
+
+例如,你可能希望**返回一个字典**或数据库对象,但**将其声明为一个 Pydantic 模型**。这样 Pydantic 模型就会为你返回的对象(例如字典或数据库对象)完成文档、校验等工作。
+
+如果你添加了返回类型注解,工具和编辑器会(正确地)报错,提示你的函数返回的类型(例如 `dict`)与声明的类型(例如一个 Pydantic 模型)不同。
+
+在这些情况下,你可以使用*路径操作装饰器*参数 `response_model`,而不是返回类型。
+
+你可以在任意*路径操作*中使用 `response_model` 参数:
* `@app.get()`
* `@app.post()`
@@ -8,149 +38,211 @@
* `@app.delete()`
* 等等。
-=== "Python 3.10+"
+{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *}
+
+/// note | 注意
+
+注意,`response_model` 是「装饰器」方法(`get`、`post` 等)的一个参数。不是你的*路径操作函数*的参数,不像所有查询参数和请求体那样。
+
+///
+
+`response_model` 接收的类型与为 Pydantic 模型字段声明的类型相同,因此它可以是一个 Pydantic 模型,也可以是一个由 Pydantic 模型组成的 `list`,例如 `List[Item]`。
+
+FastAPI 会使用这个 `response_model` 来完成数据文档、校验等,并且还会将输出数据**转换并过滤**为其类型声明。
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py310.py!}
- ```
+/// tip | 提示
-=== "Python 3.9+"
+如果你的编辑器、mypy 等进行严格类型检查,你可以将函数返回类型声明为 `Any`。
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001_py39.py!}
- ```
+这样你告诉编辑器你是有意返回任意类型。但 FastAPI 仍会使用 `response_model` 做数据文档、校验、过滤等工作。
-=== "Python 3.6+"
+///
- ```Python hl_lines="17 22 24-27"
- {!> ../../../docs_src/response_model/tutorial001.py!}
- ```
+### `response_model` 的优先级 { #response-model-priority }
-!!! note
- 注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。
+如果你同时声明了返回类型和 `response_model`,`response_model` 会具有优先级并由 FastAPI 使用。
-它接收的类型与你将为 Pydantic 模型属性所声明的类型相同,因此它可以是一个 Pydantic 模型,但也可以是一个由 Pydantic 模型组成的 `list`,例如 `List[Item]`。
+这样,即使你返回的类型与响应模型不同,你也可以为函数添加正确的类型注解,供编辑器和 mypy 等工具使用。同时你仍然可以让 FastAPI 使用 `response_model` 进行数据校验、文档等。
-FastAPI 将使用此 `response_model` 来:
+你也可以使用 `response_model=None` 来禁用该*路径操作*的响应模型生成;当你为一些不是有效 Pydantic 字段的东西添加类型注解时,可能需要这样做,下面的章节会有示例。
-* 将输出数据转换为其声明的类型。
-* 校验数据。
-* 在 OpenAPI 的*路径操作*中为响应添加一个 JSON Schema。
-* 并在自动生成文档系统中使用。
+## 返回与输入相同的数据 { #return-the-same-input-data }
-但最重要的是:
+这里我们声明一个 `UserIn` 模型,它包含一个明文密码:
-* 会将输出数据限制在该模型定义内。下面我们会看到这一点有多重要。
+{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *}
-!!! note "技术细节"
- 响应模型在参数中被声明,而不是作为函数返回类型的注解,这是因为路径函数可能不会真正返回该响应模型,而是返回一个 `dict`、数据库对象或其他模型,然后再使用 `response_model` 来执行字段约束和序列化。
+/// info | 信息
-## 返回与输入相同的数据
+要使用 `EmailStr`,首先安装 [`email-validator`](https://github.com/JoshData/python-email-validator)。
-现在我们声明一个 `UserIn` 模型,它将包含一个明文密码属性。
+请先创建并激活一个[虚拟环境](../virtual-environments.md),然后安装,例如:
-```Python hl_lines="9 11"
-{!../../../docs_src/response_model/tutorial002.py!}
+```console
+$ pip install email-validator
```
-我们正在使用此模型声明输入数据,并使用同一模型声明输出数据:
+或者:
-```Python hl_lines="17-18"
-{!../../../docs_src/response_model/tutorial002.py!}
+```console
+$ pip install "pydantic[email]"
```
-现在,每当浏览器使用一个密码创建用户时,API 都会在响应中返回相同的密码。
+///
+
+我们使用这个模型来声明输入,同时也用相同的模型来声明输出:
+
+{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *}
+
+现在,每当浏览器使用密码创建用户时,API 会在响应中返回相同的密码。
+
+在这个场景下,这可能不算问题,因为发送密码的是同一个用户。
+
+但如果我们在其他*路径操作*中使用相同的模型,就可能会把用户的密码发送给每个客户端。
+
+/// danger | 危险
+
+除非你非常清楚所有注意事项并确实知道自己在做什么,否则永远不要存储用户的明文密码,也不要像这样在响应中发送它。
+
+///
+
+## 添加输出模型 { #add-an-output-model }
+
+相反,我们可以创建一个包含明文密码的输入模型和一个不包含它的输出模型:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *}
+
+这里,即使我们的*路径操作函数*返回的是包含密码的同一个输入用户:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *}
+
+……我们仍将 `response_model` 声明为不包含密码的 `UserOut` 模型:
+
+{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *}
+
+因此,**FastAPI** 会负责过滤掉输出模型中未声明的所有数据(使用 Pydantic)。
+
+### `response_model` 还是返回类型 { #response-model-or-return-type }
-在这个案例中,这可能不算是问题,因为用户自己正在发送密码。
+在这个例子中,因为两个模型不同,如果我们将函数返回类型注解为 `UserOut`,编辑器和工具会抱怨我们返回了无效类型,因为它们是不同的类。
-但是,如果我们在其他的*路径操作*中使用相同的模型,则可能会将用户的密码发送给每个客户端。
+这就是为什么在这个例子里我们必须在 `response_model` 参数中声明它。
-!!! danger
- 永远不要存储用户的明文密码,也不要在响应中发送密码。
+……但继续往下读,看看如何更好地处理这种情况。
-## 添加输出模型
+## 返回类型与数据过滤 { #return-type-and-data-filtering }
-相反,我们可以创建一个有明文密码的输入模型和一个没有明文密码的输出模型:
+延续上一个例子。我们希望**用一种类型来注解函数**,但希望从函数返回的内容实际上可以**包含更多数据**。
-=== "Python 3.10+"
+我们希望 FastAPI 继续使用响应模型来**过滤**数据。这样即使函数返回了更多数据,响应也只会包含响应模型中声明的字段。
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+在上一个例子中,因为类不同,我们不得不使用 `response_model` 参数。但这也意味着我们无法从编辑器和工具处获得对函数返回类型的检查支持。
-=== "Python 3.6+"
+不过在大多数需要这样做的场景里,我们只是希望模型像这个例子中那样**过滤/移除**一部分数据。
- ```Python hl_lines="9 11 16"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+在这些场景里,我们可以使用类和继承,既利用函数的**类型注解**获取更好的编辑器和工具支持,又能获得 FastAPI 的**数据过滤**。
-这样,即便我们的*路径操作函数*将会返回包含密码的相同输入用户:
+{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *}
-=== "Python 3.10+"
+这样一来,我们既能从编辑器和 mypy 获得工具支持(这段代码在类型上是正确的),也能从 FastAPI 获得数据过滤。
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+这是如何做到的?我们来看看。🤓
-=== "Python 3.6+"
+### 类型注解与工具链 { #type-annotations-and-tooling }
- ```Python hl_lines="24"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+先看看编辑器、mypy 和其他工具会如何看待它。
-...我们已经将 `response_model` 声明为了不包含密码的 `UserOut` 模型:
+`BaseUser` 有基础字段。然后 `UserIn` 继承自 `BaseUser` 并新增了 `password` 字段,因此它包含了两个模型的全部字段。
-=== "Python 3.10+"
+我们把函数返回类型注解为 `BaseUser`,但实际上返回的是一个 `UserIn` 实例。
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003_py310.py!}
- ```
+编辑器、mypy 和其他工具不会对此抱怨,因为在类型系统里,`UserIn` 是 `BaseUser` 的子类,这意味着当期望 `BaseUser` 时,返回 `UserIn` 是*合法*的。
-=== "Python 3.6+"
+### FastAPI 的数据过滤 { #fastapi-data-filtering }
- ```Python hl_lines="22"
- {!> ../../../docs_src/response_model/tutorial003.py!}
- ```
+对于 FastAPI,它会查看返回类型并确保你返回的内容**只**包含该类型中声明的字段。
-因此,**FastAPI** 将会负责过滤掉未在输出模型中声明的所有数据(使用 Pydantic)。
+FastAPI 在内部配合 Pydantic 做了多项处理,确保不会把类继承的这些规则用于返回数据的过滤,否则你可能会返回比预期多得多的数据。
-## 在文档中查看
+这样,你就能兼得两方面的优势:带有**工具支持**的类型注解和**数据过滤**。
-当你查看自动化文档时,你可以检查输入模型和输出模型是否都具有自己的 JSON Schema:
+## 在文档中查看 { #see-it-in-the-docs }
-
+当你查看自动文档时,你会看到输入模型和输出模型都会有各自的 JSON Schema:
-并且两种模型都将在交互式 API 文档中使用:
+
-
+并且两个模型都会用于交互式 API 文档:
-## 响应模型编码参数
+
+
+## 其他返回类型注解 { #other-return-type-annotations }
+
+有些情况下你会返回一些不是有效 Pydantic 字段的内容,并在函数上做了相应注解,只是为了获得工具链(编辑器、mypy 等)的支持。
+
+### 直接返回 Response { #return-a-response-directly }
+
+最常见的情况是[直接返回 Response,详见进阶文档](../advanced/response-directly.md)。
+
+{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *}
+
+这个简单场景 FastAPI 会自动处理,因为返回类型注解是 `Response`(或其子类)。
+
+工具也会满意,因为 `RedirectResponse` 和 `JSONResponse` 都是 `Response` 的子类,所以类型注解是正确的。
+
+### 注解 Response 的子类 { #annotate-a-response-subclass }
+
+你也可以在类型注解中使用 `Response` 的子类:
+
+{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *}
+
+这同样可行,因为 `RedirectResponse` 是 `Response` 的子类,FastAPI 会自动处理这个简单场景。
+
+### 无效的返回类型注解 { #invalid-return-type-annotations }
+
+但当你返回其他任意对象(如数据库对象)而它不是有效的 Pydantic 类型,并在函数中按此进行了注解时,FastAPI 会尝试基于该类型注解创建一个 Pydantic 响应模型,但会失败。
+
+如果你有一个在多个类型之间的联合类型,其中一个或多个不是有效的 Pydantic 类型,也会发生同样的情况,例如这个会失败 💥:
+
+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}
+
+……它失败是因为该类型注解不是 Pydantic 类型,也不只是单个 `Response` 类或其子类,而是 `Response` 与 `dict` 的联合类型(任意其一)。
+
+### 禁用响应模型 { #disable-response-model }
+
+延续上面的例子,你可能不想要 FastAPI 执行默认的数据校验、文档、过滤等。
+
+但你可能仍然想在函数上保留返回类型注解,以获得编辑器和类型检查器(如 mypy)的支持。
+
+在这种情况下,你可以通过设置 `response_model=None` 来禁用响应模型生成:
+
+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}
+
+这会让 FastAPI 跳过响应模型的生成,这样你就可以按需使用任意返回类型注解,而不会影响你的 FastAPI 应用。🤓
+
+## 响应模型的编码参数 { #response-model-encoding-parameters }
你的响应模型可以具有默认值,例如:
-```Python hl_lines="11 13-14"
-{!../../../docs_src/response_model/tutorial004.py!}
-```
+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}
-* `description: Union[str, None] = None` 具有默认值 `None`。
-* `tax: float = 10.5` 具有默认值 `10.5`.
-* `tags: List[str] = []` 具有一个空列表作为默认值: `[]`.
+* `description: Union[str, None] = None`(或在 Python 3.10 中的 `str | None = None`)默认值为 `None`。
+* `tax: float = 10.5` 默认值为 `10.5`。
+* `tags: List[str] = []` 默认值为一个空列表:`[]`。
-但如果它们并没有存储实际的值,你可能想从结果中忽略它们的默认值。
+但如果它们并没有被实际存储,你可能希望在结果中省略这些默认值。
-举个例子,当你在 NoSQL 数据库中保存了具有许多可选属性的模型,但你又不想发送充满默认值的很长的 JSON 响应。
+例如,当你在 NoSQL 数据库中保存了具有许多可选属性的模型,但又不想发送充满默认值的冗长 JSON 响应。
-### 使用 `response_model_exclude_unset` 参数
+### 使用 `response_model_exclude_unset` 参数 { #use-the-response-model-exclude-unset-parameter }
-你可以设置*路径操作装饰器*的 `response_model_exclude_unset=True` 参数:
+你可以设置*路径操作装饰器*参数 `response_model_exclude_unset=True`:
-```Python hl_lines="24"
-{!../../../docs_src/response_model/tutorial004.py!}
-```
+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}
-然后响应中将不会包含那些默认值,而是仅有实际设置的值。
+这样响应中将不会包含那些默认值,而只包含实际设置的值。
-因此,如果你向*路径操作*发送 ID 为 `foo` 的商品的请求,则响应(不包括默认值)将为:
+因此,如果你向该*路径操作*请求 ID 为 `foo` 的商品,响应(不包括默认值)将为:
```JSON
{
@@ -159,18 +251,18 @@ FastAPI 将使用此 `response_model` 来:
}
```
-!!! info
- FastAPI 通过 Pydantic 模型的 `.dict()` 配合 该方法的 `exclude_unset` 参数 来实现此功能。
+/// info | 信息
+
+你还可以使用:
-!!! info
- 你还可以使用:
+* `response_model_exclude_defaults=True`
+* `response_model_exclude_none=True`
- * `response_model_exclude_defaults=True`
- * `response_model_exclude_none=True`
+详见 [Pydantic 文档](https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict)中对 `exclude_defaults` 和 `exclude_none` 的说明。
- 参考 Pydantic 文档 中对 `exclude_defaults` 和 `exclude_none` 的描述。
+///
-#### 默认值字段有实际值的数据
+#### 默认字段有实际值的数据 { #data-with-values-for-fields-with-defaults }
但是,如果你的数据在具有默认值的模型字段中有实际的值,例如 ID 为 `bar` 的项:
@@ -185,7 +277,7 @@ FastAPI 将使用此 `response_model` 来:
这些值将包含在响应中。
-#### 具有与默认值相同值的数据
+#### 具有与默认值相同值的数据 { #data-with-the-same-values-as-the-defaults }
如果数据具有与默认值相同的值,例如 ID 为 `baz` 的项:
@@ -199,49 +291,54 @@ FastAPI 将使用此 `response_model` 来:
}
```
-即使 `description`、`tax` 和 `tags` 具有与默认值相同的值,FastAPI 足够聪明 (实际上是 Pydantic 足够聪明) 去认识到这一点,它们的值被显式地所设定(而不是取自默认值)。
+FastAPI 足够聪明(实际上是 Pydantic 足够聪明)去认识到,即使 `description`、`tax` 和 `tags` 的值与默认值相同,它们也是被显式设置的(而不是取自默认值)。
因此,它们将包含在 JSON 响应中。
-!!! tip
- 请注意默认值可以是任何值,而不仅是`None`。
+/// tip | 提示
- 它们可以是一个列表(`[]`),一个值为 `10.5`的 `float`,等等。
+请注意默认值可以是任何值,而不仅是 `None`。
-### `response_model_include` 和 `response_model_exclude`
+它们可以是一个列表(`[]`)、值为 `10.5` 的 `float`,等等。
+
+///
+
+### `response_model_include` 和 `response_model_exclude` { #response-model-include-and-response-model-exclude }
你还可以使用*路径操作装饰器*的 `response_model_include` 和 `response_model_exclude` 参数。
-它们接收一个由属性名称 `str` 组成的 `set` 来包含(忽略其他的)或者排除(包含其他的)这些属性。
+它们接收一个由属性名 `str` 组成的 `set`,用于包含(忽略其他)或排除(包含其他)这些属性。
-如果你只有一个 Pydantic 模型,并且想要从输出中移除一些数据,则可以使用这种快捷方法。
+当你只有一个 Pydantic 模型,并且想要从输出中移除一些数据时,这可以作为一种快捷方式。
-!!! tip
- 但是依然建议你使用上面提到的主意,使用多个类而不是这些参数。
+/// tip | 提示
- 这是因为即使使用 `response_model_include` 或 `response_model_exclude` 来省略某些属性,在应用程序的 OpenAPI 定义(和文档)中生成的 JSON Schema 仍将是完整的模型。
+但仍然推荐使用上面的思路,使用多个类,而不是这些参数。
- 这也适用于作用类似的 `response_model_by_alias`。
+因为即使你使用 `response_model_include` 或 `response_model_exclude` 省略了一些属性,你的应用在 OpenAPI(和文档)中生成的 JSON Schema 仍然会是完整模型。
-```Python hl_lines="31 37"
-{!../../../docs_src/response_model/tutorial005.py!}
-```
+这同样适用于类似的 `response_model_by_alias`。
-!!! tip
- `{"name", "description"}` 语法创建一个具有这两个值的 `set`。
+///
- 等同于 `set(["name", "description"])`。
+{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}
-#### 使用 `list` 而不是 `set`
+/// tip | 提示
-如果你忘记使用 `set` 而是使用 `list` 或 `tuple`,FastAPI 仍会将其转换为 `set` 并且正常工作:
+`{"name", "description"}` 语法创建一个包含这两个值的 `set`。
-```Python hl_lines="31 37"
-{!../../../docs_src/response_model/tutorial006.py!}
-```
+等同于 `set(["name", "description"])`。
+
+///
+
+#### 使用 `list` 而不是 `set` { #using-lists-instead-of-sets }
+
+如果你忘记使用 `set` 而是使用了 `list` 或 `tuple`,FastAPI 仍会将其转换为 `set` 并正常工作:
+
+{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}
-## 总结
+## 总结 { #recap }
-使用*路径操作装饰器*的 `response_model` 参数来定义响应模型,特别是确保私有数据被过滤掉。
+使用*路径操作装饰器*的 `response_model` 参数来定义响应模型,尤其是确保私有数据被过滤掉。
-使用 `response_model_exclude_unset` 来仅返回显式设定的值。
+使用 `response_model_exclude_unset` 来仅返回显式设置的值。
diff --git a/docs/zh/docs/tutorial/response-status-code.md b/docs/zh/docs/tutorial/response-status-code.md
index 3578319423adc..e57c0e59377e7 100644
--- a/docs/zh/docs/tutorial/response-status-code.md
+++ b/docs/zh/docs/tutorial/response-status-code.md
@@ -1,89 +1,101 @@
-# 响应状态码
+# 响应状态码 { #response-status-code }
-与指定响应模型的方式相同,你也可以在以下任意的*路径操作*中使用 `status_code` 参数来声明用于响应的 HTTP 状态码:
+与指定响应模型的方式相同,在以下任意*路径操作*中,可以使用 `status_code` 参数声明用于响应的 HTTP 状态码:
* `@app.get()`
* `@app.post()`
* `@app.put()`
* `@app.delete()`
-* 等等。
+* 等...
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
-!!! note
- 注意,`status_code` 是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。
+/// note | 注意
-`status_code` 参数接收一个表示 HTTP 状态码的数字。
+注意,`status_code` 是(`get`、`post` 等)**装饰器**方法中的参数。与之前的参数和请求体不同,不是*路径操作函数*的参数。
-!!! info
- `status_code` 也能够接收一个 `IntEnum` 类型,比如 Python 的 `http.HTTPStatus`。
+///
-它将会:
+`status_code` 参数接收表示 HTTP 状态码的数字。
-* 在响应中返回该状态码。
-* 在 OpenAPI 模式中(以及在用户界面中)将其记录为:
+/// info | 信息
-
+`status_code` 还能接收 `IntEnum` 类型,比如 Python 的 [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus)。
-!!! note
- 一些响应状态码(请参阅下一部分)表示响应没有响应体。
+///
- FastAPI 知道这一点,并将生成表明没有响应体的 OpenAPI 文档。
+它可以:
-## 关于 HTTP 状态码
+* 在响应中返回状态码
+* 在 OpenAPI 概图(及用户界面)中存档:
-!!! note
- 如果你已经了解什么是 HTTP 状态码,请跳到下一部分。
+
-在 HTTP 协议中,你将发送 3 位数的数字状态码作为响应的一部分。
+/// note | 注意
-这些状态码有一个识别它们的关联名称,但是重要的还是数字。
+某些响应状态码表示响应没有响应体(参阅下一章)。
-简而言之:
+FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。
-* `100` 及以上状态码用于「消息」响应。你很少直接使用它们。具有这些状态代码的响应不能带有响应体。
-* **`200`** 及以上状态码用于「成功」响应。这些是你最常使用的。
- * `200` 是默认状态代码,它表示一切「正常」。
- * 另一个例子会是 `201`,「已创建」。它通常在数据库中创建了一条新记录后使用。
- * 一个特殊的例子是 `204`,「无内容」。此响应在没有内容返回给客户端时使用,因此该响应不能包含响应体。
-* **`300`** 及以上状态码用于「重定向」。具有这些状态码的响应可能有或者可能没有响应体,但 `304`「未修改」是个例外,该响应不得含有响应体。
-* **`400`** 及以上状态码用于「客户端错误」响应。这些可能是你第二常使用的类型。
- * 一个例子是 `404`,用于「未找到」响应。
- * 对于来自客户端的一般错误,你可以只使用 `400`。
-* `500` 及以上状态码用于服务器端错误。你几乎永远不会直接使用它们。当你的应用程序代码或服务器中的某些部分出现问题时,它将自动返回这些状态代码之一。
+///
-!!! tip
- 要了解有关每个状态代码以及适用场景的更多信息,请查看 MDN 关于 HTTP 状态码的文档。
+## 关于 HTTP 状态码 { #about-http-status-codes }
-## 记住名称的捷径
+/// note | 注意
-让我们再次看看之前的例子:
+如果已经了解 HTTP 状态码,请跳到下一章。
-```Python hl_lines="6"
-{!../../../docs_src/response_status_code/tutorial001.py!}
-```
+///
-`201` 是表示「已创建」的状态码。
+在 HTTP 协议中,发送 3 位数的数字状态码是响应的一部分。
-但是你不必去记住每个代码的含义。
+这些状态码都具有便于识别的关联名称,但是重要的还是数字。
-你可以使用来自 `fastapi.status` 的便捷变量。
+简言之:
-```Python hl_lines="1 6"
-{!../../../docs_src/response_status_code/tutorial002.py!}
-```
+* `100 - 199` 用于返回“信息”。这类状态码很少直接使用。具有这些状态码的响应不能包含响应体
+* **`200 - 299`** 用于表示“成功”。这些状态码是最常用的
+ * `200` 是默认状态码,表示一切“OK”
+ * `201` 表示“已创建”,通常在数据库中创建新记录后使用
+ * `204` 是一种特殊的例子,表示“无内容”。该响应在没有为客户端返回内容时使用,因此,该响应不能包含响应体
+* **`300 - 399`** 用于“重定向”。具有这些状态码的响应不一定包含响应体,但 `304`“未修改”是个例外,该响应不得包含响应体
+* **`400 - 499`** 用于表示“客户端错误”。这些可能是第二常用的类型
+ * `404`,用于“未找到”响应
+ * 对于来自客户端的一般错误,可以只使用 `400`
+* `500 - 599` 用于表示服务器端错误。几乎永远不会直接使用这些状态码。应用代码或服务器出现问题时,会自动返回这些状态码
-它们只是一种便捷方式,它们具有同样的数字代码,但是这样使用你就可以使用编辑器的自动补全功能来查找它们:
+/// tip | 提示
-
+想了解每个状态码的更多信息以及适用场景,请参阅 [MDN 的 HTTP 状态码文档](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)。
-!!! note "技术细节"
- 你也可以使用 `from starlette import status`。
+///
- 为了给你(即开发者)提供方便,**FastAPI** 提供了与 `starlette.status` 完全相同的 `fastapi.status`。但它直接来自于 Starlette。
+## 状态码名称快捷方式 { #shortcut-to-remember-the-names }
-## 更改默认状态码
+再看下之前的例子:
-稍后,在[高级用户指南](../advanced/response-change-status-code.md){.internal-link target=_blank}中你将了解如何返回与在此声明的默认状态码不同的状态码。
+{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *}
+
+`201` 表示“已创建”的状态码。
+
+但我们没有必要记住所有代码的含义。
+
+可以使用 `fastapi.status` 中的快捷变量。
+
+{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *}
+
+这只是一种快捷方式,具有相同的数字代码,但它可以使用编辑器的自动补全功能:
+
+
+
+/// note | 技术细节
+
+也可以使用 `from starlette import status`。
+
+为了让开发者更方便,**FastAPI** 提供了与 `starlette.status` 完全相同的 `fastapi.status`。但它直接来自于 Starlette。
+
+///
+
+## 更改默认状态码 { #changing-the-default }
+
+稍后在[高级用户指南](../advanced/response-change-status-code.md)中,你将看到如何返回与此处声明的默认状态码不同的状态码。
diff --git a/docs/zh/docs/tutorial/schema-extra-example.md b/docs/zh/docs/tutorial/schema-extra-example.md
index 816e8f68efbc4..482abd21de66b 100644
--- a/docs/zh/docs/tutorial/schema-extra-example.md
+++ b/docs/zh/docs/tutorial/schema-extra-example.md
@@ -1,106 +1,202 @@
-# 模式的额外信息 - 例子
+# 声明请求示例数据 { #declare-request-example-data }
-您可以在JSON模式中定义额外的信息。
+你可以为你的应用将接收的数据声明示例。
-一个常见的用例是添加一个将在文档中显示的`example`。
+这里有几种实现方式。
-有几种方法可以声明额外的 JSON 模式信息。
+## Pydantic 模型中的额外 JSON Schema 数据 { #extra-json-schema-data-in-pydantic-models }
-## Pydantic `schema_extra`
+你可以为一个 Pydantic 模型声明 `examples`,它们会被添加到生成的 JSON Schema 中。
-您可以使用 `Config` 和 `schema_extra` 为Pydantic模型声明一个示例,如Pydantic 文档:定制 Schema 中所述:
+{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}
-=== "Python 3.10+"
+这些额外信息会原样添加到该模型输出的 JSON Schema 中,并会在 API 文档中使用。
- ```Python hl_lines="13-21"
- {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!}
- ```
+你可以使用属性 `model_config`,它接收一个 `dict`,详见 [Pydantic 文档:配置](https://docs.pydantic.dev/latest/api/config/)。
-=== "Python 3.6+"
+你可以设置 `"json_schema_extra"`,其值为一个 `dict`,包含你希望出现在生成 JSON Schema 中的任意附加数据,包括 `examples`。
- ```Python hl_lines="15-23"
- {!> ../../../docs_src/schema_extra_example/tutorial001.py!}
- ```
+/// tip | 提示
-这些额外的信息将按原样添加到输出的JSON模式中。
+你也可以用同样的技巧扩展 JSON Schema,添加你自己的自定义额外信息。
-## `Field` 的附加参数
+例如,你可以用它为前端用户界面添加元数据等。
-在 `Field`, `Path`, `Query`, `Body` 和其他你之后将会看到的工厂函数,你可以为JSON 模式声明额外信息,你也可以通过给工厂函数传递其他的任意参数来给JSON 模式声明额外信息,比如增加 `example`:
+///
-=== "Python 3.10+"
+/// info | 信息
- ```Python hl_lines="2 8-11"
- {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!}
- ```
+OpenAPI 3.1.0(自 FastAPI 0.99.0 起使用)增加了对 `examples` 的支持,它是 JSON Schema 标准的一部分。
-=== "Python 3.6+"
+在此之前,只支持使用单个示例的关键字 `example`。OpenAPI 3.1.0 仍然支持它,但它已被弃用,并不属于 JSON Schema 标准。因此,建议你把 `example` 迁移到 `examples`。🤓
- ```Python hl_lines="4 10-13"
- {!> ../../../docs_src/schema_extra_example/tutorial002.py!}
- ```
+你可以在本页末尾阅读更多内容。
-!!! warning
- 请记住,传递的那些额外参数不会添加任何验证,只会添加注释,用于文档的目的。
+///
-## `Body` 额外参数
+## `Field` 的附加参数 { #field-additional-arguments }
-你可以通过传递额外信息给 `Field` 同样的方式操作`Path`, `Query`, `Body`等。
+在 Pydantic 模型中使用 `Field()` 时,你也可以声明额外的 `examples`:
-比如,你可以将请求体的一个 `example` 传递给 `Body`:
+{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *}
-=== "Python 3.10+"
+## JSON Schema 中的 `examples` - OpenAPI { #examples-in-json-schema-openapi }
- ```Python hl_lines="22-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!}
- ```
+在以下任意场景中使用:
-=== "Python 3.9+"
+- `Path()`
+- `Query()`
+- `Header()`
+- `Cookie()`
+- `Body()`
+- `Form()`
+- `File()`
- ```Python hl_lines="22-27"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!}
- ```
+你也可以声明一组 `examples`,这些带有附加信息的示例将被添加到它们在 OpenAPI 中的 JSON Schema 里。
-=== "Python 3.6+"
+### 带有 `examples` 的 `Body` { #body-with-examples }
- ```Python hl_lines="23-28"
- {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!}
- ```
+这里我们向 `Body()` 传入 `examples`,其中包含一个期望的数据示例:
-=== "Python 3.10+ non-Annotated"
+{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *}
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+### 文档 UI 中的示例 { #example-in-the-docs-ui }
- ```Python hl_lines="18-23"
- {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
- ```
+使用上述任一方法,在 `/docs` 中看起来会是这样:
-=== "Python 3.6+ non-Annotated"
+
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+### 带有多个 `examples` 的 `Body` { #body-with-multiple-examples }
- ```Python hl_lines="20-25"
- {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
- ```
+当然,你也可以传入多个 `examples`:
-## 文档 UI 中的例子
+{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *}
-使用上面的任何方法,它在 `/docs` 中看起来都是这样的:
+这样做时,这些示例会成为该请求体数据内部 JSON Schema 的一部分。
-
+不过,在撰写本文时,用于展示文档 UI 的 Swagger UI 并不支持显示 JSON Schema 中数据的多个示例。但请继续阅读,下面有一种变通方法。
+
+### OpenAPI 特定的 `examples` { #openapi-specific-examples }
+
+在 JSON Schema 支持 `examples` 之前,OpenAPI 就已支持一个同名但不同的字段 `examples`。
+
+这个面向 OpenAPI 的 `examples` 位于 OpenAPI 规范的另一处。它放在每个路径操作的详细信息中,而不是每个 JSON Schema 里。
+
+而 Swagger UI 早就支持这个特定的 `examples` 字段。因此,你可以用它在文档 UI 中展示不同的示例。
+
+这个 OpenAPI 特定字段 `examples` 的结构是一个包含多个示例的 `dict`(而不是一个 `list`),每个示例都包含会被添加到 OpenAPI 的额外信息。
+
+这不放在 OpenAPI 内部包含的各个 JSON Schema 里,而是直接放在路径操作上。
+
+### 使用 `openapi_examples` 参数 { #using-the-openapi-examples-parameter }
+
+你可以在 FastAPI 中通过参数 `openapi_examples` 来声明这个 OpenAPI 特定的 `examples`,适用于:
+
+- `Path()`
+- `Query()`
+- `Header()`
+- `Cookie()`
+- `Body()`
+- `Form()`
+- `File()`
+
+这个 `dict` 的键用于标识每个示例,每个值是另一个 `dict`。
+
+`examples` 中每个具体示例的 `dict` 可以包含:
+
+- `summary`:该示例的简短描述。
+- `description`:较长描述,可以包含 Markdown 文本。
+- `value`:实际展示的示例,例如一个 `dict`。
+- `externalValue`:`value` 的替代项,指向该示例的 URL。不过它的工具支持度可能不如 `value`。
+
+你可以这样使用:
+
+{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *}
+
+### 文档 UI 中的 OpenAPI 示例 { #openapi-examples-in-the-docs-ui }
+
+当把 `openapi_examples` 添加到 `Body()` 后,`/docs` 会如下所示:
+
+
+
+## 技术细节 { #technical-details }
+
+/// tip | 提示
+
+如果你已经在使用 FastAPI 版本 0.99.0 或更高版本,你大概率可以跳过这些细节。
+
+它们对更早版本(OpenAPI 3.1.0 尚不可用之前)更相关。
+
+你可以把这当作一堂简短的 OpenAPI 和 JSON Schema 历史课。🤓
+
+///
+
+/// warning | 警告
+
+以下是关于 JSON Schema 和 OpenAPI 标准的非常技术性的细节。
+
+如果上面的思路对你已经足够可用,你可能不需要这些细节,可以直接跳过。
+
+///
+
+在 OpenAPI 3.1.0 之前,OpenAPI 使用的是一个更旧且经过修改的 JSON Schema 版本。
+
+当时 JSON Schema 没有 `examples`,所以 OpenAPI 在它修改过的版本中添加了自己的 `example` 字段。
+
+OpenAPI 还在规范的其他部分添加了 `example` 和 `examples` 字段:
+
+- [`Parameter Object`(规范中)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object),被 FastAPI 的以下内容使用:
+ - `Path()`
+ - `Query()`
+ - `Header()`
+ - `Cookie()`
+- [`Request Body Object` 中的 `content` 字段里的 `Media Type Object`(规范中)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object),被 FastAPI 的以下内容使用:
+ - `Body()`
+ - `File()`
+ - `Form()`
+
+/// info | 信息
+
+这个旧的、OpenAPI 特定的 `examples` 参数,自 FastAPI `0.103.0` 起改名为 `openapi_examples`。
+
+///
+
+### JSON Schema 的 `examples` 字段 { #json-schemas-examples-field }
+
+后来,JSON Schema 在新版本的规范中添加了 [`examples`](https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.9.5) 字段。
+
+随后新的 OpenAPI 3.1.0 基于最新版本(JSON Schema 2020-12),其中包含了这个新的 `examples` 字段。
+
+现在,这个新的 `examples` 字段优先于旧的单个(且自定义的)`example` 字段,后者已被弃用。
+
+JSON Schema 中这个新的 `examples` 字段只是一个由示例组成的 `list`,而不是像上面提到的 OpenAPI 其他位置那样带有额外元数据的 `dict`。
+
+/// info | 信息
+
+即使在 OpenAPI 3.1.0 发布、并与 JSON Schema 有了这种更简单的集成之后,有一段时间里,提供自动文档的 Swagger UI 并不支持 OpenAPI 3.1.0(它自 5.0.0 版本起已支持 🎉)。
+
+因此,FastAPI 0.99.0 之前的版本仍然使用低于 3.1.0 的 OpenAPI 版本。
+
+///
+
+### Pydantic 与 FastAPI 的 `examples` { #pydantic-and-fastapi-examples }
+
+当你在 Pydantic 模型中添加 `examples`,通过 `schema_extra` 或 `Field(examples=["something"])`,这些示例会被添加到该 Pydantic 模型的 JSON Schema 中。
+
+这个 Pydantic 模型的 JSON Schema 会被包含到你的 API 的 OpenAPI 中,然后在文档 UI 中使用。
+
+在 FastAPI 0.99.0 之前的版本(0.99.0 及以上使用更新的 OpenAPI 3.1.0),当你在其他工具(`Query()`、`Body()` 等)中使用 `example` 或 `examples` 时,这些示例不会被添加到描述该数据的 JSON Schema 中(甚至不会添加到 OpenAPI 自己的 JSON Schema 版本中),而是会直接添加到 OpenAPI 的路径操作声明中(在 OpenAPI 使用 JSON Schema 的部分之外)。
-## 技术细节
+但现在 FastAPI 0.99.0 及以上使用 OpenAPI 3.1.0(其使用 JSON Schema 2020-12)以及 Swagger UI 5.0.0 及以上后,一切更加一致,示例会包含在 JSON Schema 中。
-关于 `example` 和 `examples`...
+### Swagger UI 与 OpenAPI 特定的 `examples` { #swagger-ui-and-openapi-specific-examples }
-JSON Schema在最新的一个版本中定义了一个字段 `examples` ,但是 OpenAPI 基于之前的一个旧版JSON Schema,并没有 `examples`.
+此前,由于 Swagger UI 不支持多个 JSON Schema 示例(截至 2023-08-26),用户无法在文档中展示多个示例。
-所以 OpenAPI为了相似的目的定义了自己的 `example` (使用 `example`, 而不是 `examples`), 这也是文档 UI 所使用的 (使用 Swagger UI).
+为了解决这个问题,FastAPI `0.103.0` 通过新增参数 `openapi_examples`,为声明同样的旧式 OpenAPI 特定 `examples` 字段提供了支持。🤓
-所以,虽然 `example` 不是JSON Schema的一部分,但它是OpenAPI的一部分,这将被文档UI使用。
+### 总结 { #summary }
-## 其他信息
+我曾经说我不太喜欢历史……结果现在在这儿上“技术史”课。😅
-同样的方法,你可以添加你自己的额外信息,这些信息将被添加到每个模型的JSON模式中,例如定制前端用户界面,等等。
+简而言之,升级到 FastAPI 0.99.0 或更高版本,一切会更简单、一致、直观,你也不必了解这些历史细节。😎
diff --git a/docs/zh/docs/tutorial/security/first-steps.md b/docs/zh/docs/tutorial/security/first-steps.md
index 7b1052e12aa8c..6cc91211a3313 100644
--- a/docs/zh/docs/tutorial/security/first-steps.md
+++ b/docs/zh/docs/tutorial/security/first-steps.md
@@ -1,206 +1,203 @@
-# 安全 - 第一步
+# 安全 - 第一步 { #security-first-steps }
-假设**后端** API 在某个域。
+假设你的**后端** API 位于某个域名下。
-**前端**在另一个域,或(移动应用中)在同一个域的不同路径下。
+而**前端**在另一个域名,或同一域名的不同路径(或在移动应用中)。
-并且,前端要使用后端的 **username** 与 **password** 验证用户身份。
+你希望前端能通过**username** 和 **password** 与后端进行身份验证。
-固然,**FastAPI** 支持 **OAuth2** 身份验证。
+我们可以用 **OAuth2** 在 **FastAPI** 中实现它。
-但为了节省开发者的时间,不要只为了查找很少的内容,不得不阅读冗长的规范文档。
+但为了节省你的时间,不必为获取少量信息而通读冗长的规范。
-我们建议使用 **FastAPI** 的安全工具。
+我们直接使用 **FastAPI** 提供的安全工具。
-## 概览
+## 效果预览 { #how-it-looks }
-首先,看看下面的代码是怎么运行的,然后再回过头来了解其背后的原理。
+先直接运行代码看看效果,之后再回过头理解其背后的原理。
-## 创建 `main.py`
+## 创建 `main.py` { #create-main-py }
把下面的示例代码复制到 `main.py`:
-=== "Python 3.9+"
+{* ../../docs_src/security/tutorial001_an_py310.py *}
- ```Python
- {!> ../../../docs_src/security/tutorial001_an_py39.py!}
- ```
+## 运行 { #run-it }
-=== "Python 3.6+"
+/// info | 信息
- ```Python
- {!> ../../../docs_src/security/tutorial001_an.py!}
- ```
+当你使用命令 `pip install "fastapi[standard]"` 安装 **FastAPI** 时,[`python-multipart`](https://github.com/Kludex/python-multipart) 包会自动安装。
-=== "Python 3.6+ non-Annotated"
+但是,如果你使用 `pip install fastapi`,默认不会包含 `python-multipart` 包。
- !!! tip
- 尽可能选择使用 `Annotated` 的版本。
+如需手动安装,请先创建并激活[虚拟环境](../../virtual-environments.md),然后执行:
- ```Python
- {!> ../../../docs_src/security/tutorial001.py!}
- ```
-
-## 运行
-
-!!! info "说明"
-
- 先安装 `python-multipart`。
+```console
+$ pip install python-multipart
+```
- 安装命令: `pip install python-multipart`。
+这是因为 **OAuth2** 使用“表单数据”来发送 `username` 和 `password`。
- 这是因为 **OAuth2** 使用**表单数据**发送 `username` 与 `password`。
+///
-用下面的命令运行该示例:
+用下面的命令运行示例:
-!!! check "Authorize 按钮!"
+/// check | Authorize 按钮!
+
+页面右上角已经有一个崭新的“Authorize”按钮。
- 页面右上角出现了一个「**Authorize**」按钮。
+你的*路径操作*右上角还有一个可点击的小锁图标。
- *路径操作*的右上角也出现了一个可以点击的小锁图标。
+///
-点击 **Authorize** 按钮,弹出授权表单,输入 `username` 与 `password` 及其它可选字段:
+点击它,会弹出一个授权表单,可输入 `username` 和 `password`(以及其它可选字段):
-!!! note "笔记"
+/// note | 注意
- 目前,在表单中输入内容不会有任何反应,后文会介绍相关内容。
+目前无论在表单中输入什么都不会生效,我们稍后就会实现它。
-虽然此文档不是给前端最终用户使用的,但这个自动工具非常实用,可在文档中与所有 API 交互。
+///
-前端团队(可能就是开发者本人)可以使用本工具。
+这当然不是面向最终用户的前端,但它是一个很棒的自动化工具,可交互式地为整个 API 提供文档。
-第三方应用与系统也可以调用本工具。
+前端团队(也可能就是你自己)可以使用它。
-开发者也可以用它来调试、检查、测试应用。
+第三方应用和系统也可以使用它。
-## 密码流
+你也可以用它来调试、检查和测试同一个应用。
-现在,我们回过头来介绍这段代码的原理。
+## `password` 流 { #the-password-flow }
-`Password` **流**是 OAuth2 定义的,用于处理安全与身份验证的方式(**流**)。
+现在回过头来理解这些内容。
-OAuth2 的设计目标是为了让后端或 API 独立于服务器验证用户身份。
+`password` “流”(flow)是 OAuth2 定义的处理安全与身份验证的一种方式。
-但在本例中,**FastAPI** 应用会处理 API 与身份验证。
+OAuth2 的设计目标是让后端或 API 与负责用户认证的服务器解耦。
-下面,我们来看一下简化的运行流程:
+但在这个例子中,**FastAPI** 应用同时处理 API 和认证。
-- 用户在前端输入 `username` 与`password`,并点击**回车**
-- (用户浏览器中运行的)前端把 `username` 与`password` 发送至 API 中指定的 URL(使用 `tokenUrl="token"` 声明)
-- API 检查 `username` 与`password`,并用令牌(`Token`) 响应(暂未实现此功能):
- - 令牌只是用于验证用户的字符串
- - 一般来说,令牌会在一段时间后过期
- - 过时后,用户要再次登录
- - 这样一来,就算令牌被人窃取,风险也较低。因为它与永久密钥不同,**在绝大多数情况下**不会长期有效
-- 前端临时将令牌存储在某个位置
-- 用户点击前端,前往前端应用的其它部件
-- 前端需要从 API 中提取更多数据:
- - 为指定的端点(Endpoint)进行身份验证
- - 因此,用 API 验证身份时,要发送值为 `Bearer` + 令牌的请求头 `Authorization`
- - 假如令牌为 `foobar`,`Authorization` 请求头就是: `Bearer foobar`
+从这个简化的角度来看看流程:
-## **FastAPI** 的 `OAuth2PasswordBearer`
+* 用户在前端输入 `username` 和 `password`,然后按下 `Enter`。
+* 前端(运行在用户浏览器中)把 `username` 和 `password` 发送到我们 API 中的特定 URL(使用 `tokenUrl="token"` 声明)。
+* API 校验 `username` 和 `password`,并返回一个“令牌”(这些我们尚未实现)。
+ * “令牌”只是一个字符串,包含一些内容,之后可用来验证该用户。
+ * 通常,令牌会在一段时间后过期。
+ * 因此,用户过一段时间需要重新登录。
+ * 如果令牌被窃取,风险也更小。它不像一把永久有效的钥匙(在大多数情况下)。
+* 前端会把令牌临时存储在某处。
+* 用户在前端中点击跳转到前端应用的其他部分。
+* 前端需要从 API 获取更多数据。
+ * 但该端点需要身份验证。
+ * 因此,为了与我们的 API 进行身份验证,它会发送一个 `Authorization` 请求头,值为 `Bearer ` 加上令牌。
+ * 如果令牌内容是 `foobar`,`Authorization` 请求头的内容就是:`Bearer foobar`。
-**FastAPI** 提供了不同抽象级别的安全工具。
+## **FastAPI** 的 `OAuth2PasswordBearer` { #fastapis-oauth2passwordbearer }
-本例使用 **OAuth2** 的 **Password** 流以及 **Bearer** 令牌(`Token`)。为此要使用 `OAuth2PasswordBearer` 类。
+**FastAPI** 在不同抽象层级提供了多种安全工具。
-!!! info "说明"
+本示例将使用 **OAuth2** 的 **Password** 流程并配合 **Bearer** 令牌,通过 `OAuth2PasswordBearer` 类来实现。
- `Bearer` 令牌不是唯一的选择。
+/// info | 信息
- 但它是最适合这个用例的方案。
+“Bearer” 令牌并非唯一选项。
- 甚至可以说,它是适用于绝大多数用例的最佳方案,除非您是 OAuth2 的专家,知道为什么其它方案更合适。
+但它非常适合我们的用例。
- 本例中,**FastAPI** 还提供了构建工具。
+对于大多数用例,它也可能是最佳选择,除非你是 OAuth2 专家,并明确知道为何其他方案更适合你的需求。
-创建 `OAuth2PasswordBearer` 的类实例时,要传递 `tokenUrl` 参数。该参数包含客户端(用户浏览器中运行的前端) 的 URL,用于发送 `username` 与 `password`,并获取令牌。
+在那种情况下,**FastAPI** 同样提供了相应的构建工具。
-```Python hl_lines="6"
-{!../../../docs_src/security/tutorial001.py!}
-```
+///
-!!! tip "提示"
+创建 `OAuth2PasswordBearer` 类实例时,需要传入 `tokenUrl` 参数。该参数包含客户端(运行在用户浏览器中的前端)用来发送 `username` 和 `password` 以获取令牌的 URL。
- 在此,`tokenUrl="token"` 指向的是暂未创建的相对 URL `token`。这个相对 URL 相当于 `./token`。
+{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *}
- 因为使用的是相对 URL,如果 API 位于 `https://example.com/`,则指向 `https://example.com/token`。但如果 API 位于 `https://example.com/api/v1/`,它指向的就是`https://example.com/api/v1/token`。
+/// tip | 提示
- 使用相对 URL 非常重要,可以确保应用在遇到[使用代理](../../advanced/behind-a-proxy.md){.internal-link target=_blank}这样的高级用例时,也能正常运行。
+这里的 `tokenUrl="token"` 指向的是尚未创建的相对 URL `token`,等价于 `./token`。
-该参数不会创建端点或*路径操作*,但会声明客户端用来获取令牌的 URL `/token` 。此信息用于 OpenAPI 及 API 文档。
+因为使用的是相对 URL,若你的 API 位于 `https://example.com/`,它将指向 `https://example.com/token`;若你的 API 位于 `https://example.com/api/v1/`,它将指向 `https://example.com/api/v1/token`。
-接下来,学习如何创建实际的路径操作。
+使用相对 URL 很重要,这能确保你的应用在诸如[使用代理](../../advanced/behind-a-proxy.md)等高级用例中依然正常工作。
-!!! info "说明"
+///
- 严苛的 **Pythonista** 可能不喜欢用 `tokenUrl` 这种命名风格代替 `token_url`。
+这个参数不会创建该端点/*路径操作*,而是声明客户端应使用 `/token` 这个 URL 来获取令牌。这些信息会用于 OpenAPI,进而用于交互式 API 文档系统。
- 这种命名方式是因为要使用与 OpenAPI 规范中相同的名字。以便在深入校验安全方案时,能通过复制粘贴查找更多相关信息。
+我们很快也会创建对应的实际路径操作。
-`oauth2_scheme` 变量是 `OAuth2PasswordBearer` 的实例,也是**可调用项**。
+/// info | 信息
-以如下方式调用:
+如果你是非常严格的 “Pythonista”,可能不喜欢使用参数名 `tokenUrl` 而不是 `token_url`。
+
+这是因为它使用了与 OpenAPI 规范中相同的名称。这样当你需要深入了解这些安全方案时,可以直接复制粘贴去查找更多信息。
+
+///
+
+`oauth2_scheme` 变量是 `OAuth2PasswordBearer` 的一个实例,同时它也是“可调用”的。
+
+可以像这样调用:
```Python
oauth2_scheme(some, parameters)
```
-因此,`Depends` 可以调用 `oauth2_scheme` 变量。
+因此,它可以与 `Depends` 一起使用。
-### 使用
+### 使用 { #use-it }
-接下来,使用 `Depends` 把 `oauth2_scheme` 传入依赖项。
+现在你可以通过 `Depends` 将 `oauth2_scheme` 作为依赖传入。
-```Python hl_lines="10"
-{!../../../docs_src/security/tutorial001.py!}
-```
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
+
+该依赖会提供一个 `str`,赋值给*路径操作函数*的参数 `token`。
-该依赖项使用字符串(`str`)接收*路径操作函数*的参数 `token` 。
+**FastAPI** 会据此在 OpenAPI 架构(以及自动生成的 API 文档)中定义一个“安全方案”。
-**FastAPI** 使用依赖项在 OpenAPI 概图(及 API 文档)中定义**安全方案**。
+/// info | 技术细节
-!!! info "技术细节"
+**FastAPI** 之所以知道可以使用(在依赖中声明的)`OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,是因为它继承自 `fastapi.security.oauth2.OAuth2`,而后者又继承自 `fastapi.security.base.SecurityBase`。
- **FastAPI** 使用(在依赖项中声明的)类 `OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,这是因为它继承自 `fastapi.security.oauth2.OAuth2`,而该类又是继承自`fastapi.security.base.SecurityBase`。
+所有与 OpenAPI(以及自动 API 文档)集成的安全工具都继承自 `SecurityBase`,这就是 **FastAPI** 能将它们集成到 OpenAPI 的方式。
- 所有与 OpenAPI(及 API 文档)集成的安全工具都继承自 `SecurityBase`, 这就是为什么 **FastAPI** 能把它们集成至 OpenAPI 的原因。
+///
-## 实现的操作
+## 它做了什么 { #what-it-does }
-FastAPI 校验请求中的 `Authorization` 请求头,核对请求头的值是不是由 `Bearer ` + 令牌组成, 并返回令牌字符串(`str`)。
+它会在请求中查找 `Authorization` 请求头,检查其值是否为 `Bearer ` 加上一些令牌,并将该令牌作为 `str` 返回。
-如果没有找到 `Authorization` 请求头,或请求头的值不是 `Bearer ` + 令牌。FastAPI 直接返回 401 错误状态码(`UNAUTHORIZED`)。
+如果没有 `Authorization` 请求头,或者其值不包含 `Bearer ` 令牌,它会直接返回 401 状态码错误(`UNAUTHORIZED`)。
-开发者不需要检查错误信息,查看令牌是否存在,只要该函数能够执行,函数中就会包含令牌字符串。
+你甚至无需检查令牌是否存在即可返回错误;只要你的函数被执行,就可以确定会拿到一个 `str` 类型的令牌。
-正如下图所示,API 文档已经包含了这项功能:
+你已经可以在交互式文档中试试了:
-目前,暂时还没有实现验证令牌是否有效的功能,不过后文很快就会介绍的。
+我们还没有验证令牌是否有效,但这已经是一个良好的开端。
-## 小结
+## 小结 { #recap }
-看到了吧,只要多写三四行代码,就可以添加基础的安全表单。
+只需增加三四行代码,你就已经拥有了一种初步的安全机制。
diff --git a/docs/zh/docs/tutorial/security/get-current-user.md b/docs/zh/docs/tutorial/security/get-current-user.md
index 477baec3afbf4..814ff2c82227f 100644
--- a/docs/zh/docs/tutorial/security/get-current-user.md
+++ b/docs/zh/docs/tutorial/security/get-current-user.md
@@ -1,114 +1,107 @@
-# 获取当前用户
+# 获取当前用户 { #get-current-user }
-在上一章节中,(基于依赖项注入系统的)安全系统向*路径操作函数*提供了一个 `str` 类型的 `token`:
+上一章中,(基于依赖注入系统的)安全系统向*路径操作函数*传递了 `str` 类型的 `token`:
-```Python hl_lines="10"
-{!../../../docs_src/security/tutorial001.py!}
-```
+{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *}
-但这还不是很实用。
+但这并不实用。
-让我们来使它返回当前用户给我们。
+接下来,我们学习如何返回当前用户。
-## 创建一个用户模型
+## 创建用户模型 { #create-a-user-model }
-首先,让我们来创建一个用户 Pydantic 模型。
+首先,创建 Pydantic 用户模型。
-与使用 Pydantic 声明请求体的方式相同,我们可以在其他任何地方使用它:
+与使用 Pydantic 声明请求体相同,并且可在任何位置使用:
-```Python hl_lines="5 12-16"
-{!../../../docs_src/security/tutorial002.py!}
-```
+{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *}
-## 创建一个 `get_current_user` 依赖项
+## 创建 `get_current_user` 依赖项 { #create-a-get-current-user-dependency }
-让我们来创建一个 `get_current_user` 依赖项。
+创建 `get_current_user` 依赖项。
-还记得依赖项可以有子依赖项吗?
+还记得依赖项支持子依赖项吗?
-`get_current_user` 将具有一个我们之前所创建的同一个 `oauth2_scheme` 作为依赖项。
+`get_current_user` 使用 `oauth2_scheme` 作为依赖项。
-与我们之前直接在路径操作中所做的相同,我们新的依赖项 `get_current_user` 将从子依赖项 `oauth2_scheme` 中接收一个 `str` 类型的 `token`:
+与之前直接在路径操作中的做法相同,新的 `get_current_user` 依赖项从子依赖项 `oauth2_scheme` 中接收 `str` 类型的 `token`:
-```Python hl_lines="25"
-{!../../../docs_src/security/tutorial002.py!}
-```
+{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *}
-## 获取用户
+## 获取用户 { #get-the-user }
-`get_current_user` 将使用我们创建的(伪)工具函数,该函数接收 `str` 类型的令牌并返回我们的 Pydantic `User` 模型:
+`get_current_user` 使用创建的(伪)工具函数,该函数接收 `str` 类型的令牌,并返回 Pydantic 的 `User` 模型:
-```Python hl_lines="19-22 26-27"
-{!../../../docs_src/security/tutorial002.py!}
-```
+{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *}
-## 注入当前用户
+## 注入当前用户 { #inject-the-current-user }
-因此现在我们可以在*路径操作*中使用 `get_current_user` 作为 `Depends` 了:
+在*路径操作* 的 `Depends` 中使用 `get_current_user`:
-```Python hl_lines="31"
-{!../../../docs_src/security/tutorial002.py!}
-```
+{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *}
-注意我们将 `current_user` 的类型声明为 Pydantic 模型 `User`。
+注意,此处把 `current_user` 的类型声明为 Pydantic 的 `User` 模型。
-这将帮助我们在函数内部使用所有的代码补全和类型检查。
+这有助于在函数内部使用代码补全和类型检查。
-!!! tip
- 你可能还记得请求体也是使用 Pydantic 模型来声明的。
+/// tip | 提示
- 在这里 **FastAPI** 不会搞混,因为你正在使用的是 `Depends`。
+还记得请求体也是使用 Pydantic 模型声明的吧。
-!!! check
- 这种依赖系统的设计方式使我们可以拥有不同的依赖项(不同的「可依赖类型」),并且它们都返回一个 `User` 模型。
+放心,因为使用了 `Depends`,**FastAPI** 不会搞混。
- 我们并未被局限于只能有一个返回该类型数据的依赖项。
+///
+/// check | 检查
-## 其他模型
+依赖系统的这种设计方式可以支持不同的依赖项返回同一个 `User` 模型。
-现在你可以直接在*路径操作函数*中获取当前用户,并使用 `Depends` 在**依赖注入**级别处理安全性机制。
+而不是局限于只能有一个返回该类型数据的依赖项。
-你可以使用任何模型或数据来满足安全性要求(在这个示例中,使用的是 Pydantic 模型 `User`)。
+///
-但是你并未被限制只能使用某些特定的数据模型,类或类型。
+## 其它模型 { #other-models }
-你想要在模型中使用 `id` 和 `email` 而不使用任何的 `username`?当然可以。你可以同样地使用这些工具。
+接下来,直接在*路径操作函数*中获取当前用户,并用 `Depends` 在**依赖注入**系统中处理安全机制。
-你只想要一个 `str`?或者仅仅一个 `dict`?还是直接一个数据库模型类的实例?它们的工作方式都是一样的。
+开发者可以使用任何模型或数据满足安全需求(本例中是 Pydantic 的 `User` 模型)。
-实际上你没有用户登录到你的应用程序,而是只拥有访问令牌的机器人,程序或其他系统?再一次,它们的工作方式也是一样的。
+而且,不局限于只能使用特定的数据模型、类或类型。
-尽管去使用你的应用程序所需要的任何模型,任何类,任何数据库。**FastAPI** 通过依赖项注入系统都帮你搞定。
+不想在模型中使用 `username`,而是使用 `id` 和 `email`?当然可以。这些工具也支持。
+只想使用字符串?或字典?甚至是数据库类模型的实例?工作方式都一样。
-## 代码体积
+实际上,就算登录应用的不是用户,而是只拥有访问令牌的机器人、程序或其它系统?工作方式也一样。
-这个示例似乎看起来很冗长。考虑到我们在同一文件中混合了安全性,数据模型工具函数和路径操作等代码。
+尽管使用应用所需的任何模型、类、数据库。**FastAPI** 通过依赖注入系统都能帮您搞定。
-但关键的是。
-安全性和依赖项注入内容只需要编写一次。
+## 代码大小 { #code-size }
-你可以根据需要使其变得很复杂。而且只需要在一个地方写一次。但仍然具备所有的灵活性。
+这个示例看起来有些冗长。毕竟这个文件同时包含了安全、数据模型的工具函数,以及路径操作等代码。
-但是,你可以有无数个使用同一安全系统的端点(*路径操作*)。
+但,关键是:
-所有(或所需的任何部分)的端点,都可以利用对这些或你创建的其他依赖项进行复用所带来的优势。
+**安全和依赖注入的代码只需要写一次。**
-所有的这无数个*路径操作*甚至可以小到只需 3 行代码:
+就算写得再复杂,也只是在一个位置写一次就够了。所以,要多复杂就可以写多复杂。
-```Python hl_lines="30-32"
-{!../../../docs_src/security/tutorial002.py!}
-```
+但是,就算有数千个端点(*路径操作*),它们都可以使用同一个安全系统。
-## 总结
+而且,所有端点(或它们的任何部件)都可以利用这些依赖项或任何其它依赖项。
-现在你可以直接在*路径操作函数*中获取当前用户。
+所有*路径操作*只需 3 行代码就可以了:
-我们已经进行到一半了。
+{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *}
-我们只需要再为用户/客户端添加一个真正发送 `username` 和 `password` 的*路径操作*。
+## 小结 { #recap }
-这些内容在下一章节。
+现在,我们可以直接在*路径操作函数*中获取当前用户。
+
+至此,安全的内容已经讲了一半。
+
+只要再为用户或客户端的*路径操作*添加真正发送 `username` 和 `password` 的功能就可以了。
+
+下一章见。
diff --git a/docs/zh/docs/tutorial/security/index.md b/docs/zh/docs/tutorial/security/index.md
index 0595f5f636129..a4c352110534f 100644
--- a/docs/zh/docs/tutorial/security/index.md
+++ b/docs/zh/docs/tutorial/security/index.md
@@ -1,4 +1,4 @@
-# 安全性
+# 安全性 { #security }
有许多方法可以处理安全性、身份认证和授权等问题。
@@ -10,11 +10,11 @@
但首先,让我们来看一些小的概念。
-## 没有时间?
+## 赶时间 { #in-a-hurry }
-如果你不关心这些术语,而只需要*立即*通过基于用户名和密码的身份认证来增加安全性,请跳转到下一章。
+如果你不关心这些术语,而只需要*立即*通过基于用户名和密码的身份认证来增加安全性,请跳转到接下来的章节。
-## OAuth2
+## OAuth2 { #oauth2 }
OAuth2是一个规范,它定义了几种处理身份认证和授权的方法。
@@ -22,9 +22,9 @@ OAuth2是一个规范,它定义了几种处理身份认证和授权的方法
它包括了使用「第三方」进行身份认证的方法。
-这就是所有带有「使用 Facebook,Google,Twitter,GitHub 登录」的系统背后所使用的机制。
+这就是所有带有「使用 Facebook,Google,X (Twitter),GitHub 登录」的系统背后所使用的机制。
-### OAuth 1
+### OAuth 1 { #oauth-1 }
有一个 OAuth 1,它与 OAuth2 完全不同,并且更为复杂,因为它直接包含了有关如何加密通信的规范。
@@ -32,11 +32,13 @@ OAuth2是一个规范,它定义了几种处理身份认证和授权的方法
OAuth2 没有指定如何加密通信,它期望你为应用程序使用 HTTPS 进行通信。
-!!! tip
- 在有关**部署**的章节中,你将了解如何使用 Traefik 和 Let's Encrypt 免费设置 HTTPS。
+/// tip | 提示
+在有关**部署**的章节中,你将了解如何使用 Traefik 和 Let's Encrypt 免费设置 HTTPS。
-## OpenID Connect
+///
+
+## OpenID Connect { #openid-connect }
OpenID Connect 是另一个基于 **OAuth2** 的规范。
@@ -46,7 +48,7 @@ OpenID Connect 是另一个基于 **OAuth2** 的规范。
但是 Facebook 登录不支持 OpenID Connect。它具有自己的 OAuth2 风格。
-### OpenID(非「OpenID Connect」)
+### OpenID(非「OpenID Connect」) { #openid-not-openid-connect }
还有一个「OpenID」规范。它试图解决与 **OpenID Connect** 相同的问题,但它不是基于 OAuth2。
@@ -54,7 +56,7 @@ OpenID Connect 是另一个基于 **OAuth2** 的规范。
如今它已经不是很流行,没有被广泛使用了。
-## OpenAPI
+## OpenAPI { #openapi }
OpenAPI(以前称为 Swagger)是用于构建 API 的开放规范(现已成为 Linux Foundation 的一部分)。
@@ -73,11 +75,11 @@ OpenAPI 定义了以下安全方案:
* 请求头。
* cookie。
* `http`:标准的 HTTP 身份认证系统,包括:
- * `bearer`: 一个值为 `Bearer` 加令牌字符串的 `Authorization` 请求头。这是从 OAuth2 继承的。
+ * `bearer`: 一个值为 `Bearer ` 加令牌字符串的 `Authorization` 请求头。这是从 OAuth2 继承的。
* HTTP Basic 认证方式。
* HTTP Digest,等等。
* `oauth2`:所有的 OAuth2 处理安全性的方式(称为「流程」)。
- *以下几种流程适合构建 OAuth 2.0 身份认证的提供者(例如 Google,Facebook,Twitter,GitHub 等):
+ *以下几种流程适合构建 OAuth 2.0 身份认证的提供者(例如 Google,Facebook,X (Twitter),GitHub 等):
* `implicit`
* `clientCredentials`
* `authorizationCode`
@@ -87,15 +89,18 @@ OpenAPI 定义了以下安全方案:
* 此自动发现机制是 OpenID Connect 规范中定义的内容。
-!!! tip
- 集成其他身份认证/授权提供者(例如Google,Facebook,Twitter,GitHub等)也是可能的,而且较为容易。
+/// tip | 提示
+
+集成其他身份认证/授权提供者(例如Google,Facebook,X (Twitter),GitHub等)也是可能的,而且较为容易。
+
+最复杂的问题是创建一个像这样的身份认证/授权提供程序,但是 **FastAPI** 为你提供了轻松完成任务的工具,同时为你解决了重活。
- 最复杂的问题是创建一个像这样的身份认证/授权提供程序,但是 **FastAPI** 为你提供了轻松完成任务的工具,同时为你解决了重活。
+///
-## **FastAPI** 实用工具
+## **FastAPI** 实用工具 { #fastapi-utilities }
FastAPI 在 `fastapi.security` 模块中为每个安全方案提供了几种工具,这些工具简化了这些安全机制的使用方法。
-在下一章中,你将看到如何使用 **FastAPI** 所提供的这些工具为你的 API 增加安全性。
+在接下来的章节中,你将看到如何使用 **FastAPI** 所提供的这些工具为你的 API 增加安全性。
而且你还将看到它如何自动地被集成到交互式文档系统中。
diff --git a/docs/zh/docs/tutorial/security/oauth2-jwt.md b/docs/zh/docs/tutorial/security/oauth2-jwt.md
index 054198545ef8e..8a56137d37845 100644
--- a/docs/zh/docs/tutorial/security/oauth2-jwt.md
+++ b/docs/zh/docs/tutorial/security/oauth2-jwt.md
@@ -1,132 +1,140 @@
-# OAuth2 实现密码哈希与 Bearer JWT 令牌验证
+# 使用密码(及哈希)的 OAuth2,基于 JWT 的 Bearer 令牌 { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens }
-至此,我们已经编写了所有安全流,本章学习如何使用 JWT 令牌(Token)和安全密码哈希(Hash)实现真正的安全机制。
+现在我们已经有了完整的安全流程,接下来用 JWT 令牌和安全的密码哈希,让应用真正安全起来。
-本章的示例代码真正实现了在应用的数据库中保存哈希密码等功能。
+这些代码可以直接用于你的应用,你可以把密码哈希保存到数据库中,等等。
-接下来,我们紧接上一章,继续完善安全机制。
+我们将从上一章结束的地方继续,逐步完善。
-## JWT 简介
+## 关于 JWT { #about-jwt }
-JWT 即**JSON 网络令牌**(JSON Web Tokens)。
+JWT 意为 “JSON Web Tokens”。
-JWT 是一种将 JSON 对象编码为没有空格,且难以理解的长字符串的标准。JWT 的内容如下所示:
+它是一种标准,把一个 JSON 对象编码成没有空格、很密集的一长串字符串。看起来像这样:
```
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
```
-JWT 字符串没有加密,任何人都能用它恢复原始信息。
+它不是加密的,所以任何人都可以从内容中恢复信息。
-但 JWT 使用了签名机制。接受令牌时,可以用签名校验令牌。
+但它是“签名”的。因此,当你收到一个自己签发的令牌时,你可以验证它确实是你签发的。
-使用 JWT 创建有效期为一周的令牌。第二天,用户持令牌再次访问时,仍为登录状态。
+这样你就可以创建一个例如有效期为 1 周的令牌。然后当用户第二天带着这个令牌回来时,你能知道该用户仍然处于登录状态。
-令牌于一周后过期,届时,用户身份验证就会失败。只有再次登录,才能获得新的令牌。如果用户(或第三方)篡改令牌的过期时间,因为签名不匹配会导致身份验证失败。
+一周后令牌过期,用户将不再被授权,需要重新登录以获取新令牌。而如果用户(或第三方)尝试修改令牌来更改过期时间,你也能发现,因为签名将不匹配。
-如需深入了解 JWT 令牌,了解它的工作方式,请参阅 https://jwt.io。
+如果你想动手体验 JWT 令牌并了解它的工作方式,请访问 [https://jwt.io](https://jwt.io/)。
-## 安装 `python-jose`
+## 安装 `PyJWT` { #install-pyjwt }
-安装 `python-jose`,在 Python 中生成和校验 JWT 令牌:
+我们需要安装 `PyJWT`,以便在 Python 中生成和校验 JWT 令牌。
+
+请确保创建并激活一个[虚拟环境](../../virtual-environments.md),然后安装 `pyjwt`:
-
+像之前一样进行授权。
-用与上一章同样的方式实现应用授权。
+使用以下凭证:
-使用如下凭证:
+用户名: `johndoe`
+密码: `secret`
-用户名: `johndoe` 密码: `secret`
+/// check | 检查
-!!! check "检查"
+注意,代码中的任何地方都没有明文密码 “`secret`”,我们只有它的哈希版本。
- 注意,代码中没有明文密码**`secret`**,只保存了它的哈希值。
+///
-
+
-调用 `/users/me/` 端点,收到下面的响应:
+调用 `/users/me/` 端点,你将得到如下响应:
```JSON
{
@@ -227,44 +232,46 @@ JWT 规范还包括 `sub` 键,值是令牌的主题。
}
```
-
+
+
+如果你打开开发者工具,你会看到发送的数据只包含令牌。密码只会在第一个请求中用于认证用户并获取访问令牌,之后就不会再发送密码了:
-打开浏览器的开发者工具,查看数据是怎么发送的,而且数据里只包含了令牌,只有验证用户的第一个请求才发送密码,并获取访问令牌,但之后不会再发送密码:
+
-
+/// note | 注意
-!!! note "笔记"
+注意 `Authorization` 请求头,其值以 `Bearer ` 开头。
- 注意,请求中 `Authorization` 响应头的值以 `Bearer` 开头。
+///
-## `scopes` 高级用法
+## 使用 `scopes` 的高级用法 { #advanced-usage-with-scopes }
-OAuth2 支持**`scopes`**(作用域)。
+OAuth2 支持 “scopes”(作用域)。
-**`scopes`**为 JWT 令牌添加指定权限。
+你可以用它们为 JWT 令牌添加一组特定的权限。
-让持有令牌的用户或第三方在指定限制条件下与 API 交互。
+然后你可以把这个令牌直接交给用户或第三方,在一组限制条件下与 API 交互。
-**高级用户指南**中将介绍如何使用 `scopes`,及如何把 `scopes` 集成至 **FastAPI**。
+在**高级用户指南**中你将学习如何使用它们,以及它们如何集成进 **FastAPI**。
-## 小结
+## 小结 { #recap }
-至此,您可以使用 OAuth2 和 JWT 等标准配置安全的 **FastAPI** 应用。
+通过目前所学内容,你可以使用 OAuth2 和 JWT 等标准来搭建一个安全的 **FastAPI** 应用。
-几乎在所有框架中,处理安全问题很快都会变得非常复杂。
+在几乎任何框架中,处理安全问题都会很快变得相当复杂。
-有些包为了简化安全流,不得不在数据模型、数据库和功能上做出妥协。而有些过于简化的软件包其实存在了安全隐患。
+许多把安全流程大幅简化的包,往往要在数据模型、数据库和可用特性上做出大量妥协。而有些过度简化的包实际上在底层存在安全隐患。
---
-**FastAPI** 不向任何数据库、数据模型或工具做妥协。
+**FastAPI** 不会在任何数据库、数据模型或工具上做妥协。
-开发者可以灵活选择最适合项目的安全机制。
+它给予你完全的灵活性,选择最适合你项目的方案。
-还可以直接使用 `passlib` 和 `python-jose` 等维护良好、使用广泛的包,这是因为 **FastAPI** 不需要任何复杂机制,就能集成外部的包。
+而且你可以直接使用许多维护良好、广泛使用的包,比如 `pwdlib` 和 `PyJWT`,因为 **FastAPI** 不需要复杂机制来集成外部包。
-而且,**FastAPI** 还提供了一些工具,在不影响灵活、稳定和安全的前提下,尽可能地简化安全机制。
+同时它也为你提供尽可能简化流程的工具,而不牺牲灵活性、健壮性或安全性。
-**FastAPI** 还支持以相对简单的方式,使用 OAuth2 等安全、标准的协议。
+你可以以相对简单的方式使用和实现像 OAuth2 这样的安全、标准协议。
-**高级用户指南**中详细介绍了 OAuth2**`scopes`**的内容,遵循同样的标准,实现更精密的权限系统。OAuth2 的作用域是脸书、谷歌、GitHub、微软、推特等第三方身份验证应用使用的机制,让用户授权第三方应用与 API 交互。
+在**高级用户指南**中,你可以进一步了解如何使用 OAuth2 的 “scopes”,以遵循相同标准实现更细粒度的权限系统。带作用域的 OAuth2 是许多大型身份认证提供商(如 Facebook、Google、GitHub、Microsoft、X(Twitter)等)用来授权第三方应用代表其用户与其 API 交互的机制。
diff --git a/docs/zh/docs/tutorial/security/simple-oauth2.md b/docs/zh/docs/tutorial/security/simple-oauth2.md
index c7f46177f0314..d8d5b561e034c 100644
--- a/docs/zh/docs/tutorial/security/simple-oauth2.md
+++ b/docs/zh/docs/tutorial/security/simple-oauth2.md
@@ -1,14 +1,14 @@
-# OAuth2 实现简单的 Password 和 Bearer 验证
+# OAuth2 实现简单的 Password 和 Bearer 验证 { #simple-oauth2-with-password-and-bearer }
本章添加上一章示例中欠缺的部分,实现完整的安全流。
-## 获取 `username` 和 `password`
+## 获取 `username` 和 `password` { #get-the-username-and-password }
首先,使用 **FastAPI** 安全工具获取 `username` 和 `password`。
-OAuth2 规范要求使用**密码流**时,客户端或用户必须以表单数据形式发送 `username` 和 `password` 字段。
+OAuth2 规范要求使用“密码流”时,客户端或用户必须以表单数据形式发送 `username` 和 `password` 字段。
-并且,这两个字段必须命名为 `username` 和 `password` ,不能使用 `user-name` 或 `email` 等其它名称。
+并且,这两个字段必须命名为 `username` 和 `password`,不能使用 `user-name` 或 `email` 等其它名称。
不过也不用担心,前端仍可以显示终端用户所需的名称。
@@ -18,7 +18,7 @@ OAuth2 规范要求使用**密码流**时,客户端或用户必须以表单数
该规范要求必须以表单数据形式发送 `username` 和 `password`,因此,不能使用 JSON 对象。
-### `Scope`(作用域)
+### `scope` { #scope }
OAuth2 还支持客户端发送**`scope`**表单字段。
@@ -32,27 +32,27 @@ OAuth2 还支持客户端发送**`scope`**表单字段。
* 脸书和 Instagram 使用 `instagram_basic`
* 谷歌使用 `https://www.googleapis.com/auth/drive`
-!!! info "说明"
+/// info | 信息
- OAuth2 中,**作用域**只是声明指定权限的字符串。
+OAuth2 中,**作用域**只是声明指定权限的字符串。
- 是否使用冒号 `:` 等符号,或是不是 URL 并不重要。
+是否使用冒号 `:` 等符号,或是不是 URL 并不重要。
- 这些细节只是特定的实现方式。
+这些细节只是特定的实现方式。
- 对 OAuth2 来说,都只是字符串而已。
+对 OAuth2 来说,都只是字符串而已。
-## 获取 `username` 和 `password` 的代码
+///
+
+## 获取 `username` 和 `password` 的代码 { #code-to-get-the-username-and-password }
接下来,使用 **FastAPI** 工具获取用户名与密码。
-### `OAuth2PasswordRequestForm`
+### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform }
首先,导入 `OAuth2PasswordRequestForm`,然后,在 `/token` *路径操作* 中,用 `Depends` 把该类作为依赖项。
-```Python hl_lines="4 76"
-{!../../../docs_src/security/tutorial003.py!}
-```
+{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *}
`OAuth2PasswordRequestForm` 是用以下几项内容声明表单请求体的类依赖项:
@@ -61,32 +61,38 @@ OAuth2 还支持客户端发送**`scope`**表单字段。
* 可选的 `scope` 字段,由多个空格分隔的字符串组成的长字符串
* 可选的 `grant_type`
-!!! tip "提示"
+/// tip | 提示
- 实际上,OAuth2 规范*要求* `grant_type` 字段使用固定值 `password`,但 `OAuth2PasswordRequestForm` 没有作强制约束。
+实际上,OAuth2 规范*要求* `grant_type` 字段使用固定值 `password`,但 `OAuth2PasswordRequestForm` 没有作强制约束。
- 如需强制使用固定值 `password`,则不要用 `OAuth2PasswordRequestForm`,而是用 `OAuth2PasswordRequestFormStrict`。
+如需强制使用固定值 `password`,则不要用 `OAuth2PasswordRequestForm`,而是用 `OAuth2PasswordRequestFormStrict`。
+
+///
* 可选的 `client_id`(本例未使用)
* 可选的 `client_secret`(本例未使用)
-!!! info "说明"
+/// info | 信息
+
+`OAuth2PasswordRequestForm` 并不像 `OAuth2PasswordBearer` 那样是 **FastAPI** 的特殊类。
- `OAuth2PasswordRequestForm` 与 `OAuth2PasswordBearer` 一样,都不是 FastAPI 的特殊类。
+**FastAPI** 把 `OAuth2PasswordBearer` 识别为安全方案。因此,可以通过这种方式把它添加至 OpenAPI。
- **FastAPI** 把 `OAuth2PasswordBearer` 识别为安全方案。因此,可以通过这种方式把它添加至 OpenAPI。
+但 `OAuth2PasswordRequestForm` 只是可以自行编写的类依赖项,也可以直接声明 `Form` 参数。
- 但 `OAuth2PasswordRequestForm` 只是可以自行编写的类依赖项,也可以直接声明 `Form` 参数。
+但由于这种用例很常见,FastAPI 为了简便,就直接提供了对它的支持。
- 但由于这种用例很常见,FastAPI 为了简便,就直接提供了对它的支持。
+///
-### 使用表单数据
+### 使用表单数据 { #use-the-form-data }
-!!! tip "提示"
+/// tip | 提示
- `OAuth2PasswordRequestForm` 类依赖项的实例没有以空格分隔的长字符串属性 `scope`,但它支持 `scopes` 属性,由已发送的 scope 字符串列表组成。
+`OAuth2PasswordRequestForm` 类依赖项的实例没有以空格分隔的长字符串属性 `scope`,但它支持 `scopes` 属性,由已发送的 scope 字符串列表组成。
- 本例没有使用 `scopes`,但开发者也可以根据需要使用该属性。
+本例没有使用 `scopes`,但开发者也可以根据需要使用该属性。
+
+///
现在,即可使用表单字段 `username`,从(伪)数据库中获取用户数据。
@@ -94,11 +100,9 @@ OAuth2 还支持客户端发送**`scope`**表单字段。
本例使用 `HTTPException` 异常显示此错误:
-```Python hl_lines="3 77-79"
-{!../../../docs_src/security/tutorial003.py!}
-```
+{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *}
-### 校验密码
+### 校验密码 { #check-the-password }
至此,我们已经从数据库中获取了用户数据,但尚未校验密码。
@@ -108,7 +112,7 @@ OAuth2 还支持客户端发送**`scope`**表单字段。
如果密码不匹配,则返回与上面相同的错误。
-#### 密码哈希
+#### 密码哈希 { #password-hashing }
**哈希**是指,将指定内容(本例中为密码)转换为形似乱码的字节序列(其实就是字符串)。
@@ -116,17 +120,15 @@ OAuth2 还支持客户端发送**`scope`**表单字段。
但这个乱码无法转换回传入的密码。
-##### 为什么使用密码哈希
+##### 为什么使用密码哈希 { #why-use-password-hashing }
原因很简单,假如数据库被盗,窃贼无法获取用户的明文密码,得到的只是哈希值。
这样一来,窃贼就无法在其它应用中使用窃取的密码,要知道,很多用户在所有系统中都使用相同的密码,风险超大。
-```Python hl_lines="80-83"
-{!../../../docs_src/security/tutorial003.py!}
-```
+{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *}
-#### 关于 `**user_dict`
+#### 关于 `**user_dict` { #about-user-dict }
`UserInDB(**user_dict)` 是指:
@@ -142,11 +144,13 @@ UserInDB(
)
```
-!!! info "说明"
+/// info | 信息
- `user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#about-user_indict){.internal-link target=_blank}。
+`user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#about-user-in-dict)。
-## 返回 Token
+///
+
+## 返回 Token { #return-the-token }
`token` 端点的响应必须是 JSON 对象。
@@ -156,27 +160,29 @@ UserInDB(
本例只是简单的演示,返回的 Token 就是 `username`,但这种方式极不安全。
-!!! tip "提示"
+/// tip | 提示
- 下一章介绍使用哈希密码和 JWT Token 的真正安全机制。
+下一章介绍使用哈希密码和 JWT Token 的真正安全机制。
- 但现在,仅关注所需的特定细节。
+但现在,仅关注所需的特定细节。
-```Python hl_lines="85"
-{!../../../docs_src/security/tutorial003.py!}
-```
+///
+
+{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *}
-!!! tip "提示"
+/// tip | 提示
- 按规范的要求,应像本示例一样,返回带有 `access_token` 和 `token_type` 的 JSON 对象。
+按规范的要求,应像本示例一样,返回带有 `access_token` 和 `token_type` 的 JSON 对象。
- 这是开发者必须在代码中自行完成的工作,并且要确保使用这些 JSON 的键。
+这是开发者必须在代码中自行完成的工作,并且要确保使用这些 JSON 的键。
- 这几乎是唯一需要开发者牢记在心,并按规范要求正确执行的事。
+这几乎是唯一需要开发者牢记在心,并按规范要求正确执行的事。
- **FastAPI** 则负责处理其它的工作。
+**FastAPI** 则负责处理其它的工作。
-## 更新依赖项
+///
+
+## 更新依赖项 { #update-the-dependencies }
接下来,更新依赖项。
@@ -188,33 +194,33 @@ UserInDB(
因此,在端点中,只有当用户存在、通过身份验证、且状态为激活时,才能获得该用户:
-```Python hl_lines="58-67 69-72 90"
-{!../../../docs_src/security/tutorial003.py!}
-```
+{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *}
+
+/// info | 信息
-!!! info "说明"
+此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。
- 此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。
+任何 401“UNAUTHORIZED”HTTP(错误)状态码都应返回 `WWW-Authenticate` 响应头。
- 任何 401**UNAUTHORIZED**HTTP(错误)状态码都应返回 `WWW-Authenticate` 响应头。
+本例中,因为使用的是 Bearer Token,该响应头的值应为 `Bearer`。
- 本例中,因为使用的是 Bearer Token,该响应头的值应为 `Bearer`。
+实际上,忽略这个附加响应头,也不会有什么问题。
- 实际上,忽略这个附加响应头,也不会有什么问题。
+之所以在此提供这个附加响应头,是为了符合规范的要求。
- 之所以在此提供这个附加响应头,是为了符合规范的要求。
+说不定什么时候,就有工具用得上它,而且,开发者或用户也可能用得上。
- 说不定什么时候,就有工具用得上它,而且,开发者或用户也可能用得上。
+这就是遵循标准的好处...
- 这就是遵循标准的好处……
+///
-## 实际效果
+## 实际效果 { #see-it-in-action }
-打开 API 文档:http://127.0.0.1:8000/docs。
+打开交互式文档:[http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)。
-### 身份验证
+### 身份验证 { #authenticate }
-点击**Authorize**按钮。
+点击“Authorize”按钮。
使用以下凭证:
@@ -222,13 +228,13 @@ UserInDB(
密码:`secret`
-
+
通过身份验证后,显示下图所示的内容:
-
+
-### 获取当前用户数据
+### 获取当前用户数据 { #get-your-own-user-data }
使用 `/users/me` 路径的 `GET` 操作。
@@ -244,7 +250,7 @@ UserInDB(
}
```
-
+
点击小锁图标,注销后,再执行同样的操作,则会得到 HTTP 401 错误:
@@ -254,7 +260,7 @@ UserInDB(
}
```
-### 未激活用户
+### 未激活用户 { #inactive-user }
测试未激活用户,输入以下信息,进行身份验证:
@@ -272,7 +278,7 @@ UserInDB(
}
```
-## 小结
+## 小结 { #recap }
使用本章的工具实现基于 `username` 和 `password` 的完整 API 安全系统。
@@ -280,4 +286,4 @@ UserInDB(
唯一欠缺的是,它仍然不是真的**安全**。
-下一章,介绍使用密码哈希支持库与 JWT 令牌实现真正的安全机制。
+下一章你将看到如何使用安全的密码哈希库和 JWT 令牌。
diff --git a/docs/zh/docs/tutorial/server-sent-events.md b/docs/zh/docs/tutorial/server-sent-events.md
new file mode 100644
index 0000000000000..c78562b91efef
--- /dev/null
+++ b/docs/zh/docs/tutorial/server-sent-events.md
@@ -0,0 +1,120 @@
+# 服务器发送事件(SSE) { #server-sent-events-sse }
+
+你可以使用**服务器发送事件**(SSE)向客户端流式发送数据。
+
+这类似于[流式传输 JSON Lines](stream-json-lines.md),但使用 `text/event-stream` 格式,浏览器原生通过 [`EventSource` API](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) 支持。
+
+/// info | 信息
+
+新增于 FastAPI 0.135.0。
+
+///
+
+## 什么是服务器发送事件? { #what-are-server-sent-events }
+
+SSE 是一种通过 HTTP 从服务器向客户端流式传输数据的标准。
+
+每个事件是一个带有 `data`、`event`、`id` 和 `retry` 等“字段”的小文本块,以空行分隔。
+
+看起来像这样:
+
+```
+data: {"name": "Portal Gun", "price": 999.99}
+
+data: {"name": "Plumbus", "price": 32.99}
+
+```
+
+SSE 常用于 AI 聊天流式输出、实时通知、日志与可观测性,以及其他服务器向客户端推送更新的场景。
+
+/// tip | 提示
+
+如果你想流式传输二进制数据(例如视频或音频),请查看高级指南:[流式传输数据](../advanced/stream-data.md)。
+
+///
+
+## 使用 FastAPI 流式传输 SSE { #stream-sse-with-fastapi }
+
+要在 FastAPI 中流式传输 SSE,在你的*路径操作函数*中使用 `yield`,并设置 `response_class=EventSourceResponse`。
+
+从 `fastapi.sse` 导入 `EventSourceResponse`:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[4,22] *}
+
+每个被 yield 的项会被编码为 JSON,并放入 SSE 事件的 `data:` 字段发送。
+
+如果你将返回类型声明为 `AsyncIterable[Item]`,FastAPI 将使用它通过 Pydantic对数据进行**校验**、**文档化**和**序列化**。
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[10:12,23] *}
+
+/// tip | 提示
+
+由于 Pydantic 会在**Rust** 端序列化它,相比未声明返回类型,你将获得更高的**性能**。
+
+///
+
+### 非 async 的*路径操作函数* { #non-async-path-operation-functions }
+
+你也可以使用常规的 `def` 函数(没有 `async`),并以同样的方式使用 `yield`。
+
+FastAPI 会确保其正确运行,从而不阻塞事件循环。
+
+由于此时函数不是 async,正确的返回类型应为 `Iterable[Item]`:
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[28:31] hl[29] *}
+
+### 无返回类型 { #no-return-type }
+
+你也可以省略返回类型。FastAPI 将使用 [`jsonable_encoder`](./encoder.md) 转换数据并发送。
+
+{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[34:37] hl[35] *}
+
+## `ServerSentEvent` { #serversentevent }
+
+如果你需要设置 `event`、`id`、`retry` 或 `comment` 等 SSE 字段,你可以 yield `ServerSentEvent` 对象,而不是直接返回数据。
+
+从 `fastapi.sse` 导入 `ServerSentEvent`:
+
+{* ../../docs_src/server_sent_events/tutorial002_py310.py hl[4,26] *}
+
+`data` 字段始终会被编码为 JSON。你可以传入任何可被序列化为 JSON 的值,包括 Pydantic 模型。
+
+## 原始数据 { #raw-data }
+
+如果你需要发送**不**进行 JSON 编码的数据,请使用 `raw_data` 而不是 `data`。
+
+这对于发送预格式化文本、日志行或特殊的 "哨兵" 值(例如 `[DONE]`)很有用。
+
+{* ../../docs_src/server_sent_events/tutorial003_py310.py hl[17] *}
+
+/// note | 注意
+
+`data` 和 `raw_data` 是互斥的。每个 `ServerSentEvent` 上只能设置其中一个。
+
+///
+
+## 使用 `Last-Event-ID` 恢复 { #resuming-with-last-event-id }
+
+当连接中断后浏览器重新连接时,会在 `Last-Event-ID` 头中发送上次收到的 `id`。
+
+你可以将其读取为一个请求头参数,并据此从客户端离开的地方恢复流:
+
+{* ../../docs_src/server_sent_events/tutorial004_py310.py hl[25,27,31] *}
+
+## 使用 POST 的 SSE { #sse-with-post }
+
+SSE 适用于**任意 HTTP 方法**,不仅仅是 `GET`。
+
+这对像 [MCP](https://modelcontextprotocol.io) 这样通过 `POST` 传输 SSE 的协议很有用:
+
+{* ../../docs_src/server_sent_events/tutorial005_py310.py hl[14] *}
+
+## 技术细节 { #technical-details }
+
+FastAPI 开箱即用地实现了一些 SSE 的最佳实践。
+
+- 当 15 秒内没有任何消息时,发送一个**保活 `ping` 注释**,以防某些代理关闭连接,正如 [HTML 规范:Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes) 中建议的那样。
+- 设置 `Cache-Control: no-cache` 响应头,**防止缓存**流。
+- 设置特殊响应头 `X-Accel-Buffering: no`,以**防止**某些代理(如 Nginx)**缓冲**。
+
+你无需做任何事,它开箱即用。🤓
diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md
index 482588f94d7ec..9004983b10b02 100644
--- a/docs/zh/docs/tutorial/sql-databases.md
+++ b/docs/zh/docs/tutorial/sql-databases.md
@@ -1,770 +1,357 @@
-# SQL (关系型) 数据库
+# SQL(关系型)数据库 { #sql-relational-databases }
-**FastAPI**不需要你使用SQL(关系型)数据库。
+**FastAPI** 并不要求你使用 SQL(关系型)数据库。你可以使用你想用的**任何数据库**。
-但是您可以使用任何您想要的关系型数据库。
+这里,我们来看一个使用 [SQLModel](https://sqlmodel.tiangolo.com/) 的示例。
-在这里,让我们看一个使用着[SQLAlchemy](https://www.sqlalchemy.org/)的示例。
+**SQLModel** 基于 [SQLAlchemy](https://www.sqlalchemy.org/) 和 Pydantic 构建。它由 **FastAPI** 的同一作者制作,旨在完美匹配需要使用**SQL 数据库**的 FastAPI 应用程序。
-您可以很容易地将SQLAlchemy支持任何数据库,像:
+/// tip | 提示
+
+你可以使用任意其他你想要的 SQL 或 NoSQL 数据库库(在某些情况下称为 "ORMs"),FastAPI 不会强迫你使用任何东西。😎
+
+///
+
+由于 SQLModel 基于 SQLAlchemy,因此你可以轻松使用任何由 SQLAlchemy **支持的数据库**(这也让它们被 SQLModel 支持),例如:
* PostgreSQL
* MySQL
* SQLite
* Oracle
-* Microsoft SQL Server,等等其它数据库
-
-在此示例中,我们将使用**SQLite**,因为它使用单个文件并且 在Python中具有集成支持。因此,您可以复制此示例并按原样来运行它。
-
-稍后,对于您的产品级别的应用程序,您可能会要使用像**PostgreSQL**这样的数据库服务器。
-
-!!! tip
- 这儿有一个**FastAPI**和**PostgreSQL**的官方项目生成器,全部基于**Docker**,包括前端和更多工具:https://github.com/tiangolo/full-stack-fastapi-postgresql
-
-!!! note
- 请注意,大部分代码是`SQLAlchemy`的标准代码,您可以用于任何框架。FastAPI特定的代码和往常一样少。
-
-## ORMs(对象关系映射)
-
-**FastAPI**可与任何数据库在任何样式的库中一起与 数据库进行通信。
-
-一种常见的模式是使用“ORM”:对象关系映射。
-
-ORM 具有在代码和数据库表(“*关系型”)中的**对象**之间转换(“*映射*”)的工具。
-
-使用 ORM,您通常会在 SQL 数据库中创建一个代表映射的类,该类的每个属性代表一个列,具有名称和类型。
-
-例如,一个类`Pet`可以表示一个 SQL 表`pets`。
-
-该类的每个*实例对象都代表数据库中的一行数据。*
-
-又例如,一个对象`orion_cat`(`Pet`的一个实例)可以有一个属性`orion_cat.type`, 对标数据库中的`type`列。并且该属性的值可以是其它,例如`"cat"`。
-
-这些 ORM 还具有在表或实体之间建立关系的工具(比如创建多表关系)。
-
-这样,您还可以拥有一个属性`orion_cat.owner`,它包含该宠物所有者的数据,这些数据取自另外一个表。
-
-因此,`orion_cat.owner.name`可能是该宠物主人的姓名(来自表`owners`中的列`name`)。
-
-它可能有一个像`"Arquilian"`(一种业务逻辑)。
-
-当您尝试从您的宠物对象访问它时,ORM 将完成所有工作以从相应的表*所有者那里再获取信息。*
-
-常见的 ORM 例如:Django-ORM(Django 框架的一部分)、SQLAlchemy ORM(SQLAlchemy 的一部分,独立于框架)和 Peewee(独立于框架)等。
-
-在这里,我们将看到如何使用**SQLAlchemy ORM**。
-
-以类似的方式,您也可以使用任何其他 ORM。
-
-!!! tip
- 在文档中也有一篇使用 Peewee 的等效的文章。
-
-## 文件结构
-
-对于这些示例,假设您有一个名为的目录`my_super_project`,其中包含一个名为的子目录`sql_app`,其结构如下:
-
-```
-.
-└── sql_app
- ├── __init__.py
- ├── crud.py
- ├── database.py
- ├── main.py
- ├── models.py
- └── schemas.py
-```
-
-该文件`__init__.py`只是一个空文件,但它告诉 Python 其中`sql_app`的所有模块(Python 文件)都是一个包。
-
-现在让我们看看每个文件/模块的作用。
-
-## 创建 SQLAlchemy 部件
-
-让我们涉及到文件`sql_app/database.py`。
-
-### 导入 SQLAlchemy 部件
-
-```Python hl_lines="1-3"
-{!../../../docs_src/sql_databases/sql_app/database.py!}
-```
-
-### 为 SQLAlchemy 定义数据库 URL地址
-
-```Python hl_lines="5-6"
-{!../../../docs_src/sql_databases/sql_app/database.py!}
-```
-
-在这个例子中,我们正在“连接”到一个 SQLite 数据库(用 SQLite 数据库打开一个文件)。
-
-该文件将位于文件中的同一目录中`sql_app.db`。
-
-这就是为什么最后一部分是`./sql_app.db`.
-
-如果您使用的是**PostgreSQL**数据库,则只需取消注释该行:
-
-```Python
-SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"
-```
-
-...并根据您的数据库数据和相关凭据(也适用于 MySQL、MariaDB 或任何其他)对其进行调整。
-
-!!! tip
-
- 如果您想使用不同的数据库,这是就是您必须修改的地方。
-
-### 创建 SQLAlchemy 引擎
-
-第一步,创建一个 SQLAlchemy的“引擎”。
-
-我们稍后会将这个`engine`在其他地方使用。
-
-```Python hl_lines="8-10"
-{!../../../docs_src/sql_databases/sql_app/database.py!}
-```
-
-#### 注意
-
-参数:
-
-```Python
-connect_args={"check_same_thread": False}
-```
-
-...仅用于`SQLite`,在其他数据库不需要它。
-
-!!! info "技术细节"
-
- 默认情况下,SQLite 只允许一个线程与其通信,假设有多个线程的话,也只将处理一个独立的请求。
-
- 这是为了防止意外地为不同的事物(不同的请求)共享相同的连接。
-
- 但是在 FastAPI 中,普遍使用def函数,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。
-
- 此外,我们将确保每个请求都在依赖项中获得自己的数据库连接会话,因此不需要该默认机制。
-
-### 创建一个`SessionLocal`类
-
-每个实例`SessionLocal`都会是一个数据库会话。当然该类本身还不是数据库会话。
-
-但是一旦我们创建了一个`SessionLocal`类的实例,这个实例将是实际的数据库会话。
-
-我们命名它是`SessionLocal`为了将它与我们从 SQLAlchemy 导入的`Session`区别开来。
-
-稍后我们将使用`Session`(从 SQLAlchemy 导入的那个)。
-
-要创建`SessionLocal`类,请使用函数`sessionmaker`:
-
-```Python hl_lines="11"
-{!../../../docs_src/sql_databases/sql_app/database.py!}
-```
-
-### 创建一个`Base`类
-
-现在我们将使用`declarative_base()`返回一个类。
-
-稍后我们将用这个类继承,来创建每个数据库模型或类(ORM 模型):
-
-```Python hl_lines="13"
-{!../../../docs_src/sql_databases/sql_app/database.py!}
-```
-
-## 创建数据库模型
-
-现在让我们看看文件`sql_app/models.py`。
-
-### 用`Base`类来创建 SQLAlchemy 模型
-
-我们将使用我们之前创建的`Base`类来创建 SQLAlchemy 模型。
-
-!!! tip
- SQLAlchemy 使用的“**模型**”这个术语 来指代与数据库交互的这些类和实例。
-
- 而 Pydantic 也使用“模型”这个术语 来指代不同的东西,即数据验证、转换以及文档类和实例。
-
-从`database`(来自上面的`database.py`文件)导入`Base`。
-
-创建从它继承的类。
-
-这些类就是 SQLAlchemy 模型。
-
-```Python hl_lines="4 7-8 18-19"
-{!../../../docs_src/sql_databases/sql_app/models.py!}
-```
-
-这个`__tablename__`属性是用来告诉 SQLAlchemy 要在数据库中为每个模型使用的数据库表的名称。
-
-### 创建模型属性/列
-
-现在创建所有模型(类)属性。
-
-这些属性中的每一个都代表其相应数据库表中的一列。
-
-我们使用`Column`来表示 SQLAlchemy 中的默认值。
-
-我们传递一个 SQLAlchemy “类型”,如`Integer`、`String`和`Boolean`,它定义了数据库中的类型,作为参数。
-
-```Python hl_lines="1 10-13 21-24"
-{!../../../docs_src/sql_databases/sql_app/models.py!}
-```
-
-### 创建关系
-
-现在创建关系。
-
-为此,我们使用SQLAlchemy ORM提供的`relationship`。
-
-这将或多或少会成为一种“神奇”属性,其中表示该表与其他相关的表中的值。
-
-```Python hl_lines="2 15 26"
-{!../../../docs_src/sql_databases/sql_app/models.py!}
-```
-
-当访问 user 中的属性`items`时,如 中`my_user.items`,它将有一个`Item`SQLAlchemy 模型列表(来自`items`表),这些模型具有指向`users`表中此记录的外键。
-
-当您访问`my_user.items`时,SQLAlchemy 实际上会从`items`表中的获取一批记录并在此处填充进去。
-
-同样,当访问 Item中的属性`owner`时,它将包含表中的`User`SQLAlchemy 模型`users`。使用`owner_id`属性/列及其外键来了解要从`users`表中获取哪条记录。
-
-## 创建 Pydantic 模型
-
-现在让我们查看一下文件`sql_app/schemas.py`。
+* Microsoft SQL Server 等
-!!! tip
- 为了避免 SQLAlchemy*模型*和 Pydantic*模型*之间的混淆,我们将有`models.py`(SQLAlchemy 模型的文件)和`schemas.py`( Pydantic 模型的文件)。
+在这个示例中,我们将使用 **SQLite**,因为它使用单个文件,并且 Python 对其有集成支持。因此,你可以直接复制这个示例并运行。
- 这些 Pydantic 模型或多或少地定义了一个“schema”(一个有效的数据形状)。
+之后,对于你的生产应用程序,你可能会想要使用像 **PostgreSQL** 这样的数据库服务器。
- 因此,这将帮助我们在使用两者时避免混淆。
+/// tip | 提示
-### 创建初始 Pydantic*模型*/模式
+有一个使用 **FastAPI** 和 **PostgreSQL** 的官方项目生成器,其中包括了前端和更多工具: [https://github.com/fastapi/full-stack-fastapi-template](https://github.com/fastapi/full-stack-fastapi-template)
-创建一个`ItemBase`和`UserBase`Pydantic*模型*(或者我们说“schema”)以及在创建或读取数据时具有共同的属性。
+///
-`ItemCreate`为 创建一个`UserCreate`继承自它们的所有属性(因此它们将具有相同的属性),以及创建所需的任何其他数据(属性)。
+这是一个非常简单和简短的教程。如果你想了解一般的数据库、SQL 或更高级的功能,请查看 [SQLModel 文档](https://sqlmodel.tiangolo.com/)。
-因此在创建时也应当有一个`password`属性。
+## 安装 `SQLModel` { #install-sqlmodel }
-但是为了安全起见,`password`不会出现在其他同类 Pydantic*模型*中,例如用户请求时不应该从 API 返回响应中包含它。
+首先,确保你创建并激活了[虚拟环境](../virtual-environments.md),然后安装 `sqlmodel`:
-=== "Python 3.10+"
-
- ```Python hl_lines="1 4-6 9-10 21-22 25-26"
- {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!}
- ```
-
-=== "Python 3.9+"
-
- ```Python hl_lines="3 6-8 11-12 23-24 27-28"
- {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!}
- ```
-
-=== "Python 3.6+"
-
- ```Python hl_lines="3 6-8 11-12 23-24 27-28"
- {!> ../../../docs_src/sql_databases/sql_app/schemas.py!}
- ```
-
-#### SQLAlchemy 风格和 Pydantic 风格
-
-请注意,SQLAlchemy*模型*使用 `=`来定义属性,并将类型作为参数传递给`Column`,例如:
-
-```Python
-name = Column(String)
-```
-
-虽然 Pydantic*模型*使用`:` 声明类型,但新的类型注释语法/类型提示是:
+
+
-
-## 直接与数据库交互
-
-如果您想独立于 FastAPI 直接浏览 SQLite 数据库(文件)以调试其内容、添加表、列、记录、修改数据等,您可以使用[SQLite 的 DB Browser](https://sqlitebrowser.org/)
-
-它看起来像这样:
+如果你进入 `/docs` API UI,你会看到它现在已经更新,并且在创建 hero 时,它不会再期望从客户端接收 `id` 数据等。
+
+This is a list of items.
" diff --git a/docs_src/dataclasses/tutorial001.py b/docs_src/dataclasses/tutorial001.py deleted file mode 100644 index 2954c391f1ce2..0000000000000 --- a/docs_src/dataclasses/tutorial001.py +++ /dev/null @@ -1,20 +0,0 @@ -from dataclasses import dataclass -from typing import Union - -from fastapi import FastAPI - - -@dataclass -class Item: - name: str - price: float - description: Union[str, None] = None - tax: Union[float, None] = None - - -app = FastAPI() - - -@app.post("/items/") -async def create_item(item: Item): - return item diff --git a/docs_src/dataclasses/tutorial002.py b/docs_src/dataclasses/tutorial002.py deleted file mode 100644 index 08a2380804656..0000000000000 --- a/docs_src/dataclasses/tutorial002.py +++ /dev/null @@ -1,26 +0,0 @@ -from dataclasses import dataclass, field -from typing import List, Union - -from fastapi import FastAPI - - -@dataclass -class Item: - name: str - price: float - tags: List[str] = field(default_factory=list) - description: Union[str, None] = None - tax: Union[float, None] = None - - -app = FastAPI() - - -@app.get("/items/next", response_model=Item) -async def read_next_item(): - return { - "name": "Island In The Moon", - "price": 12.99, - "description": "A place to be be playin' and havin' fun", - "tags": ["breater"], - } diff --git a/docs_src/dataclasses/tutorial003.py b/docs_src/dataclasses/tutorial003.py deleted file mode 100644 index 34ce1199e52b7..0000000000000 --- a/docs_src/dataclasses/tutorial003.py +++ /dev/null @@ -1,55 +0,0 @@ -from dataclasses import field # (1) -from typing import List, Union - -from fastapi import FastAPI -from pydantic.dataclasses import dataclass # (2) - - -@dataclass -class Item: - name: str - description: Union[str, None] = None - - -@dataclass -class Author: - name: str - items: List[Item] = field(default_factory=list) # (3) - - -app = FastAPI() - - -@app.post("/authors/{author_id}/items/", response_model=Author) # (4) -async def create_author_items(author_id: str, items: List[Item]): # (5) - return {"name": author_id, "items": items} # (6) - - -@app.get("/authors/", response_model=List[Author]) # (7) -def get_authors(): # (8) - return [ # (9) - { - "name": "Breaters", - "items": [ - { - "name": "Island In The Moon", - "description": "A place to be be playin' and havin' fun", - }, - {"name": "Holy Buddies"}, - ], - }, - { - "name": "System of an Up", - "items": [ - { - "name": "Salt", - "description": "The kombucha mushroom people's favorite", - }, - {"name": "Pad Thai"}, - { - "name": "Lonely Night", - "description": "The mostests lonliest nightiest of allest", - }, - ], - }, - ] diff --git a/docs_src/sql_databases/sql_app_py39/tests/__init__.py b/docs_src/dataclasses_/__init__.py similarity index 100% rename from docs_src/sql_databases/sql_app_py39/tests/__init__.py rename to docs_src/dataclasses_/__init__.py diff --git a/docs_src/dataclasses_/tutorial001_py310.py b/docs_src/dataclasses_/tutorial001_py310.py new file mode 100644 index 0000000000000..ab709a7c85091 --- /dev/null +++ b/docs_src/dataclasses_/tutorial001_py310.py @@ -0,0 +1,19 @@ +from dataclasses import dataclass + +from fastapi import FastAPI + + +@dataclass +class Item: + name: str + price: float + description: str | None = None + tax: float | None = None + + +app = FastAPI() + + +@app.post("/items/") +async def create_item(item: Item): + return item diff --git a/docs_src/dataclasses_/tutorial002_py310.py b/docs_src/dataclasses_/tutorial002_py310.py new file mode 100644 index 0000000000000..e16249f1e1f58 --- /dev/null +++ b/docs_src/dataclasses_/tutorial002_py310.py @@ -0,0 +1,25 @@ +from dataclasses import dataclass, field + +from fastapi import FastAPI + + +@dataclass +class Item: + name: str + price: float + tags: list[str] = field(default_factory=list) + description: str | None = None + tax: float | None = None + + +app = FastAPI() + + +@app.get("/items/next", response_model=Item) +async def read_next_item(): + return { + "name": "Island In The Moon", + "price": 12.99, + "description": "A place to be playin' and havin' fun", + "tags": ["breater"], + } diff --git a/docs_src/dataclasses_/tutorial003_py310.py b/docs_src/dataclasses_/tutorial003_py310.py new file mode 100644 index 0000000000000..9b9a3fd635869 --- /dev/null +++ b/docs_src/dataclasses_/tutorial003_py310.py @@ -0,0 +1,54 @@ +from dataclasses import field # (1) + +from fastapi import FastAPI +from pydantic.dataclasses import dataclass # (2) + + +@dataclass +class Item: + name: str + description: str | None = None + + +@dataclass +class Author: + name: str + items: list[Item] = field(default_factory=list) # (3) + + +app = FastAPI() + + +@app.post("/authors/{author_id}/items/", response_model=Author) # (4) +async def create_author_items(author_id: str, items: list[Item]): # (5) + return {"name": author_id, "items": items} # (6) + + +@app.get("/authors/", response_model=list[Author]) # (7) +def get_authors(): # (8) + return [ # (9) + { + "name": "Breaters", + "items": [ + { + "name": "Island In The Moon", + "description": "A place to be playin' and havin' fun", + }, + {"name": "Holy Buddies"}, + ], + }, + { + "name": "System of an Up", + "items": [ + { + "name": "Salt", + "description": "The kombucha mushroom people's favorite", + }, + {"name": "Pad Thai"}, + { + "name": "Lonely Night", + "description": "The mostests lonliest nightiest of allest", + }, + ], + }, + ] diff --git a/docs_src/sql_databases_peewee/sql_app/__init__.py b/docs_src/debugging/__init__.py similarity index 100% rename from docs_src/sql_databases_peewee/sql_app/__init__.py rename to docs_src/debugging/__init__.py diff --git a/docs_src/debugging/tutorial001.py b/docs_src/debugging/tutorial001_py310.py similarity index 100% rename from docs_src/debugging/tutorial001.py rename to docs_src/debugging/tutorial001_py310.py diff --git a/docs_src/websockets/__init__.py b/docs_src/dependencies/__init__.py similarity index 100% rename from docs_src/websockets/__init__.py rename to docs_src/dependencies/__init__.py diff --git a/docs_src/dependencies/tutorial001.py b/docs_src/dependencies/tutorial001.py deleted file mode 100644 index b1275103a0075..0000000000000 --- a/docs_src/dependencies/tutorial001.py +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Union - -from fastapi import Depends, FastAPI - -app = FastAPI() - - -async def common_parameters( - q: Union[str, None] = None, skip: int = 0, limit: int = 100 -): - return {"q": q, "skip": skip, "limit": limit} - - -@app.get("/items/") -async def read_items(commons: dict = Depends(common_parameters)): - return commons - - -@app.get("/users/") -async def read_users(commons: dict = Depends(common_parameters)): - return commons diff --git a/docs_src/dependencies/tutorial001_02_an.py b/docs_src/dependencies/tutorial001_02_an.py deleted file mode 100644 index 455d60c822bfb..0000000000000 --- a/docs_src/dependencies/tutorial001_02_an.py +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Union - -from fastapi import Depends, FastAPI -from typing_extensions import Annotated - -app = FastAPI() - - -async def common_parameters( - q: Union[str, None] = None, skip: int = 0, limit: int = 100 -): - return {"q": q, "skip": skip, "limit": limit} - - -CommonsDep = Annotated[dict, Depends(common_parameters)] - - -@app.get("/items/") -async def read_items(commons: CommonsDep): - return commons - - -@app.get("/users/") -async def read_users(commons: CommonsDep): - return commons diff --git a/docs_src/dependencies/tutorial001_02_an_py39.py b/docs_src/dependencies/tutorial001_02_an_py39.py deleted file mode 100644 index df969ae9c83c9..0000000000000 --- a/docs_src/dependencies/tutorial001_02_an_py39.py +++ /dev/null @@ -1,24 +0,0 @@ -from typing import Annotated, Union - -from fastapi import Depends, FastAPI - -app = FastAPI() - - -async def common_parameters( - q: Union[str, None] = None, skip: int = 0, limit: int = 100 -): - return {"q": q, "skip": skip, "limit": limit} - - -CommonsDep = Annotated[dict, Depends(common_parameters)] - - -@app.get("/items/") -async def read_items(commons: CommonsDep): - return commons - - -@app.get("/users/") -async def read_users(commons: CommonsDep): - return commons diff --git a/docs_src/dependencies/tutorial001_an.py b/docs_src/dependencies/tutorial001_an.py deleted file mode 100644 index 81e24fe86c227..0000000000000 --- a/docs_src/dependencies/tutorial001_an.py +++ /dev/null @@ -1,22 +0,0 @@ -from typing import Union - -from fastapi import Depends, FastAPI -from typing_extensions import Annotated - -app = FastAPI() - - -async def common_parameters( - q: Union[str, None] = None, skip: int = 0, limit: int = 100 -): - return {"q": q, "skip": skip, "limit": limit} - - -@app.get("/items/") -async def read_items(commons: Annotated[dict, Depends(common_parameters)]): - return commons - - -@app.get("/users/") -async def read_users(commons: Annotated[dict, Depends(common_parameters)]): - return commons diff --git a/docs_src/dependencies/tutorial001_an_py39.py b/docs_src/dependencies/tutorial001_an_py39.py deleted file mode 100644 index 5d9fe6ddfd035..0000000000000 --- a/docs_src/dependencies/tutorial001_an_py39.py +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Annotated, Union - -from fastapi import Depends, FastAPI - -app = FastAPI() - - -async def common_parameters( - q: Union[str, None] = None, skip: int = 0, limit: int = 100 -): - return {"q": q, "skip": skip, "limit": limit} - - -@app.get("/items/") -async def read_items(commons: Annotated[dict, Depends(common_parameters)]): - return commons - - -@app.get("/users/") -async def read_users(commons: Annotated[dict, Depends(common_parameters)]): - return commons diff --git a/docs_src/dependencies/tutorial002.py b/docs_src/dependencies/tutorial002.py deleted file mode 100644 index 8e863e4fabed7..0000000000000 --- a/docs_src/dependencies/tutorial002.py +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Union - -from fastapi import Depends, FastAPI - -app = FastAPI() - - -fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}] - - -class CommonQueryParams: - def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100): - self.q = q - self.skip = skip - self.limit = limit - - -@app.get("/items/") -async def read_items(commons: CommonQueryParams = Depends(CommonQueryParams)): - response = {} - if commons.q: - response.update({"q": commons.q}) - items = fake_items_db[commons.skip : commons.skip + commons.limit] - response.update({"items": items}) - return response diff --git a/docs_src/dependencies/tutorial002_an.py b/docs_src/dependencies/tutorial002_an.py deleted file mode 100644 index 964ccf66ca9a9..0000000000000 --- a/docs_src/dependencies/tutorial002_an.py +++ /dev/null @@ -1,26 +0,0 @@ -from typing import Union - -from fastapi import Depends, FastAPI -from typing_extensions import Annotated - -app = FastAPI() - - -fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}] - - -class CommonQueryParams: - def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100): - self.q = q - self.skip = skip - self.limit = limit - - -@app.get("/items/") -async def read_items(commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]): - response = {} - if commons.q: - response.update({"q": commons.q}) - items = fake_items_db[commons.skip : commons.skip + commons.limit] - response.update({"items": items}) - return response diff --git a/docs_src/dependencies/tutorial002_an_py39.py b/docs_src/dependencies/tutorial002_an_py39.py deleted file mode 100644 index 844a23c5a7345..0000000000000 --- a/docs_src/dependencies/tutorial002_an_py39.py +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Annotated, Union - -from fastapi import Depends, FastAPI - -app = FastAPI() - - -fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}] - - -class CommonQueryParams: - def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100): - self.q = q - self.skip = skip - self.limit = limit - - -@app.get("/items/") -async def read_items(commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]): - response = {} - if commons.q: - response.update({"q": commons.q}) - items = fake_items_db[commons.skip : commons.skip + commons.limit] - response.update({"items": items}) - return response diff --git a/docs_src/dependencies/tutorial003.py b/docs_src/dependencies/tutorial003.py deleted file mode 100644 index 34614e5397fd0..0000000000000 --- a/docs_src/dependencies/tutorial003.py +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Union - -from fastapi import Depends, FastAPI - -app = FastAPI() - - -fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}] - - -class CommonQueryParams: - def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100): - self.q = q - self.skip = skip - self.limit = limit - - -@app.get("/items/") -async def read_items(commons=Depends(CommonQueryParams)): - response = {} - if commons.q: - response.update({"q": commons.q}) - items = fake_items_db[commons.skip : commons.skip + commons.limit] - response.update({"items": items}) - return response diff --git a/docs_src/dependencies/tutorial003_an.py b/docs_src/dependencies/tutorial003_an.py deleted file mode 100644 index ba8e9f71747d0..0000000000000 --- a/docs_src/dependencies/tutorial003_an.py +++ /dev/null @@ -1,26 +0,0 @@ -from typing import Any, Union - -from fastapi import Depends, FastAPI -from typing_extensions import Annotated - -app = FastAPI() - - -fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}] - - -class CommonQueryParams: - def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100): - self.q = q - self.skip = skip - self.limit = limit - - -@app.get("/items/") -async def read_items(commons: Annotated[Any, Depends(CommonQueryParams)]): - response = {} - if commons.q: - response.update({"q": commons.q}) - items = fake_items_db[commons.skip : commons.skip + commons.limit] - response.update({"items": items}) - return response diff --git a/docs_src/dependencies/tutorial003_an_py39.py b/docs_src/dependencies/tutorial003_an_py39.py deleted file mode 100644 index 9e9123ad2fc1c..0000000000000 --- a/docs_src/dependencies/tutorial003_an_py39.py +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Annotated, Any, Union - -from fastapi import Depends, FastAPI - -app = FastAPI() - - -fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}] - - -class CommonQueryParams: - def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100): - self.q = q - self.skip = skip - self.limit = limit - - -@app.get("/items/") -async def read_items(commons: Annotated[Any, Depends(CommonQueryParams)]): - response = {} - if commons.q: - response.update({"q": commons.q}) - items = fake_items_db[commons.skip : commons.skip + commons.limit] - response.update({"items": items}) - return response diff --git a/docs_src/dependencies/tutorial004.py b/docs_src/dependencies/tutorial004.py deleted file mode 100644 index d9fe8814886ea..0000000000000 --- a/docs_src/dependencies/tutorial004.py +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Union - -from fastapi import Depends, FastAPI - -app = FastAPI() - - -fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}] - - -class CommonQueryParams: - def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100): - self.q = q - self.skip = skip - self.limit = limit - - -@app.get("/items/") -async def read_items(commons: CommonQueryParams = Depends()): - response = {} - if commons.q: - response.update({"q": commons.q}) - items = fake_items_db[commons.skip : commons.skip + commons.limit] - response.update({"items": items}) - return response diff --git a/docs_src/dependencies/tutorial004_an.py b/docs_src/dependencies/tutorial004_an.py deleted file mode 100644 index 78881a354ca19..0000000000000 --- a/docs_src/dependencies/tutorial004_an.py +++ /dev/null @@ -1,26 +0,0 @@ -from typing import Union - -from fastapi import Depends, FastAPI -from typing_extensions import Annotated - -app = FastAPI() - - -fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}] - - -class CommonQueryParams: - def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100): - self.q = q - self.skip = skip - self.limit = limit - - -@app.get("/items/") -async def read_items(commons: Annotated[CommonQueryParams, Depends()]): - response = {} - if commons.q: - response.update({"q": commons.q}) - items = fake_items_db[commons.skip : commons.skip + commons.limit] - response.update({"items": items}) - return response diff --git a/docs_src/dependencies/tutorial004_an_py39.py b/docs_src/dependencies/tutorial004_an_py39.py deleted file mode 100644 index 74268626b40a4..0000000000000 --- a/docs_src/dependencies/tutorial004_an_py39.py +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Annotated, Union - -from fastapi import Depends, FastAPI - -app = FastAPI() - - -fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}] - - -class CommonQueryParams: - def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100): - self.q = q - self.skip = skip - self.limit = limit - - -@app.get("/items/") -async def read_items(commons: Annotated[CommonQueryParams, Depends()]): - response = {} - if commons.q: - response.update({"q": commons.q}) - items = fake_items_db[commons.skip : commons.skip + commons.limit] - response.update({"items": items}) - return response diff --git a/docs_src/dependencies/tutorial005.py b/docs_src/dependencies/tutorial005.py deleted file mode 100644 index 697332b5ba3b6..0000000000000 --- a/docs_src/dependencies/tutorial005.py +++ /dev/null @@ -1,23 +0,0 @@ -from typing import Union - -from fastapi import Cookie, Depends, FastAPI - -app = FastAPI() - - -def query_extractor(q: Union[str, None] = None): - return q - - -def query_or_cookie_extractor( - q: str = Depends(query_extractor), - last_query: Union[str, None] = Cookie(default=None), -): - if not q: - return last_query - return q - - -@app.get("/items/") -async def read_query(query_or_default: str = Depends(query_or_cookie_extractor)): - return {"q_or_cookie": query_or_default} diff --git a/docs_src/dependencies/tutorial005_an.py b/docs_src/dependencies/tutorial005_an.py deleted file mode 100644 index 6785099dabe7b..0000000000000 --- a/docs_src/dependencies/tutorial005_an.py +++ /dev/null @@ -1,26 +0,0 @@ -from typing import Union - -from fastapi import Cookie, Depends, FastAPI -from typing_extensions import Annotated - -app = FastAPI() - - -def query_extractor(q: Union[str, None] = None): - return q - - -def query_or_cookie_extractor( - q: Annotated[str, Depends(query_extractor)], - last_query: Annotated[Union[str, None], Cookie()] = None, -): - if not q: - return last_query - return q - - -@app.get("/items/") -async def read_query( - query_or_default: Annotated[str, Depends(query_or_cookie_extractor)] -): - return {"q_or_cookie": query_or_default} diff --git a/docs_src/dependencies/tutorial005_an_py310.py b/docs_src/dependencies/tutorial005_an_py310.py index 6c0aa0b3686be..5ccfc62bdfb27 100644 --- a/docs_src/dependencies/tutorial005_an_py310.py +++ b/docs_src/dependencies/tutorial005_an_py310.py @@ -20,6 +20,6 @@ def query_or_cookie_extractor( @app.get("/items/") async def read_query( - query_or_default: Annotated[str, Depends(query_or_cookie_extractor)] + query_or_default: Annotated[str, Depends(query_or_cookie_extractor)], ): return {"q_or_cookie": query_or_default} diff --git a/docs_src/dependencies/tutorial005_an_py39.py b/docs_src/dependencies/tutorial005_an_py39.py deleted file mode 100644 index e8887e162167c..0000000000000 --- a/docs_src/dependencies/tutorial005_an_py39.py +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Annotated, Union - -from fastapi import Cookie, Depends, FastAPI - -app = FastAPI() - - -def query_extractor(q: Union[str, None] = None): - return q - - -def query_or_cookie_extractor( - q: Annotated[str, Depends(query_extractor)], - last_query: Annotated[Union[str, None], Cookie()] = None, -): - if not q: - return last_query - return q - - -@app.get("/items/") -async def read_query( - query_or_default: Annotated[str, Depends(query_or_cookie_extractor)] -): - return {"q_or_cookie": query_or_default} diff --git a/docs_src/dependencies/tutorial006_an.py b/docs_src/dependencies/tutorial006_an.py deleted file mode 100644 index 5aaea04d16570..0000000000000 --- a/docs_src/dependencies/tutorial006_an.py +++ /dev/null @@ -1,20 +0,0 @@ -from fastapi import Depends, FastAPI, Header, HTTPException -from typing_extensions import Annotated - -app = FastAPI() - - -async def verify_token(x_token: Annotated[str, Header()]): - if x_token != "fake-super-secret-token": - raise HTTPException(status_code=400, detail="X-Token header invalid") - - -async def verify_key(x_key: Annotated[str, Header()]): - if x_key != "fake-super-secret-key": - raise HTTPException(status_code=400, detail="X-Key header invalid") - return x_key - - -@app.get("/items/", dependencies=[Depends(verify_token), Depends(verify_key)]) -async def read_items(): - return [{"item": "Foo"}, {"item": "Bar"}] diff --git a/docs_src/dependencies/tutorial006_an_py39.py b/docs_src/dependencies/tutorial006_an_py310.py similarity index 100% rename from docs_src/dependencies/tutorial006_an_py39.py rename to docs_src/dependencies/tutorial006_an_py310.py diff --git a/docs_src/dependencies/tutorial006.py b/docs_src/dependencies/tutorial006_py310.py similarity index 100% rename from docs_src/dependencies/tutorial006.py rename to docs_src/dependencies/tutorial006_py310.py diff --git a/docs_src/dependencies/tutorial007.py b/docs_src/dependencies/tutorial007_py310.py similarity index 100% rename from docs_src/dependencies/tutorial007.py rename to docs_src/dependencies/tutorial007_py310.py diff --git a/docs_src/dependencies/tutorial008_an.py b/docs_src/dependencies/tutorial008_an.py deleted file mode 100644 index 2de86f042d461..0000000000000 --- a/docs_src/dependencies/tutorial008_an.py +++ /dev/null @@ -1,26 +0,0 @@ -from fastapi import Depends -from typing_extensions import Annotated - - -async def dependency_a(): - dep_a = generate_dep_a() - try: - yield dep_a - finally: - dep_a.close() - - -async def dependency_b(dep_a: Annotated[DepA, Depends(dependency_a)]): - dep_b = generate_dep_b() - try: - yield dep_b - finally: - dep_b.close(dep_a) - - -async def dependency_c(dep_b: Annotated[DepB, Depends(dependency_b)]): - dep_c = generate_dep_c() - try: - yield dep_c - finally: - dep_c.close(dep_b) diff --git a/docs_src/dependencies/tutorial008_an_py39.py b/docs_src/dependencies/tutorial008_an_py310.py similarity index 100% rename from docs_src/dependencies/tutorial008_an_py39.py rename to docs_src/dependencies/tutorial008_an_py310.py diff --git a/docs_src/dependencies/tutorial008.py b/docs_src/dependencies/tutorial008_py310.py similarity index 100% rename from docs_src/dependencies/tutorial008.py rename to docs_src/dependencies/tutorial008_py310.py diff --git a/docs_src/dependencies/tutorial008b_an_py310.py b/docs_src/dependencies/tutorial008b_an_py310.py new file mode 100644 index 0000000000000..3b8434c816711 --- /dev/null +++ b/docs_src/dependencies/tutorial008b_an_py310.py @@ -0,0 +1,32 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +data = { + "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"}, + "portal-gun": {"description": "Gun to create portals", "owner": "Rick"}, +} + + +class OwnerError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except OwnerError as e: + raise HTTPException(status_code=400, detail=f"Owner error: {e}") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id not in data: + raise HTTPException(status_code=404, detail="Item not found") + item = data[item_id] + if item["owner"] != username: + raise OwnerError(username) + return item diff --git a/docs_src/dependencies/tutorial008b_py310.py b/docs_src/dependencies/tutorial008b_py310.py new file mode 100644 index 0000000000000..163e96600f9b3 --- /dev/null +++ b/docs_src/dependencies/tutorial008b_py310.py @@ -0,0 +1,30 @@ +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +data = { + "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"}, + "portal-gun": {"description": "Gun to create portals", "owner": "Rick"}, +} + + +class OwnerError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except OwnerError as e: + raise HTTPException(status_code=400, detail=f"Owner error: {e}") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: str = Depends(get_username)): + if item_id not in data: + raise HTTPException(status_code=404, detail="Item not found") + item = data[item_id] + if item["owner"] != username: + raise OwnerError(username) + return item diff --git a/docs_src/dependencies/tutorial008c_an_py310.py b/docs_src/dependencies/tutorial008c_an_py310.py new file mode 100644 index 0000000000000..da92efa9c3ce5 --- /dev/null +++ b/docs_src/dependencies/tutorial008c_an_py310.py @@ -0,0 +1,29 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("Oops, we didn't raise again, Britney 😱") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/dependencies/tutorial008c_py310.py b/docs_src/dependencies/tutorial008c_py310.py new file mode 100644 index 0000000000000..4b99a5a31150b --- /dev/null +++ b/docs_src/dependencies/tutorial008c_py310.py @@ -0,0 +1,27 @@ +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("Oops, we didn't raise again, Britney 😱") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: str = Depends(get_username)): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/dependencies/tutorial008d_an_py310.py b/docs_src/dependencies/tutorial008d_an_py310.py new file mode 100644 index 0000000000000..99bd5cb911392 --- /dev/null +++ b/docs_src/dependencies/tutorial008d_an_py310.py @@ -0,0 +1,30 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("We don't swallow the internal error here, we raise again 😎") + raise + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/dependencies/tutorial008d_py310.py b/docs_src/dependencies/tutorial008d_py310.py new file mode 100644 index 0000000000000..93039343d1c39 --- /dev/null +++ b/docs_src/dependencies/tutorial008d_py310.py @@ -0,0 +1,28 @@ +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("We don't swallow the internal error here, we raise again 😎") + raise + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: str = Depends(get_username)): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/dependencies/tutorial008e_an_py310.py b/docs_src/dependencies/tutorial008e_an_py310.py new file mode 100644 index 0000000000000..80a44c7e23fb4 --- /dev/null +++ b/docs_src/dependencies/tutorial008e_an_py310.py @@ -0,0 +1,17 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI + +app = FastAPI() + + +def get_username(): + try: + yield "Rick" + finally: + print("Cleanup up before response is sent") + + +@app.get("/users/me") +def get_user_me(username: Annotated[str, Depends(get_username, scope="function")]): + return username diff --git a/docs_src/dependencies/tutorial008e_py310.py b/docs_src/dependencies/tutorial008e_py310.py new file mode 100644 index 0000000000000..1ed056e91ef3c --- /dev/null +++ b/docs_src/dependencies/tutorial008e_py310.py @@ -0,0 +1,15 @@ +from fastapi import Depends, FastAPI + +app = FastAPI() + + +def get_username(): + try: + yield "Rick" + finally: + print("Cleanup up before response is sent") + + +@app.get("/users/me") +def get_user_me(username: str = Depends(get_username, scope="function")): + return username diff --git a/docs_src/dependencies/tutorial009.py b/docs_src/dependencies/tutorial009.py deleted file mode 100644 index 8472f642de850..0000000000000 --- a/docs_src/dependencies/tutorial009.py +++ /dev/null @@ -1,25 +0,0 @@ -from fastapi import Depends - - -async def dependency_a(): - dep_a = generate_dep_a() - try: - yield dep_a - finally: - dep_a.close() - - -async def dependency_b(dep_a=Depends(dependency_a)): - dep_b = generate_dep_b() - try: - yield dep_b - finally: - dep_b.close(dep_a) - - -async def dependency_c(dep_b=Depends(dependency_b)): - dep_c = generate_dep_c() - try: - yield dep_c - finally: - dep_c.close(dep_b) diff --git a/docs_src/dependencies/tutorial010.py b/docs_src/dependencies/tutorial010_py310.py similarity index 100% rename from docs_src/dependencies/tutorial010.py rename to docs_src/dependencies/tutorial010_py310.py diff --git a/docs_src/dependencies/tutorial011_an.py b/docs_src/dependencies/tutorial011_an.py deleted file mode 100644 index 6c13d9033f3b0..0000000000000 --- a/docs_src/dependencies/tutorial011_an.py +++ /dev/null @@ -1,22 +0,0 @@ -from fastapi import Depends, FastAPI -from typing_extensions import Annotated - -app = FastAPI() - - -class FixedContentQueryChecker: - def __init__(self, fixed_content: str): - self.fixed_content = fixed_content - - def __call__(self, q: str = ""): - if q: - return self.fixed_content in q - return False - - -checker = FixedContentQueryChecker("bar") - - -@app.get("/query-checker/") -async def read_query_check(fixed_content_included: Annotated[bool, Depends(checker)]): - return {"fixed_content_in_query": fixed_content_included} diff --git a/docs_src/dependencies/tutorial011_an_py39.py b/docs_src/dependencies/tutorial011_an_py310.py similarity index 100% rename from docs_src/dependencies/tutorial011_an_py39.py rename to docs_src/dependencies/tutorial011_an_py310.py diff --git a/docs_src/dependencies/tutorial011.py b/docs_src/dependencies/tutorial011_py310.py similarity index 100% rename from docs_src/dependencies/tutorial011.py rename to docs_src/dependencies/tutorial011_py310.py diff --git a/docs_src/dependencies/tutorial012_an.py b/docs_src/dependencies/tutorial012_an.py deleted file mode 100644 index 7541e6bf41ad0..0000000000000 --- a/docs_src/dependencies/tutorial012_an.py +++ /dev/null @@ -1,26 +0,0 @@ -from fastapi import Depends, FastAPI, Header, HTTPException -from typing_extensions import Annotated - - -async def verify_token(x_token: Annotated[str, Header()]): - if x_token != "fake-super-secret-token": - raise HTTPException(status_code=400, detail="X-Token header invalid") - - -async def verify_key(x_key: Annotated[str, Header()]): - if x_key != "fake-super-secret-key": - raise HTTPException(status_code=400, detail="X-Key header invalid") - return x_key - - -app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)]) - - -@app.get("/items/") -async def read_items(): - return [{"item": "Portal Gun"}, {"item": "Plumbus"}] - - -@app.get("/users/") -async def read_users(): - return [{"username": "Rick"}, {"username": "Morty"}] diff --git a/docs_src/dependencies/tutorial012_an_py310.py b/docs_src/dependencies/tutorial012_an_py310.py new file mode 100644 index 0000000000000..6503591fc3174 --- /dev/null +++ b/docs_src/dependencies/tutorial012_an_py310.py @@ -0,0 +1,27 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, Header, HTTPException + + +async def verify_token(x_token: Annotated[str, Header()]): + if x_token != "fake-super-secret-token": + raise HTTPException(status_code=400, detail="X-Token header invalid") + + +async def verify_key(x_key: Annotated[str, Header()]): + if x_key != "fake-super-secret-key": + raise HTTPException(status_code=400, detail="X-Key header invalid") + return x_key + + +app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)]) + + +@app.get("/items/") +async def read_items(): + return [{"item": "Portal Gun"}, {"item": "Plumbus"}] + + +@app.get("/users/") +async def read_users(): + return [{"username": "Rick"}, {"username": "Morty"}] diff --git a/docs_src/dependencies/tutorial012_an_py39.py b/docs_src/dependencies/tutorial012_an_py39.py deleted file mode 100644 index 7541e6bf41ad0..0000000000000 --- a/docs_src/dependencies/tutorial012_an_py39.py +++ /dev/null @@ -1,26 +0,0 @@ -from fastapi import Depends, FastAPI, Header, HTTPException -from typing_extensions import Annotated - - -async def verify_token(x_token: Annotated[str, Header()]): - if x_token != "fake-super-secret-token": - raise HTTPException(status_code=400, detail="X-Token header invalid") - - -async def verify_key(x_key: Annotated[str, Header()]): - if x_key != "fake-super-secret-key": - raise HTTPException(status_code=400, detail="X-Key header invalid") - return x_key - - -app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)]) - - -@app.get("/items/") -async def read_items(): - return [{"item": "Portal Gun"}, {"item": "Plumbus"}] - - -@app.get("/users/") -async def read_users(): - return [{"username": "Rick"}, {"username": "Morty"}] diff --git a/docs_src/dependencies/tutorial012.py b/docs_src/dependencies/tutorial012_py310.py similarity index 100% rename from docs_src/dependencies/tutorial012.py rename to docs_src/dependencies/tutorial012_py310.py diff --git a/docs_src/dependencies/tutorial013_an_py310.py b/docs_src/dependencies/tutorial013_an_py310.py new file mode 100644 index 0000000000000..0c2f62c4f9086 --- /dev/null +++ b/docs_src/dependencies/tutorial013_an_py310.py @@ -0,0 +1,38 @@ +import time +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException +from fastapi.responses import StreamingResponse +from sqlmodel import Field, Session, SQLModel, create_engine + +engine = create_engine("postgresql+psycopg://postgres:postgres@localhost/db") + + +class User(SQLModel, table=True): + id: int | None = Field(default=None, primary_key=True) + name: str + + +app = FastAPI() + + +def get_session(): + with Session(engine) as session: + yield session + + +def get_user(user_id: int, session: Annotated[Session, Depends(get_session)]): + user = session.get(User, user_id) + if not user: + raise HTTPException(status_code=403, detail="Not authorized") + + +def generate_stream(query: str): + for ch in query: + yield ch + time.sleep(0.1) + + +@app.get("/generate", dependencies=[Depends(get_user)]) +def generate(query: str): + return StreamingResponse(content=generate_stream(query)) diff --git a/docs_src/dependencies/tutorial014_an_py310.py b/docs_src/dependencies/tutorial014_an_py310.py new file mode 100644 index 0000000000000..ed7c1809a521f --- /dev/null +++ b/docs_src/dependencies/tutorial014_an_py310.py @@ -0,0 +1,39 @@ +import time +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException +from fastapi.responses import StreamingResponse +from sqlmodel import Field, Session, SQLModel, create_engine + +engine = create_engine("postgresql+psycopg://postgres:postgres@localhost/db") + + +class User(SQLModel, table=True): + id: int | None = Field(default=None, primary_key=True) + name: str + + +app = FastAPI() + + +def get_session(): + with Session(engine) as session: + yield session + + +def get_user(user_id: int, session: Annotated[Session, Depends(get_session)]): + user = session.get(User, user_id) + if not user: + raise HTTPException(status_code=403, detail="Not authorized") + session.close() + + +def generate_stream(query: str): + for ch in query: + yield ch + time.sleep(0.1) + + +@app.get("/generate", dependencies=[Depends(get_user)]) +def generate(query: str): + return StreamingResponse(content=generate_stream(query)) diff --git a/tests/test_filter_pydantic_sub_model/__init__.py b/docs_src/dependency_testing/__init__.py similarity index 100% rename from tests/test_filter_pydantic_sub_model/__init__.py rename to docs_src/dependency_testing/__init__.py diff --git a/docs_src/dependency_testing/tutorial001.py b/docs_src/dependency_testing/tutorial001.py deleted file mode 100644 index a5fe1d9bff84c..0000000000000 --- a/docs_src/dependency_testing/tutorial001.py +++ /dev/null @@ -1,59 +0,0 @@ -from typing import Union - -from fastapi import Depends, FastAPI -from fastapi.testclient import TestClient - -app = FastAPI() - - -async def common_parameters( - q: Union[str, None] = None, skip: int = 0, limit: int = 100 -): - return {"q": q, "skip": skip, "limit": limit} - - -@app.get("/items/") -async def read_items(commons: dict = Depends(common_parameters)): - return {"message": "Hello Items!", "params": commons} - - -@app.get("/users/") -async def read_users(commons: dict = Depends(common_parameters)): - return {"message": "Hello Users!", "params": commons} - - -client = TestClient(app) - - -async def override_dependency(q: Union[str, None] = None): - return {"q": q, "skip": 5, "limit": 10} - - -app.dependency_overrides[common_parameters] = override_dependency - - -def test_override_in_items(): - response = client.get("/items/") - assert response.status_code == 200 - assert response.json() == { - "message": "Hello Items!", - "params": {"q": None, "skip": 5, "limit": 10}, - } - - -def test_override_in_items_with_q(): - response = client.get("/items/?q=foo") - assert response.status_code == 200 - assert response.json() == { - "message": "Hello Items!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -def test_override_in_items_with_params(): - response = client.get("/items/?q=foo&skip=100&limit=200") - assert response.status_code == 200 - assert response.json() == { - "message": "Hello Items!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } diff --git a/docs_src/dependency_testing/tutorial001_an.py b/docs_src/dependency_testing/tutorial001_an.py deleted file mode 100644 index 4c76a87ff53f6..0000000000000 --- a/docs_src/dependency_testing/tutorial001_an.py +++ /dev/null @@ -1,60 +0,0 @@ -from typing import Union - -from fastapi import Depends, FastAPI -from fastapi.testclient import TestClient -from typing_extensions import Annotated - -app = FastAPI() - - -async def common_parameters( - q: Union[str, None] = None, skip: int = 0, limit: int = 100 -): - return {"q": q, "skip": skip, "limit": limit} - - -@app.get("/items/") -async def read_items(commons: Annotated[dict, Depends(common_parameters)]): - return {"message": "Hello Items!", "params": commons} - - -@app.get("/users/") -async def read_users(commons: Annotated[dict, Depends(common_parameters)]): - return {"message": "Hello Users!", "params": commons} - - -client = TestClient(app) - - -async def override_dependency(q: Union[str, None] = None): - return {"q": q, "skip": 5, "limit": 10} - - -app.dependency_overrides[common_parameters] = override_dependency - - -def test_override_in_items(): - response = client.get("/items/") - assert response.status_code == 200 - assert response.json() == { - "message": "Hello Items!", - "params": {"q": None, "skip": 5, "limit": 10}, - } - - -def test_override_in_items_with_q(): - response = client.get("/items/?q=foo") - assert response.status_code == 200 - assert response.json() == { - "message": "Hello Items!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -def test_override_in_items_with_params(): - response = client.get("/items/?q=foo&skip=100&limit=200") - assert response.status_code == 200 - assert response.json() == { - "message": "Hello Items!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } diff --git a/docs_src/dependency_testing/tutorial001_an_py39.py b/docs_src/dependency_testing/tutorial001_an_py39.py deleted file mode 100644 index bccb0cdb1f4a3..0000000000000 --- a/docs_src/dependency_testing/tutorial001_an_py39.py +++ /dev/null @@ -1,59 +0,0 @@ -from typing import Annotated, Union - -from fastapi import Depends, FastAPI -from fastapi.testclient import TestClient - -app = FastAPI() - - -async def common_parameters( - q: Union[str, None] = None, skip: int = 0, limit: int = 100 -): - return {"q": q, "skip": skip, "limit": limit} - - -@app.get("/items/") -async def read_items(commons: Annotated[dict, Depends(common_parameters)]): - return {"message": "Hello Items!", "params": commons} - - -@app.get("/users/") -async def read_users(commons: Annotated[dict, Depends(common_parameters)]): - return {"message": "Hello Users!", "params": commons} - - -client = TestClient(app) - - -async def override_dependency(q: Union[str, None] = None): - return {"q": q, "skip": 5, "limit": 10} - - -app.dependency_overrides[common_parameters] = override_dependency - - -def test_override_in_items(): - response = client.get("/items/") - assert response.status_code == 200 - assert response.json() == { - "message": "Hello Items!", - "params": {"q": None, "skip": 5, "limit": 10}, - } - - -def test_override_in_items_with_q(): - response = client.get("/items/?q=foo") - assert response.status_code == 200 - assert response.json() == { - "message": "Hello Items!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -def test_override_in_items_with_params(): - response = client.get("/items/?q=foo&skip=100&limit=200") - assert response.status_code == 200 - assert response.json() == { - "message": "Hello Items!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } diff --git a/tests/test_tutorial/test_async_sql_databases/__init__.py b/docs_src/encoder/__init__.py similarity index 100% rename from tests/test_tutorial/test_async_sql_databases/__init__.py rename to docs_src/encoder/__init__.py diff --git a/docs_src/encoder/tutorial001.py b/docs_src/encoder/tutorial001.py deleted file mode 100644 index 5f7e7061e4993..0000000000000 --- a/docs_src/encoder/tutorial001.py +++ /dev/null @@ -1,23 +0,0 @@ -from datetime import datetime -from typing import Union - -from fastapi import FastAPI -from fastapi.encoders import jsonable_encoder -from pydantic import BaseModel - -fake_db = {} - - -class Item(BaseModel): - title: str - timestamp: datetime - description: Union[str, None] = None - - -app = FastAPI() - - -@app.put("/items/{id}") -def update_item(id: str, item: Item): - json_compatible_item_data = jsonable_encoder(item) - fake_db[id] = json_compatible_item_data diff --git a/docs/en/mkdocs.no-insiders.yml b/docs_src/events/__init__.py similarity index 100% rename from docs/en/mkdocs.no-insiders.yml rename to docs_src/events/__init__.py diff --git a/docs_src/events/tutorial001.py b/docs_src/events/tutorial001_py310.py similarity index 100% rename from docs_src/events/tutorial001.py rename to docs_src/events/tutorial001_py310.py diff --git a/docs_src/events/tutorial002.py b/docs_src/events/tutorial002_py310.py similarity index 100% rename from docs_src/events/tutorial002.py rename to docs_src/events/tutorial002_py310.py diff --git a/docs_src/events/tutorial003.py b/docs_src/events/tutorial003_py310.py similarity index 100% rename from docs_src/events/tutorial003.py rename to docs_src/events/tutorial003_py310.py diff --git a/docs_src/extending_openapi/__init__.py b/docs_src/extending_openapi/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/extending_openapi/tutorial001.py b/docs_src/extending_openapi/tutorial001_py310.py similarity index 100% rename from docs_src/extending_openapi/tutorial001.py rename to docs_src/extending_openapi/tutorial001_py310.py diff --git a/docs_src/extra_data_types/__init__.py b/docs_src/extra_data_types/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/extra_data_types/tutorial001.py b/docs_src/extra_data_types/tutorial001.py deleted file mode 100644 index 8ae8472a70695..0000000000000 --- a/docs_src/extra_data_types/tutorial001.py +++ /dev/null @@ -1,28 +0,0 @@ -from datetime import datetime, time, timedelta -from typing import Union -from uuid import UUID - -from fastapi import Body, FastAPI - -app = FastAPI() - - -@app.put("/items/{item_id}") -async def read_items( - item_id: UUID, - start_datetime: Union[datetime, None] = Body(default=None), - end_datetime: Union[datetime, None] = Body(default=None), - repeat_at: Union[time, None] = Body(default=None), - process_after: Union[timedelta, None] = Body(default=None), -): - start_process = start_datetime + process_after - duration = end_datetime - start_process - return { - "item_id": item_id, - "start_datetime": start_datetime, - "end_datetime": end_datetime, - "repeat_at": repeat_at, - "process_after": process_after, - "start_process": start_process, - "duration": duration, - } diff --git a/docs_src/extra_data_types/tutorial001_an.py b/docs_src/extra_data_types/tutorial001_an.py deleted file mode 100644 index a4c074241a7b7..0000000000000 --- a/docs_src/extra_data_types/tutorial001_an.py +++ /dev/null @@ -1,29 +0,0 @@ -from datetime import datetime, time, timedelta -from typing import Union -from uuid import UUID - -from fastapi import Body, FastAPI -from typing_extensions import Annotated - -app = FastAPI() - - -@app.put("/items/{item_id}") -async def read_items( - item_id: UUID, - start_datetime: Annotated[Union[datetime, None], Body()] = None, - end_datetime: Annotated[Union[datetime, None], Body()] = None, - repeat_at: Annotated[Union[time, None], Body()] = None, - process_after: Annotated[Union[timedelta, None], Body()] = None, -): - start_process = start_datetime + process_after - duration = end_datetime - start_process - return { - "item_id": item_id, - "start_datetime": start_datetime, - "end_datetime": end_datetime, - "repeat_at": repeat_at, - "process_after": process_after, - "start_process": start_process, - "duration": duration, - } diff --git a/docs_src/extra_data_types/tutorial001_an_py310.py b/docs_src/extra_data_types/tutorial001_an_py310.py index 4f69c40d95027..668bf19090d4e 100644 --- a/docs_src/extra_data_types/tutorial001_an_py310.py +++ b/docs_src/extra_data_types/tutorial001_an_py310.py @@ -10,10 +10,10 @@ @app.put("/items/{item_id}") async def read_items( item_id: UUID, - start_datetime: Annotated[datetime | None, Body()] = None, - end_datetime: Annotated[datetime | None, Body()] = None, + start_datetime: Annotated[datetime, Body()], + end_datetime: Annotated[datetime, Body()], + process_after: Annotated[timedelta, Body()], repeat_at: Annotated[time | None, Body()] = None, - process_after: Annotated[timedelta | None, Body()] = None, ): start_process = start_datetime + process_after duration = end_datetime - start_process @@ -21,8 +21,8 @@ async def read_items( "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, - "repeat_at": repeat_at, "process_after": process_after, + "repeat_at": repeat_at, "start_process": start_process, "duration": duration, } diff --git a/docs_src/extra_data_types/tutorial001_an_py39.py b/docs_src/extra_data_types/tutorial001_an_py39.py deleted file mode 100644 index 630d36ae31ee4..0000000000000 --- a/docs_src/extra_data_types/tutorial001_an_py39.py +++ /dev/null @@ -1,28 +0,0 @@ -from datetime import datetime, time, timedelta -from typing import Annotated, Union -from uuid import UUID - -from fastapi import Body, FastAPI - -app = FastAPI() - - -@app.put("/items/{item_id}") -async def read_items( - item_id: UUID, - start_datetime: Annotated[Union[datetime, None], Body()] = None, - end_datetime: Annotated[Union[datetime, None], Body()] = None, - repeat_at: Annotated[Union[time, None], Body()] = None, - process_after: Annotated[Union[timedelta, None], Body()] = None, -): - start_process = start_datetime + process_after - duration = end_datetime - start_process - return { - "item_id": item_id, - "start_datetime": start_datetime, - "end_datetime": end_datetime, - "repeat_at": repeat_at, - "process_after": process_after, - "start_process": start_process, - "duration": duration, - } diff --git a/docs_src/extra_data_types/tutorial001_py310.py b/docs_src/extra_data_types/tutorial001_py310.py index d22f818886d9d..a275a05776946 100644 --- a/docs_src/extra_data_types/tutorial001_py310.py +++ b/docs_src/extra_data_types/tutorial001_py310.py @@ -9,10 +9,10 @@ @app.put("/items/{item_id}") async def read_items( item_id: UUID, - start_datetime: datetime | None = Body(default=None), - end_datetime: datetime | None = Body(default=None), + start_datetime: datetime = Body(), + end_datetime: datetime = Body(), + process_after: timedelta = Body(), repeat_at: time | None = Body(default=None), - process_after: timedelta | None = Body(default=None), ): start_process = start_datetime + process_after duration = end_datetime - start_process @@ -20,8 +20,8 @@ async def read_items( "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, - "repeat_at": repeat_at, "process_after": process_after, + "repeat_at": repeat_at, "start_process": start_process, "duration": duration, } diff --git a/docs_src/extra_models/__init__.py b/docs_src/extra_models/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/extra_models/tutorial001.py b/docs_src/extra_models/tutorial001.py deleted file mode 100644 index 4be56cd2a744b..0000000000000 --- a/docs_src/extra_models/tutorial001.py +++ /dev/null @@ -1,43 +0,0 @@ -from typing import Union - -from fastapi import FastAPI -from pydantic import BaseModel, EmailStr - -app = FastAPI() - - -class UserIn(BaseModel): - username: str - password: str - email: EmailStr - full_name: Union[str, None] = None - - -class UserOut(BaseModel): - username: str - email: EmailStr - full_name: Union[str, None] = None - - -class UserInDB(BaseModel): - username: str - hashed_password: str - email: EmailStr - full_name: Union[str, None] = None - - -def fake_password_hasher(raw_password: str): - return "supersecret" + raw_password - - -def fake_save_user(user_in: UserIn): - hashed_password = fake_password_hasher(user_in.password) - user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password) - print("User saved! ..not really") - return user_in_db - - -@app.post("/user/", response_model=UserOut) -async def create_user(user_in: UserIn): - user_saved = fake_save_user(user_in) - return user_saved diff --git a/docs_src/extra_models/tutorial001_py310.py b/docs_src/extra_models/tutorial001_py310.py index 669386ae6ebd5..cf39142e4af84 100644 --- a/docs_src/extra_models/tutorial001_py310.py +++ b/docs_src/extra_models/tutorial001_py310.py @@ -30,7 +30,7 @@ def fake_password_hasher(raw_password: str): def fake_save_user(user_in: UserIn): hashed_password = fake_password_hasher(user_in.password) - user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password) + user_in_db = UserInDB(**user_in.model_dump(), hashed_password=hashed_password) print("User saved! ..not really") return user_in_db diff --git a/docs_src/extra_models/tutorial002.py b/docs_src/extra_models/tutorial002.py deleted file mode 100644 index 70fa16441d642..0000000000000 --- a/docs_src/extra_models/tutorial002.py +++ /dev/null @@ -1,41 +0,0 @@ -from typing import Union - -from fastapi import FastAPI -from pydantic import BaseModel, EmailStr - -app = FastAPI() - - -class UserBase(BaseModel): - username: str - email: EmailStr - full_name: Union[str, None] = None - - -class UserIn(UserBase): - password: str - - -class UserOut(UserBase): - pass - - -class UserInDB(UserBase): - hashed_password: str - - -def fake_password_hasher(raw_password: str): - return "supersecret" + raw_password - - -def fake_save_user(user_in: UserIn): - hashed_password = fake_password_hasher(user_in.password) - user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password) - print("User saved! ..not really") - return user_in_db - - -@app.post("/user/", response_model=UserOut) -async def create_user(user_in: UserIn): - user_saved = fake_save_user(user_in) - return user_saved diff --git a/docs_src/extra_models/tutorial002_py310.py b/docs_src/extra_models/tutorial002_py310.py index 5b8ed7de3dcd6..e8a4f5f29bcb5 100644 --- a/docs_src/extra_models/tutorial002_py310.py +++ b/docs_src/extra_models/tutorial002_py310.py @@ -28,7 +28,7 @@ def fake_password_hasher(raw_password: str): def fake_save_user(user_in: UserIn): hashed_password = fake_password_hasher(user_in.password) - user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password) + user_in_db = UserInDB(**user_in.model_dump(), hashed_password=hashed_password) print("User saved! ..not really") return user_in_db diff --git a/docs_src/extra_models/tutorial003.py b/docs_src/extra_models/tutorial003.py deleted file mode 100644 index 06675cbc09808..0000000000000 --- a/docs_src/extra_models/tutorial003.py +++ /dev/null @@ -1,35 +0,0 @@ -from typing import Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class BaseItem(BaseModel): - description: str - type: str - - -class CarItem(BaseItem): - type: str = "car" - - -class PlaneItem(BaseItem): - type: str = "plane" - size: int - - -items = { - "item1": {"description": "All my friends drive a low rider", "type": "car"}, - "item2": { - "description": "Music is my aeroplane, it's my aeroplane", - "type": "plane", - "size": 5, - }, -} - - -@app.get("/items/{item_id}", response_model=Union[PlaneItem, CarItem]) -async def read_item(item_id: str): - return items[item_id] diff --git a/docs_src/extra_models/tutorial003_py310.py b/docs_src/extra_models/tutorial003_py310.py index 06675cbc09808..8fe6f7136e17f 100644 --- a/docs_src/extra_models/tutorial003_py310.py +++ b/docs_src/extra_models/tutorial003_py310.py @@ -1,5 +1,3 @@ -from typing import Union - from fastapi import FastAPI from pydantic import BaseModel @@ -30,6 +28,6 @@ class PlaneItem(BaseItem): } -@app.get("/items/{item_id}", response_model=Union[PlaneItem, CarItem]) +@app.get("/items/{item_id}", response_model=PlaneItem | CarItem) async def read_item(item_id: str): return items[item_id] diff --git a/docs_src/extra_models/tutorial004.py b/docs_src/extra_models/tutorial004.py deleted file mode 100644 index a8e0f7af5a750..0000000000000 --- a/docs_src/extra_models/tutorial004.py +++ /dev/null @@ -1,22 +0,0 @@ -from typing import List - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: str - - -items = [ - {"name": "Foo", "description": "There comes my hero"}, - {"name": "Red", "description": "It's my aeroplane"}, -] - - -@app.get("/items/", response_model=List[Item]) -async def read_items(): - return items diff --git a/docs_src/extra_models/tutorial004_py39.py b/docs_src/extra_models/tutorial004_py310.py similarity index 100% rename from docs_src/extra_models/tutorial004_py39.py rename to docs_src/extra_models/tutorial004_py310.py diff --git a/docs_src/extra_models/tutorial005.py b/docs_src/extra_models/tutorial005.py deleted file mode 100644 index a81cbc2c583ac..0000000000000 --- a/docs_src/extra_models/tutorial005.py +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Dict - -from fastapi import FastAPI - -app = FastAPI() - - -@app.get("/keyword-weights/", response_model=Dict[str, float]) -async def read_keyword_weights(): - return {"foo": 2.3, "bar": 3.4} diff --git a/docs_src/extra_models/tutorial005_py39.py b/docs_src/extra_models/tutorial005_py310.py similarity index 100% rename from docs_src/extra_models/tutorial005_py39.py rename to docs_src/extra_models/tutorial005_py310.py diff --git a/docs_src/first_steps/__init__.py b/docs_src/first_steps/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/first_steps/tutorial001.py b/docs_src/first_steps/tutorial001_py310.py similarity index 100% rename from docs_src/first_steps/tutorial001.py rename to docs_src/first_steps/tutorial001_py310.py diff --git a/docs_src/first_steps/tutorial002.py b/docs_src/first_steps/tutorial002.py deleted file mode 100644 index ca7d48cff933b..0000000000000 --- a/docs_src/first_steps/tutorial002.py +++ /dev/null @@ -1,8 +0,0 @@ -from fastapi import FastAPI - -my_awesome_api = FastAPI() - - -@my_awesome_api.get("/") -async def root(): - return {"message": "Hello World"} diff --git a/docs_src/first_steps/tutorial003.py b/docs_src/first_steps/tutorial003_py310.py similarity index 100% rename from docs_src/first_steps/tutorial003.py rename to docs_src/first_steps/tutorial003_py310.py diff --git a/docs_src/generate_clients/__init__.py b/docs_src/generate_clients/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/generate_clients/tutorial001.py b/docs_src/generate_clients/tutorial001.py deleted file mode 100644 index 2d1f91bc6ce3f..0000000000000 --- a/docs_src/generate_clients/tutorial001.py +++ /dev/null @@ -1,28 +0,0 @@ -from typing import List - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - price: float - - -class ResponseMessage(BaseModel): - message: str - - -@app.post("/items/", response_model=ResponseMessage) -async def create_item(item: Item): - return {"message": "item received"} - - -@app.get("/items/", response_model=List[Item]) -async def get_items(): - return [ - {"name": "Plumbus", "price": 3}, - {"name": "Portal Gun", "price": 9001}, - ] diff --git a/docs_src/generate_clients/tutorial001_py39.py b/docs_src/generate_clients/tutorial001_py310.py similarity index 100% rename from docs_src/generate_clients/tutorial001_py39.py rename to docs_src/generate_clients/tutorial001_py310.py diff --git a/docs_src/generate_clients/tutorial002.py b/docs_src/generate_clients/tutorial002.py deleted file mode 100644 index bd80449af9125..0000000000000 --- a/docs_src/generate_clients/tutorial002.py +++ /dev/null @@ -1,38 +0,0 @@ -from typing import List - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - price: float - - -class ResponseMessage(BaseModel): - message: str - - -class User(BaseModel): - username: str - email: str - - -@app.post("/items/", response_model=ResponseMessage, tags=["items"]) -async def create_item(item: Item): - return {"message": "Item received"} - - -@app.get("/items/", response_model=List[Item], tags=["items"]) -async def get_items(): - return [ - {"name": "Plumbus", "price": 3}, - {"name": "Portal Gun", "price": 9001}, - ] - - -@app.post("/users/", response_model=ResponseMessage, tags=["users"]) -async def create_user(user: User): - return {"message": "User received"} diff --git a/docs_src/generate_clients/tutorial002_py39.py b/docs_src/generate_clients/tutorial002_py310.py similarity index 100% rename from docs_src/generate_clients/tutorial002_py39.py rename to docs_src/generate_clients/tutorial002_py310.py diff --git a/docs_src/generate_clients/tutorial003.py b/docs_src/generate_clients/tutorial003.py deleted file mode 100644 index 49eab73a1bf52..0000000000000 --- a/docs_src/generate_clients/tutorial003.py +++ /dev/null @@ -1,44 +0,0 @@ -from typing import List - -from fastapi import FastAPI -from fastapi.routing import APIRoute -from pydantic import BaseModel - - -def custom_generate_unique_id(route: APIRoute): - return f"{route.tags[0]}-{route.name}" - - -app = FastAPI(generate_unique_id_function=custom_generate_unique_id) - - -class Item(BaseModel): - name: str - price: float - - -class ResponseMessage(BaseModel): - message: str - - -class User(BaseModel): - username: str - email: str - - -@app.post("/items/", response_model=ResponseMessage, tags=["items"]) -async def create_item(item: Item): - return {"message": "Item received"} - - -@app.get("/items/", response_model=List[Item], tags=["items"]) -async def get_items(): - return [ - {"name": "Plumbus", "price": 3}, - {"name": "Portal Gun", "price": 9001}, - ] - - -@app.post("/users/", response_model=ResponseMessage, tags=["users"]) -async def create_user(user: User): - return {"message": "User received"} diff --git a/docs_src/generate_clients/tutorial003_py39.py b/docs_src/generate_clients/tutorial003_py310.py similarity index 100% rename from docs_src/generate_clients/tutorial003_py39.py rename to docs_src/generate_clients/tutorial003_py310.py diff --git a/docs_src/generate_clients/tutorial004.js b/docs_src/generate_clients/tutorial004.js new file mode 100644 index 0000000000000..fa222ba6cc884 --- /dev/null +++ b/docs_src/generate_clients/tutorial004.js @@ -0,0 +1,36 @@ +import * as fs from 'fs' + +async function modifyOpenAPIFile(filePath) { + try { + const data = await fs.promises.readFile(filePath) + const openapiContent = JSON.parse(data) + + const paths = openapiContent.paths + for (const pathKey of Object.keys(paths)) { + const pathData = paths[pathKey] + for (const method of Object.keys(pathData)) { + const operation = pathData[method] + if (operation.tags && operation.tags.length > 0) { + const tag = operation.tags[0] + const operationId = operation.operationId + const toRemove = `${tag}-` + if (operationId.startsWith(toRemove)) { + const newOperationId = operationId.substring(toRemove.length) + operation.operationId = newOperationId + } + } + } + } + + await fs.promises.writeFile( + filePath, + JSON.stringify(openapiContent, null, 2), + ) + console.log('File successfully modified') + } catch (err) { + console.error('Error:', err) + } +} + +const filePath = './openapi.json' +modifyOpenAPIFile(filePath) diff --git a/docs_src/generate_clients/tutorial004.py b/docs_src/generate_clients/tutorial004_py310.py similarity index 100% rename from docs_src/generate_clients/tutorial004.py rename to docs_src/generate_clients/tutorial004_py310.py diff --git a/docs_src/graphql/tutorial001.py b/docs_src/graphql/tutorial001.py deleted file mode 100644 index 3b4ca99cf6b50..0000000000000 --- a/docs_src/graphql/tutorial001.py +++ /dev/null @@ -1,26 +0,0 @@ -import strawberry -from fastapi import FastAPI -from strawberry.asgi import GraphQL - - -@strawberry.type -class User: - name: str - age: int - - -@strawberry.type -class Query: - @strawberry.field - def user(self) -> User: - return User(name="Patrick", age=100) - - -schema = strawberry.Schema(query=Query) - - -graphql_app = GraphQL(schema) - -app = FastAPI() -app.add_route("/graphql", graphql_app) -app.add_websocket_route("/graphql", graphql_app) diff --git a/docs_src/graphql_/__init__.py b/docs_src/graphql_/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/graphql_/tutorial001_py310.py b/docs_src/graphql_/tutorial001_py310.py new file mode 100644 index 0000000000000..e92b2d71c4184 --- /dev/null +++ b/docs_src/graphql_/tutorial001_py310.py @@ -0,0 +1,25 @@ +import strawberry +from fastapi import FastAPI +from strawberry.fastapi import GraphQLRouter + + +@strawberry.type +class User: + name: str + age: int + + +@strawberry.type +class Query: + @strawberry.field + def user(self) -> User: + return User(name="Patrick", age=100) + + +schema = strawberry.Schema(query=Query) + + +graphql_app = GraphQLRouter(schema) + +app = FastAPI() +app.include_router(graphql_app, prefix="/graphql") diff --git a/docs_src/handling_errors/__init__.py b/docs_src/handling_errors/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/handling_errors/tutorial001.py b/docs_src/handling_errors/tutorial001_py310.py similarity index 100% rename from docs_src/handling_errors/tutorial001.py rename to docs_src/handling_errors/tutorial001_py310.py diff --git a/docs_src/handling_errors/tutorial002.py b/docs_src/handling_errors/tutorial002_py310.py similarity index 100% rename from docs_src/handling_errors/tutorial002.py rename to docs_src/handling_errors/tutorial002_py310.py diff --git a/docs_src/handling_errors/tutorial003.py b/docs_src/handling_errors/tutorial003_py310.py similarity index 100% rename from docs_src/handling_errors/tutorial003.py rename to docs_src/handling_errors/tutorial003_py310.py diff --git a/docs_src/handling_errors/tutorial004.py b/docs_src/handling_errors/tutorial004.py deleted file mode 100644 index 300a3834ff47c..0000000000000 --- a/docs_src/handling_errors/tutorial004.py +++ /dev/null @@ -1,23 +0,0 @@ -from fastapi import FastAPI, HTTPException -from fastapi.exceptions import RequestValidationError -from fastapi.responses import PlainTextResponse -from starlette.exceptions import HTTPException as StarletteHTTPException - -app = FastAPI() - - -@app.exception_handler(StarletteHTTPException) -async def http_exception_handler(request, exc): - return PlainTextResponse(str(exc.detail), status_code=exc.status_code) - - -@app.exception_handler(RequestValidationError) -async def validation_exception_handler(request, exc): - return PlainTextResponse(str(exc), status_code=400) - - -@app.get("/items/{item_id}") -async def read_item(item_id: int): - if item_id == 3: - raise HTTPException(status_code=418, detail="Nope! I don't like 3.") - return {"item_id": item_id} diff --git a/docs_src/handling_errors/tutorial004_py310.py b/docs_src/handling_errors/tutorial004_py310.py new file mode 100644 index 0000000000000..ae50807e97336 --- /dev/null +++ b/docs_src/handling_errors/tutorial004_py310.py @@ -0,0 +1,26 @@ +from fastapi import FastAPI, HTTPException +from fastapi.exceptions import RequestValidationError +from fastapi.responses import PlainTextResponse +from starlette.exceptions import HTTPException as StarletteHTTPException + +app = FastAPI() + + +@app.exception_handler(StarletteHTTPException) +async def http_exception_handler(request, exc): + return PlainTextResponse(str(exc.detail), status_code=exc.status_code) + + +@app.exception_handler(RequestValidationError) +async def validation_exception_handler(request, exc: RequestValidationError): + message = "Validation errors:" + for error in exc.errors(): + message += f"\nField: {error['loc']}, Error: {error['msg']}" + return PlainTextResponse(message, status_code=400) + + +@app.get("/items/{item_id}") +async def read_item(item_id: int): + if item_id == 3: + raise HTTPException(status_code=418, detail="Nope! I don't like 3.") + return {"item_id": item_id} diff --git a/docs_src/handling_errors/tutorial005.py b/docs_src/handling_errors/tutorial005.py deleted file mode 100644 index 6e0b81d313fdc..0000000000000 --- a/docs_src/handling_errors/tutorial005.py +++ /dev/null @@ -1,25 +0,0 @@ -from fastapi import FastAPI, Request, status -from fastapi.encoders import jsonable_encoder -from fastapi.exceptions import RequestValidationError -from fastapi.responses import JSONResponse -from pydantic import BaseModel - -app = FastAPI() - - -@app.exception_handler(RequestValidationError) -async def validation_exception_handler(request: Request, exc: RequestValidationError): - return JSONResponse( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}), - ) - - -class Item(BaseModel): - title: str - size: int - - -@app.post("/items/") -async def create_item(item: Item): - return item diff --git a/docs_src/handling_errors/tutorial005_py310.py b/docs_src/handling_errors/tutorial005_py310.py new file mode 100644 index 0000000000000..0e04fa0864050 --- /dev/null +++ b/docs_src/handling_errors/tutorial005_py310.py @@ -0,0 +1,25 @@ +from fastapi import FastAPI, Request +from fastapi.encoders import jsonable_encoder +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +app = FastAPI() + + +@app.exception_handler(RequestValidationError) +async def validation_exception_handler(request: Request, exc: RequestValidationError): + return JSONResponse( + status_code=422, + content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}), + ) + + +class Item(BaseModel): + title: str + size: int + + +@app.post("/items/") +async def create_item(item: Item): + return item diff --git a/docs_src/handling_errors/tutorial006.py b/docs_src/handling_errors/tutorial006_py310.py similarity index 100% rename from docs_src/handling_errors/tutorial006.py rename to docs_src/handling_errors/tutorial006_py310.py diff --git a/docs_src/header_param_models/__init__.py b/docs_src/header_param_models/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/header_param_models/tutorial001_an_py310.py b/docs_src/header_param_models/tutorial001_an_py310.py new file mode 100644 index 0000000000000..acfb6b9bf2699 --- /dev/null +++ b/docs_src/header_param_models/tutorial001_an_py310.py @@ -0,0 +1,19 @@ +from typing import Annotated + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial001_py310.py b/docs_src/header_param_models/tutorial001_py310.py new file mode 100644 index 0000000000000..7239c64ceadc1 --- /dev/null +++ b/docs_src/header_param_models/tutorial001_py310.py @@ -0,0 +1,17 @@ +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial002_an_py310.py b/docs_src/header_param_models/tutorial002_an_py310.py new file mode 100644 index 0000000000000..e9535f045fb32 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_an_py310.py @@ -0,0 +1,21 @@ +from typing import Annotated + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial002_py310.py b/docs_src/header_param_models/tutorial002_py310.py new file mode 100644 index 0000000000000..3d229634540bf --- /dev/null +++ b/docs_src/header_param_models/tutorial002_py310.py @@ -0,0 +1,19 @@ +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial003_an_py310.py b/docs_src/header_param_models/tutorial003_an_py310.py new file mode 100644 index 0000000000000..07bfa83bfe5f8 --- /dev/null +++ b/docs_src/header_param_models/tutorial003_an_py310.py @@ -0,0 +1,21 @@ +from typing import Annotated + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items( + headers: Annotated[CommonHeaders, Header(convert_underscores=False)], +): + return headers diff --git a/docs_src/header_param_models/tutorial003_py310.py b/docs_src/header_param_models/tutorial003_py310.py new file mode 100644 index 0000000000000..65e92a28cfff7 --- /dev/null +++ b/docs_src/header_param_models/tutorial003_py310.py @@ -0,0 +1,17 @@ +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header(convert_underscores=False)): + return headers diff --git a/docs_src/header_params/__init__.py b/docs_src/header_params/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/header_params/tutorial001.py b/docs_src/header_params/tutorial001.py deleted file mode 100644 index 74429c8e2d542..0000000000000 --- a/docs_src/header_params/tutorial001.py +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Header - -app = FastAPI() - - -@app.get("/items/") -async def read_items(user_agent: Union[str, None] = Header(default=None)): - return {"User-Agent": user_agent} diff --git a/docs_src/header_params/tutorial001_an.py b/docs_src/header_params/tutorial001_an.py deleted file mode 100644 index 816c000862cd5..0000000000000 --- a/docs_src/header_params/tutorial001_an.py +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Header -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items(user_agent: Annotated[Union[str, None], Header()] = None): - return {"User-Agent": user_agent} diff --git a/docs_src/header_params/tutorial001_an_py39.py b/docs_src/header_params/tutorial001_an_py39.py deleted file mode 100644 index 1fbe3bb99a8d2..0000000000000 --- a/docs_src/header_params/tutorial001_an_py39.py +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Annotated, Union - -from fastapi import FastAPI, Header - -app = FastAPI() - - -@app.get("/items/") -async def read_items(user_agent: Annotated[Union[str, None], Header()] = None): - return {"User-Agent": user_agent} diff --git a/docs_src/header_params/tutorial002.py b/docs_src/header_params/tutorial002.py deleted file mode 100644 index 639ab1735d068..0000000000000 --- a/docs_src/header_params/tutorial002.py +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Header - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - strange_header: Union[str, None] = Header(default=None, convert_underscores=False) -): - return {"strange_header": strange_header} diff --git a/docs_src/header_params/tutorial002_an.py b/docs_src/header_params/tutorial002_an.py deleted file mode 100644 index 65d972d46eec8..0000000000000 --- a/docs_src/header_params/tutorial002_an.py +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Header -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - strange_header: Annotated[ - Union[str, None], Header(convert_underscores=False) - ] = None -): - return {"strange_header": strange_header} diff --git a/docs_src/header_params/tutorial002_an_py310.py b/docs_src/header_params/tutorial002_an_py310.py index b340647b600d0..8a102749f289f 100644 --- a/docs_src/header_params/tutorial002_an_py310.py +++ b/docs_src/header_params/tutorial002_an_py310.py @@ -7,6 +7,6 @@ @app.get("/items/") async def read_items( - strange_header: Annotated[str | None, Header(convert_underscores=False)] = None + strange_header: Annotated[str | None, Header(convert_underscores=False)] = None, ): return {"strange_header": strange_header} diff --git a/docs_src/header_params/tutorial002_an_py39.py b/docs_src/header_params/tutorial002_an_py39.py deleted file mode 100644 index 7f6a99f9c3690..0000000000000 --- a/docs_src/header_params/tutorial002_an_py39.py +++ /dev/null @@ -1,14 +0,0 @@ -from typing import Annotated, Union - -from fastapi import FastAPI, Header - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - strange_header: Annotated[ - Union[str, None], Header(convert_underscores=False) - ] = None -): - return {"strange_header": strange_header} diff --git a/docs_src/header_params/tutorial002_py310.py b/docs_src/header_params/tutorial002_py310.py index b7979b542a143..10d6716c649e7 100644 --- a/docs_src/header_params/tutorial002_py310.py +++ b/docs_src/header_params/tutorial002_py310.py @@ -5,6 +5,6 @@ @app.get("/items/") async def read_items( - strange_header: str | None = Header(default=None, convert_underscores=False) + strange_header: str | None = Header(default=None, convert_underscores=False), ): return {"strange_header": strange_header} diff --git a/docs_src/header_params/tutorial003.py b/docs_src/header_params/tutorial003.py deleted file mode 100644 index a61314aedbbcc..0000000000000 --- a/docs_src/header_params/tutorial003.py +++ /dev/null @@ -1,10 +0,0 @@ -from typing import List, Union - -from fastapi import FastAPI, Header - -app = FastAPI() - - -@app.get("/items/") -async def read_items(x_token: Union[List[str], None] = Header(default=None)): - return {"X-Token values": x_token} diff --git a/docs_src/header_params/tutorial003_an.py b/docs_src/header_params/tutorial003_an.py deleted file mode 100644 index 5406fd1f88b63..0000000000000 --- a/docs_src/header_params/tutorial003_an.py +++ /dev/null @@ -1,11 +0,0 @@ -from typing import List, Union - -from fastapi import FastAPI, Header -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items(x_token: Annotated[Union[List[str], None], Header()] = None): - return {"X-Token values": x_token} diff --git a/docs_src/header_params/tutorial003_an_py39.py b/docs_src/header_params/tutorial003_an_py39.py deleted file mode 100644 index c1dd4996113f1..0000000000000 --- a/docs_src/header_params/tutorial003_an_py39.py +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Annotated, List, Union - -from fastapi import FastAPI, Header - -app = FastAPI() - - -@app.get("/items/") -async def read_items(x_token: Annotated[Union[List[str], None], Header()] = None): - return {"X-Token values": x_token} diff --git a/docs_src/header_params/tutorial003_py39.py b/docs_src/header_params/tutorial003_py39.py deleted file mode 100644 index 34437db161fc3..0000000000000 --- a/docs_src/header_params/tutorial003_py39.py +++ /dev/null @@ -1,10 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Header - -app = FastAPI() - - -@app.get("/items/") -async def read_items(x_token: Union[list[str], None] = Header(default=None)): - return {"X-Token values": x_token} diff --git a/docs_src/json_base64_bytes/__init__.py b/docs_src/json_base64_bytes/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/json_base64_bytes/tutorial001_py310.py b/docs_src/json_base64_bytes/tutorial001_py310.py new file mode 100644 index 0000000000000..3262ffb7f0ba9 --- /dev/null +++ b/docs_src/json_base64_bytes/tutorial001_py310.py @@ -0,0 +1,46 @@ +from fastapi import FastAPI +from pydantic import BaseModel + + +class DataInput(BaseModel): + description: str + data: bytes + + model_config = {"val_json_bytes": "base64"} + + +class DataOutput(BaseModel): + description: str + data: bytes + + model_config = {"ser_json_bytes": "base64"} + + +class DataInputOutput(BaseModel): + description: str + data: bytes + + model_config = { + "val_json_bytes": "base64", + "ser_json_bytes": "base64", + } + + +app = FastAPI() + + +@app.post("/data") +def post_data(body: DataInput): + content = body.data.decode("utf-8") + return {"description": body.description, "content": content} + + +@app.get("/data") +def get_data() -> DataOutput: + data = "hello".encode("utf-8") + return DataOutput(description="A plumbus", data=data) + + +@app.post("/data-in-out") +def post_data_in_out(body: DataInputOutput) -> DataInputOutput: + return body diff --git a/docs_src/metadata/__init__.py b/docs_src/metadata/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/metadata/tutorial001_1.py b/docs_src/metadata/tutorial001_1.py deleted file mode 100644 index a8f5b94588d9c..0000000000000 --- a/docs_src/metadata/tutorial001_1.py +++ /dev/null @@ -1,38 +0,0 @@ -from fastapi import FastAPI - -description = """ -ChimichangApp API helps you do awesome stuff. 🚀 - -## Items - -You can **read items**. - -## Users - -You will be able to: - -* **Create users** (_not implemented_). -* **Read users** (_not implemented_). -""" - -app = FastAPI( - title="ChimichangApp", - description=description, - summary="Deadpool's favorite app. Nuff said.", - version="0.0.1", - terms_of_service="http://example.com/terms/", - contact={ - "name": "Deadpoolio the Amazing", - "url": "http://x-force.example.com/contact/", - "email": "dp@x-force.example.com", - }, - license_info={ - "name": "Apache 2.0", - "identifier": "MIT", - }, -) - - -@app.get("/items/") -async def read_items(): - return [{"name": "Katana"}] diff --git a/docs_src/metadata/tutorial001_1_py310.py b/docs_src/metadata/tutorial001_1_py310.py new file mode 100644 index 0000000000000..419232d8616c9 --- /dev/null +++ b/docs_src/metadata/tutorial001_1_py310.py @@ -0,0 +1,38 @@ +from fastapi import FastAPI + +description = """ +ChimichangApp API helps you do awesome stuff. 🚀 + +## Items + +You can **read items**. + +## Users + +You will be able to: + +* **Create users** (_not implemented_). +* **Read users** (_not implemented_). +""" + +app = FastAPI( + title="ChimichangApp", + description=description, + summary="Deadpool's favorite app. Nuff said.", + version="0.0.1", + terms_of_service="http://example.com/terms/", + contact={ + "name": "Deadpoolio the Amazing", + "url": "http://x-force.example.com/contact/", + "email": "dp@x-force.example.com", + }, + license_info={ + "name": "Apache 2.0", + "identifier": "Apache-2.0", + }, +) + + +@app.get("/items/") +async def read_items(): + return [{"name": "Katana"}] diff --git a/docs_src/metadata/tutorial001.py b/docs_src/metadata/tutorial001_py310.py similarity index 100% rename from docs_src/metadata/tutorial001.py rename to docs_src/metadata/tutorial001_py310.py diff --git a/docs_src/metadata/tutorial002.py b/docs_src/metadata/tutorial002_py310.py similarity index 100% rename from docs_src/metadata/tutorial002.py rename to docs_src/metadata/tutorial002_py310.py diff --git a/docs_src/metadata/tutorial003.py b/docs_src/metadata/tutorial003_py310.py similarity index 100% rename from docs_src/metadata/tutorial003.py rename to docs_src/metadata/tutorial003_py310.py diff --git a/docs_src/metadata/tutorial004.py b/docs_src/metadata/tutorial004_py310.py similarity index 100% rename from docs_src/metadata/tutorial004.py rename to docs_src/metadata/tutorial004_py310.py diff --git a/docs_src/middleware/__init__.py b/docs_src/middleware/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/middleware/tutorial001.py b/docs_src/middleware/tutorial001.py deleted file mode 100644 index 6bab3410a6548..0000000000000 --- a/docs_src/middleware/tutorial001.py +++ /dev/null @@ -1,14 +0,0 @@ -import time - -from fastapi import FastAPI, Request - -app = FastAPI() - - -@app.middleware("http") -async def add_process_time_header(request: Request, call_next): - start_time = time.time() - response = await call_next(request) - process_time = time.time() - start_time - response.headers["X-Process-Time"] = str(process_time) - return response diff --git a/docs_src/middleware/tutorial001_py310.py b/docs_src/middleware/tutorial001_py310.py new file mode 100644 index 0000000000000..e65a7dade1791 --- /dev/null +++ b/docs_src/middleware/tutorial001_py310.py @@ -0,0 +1,14 @@ +import time + +from fastapi import FastAPI, Request + +app = FastAPI() + + +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.perf_counter() + response = await call_next(request) + process_time = time.perf_counter() - start_time + response.headers["X-Process-Time"] = str(process_time) + return response diff --git a/docs_src/nosql_databases/tutorial001.py b/docs_src/nosql_databases/tutorial001.py deleted file mode 100644 index 91893e52811d3..0000000000000 --- a/docs_src/nosql_databases/tutorial001.py +++ /dev/null @@ -1,53 +0,0 @@ -from typing import Union - -from couchbase import LOCKMODE_WAIT -from couchbase.bucket import Bucket -from couchbase.cluster import Cluster, PasswordAuthenticator -from fastapi import FastAPI -from pydantic import BaseModel - -USERPROFILE_DOC_TYPE = "userprofile" - - -def get_bucket(): - cluster = Cluster( - "couchbase://couchbasehost:8091?fetch_mutation_tokens=1&operation_timeout=30&n1ql_timeout=300" - ) - authenticator = PasswordAuthenticator("username", "password") - cluster.authenticate(authenticator) - bucket: Bucket = cluster.open_bucket("bucket_name", lockmode=LOCKMODE_WAIT) - bucket.timeout = 30 - bucket.n1ql_timeout = 300 - return bucket - - -class User(BaseModel): - username: str - email: Union[str, None] = None - full_name: Union[str, None] = None - disabled: Union[bool, None] = None - - -class UserInDB(User): - type: str = USERPROFILE_DOC_TYPE - hashed_password: str - - -def get_user(bucket: Bucket, username: str): - doc_id = f"userprofile::{username}" - result = bucket.get(doc_id, quiet=True) - if not result.value: - return None - user = UserInDB(**result.value) - return user - - -# FastAPI specific code -app = FastAPI() - - -@app.get("/users/{username}", response_model=User) -def read_user(username: str): - bucket = get_bucket() - user = get_user(bucket=bucket, username=username) - return user diff --git a/docs_src/openapi_callbacks/__init__.py b/docs_src/openapi_callbacks/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/openapi_callbacks/tutorial001.py b/docs_src/openapi_callbacks/tutorial001.py deleted file mode 100644 index 3f1bac6e29926..0000000000000 --- a/docs_src/openapi_callbacks/tutorial001.py +++ /dev/null @@ -1,53 +0,0 @@ -from typing import Union - -from fastapi import APIRouter, FastAPI -from pydantic import BaseModel, HttpUrl - -app = FastAPI() - - -class Invoice(BaseModel): - id: str - title: Union[str, None] = None - customer: str - total: float - - -class InvoiceEvent(BaseModel): - description: str - paid: bool - - -class InvoiceEventReceived(BaseModel): - ok: bool - - -invoices_callback_router = APIRouter() - - -@invoices_callback_router.post( - "{$callback_url}/invoices/{$request.body.id}", response_model=InvoiceEventReceived -) -def invoice_notification(body: InvoiceEvent): - pass - - -@app.post("/invoices/", callbacks=invoices_callback_router.routes) -def create_invoice(invoice: Invoice, callback_url: Union[HttpUrl, None] = None): - """ - Create an invoice. - - This will (let's imagine) let the API user (some external developer) create an - invoice. - - And this path operation will: - - * Send the invoice to the client. - * Collect the money from the client. - * Send a notification back to the API user (the external developer), as a callback. - * At this point is that the API will somehow send a POST request to the - external API with the notification of the invoice event - (e.g. "payment successful"). - """ - # Send the invoice, collect the money, send the notification (the callback) - return {"msg": "Invoice received"} diff --git a/docs_src/openapi_callbacks/tutorial001_py310.py b/docs_src/openapi_callbacks/tutorial001_py310.py new file mode 100644 index 0000000000000..3efe0ee25f347 --- /dev/null +++ b/docs_src/openapi_callbacks/tutorial001_py310.py @@ -0,0 +1,51 @@ +from fastapi import APIRouter, FastAPI +from pydantic import BaseModel, HttpUrl + +app = FastAPI() + + +class Invoice(BaseModel): + id: str + title: str | None = None + customer: str + total: float + + +class InvoiceEvent(BaseModel): + description: str + paid: bool + + +class InvoiceEventReceived(BaseModel): + ok: bool + + +invoices_callback_router = APIRouter() + + +@invoices_callback_router.post( + "{$callback_url}/invoices/{$request.body.id}", response_model=InvoiceEventReceived +) +def invoice_notification(body: InvoiceEvent): + pass + + +@app.post("/invoices/", callbacks=invoices_callback_router.routes) +def create_invoice(invoice: Invoice, callback_url: HttpUrl | None = None): + """ + Create an invoice. + + This will (let's imagine) let the API user (some external developer) create an + invoice. + + And this path operation will: + + * Send the invoice to the client. + * Collect the money from the client. + * Send a notification back to the API user (the external developer), as a callback. + * At this point is that the API will somehow send a POST request to the + external API with the notification of the invoice event + (e.g. "payment successful"). + """ + # Send the invoice, collect the money, send the notification (the callback) + return {"msg": "Invoice received"} diff --git a/docs_src/openapi_webhooks/__init__.py b/docs_src/openapi_webhooks/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/openapi_webhooks/tutorial001.py b/docs_src/openapi_webhooks/tutorial001.py deleted file mode 100644 index 5016f5b00fac3..0000000000000 --- a/docs_src/openapi_webhooks/tutorial001.py +++ /dev/null @@ -1,25 +0,0 @@ -from datetime import datetime - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Subscription(BaseModel): - username: str - montly_fee: float - start_date: datetime - - -@app.webhooks.post("new-subscription") -def new_subscription(body: Subscription): - """ - When a new user subscribes to your service we'll send you a POST request with this - data to the URL that you register for the event `new-subscription` in the dashboard. - """ - - -@app.get("/users/") -def read_users(): - return ["Rick", "Morty"] diff --git a/docs_src/openapi_webhooks/tutorial001_py310.py b/docs_src/openapi_webhooks/tutorial001_py310.py new file mode 100644 index 0000000000000..55822bb48f2ed --- /dev/null +++ b/docs_src/openapi_webhooks/tutorial001_py310.py @@ -0,0 +1,25 @@ +from datetime import datetime + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Subscription(BaseModel): + username: str + monthly_fee: float + start_date: datetime + + +@app.webhooks.post("new-subscription") +def new_subscription(body: Subscription): + """ + When a new user subscribes to your service we'll send you a POST request with this + data to the URL that you register for the event `new-subscription` in the dashboard. + """ + + +@app.get("/users/") +def read_users(): + return ["Rick", "Morty"] diff --git a/docs_src/path_operation_advanced_configuration/__init__.py b/docs_src/path_operation_advanced_configuration/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/path_operation_advanced_configuration/tutorial001.py b/docs_src/path_operation_advanced_configuration/tutorial001_py310.py similarity index 100% rename from docs_src/path_operation_advanced_configuration/tutorial001.py rename to docs_src/path_operation_advanced_configuration/tutorial001_py310.py diff --git a/docs_src/path_operation_advanced_configuration/tutorial002.py b/docs_src/path_operation_advanced_configuration/tutorial002_py310.py similarity index 100% rename from docs_src/path_operation_advanced_configuration/tutorial002.py rename to docs_src/path_operation_advanced_configuration/tutorial002_py310.py diff --git a/docs_src/path_operation_advanced_configuration/tutorial003.py b/docs_src/path_operation_advanced_configuration/tutorial003_py310.py similarity index 100% rename from docs_src/path_operation_advanced_configuration/tutorial003.py rename to docs_src/path_operation_advanced_configuration/tutorial003_py310.py diff --git a/docs_src/path_operation_advanced_configuration/tutorial004.py b/docs_src/path_operation_advanced_configuration/tutorial004.py deleted file mode 100644 index a3aad4ac4009e..0000000000000 --- a/docs_src/path_operation_advanced_configuration/tutorial004.py +++ /dev/null @@ -1,30 +0,0 @@ -from typing import Set, Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - tags: Set[str] = set() - - -@app.post("/items/", response_model=Item, summary="Create an item") -async def create_item(item: Item): - """ - Create an item with all the information: - - - **name**: each item must have a name - - **description**: a long description - - **price**: required - - **tax**: if the item doesn't have tax, you can omit this - - **tags**: a set of unique tag strings for this item - \f - :param item: User input. - """ - return item diff --git a/docs_src/path_operation_advanced_configuration/tutorial004_py310.py b/docs_src/path_operation_advanced_configuration/tutorial004_py310.py new file mode 100644 index 0000000000000..f222b11dc6e09 --- /dev/null +++ b/docs_src/path_operation_advanced_configuration/tutorial004_py310.py @@ -0,0 +1,28 @@ +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + description: str | None = None + price: float + tax: float | None = None + tags: set[str] = set() + + +@app.post("/items/", summary="Create an item") +async def create_item(item: Item) -> Item: + """ + Create an item with all the information: + + - **name**: each item must have a name + - **description**: a long description + - **price**: required + - **tax**: if the item doesn't have tax, you can omit this + - **tags**: a set of unique tag strings for this item + \f + :param item: User input. + """ + return item diff --git a/docs_src/path_operation_advanced_configuration/tutorial005.py b/docs_src/path_operation_advanced_configuration/tutorial005_py310.py similarity index 100% rename from docs_src/path_operation_advanced_configuration/tutorial005.py rename to docs_src/path_operation_advanced_configuration/tutorial005_py310.py diff --git a/docs_src/path_operation_advanced_configuration/tutorial006.py b/docs_src/path_operation_advanced_configuration/tutorial006_py310.py similarity index 100% rename from docs_src/path_operation_advanced_configuration/tutorial006.py rename to docs_src/path_operation_advanced_configuration/tutorial006_py310.py diff --git a/docs_src/path_operation_advanced_configuration/tutorial007.py b/docs_src/path_operation_advanced_configuration/tutorial007.py deleted file mode 100644 index 972ddbd2cc918..0000000000000 --- a/docs_src/path_operation_advanced_configuration/tutorial007.py +++ /dev/null @@ -1,34 +0,0 @@ -from typing import List - -import yaml -from fastapi import FastAPI, HTTPException, Request -from pydantic import BaseModel, ValidationError - -app = FastAPI() - - -class Item(BaseModel): - name: str - tags: List[str] - - -@app.post( - "/items/", - openapi_extra={ - "requestBody": { - "content": {"application/x-yaml": {"schema": Item.model_json_schema()}}, - "required": True, - }, - }, -) -async def create_item(request: Request): - raw_body = await request.body() - try: - data = yaml.safe_load(raw_body) - except yaml.YAMLError: - raise HTTPException(status_code=422, detail="Invalid YAML") - try: - item = Item.model_validate(data) - except ValidationError as e: - raise HTTPException(status_code=422, detail=e.errors()) - return item diff --git a/docs_src/path_operation_advanced_configuration/tutorial007_pv1.py b/docs_src/path_operation_advanced_configuration/tutorial007_pv1.py deleted file mode 100644 index d51752bb875cc..0000000000000 --- a/docs_src/path_operation_advanced_configuration/tutorial007_pv1.py +++ /dev/null @@ -1,34 +0,0 @@ -from typing import List - -import yaml -from fastapi import FastAPI, HTTPException, Request -from pydantic import BaseModel, ValidationError - -app = FastAPI() - - -class Item(BaseModel): - name: str - tags: List[str] - - -@app.post( - "/items/", - openapi_extra={ - "requestBody": { - "content": {"application/x-yaml": {"schema": Item.schema()}}, - "required": True, - }, - }, -) -async def create_item(request: Request): - raw_body = await request.body() - try: - data = yaml.safe_load(raw_body) - except yaml.YAMLError: - raise HTTPException(status_code=422, detail="Invalid YAML") - try: - item = Item.parse_obj(data) - except ValidationError as e: - raise HTTPException(status_code=422, detail=e.errors()) - return item diff --git a/docs_src/path_operation_advanced_configuration/tutorial007_py310.py b/docs_src/path_operation_advanced_configuration/tutorial007_py310.py new file mode 100644 index 0000000000000..ff64ef7923235 --- /dev/null +++ b/docs_src/path_operation_advanced_configuration/tutorial007_py310.py @@ -0,0 +1,32 @@ +import yaml +from fastapi import FastAPI, HTTPException, Request +from pydantic import BaseModel, ValidationError + +app = FastAPI() + + +class Item(BaseModel): + name: str + tags: list[str] + + +@app.post( + "/items/", + openapi_extra={ + "requestBody": { + "content": {"application/x-yaml": {"schema": Item.model_json_schema()}}, + "required": True, + }, + }, +) +async def create_item(request: Request): + raw_body = await request.body() + try: + data = yaml.safe_load(raw_body) + except yaml.YAMLError: + raise HTTPException(status_code=422, detail="Invalid YAML") + try: + item = Item.model_validate(data) + except ValidationError as e: + raise HTTPException(status_code=422, detail=e.errors(include_url=False)) + return item diff --git a/docs_src/path_operation_configuration/__init__.py b/docs_src/path_operation_configuration/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/path_operation_configuration/tutorial001.py b/docs_src/path_operation_configuration/tutorial001.py deleted file mode 100644 index 83fd8377ab7c9..0000000000000 --- a/docs_src/path_operation_configuration/tutorial001.py +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Set, Union - -from fastapi import FastAPI, status -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - tags: Set[str] = set() - - -@app.post("/items/", response_model=Item, status_code=status.HTTP_201_CREATED) -async def create_item(item: Item): - return item diff --git a/docs_src/path_operation_configuration/tutorial001_py310.py b/docs_src/path_operation_configuration/tutorial001_py310.py index da078fdf582fe..2e7488ea4f903 100644 --- a/docs_src/path_operation_configuration/tutorial001_py310.py +++ b/docs_src/path_operation_configuration/tutorial001_py310.py @@ -12,6 +12,6 @@ class Item(BaseModel): tags: set[str] = set() -@app.post("/items/", response_model=Item, status_code=status.HTTP_201_CREATED) -async def create_item(item: Item): +@app.post("/items/", status_code=status.HTTP_201_CREATED) +async def create_item(item: Item) -> Item: return item diff --git a/docs_src/path_operation_configuration/tutorial001_py39.py b/docs_src/path_operation_configuration/tutorial001_py39.py deleted file mode 100644 index a9dcbf3898b9d..0000000000000 --- a/docs_src/path_operation_configuration/tutorial001_py39.py +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, status -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - tags: set[str] = set() - - -@app.post("/items/", response_model=Item, status_code=status.HTTP_201_CREATED) -async def create_item(item: Item): - return item diff --git a/docs_src/path_operation_configuration/tutorial002.py b/docs_src/path_operation_configuration/tutorial002.py deleted file mode 100644 index 798b0c23115a3..0000000000000 --- a/docs_src/path_operation_configuration/tutorial002.py +++ /dev/null @@ -1,29 +0,0 @@ -from typing import Set, Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - tags: Set[str] = set() - - -@app.post("/items/", response_model=Item, tags=["items"]) -async def create_item(item: Item): - return item - - -@app.get("/items/", tags=["items"]) -async def read_items(): - return [{"name": "Foo", "price": 42}] - - -@app.get("/users/", tags=["users"]) -async def read_users(): - return [{"username": "johndoe"}] diff --git a/docs_src/path_operation_configuration/tutorial002_py310.py b/docs_src/path_operation_configuration/tutorial002_py310.py index 9a8af543276fe..59908ed7c8c03 100644 --- a/docs_src/path_operation_configuration/tutorial002_py310.py +++ b/docs_src/path_operation_configuration/tutorial002_py310.py @@ -12,8 +12,8 @@ class Item(BaseModel): tags: set[str] = set() -@app.post("/items/", response_model=Item, tags=["items"]) -async def create_item(item: Item): +@app.post("/items/", tags=["items"]) +async def create_item(item: Item) -> Item: return item diff --git a/docs_src/path_operation_configuration/tutorial002_py39.py b/docs_src/path_operation_configuration/tutorial002_py39.py deleted file mode 100644 index e7ced7de7e6a1..0000000000000 --- a/docs_src/path_operation_configuration/tutorial002_py39.py +++ /dev/null @@ -1,29 +0,0 @@ -from typing import Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - tags: set[str] = set() - - -@app.post("/items/", response_model=Item, tags=["items"]) -async def create_item(item: Item): - return item - - -@app.get("/items/", tags=["items"]) -async def read_items(): - return [{"name": "Foo", "price": 42}] - - -@app.get("/users/", tags=["users"]) -async def read_users(): - return [{"username": "johndoe"}] diff --git a/docs_src/path_operation_configuration/tutorial002b.py b/docs_src/path_operation_configuration/tutorial002b_py310.py similarity index 100% rename from docs_src/path_operation_configuration/tutorial002b.py rename to docs_src/path_operation_configuration/tutorial002b_py310.py diff --git a/docs_src/path_operation_configuration/tutorial003.py b/docs_src/path_operation_configuration/tutorial003.py deleted file mode 100644 index 26bf7dabae202..0000000000000 --- a/docs_src/path_operation_configuration/tutorial003.py +++ /dev/null @@ -1,24 +0,0 @@ -from typing import Set, Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - tags: Set[str] = set() - - -@app.post( - "/items/", - response_model=Item, - summary="Create an item", - description="Create an item with all the information, name, description, price, tax and a set of unique tags", -) -async def create_item(item: Item): - return item diff --git a/docs_src/path_operation_configuration/tutorial003_py310.py b/docs_src/path_operation_configuration/tutorial003_py310.py index 3d94afe2c054f..56bd7e36aacac 100644 --- a/docs_src/path_operation_configuration/tutorial003_py310.py +++ b/docs_src/path_operation_configuration/tutorial003_py310.py @@ -14,9 +14,8 @@ class Item(BaseModel): @app.post( "/items/", - response_model=Item, summary="Create an item", description="Create an item with all the information, name, description, price, tax and a set of unique tags", ) -async def create_item(item: Item): +async def create_item(item: Item) -> Item: return item diff --git a/docs_src/path_operation_configuration/tutorial003_py39.py b/docs_src/path_operation_configuration/tutorial003_py39.py deleted file mode 100644 index 607c5707e6e30..0000000000000 --- a/docs_src/path_operation_configuration/tutorial003_py39.py +++ /dev/null @@ -1,24 +0,0 @@ -from typing import Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - tags: set[str] = set() - - -@app.post( - "/items/", - response_model=Item, - summary="Create an item", - description="Create an item with all the information, name, description, price, tax and a set of unique tags", -) -async def create_item(item: Item): - return item diff --git a/docs_src/path_operation_configuration/tutorial004.py b/docs_src/path_operation_configuration/tutorial004.py deleted file mode 100644 index 8f865c58a6ad0..0000000000000 --- a/docs_src/path_operation_configuration/tutorial004.py +++ /dev/null @@ -1,28 +0,0 @@ -from typing import Set, Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - tags: Set[str] = set() - - -@app.post("/items/", response_model=Item, summary="Create an item") -async def create_item(item: Item): - """ - Create an item with all the information: - - - **name**: each item must have a name - - **description**: a long description - - **price**: required - - **tax**: if the item doesn't have tax, you can omit this - - **tags**: a set of unique tag strings for this item - """ - return item diff --git a/docs_src/path_operation_configuration/tutorial004_py310.py b/docs_src/path_operation_configuration/tutorial004_py310.py index 4cb8bdd438ab1..44404aa0836e7 100644 --- a/docs_src/path_operation_configuration/tutorial004_py310.py +++ b/docs_src/path_operation_configuration/tutorial004_py310.py @@ -12,8 +12,8 @@ class Item(BaseModel): tags: set[str] = set() -@app.post("/items/", response_model=Item, summary="Create an item") -async def create_item(item: Item): +@app.post("/items/", summary="Create an item") +async def create_item(item: Item) -> Item: """ Create an item with all the information: diff --git a/docs_src/path_operation_configuration/tutorial004_py39.py b/docs_src/path_operation_configuration/tutorial004_py39.py deleted file mode 100644 index fc25680c5a3d6..0000000000000 --- a/docs_src/path_operation_configuration/tutorial004_py39.py +++ /dev/null @@ -1,28 +0,0 @@ -from typing import Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - tags: set[str] = set() - - -@app.post("/items/", response_model=Item, summary="Create an item") -async def create_item(item: Item): - """ - Create an item with all the information: - - - **name**: each item must have a name - - **description**: a long description - - **price**: required - - **tax**: if the item doesn't have tax, you can omit this - - **tags**: a set of unique tag strings for this item - """ - return item diff --git a/docs_src/path_operation_configuration/tutorial005.py b/docs_src/path_operation_configuration/tutorial005.py deleted file mode 100644 index 2c1be4a34bcc7..0000000000000 --- a/docs_src/path_operation_configuration/tutorial005.py +++ /dev/null @@ -1,33 +0,0 @@ -from typing import Set, Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - tags: Set[str] = set() - - -@app.post( - "/items/", - response_model=Item, - summary="Create an item", - response_description="The created item", -) -async def create_item(item: Item): - """ - Create an item with all the information: - - - **name**: each item must have a name - - **description**: a long description - - **price**: required - - **tax**: if the item doesn't have tax, you can omit this - - **tags**: a set of unique tag strings for this item - """ - return item diff --git a/docs_src/path_operation_configuration/tutorial005_py310.py b/docs_src/path_operation_configuration/tutorial005_py310.py index b176631d846bb..a4129d600a31f 100644 --- a/docs_src/path_operation_configuration/tutorial005_py310.py +++ b/docs_src/path_operation_configuration/tutorial005_py310.py @@ -14,11 +14,10 @@ class Item(BaseModel): @app.post( "/items/", - response_model=Item, summary="Create an item", response_description="The created item", ) -async def create_item(item: Item): +async def create_item(item: Item) -> Item: """ Create an item with all the information: diff --git a/docs_src/path_operation_configuration/tutorial005_py39.py b/docs_src/path_operation_configuration/tutorial005_py39.py deleted file mode 100644 index ddf29b733d07c..0000000000000 --- a/docs_src/path_operation_configuration/tutorial005_py39.py +++ /dev/null @@ -1,33 +0,0 @@ -from typing import Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - tags: set[str] = set() - - -@app.post( - "/items/", - response_model=Item, - summary="Create an item", - response_description="The created item", -) -async def create_item(item: Item): - """ - Create an item with all the information: - - - **name**: each item must have a name - - **description**: a long description - - **price**: required - - **tax**: if the item doesn't have tax, you can omit this - - **tags**: a set of unique tag strings for this item - """ - return item diff --git a/docs_src/path_operation_configuration/tutorial006.py b/docs_src/path_operation_configuration/tutorial006_py310.py similarity index 100% rename from docs_src/path_operation_configuration/tutorial006.py rename to docs_src/path_operation_configuration/tutorial006_py310.py diff --git a/docs_src/path_params/__init__.py b/docs_src/path_params/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/path_params/tutorial001.py b/docs_src/path_params/tutorial001_py310.py similarity index 100% rename from docs_src/path_params/tutorial001.py rename to docs_src/path_params/tutorial001_py310.py diff --git a/docs_src/path_params/tutorial002.py b/docs_src/path_params/tutorial002_py310.py similarity index 100% rename from docs_src/path_params/tutorial002.py rename to docs_src/path_params/tutorial002_py310.py diff --git a/docs_src/path_params/tutorial003.py b/docs_src/path_params/tutorial003_py310.py similarity index 100% rename from docs_src/path_params/tutorial003.py rename to docs_src/path_params/tutorial003_py310.py diff --git a/docs_src/path_params/tutorial003b.py b/docs_src/path_params/tutorial003b_py310.py similarity index 100% rename from docs_src/path_params/tutorial003b.py rename to docs_src/path_params/tutorial003b_py310.py diff --git a/docs_src/path_params/tutorial004.py b/docs_src/path_params/tutorial004_py310.py similarity index 100% rename from docs_src/path_params/tutorial004.py rename to docs_src/path_params/tutorial004_py310.py diff --git a/docs_src/path_params/tutorial005.py b/docs_src/path_params/tutorial005_py310.py similarity index 100% rename from docs_src/path_params/tutorial005.py rename to docs_src/path_params/tutorial005_py310.py diff --git a/docs_src/path_params_numeric_validations/__init__.py b/docs_src/path_params_numeric_validations/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/path_params_numeric_validations/tutorial001.py b/docs_src/path_params_numeric_validations/tutorial001.py deleted file mode 100644 index 53014702826e3..0000000000000 --- a/docs_src/path_params_numeric_validations/tutorial001.py +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Path, Query - -app = FastAPI() - - -@app.get("/items/{item_id}") -async def read_items( - item_id: int = Path(title="The ID of the item to get"), - q: Union[str, None] = Query(default=None, alias="item-query"), -): - results = {"item_id": item_id} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/path_params_numeric_validations/tutorial001_an.py b/docs_src/path_params_numeric_validations/tutorial001_an.py deleted file mode 100644 index 621be7b04535c..0000000000000 --- a/docs_src/path_params_numeric_validations/tutorial001_an.py +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Path, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/{item_id}") -async def read_items( - item_id: Annotated[int, Path(title="The ID of the item to get")], - q: Annotated[Union[str, None], Query(alias="item-query")] = None, -): - results = {"item_id": item_id} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/path_params_numeric_validations/tutorial001_an_py39.py b/docs_src/path_params_numeric_validations/tutorial001_an_py39.py deleted file mode 100644 index b36315a46dd8e..0000000000000 --- a/docs_src/path_params_numeric_validations/tutorial001_an_py39.py +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Annotated, Union - -from fastapi import FastAPI, Path, Query - -app = FastAPI() - - -@app.get("/items/{item_id}") -async def read_items( - item_id: Annotated[int, Path(title="The ID of the item to get")], - q: Annotated[Union[str, None], Query(alias="item-query")] = None, -): - results = {"item_id": item_id} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/path_params_numeric_validations/tutorial002_an.py b/docs_src/path_params_numeric_validations/tutorial002_an.py deleted file mode 100644 index 322f8cf0bb07f..0000000000000 --- a/docs_src/path_params_numeric_validations/tutorial002_an.py +++ /dev/null @@ -1,14 +0,0 @@ -from fastapi import FastAPI, Path -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/{item_id}") -async def read_items( - q: str, item_id: Annotated[int, Path(title="The ID of the item to get")] -): - results = {"item_id": item_id} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/path_params_numeric_validations/tutorial002_an_py39.py b/docs_src/path_params_numeric_validations/tutorial002_an_py310.py similarity index 100% rename from docs_src/path_params_numeric_validations/tutorial002_an_py39.py rename to docs_src/path_params_numeric_validations/tutorial002_an_py310.py diff --git a/docs_src/path_params_numeric_validations/tutorial002.py b/docs_src/path_params_numeric_validations/tutorial002_py310.py similarity index 100% rename from docs_src/path_params_numeric_validations/tutorial002.py rename to docs_src/path_params_numeric_validations/tutorial002_py310.py diff --git a/docs_src/path_params_numeric_validations/tutorial003_an.py b/docs_src/path_params_numeric_validations/tutorial003_an.py deleted file mode 100644 index d0fa8b3db9517..0000000000000 --- a/docs_src/path_params_numeric_validations/tutorial003_an.py +++ /dev/null @@ -1,14 +0,0 @@ -from fastapi import FastAPI, Path -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/{item_id}") -async def read_items( - item_id: Annotated[int, Path(title="The ID of the item to get")], q: str -): - results = {"item_id": item_id} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/path_params_numeric_validations/tutorial003_an_py39.py b/docs_src/path_params_numeric_validations/tutorial003_an_py310.py similarity index 100% rename from docs_src/path_params_numeric_validations/tutorial003_an_py39.py rename to docs_src/path_params_numeric_validations/tutorial003_an_py310.py diff --git a/docs_src/path_params_numeric_validations/tutorial003.py b/docs_src/path_params_numeric_validations/tutorial003_py310.py similarity index 100% rename from docs_src/path_params_numeric_validations/tutorial003.py rename to docs_src/path_params_numeric_validations/tutorial003_py310.py diff --git a/docs_src/path_params_numeric_validations/tutorial004_an.py b/docs_src/path_params_numeric_validations/tutorial004_an.py deleted file mode 100644 index ffc50f6c5b930..0000000000000 --- a/docs_src/path_params_numeric_validations/tutorial004_an.py +++ /dev/null @@ -1,14 +0,0 @@ -from fastapi import FastAPI, Path -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/{item_id}") -async def read_items( - item_id: Annotated[int, Path(title="The ID of the item to get", ge=1)], q: str -): - results = {"item_id": item_id} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/path_params_numeric_validations/tutorial004_an_py39.py b/docs_src/path_params_numeric_validations/tutorial004_an_py310.py similarity index 100% rename from docs_src/path_params_numeric_validations/tutorial004_an_py39.py rename to docs_src/path_params_numeric_validations/tutorial004_an_py310.py diff --git a/docs_src/path_params_numeric_validations/tutorial004.py b/docs_src/path_params_numeric_validations/tutorial004_py310.py similarity index 100% rename from docs_src/path_params_numeric_validations/tutorial004.py rename to docs_src/path_params_numeric_validations/tutorial004_py310.py diff --git a/docs_src/path_params_numeric_validations/tutorial005_an.py b/docs_src/path_params_numeric_validations/tutorial005_an.py deleted file mode 100644 index 433c69129fde9..0000000000000 --- a/docs_src/path_params_numeric_validations/tutorial005_an.py +++ /dev/null @@ -1,15 +0,0 @@ -from fastapi import FastAPI, Path -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/{item_id}") -async def read_items( - item_id: Annotated[int, Path(title="The ID of the item to get", gt=0, le=1000)], - q: str, -): - results = {"item_id": item_id} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/path_params_numeric_validations/tutorial005_an_py39.py b/docs_src/path_params_numeric_validations/tutorial005_an_py310.py similarity index 100% rename from docs_src/path_params_numeric_validations/tutorial005_an_py39.py rename to docs_src/path_params_numeric_validations/tutorial005_an_py310.py diff --git a/docs_src/path_params_numeric_validations/tutorial005.py b/docs_src/path_params_numeric_validations/tutorial005_py310.py similarity index 100% rename from docs_src/path_params_numeric_validations/tutorial005.py rename to docs_src/path_params_numeric_validations/tutorial005_py310.py diff --git a/docs_src/path_params_numeric_validations/tutorial006.py b/docs_src/path_params_numeric_validations/tutorial006.py deleted file mode 100644 index 0ea32694ae54b..0000000000000 --- a/docs_src/path_params_numeric_validations/tutorial006.py +++ /dev/null @@ -1,16 +0,0 @@ -from fastapi import FastAPI, Path, Query - -app = FastAPI() - - -@app.get("/items/{item_id}") -async def read_items( - *, - item_id: int = Path(title="The ID of the item to get", ge=0, le=1000), - q: str, - size: float = Query(gt=0, lt=10.5), -): - results = {"item_id": item_id} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/path_params_numeric_validations/tutorial006_an.py b/docs_src/path_params_numeric_validations/tutorial006_an.py deleted file mode 100644 index 22a1436236310..0000000000000 --- a/docs_src/path_params_numeric_validations/tutorial006_an.py +++ /dev/null @@ -1,17 +0,0 @@ -from fastapi import FastAPI, Path, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/{item_id}") -async def read_items( - *, - item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)], - q: str, - size: Annotated[float, Query(gt=0, lt=10.5)], -): - results = {"item_id": item_id} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/path_params_numeric_validations/tutorial006_an_py310.py b/docs_src/path_params_numeric_validations/tutorial006_an_py310.py new file mode 100644 index 0000000000000..426ec3776446b --- /dev/null +++ b/docs_src/path_params_numeric_validations/tutorial006_an_py310.py @@ -0,0 +1,20 @@ +from typing import Annotated + +from fastapi import FastAPI, Path, Query + +app = FastAPI() + + +@app.get("/items/{item_id}") +async def read_items( + *, + item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)], + q: str, + size: Annotated[float, Query(gt=0, lt=10.5)], +): + results = {"item_id": item_id} + if q: + results.update({"q": q}) + if size: + results.update({"size": size}) + return results diff --git a/docs_src/path_params_numeric_validations/tutorial006_an_py39.py b/docs_src/path_params_numeric_validations/tutorial006_an_py39.py deleted file mode 100644 index 804751893c64d..0000000000000 --- a/docs_src/path_params_numeric_validations/tutorial006_an_py39.py +++ /dev/null @@ -1,18 +0,0 @@ -from typing import Annotated - -from fastapi import FastAPI, Path, Query - -app = FastAPI() - - -@app.get("/items/{item_id}") -async def read_items( - *, - item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)], - q: str, - size: Annotated[float, Query(gt=0, lt=10.5)], -): - results = {"item_id": item_id} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/path_params_numeric_validations/tutorial006_py310.py b/docs_src/path_params_numeric_validations/tutorial006_py310.py new file mode 100644 index 0000000000000..f07629aa0ae03 --- /dev/null +++ b/docs_src/path_params_numeric_validations/tutorial006_py310.py @@ -0,0 +1,18 @@ +from fastapi import FastAPI, Path, Query + +app = FastAPI() + + +@app.get("/items/{item_id}") +async def read_items( + *, + item_id: int = Path(title="The ID of the item to get", ge=0, le=1000), + q: str, + size: float = Query(gt=0, lt=10.5), +): + results = {"item_id": item_id} + if q: + results.update({"q": q}) + if size: + results.update({"size": size}) + return results diff --git a/docs_src/pydantic_v1_in_v2/__init__.py b/docs_src/pydantic_v1_in_v2/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py b/docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py new file mode 100644 index 0000000000000..a8ec729b3268a --- /dev/null +++ b/docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py @@ -0,0 +1,7 @@ +from pydantic.v1 import BaseModel + + +class Item(BaseModel): + name: str + description: str | None = None + size: float diff --git a/docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py b/docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py new file mode 100644 index 0000000000000..4934e70041deb --- /dev/null +++ b/docs_src/pydantic_v1_in_v2/tutorial002_an_py310.py @@ -0,0 +1,16 @@ +from fastapi import FastAPI +from pydantic.v1 import BaseModel + + +class Item(BaseModel): + name: str + description: str | None = None + size: float + + +app = FastAPI() + + +@app.post("/items/") +async def create_item(item: Item) -> Item: + return item diff --git a/docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py b/docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py new file mode 100644 index 0000000000000..6e3013644c70b --- /dev/null +++ b/docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py @@ -0,0 +1,23 @@ +from fastapi import FastAPI +from pydantic import BaseModel as BaseModelV2 +from pydantic.v1 import BaseModel + + +class Item(BaseModel): + name: str + description: str | None = None + size: float + + +class ItemV2(BaseModelV2): + name: str + description: str | None = None + size: float + + +app = FastAPI() + + +@app.post("/items/", response_model=ItemV2) +async def create_item(item: Item): + return item diff --git a/docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py b/docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py new file mode 100644 index 0000000000000..c251311e0b44d --- /dev/null +++ b/docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py @@ -0,0 +1,19 @@ +from typing import Annotated + +from fastapi import FastAPI +from fastapi.temp_pydantic_v1_params import Body +from pydantic.v1 import BaseModel + + +class Item(BaseModel): + name: str + description: str | None = None + size: float + + +app = FastAPI() + + +@app.post("/items/") +async def create_item(item: Annotated[Item, Body(embed=True)]) -> Item: + return item diff --git a/docs_src/python_types/__init__.py b/docs_src/python_types/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/python_types/tutorial001.py b/docs_src/python_types/tutorial001_py310.py similarity index 100% rename from docs_src/python_types/tutorial001.py rename to docs_src/python_types/tutorial001_py310.py diff --git a/docs_src/python_types/tutorial002.py b/docs_src/python_types/tutorial002_py310.py similarity index 100% rename from docs_src/python_types/tutorial002.py rename to docs_src/python_types/tutorial002_py310.py diff --git a/docs_src/python_types/tutorial003.py b/docs_src/python_types/tutorial003_py310.py similarity index 100% rename from docs_src/python_types/tutorial003.py rename to docs_src/python_types/tutorial003_py310.py diff --git a/docs_src/python_types/tutorial004.py b/docs_src/python_types/tutorial004_py310.py similarity index 100% rename from docs_src/python_types/tutorial004.py rename to docs_src/python_types/tutorial004_py310.py diff --git a/docs_src/python_types/tutorial005.py b/docs_src/python_types/tutorial005.py deleted file mode 100644 index 08ab44a941b91..0000000000000 --- a/docs_src/python_types/tutorial005.py +++ /dev/null @@ -1,2 +0,0 @@ -def get_items(item_a: str, item_b: int, item_c: float, item_d: bool, item_e: bytes): - return item_a, item_b, item_c, item_d, item_d, item_e diff --git a/docs_src/python_types/tutorial005_py310.py b/docs_src/python_types/tutorial005_py310.py new file mode 100644 index 0000000000000..6c8edb0ec4848 --- /dev/null +++ b/docs_src/python_types/tutorial005_py310.py @@ -0,0 +1,2 @@ +def get_items(item_a: str, item_b: int, item_c: float, item_d: bool, item_e: bytes): + return item_a, item_b, item_c, item_d, item_e diff --git a/docs_src/python_types/tutorial006.py b/docs_src/python_types/tutorial006.py deleted file mode 100644 index 87394ecb0c8fb..0000000000000 --- a/docs_src/python_types/tutorial006.py +++ /dev/null @@ -1,6 +0,0 @@ -from typing import List - - -def process_items(items: List[str]): - for item in items: - print(item) diff --git a/docs_src/python_types/tutorial006_py39.py b/docs_src/python_types/tutorial006_py310.py similarity index 100% rename from docs_src/python_types/tutorial006_py39.py rename to docs_src/python_types/tutorial006_py310.py diff --git a/docs_src/python_types/tutorial007.py b/docs_src/python_types/tutorial007.py deleted file mode 100644 index 5b13f15494a8d..0000000000000 --- a/docs_src/python_types/tutorial007.py +++ /dev/null @@ -1,5 +0,0 @@ -from typing import Set, Tuple - - -def process_items(items_t: Tuple[int, int, str], items_s: Set[bytes]): - return items_t, items_s diff --git a/docs_src/python_types/tutorial007_py39.py b/docs_src/python_types/tutorial007_py310.py similarity index 100% rename from docs_src/python_types/tutorial007_py39.py rename to docs_src/python_types/tutorial007_py310.py diff --git a/docs_src/python_types/tutorial008.py b/docs_src/python_types/tutorial008.py deleted file mode 100644 index 9fb1043bb88b5..0000000000000 --- a/docs_src/python_types/tutorial008.py +++ /dev/null @@ -1,7 +0,0 @@ -from typing import Dict - - -def process_items(prices: Dict[str, float]): - for item_name, item_price in prices.items(): - print(item_name) - print(item_price) diff --git a/docs_src/python_types/tutorial008_py39.py b/docs_src/python_types/tutorial008_py310.py similarity index 100% rename from docs_src/python_types/tutorial008_py39.py rename to docs_src/python_types/tutorial008_py310.py diff --git a/docs_src/python_types/tutorial008b.py b/docs_src/python_types/tutorial008b.py deleted file mode 100644 index e52539ead0ac4..0000000000000 --- a/docs_src/python_types/tutorial008b.py +++ /dev/null @@ -1,5 +0,0 @@ -from typing import Union - - -def process_item(item: Union[int, str]): - print(item) diff --git a/docs_src/python_types/tutorial009.py b/docs_src/python_types/tutorial009.py deleted file mode 100644 index 6328a1495c858..0000000000000 --- a/docs_src/python_types/tutorial009.py +++ /dev/null @@ -1,8 +0,0 @@ -from typing import Optional - - -def say_hi(name: Optional[str] = None): - if name is not None: - print(f"Hey {name}!") - else: - print("Hello World") diff --git a/docs_src/python_types/tutorial009b.py b/docs_src/python_types/tutorial009b.py deleted file mode 100644 index 9f1a05bc0f011..0000000000000 --- a/docs_src/python_types/tutorial009b.py +++ /dev/null @@ -1,8 +0,0 @@ -from typing import Union - - -def say_hi(name: Union[str, None] = None): - if name is not None: - print(f"Hey {name}!") - else: - print("Hello World") diff --git a/docs_src/python_types/tutorial009c.py b/docs_src/python_types/tutorial009c.py deleted file mode 100644 index 2f539a34b18f6..0000000000000 --- a/docs_src/python_types/tutorial009c.py +++ /dev/null @@ -1,5 +0,0 @@ -from typing import Optional - - -def say_hi(name: Optional[str]): - print(f"Hey {name}!") diff --git a/docs_src/python_types/tutorial009c_py310.py b/docs_src/python_types/tutorial009c_py310.py deleted file mode 100644 index 96b1220fcc7b8..0000000000000 --- a/docs_src/python_types/tutorial009c_py310.py +++ /dev/null @@ -1,2 +0,0 @@ -def say_hi(name: str | None): - print(f"Hey {name}!") diff --git a/docs_src/python_types/tutorial010.py b/docs_src/python_types/tutorial010_py310.py similarity index 100% rename from docs_src/python_types/tutorial010.py rename to docs_src/python_types/tutorial010_py310.py diff --git a/docs_src/python_types/tutorial011.py b/docs_src/python_types/tutorial011.py deleted file mode 100644 index 297a84db68ca0..0000000000000 --- a/docs_src/python_types/tutorial011.py +++ /dev/null @@ -1,23 +0,0 @@ -from datetime import datetime -from typing import List, Union - -from pydantic import BaseModel - - -class User(BaseModel): - id: int - name: str = "John Doe" - signup_ts: Union[datetime, None] = None - friends: List[int] = [] - - -external_data = { - "id": "123", - "signup_ts": "2017-06-01 12:22", - "friends": [1, "2", b"3"], -} -user = User(**external_data) -print(user) -# > User id=123 name='John Doe' signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3] -print(user.id) -# > 123 diff --git a/docs_src/python_types/tutorial011_py39.py b/docs_src/python_types/tutorial011_py39.py deleted file mode 100644 index 4eb40b405fe50..0000000000000 --- a/docs_src/python_types/tutorial011_py39.py +++ /dev/null @@ -1,23 +0,0 @@ -from datetime import datetime -from typing import Union - -from pydantic import BaseModel - - -class User(BaseModel): - id: int - name: str = "John Doe" - signup_ts: Union[datetime, None] = None - friends: list[int] = [] - - -external_data = { - "id": "123", - "signup_ts": "2017-06-01 12:22", - "friends": [1, "2", b"3"], -} -user = User(**external_data) -print(user) -# > User id=123 name='John Doe' signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3] -print(user.id) -# > 123 diff --git a/docs_src/python_types/tutorial012.py b/docs_src/python_types/tutorial012.py deleted file mode 100644 index 74fa94c432d1f..0000000000000 --- a/docs_src/python_types/tutorial012.py +++ /dev/null @@ -1,8 +0,0 @@ -from typing import Optional - -from pydantic import BaseModel - - -class User(BaseModel): - name: str - age: Optional[int] diff --git a/docs_src/python_types/tutorial013.py b/docs_src/python_types/tutorial013.py deleted file mode 100644 index 0ec7735199f02..0000000000000 --- a/docs_src/python_types/tutorial013.py +++ /dev/null @@ -1,5 +0,0 @@ -from typing_extensions import Annotated - - -def say_hello(name: Annotated[str, "this is just metadata"]) -> str: - return f"Hello {name}" diff --git a/docs_src/python_types/tutorial013_py39.py b/docs_src/python_types/tutorial013_py310.py similarity index 100% rename from docs_src/python_types/tutorial013_py39.py rename to docs_src/python_types/tutorial013_py310.py diff --git a/docs_src/query_param_models/__init__.py b/docs_src/query_param_models/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/query_param_models/tutorial001_an_py310.py b/docs_src/query_param_models/tutorial001_an_py310.py new file mode 100644 index 0000000000000..71427acae12ee --- /dev/null +++ b/docs_src/query_param_models/tutorial001_an_py310.py @@ -0,0 +1,18 @@ +from typing import Annotated, Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial001_py310.py b/docs_src/query_param_models/tutorial001_py310.py new file mode 100644 index 0000000000000..3ebf9f4d7000b --- /dev/null +++ b/docs_src/query_param_models/tutorial001_py310.py @@ -0,0 +1,18 @@ +from typing import Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_an_py310.py b/docs_src/query_param_models/tutorial002_an_py310.py new file mode 100644 index 0000000000000..97595650234dd --- /dev/null +++ b/docs_src/query_param_models/tutorial002_an_py310.py @@ -0,0 +1,20 @@ +from typing import Annotated, Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_py310.py b/docs_src/query_param_models/tutorial002_py310.py new file mode 100644 index 0000000000000..6ec418499136e --- /dev/null +++ b/docs_src/query_param_models/tutorial002_py310.py @@ -0,0 +1,20 @@ +from typing import Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_params/__init__.py b/docs_src/query_params/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/query_params/tutorial001.py b/docs_src/query_params/tutorial001_py310.py similarity index 100% rename from docs_src/query_params/tutorial001.py rename to docs_src/query_params/tutorial001_py310.py diff --git a/docs_src/query_params/tutorial002.py b/docs_src/query_params/tutorial002.py deleted file mode 100644 index 8465f45eedf16..0000000000000 --- a/docs_src/query_params/tutorial002.py +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Union - -from fastapi import FastAPI - -app = FastAPI() - - -@app.get("/items/{item_id}") -async def read_item(item_id: str, q: Union[str, None] = None): - if q: - return {"item_id": item_id, "q": q} - return {"item_id": item_id} diff --git a/docs_src/query_params/tutorial003.py b/docs_src/query_params/tutorial003.py deleted file mode 100644 index 3362715b39702..0000000000000 --- a/docs_src/query_params/tutorial003.py +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Union - -from fastapi import FastAPI - -app = FastAPI() - - -@app.get("/items/{item_id}") -async def read_item(item_id: str, q: Union[str, None] = None, short: bool = False): - item = {"item_id": item_id} - if q: - item.update({"q": q}) - if not short: - item.update( - {"description": "This is an amazing item that has a long description"} - ) - return item diff --git a/docs_src/query_params/tutorial004.py b/docs_src/query_params/tutorial004.py deleted file mode 100644 index 049c3ae934d62..0000000000000 --- a/docs_src/query_params/tutorial004.py +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Union - -from fastapi import FastAPI - -app = FastAPI() - - -@app.get("/users/{user_id}/items/{item_id}") -async def read_user_item( - user_id: int, item_id: str, q: Union[str, None] = None, short: bool = False -): - item = {"item_id": item_id, "owner_id": user_id} - if q: - item.update({"q": q}) - if not short: - item.update( - {"description": "This is an amazing item that has a long description"} - ) - return item diff --git a/docs_src/query_params/tutorial005.py b/docs_src/query_params/tutorial005_py310.py similarity index 100% rename from docs_src/query_params/tutorial005.py rename to docs_src/query_params/tutorial005_py310.py diff --git a/docs_src/query_params/tutorial006.py b/docs_src/query_params/tutorial006.py deleted file mode 100644 index f0dbfe08feaef..0000000000000 --- a/docs_src/query_params/tutorial006.py +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Union - -from fastapi import FastAPI - -app = FastAPI() - - -@app.get("/items/{item_id}") -async def read_user_item( - item_id: str, needy: str, skip: int = 0, limit: Union[int, None] = None -): - item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit} - return item diff --git a/docs_src/query_params/tutorial006b.py b/docs_src/query_params/tutorial006b.py deleted file mode 100644 index f0dbfe08feaef..0000000000000 --- a/docs_src/query_params/tutorial006b.py +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Union - -from fastapi import FastAPI - -app = FastAPI() - - -@app.get("/items/{item_id}") -async def read_user_item( - item_id: str, needy: str, skip: int = 0, limit: Union[int, None] = None -): - item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit} - return item diff --git a/docs_src/query_params_str_validations/__init__.py b/docs_src/query_params_str_validations/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/query_params_str_validations/tutorial001.py b/docs_src/query_params_str_validations/tutorial001.py deleted file mode 100644 index e38326b18cab9..0000000000000 --- a/docs_src/query_params_str_validations/tutorial001.py +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Union - -from fastapi import FastAPI - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Union[str, None] = None): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial002.py b/docs_src/query_params_str_validations/tutorial002.py deleted file mode 100644 index 17e017b7e7142..0000000000000 --- a/docs_src/query_params_str_validations/tutorial002.py +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Union[str, None] = Query(default=None, max_length=50)): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial002_an.py b/docs_src/query_params_str_validations/tutorial002_an.py deleted file mode 100644 index cb1b38940c495..0000000000000 --- a/docs_src/query_params_str_validations/tutorial002_an.py +++ /dev/null @@ -1,14 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[Union[str, None], Query(max_length=50)] = None): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial003.py b/docs_src/query_params_str_validations/tutorial003.py deleted file mode 100644 index 73d2e08c8ef0d..0000000000000 --- a/docs_src/query_params_str_validations/tutorial003.py +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - q: Union[str, None] = Query(default=None, min_length=3, max_length=50) -): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial003_an.py b/docs_src/query_params_str_validations/tutorial003_an.py deleted file mode 100644 index a3665f6a85d6c..0000000000000 --- a/docs_src/query_params_str_validations/tutorial003_an.py +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - q: Annotated[Union[str, None], Query(min_length=3, max_length=50)] = None -): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial003_an_py310.py b/docs_src/query_params_str_validations/tutorial003_an_py310.py index 836af04de0bee..79a604b6ce935 100644 --- a/docs_src/query_params_str_validations/tutorial003_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial003_an_py310.py @@ -7,7 +7,7 @@ @app.get("/items/") async def read_items( - q: Annotated[str | None, Query(min_length=3, max_length=50)] = None + q: Annotated[str | None, Query(min_length=3, max_length=50)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial003_an_py39.py b/docs_src/query_params_str_validations/tutorial003_an_py39.py deleted file mode 100644 index 87a4268394a61..0000000000000 --- a/docs_src/query_params_str_validations/tutorial003_an_py39.py +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Annotated, Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - q: Annotated[Union[str, None], Query(min_length=3, max_length=50)] = None -): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial004.py b/docs_src/query_params_str_validations/tutorial004.py deleted file mode 100644 index 3639b6c38fe75..0000000000000 --- a/docs_src/query_params_str_validations/tutorial004.py +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - q: Union[str, None] = Query( - default=None, min_length=3, max_length=50, pattern="^fixedquery$" - ) -): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial004_an.py b/docs_src/query_params_str_validations/tutorial004_an.py deleted file mode 100644 index 24698c7b34fac..0000000000000 --- a/docs_src/query_params_str_validations/tutorial004_an.py +++ /dev/null @@ -1,18 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - q: Annotated[ - Union[str, None], Query(min_length=3, max_length=50, pattern="^fixedquery$") - ] = None -): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial004_an_py310.py b/docs_src/query_params_str_validations/tutorial004_an_py310.py index b7b629ee8acec..20cf1988fdd8a 100644 --- a/docs_src/query_params_str_validations/tutorial004_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial004_an_py310.py @@ -9,7 +9,7 @@ async def read_items( q: Annotated[ str | None, Query(min_length=3, max_length=50, pattern="^fixedquery$") - ] = None + ] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial004_an_py310_regex.py b/docs_src/query_params_str_validations/tutorial004_an_py310_regex.py deleted file mode 100644 index 8fd375b3d549f..0000000000000 --- a/docs_src/query_params_str_validations/tutorial004_an_py310_regex.py +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Annotated - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - q: Annotated[ - str | None, Query(min_length=3, max_length=50, regex="^fixedquery$") - ] = None -): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial004_an_py39.py b/docs_src/query_params_str_validations/tutorial004_an_py39.py deleted file mode 100644 index 8e9a6fc32d88f..0000000000000 --- a/docs_src/query_params_str_validations/tutorial004_an_py39.py +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Annotated, Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - q: Annotated[ - Union[str, None], Query(min_length=3, max_length=50, pattern="^fixedquery$") - ] = None -): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial004_py310.py b/docs_src/query_params_str_validations/tutorial004_py310.py index f80798bcb8f8f..7801e75000f8d 100644 --- a/docs_src/query_params_str_validations/tutorial004_py310.py +++ b/docs_src/query_params_str_validations/tutorial004_py310.py @@ -5,8 +5,9 @@ @app.get("/items/") async def read_items( - q: str - | None = Query(default=None, min_length=3, max_length=50, pattern="^fixedquery$") + q: str | None = Query( + default=None, min_length=3, max_length=50, pattern="^fixedquery$" + ), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial005_an.py b/docs_src/query_params_str_validations/tutorial005_an.py deleted file mode 100644 index 452d4d38d7826..0000000000000 --- a/docs_src/query_params_str_validations/tutorial005_an.py +++ /dev/null @@ -1,12 +0,0 @@ -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = "fixedquery"): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial005_an_py39.py b/docs_src/query_params_str_validations/tutorial005_an_py310.py similarity index 100% rename from docs_src/query_params_str_validations/tutorial005_an_py39.py rename to docs_src/query_params_str_validations/tutorial005_an_py310.py diff --git a/docs_src/query_params_str_validations/tutorial005.py b/docs_src/query_params_str_validations/tutorial005_py310.py similarity index 100% rename from docs_src/query_params_str_validations/tutorial005.py rename to docs_src/query_params_str_validations/tutorial005_py310.py diff --git a/docs_src/query_params_str_validations/tutorial006_an.py b/docs_src/query_params_str_validations/tutorial006_an.py deleted file mode 100644 index 559480d2bfeb9..0000000000000 --- a/docs_src/query_params_str_validations/tutorial006_an.py +++ /dev/null @@ -1,12 +0,0 @@ -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)]): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006_an_py39.py b/docs_src/query_params_str_validations/tutorial006_an_py310.py similarity index 100% rename from docs_src/query_params_str_validations/tutorial006_an_py39.py rename to docs_src/query_params_str_validations/tutorial006_an_py310.py diff --git a/docs_src/query_params_str_validations/tutorial006.py b/docs_src/query_params_str_validations/tutorial006_py310.py similarity index 100% rename from docs_src/query_params_str_validations/tutorial006.py rename to docs_src/query_params_str_validations/tutorial006_py310.py diff --git a/docs_src/query_params_str_validations/tutorial006b.py b/docs_src/query_params_str_validations/tutorial006b.py deleted file mode 100644 index a8d69c8899cf0..0000000000000 --- a/docs_src/query_params_str_validations/tutorial006b.py +++ /dev/null @@ -1,11 +0,0 @@ -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: str = Query(default=..., min_length=3)): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006b_an.py b/docs_src/query_params_str_validations/tutorial006b_an.py deleted file mode 100644 index ea3b02583a7b6..0000000000000 --- a/docs_src/query_params_str_validations/tutorial006b_an.py +++ /dev/null @@ -1,12 +0,0 @@ -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = ...): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006b_an_py39.py b/docs_src/query_params_str_validations/tutorial006b_an_py39.py deleted file mode 100644 index 687a9f5446e6a..0000000000000 --- a/docs_src/query_params_str_validations/tutorial006b_an_py39.py +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Annotated - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = ...): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006c.py b/docs_src/query_params_str_validations/tutorial006c.py deleted file mode 100644 index 2ac148c94f623..0000000000000 --- a/docs_src/query_params_str_validations/tutorial006c.py +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Union[str, None] = Query(default=..., min_length=3)): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006c_an.py b/docs_src/query_params_str_validations/tutorial006c_an.py deleted file mode 100644 index 10bf26a577943..0000000000000 --- a/docs_src/query_params_str_validations/tutorial006c_an.py +++ /dev/null @@ -1,14 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[Union[str, None], Query(min_length=3)] = ...): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006c_an_py310.py b/docs_src/query_params_str_validations/tutorial006c_an_py310.py index 1ab0a7d53dbd2..2995d9c9798d6 100644 --- a/docs_src/query_params_str_validations/tutorial006c_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial006c_an_py310.py @@ -6,7 +6,7 @@ @app.get("/items/") -async def read_items(q: Annotated[str | None, Query(min_length=3)] = ...): +async def read_items(q: Annotated[str | None, Query(min_length=3)]): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006c_an_py39.py b/docs_src/query_params_str_validations/tutorial006c_an_py39.py deleted file mode 100644 index ac127333188dc..0000000000000 --- a/docs_src/query_params_str_validations/tutorial006c_an_py39.py +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Annotated, Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[Union[str, None], Query(min_length=3)] = ...): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006c_py310.py b/docs_src/query_params_str_validations/tutorial006c_py310.py index 82dd9e5d7c30c..88b499c7afc7c 100644 --- a/docs_src/query_params_str_validations/tutorial006c_py310.py +++ b/docs_src/query_params_str_validations/tutorial006c_py310.py @@ -4,7 +4,7 @@ @app.get("/items/") -async def read_items(q: str | None = Query(default=..., min_length=3)): +async def read_items(q: str | None = Query(min_length=3)): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006d.py b/docs_src/query_params_str_validations/tutorial006d.py deleted file mode 100644 index 42c5bf4ebb57f..0000000000000 --- a/docs_src/query_params_str_validations/tutorial006d.py +++ /dev/null @@ -1,12 +0,0 @@ -from fastapi import FastAPI, Query -from pydantic import Required - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: str = Query(default=Required, min_length=3)): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006d_an.py b/docs_src/query_params_str_validations/tutorial006d_an.py deleted file mode 100644 index bc8283e1530ca..0000000000000 --- a/docs_src/query_params_str_validations/tutorial006d_an.py +++ /dev/null @@ -1,13 +0,0 @@ -from fastapi import FastAPI, Query -from pydantic import Required -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = Required): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006d_an_py39.py b/docs_src/query_params_str_validations/tutorial006d_an_py39.py deleted file mode 100644 index 035d9e3bdd3f0..0000000000000 --- a/docs_src/query_params_str_validations/tutorial006d_an_py39.py +++ /dev/null @@ -1,14 +0,0 @@ -from typing import Annotated - -from fastapi import FastAPI, Query -from pydantic import Required - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = Required): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial007.py b/docs_src/query_params_str_validations/tutorial007.py deleted file mode 100644 index cb836569e980e..0000000000000 --- a/docs_src/query_params_str_validations/tutorial007.py +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - q: Union[str, None] = Query(default=None, title="Query string", min_length=3) -): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial007_an.py b/docs_src/query_params_str_validations/tutorial007_an.py deleted file mode 100644 index 3bc85cc0cf511..0000000000000 --- a/docs_src/query_params_str_validations/tutorial007_an.py +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - q: Annotated[Union[str, None], Query(title="Query string", min_length=3)] = None -): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial007_an_py310.py b/docs_src/query_params_str_validations/tutorial007_an_py310.py index 5933911fdfaaf..ef18e500d6cb3 100644 --- a/docs_src/query_params_str_validations/tutorial007_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial007_an_py310.py @@ -7,7 +7,7 @@ @app.get("/items/") async def read_items( - q: Annotated[str | None, Query(title="Query string", min_length=3)] = None + q: Annotated[str | None, Query(title="Query string", min_length=3)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial007_an_py39.py b/docs_src/query_params_str_validations/tutorial007_an_py39.py deleted file mode 100644 index dafa1c5c94988..0000000000000 --- a/docs_src/query_params_str_validations/tutorial007_an_py39.py +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Annotated, Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - q: Annotated[Union[str, None], Query(title="Query string", min_length=3)] = None -): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial007_py310.py b/docs_src/query_params_str_validations/tutorial007_py310.py index e3e1ef2e08711..c283576d52b52 100644 --- a/docs_src/query_params_str_validations/tutorial007_py310.py +++ b/docs_src/query_params_str_validations/tutorial007_py310.py @@ -5,7 +5,7 @@ @app.get("/items/") async def read_items( - q: str | None = Query(default=None, title="Query string", min_length=3) + q: str | None = Query(default=None, title="Query string", min_length=3), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial008.py b/docs_src/query_params_str_validations/tutorial008.py deleted file mode 100644 index d112a9ab8aa5a..0000000000000 --- a/docs_src/query_params_str_validations/tutorial008.py +++ /dev/null @@ -1,20 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - q: Union[str, None] = Query( - default=None, - title="Query string", - description="Query string for the items to search in the database that have a good match", - min_length=3, - ) -): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial008_an.py b/docs_src/query_params_str_validations/tutorial008_an.py deleted file mode 100644 index 5699f1e88d596..0000000000000 --- a/docs_src/query_params_str_validations/tutorial008_an.py +++ /dev/null @@ -1,23 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - q: Annotated[ - Union[str, None], - Query( - title="Query string", - description="Query string for the items to search in the database that have a good match", - min_length=3, - ), - ] = None -): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial008_an_py310.py b/docs_src/query_params_str_validations/tutorial008_an_py310.py index 4aaadf8b4785e..44b3082b63bad 100644 --- a/docs_src/query_params_str_validations/tutorial008_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial008_an_py310.py @@ -14,7 +14,7 @@ async def read_items( description="Query string for the items to search in the database that have a good match", min_length=3, ), - ] = None + ] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial008_an_py39.py b/docs_src/query_params_str_validations/tutorial008_an_py39.py deleted file mode 100644 index 1c3b36176517d..0000000000000 --- a/docs_src/query_params_str_validations/tutorial008_an_py39.py +++ /dev/null @@ -1,22 +0,0 @@ -from typing import Annotated, Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - q: Annotated[ - Union[str, None], - Query( - title="Query string", - description="Query string for the items to search in the database that have a good match", - min_length=3, - ), - ] = None -): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial008_py310.py b/docs_src/query_params_str_validations/tutorial008_py310.py index 489f631d5e908..57438527262fd 100644 --- a/docs_src/query_params_str_validations/tutorial008_py310.py +++ b/docs_src/query_params_str_validations/tutorial008_py310.py @@ -5,13 +5,12 @@ @app.get("/items/") async def read_items( - q: str - | None = Query( + q: str | None = Query( default=None, title="Query string", description="Query string for the items to search in the database that have a good match", min_length=3, - ) + ), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial009.py b/docs_src/query_params_str_validations/tutorial009.py deleted file mode 100644 index 8a6bfe2d93fb3..0000000000000 --- a/docs_src/query_params_str_validations/tutorial009.py +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Union[str, None] = Query(default=None, alias="item-query")): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial009_an.py b/docs_src/query_params_str_validations/tutorial009_an.py deleted file mode 100644 index 2894e2d51a223..0000000000000 --- a/docs_src/query_params_str_validations/tutorial009_an.py +++ /dev/null @@ -1,14 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[Union[str, None], Query(alias="item-query")] = None): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial009_an_py39.py b/docs_src/query_params_str_validations/tutorial009_an_py39.py deleted file mode 100644 index 70a89e6137e88..0000000000000 --- a/docs_src/query_params_str_validations/tutorial009_an_py39.py +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Annotated, Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[Union[str, None], Query(alias="item-query")] = None): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial010.py b/docs_src/query_params_str_validations/tutorial010.py deleted file mode 100644 index 3314f8b6d6440..0000000000000 --- a/docs_src/query_params_str_validations/tutorial010.py +++ /dev/null @@ -1,24 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - q: Union[str, None] = Query( - default=None, - alias="item-query", - title="Query string", - description="Query string for the items to search in the database that have a good match", - min_length=3, - max_length=50, - pattern="^fixedquery$", - deprecated=True, - ) -): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial010_an.py b/docs_src/query_params_str_validations/tutorial010_an.py deleted file mode 100644 index c5df00897f988..0000000000000 --- a/docs_src/query_params_str_validations/tutorial010_an.py +++ /dev/null @@ -1,27 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - q: Annotated[ - Union[str, None], - Query( - alias="item-query", - title="Query string", - description="Query string for the items to search in the database that have a good match", - min_length=3, - max_length=50, - pattern="^fixedquery$", - deprecated=True, - ), - ] = None -): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial010_an_py310.py b/docs_src/query_params_str_validations/tutorial010_an_py310.py index a8e8c099b5e0a..775095bda86ae 100644 --- a/docs_src/query_params_str_validations/tutorial010_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial010_an_py310.py @@ -18,7 +18,7 @@ async def read_items( pattern="^fixedquery$", deprecated=True, ), - ] = None + ] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial010_an_py39.py b/docs_src/query_params_str_validations/tutorial010_an_py39.py deleted file mode 100644 index 955880dd6a65b..0000000000000 --- a/docs_src/query_params_str_validations/tutorial010_an_py39.py +++ /dev/null @@ -1,26 +0,0 @@ -from typing import Annotated, Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - q: Annotated[ - Union[str, None], - Query( - alias="item-query", - title="Query string", - description="Query string for the items to search in the database that have a good match", - min_length=3, - max_length=50, - pattern="^fixedquery$", - deprecated=True, - ), - ] = None -): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial010_py310.py b/docs_src/query_params_str_validations/tutorial010_py310.py index 9ea7b3c49f81f..530e6cf5b6c93 100644 --- a/docs_src/query_params_str_validations/tutorial010_py310.py +++ b/docs_src/query_params_str_validations/tutorial010_py310.py @@ -5,8 +5,7 @@ @app.get("/items/") async def read_items( - q: str - | None = Query( + q: str | None = Query( default=None, alias="item-query", title="Query string", @@ -15,7 +14,7 @@ async def read_items( max_length=50, pattern="^fixedquery$", deprecated=True, - ) + ), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial011.py b/docs_src/query_params_str_validations/tutorial011.py deleted file mode 100644 index 65bbce781ac41..0000000000000 --- a/docs_src/query_params_str_validations/tutorial011.py +++ /dev/null @@ -1,11 +0,0 @@ -from typing import List, Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Union[List[str], None] = Query(default=None)): - query_items = {"q": q} - return query_items diff --git a/docs_src/query_params_str_validations/tutorial011_an.py b/docs_src/query_params_str_validations/tutorial011_an.py deleted file mode 100644 index 8ed699337d1ce..0000000000000 --- a/docs_src/query_params_str_validations/tutorial011_an.py +++ /dev/null @@ -1,12 +0,0 @@ -from typing import List, Union - -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[Union[List[str], None], Query()] = None): - query_items = {"q": q} - return query_items diff --git a/docs_src/query_params_str_validations/tutorial011_an_py39.py b/docs_src/query_params_str_validations/tutorial011_an_py39.py deleted file mode 100644 index 416e3990dc544..0000000000000 --- a/docs_src/query_params_str_validations/tutorial011_an_py39.py +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Annotated, Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[Union[list[str], None], Query()] = None): - query_items = {"q": q} - return query_items diff --git a/docs_src/query_params_str_validations/tutorial011_py39.py b/docs_src/query_params_str_validations/tutorial011_py39.py deleted file mode 100644 index 878f95c7984cf..0000000000000 --- a/docs_src/query_params_str_validations/tutorial011_py39.py +++ /dev/null @@ -1,11 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Union[list[str], None] = Query(default=None)): - query_items = {"q": q} - return query_items diff --git a/docs_src/query_params_str_validations/tutorial012.py b/docs_src/query_params_str_validations/tutorial012.py deleted file mode 100644 index e77d56974de91..0000000000000 --- a/docs_src/query_params_str_validations/tutorial012.py +++ /dev/null @@ -1,11 +0,0 @@ -from typing import List - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: List[str] = Query(default=["foo", "bar"])): - query_items = {"q": q} - return query_items diff --git a/docs_src/query_params_str_validations/tutorial012_an.py b/docs_src/query_params_str_validations/tutorial012_an.py deleted file mode 100644 index 261af250a12df..0000000000000 --- a/docs_src/query_params_str_validations/tutorial012_an.py +++ /dev/null @@ -1,12 +0,0 @@ -from typing import List - -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[List[str], Query()] = ["foo", "bar"]): - query_items = {"q": q} - return query_items diff --git a/docs_src/query_params_str_validations/tutorial012_an_py39.py b/docs_src/query_params_str_validations/tutorial012_an_py310.py similarity index 100% rename from docs_src/query_params_str_validations/tutorial012_an_py39.py rename to docs_src/query_params_str_validations/tutorial012_an_py310.py diff --git a/docs_src/query_params_str_validations/tutorial012_py39.py b/docs_src/query_params_str_validations/tutorial012_py310.py similarity index 100% rename from docs_src/query_params_str_validations/tutorial012_py39.py rename to docs_src/query_params_str_validations/tutorial012_py310.py diff --git a/docs_src/query_params_str_validations/tutorial013_an.py b/docs_src/query_params_str_validations/tutorial013_an.py deleted file mode 100644 index f12a2505593af..0000000000000 --- a/docs_src/query_params_str_validations/tutorial013_an.py +++ /dev/null @@ -1,10 +0,0 @@ -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[list, Query()] = []): - query_items = {"q": q} - return query_items diff --git a/docs_src/query_params_str_validations/tutorial013_an_py39.py b/docs_src/query_params_str_validations/tutorial013_an_py310.py similarity index 100% rename from docs_src/query_params_str_validations/tutorial013_an_py39.py rename to docs_src/query_params_str_validations/tutorial013_an_py310.py diff --git a/docs_src/query_params_str_validations/tutorial013.py b/docs_src/query_params_str_validations/tutorial013_py310.py similarity index 100% rename from docs_src/query_params_str_validations/tutorial013.py rename to docs_src/query_params_str_validations/tutorial013_py310.py diff --git a/docs_src/query_params_str_validations/tutorial014.py b/docs_src/query_params_str_validations/tutorial014.py deleted file mode 100644 index 50e0a6c2b18ce..0000000000000 --- a/docs_src/query_params_str_validations/tutorial014.py +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - hidden_query: Union[str, None] = Query(default=None, include_in_schema=False) -): - if hidden_query: - return {"hidden_query": hidden_query} - else: - return {"hidden_query": "Not found"} diff --git a/docs_src/query_params_str_validations/tutorial014_an.py b/docs_src/query_params_str_validations/tutorial014_an.py deleted file mode 100644 index a9a9c44270c44..0000000000000 --- a/docs_src/query_params_str_validations/tutorial014_an.py +++ /dev/null @@ -1,16 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - hidden_query: Annotated[Union[str, None], Query(include_in_schema=False)] = None -): - if hidden_query: - return {"hidden_query": hidden_query} - else: - return {"hidden_query": "Not found"} diff --git a/docs_src/query_params_str_validations/tutorial014_an_py310.py b/docs_src/query_params_str_validations/tutorial014_an_py310.py index 5fba54150be79..e728dbdb597f7 100644 --- a/docs_src/query_params_str_validations/tutorial014_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial014_an_py310.py @@ -7,7 +7,7 @@ @app.get("/items/") async def read_items( - hidden_query: Annotated[str | None, Query(include_in_schema=False)] = None + hidden_query: Annotated[str | None, Query(include_in_schema=False)] = None, ): if hidden_query: return {"hidden_query": hidden_query} diff --git a/docs_src/query_params_str_validations/tutorial014_an_py39.py b/docs_src/query_params_str_validations/tutorial014_an_py39.py deleted file mode 100644 index b079852100f64..0000000000000 --- a/docs_src/query_params_str_validations/tutorial014_an_py39.py +++ /dev/null @@ -1,15 +0,0 @@ -from typing import Annotated, Union - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items( - hidden_query: Annotated[Union[str, None], Query(include_in_schema=False)] = None -): - if hidden_query: - return {"hidden_query": hidden_query} - else: - return {"hidden_query": "Not found"} diff --git a/docs_src/query_params_str_validations/tutorial014_py310.py b/docs_src/query_params_str_validations/tutorial014_py310.py index 1b617efdd128a..97bb3386ee0f9 100644 --- a/docs_src/query_params_str_validations/tutorial014_py310.py +++ b/docs_src/query_params_str_validations/tutorial014_py310.py @@ -5,7 +5,7 @@ @app.get("/items/") async def read_items( - hidden_query: str | None = Query(default=None, include_in_schema=False) + hidden_query: str | None = Query(default=None, include_in_schema=False), ): if hidden_query: return {"hidden_query": hidden_query} diff --git a/docs_src/query_params_str_validations/tutorial015_an_py310.py b/docs_src/query_params_str_validations/tutorial015_an_py310.py new file mode 100644 index 0000000000000..35f3680949ae4 --- /dev/null +++ b/docs_src/query_params_str_validations/tutorial015_an_py310.py @@ -0,0 +1,30 @@ +import random +from typing import Annotated + +from fastapi import FastAPI +from pydantic import AfterValidator + +app = FastAPI() + +data = { + "isbn-9781529046137": "The Hitchhiker's Guide to the Galaxy", + "imdb-tt0371724": "The Hitchhiker's Guide to the Galaxy", + "isbn-9781439512982": "Isaac Asimov: The Complete Stories, Vol. 2", +} + + +def check_valid_id(id: str): + if not id.startswith(("isbn-", "imdb-")): + raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"') + return id + + +@app.get("/items/") +async def read_items( + id: Annotated[str | None, AfterValidator(check_valid_id)] = None, +): + if id: + item = data.get(id) + else: + id, item = random.choice(list(data.items())) + return {"id": id, "name": item} diff --git a/docs_src/request_files/__init__.py b/docs_src/request_files/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/request_files/tutorial001_02.py b/docs_src/request_files/tutorial001_02.py deleted file mode 100644 index ac30be2d303ca..0000000000000 --- a/docs_src/request_files/tutorial001_02.py +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, File, UploadFile - -app = FastAPI() - - -@app.post("/files/") -async def create_file(file: Union[bytes, None] = File(default=None)): - if not file: - return {"message": "No file sent"} - else: - return {"file_size": len(file)} - - -@app.post("/uploadfile/") -async def create_upload_file(file: Union[UploadFile, None] = None): - if not file: - return {"message": "No upload file sent"} - else: - return {"filename": file.filename} diff --git a/docs_src/request_files/tutorial001_02_an.py b/docs_src/request_files/tutorial001_02_an.py deleted file mode 100644 index 5007fef159a02..0000000000000 --- a/docs_src/request_files/tutorial001_02_an.py +++ /dev/null @@ -1,22 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, File, UploadFile -from typing_extensions import Annotated - -app = FastAPI() - - -@app.post("/files/") -async def create_file(file: Annotated[Union[bytes, None], File()] = None): - if not file: - return {"message": "No file sent"} - else: - return {"file_size": len(file)} - - -@app.post("/uploadfile/") -async def create_upload_file(file: Union[UploadFile, None] = None): - if not file: - return {"message": "No upload file sent"} - else: - return {"filename": file.filename} diff --git a/docs_src/request_files/tutorial001_02_an_py39.py b/docs_src/request_files/tutorial001_02_an_py39.py deleted file mode 100644 index bb090ff6caf83..0000000000000 --- a/docs_src/request_files/tutorial001_02_an_py39.py +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Annotated, Union - -from fastapi import FastAPI, File, UploadFile - -app = FastAPI() - - -@app.post("/files/") -async def create_file(file: Annotated[Union[bytes, None], File()] = None): - if not file: - return {"message": "No file sent"} - else: - return {"file_size": len(file)} - - -@app.post("/uploadfile/") -async def create_upload_file(file: Union[UploadFile, None] = None): - if not file: - return {"message": "No upload file sent"} - else: - return {"filename": file.filename} diff --git a/docs_src/request_files/tutorial001_03_an.py b/docs_src/request_files/tutorial001_03_an.py deleted file mode 100644 index 8a6b0a24559aa..0000000000000 --- a/docs_src/request_files/tutorial001_03_an.py +++ /dev/null @@ -1,16 +0,0 @@ -from fastapi import FastAPI, File, UploadFile -from typing_extensions import Annotated - -app = FastAPI() - - -@app.post("/files/") -async def create_file(file: Annotated[bytes, File(description="A file read as bytes")]): - return {"file_size": len(file)} - - -@app.post("/uploadfile/") -async def create_upload_file( - file: Annotated[UploadFile, File(description="A file read as UploadFile")], -): - return {"filename": file.filename} diff --git a/docs_src/request_files/tutorial001_03_an_py39.py b/docs_src/request_files/tutorial001_03_an_py310.py similarity index 100% rename from docs_src/request_files/tutorial001_03_an_py39.py rename to docs_src/request_files/tutorial001_03_an_py310.py diff --git a/docs_src/request_files/tutorial001_03.py b/docs_src/request_files/tutorial001_03_py310.py similarity index 100% rename from docs_src/request_files/tutorial001_03.py rename to docs_src/request_files/tutorial001_03_py310.py diff --git a/docs_src/request_files/tutorial001_an.py b/docs_src/request_files/tutorial001_an.py deleted file mode 100644 index ca2f76d5c677b..0000000000000 --- a/docs_src/request_files/tutorial001_an.py +++ /dev/null @@ -1,14 +0,0 @@ -from fastapi import FastAPI, File, UploadFile -from typing_extensions import Annotated - -app = FastAPI() - - -@app.post("/files/") -async def create_file(file: Annotated[bytes, File()]): - return {"file_size": len(file)} - - -@app.post("/uploadfile/") -async def create_upload_file(file: UploadFile): - return {"filename": file.filename} diff --git a/docs_src/request_files/tutorial001_an_py39.py b/docs_src/request_files/tutorial001_an_py310.py similarity index 100% rename from docs_src/request_files/tutorial001_an_py39.py rename to docs_src/request_files/tutorial001_an_py310.py diff --git a/docs_src/request_files/tutorial001.py b/docs_src/request_files/tutorial001_py310.py similarity index 100% rename from docs_src/request_files/tutorial001.py rename to docs_src/request_files/tutorial001_py310.py diff --git a/docs_src/request_files/tutorial002.py b/docs_src/request_files/tutorial002.py deleted file mode 100644 index b4d0acc68f1ad..0000000000000 --- a/docs_src/request_files/tutorial002.py +++ /dev/null @@ -1,33 +0,0 @@ -from typing import List - -from fastapi import FastAPI, File, UploadFile -from fastapi.responses import HTMLResponse - -app = FastAPI() - - -@app.post("/files/") -async def create_files(files: List[bytes] = File()): - return {"file_sizes": [len(file) for file in files]} - - -@app.post("/uploadfiles/") -async def create_upload_files(files: List[UploadFile]): - return {"filenames": [file.filename for file in files]} - - -@app.get("/") -async def main(): - content = """ - - - - - """ - return HTMLResponse(content=content) diff --git a/docs_src/request_files/tutorial002_an.py b/docs_src/request_files/tutorial002_an.py deleted file mode 100644 index eaa90da2b634c..0000000000000 --- a/docs_src/request_files/tutorial002_an.py +++ /dev/null @@ -1,34 +0,0 @@ -from typing import List - -from fastapi import FastAPI, File, UploadFile -from fastapi.responses import HTMLResponse -from typing_extensions import Annotated - -app = FastAPI() - - -@app.post("/files/") -async def create_files(files: Annotated[List[bytes], File()]): - return {"file_sizes": [len(file) for file in files]} - - -@app.post("/uploadfiles/") -async def create_upload_files(files: List[UploadFile]): - return {"filenames": [file.filename for file in files]} - - -@app.get("/") -async def main(): - content = """ - - - - - """ - return HTMLResponse(content=content) diff --git a/docs_src/request_files/tutorial002_an_py39.py b/docs_src/request_files/tutorial002_an_py310.py similarity index 100% rename from docs_src/request_files/tutorial002_an_py39.py rename to docs_src/request_files/tutorial002_an_py310.py diff --git a/docs_src/request_files/tutorial002_py39.py b/docs_src/request_files/tutorial002_py310.py similarity index 100% rename from docs_src/request_files/tutorial002_py39.py rename to docs_src/request_files/tutorial002_py310.py diff --git a/docs_src/request_files/tutorial003.py b/docs_src/request_files/tutorial003.py deleted file mode 100644 index e3f805f605262..0000000000000 --- a/docs_src/request_files/tutorial003.py +++ /dev/null @@ -1,37 +0,0 @@ -from typing import List - -from fastapi import FastAPI, File, UploadFile -from fastapi.responses import HTMLResponse - -app = FastAPI() - - -@app.post("/files/") -async def create_files( - files: List[bytes] = File(description="Multiple files as bytes"), -): - return {"file_sizes": [len(file) for file in files]} - - -@app.post("/uploadfiles/") -async def create_upload_files( - files: List[UploadFile] = File(description="Multiple files as UploadFile"), -): - return {"filenames": [file.filename for file in files]} - - -@app.get("/") -async def main(): - content = """ - - - - - """ - return HTMLResponse(content=content) diff --git a/docs_src/request_files/tutorial003_an.py b/docs_src/request_files/tutorial003_an.py deleted file mode 100644 index 2238e3c94b7e6..0000000000000 --- a/docs_src/request_files/tutorial003_an.py +++ /dev/null @@ -1,40 +0,0 @@ -from typing import List - -from fastapi import FastAPI, File, UploadFile -from fastapi.responses import HTMLResponse -from typing_extensions import Annotated - -app = FastAPI() - - -@app.post("/files/") -async def create_files( - files: Annotated[List[bytes], File(description="Multiple files as bytes")], -): - return {"file_sizes": [len(file) for file in files]} - - -@app.post("/uploadfiles/") -async def create_upload_files( - files: Annotated[ - List[UploadFile], File(description="Multiple files as UploadFile") - ], -): - return {"filenames": [file.filename for file in files]} - - -@app.get("/") -async def main(): - content = """ - - - - - """ - return HTMLResponse(content=content) diff --git a/docs_src/request_files/tutorial003_an_py39.py b/docs_src/request_files/tutorial003_an_py310.py similarity index 100% rename from docs_src/request_files/tutorial003_an_py39.py rename to docs_src/request_files/tutorial003_an_py310.py diff --git a/docs_src/request_files/tutorial003_py39.py b/docs_src/request_files/tutorial003_py310.py similarity index 100% rename from docs_src/request_files/tutorial003_py39.py rename to docs_src/request_files/tutorial003_py310.py diff --git a/docs_src/request_form_models/__init__.py b/docs_src/request_form_models/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/request_form_models/tutorial001_an_py310.py b/docs_src/request_form_models/tutorial001_an_py310.py new file mode 100644 index 0000000000000..7cc81aae9586d --- /dev/null +++ b/docs_src/request_form_models/tutorial001_an_py310.py @@ -0,0 +1,16 @@ +from typing import Annotated + +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/docs_src/request_form_models/tutorial001_py310.py b/docs_src/request_form_models/tutorial001_py310.py new file mode 100644 index 0000000000000..98feff0b9f4e8 --- /dev/null +++ b/docs_src/request_form_models/tutorial001_py310.py @@ -0,0 +1,14 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + +@app.post("/login/") +async def login(data: FormData = Form()): + return data diff --git a/docs_src/request_form_models/tutorial002_an_py310.py b/docs_src/request_form_models/tutorial002_an_py310.py new file mode 100644 index 0000000000000..3004e085243c2 --- /dev/null +++ b/docs_src/request_form_models/tutorial002_an_py310.py @@ -0,0 +1,17 @@ +from typing import Annotated + +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + model_config = {"extra": "forbid"} + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/docs_src/request_form_models/tutorial002_py310.py b/docs_src/request_form_models/tutorial002_py310.py new file mode 100644 index 0000000000000..59b329e8d8955 --- /dev/null +++ b/docs_src/request_form_models/tutorial002_py310.py @@ -0,0 +1,15 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + model_config = {"extra": "forbid"} + + +@app.post("/login/") +async def login(data: FormData = Form()): + return data diff --git a/docs_src/request_forms/__init__.py b/docs_src/request_forms/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/request_forms/tutorial001_an.py b/docs_src/request_forms/tutorial001_an.py deleted file mode 100644 index 677fbf2db8080..0000000000000 --- a/docs_src/request_forms/tutorial001_an.py +++ /dev/null @@ -1,9 +0,0 @@ -from fastapi import FastAPI, Form -from typing_extensions import Annotated - -app = FastAPI() - - -@app.post("/login/") -async def login(username: Annotated[str, Form()], password: Annotated[str, Form()]): - return {"username": username} diff --git a/docs_src/request_forms/tutorial001_an_py39.py b/docs_src/request_forms/tutorial001_an_py310.py similarity index 100% rename from docs_src/request_forms/tutorial001_an_py39.py rename to docs_src/request_forms/tutorial001_an_py310.py diff --git a/docs_src/request_forms/tutorial001.py b/docs_src/request_forms/tutorial001_py310.py similarity index 100% rename from docs_src/request_forms/tutorial001.py rename to docs_src/request_forms/tutorial001_py310.py diff --git a/docs_src/request_forms_and_files/__init__.py b/docs_src/request_forms_and_files/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/request_forms_and_files/tutorial001_an.py b/docs_src/request_forms_and_files/tutorial001_an.py deleted file mode 100644 index 0ea285ac876ec..0000000000000 --- a/docs_src/request_forms_and_files/tutorial001_an.py +++ /dev/null @@ -1,17 +0,0 @@ -from fastapi import FastAPI, File, Form, UploadFile -from typing_extensions import Annotated - -app = FastAPI() - - -@app.post("/files/") -async def create_file( - file: Annotated[bytes, File()], - fileb: Annotated[UploadFile, File()], - token: Annotated[str, Form()], -): - return { - "file_size": len(file), - "token": token, - "fileb_content_type": fileb.content_type, - } diff --git a/docs_src/request_forms_and_files/tutorial001_an_py39.py b/docs_src/request_forms_and_files/tutorial001_an_py310.py similarity index 100% rename from docs_src/request_forms_and_files/tutorial001_an_py39.py rename to docs_src/request_forms_and_files/tutorial001_an_py310.py diff --git a/docs_src/request_forms_and_files/tutorial001.py b/docs_src/request_forms_and_files/tutorial001_py310.py similarity index 100% rename from docs_src/request_forms_and_files/tutorial001.py rename to docs_src/request_forms_and_files/tutorial001_py310.py diff --git a/docs_src/response_change_status_code/__init__.py b/docs_src/response_change_status_code/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/response_change_status_code/tutorial001.py b/docs_src/response_change_status_code/tutorial001_py310.py similarity index 100% rename from docs_src/response_change_status_code/tutorial001.py rename to docs_src/response_change_status_code/tutorial001_py310.py diff --git a/docs_src/response_cookies/__init__.py b/docs_src/response_cookies/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/response_cookies/tutorial001.py b/docs_src/response_cookies/tutorial001_py310.py similarity index 100% rename from docs_src/response_cookies/tutorial001.py rename to docs_src/response_cookies/tutorial001_py310.py diff --git a/docs_src/response_cookies/tutorial002.py b/docs_src/response_cookies/tutorial002_py310.py similarity index 100% rename from docs_src/response_cookies/tutorial002.py rename to docs_src/response_cookies/tutorial002_py310.py diff --git a/docs_src/response_directly/__init__.py b/docs_src/response_directly/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/response_directly/tutorial001.py b/docs_src/response_directly/tutorial001.py deleted file mode 100644 index 5ab655a8a7e47..0000000000000 --- a/docs_src/response_directly/tutorial001.py +++ /dev/null @@ -1,22 +0,0 @@ -from datetime import datetime -from typing import Union - -from fastapi import FastAPI -from fastapi.encoders import jsonable_encoder -from fastapi.responses import JSONResponse -from pydantic import BaseModel - - -class Item(BaseModel): - title: str - timestamp: datetime - description: Union[str, None] = None - - -app = FastAPI() - - -@app.put("/items/{id}") -def update_item(id: str, item: Item): - json_compatible_item_data = jsonable_encoder(item) - return JSONResponse(content=json_compatible_item_data) diff --git a/docs_src/response_directly/tutorial001_py310.py b/docs_src/response_directly/tutorial001_py310.py new file mode 100644 index 0000000000000..81e094dc690f0 --- /dev/null +++ b/docs_src/response_directly/tutorial001_py310.py @@ -0,0 +1,21 @@ +from datetime import datetime + +from fastapi import FastAPI +from fastapi.encoders import jsonable_encoder +from fastapi.responses import JSONResponse +from pydantic import BaseModel + + +class Item(BaseModel): + title: str + timestamp: datetime + description: str | None = None + + +app = FastAPI() + + +@app.put("/items/{id}") +def update_item(id: str, item: Item): + json_compatible_item_data = jsonable_encoder(item) + return JSONResponse(content=json_compatible_item_data) diff --git a/docs_src/response_directly/tutorial002.py b/docs_src/response_directly/tutorial002_py310.py similarity index 100% rename from docs_src/response_directly/tutorial002.py rename to docs_src/response_directly/tutorial002_py310.py diff --git a/docs_src/response_headers/__init__.py b/docs_src/response_headers/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/response_headers/tutorial001.py b/docs_src/response_headers/tutorial001_py310.py similarity index 100% rename from docs_src/response_headers/tutorial001.py rename to docs_src/response_headers/tutorial001_py310.py diff --git a/docs_src/response_headers/tutorial002.py b/docs_src/response_headers/tutorial002_py310.py similarity index 100% rename from docs_src/response_headers/tutorial002.py rename to docs_src/response_headers/tutorial002_py310.py diff --git a/docs_src/response_model/__init__.py b/docs_src/response_model/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/response_model/tutorial001.py b/docs_src/response_model/tutorial001.py deleted file mode 100644 index fd1c902a52fdb..0000000000000 --- a/docs_src/response_model/tutorial001.py +++ /dev/null @@ -1,27 +0,0 @@ -from typing import Any, List, Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - tags: List[str] = [] - - -@app.post("/items/", response_model=Item) -async def create_item(item: Item) -> Any: - return item - - -@app.get("/items/", response_model=List[Item]) -async def read_items() -> Any: - return [ - {"name": "Portal Gun", "price": 42.0}, - {"name": "Plumbus", "price": 32.0}, - ] diff --git a/docs_src/response_model/tutorial001_01.py b/docs_src/response_model/tutorial001_01.py deleted file mode 100644 index 98d30d540f793..0000000000000 --- a/docs_src/response_model/tutorial001_01.py +++ /dev/null @@ -1,27 +0,0 @@ -from typing import List, Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - tags: List[str] = [] - - -@app.post("/items/") -async def create_item(item: Item) -> Item: - return item - - -@app.get("/items/") -async def read_items() -> List[Item]: - return [ - Item(name="Portal Gun", price=42.0), - Item(name="Plumbus", price=32.0), - ] diff --git a/docs_src/response_model/tutorial001_01_py39.py b/docs_src/response_model/tutorial001_01_py39.py deleted file mode 100644 index 16c78aa3fdb2f..0000000000000 --- a/docs_src/response_model/tutorial001_01_py39.py +++ /dev/null @@ -1,27 +0,0 @@ -from typing import Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - tags: list[str] = [] - - -@app.post("/items/") -async def create_item(item: Item) -> Item: - return item - - -@app.get("/items/") -async def read_items() -> list[Item]: - return [ - Item(name="Portal Gun", price=42.0), - Item(name="Plumbus", price=32.0), - ] diff --git a/docs_src/response_model/tutorial001_py39.py b/docs_src/response_model/tutorial001_py39.py deleted file mode 100644 index 261e252d00009..0000000000000 --- a/docs_src/response_model/tutorial001_py39.py +++ /dev/null @@ -1,27 +0,0 @@ -from typing import Any, Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - tags: list[str] = [] - - -@app.post("/items/", response_model=Item) -async def create_item(item: Item) -> Any: - return item - - -@app.get("/items/", response_model=list[Item]) -async def read_items() -> Any: - return [ - {"name": "Portal Gun", "price": 42.0}, - {"name": "Plumbus", "price": 32.0}, - ] diff --git a/docs_src/response_model/tutorial002.py b/docs_src/response_model/tutorial002.py deleted file mode 100644 index a58668f9ef962..0000000000000 --- a/docs_src/response_model/tutorial002.py +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Union - -from fastapi import FastAPI -from pydantic import BaseModel, EmailStr - -app = FastAPI() - - -class UserIn(BaseModel): - username: str - password: str - email: EmailStr - full_name: Union[str, None] = None - - -# Don't do this in production! -@app.post("/user/") -async def create_user(user: UserIn) -> UserIn: - return user diff --git a/docs_src/response_model/tutorial003.py b/docs_src/response_model/tutorial003.py deleted file mode 100644 index c42dbc707710d..0000000000000 --- a/docs_src/response_model/tutorial003.py +++ /dev/null @@ -1,24 +0,0 @@ -from typing import Any, Union - -from fastapi import FastAPI -from pydantic import BaseModel, EmailStr - -app = FastAPI() - - -class UserIn(BaseModel): - username: str - password: str - email: EmailStr - full_name: Union[str, None] = None - - -class UserOut(BaseModel): - username: str - email: EmailStr - full_name: Union[str, None] = None - - -@app.post("/user/", response_model=UserOut) -async def create_user(user: UserIn) -> Any: - return user diff --git a/docs_src/response_model/tutorial003_01.py b/docs_src/response_model/tutorial003_01.py deleted file mode 100644 index 52694b5510c70..0000000000000 --- a/docs_src/response_model/tutorial003_01.py +++ /dev/null @@ -1,21 +0,0 @@ -from typing import Union - -from fastapi import FastAPI -from pydantic import BaseModel, EmailStr - -app = FastAPI() - - -class BaseUser(BaseModel): - username: str - email: EmailStr - full_name: Union[str, None] = None - - -class UserIn(BaseUser): - password: str - - -@app.post("/user/") -async def create_user(user: UserIn) -> BaseUser: - return user diff --git a/docs_src/response_model/tutorial003_02.py b/docs_src/response_model/tutorial003_02_py310.py similarity index 100% rename from docs_src/response_model/tutorial003_02.py rename to docs_src/response_model/tutorial003_02_py310.py diff --git a/docs_src/response_model/tutorial003_03.py b/docs_src/response_model/tutorial003_03_py310.py similarity index 100% rename from docs_src/response_model/tutorial003_03.py rename to docs_src/response_model/tutorial003_03_py310.py diff --git a/docs_src/response_model/tutorial003_04.py b/docs_src/response_model/tutorial003_04.py deleted file mode 100644 index b13a926929ab9..0000000000000 --- a/docs_src/response_model/tutorial003_04.py +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Response -from fastapi.responses import RedirectResponse - -app = FastAPI() - - -@app.get("/portal") -async def get_portal(teleport: bool = False) -> Union[Response, dict]: - if teleport: - return RedirectResponse(url="https://www.youtube.com/watch?v=dQw4w9WgXcQ") - return {"message": "Here's your interdimensional portal."} diff --git a/docs_src/response_model/tutorial003_05.py b/docs_src/response_model/tutorial003_05.py deleted file mode 100644 index 0962061a60d0b..0000000000000 --- a/docs_src/response_model/tutorial003_05.py +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Union - -from fastapi import FastAPI, Response -from fastapi.responses import RedirectResponse - -app = FastAPI() - - -@app.get("/portal", response_model=None) -async def get_portal(teleport: bool = False) -> Union[Response, dict]: - if teleport: - return RedirectResponse(url="https://www.youtube.com/watch?v=dQw4w9WgXcQ") - return {"message": "Here's your interdimensional portal."} diff --git a/docs_src/response_model/tutorial004.py b/docs_src/response_model/tutorial004.py deleted file mode 100644 index 10b48039aedc3..0000000000000 --- a/docs_src/response_model/tutorial004.py +++ /dev/null @@ -1,26 +0,0 @@ -from typing import List, Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: float = 10.5 - tags: List[str] = [] - - -items = { - "foo": {"name": "Foo", "price": 50.2}, - "bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2}, - "baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []}, -} - - -@app.get("/items/{item_id}", response_model=Item, response_model_exclude_unset=True) -async def read_item(item_id: str): - return items[item_id] diff --git a/docs_src/response_model/tutorial004_py39.py b/docs_src/response_model/tutorial004_py39.py deleted file mode 100644 index 9463b45ec13a7..0000000000000 --- a/docs_src/response_model/tutorial004_py39.py +++ /dev/null @@ -1,26 +0,0 @@ -from typing import Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: float = 10.5 - tags: list[str] = [] - - -items = { - "foo": {"name": "Foo", "price": 50.2}, - "bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2}, - "baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []}, -} - - -@app.get("/items/{item_id}", response_model=Item, response_model_exclude_unset=True) -async def read_item(item_id: str): - return items[item_id] diff --git a/docs_src/response_model/tutorial005.py b/docs_src/response_model/tutorial005.py deleted file mode 100644 index 30eb9f8e3fb78..0000000000000 --- a/docs_src/response_model/tutorial005.py +++ /dev/null @@ -1,39 +0,0 @@ -from typing import Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: float = 10.5 - - -items = { - "foo": {"name": "Foo", "price": 50.2}, - "bar": {"name": "Bar", "description": "The Bar fighters", "price": 62, "tax": 20.2}, - "baz": { - "name": "Baz", - "description": "There goes my baz", - "price": 50.2, - "tax": 10.5, - }, -} - - -@app.get( - "/items/{item_id}/name", - response_model=Item, - response_model_include={"name", "description"}, -) -async def read_item_name(item_id: str): - return items[item_id] - - -@app.get("/items/{item_id}/public", response_model=Item, response_model_exclude={"tax"}) -async def read_item_public_data(item_id: str): - return items[item_id] diff --git a/docs_src/response_model/tutorial006.py b/docs_src/response_model/tutorial006.py deleted file mode 100644 index 3ffdb512bce7d..0000000000000 --- a/docs_src/response_model/tutorial006.py +++ /dev/null @@ -1,39 +0,0 @@ -from typing import Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: float = 10.5 - - -items = { - "foo": {"name": "Foo", "price": 50.2}, - "bar": {"name": "Bar", "description": "The Bar fighters", "price": 62, "tax": 20.2}, - "baz": { - "name": "Baz", - "description": "There goes my baz", - "price": 50.2, - "tax": 10.5, - }, -} - - -@app.get( - "/items/{item_id}/name", - response_model=Item, - response_model_include=["name", "description"], -) -async def read_item_name(item_id: str): - return items[item_id] - - -@app.get("/items/{item_id}/public", response_model=Item, response_model_exclude=["tax"]) -async def read_item_public_data(item_id: str): - return items[item_id] diff --git a/docs_src/response_status_code/__init__.py b/docs_src/response_status_code/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/response_status_code/tutorial001.py b/docs_src/response_status_code/tutorial001_py310.py similarity index 100% rename from docs_src/response_status_code/tutorial001.py rename to docs_src/response_status_code/tutorial001_py310.py diff --git a/docs_src/response_status_code/tutorial002.py b/docs_src/response_status_code/tutorial002_py310.py similarity index 100% rename from docs_src/response_status_code/tutorial002.py rename to docs_src/response_status_code/tutorial002_py310.py diff --git a/docs_src/schema_extra_example/__init__.py b/docs_src/schema_extra_example/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/schema_extra_example/tutorial001.py b/docs_src/schema_extra_example/tutorial001.py deleted file mode 100644 index 32a66db3a97b8..0000000000000 --- a/docs_src/schema_extra_example/tutorial001.py +++ /dev/null @@ -1,32 +0,0 @@ -from typing import Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - - model_config = { - "json_schema_extra": { - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - } - ] - } - } - - -@app.put("/items/{item_id}") -async def update_item(item_id: int, item: Item): - results = {"item_id": item_id, "item": item} - return results diff --git a/docs_src/schema_extra_example/tutorial001_pv1.py b/docs_src/schema_extra_example/tutorial001_pv1.py deleted file mode 100644 index 6ab96ff859d0d..0000000000000 --- a/docs_src/schema_extra_example/tutorial001_pv1.py +++ /dev/null @@ -1,31 +0,0 @@ -from typing import Union - -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - - class Config: - schema_extra = { - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - } - ] - } - - -@app.put("/items/{item_id}") -async def update_item(item_id: int, item: Item): - results = {"item_id": item_id, "item": item} - return results diff --git a/docs_src/schema_extra_example/tutorial001_py310_pv1.py b/docs_src/schema_extra_example/tutorial001_py310_pv1.py deleted file mode 100644 index ec83f1112f20f..0000000000000 --- a/docs_src/schema_extra_example/tutorial001_py310_pv1.py +++ /dev/null @@ -1,29 +0,0 @@ -from fastapi import FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: str | None = None - price: float - tax: float | None = None - - class Config: - schema_extra = { - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - } - ] - } - - -@app.put("/items/{item_id}") -async def update_item(item_id: int, item: Item): - results = {"item_id": item_id, "item": item} - return results diff --git a/docs_src/schema_extra_example/tutorial002.py b/docs_src/schema_extra_example/tutorial002.py deleted file mode 100644 index 70f06567c3787..0000000000000 --- a/docs_src/schema_extra_example/tutorial002.py +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Union - -from fastapi import FastAPI -from pydantic import BaseModel, Field - -app = FastAPI() - - -class Item(BaseModel): - name: str = Field(examples=["Foo"]) - description: Union[str, None] = Field(default=None, examples=["A very nice Item"]) - price: float = Field(examples=[35.4]) - tax: Union[float, None] = Field(default=None, examples=[3.2]) - - -@app.put("/items/{item_id}") -async def update_item(item_id: int, item: Item): - results = {"item_id": item_id, "item": item} - return results diff --git a/docs_src/schema_extra_example/tutorial003.py b/docs_src/schema_extra_example/tutorial003.py deleted file mode 100644 index 385f3de8a1c81..0000000000000 --- a/docs_src/schema_extra_example/tutorial003.py +++ /dev/null @@ -1,31 +0,0 @@ -from typing import Union - -from fastapi import Body, FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - - -@app.put("/items/{item_id}") -async def update_item( - item_id: int, - item: Item = Body( - examples=[ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - } - ], - ), -): - results = {"item_id": item_id, "item": item} - return results diff --git a/docs_src/schema_extra_example/tutorial003_an.py b/docs_src/schema_extra_example/tutorial003_an.py deleted file mode 100644 index 23675aba14f8f..0000000000000 --- a/docs_src/schema_extra_example/tutorial003_an.py +++ /dev/null @@ -1,35 +0,0 @@ -from typing import Union - -from fastapi import Body, FastAPI -from pydantic import BaseModel -from typing_extensions import Annotated - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - - -@app.put("/items/{item_id}") -async def update_item( - item_id: int, - item: Annotated[ - Item, - Body( - examples=[ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - } - ], - ), - ], -): - results = {"item_id": item_id, "item": item} - return results diff --git a/docs_src/schema_extra_example/tutorial003_an_py39.py b/docs_src/schema_extra_example/tutorial003_an_py39.py deleted file mode 100644 index 4728085617f6e..0000000000000 --- a/docs_src/schema_extra_example/tutorial003_an_py39.py +++ /dev/null @@ -1,34 +0,0 @@ -from typing import Annotated, Union - -from fastapi import Body, FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - - -@app.put("/items/{item_id}") -async def update_item( - item_id: int, - item: Annotated[ - Item, - Body( - examples=[ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - } - ], - ), - ], -): - results = {"item_id": item_id, "item": item} - return results diff --git a/docs_src/schema_extra_example/tutorial004.py b/docs_src/schema_extra_example/tutorial004.py deleted file mode 100644 index 75514a3e914ad..0000000000000 --- a/docs_src/schema_extra_example/tutorial004.py +++ /dev/null @@ -1,40 +0,0 @@ -from typing import Union - -from fastapi import Body, FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - - -@app.put("/items/{item_id}") -async def update_item( - *, - item_id: int, - item: Item = Body( - examples=[ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - { - "name": "Bar", - "price": "35.4", - }, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - ), -): - results = {"item_id": item_id, "item": item} - return results diff --git a/docs_src/schema_extra_example/tutorial004_an.py b/docs_src/schema_extra_example/tutorial004_an.py deleted file mode 100644 index e817302a2240d..0000000000000 --- a/docs_src/schema_extra_example/tutorial004_an.py +++ /dev/null @@ -1,44 +0,0 @@ -from typing import Union - -from fastapi import Body, FastAPI -from pydantic import BaseModel -from typing_extensions import Annotated - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - - -@app.put("/items/{item_id}") -async def update_item( - *, - item_id: int, - item: Annotated[ - Item, - Body( - examples=[ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - { - "name": "Bar", - "price": "35.4", - }, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - ), - ], -): - results = {"item_id": item_id, "item": item} - return results diff --git a/docs_src/schema_extra_example/tutorial004_an_py39.py b/docs_src/schema_extra_example/tutorial004_an_py39.py deleted file mode 100644 index dc5a8fe49c6f9..0000000000000 --- a/docs_src/schema_extra_example/tutorial004_an_py39.py +++ /dev/null @@ -1,43 +0,0 @@ -from typing import Annotated, Union - -from fastapi import Body, FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - - -@app.put("/items/{item_id}") -async def update_item( - *, - item_id: int, - item: Annotated[ - Item, - Body( - examples=[ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - { - "name": "Bar", - "price": "35.4", - }, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - ), - ], -): - results = {"item_id": item_id, "item": item} - return results diff --git a/docs_src/schema_extra_example/tutorial005.py b/docs_src/schema_extra_example/tutorial005.py deleted file mode 100644 index b8217c27e9971..0000000000000 --- a/docs_src/schema_extra_example/tutorial005.py +++ /dev/null @@ -1,51 +0,0 @@ -from typing import Union - -from fastapi import Body, FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - - -@app.put("/items/{item_id}") -async def update_item( - *, - item_id: int, - item: Item = Body( - openapi_examples={ - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": { - "name": "Bar", - "price": "35.4", - }, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, - ), -): - results = {"item_id": item_id, "item": item} - return results diff --git a/docs_src/schema_extra_example/tutorial005_an.py b/docs_src/schema_extra_example/tutorial005_an.py deleted file mode 100644 index 4b2d9c662b7d6..0000000000000 --- a/docs_src/schema_extra_example/tutorial005_an.py +++ /dev/null @@ -1,55 +0,0 @@ -from typing import Union - -from fastapi import Body, FastAPI -from pydantic import BaseModel -from typing_extensions import Annotated - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - - -@app.put("/items/{item_id}") -async def update_item( - *, - item_id: int, - item: Annotated[ - Item, - Body( - openapi_examples={ - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": { - "name": "Bar", - "price": "35.4", - }, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, - ), - ], -): - results = {"item_id": item_id, "item": item} - return results diff --git a/docs_src/schema_extra_example/tutorial005_an_py39.py b/docs_src/schema_extra_example/tutorial005_an_py39.py deleted file mode 100644 index edeb1affce572..0000000000000 --- a/docs_src/schema_extra_example/tutorial005_an_py39.py +++ /dev/null @@ -1,54 +0,0 @@ -from typing import Annotated, Union - -from fastapi import Body, FastAPI -from pydantic import BaseModel - -app = FastAPI() - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - price: float - tax: Union[float, None] = None - - -@app.put("/items/{item_id}") -async def update_item( - *, - item_id: int, - item: Annotated[ - Item, - Body( - openapi_examples={ - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": { - "name": "Bar", - "price": "35.4", - }, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, - ), - ], -): - results = {"item_id": item_id, "item": item} - return results diff --git a/docs_src/security/__init__.py b/docs_src/security/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/security/tutorial001_an.py b/docs_src/security/tutorial001_an.py deleted file mode 100644 index dac915b7cace5..0000000000000 --- a/docs_src/security/tutorial001_an.py +++ /dev/null @@ -1,12 +0,0 @@ -from fastapi import Depends, FastAPI -from fastapi.security import OAuth2PasswordBearer -from typing_extensions import Annotated - -app = FastAPI() - -oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") - - -@app.get("/items/") -async def read_items(token: Annotated[str, Depends(oauth2_scheme)]): - return {"token": token} diff --git a/docs_src/security/tutorial001_an_py39.py b/docs_src/security/tutorial001_an_py310.py similarity index 100% rename from docs_src/security/tutorial001_an_py39.py rename to docs_src/security/tutorial001_an_py310.py diff --git a/docs_src/security/tutorial001.py b/docs_src/security/tutorial001_py310.py similarity index 100% rename from docs_src/security/tutorial001.py rename to docs_src/security/tutorial001_py310.py diff --git a/docs_src/security/tutorial002.py b/docs_src/security/tutorial002.py deleted file mode 100644 index bfd035221c09d..0000000000000 --- a/docs_src/security/tutorial002.py +++ /dev/null @@ -1,32 +0,0 @@ -from typing import Union - -from fastapi import Depends, FastAPI -from fastapi.security import OAuth2PasswordBearer -from pydantic import BaseModel - -app = FastAPI() - -oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") - - -class User(BaseModel): - username: str - email: Union[str, None] = None - full_name: Union[str, None] = None - disabled: Union[bool, None] = None - - -def fake_decode_token(token): - return User( - username=token + "fakedecoded", email="john@example.com", full_name="John Doe" - ) - - -async def get_current_user(token: str = Depends(oauth2_scheme)): - user = fake_decode_token(token) - return user - - -@app.get("/users/me") -async def read_users_me(current_user: User = Depends(get_current_user)): - return current_user diff --git a/docs_src/security/tutorial002_an.py b/docs_src/security/tutorial002_an.py deleted file mode 100644 index 291b3bf530012..0000000000000 --- a/docs_src/security/tutorial002_an.py +++ /dev/null @@ -1,33 +0,0 @@ -from typing import Union - -from fastapi import Depends, FastAPI -from fastapi.security import OAuth2PasswordBearer -from pydantic import BaseModel -from typing_extensions import Annotated - -app = FastAPI() - -oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") - - -class User(BaseModel): - username: str - email: Union[str, None] = None - full_name: Union[str, None] = None - disabled: Union[bool, None] = None - - -def fake_decode_token(token): - return User( - username=token + "fakedecoded", email="john@example.com", full_name="John Doe" - ) - - -async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): - user = fake_decode_token(token) - return user - - -@app.get("/users/me") -async def read_users_me(current_user: Annotated[User, Depends(get_current_user)]): - return current_user diff --git a/docs_src/security/tutorial002_an_py39.py b/docs_src/security/tutorial002_an_py39.py deleted file mode 100644 index 7ff1c470bb90a..0000000000000 --- a/docs_src/security/tutorial002_an_py39.py +++ /dev/null @@ -1,32 +0,0 @@ -from typing import Annotated, Union - -from fastapi import Depends, FastAPI -from fastapi.security import OAuth2PasswordBearer -from pydantic import BaseModel - -app = FastAPI() - -oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") - - -class User(BaseModel): - username: str - email: Union[str, None] = None - full_name: Union[str, None] = None - disabled: Union[bool, None] = None - - -def fake_decode_token(token): - return User( - username=token + "fakedecoded", email="john@example.com", full_name="John Doe" - ) - - -async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): - user = fake_decode_token(token) - return user - - -@app.get("/users/me") -async def read_users_me(current_user: Annotated[User, Depends(get_current_user)]): - return current_user diff --git a/docs_src/security/tutorial003.py b/docs_src/security/tutorial003.py deleted file mode 100644 index 4b324866f6850..0000000000000 --- a/docs_src/security/tutorial003.py +++ /dev/null @@ -1,90 +0,0 @@ -from typing import Union - -from fastapi import Depends, FastAPI, HTTPException, status -from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from pydantic import BaseModel - -fake_users_db = { - "johndoe": { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "fakehashedsecret", - "disabled": False, - }, - "alice": { - "username": "alice", - "full_name": "Alice Wonderson", - "email": "alice@example.com", - "hashed_password": "fakehashedsecret2", - "disabled": True, - }, -} - -app = FastAPI() - - -def fake_hash_password(password: str): - return "fakehashed" + password - - -oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") - - -class User(BaseModel): - username: str - email: Union[str, None] = None - full_name: Union[str, None] = None - disabled: Union[bool, None] = None - - -class UserInDB(User): - hashed_password: str - - -def get_user(db, username: str): - if username in db: - user_dict = db[username] - return UserInDB(**user_dict) - - -def fake_decode_token(token): - # This doesn't provide any security at all - # Check the next version - user = get_user(fake_users_db, token) - return user - - -async def get_current_user(token: str = Depends(oauth2_scheme)): - user = fake_decode_token(token) - if not user: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Invalid authentication credentials", - headers={"WWW-Authenticate": "Bearer"}, - ) - return user - - -async def get_current_active_user(current_user: User = Depends(get_current_user)): - if current_user.disabled: - raise HTTPException(status_code=400, detail="Inactive user") - return current_user - - -@app.post("/token") -async def login(form_data: OAuth2PasswordRequestForm = Depends()): - user_dict = fake_users_db.get(form_data.username) - if not user_dict: - raise HTTPException(status_code=400, detail="Incorrect username or password") - user = UserInDB(**user_dict) - hashed_password = fake_hash_password(form_data.password) - if not hashed_password == user.hashed_password: - raise HTTPException(status_code=400, detail="Incorrect username or password") - - return {"access_token": user.username, "token_type": "bearer"} - - -@app.get("/users/me") -async def read_users_me(current_user: User = Depends(get_current_active_user)): - return current_user diff --git a/docs_src/security/tutorial003_an.py b/docs_src/security/tutorial003_an.py deleted file mode 100644 index 261cb4857d2f1..0000000000000 --- a/docs_src/security/tutorial003_an.py +++ /dev/null @@ -1,95 +0,0 @@ -from typing import Union - -from fastapi import Depends, FastAPI, HTTPException, status -from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from pydantic import BaseModel -from typing_extensions import Annotated - -fake_users_db = { - "johndoe": { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "fakehashedsecret", - "disabled": False, - }, - "alice": { - "username": "alice", - "full_name": "Alice Wonderson", - "email": "alice@example.com", - "hashed_password": "fakehashedsecret2", - "disabled": True, - }, -} - -app = FastAPI() - - -def fake_hash_password(password: str): - return "fakehashed" + password - - -oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") - - -class User(BaseModel): - username: str - email: Union[str, None] = None - full_name: Union[str, None] = None - disabled: Union[bool, None] = None - - -class UserInDB(User): - hashed_password: str - - -def get_user(db, username: str): - if username in db: - user_dict = db[username] - return UserInDB(**user_dict) - - -def fake_decode_token(token): - # This doesn't provide any security at all - # Check the next version - user = get_user(fake_users_db, token) - return user - - -async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): - user = fake_decode_token(token) - if not user: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Invalid authentication credentials", - headers={"WWW-Authenticate": "Bearer"}, - ) - return user - - -async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] -): - if current_user.disabled: - raise HTTPException(status_code=400, detail="Inactive user") - return current_user - - -@app.post("/token") -async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): - user_dict = fake_users_db.get(form_data.username) - if not user_dict: - raise HTTPException(status_code=400, detail="Incorrect username or password") - user = UserInDB(**user_dict) - hashed_password = fake_hash_password(form_data.password) - if not hashed_password == user.hashed_password: - raise HTTPException(status_code=400, detail="Incorrect username or password") - - return {"access_token": user.username, "token_type": "bearer"} - - -@app.get("/users/me") -async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] -): - return current_user diff --git a/docs_src/security/tutorial003_an_py310.py b/docs_src/security/tutorial003_an_py310.py index a03f4f8bf5fb0..4a2743f6f8ed4 100644 --- a/docs_src/security/tutorial003_an_py310.py +++ b/docs_src/security/tutorial003_an_py310.py @@ -60,14 +60,14 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): if not user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail="Invalid authentication credentials", + detail="Not authenticated", headers={"WWW-Authenticate": "Bearer"}, ) return user async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -89,6 +89,6 @@ async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): @app.get("/users/me") async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user diff --git a/docs_src/security/tutorial003_an_py39.py b/docs_src/security/tutorial003_an_py39.py deleted file mode 100644 index 308dbe798fa17..0000000000000 --- a/docs_src/security/tutorial003_an_py39.py +++ /dev/null @@ -1,94 +0,0 @@ -from typing import Annotated, Union - -from fastapi import Depends, FastAPI, HTTPException, status -from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from pydantic import BaseModel - -fake_users_db = { - "johndoe": { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "fakehashedsecret", - "disabled": False, - }, - "alice": { - "username": "alice", - "full_name": "Alice Wonderson", - "email": "alice@example.com", - "hashed_password": "fakehashedsecret2", - "disabled": True, - }, -} - -app = FastAPI() - - -def fake_hash_password(password: str): - return "fakehashed" + password - - -oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") - - -class User(BaseModel): - username: str - email: Union[str, None] = None - full_name: Union[str, None] = None - disabled: Union[bool, None] = None - - -class UserInDB(User): - hashed_password: str - - -def get_user(db, username: str): - if username in db: - user_dict = db[username] - return UserInDB(**user_dict) - - -def fake_decode_token(token): - # This doesn't provide any security at all - # Check the next version - user = get_user(fake_users_db, token) - return user - - -async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): - user = fake_decode_token(token) - if not user: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Invalid authentication credentials", - headers={"WWW-Authenticate": "Bearer"}, - ) - return user - - -async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] -): - if current_user.disabled: - raise HTTPException(status_code=400, detail="Inactive user") - return current_user - - -@app.post("/token") -async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): - user_dict = fake_users_db.get(form_data.username) - if not user_dict: - raise HTTPException(status_code=400, detail="Incorrect username or password") - user = UserInDB(**user_dict) - hashed_password = fake_hash_password(form_data.password) - if not hashed_password == user.hashed_password: - raise HTTPException(status_code=400, detail="Incorrect username or password") - - return {"access_token": user.username, "token_type": "bearer"} - - -@app.get("/users/me") -async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] -): - return current_user diff --git a/docs_src/security/tutorial003_py310.py b/docs_src/security/tutorial003_py310.py index af935e997dfd8..081259b31703a 100644 --- a/docs_src/security/tutorial003_py310.py +++ b/docs_src/security/tutorial003_py310.py @@ -58,7 +58,7 @@ async def get_current_user(token: str = Depends(oauth2_scheme)): if not user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail="Invalid authentication credentials", + detail="Not authenticated", headers={"WWW-Authenticate": "Bearer"}, ) return user diff --git a/docs_src/security/tutorial004.py b/docs_src/security/tutorial004.py deleted file mode 100644 index 64099abe9cffe..0000000000000 --- a/docs_src/security/tutorial004.py +++ /dev/null @@ -1,138 +0,0 @@ -from datetime import datetime, timedelta -from typing import Union - -from fastapi import Depends, FastAPI, HTTPException, status -from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt -from passlib.context import CryptContext -from pydantic import BaseModel - -# to get a string like this run: -# openssl rand -hex 32 -SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" -ALGORITHM = "HS256" -ACCESS_TOKEN_EXPIRE_MINUTES = 30 - - -fake_users_db = { - "johndoe": { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW", - "disabled": False, - } -} - - -class Token(BaseModel): - access_token: str - token_type: str - - -class TokenData(BaseModel): - username: Union[str, None] = None - - -class User(BaseModel): - username: str - email: Union[str, None] = None - full_name: Union[str, None] = None - disabled: Union[bool, None] = None - - -class UserInDB(User): - hashed_password: str - - -pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") - -oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") - -app = FastAPI() - - -def verify_password(plain_password, hashed_password): - return pwd_context.verify(plain_password, hashed_password) - - -def get_password_hash(password): - return pwd_context.hash(password) - - -def get_user(db, username: str): - if username in db: - user_dict = db[username] - return UserInDB(**user_dict) - - -def authenticate_user(fake_db, username: str, password: str): - user = get_user(fake_db, username) - if not user: - return False - if not verify_password(password, user.hashed_password): - return False - return user - - -def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): - to_encode = data.copy() - if expires_delta: - expire = datetime.utcnow() + expires_delta - else: - expire = datetime.utcnow() + timedelta(minutes=15) - to_encode.update({"exp": expire}) - encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) - return encoded_jwt - - -async def get_current_user(token: str = Depends(oauth2_scheme)): - credentials_exception = HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Could not validate credentials", - headers={"WWW-Authenticate": "Bearer"}, - ) - try: - payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") - if username is None: - raise credentials_exception - token_data = TokenData(username=username) - except JWTError: - raise credentials_exception - user = get_user(fake_users_db, username=token_data.username) - if user is None: - raise credentials_exception - return user - - -async def get_current_active_user(current_user: User = Depends(get_current_user)): - if current_user.disabled: - raise HTTPException(status_code=400, detail="Inactive user") - return current_user - - -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): - user = authenticate_user(fake_users_db, form_data.username, form_data.password) - if not user: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect username or password", - headers={"WWW-Authenticate": "Bearer"}, - ) - access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) - access_token = create_access_token( - data={"sub": user.username}, expires_delta=access_token_expires - ) - return {"access_token": access_token, "token_type": "bearer"} - - -@app.get("/users/me/", response_model=User) -async def read_users_me(current_user: User = Depends(get_current_active_user)): - return current_user - - -@app.get("/users/me/items/") -async def read_own_items(current_user: User = Depends(get_current_active_user)): - return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial004_an.py b/docs_src/security/tutorial004_an.py deleted file mode 100644 index ca350343d2082..0000000000000 --- a/docs_src/security/tutorial004_an.py +++ /dev/null @@ -1,147 +0,0 @@ -from datetime import datetime, timedelta -from typing import Union - -from fastapi import Depends, FastAPI, HTTPException, status -from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt -from passlib.context import CryptContext -from pydantic import BaseModel -from typing_extensions import Annotated - -# to get a string like this run: -# openssl rand -hex 32 -SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" -ALGORITHM = "HS256" -ACCESS_TOKEN_EXPIRE_MINUTES = 30 - - -fake_users_db = { - "johndoe": { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW", - "disabled": False, - } -} - - -class Token(BaseModel): - access_token: str - token_type: str - - -class TokenData(BaseModel): - username: Union[str, None] = None - - -class User(BaseModel): - username: str - email: Union[str, None] = None - full_name: Union[str, None] = None - disabled: Union[bool, None] = None - - -class UserInDB(User): - hashed_password: str - - -pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") - -oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") - -app = FastAPI() - - -def verify_password(plain_password, hashed_password): - return pwd_context.verify(plain_password, hashed_password) - - -def get_password_hash(password): - return pwd_context.hash(password) - - -def get_user(db, username: str): - if username in db: - user_dict = db[username] - return UserInDB(**user_dict) - - -def authenticate_user(fake_db, username: str, password: str): - user = get_user(fake_db, username) - if not user: - return False - if not verify_password(password, user.hashed_password): - return False - return user - - -def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): - to_encode = data.copy() - if expires_delta: - expire = datetime.utcnow() + expires_delta - else: - expire = datetime.utcnow() + timedelta(minutes=15) - to_encode.update({"exp": expire}) - encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) - return encoded_jwt - - -async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): - credentials_exception = HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Could not validate credentials", - headers={"WWW-Authenticate": "Bearer"}, - ) - try: - payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") - if username is None: - raise credentials_exception - token_data = TokenData(username=username) - except JWTError: - raise credentials_exception - user = get_user(fake_users_db, username=token_data.username) - if user is None: - raise credentials_exception - return user - - -async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] -): - if current_user.disabled: - raise HTTPException(status_code=400, detail="Inactive user") - return current_user - - -@app.post("/token", response_model=Token) -async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): - user = authenticate_user(fake_users_db, form_data.username, form_data.password) - if not user: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect username or password", - headers={"WWW-Authenticate": "Bearer"}, - ) - access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) - access_token = create_access_token( - data={"sub": user.username}, expires_delta=access_token_expires - ) - return {"access_token": access_token, "token_type": "bearer"} - - -@app.get("/users/me/", response_model=User) -async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] -): - return current_user - - -@app.get("/users/me/items/") -async def read_own_items( - current_user: Annotated[User, Depends(get_current_active_user)] -): - return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial004_an_py310.py b/docs_src/security/tutorial004_an_py310.py index 8bf5f3b7185cd..685cb034eeeb0 100644 --- a/docs_src/security/tutorial004_an_py310.py +++ b/docs_src/security/tutorial004_an_py310.py @@ -1,10 +1,11 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Annotated +import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt -from passlib.context import CryptContext +from jwt.exceptions import InvalidTokenError +from pwdlib import PasswordHash from pydantic import BaseModel # to get a string like this run: @@ -19,7 +20,7 @@ "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", - "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW", + "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, } } @@ -45,7 +46,9 @@ class UserInDB(User): hashed_password: str -pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") +password_hash = PasswordHash.recommended() + +DUMMY_HASH = password_hash.hash("dummypassword") oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") @@ -53,11 +56,11 @@ class UserInDB(User): def verify_password(plain_password, hashed_password): - return pwd_context.verify(plain_password, hashed_password) + return password_hash.verify(plain_password, hashed_password) def get_password_hash(password): - return pwd_context.hash(password) + return password_hash.hash(password) def get_user(db, username: str): @@ -69,6 +72,7 @@ def get_user(db, username: str): def authenticate_user(fake_db, username: str, password: str): user = get_user(fake_db, username) if not user: + verify_password(password, DUMMY_HASH) return False if not verify_password(password, user.hashed_password): return False @@ -78,9 +82,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: timedelta | None = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -94,11 +98,11 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) - except JWTError: + except InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: @@ -107,17 +111,17 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -129,18 +133,18 @@ 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) +@app.get("/users/me/") async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] -): + current_user: Annotated[User, Depends(get_current_active_user)], +) -> User: return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial004_an_py39.py b/docs_src/security/tutorial004_an_py39.py deleted file mode 100644 index a634e23de9843..0000000000000 --- a/docs_src/security/tutorial004_an_py39.py +++ /dev/null @@ -1,146 +0,0 @@ -from datetime import datetime, timedelta -from typing import Annotated, Union - -from fastapi import Depends, FastAPI, HTTPException, status -from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt -from passlib.context import CryptContext -from pydantic import BaseModel - -# to get a string like this run: -# openssl rand -hex 32 -SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" -ALGORITHM = "HS256" -ACCESS_TOKEN_EXPIRE_MINUTES = 30 - - -fake_users_db = { - "johndoe": { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW", - "disabled": False, - } -} - - -class Token(BaseModel): - access_token: str - token_type: str - - -class TokenData(BaseModel): - username: Union[str, None] = None - - -class User(BaseModel): - username: str - email: Union[str, None] = None - full_name: Union[str, None] = None - disabled: Union[bool, None] = None - - -class UserInDB(User): - hashed_password: str - - -pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") - -oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") - -app = FastAPI() - - -def verify_password(plain_password, hashed_password): - return pwd_context.verify(plain_password, hashed_password) - - -def get_password_hash(password): - return pwd_context.hash(password) - - -def get_user(db, username: str): - if username in db: - user_dict = db[username] - return UserInDB(**user_dict) - - -def authenticate_user(fake_db, username: str, password: str): - user = get_user(fake_db, username) - if not user: - return False - if not verify_password(password, user.hashed_password): - return False - return user - - -def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): - to_encode = data.copy() - if expires_delta: - expire = datetime.utcnow() + expires_delta - else: - expire = datetime.utcnow() + timedelta(minutes=15) - to_encode.update({"exp": expire}) - encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) - return encoded_jwt - - -async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): - credentials_exception = HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Could not validate credentials", - headers={"WWW-Authenticate": "Bearer"}, - ) - try: - payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") - if username is None: - raise credentials_exception - token_data = TokenData(username=username) - except JWTError: - raise credentials_exception - user = get_user(fake_users_db, username=token_data.username) - if user is None: - raise credentials_exception - return user - - -async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] -): - if current_user.disabled: - raise HTTPException(status_code=400, detail="Inactive user") - return current_user - - -@app.post("/token", response_model=Token) -async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): - user = authenticate_user(fake_users_db, form_data.username, form_data.password) - if not user: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect username or password", - headers={"WWW-Authenticate": "Bearer"}, - ) - access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) - access_token = create_access_token( - data={"sub": user.username}, expires_delta=access_token_expires - ) - return {"access_token": access_token, "token_type": "bearer"} - - -@app.get("/users/me/", response_model=User) -async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] -): - return current_user - - -@app.get("/users/me/items/") -async def read_own_items( - current_user: Annotated[User, Depends(get_current_active_user)] -): - return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial004_py310.py b/docs_src/security/tutorial004_py310.py index 797d56d0431ab..dc7f1c9e296dd 100644 --- a/docs_src/security/tutorial004_py310.py +++ b/docs_src/security/tutorial004_py310.py @@ -1,9 +1,10 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone +import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt -from passlib.context import CryptContext +from jwt.exceptions import InvalidTokenError +from pwdlib import PasswordHash from pydantic import BaseModel # to get a string like this run: @@ -18,7 +19,7 @@ "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", - "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW", + "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, } } @@ -44,7 +45,9 @@ class UserInDB(User): hashed_password: str -pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") +password_hash = PasswordHash.recommended() + +DUMMY_HASH = password_hash.hash("dummypassword") oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") @@ -52,11 +55,11 @@ class UserInDB(User): def verify_password(plain_password, hashed_password): - return pwd_context.verify(plain_password, hashed_password) + return password_hash.verify(plain_password, hashed_password) def get_password_hash(password): - return pwd_context.hash(password) + return password_hash.hash(password) def get_user(db, username: str): @@ -68,6 +71,7 @@ def get_user(db, username: str): def authenticate_user(fake_db, username: str, password: str): user = get_user(fake_db, username) if not user: + verify_password(password, DUMMY_HASH) return False if not verify_password(password, user.hashed_password): return False @@ -77,9 +81,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: timedelta | None = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -93,11 +97,11 @@ async def get_current_user(token: str = Depends(oauth2_scheme)): ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) - except JWTError: + except InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: @@ -111,8 +115,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,11 +130,11 @@ 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) -async def read_users_me(current_user: User = Depends(get_current_active_user)): +@app.get("/users/me/") +async def read_users_me(current_user: User = Depends(get_current_active_user)) -> User: return current_user diff --git a/docs_src/security/tutorial005.py b/docs_src/security/tutorial005.py deleted file mode 100644 index bd0a33581c21c..0000000000000 --- a/docs_src/security/tutorial005.py +++ /dev/null @@ -1,173 +0,0 @@ -from datetime import datetime, timedelta -from typing import List, Union - -from fastapi import Depends, FastAPI, HTTPException, Security, status -from fastapi.security import ( - OAuth2PasswordBearer, - OAuth2PasswordRequestForm, - SecurityScopes, -) -from jose import JWTError, jwt -from passlib.context import CryptContext -from pydantic import BaseModel, ValidationError - -# to get a string like this run: -# openssl rand -hex 32 -SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" -ALGORITHM = "HS256" -ACCESS_TOKEN_EXPIRE_MINUTES = 30 - - -fake_users_db = { - "johndoe": { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW", - "disabled": False, - }, - "alice": { - "username": "alice", - "full_name": "Alice Chains", - "email": "alicechains@example.com", - "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm", - "disabled": True, - }, -} - - -class Token(BaseModel): - access_token: str - token_type: str - - -class TokenData(BaseModel): - username: Union[str, None] = None - scopes: List[str] = [] - - -class User(BaseModel): - username: str - email: Union[str, None] = None - full_name: Union[str, None] = None - disabled: Union[bool, None] = None - - -class UserInDB(User): - hashed_password: str - - -pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") - -oauth2_scheme = OAuth2PasswordBearer( - tokenUrl="token", - scopes={"me": "Read information about the current user.", "items": "Read items."}, -) - -app = FastAPI() - - -def verify_password(plain_password, hashed_password): - return pwd_context.verify(plain_password, hashed_password) - - -def get_password_hash(password): - return pwd_context.hash(password) - - -def get_user(db, username: str): - if username in db: - user_dict = db[username] - return UserInDB(**user_dict) - - -def authenticate_user(fake_db, username: str, password: str): - user = get_user(fake_db, username) - if not user: - return False - if not verify_password(password, user.hashed_password): - return False - return user - - -def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): - to_encode = data.copy() - if expires_delta: - expire = datetime.utcnow() + expires_delta - else: - expire = datetime.utcnow() + timedelta(minutes=15) - to_encode.update({"exp": expire}) - encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) - return encoded_jwt - - -async def get_current_user( - security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme) -): - if security_scopes.scopes: - authenticate_value = f'Bearer scope="{security_scopes.scope_str}"' - else: - authenticate_value = "Bearer" - credentials_exception = HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Could not validate credentials", - headers={"WWW-Authenticate": authenticate_value}, - ) - try: - payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") - if username is None: - raise credentials_exception - token_scopes = payload.get("scopes", []) - token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): - raise credentials_exception - user = get_user(fake_users_db, username=token_data.username) - if user is None: - raise credentials_exception - for scope in security_scopes.scopes: - if scope not in token_data.scopes: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Not enough permissions", - headers={"WWW-Authenticate": authenticate_value}, - ) - return user - - -async def get_current_active_user( - current_user: User = Security(get_current_user, scopes=["me"]) -): - if current_user.disabled: - raise HTTPException(status_code=400, detail="Inactive user") - return current_user - - -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): - 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") - access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) - access_token = create_access_token( - data={"sub": user.username, "scopes": form_data.scopes}, - expires_delta=access_token_expires, - ) - return {"access_token": access_token, "token_type": "bearer"} - - -@app.get("/users/me/", response_model=User) -async def read_users_me(current_user: User = Depends(get_current_active_user)): - return current_user - - -@app.get("/users/me/items/") -async def read_own_items( - current_user: User = Security(get_current_active_user, scopes=["items"]) -): - return [{"item_id": "Foo", "owner": current_user.username}] - - -@app.get("/status/") -async def read_system_status(current_user: User = Depends(get_current_user)): - return {"status": "ok"} diff --git a/docs_src/security/tutorial005_an.py b/docs_src/security/tutorial005_an.py deleted file mode 100644 index ec4fa1a07e2cd..0000000000000 --- a/docs_src/security/tutorial005_an.py +++ /dev/null @@ -1,178 +0,0 @@ -from datetime import datetime, timedelta -from typing import List, Union - -from fastapi import Depends, FastAPI, HTTPException, Security, status -from fastapi.security import ( - OAuth2PasswordBearer, - OAuth2PasswordRequestForm, - SecurityScopes, -) -from jose import JWTError, jwt -from passlib.context import CryptContext -from pydantic import BaseModel, ValidationError -from typing_extensions import Annotated - -# to get a string like this run: -# openssl rand -hex 32 -SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" -ALGORITHM = "HS256" -ACCESS_TOKEN_EXPIRE_MINUTES = 30 - - -fake_users_db = { - "johndoe": { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW", - "disabled": False, - }, - "alice": { - "username": "alice", - "full_name": "Alice Chains", - "email": "alicechains@example.com", - "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm", - "disabled": True, - }, -} - - -class Token(BaseModel): - access_token: str - token_type: str - - -class TokenData(BaseModel): - username: Union[str, None] = None - scopes: List[str] = [] - - -class User(BaseModel): - username: str - email: Union[str, None] = None - full_name: Union[str, None] = None - disabled: Union[bool, None] = None - - -class UserInDB(User): - hashed_password: str - - -pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") - -oauth2_scheme = OAuth2PasswordBearer( - tokenUrl="token", - scopes={"me": "Read information about the current user.", "items": "Read items."}, -) - -app = FastAPI() - - -def verify_password(plain_password, hashed_password): - return pwd_context.verify(plain_password, hashed_password) - - -def get_password_hash(password): - return pwd_context.hash(password) - - -def get_user(db, username: str): - if username in db: - user_dict = db[username] - return UserInDB(**user_dict) - - -def authenticate_user(fake_db, username: str, password: str): - user = get_user(fake_db, username) - if not user: - return False - if not verify_password(password, user.hashed_password): - return False - return user - - -def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): - to_encode = data.copy() - if expires_delta: - expire = datetime.utcnow() + expires_delta - else: - expire = datetime.utcnow() + timedelta(minutes=15) - to_encode.update({"exp": expire}) - encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) - return encoded_jwt - - -async def get_current_user( - security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)] -): - if security_scopes.scopes: - authenticate_value = f'Bearer scope="{security_scopes.scope_str}"' - else: - authenticate_value = "Bearer" - credentials_exception = HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Could not validate credentials", - headers={"WWW-Authenticate": authenticate_value}, - ) - try: - payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") - if username is None: - raise credentials_exception - token_scopes = payload.get("scopes", []) - token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): - raise credentials_exception - user = get_user(fake_users_db, username=token_data.username) - if user is None: - raise credentials_exception - for scope in security_scopes.scopes: - if scope not in token_data.scopes: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Not enough permissions", - headers={"WWW-Authenticate": authenticate_value}, - ) - return user - - -async def get_current_active_user( - current_user: Annotated[User, Security(get_current_user, scopes=["me"])] -): - if current_user.disabled: - raise HTTPException(status_code=400, detail="Inactive user") - return current_user - - -@app.post("/token", response_model=Token) -async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): - 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") - access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) - access_token = create_access_token( - data={"sub": user.username, "scopes": form_data.scopes}, - expires_delta=access_token_expires, - ) - return {"access_token": access_token, "token_type": "bearer"} - - -@app.get("/users/me/", response_model=User) -async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] -): - return current_user - - -@app.get("/users/me/items/") -async def read_own_items( - current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] -): - return [{"item_id": "Foo", "owner": current_user.username}] - - -@app.get("/status/") -async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]): - return {"status": "ok"} diff --git a/docs_src/security/tutorial005_an_py310.py b/docs_src/security/tutorial005_an_py310.py index 45f3fc0bd6de1..9911723db7dbc 100644 --- a/docs_src/security/tutorial005_an_py310.py +++ b/docs_src/security/tutorial005_an_py310.py @@ -1,14 +1,15 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Annotated +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt -from passlib.context import CryptContext +from jwt.exceptions import InvalidTokenError +from pwdlib import PasswordHash from pydantic import BaseModel, ValidationError # to get a string like this run: @@ -23,14 +24,14 @@ "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", - "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW", + "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, }, "alice": { "username": "alice", "full_name": "Alice Chains", "email": "alicechains@example.com", - "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm", + "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$g2/AV1zwopqUntPKJavBFw$BwpRGDCyUHLvHICnwijyX8ROGoiUPwNKZ7915MeYfCE", "disabled": True, }, } @@ -57,7 +58,9 @@ class UserInDB(User): hashed_password: str -pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") +password_hash = PasswordHash.recommended() + +DUMMY_HASH = password_hash.hash("dummypassword") oauth2_scheme = OAuth2PasswordBearer( tokenUrl="token", @@ -68,11 +71,11 @@ class UserInDB(User): def verify_password(plain_password, hashed_password): - return pwd_context.verify(plain_password, hashed_password) + return password_hash.verify(plain_password, hashed_password) def get_password_hash(password): - return pwd_context.hash(password) + return password_hash.hash(password) def get_user(db, username: str): @@ -84,6 +87,7 @@ def get_user(db, username: str): def authenticate_user(fake_db, username: str, password: str): user = get_user(fake_db, username) if not user: + verify_password(password, DUMMY_HASH) return False if not verify_password(password, user.hashed_password): return False @@ -93,9 +97,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: timedelta | None = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -115,12 +119,13 @@ async def get_current_user( ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception - token_scopes = payload.get("scopes", []) + scope: str = payload.get("scope", "") + token_scopes = scope.split(" ") token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: @@ -136,38 +141,38 @@ async def get_current_user( async def get_current_active_user( - current_user: Annotated[User, Security(get_current_user, scopes=["me"])] + current_user: Annotated[User, Security(get_current_user, scopes=["me"])], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): + 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") access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) access_token = create_access_token( - data={"sub": user.username, "scopes": form_data.scopes}, + data={"sub": user.username, "scope": " ".join(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) +@app.get("/users/me/") async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] -): + current_user: Annotated[User, Depends(get_current_active_user)], +) -> User: return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] + current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial005_an_py39.py b/docs_src/security/tutorial005_an_py39.py deleted file mode 100644 index ecb5ed5160d86..0000000000000 --- a/docs_src/security/tutorial005_an_py39.py +++ /dev/null @@ -1,177 +0,0 @@ -from datetime import datetime, timedelta -from typing import Annotated, List, Union - -from fastapi import Depends, FastAPI, HTTPException, Security, status -from fastapi.security import ( - OAuth2PasswordBearer, - OAuth2PasswordRequestForm, - SecurityScopes, -) -from jose import JWTError, jwt -from passlib.context import CryptContext -from pydantic import BaseModel, ValidationError - -# to get a string like this run: -# openssl rand -hex 32 -SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" -ALGORITHM = "HS256" -ACCESS_TOKEN_EXPIRE_MINUTES = 30 - - -fake_users_db = { - "johndoe": { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW", - "disabled": False, - }, - "alice": { - "username": "alice", - "full_name": "Alice Chains", - "email": "alicechains@example.com", - "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm", - "disabled": True, - }, -} - - -class Token(BaseModel): - access_token: str - token_type: str - - -class TokenData(BaseModel): - username: Union[str, None] = None - scopes: List[str] = [] - - -class User(BaseModel): - username: str - email: Union[str, None] = None - full_name: Union[str, None] = None - disabled: Union[bool, None] = None - - -class UserInDB(User): - hashed_password: str - - -pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") - -oauth2_scheme = OAuth2PasswordBearer( - tokenUrl="token", - scopes={"me": "Read information about the current user.", "items": "Read items."}, -) - -app = FastAPI() - - -def verify_password(plain_password, hashed_password): - return pwd_context.verify(plain_password, hashed_password) - - -def get_password_hash(password): - return pwd_context.hash(password) - - -def get_user(db, username: str): - if username in db: - user_dict = db[username] - return UserInDB(**user_dict) - - -def authenticate_user(fake_db, username: str, password: str): - user = get_user(fake_db, username) - if not user: - return False - if not verify_password(password, user.hashed_password): - return False - return user - - -def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): - to_encode = data.copy() - if expires_delta: - expire = datetime.utcnow() + expires_delta - else: - expire = datetime.utcnow() + timedelta(minutes=15) - to_encode.update({"exp": expire}) - encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) - return encoded_jwt - - -async def get_current_user( - security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)] -): - if security_scopes.scopes: - authenticate_value = f'Bearer scope="{security_scopes.scope_str}"' - else: - authenticate_value = "Bearer" - credentials_exception = HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Could not validate credentials", - headers={"WWW-Authenticate": authenticate_value}, - ) - try: - payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") - if username is None: - raise credentials_exception - token_scopes = payload.get("scopes", []) - token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): - raise credentials_exception - user = get_user(fake_users_db, username=token_data.username) - if user is None: - raise credentials_exception - for scope in security_scopes.scopes: - if scope not in token_data.scopes: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Not enough permissions", - headers={"WWW-Authenticate": authenticate_value}, - ) - return user - - -async def get_current_active_user( - current_user: Annotated[User, Security(get_current_user, scopes=["me"])] -): - if current_user.disabled: - raise HTTPException(status_code=400, detail="Inactive user") - return current_user - - -@app.post("/token", response_model=Token) -async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): - 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") - access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) - access_token = create_access_token( - data={"sub": user.username, "scopes": form_data.scopes}, - expires_delta=access_token_expires, - ) - return {"access_token": access_token, "token_type": "bearer"} - - -@app.get("/users/me/", response_model=User) -async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] -): - return current_user - - -@app.get("/users/me/items/") -async def read_own_items( - current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] -): - return [{"item_id": "Foo", "owner": current_user.username}] - - -@app.get("/status/") -async def read_system_status(current_user: Annotated[User, Depends(get_current_user)]): - return {"status": "ok"} diff --git a/docs_src/security/tutorial005_py310.py b/docs_src/security/tutorial005_py310.py index ba756ef4f4d67..710cdac329ca3 100644 --- a/docs_src/security/tutorial005_py310.py +++ b/docs_src/security/tutorial005_py310.py @@ -1,13 +1,14 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt -from passlib.context import CryptContext +from jwt.exceptions import InvalidTokenError +from pwdlib import PasswordHash from pydantic import BaseModel, ValidationError # to get a string like this run: @@ -22,14 +23,14 @@ "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", - "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW", + "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc", "disabled": False, }, "alice": { "username": "alice", "full_name": "Alice Chains", "email": "alicechains@example.com", - "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm", + "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$g2/AV1zwopqUntPKJavBFw$BwpRGDCyUHLvHICnwijyX8ROGoiUPwNKZ7915MeYfCE", "disabled": True, }, } @@ -56,7 +57,9 @@ class UserInDB(User): hashed_password: str -pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") +password_hash = PasswordHash.recommended() + +DUMMY_HASH = password_hash.hash("dummypassword") oauth2_scheme = OAuth2PasswordBearer( tokenUrl="token", @@ -67,11 +70,11 @@ class UserInDB(User): def verify_password(plain_password, hashed_password): - return pwd_context.verify(plain_password, hashed_password) + return password_hash.verify(plain_password, hashed_password) def get_password_hash(password): - return pwd_context.hash(password) + return password_hash.hash(password) def get_user(db, username: str): @@ -83,6 +86,7 @@ def get_user(db, username: str): def authenticate_user(fake_db, username: str, password: str): user = get_user(fake_db, username) if not user: + verify_password(password, DUMMY_HASH) return False if not verify_password(password, user.hashed_password): return False @@ -92,9 +96,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: timedelta | None = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -117,9 +121,10 @@ async def get_current_user( username: str = payload.get("sub") if username is None: raise credentials_exception - token_scopes = payload.get("scopes", []) + scope: str = payload.get("scope", "") + token_scopes = scope.split(" ") token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: @@ -135,34 +140,36 @@ async def get_current_user( async def get_current_active_user( - current_user: User = Security(get_current_user, scopes=["me"]) + current_user: User = Security(get_current_user, scopes=["me"]), ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive 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") access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) access_token = create_access_token( - data={"sub": user.username, "scopes": form_data.scopes}, + data={"sub": user.username, "scope": " ".join(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) -async def read_users_me(current_user: User = Depends(get_current_active_user)): +@app.get("/users/me/") +async def read_users_me(current_user: User = Depends(get_current_active_user)) -> User: return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: User = Security(get_current_active_user, scopes=["items"]) + current_user: User = Security(get_current_active_user, scopes=["items"]), ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial005_py39.py b/docs_src/security/tutorial005_py39.py deleted file mode 100644 index 9e4dbcffba38d..0000000000000 --- a/docs_src/security/tutorial005_py39.py +++ /dev/null @@ -1,173 +0,0 @@ -from datetime import datetime, timedelta -from typing import Union - -from fastapi import Depends, FastAPI, HTTPException, Security, status -from fastapi.security import ( - OAuth2PasswordBearer, - OAuth2PasswordRequestForm, - SecurityScopes, -) -from jose import JWTError, jwt -from passlib.context import CryptContext -from pydantic import BaseModel, ValidationError - -# to get a string like this run: -# openssl rand -hex 32 -SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" -ALGORITHM = "HS256" -ACCESS_TOKEN_EXPIRE_MINUTES = 30 - - -fake_users_db = { - "johndoe": { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW", - "disabled": False, - }, - "alice": { - "username": "alice", - "full_name": "Alice Chains", - "email": "alicechains@example.com", - "hashed_password": "$2b$12$gSvqqUPvlXP2tfVFaWK1Be7DlH.PKZbv5H8KnzzVgXXbVxpva.pFm", - "disabled": True, - }, -} - - -class Token(BaseModel): - access_token: str - token_type: str - - -class TokenData(BaseModel): - username: Union[str, None] = None - scopes: list[str] = [] - - -class User(BaseModel): - username: str - email: Union[str, None] = None - full_name: Union[str, None] = None - disabled: Union[bool, None] = None - - -class UserInDB(User): - hashed_password: str - - -pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") - -oauth2_scheme = OAuth2PasswordBearer( - tokenUrl="token", - scopes={"me": "Read information about the current user.", "items": "Read items."}, -) - -app = FastAPI() - - -def verify_password(plain_password, hashed_password): - return pwd_context.verify(plain_password, hashed_password) - - -def get_password_hash(password): - return pwd_context.hash(password) - - -def get_user(db, username: str): - if username in db: - user_dict = db[username] - return UserInDB(**user_dict) - - -def authenticate_user(fake_db, username: str, password: str): - user = get_user(fake_db, username) - if not user: - return False - if not verify_password(password, user.hashed_password): - return False - return user - - -def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): - to_encode = data.copy() - if expires_delta: - expire = datetime.utcnow() + expires_delta - else: - expire = datetime.utcnow() + timedelta(minutes=15) - to_encode.update({"exp": expire}) - encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) - return encoded_jwt - - -async def get_current_user( - security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme) -): - if security_scopes.scopes: - authenticate_value = f'Bearer scope="{security_scopes.scope_str}"' - else: - authenticate_value = "Bearer" - credentials_exception = HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Could not validate credentials", - headers={"WWW-Authenticate": authenticate_value}, - ) - try: - payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") - if username is None: - raise credentials_exception - token_scopes = payload.get("scopes", []) - token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): - raise credentials_exception - user = get_user(fake_users_db, username=token_data.username) - if user is None: - raise credentials_exception - for scope in security_scopes.scopes: - if scope not in token_data.scopes: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Not enough permissions", - headers={"WWW-Authenticate": authenticate_value}, - ) - return user - - -async def get_current_active_user( - current_user: User = Security(get_current_user, scopes=["me"]) -): - if current_user.disabled: - raise HTTPException(status_code=400, detail="Inactive user") - return current_user - - -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): - 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") - access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) - access_token = create_access_token( - data={"sub": user.username, "scopes": form_data.scopes}, - expires_delta=access_token_expires, - ) - return {"access_token": access_token, "token_type": "bearer"} - - -@app.get("/users/me/", response_model=User) -async def read_users_me(current_user: User = Depends(get_current_active_user)): - return current_user - - -@app.get("/users/me/items/") -async def read_own_items( - current_user: User = Security(get_current_active_user, scopes=["items"]) -): - return [{"item_id": "Foo", "owner": current_user.username}] - - -@app.get("/status/") -async def read_system_status(current_user: User = Depends(get_current_user)): - return {"status": "ok"} diff --git a/docs_src/security/tutorial006_an.py b/docs_src/security/tutorial006_an.py deleted file mode 100644 index 985e4b2ad2a25..0000000000000 --- a/docs_src/security/tutorial006_an.py +++ /dev/null @@ -1,12 +0,0 @@ -from fastapi import Depends, FastAPI -from fastapi.security import HTTPBasic, HTTPBasicCredentials -from typing_extensions import Annotated - -app = FastAPI() - -security = HTTPBasic() - - -@app.get("/users/me") -def read_current_user(credentials: Annotated[HTTPBasicCredentials, Depends(security)]): - return {"username": credentials.username, "password": credentials.password} diff --git a/docs_src/security/tutorial006_an_py39.py b/docs_src/security/tutorial006_an_py310.py similarity index 100% rename from docs_src/security/tutorial006_an_py39.py rename to docs_src/security/tutorial006_an_py310.py diff --git a/docs_src/security/tutorial006.py b/docs_src/security/tutorial006_py310.py similarity index 100% rename from docs_src/security/tutorial006.py rename to docs_src/security/tutorial006_py310.py diff --git a/docs_src/security/tutorial007.py b/docs_src/security/tutorial007.py deleted file mode 100644 index 790ee10bc6b1d..0000000000000 --- a/docs_src/security/tutorial007.py +++ /dev/null @@ -1,33 +0,0 @@ -import secrets - -from fastapi import Depends, FastAPI, HTTPException, status -from fastapi.security import HTTPBasic, HTTPBasicCredentials - -app = FastAPI() - -security = HTTPBasic() - - -def get_current_username(credentials: HTTPBasicCredentials = Depends(security)): - current_username_bytes = credentials.username.encode("utf8") - correct_username_bytes = b"stanleyjobson" - is_correct_username = secrets.compare_digest( - current_username_bytes, correct_username_bytes - ) - current_password_bytes = credentials.password.encode("utf8") - correct_password_bytes = b"swordfish" - is_correct_password = secrets.compare_digest( - current_password_bytes, correct_password_bytes - ) - if not (is_correct_username and is_correct_password): - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect email or password", - headers={"WWW-Authenticate": "Basic"}, - ) - return credentials.username - - -@app.get("/users/me") -def read_current_user(username: str = Depends(get_current_username)): - return {"username": username} diff --git a/docs_src/security/tutorial007_an.py b/docs_src/security/tutorial007_an.py deleted file mode 100644 index 5fb7c8e57560c..0000000000000 --- a/docs_src/security/tutorial007_an.py +++ /dev/null @@ -1,36 +0,0 @@ -import secrets - -from fastapi import Depends, FastAPI, HTTPException, status -from fastapi.security import HTTPBasic, HTTPBasicCredentials -from typing_extensions import Annotated - -app = FastAPI() - -security = HTTPBasic() - - -def get_current_username( - credentials: Annotated[HTTPBasicCredentials, Depends(security)] -): - current_username_bytes = credentials.username.encode("utf8") - correct_username_bytes = b"stanleyjobson" - is_correct_username = secrets.compare_digest( - current_username_bytes, correct_username_bytes - ) - current_password_bytes = credentials.password.encode("utf8") - correct_password_bytes = b"swordfish" - is_correct_password = secrets.compare_digest( - current_password_bytes, correct_password_bytes - ) - if not (is_correct_username and is_correct_password): - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect email or password", - headers={"WWW-Authenticate": "Basic"}, - ) - return credentials.username - - -@app.get("/users/me") -def read_current_user(username: Annotated[str, Depends(get_current_username)]): - return {"username": username} diff --git a/docs_src/security/tutorial007_an_py310.py b/docs_src/security/tutorial007_an_py310.py new file mode 100644 index 0000000000000..87ef986574354 --- /dev/null +++ b/docs_src/security/tutorial007_an_py310.py @@ -0,0 +1,36 @@ +import secrets +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException, status +from fastapi.security import HTTPBasic, HTTPBasicCredentials + +app = FastAPI() + +security = HTTPBasic() + + +def get_current_username( + credentials: Annotated[HTTPBasicCredentials, Depends(security)], +): + current_username_bytes = credentials.username.encode("utf8") + correct_username_bytes = b"stanleyjobson" + is_correct_username = secrets.compare_digest( + current_username_bytes, correct_username_bytes + ) + current_password_bytes = credentials.password.encode("utf8") + correct_password_bytes = b"swordfish" + is_correct_password = secrets.compare_digest( + current_password_bytes, correct_password_bytes + ) + if not (is_correct_username and is_correct_password): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect username or password", + headers={"WWW-Authenticate": "Basic"}, + ) + return credentials.username + + +@app.get("/users/me") +def read_current_user(username: Annotated[str, Depends(get_current_username)]): + return {"username": username} diff --git a/docs_src/security/tutorial007_an_py39.py b/docs_src/security/tutorial007_an_py39.py deleted file mode 100644 index 17177dabf9e47..0000000000000 --- a/docs_src/security/tutorial007_an_py39.py +++ /dev/null @@ -1,36 +0,0 @@ -import secrets -from typing import Annotated - -from fastapi import Depends, FastAPI, HTTPException, status -from fastapi.security import HTTPBasic, HTTPBasicCredentials - -app = FastAPI() - -security = HTTPBasic() - - -def get_current_username( - credentials: Annotated[HTTPBasicCredentials, Depends(security)] -): - current_username_bytes = credentials.username.encode("utf8") - correct_username_bytes = b"stanleyjobson" - is_correct_username = secrets.compare_digest( - current_username_bytes, correct_username_bytes - ) - current_password_bytes = credentials.password.encode("utf8") - correct_password_bytes = b"swordfish" - is_correct_password = secrets.compare_digest( - current_password_bytes, correct_password_bytes - ) - if not (is_correct_username and is_correct_password): - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect email or password", - headers={"WWW-Authenticate": "Basic"}, - ) - return credentials.username - - -@app.get("/users/me") -def read_current_user(username: Annotated[str, Depends(get_current_username)]): - return {"username": username} diff --git a/docs_src/security/tutorial007_py310.py b/docs_src/security/tutorial007_py310.py new file mode 100644 index 0000000000000..ac816eb0c19d2 --- /dev/null +++ b/docs_src/security/tutorial007_py310.py @@ -0,0 +1,33 @@ +import secrets + +from fastapi import Depends, FastAPI, HTTPException, status +from fastapi.security import HTTPBasic, HTTPBasicCredentials + +app = FastAPI() + +security = HTTPBasic() + + +def get_current_username(credentials: HTTPBasicCredentials = Depends(security)): + current_username_bytes = credentials.username.encode("utf8") + correct_username_bytes = b"stanleyjobson" + is_correct_username = secrets.compare_digest( + current_username_bytes, correct_username_bytes + ) + current_password_bytes = credentials.password.encode("utf8") + correct_password_bytes = b"swordfish" + is_correct_password = secrets.compare_digest( + current_password_bytes, correct_password_bytes + ) + if not (is_correct_username and is_correct_password): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect username or password", + headers={"WWW-Authenticate": "Basic"}, + ) + return credentials.username + + +@app.get("/users/me") +def read_current_user(username: str = Depends(get_current_username)): + return {"username": username} diff --git a/docs_src/separate_openapi_schemas/__init__.py b/docs_src/separate_openapi_schemas/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/separate_openapi_schemas/tutorial001.py b/docs_src/separate_openapi_schemas/tutorial001.py deleted file mode 100644 index 415eef8e2824f..0000000000000 --- a/docs_src/separate_openapi_schemas/tutorial001.py +++ /dev/null @@ -1,28 +0,0 @@ -from typing import List, Union - -from fastapi import FastAPI -from pydantic import BaseModel - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - - -app = FastAPI() - - -@app.post("/items/") -def create_item(item: Item): - return item - - -@app.get("/items/") -def read_items() -> List[Item]: - return [ - Item( - name="Portal Gun", - description="Device to travel through the multi-rick-verse", - ), - Item(name="Plumbus"), - ] diff --git a/docs_src/separate_openapi_schemas/tutorial001_py39.py b/docs_src/separate_openapi_schemas/tutorial001_py39.py deleted file mode 100644 index 63cffd1e307fb..0000000000000 --- a/docs_src/separate_openapi_schemas/tutorial001_py39.py +++ /dev/null @@ -1,28 +0,0 @@ -from typing import Optional - -from fastapi import FastAPI -from pydantic import BaseModel - - -class Item(BaseModel): - name: str - description: Optional[str] = None - - -app = FastAPI() - - -@app.post("/items/") -def create_item(item: Item): - return item - - -@app.get("/items/") -def read_items() -> list[Item]: - return [ - Item( - name="Portal Gun", - description="Device to travel through the multi-rick-verse", - ), - Item(name="Plumbus"), - ] diff --git a/docs_src/separate_openapi_schemas/tutorial002.py b/docs_src/separate_openapi_schemas/tutorial002.py deleted file mode 100644 index 7df93783b9585..0000000000000 --- a/docs_src/separate_openapi_schemas/tutorial002.py +++ /dev/null @@ -1,28 +0,0 @@ -from typing import List, Union - -from fastapi import FastAPI -from pydantic import BaseModel - - -class Item(BaseModel): - name: str - description: Union[str, None] = None - - -app = FastAPI(separate_input_output_schemas=False) - - -@app.post("/items/") -def create_item(item: Item): - return item - - -@app.get("/items/") -def read_items() -> List[Item]: - return [ - Item( - name="Portal Gun", - description="Device to travel through the multi-rick-verse", - ), - Item(name="Plumbus"), - ] diff --git a/docs_src/separate_openapi_schemas/tutorial002_py39.py b/docs_src/separate_openapi_schemas/tutorial002_py39.py deleted file mode 100644 index 50d997d92aa43..0000000000000 --- a/docs_src/separate_openapi_schemas/tutorial002_py39.py +++ /dev/null @@ -1,28 +0,0 @@ -from typing import Optional - -from fastapi import FastAPI -from pydantic import BaseModel - - -class Item(BaseModel): - name: str - description: Optional[str] = None - - -app = FastAPI(separate_input_output_schemas=False) - - -@app.post("/items/") -def create_item(item: Item): - return item - - -@app.get("/items/") -def read_items() -> list[Item]: - return [ - Item( - name="Portal Gun", - description="Device to travel through the multi-rick-verse", - ), - Item(name="Plumbus"), - ] diff --git a/docs_src/server_sent_events/__init__.py b/docs_src/server_sent_events/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/server_sent_events/tutorial001_py310.py b/docs_src/server_sent_events/tutorial001_py310.py new file mode 100644 index 0000000000000..8fa470da50d7b --- /dev/null +++ b/docs_src/server_sent_events/tutorial001_py310.py @@ -0,0 +1,43 @@ +from collections.abc import AsyncIterable, Iterable + +from fastapi import FastAPI +from fastapi.sse import EventSourceResponse +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + description: str | None + + +items = [ + Item(name="Plumbus", description="A multi-purpose household device."), + Item(name="Portal Gun", description="A portal opening device."), + Item(name="Meeseeks Box", description="A box that summons a Meeseeks."), +] + + +@app.get("/items/stream", response_class=EventSourceResponse) +async def sse_items() -> AsyncIterable[Item]: + for item in items: + yield item + + +@app.get("/items/stream-no-async", response_class=EventSourceResponse) +def sse_items_no_async() -> Iterable[Item]: + for item in items: + yield item + + +@app.get("/items/stream-no-annotation", response_class=EventSourceResponse) +async def sse_items_no_annotation(): + for item in items: + yield item + + +@app.get("/items/stream-no-async-no-annotation", response_class=EventSourceResponse) +def sse_items_no_async_no_annotation(): + for item in items: + yield item diff --git a/docs_src/server_sent_events/tutorial002_py310.py b/docs_src/server_sent_events/tutorial002_py310.py new file mode 100644 index 0000000000000..0f6136f4fdd19 --- /dev/null +++ b/docs_src/server_sent_events/tutorial002_py310.py @@ -0,0 +1,26 @@ +from collections.abc import AsyncIterable + +from fastapi import FastAPI +from fastapi.sse import EventSourceResponse, ServerSentEvent +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + + +items = [ + Item(name="Plumbus", price=32.99), + Item(name="Portal Gun", price=999.99), + Item(name="Meeseeks Box", price=49.99), +] + + +@app.get("/items/stream", response_class=EventSourceResponse) +async def stream_items() -> AsyncIterable[ServerSentEvent]: + yield ServerSentEvent(comment="stream of item updates") + for i, item in enumerate(items): + yield ServerSentEvent(data=item, event="item_update", id=str(i + 1), retry=5000) diff --git a/docs_src/server_sent_events/tutorial003_py310.py b/docs_src/server_sent_events/tutorial003_py310.py new file mode 100644 index 0000000000000..3006deb86d3c2 --- /dev/null +++ b/docs_src/server_sent_events/tutorial003_py310.py @@ -0,0 +1,17 @@ +from collections.abc import AsyncIterable + +from fastapi import FastAPI +from fastapi.sse import EventSourceResponse, ServerSentEvent + +app = FastAPI() + + +@app.get("/logs/stream", response_class=EventSourceResponse) +async def stream_logs() -> AsyncIterable[ServerSentEvent]: + logs = [ + "2025-01-01 INFO Application started", + "2025-01-01 DEBUG Connected to database", + "2025-01-01 WARN High memory usage detected", + ] + for log_line in logs: + yield ServerSentEvent(raw_data=log_line) diff --git a/docs_src/server_sent_events/tutorial004_py310.py b/docs_src/server_sent_events/tutorial004_py310.py new file mode 100644 index 0000000000000..3e8f8d113fc8a --- /dev/null +++ b/docs_src/server_sent_events/tutorial004_py310.py @@ -0,0 +1,31 @@ +from collections.abc import AsyncIterable +from typing import Annotated + +from fastapi import FastAPI, Header +from fastapi.sse import EventSourceResponse, ServerSentEvent +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + + +items = [ + Item(name="Plumbus", price=32.99), + Item(name="Portal Gun", price=999.99), + Item(name="Meeseeks Box", price=49.99), +] + + +@app.get("/items/stream", response_class=EventSourceResponse) +async def stream_items( + last_event_id: Annotated[int | None, Header()] = None, +) -> AsyncIterable[ServerSentEvent]: + start = last_event_id + 1 if last_event_id is not None else 0 + for i, item in enumerate(items): + if i < start: + continue + yield ServerSentEvent(data=item, id=str(i)) diff --git a/docs_src/server_sent_events/tutorial005_py310.py b/docs_src/server_sent_events/tutorial005_py310.py new file mode 100644 index 0000000000000..4e6730e5aac72 --- /dev/null +++ b/docs_src/server_sent_events/tutorial005_py310.py @@ -0,0 +1,19 @@ +from collections.abc import AsyncIterable + +from fastapi import FastAPI +from fastapi.sse import EventSourceResponse, ServerSentEvent +from pydantic import BaseModel + +app = FastAPI() + + +class Prompt(BaseModel): + text: str + + +@app.post("/chat/stream", response_class=EventSourceResponse) +async def stream_chat(prompt: Prompt) -> AsyncIterable[ServerSentEvent]: + words = prompt.text.split() + for word in words: + yield ServerSentEvent(data=word, event="token") + yield ServerSentEvent(raw_data="[DONE]", event="done") diff --git a/docs_src/settings/__init__.py b/docs_src/settings/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/settings/app01_py310/__init__.py b/docs_src/settings/app01_py310/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/settings/app01/config.py b/docs_src/settings/app01_py310/config.py similarity index 100% rename from docs_src/settings/app01/config.py rename to docs_src/settings/app01_py310/config.py diff --git a/docs_src/settings/app01/main.py b/docs_src/settings/app01_py310/main.py similarity index 100% rename from docs_src/settings/app01/main.py rename to docs_src/settings/app01_py310/main.py diff --git a/docs_src/settings/app02/main.py b/docs_src/settings/app02/main.py deleted file mode 100644 index 163aa26142464..0000000000000 --- a/docs_src/settings/app02/main.py +++ /dev/null @@ -1,21 +0,0 @@ -from functools import lru_cache - -from fastapi import Depends, FastAPI - -from .config import Settings - -app = FastAPI() - - -@lru_cache() -def get_settings(): - return Settings() - - -@app.get("/info") -async def info(settings: Settings = Depends(get_settings)): - return { - "app_name": settings.app_name, - "admin_email": settings.admin_email, - "items_per_user": settings.items_per_user, - } diff --git a/docs_src/settings/app02_an/main.py b/docs_src/settings/app02_an/main.py deleted file mode 100644 index cb679202d6ed5..0000000000000 --- a/docs_src/settings/app02_an/main.py +++ /dev/null @@ -1,22 +0,0 @@ -from functools import lru_cache - -from fastapi import Depends, FastAPI -from typing_extensions import Annotated - -from .config import Settings - -app = FastAPI() - - -@lru_cache() -def get_settings(): - return Settings() - - -@app.get("/info") -async def info(settings: Annotated[Settings, Depends(get_settings)]): - return { - "app_name": settings.app_name, - "admin_email": settings.admin_email, - "items_per_user": settings.items_per_user, - } diff --git a/docs_src/settings/app02_an_py310/__init__.py b/docs_src/settings/app02_an_py310/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/settings/app02/config.py b/docs_src/settings/app02_an_py310/config.py similarity index 100% rename from docs_src/settings/app02/config.py rename to docs_src/settings/app02_an_py310/config.py diff --git a/docs_src/settings/app02_an_py310/main.py b/docs_src/settings/app02_an_py310/main.py new file mode 100644 index 0000000000000..6d5db12a87941 --- /dev/null +++ b/docs_src/settings/app02_an_py310/main.py @@ -0,0 +1,22 @@ +from functools import lru_cache +from typing import Annotated + +from fastapi import Depends, FastAPI + +from .config import Settings + +app = FastAPI() + + +@lru_cache +def get_settings(): + return Settings() + + +@app.get("/info") +async def info(settings: Annotated[Settings, Depends(get_settings)]): + return { + "app_name": settings.app_name, + "admin_email": settings.admin_email, + "items_per_user": settings.items_per_user, + } diff --git a/docs_src/settings/app02/test_main.py b/docs_src/settings/app02_an_py310/test_main.py similarity index 100% rename from docs_src/settings/app02/test_main.py rename to docs_src/settings/app02_an_py310/test_main.py diff --git a/docs_src/settings/app02_an_py39/config.py b/docs_src/settings/app02_an_py39/config.py deleted file mode 100644 index e17b5035dcc77..0000000000000 --- a/docs_src/settings/app02_an_py39/config.py +++ /dev/null @@ -1,7 +0,0 @@ -from pydantic_settings import BaseSettings - - -class Settings(BaseSettings): - app_name: str = "Awesome API" - admin_email: str - items_per_user: int = 50 diff --git a/docs_src/settings/app02_an_py39/main.py b/docs_src/settings/app02_an_py39/main.py deleted file mode 100644 index 61be74fcb9a17..0000000000000 --- a/docs_src/settings/app02_an_py39/main.py +++ /dev/null @@ -1,22 +0,0 @@ -from functools import lru_cache -from typing import Annotated - -from fastapi import Depends, FastAPI - -from .config import Settings - -app = FastAPI() - - -@lru_cache() -def get_settings(): - return Settings() - - -@app.get("/info") -async def info(settings: Annotated[Settings, Depends(get_settings)]): - return { - "app_name": settings.app_name, - "admin_email": settings.admin_email, - "items_per_user": settings.items_per_user, - } diff --git a/docs_src/settings/app02_an_py39/test_main.py b/docs_src/settings/app02_an_py39/test_main.py deleted file mode 100644 index 7a04d7e8ee02a..0000000000000 --- a/docs_src/settings/app02_an_py39/test_main.py +++ /dev/null @@ -1,23 +0,0 @@ -from fastapi.testclient import TestClient - -from .config import Settings -from .main import app, get_settings - -client = TestClient(app) - - -def get_settings_override(): - return Settings(admin_email="testing_admin@example.com") - - -app.dependency_overrides[get_settings] = get_settings_override - - -def test_app(): - response = client.get("/info") - data = response.json() - assert data == { - "app_name": "Awesome API", - "admin_email": "testing_admin@example.com", - "items_per_user": 50, - } diff --git a/docs_src/settings/app02_py310/__init__.py b/docs_src/settings/app02_py310/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/settings/app02_an/config.py b/docs_src/settings/app02_py310/config.py similarity index 100% rename from docs_src/settings/app02_an/config.py rename to docs_src/settings/app02_py310/config.py diff --git a/docs_src/settings/app02_py310/main.py b/docs_src/settings/app02_py310/main.py new file mode 100644 index 0000000000000..941f82e6b39b6 --- /dev/null +++ b/docs_src/settings/app02_py310/main.py @@ -0,0 +1,21 @@ +from functools import lru_cache + +from fastapi import Depends, FastAPI + +from .config import Settings + +app = FastAPI() + + +@lru_cache +def get_settings(): + return Settings() + + +@app.get("/info") +async def info(settings: Settings = Depends(get_settings)): + return { + "app_name": settings.app_name, + "admin_email": settings.admin_email, + "items_per_user": settings.items_per_user, + } diff --git a/docs_src/settings/app02_an/test_main.py b/docs_src/settings/app02_py310/test_main.py similarity index 100% rename from docs_src/settings/app02_an/test_main.py rename to docs_src/settings/app02_py310/test_main.py diff --git a/docs_src/settings/app03/config.py b/docs_src/settings/app03/config.py deleted file mode 100644 index 942aea3e58b70..0000000000000 --- a/docs_src/settings/app03/config.py +++ /dev/null @@ -1,10 +0,0 @@ -from pydantic_settings import BaseSettings - - -class Settings(BaseSettings): - app_name: str = "Awesome API" - admin_email: str - items_per_user: int = 50 - - class Config: - env_file = ".env" diff --git a/docs_src/settings/app03/main.py b/docs_src/settings/app03/main.py deleted file mode 100644 index 69bc8c6e0eb6b..0000000000000 --- a/docs_src/settings/app03/main.py +++ /dev/null @@ -1,21 +0,0 @@ -from functools import lru_cache - -from fastapi import Depends, FastAPI - -from . import config - -app = FastAPI() - - -@lru_cache() -def get_settings(): - return config.Settings() - - -@app.get("/info") -async def info(settings: config.Settings = Depends(get_settings)): - return { - "app_name": settings.app_name, - "admin_email": settings.admin_email, - "items_per_user": settings.items_per_user, - } diff --git a/docs_src/settings/app03_an/config_pv1.py b/docs_src/settings/app03_an/config_pv1.py deleted file mode 100644 index e1c3ee30063b7..0000000000000 --- a/docs_src/settings/app03_an/config_pv1.py +++ /dev/null @@ -1,10 +0,0 @@ -from pydantic import BaseSettings - - -class Settings(BaseSettings): - app_name: str = "Awesome API" - admin_email: str - items_per_user: int = 50 - - class Config: - env_file = ".env" diff --git a/docs_src/settings/app03_an/main.py b/docs_src/settings/app03_an/main.py deleted file mode 100644 index c33b98f474880..0000000000000 --- a/docs_src/settings/app03_an/main.py +++ /dev/null @@ -1,22 +0,0 @@ -from functools import lru_cache -from typing import Annotated - -from fastapi import Depends, FastAPI - -from . import config - -app = FastAPI() - - -@lru_cache() -def get_settings(): - return config.Settings() - - -@app.get("/info") -async def info(settings: Annotated[config.Settings, Depends(get_settings)]): - return { - "app_name": settings.app_name, - "admin_email": settings.admin_email, - "items_per_user": settings.items_per_user, - } diff --git a/docs_src/settings/app03_an_py310/__init__.py b/docs_src/settings/app03_an_py310/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/settings/app03_an/config.py b/docs_src/settings/app03_an_py310/config.py similarity index 100% rename from docs_src/settings/app03_an/config.py rename to docs_src/settings/app03_an_py310/config.py diff --git a/docs_src/settings/app03_an_py310/main.py b/docs_src/settings/app03_an_py310/main.py new file mode 100644 index 0000000000000..2f64b9cd175d8 --- /dev/null +++ b/docs_src/settings/app03_an_py310/main.py @@ -0,0 +1,22 @@ +from functools import lru_cache +from typing import Annotated + +from fastapi import Depends, FastAPI + +from . import config + +app = FastAPI() + + +@lru_cache +def get_settings(): + return config.Settings() + + +@app.get("/info") +async def info(settings: Annotated[config.Settings, Depends(get_settings)]): + return { + "app_name": settings.app_name, + "admin_email": settings.admin_email, + "items_per_user": settings.items_per_user, + } diff --git a/docs_src/settings/app03_an_py39/config.py b/docs_src/settings/app03_an_py39/config.py deleted file mode 100644 index 942aea3e58b70..0000000000000 --- a/docs_src/settings/app03_an_py39/config.py +++ /dev/null @@ -1,10 +0,0 @@ -from pydantic_settings import BaseSettings - - -class Settings(BaseSettings): - app_name: str = "Awesome API" - admin_email: str - items_per_user: int = 50 - - class Config: - env_file = ".env" diff --git a/docs_src/settings/app03_an_py39/main.py b/docs_src/settings/app03_an_py39/main.py deleted file mode 100644 index b89c6b6cf44fb..0000000000000 --- a/docs_src/settings/app03_an_py39/main.py +++ /dev/null @@ -1,22 +0,0 @@ -from functools import lru_cache - -from fastapi import Depends, FastAPI -from typing_extensions import Annotated - -from . import config - -app = FastAPI() - - -@lru_cache() -def get_settings(): - return config.Settings() - - -@app.get("/info") -async def info(settings: Annotated[config.Settings, Depends(get_settings)]): - return { - "app_name": settings.app_name, - "admin_email": settings.admin_email, - "items_per_user": settings.items_per_user, - } diff --git a/docs_src/settings/app03_py310/__init__.py b/docs_src/settings/app03_py310/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/settings/app03_py310/config.py b/docs_src/settings/app03_py310/config.py new file mode 100644 index 0000000000000..08f8f88c280ac --- /dev/null +++ b/docs_src/settings/app03_py310/config.py @@ -0,0 +1,9 @@ +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class Settings(BaseSettings): + app_name: str = "Awesome API" + admin_email: str + items_per_user: int = 50 + + model_config = SettingsConfigDict(env_file=".env") diff --git a/docs_src/settings/app03_py310/main.py b/docs_src/settings/app03_py310/main.py new file mode 100644 index 0000000000000..ea64a5709cb49 --- /dev/null +++ b/docs_src/settings/app03_py310/main.py @@ -0,0 +1,21 @@ +from functools import lru_cache + +from fastapi import Depends, FastAPI + +from . import config + +app = FastAPI() + + +@lru_cache +def get_settings(): + return config.Settings() + + +@app.get("/info") +async def info(settings: config.Settings = Depends(get_settings)): + return { + "app_name": settings.app_name, + "admin_email": settings.admin_email, + "items_per_user": settings.items_per_user, + } diff --git a/docs_src/settings/tutorial001_pv1.py b/docs_src/settings/tutorial001_pv1.py deleted file mode 100644 index 0cfd1b6632f0b..0000000000000 --- a/docs_src/settings/tutorial001_pv1.py +++ /dev/null @@ -1,21 +0,0 @@ -from fastapi import FastAPI -from pydantic import BaseSettings - - -class Settings(BaseSettings): - app_name: str = "Awesome API" - admin_email: str - items_per_user: int = 50 - - -settings = Settings() -app = FastAPI() - - -@app.get("/info") -async def info(): - return { - "app_name": settings.app_name, - "admin_email": settings.admin_email, - "items_per_user": settings.items_per_user, - } diff --git a/docs_src/settings/tutorial001.py b/docs_src/settings/tutorial001_py310.py similarity index 100% rename from docs_src/settings/tutorial001.py rename to docs_src/settings/tutorial001_py310.py diff --git a/docs_src/sql_databases/sql_app/alt_main.py b/docs_src/sql_databases/sql_app/alt_main.py deleted file mode 100644 index f7206bcb4173f..0000000000000 --- a/docs_src/sql_databases/sql_app/alt_main.py +++ /dev/null @@ -1,62 +0,0 @@ -from typing import List - -from fastapi import Depends, FastAPI, HTTPException, Request, Response -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -@app.middleware("http") -async def db_session_middleware(request: Request, call_next): - response = Response("Internal server error", status_code=500) - try: - request.state.db = SessionLocal() - response = await call_next(request) - finally: - request.state.db.close() - return response - - -# Dependency -def get_db(request: Request): - return request.state.db - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=List[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=List[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app/crud.py b/docs_src/sql_databases/sql_app/crud.py deleted file mode 100644 index 679acdb5cee6d..0000000000000 --- a/docs_src/sql_databases/sql_app/crud.py +++ /dev/null @@ -1,36 +0,0 @@ -from sqlalchemy.orm import Session - -from . import models, schemas - - -def get_user(db: Session, user_id: int): - return db.query(models.User).filter(models.User.id == user_id).first() - - -def get_user_by_email(db: Session, email: str): - return db.query(models.User).filter(models.User.email == email).first() - - -def get_users(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.User).offset(skip).limit(limit).all() - - -def create_user(db: Session, user: schemas.UserCreate): - fake_hashed_password = user.password + "notreallyhashed" - db_user = models.User(email=user.email, hashed_password=fake_hashed_password) - db.add(db_user) - db.commit() - db.refresh(db_user) - return db_user - - -def get_items(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.Item).offset(skip).limit(limit).all() - - -def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int): - db_item = models.Item(**item.dict(), owner_id=user_id) - db.add(db_item) - db.commit() - db.refresh(db_item) - return db_item diff --git a/docs_src/sql_databases/sql_app/database.py b/docs_src/sql_databases/sql_app/database.py deleted file mode 100644 index 45a8b9f6942b3..0000000000000 --- a/docs_src/sql_databases/sql_app/database.py +++ /dev/null @@ -1,13 +0,0 @@ -from sqlalchemy import create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker - -SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" -# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - -Base = declarative_base() diff --git a/docs_src/sql_databases/sql_app/main.py b/docs_src/sql_databases/sql_app/main.py deleted file mode 100644 index e7508c59d45d0..0000000000000 --- a/docs_src/sql_databases/sql_app/main.py +++ /dev/null @@ -1,55 +0,0 @@ -from typing import List - -from fastapi import Depends, FastAPI, HTTPException -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -# Dependency -def get_db(): - db = SessionLocal() - try: - yield db - finally: - db.close() - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=List[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=List[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app/models.py b/docs_src/sql_databases/sql_app/models.py deleted file mode 100644 index 62d8ab4aaac16..0000000000000 --- a/docs_src/sql_databases/sql_app/models.py +++ /dev/null @@ -1,26 +0,0 @@ -from sqlalchemy import Boolean, Column, ForeignKey, Integer, String -from sqlalchemy.orm import relationship - -from .database import Base - - -class User(Base): - __tablename__ = "users" - - id = Column(Integer, primary_key=True, index=True) - email = Column(String, unique=True, index=True) - hashed_password = Column(String) - is_active = Column(Boolean, default=True) - - items = relationship("Item", back_populates="owner") - - -class Item(Base): - __tablename__ = "items" - - id = Column(Integer, primary_key=True, index=True) - title = Column(String, index=True) - description = Column(String, index=True) - owner_id = Column(Integer, ForeignKey("users.id")) - - owner = relationship("User", back_populates="items") diff --git a/docs_src/sql_databases/sql_app/schemas.py b/docs_src/sql_databases/sql_app/schemas.py deleted file mode 100644 index c49beba882707..0000000000000 --- a/docs_src/sql_databases/sql_app/schemas.py +++ /dev/null @@ -1,37 +0,0 @@ -from typing import List, Union - -from pydantic import BaseModel - - -class ItemBase(BaseModel): - title: str - description: Union[str, None] = None - - -class ItemCreate(ItemBase): - pass - - -class Item(ItemBase): - id: int - owner_id: int - - class Config: - orm_mode = True - - -class UserBase(BaseModel): - email: str - - -class UserCreate(UserBase): - password: str - - -class User(UserBase): - id: int - is_active: bool - items: List[Item] = [] - - class Config: - orm_mode = True diff --git a/docs_src/sql_databases/sql_app/tests/test_sql_app.py b/docs_src/sql_databases/sql_app/tests/test_sql_app.py deleted file mode 100644 index 5f55add0a9b49..0000000000000 --- a/docs_src/sql_databases/sql_app/tests/test_sql_app.py +++ /dev/null @@ -1,50 +0,0 @@ -from fastapi.testclient import TestClient -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import StaticPool - -from ..database import Base -from ..main import app, get_db - -SQLALCHEMY_DATABASE_URL = "sqlite://" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, - connect_args={"check_same_thread": False}, - poolclass=StaticPool, -) -TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - - -Base.metadata.create_all(bind=engine) - - -def override_get_db(): - try: - db = TestingSessionLocal() - yield db - finally: - db.close() - - -app.dependency_overrides[get_db] = override_get_db - -client = TestClient(app) - - -def test_create_user(): - response = client.post( - "/users/", - json={"email": "deadpool@example.com", "password": "chimichangas4life"}, - ) - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert "id" in data - user_id = data["id"] - - response = client.get(f"/users/{user_id}") - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert data["id"] == user_id diff --git a/docs_src/sql_databases/sql_app_py310/alt_main.py b/docs_src/sql_databases/sql_app_py310/alt_main.py deleted file mode 100644 index 5de88ec3a13a8..0000000000000 --- a/docs_src/sql_databases/sql_app_py310/alt_main.py +++ /dev/null @@ -1,60 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException, Request, Response -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -@app.middleware("http") -async def db_session_middleware(request: Request, call_next): - response = Response("Internal server error", status_code=500) - try: - request.state.db = SessionLocal() - response = await call_next(request) - finally: - request.state.db.close() - return response - - -# Dependency -def get_db(request: Request): - return request.state.db - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py310/crud.py b/docs_src/sql_databases/sql_app_py310/crud.py deleted file mode 100644 index 679acdb5cee6d..0000000000000 --- a/docs_src/sql_databases/sql_app_py310/crud.py +++ /dev/null @@ -1,36 +0,0 @@ -from sqlalchemy.orm import Session - -from . import models, schemas - - -def get_user(db: Session, user_id: int): - return db.query(models.User).filter(models.User.id == user_id).first() - - -def get_user_by_email(db: Session, email: str): - return db.query(models.User).filter(models.User.email == email).first() - - -def get_users(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.User).offset(skip).limit(limit).all() - - -def create_user(db: Session, user: schemas.UserCreate): - fake_hashed_password = user.password + "notreallyhashed" - db_user = models.User(email=user.email, hashed_password=fake_hashed_password) - db.add(db_user) - db.commit() - db.refresh(db_user) - return db_user - - -def get_items(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.Item).offset(skip).limit(limit).all() - - -def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int): - db_item = models.Item(**item.dict(), owner_id=user_id) - db.add(db_item) - db.commit() - db.refresh(db_item) - return db_item diff --git a/docs_src/sql_databases/sql_app_py310/database.py b/docs_src/sql_databases/sql_app_py310/database.py deleted file mode 100644 index 45a8b9f6942b3..0000000000000 --- a/docs_src/sql_databases/sql_app_py310/database.py +++ /dev/null @@ -1,13 +0,0 @@ -from sqlalchemy import create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker - -SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" -# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - -Base = declarative_base() diff --git a/docs_src/sql_databases/sql_app_py310/main.py b/docs_src/sql_databases/sql_app_py310/main.py deleted file mode 100644 index a9856d0b68cc1..0000000000000 --- a/docs_src/sql_databases/sql_app_py310/main.py +++ /dev/null @@ -1,53 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -# Dependency -def get_db(): - db = SessionLocal() - try: - yield db - finally: - db.close() - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py310/models.py b/docs_src/sql_databases/sql_app_py310/models.py deleted file mode 100644 index 62d8ab4aaac16..0000000000000 --- a/docs_src/sql_databases/sql_app_py310/models.py +++ /dev/null @@ -1,26 +0,0 @@ -from sqlalchemy import Boolean, Column, ForeignKey, Integer, String -from sqlalchemy.orm import relationship - -from .database import Base - - -class User(Base): - __tablename__ = "users" - - id = Column(Integer, primary_key=True, index=True) - email = Column(String, unique=True, index=True) - hashed_password = Column(String) - is_active = Column(Boolean, default=True) - - items = relationship("Item", back_populates="owner") - - -class Item(Base): - __tablename__ = "items" - - id = Column(Integer, primary_key=True, index=True) - title = Column(String, index=True) - description = Column(String, index=True) - owner_id = Column(Integer, ForeignKey("users.id")) - - owner = relationship("User", back_populates="items") diff --git a/docs_src/sql_databases/sql_app_py310/schemas.py b/docs_src/sql_databases/sql_app_py310/schemas.py deleted file mode 100644 index aea2e3f1016cf..0000000000000 --- a/docs_src/sql_databases/sql_app_py310/schemas.py +++ /dev/null @@ -1,35 +0,0 @@ -from pydantic import BaseModel - - -class ItemBase(BaseModel): - title: str - description: str | None = None - - -class ItemCreate(ItemBase): - pass - - -class Item(ItemBase): - id: int - owner_id: int - - class Config: - orm_mode = True - - -class UserBase(BaseModel): - email: str - - -class UserCreate(UserBase): - password: str - - -class User(UserBase): - id: int - is_active: bool - items: list[Item] = [] - - class Config: - orm_mode = True diff --git a/docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py b/docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py deleted file mode 100644 index c60c3356f85ed..0000000000000 --- a/docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py +++ /dev/null @@ -1,47 +0,0 @@ -from fastapi.testclient import TestClient -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker - -from ..database import Base -from ..main import app, get_db - -SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - - -Base.metadata.create_all(bind=engine) - - -def override_get_db(): - try: - db = TestingSessionLocal() - yield db - finally: - db.close() - - -app.dependency_overrides[get_db] = override_get_db - -client = TestClient(app) - - -def test_create_user(): - response = client.post( - "/users/", - json={"email": "deadpool@example.com", "password": "chimichangas4life"}, - ) - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert "id" in data - user_id = data["id"] - - response = client.get(f"/users/{user_id}") - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert data["id"] == user_id diff --git a/docs_src/sql_databases/sql_app_py39/alt_main.py b/docs_src/sql_databases/sql_app_py39/alt_main.py deleted file mode 100644 index 5de88ec3a13a8..0000000000000 --- a/docs_src/sql_databases/sql_app_py39/alt_main.py +++ /dev/null @@ -1,60 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException, Request, Response -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -@app.middleware("http") -async def db_session_middleware(request: Request, call_next): - response = Response("Internal server error", status_code=500) - try: - request.state.db = SessionLocal() - response = await call_next(request) - finally: - request.state.db.close() - return response - - -# Dependency -def get_db(request: Request): - return request.state.db - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py39/crud.py b/docs_src/sql_databases/sql_app_py39/crud.py deleted file mode 100644 index 679acdb5cee6d..0000000000000 --- a/docs_src/sql_databases/sql_app_py39/crud.py +++ /dev/null @@ -1,36 +0,0 @@ -from sqlalchemy.orm import Session - -from . import models, schemas - - -def get_user(db: Session, user_id: int): - return db.query(models.User).filter(models.User.id == user_id).first() - - -def get_user_by_email(db: Session, email: str): - return db.query(models.User).filter(models.User.email == email).first() - - -def get_users(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.User).offset(skip).limit(limit).all() - - -def create_user(db: Session, user: schemas.UserCreate): - fake_hashed_password = user.password + "notreallyhashed" - db_user = models.User(email=user.email, hashed_password=fake_hashed_password) - db.add(db_user) - db.commit() - db.refresh(db_user) - return db_user - - -def get_items(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.Item).offset(skip).limit(limit).all() - - -def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int): - db_item = models.Item(**item.dict(), owner_id=user_id) - db.add(db_item) - db.commit() - db.refresh(db_item) - return db_item diff --git a/docs_src/sql_databases/sql_app_py39/database.py b/docs_src/sql_databases/sql_app_py39/database.py deleted file mode 100644 index 45a8b9f6942b3..0000000000000 --- a/docs_src/sql_databases/sql_app_py39/database.py +++ /dev/null @@ -1,13 +0,0 @@ -from sqlalchemy import create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker - -SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" -# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - -Base = declarative_base() diff --git a/docs_src/sql_databases/sql_app_py39/main.py b/docs_src/sql_databases/sql_app_py39/main.py deleted file mode 100644 index a9856d0b68cc1..0000000000000 --- a/docs_src/sql_databases/sql_app_py39/main.py +++ /dev/null @@ -1,53 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -# Dependency -def get_db(): - db = SessionLocal() - try: - yield db - finally: - db.close() - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py39/models.py b/docs_src/sql_databases/sql_app_py39/models.py deleted file mode 100644 index 62d8ab4aaac16..0000000000000 --- a/docs_src/sql_databases/sql_app_py39/models.py +++ /dev/null @@ -1,26 +0,0 @@ -from sqlalchemy import Boolean, Column, ForeignKey, Integer, String -from sqlalchemy.orm import relationship - -from .database import Base - - -class User(Base): - __tablename__ = "users" - - id = Column(Integer, primary_key=True, index=True) - email = Column(String, unique=True, index=True) - hashed_password = Column(String) - is_active = Column(Boolean, default=True) - - items = relationship("Item", back_populates="owner") - - -class Item(Base): - __tablename__ = "items" - - id = Column(Integer, primary_key=True, index=True) - title = Column(String, index=True) - description = Column(String, index=True) - owner_id = Column(Integer, ForeignKey("users.id")) - - owner = relationship("User", back_populates="items") diff --git a/docs_src/sql_databases/sql_app_py39/schemas.py b/docs_src/sql_databases/sql_app_py39/schemas.py deleted file mode 100644 index dadc403d93f8b..0000000000000 --- a/docs_src/sql_databases/sql_app_py39/schemas.py +++ /dev/null @@ -1,37 +0,0 @@ -from typing import Union - -from pydantic import BaseModel - - -class ItemBase(BaseModel): - title: str - description: Union[str, None] = None - - -class ItemCreate(ItemBase): - pass - - -class Item(ItemBase): - id: int - owner_id: int - - class Config: - orm_mode = True - - -class UserBase(BaseModel): - email: str - - -class UserCreate(UserBase): - password: str - - -class User(UserBase): - id: int - is_active: bool - items: list[Item] = [] - - class Config: - orm_mode = True diff --git a/docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py b/docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py deleted file mode 100644 index c60c3356f85ed..0000000000000 --- a/docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py +++ /dev/null @@ -1,47 +0,0 @@ -from fastapi.testclient import TestClient -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker - -from ..database import Base -from ..main import app, get_db - -SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - - -Base.metadata.create_all(bind=engine) - - -def override_get_db(): - try: - db = TestingSessionLocal() - yield db - finally: - db.close() - - -app.dependency_overrides[get_db] = override_get_db - -client = TestClient(app) - - -def test_create_user(): - response = client.post( - "/users/", - json={"email": "deadpool@example.com", "password": "chimichangas4life"}, - ) - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert "id" in data - user_id = data["id"] - - response = client.get(f"/users/{user_id}") - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert data["id"] == user_id diff --git a/docs_src/sql_databases/tutorial001_an_py310.py b/docs_src/sql_databases/tutorial001_an_py310.py new file mode 100644 index 0000000000000..de1fb81faf20a --- /dev/null +++ b/docs_src/sql_databases/tutorial001_an_py310.py @@ -0,0 +1,73 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: int | None = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: SessionDep) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +) -> list[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: SessionDep) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_py310.py b/docs_src/sql_databases/tutorial001_py310.py new file mode 100644 index 0000000000000..b58462e6a5dd7 --- /dev/null +++ b/docs_src/sql_databases/tutorial001_py310.py @@ -0,0 +1,69 @@ +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: int | None = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: Session = Depends(get_session)) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +) -> list[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: Session = Depends(get_session)) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_an_py310.py b/docs_src/sql_databases/tutorial002_an_py310.py new file mode 100644 index 0000000000000..64c554b8a2b63 --- /dev/null +++ b/docs_src/sql_databases/tutorial002_an_py310.py @@ -0,0 +1,103 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: int | None = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: str | None = None + age: int | None = None + secret_name: str | None = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: SessionDep): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=list[HeroPublic]) +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_py310.py b/docs_src/sql_databases/tutorial002_py310.py new file mode 100644 index 0000000000000..ec3d68db53a18 --- /dev/null +++ b/docs_src/sql_databases/tutorial002_py310.py @@ -0,0 +1,102 @@ +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: int | None = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: str | None = None + age: int | None = None + secret_name: str | None = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: Session = Depends(get_session)): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=list[HeroPublic]) +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero( + hero_id: int, hero: HeroUpdate, session: Session = Depends(get_session) +): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases_peewee/sql_app/crud.py b/docs_src/sql_databases_peewee/sql_app/crud.py deleted file mode 100644 index 56c5875595aac..0000000000000 --- a/docs_src/sql_databases_peewee/sql_app/crud.py +++ /dev/null @@ -1,30 +0,0 @@ -from . import models, schemas - - -def get_user(user_id: int): - return models.User.filter(models.User.id == user_id).first() - - -def get_user_by_email(email: str): - return models.User.filter(models.User.email == email).first() - - -def get_users(skip: int = 0, limit: int = 100): - return list(models.User.select().offset(skip).limit(limit)) - - -def create_user(user: schemas.UserCreate): - fake_hashed_password = user.password + "notreallyhashed" - db_user = models.User(email=user.email, hashed_password=fake_hashed_password) - db_user.save() - return db_user - - -def get_items(skip: int = 0, limit: int = 100): - return list(models.Item.select().offset(skip).limit(limit)) - - -def create_user_item(item: schemas.ItemCreate, user_id: int): - db_item = models.Item(**item.dict(), owner_id=user_id) - db_item.save() - return db_item diff --git a/docs_src/sql_databases_peewee/sql_app/database.py b/docs_src/sql_databases_peewee/sql_app/database.py deleted file mode 100644 index 6938fe8263977..0000000000000 --- a/docs_src/sql_databases_peewee/sql_app/database.py +++ /dev/null @@ -1,24 +0,0 @@ -from contextvars import ContextVar - -import peewee - -DATABASE_NAME = "test.db" -db_state_default = {"closed": None, "conn": None, "ctx": None, "transactions": None} -db_state = ContextVar("db_state", default=db_state_default.copy()) - - -class PeeweeConnectionState(peewee._ConnectionState): - def __init__(self, **kwargs): - super().__setattr__("_state", db_state) - super().__init__(**kwargs) - - def __setattr__(self, name, value): - self._state.get()[name] = value - - def __getattr__(self, name): - return self._state.get()[name] - - -db = peewee.SqliteDatabase(DATABASE_NAME, check_same_thread=False) - -db._state = PeeweeConnectionState() diff --git a/docs_src/sql_databases_peewee/sql_app/main.py b/docs_src/sql_databases_peewee/sql_app/main.py deleted file mode 100644 index 8fbd2075d62d2..0000000000000 --- a/docs_src/sql_databases_peewee/sql_app/main.py +++ /dev/null @@ -1,79 +0,0 @@ -import time -from typing import List - -from fastapi import Depends, FastAPI, HTTPException - -from . import crud, database, models, schemas -from .database import db_state_default - -database.db.connect() -database.db.create_tables([models.User, models.Item]) -database.db.close() - -app = FastAPI() - -sleep_time = 10 - - -async def reset_db_state(): - database.db._state._state.set(db_state_default.copy()) - database.db._state.reset() - - -def get_db(db_state=Depends(reset_db_state)): - try: - database.db.connect() - yield - finally: - if not database.db.is_closed(): - database.db.close() - - -@app.post("/users/", response_model=schemas.User, dependencies=[Depends(get_db)]) -def create_user(user: schemas.UserCreate): - db_user = crud.get_user_by_email(email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(user=user) - - -@app.get("/users/", response_model=List[schemas.User], dependencies=[Depends(get_db)]) -def read_users(skip: int = 0, limit: int = 100): - users = crud.get_users(skip=skip, limit=limit) - return users - - -@app.get( - "/users/{user_id}", response_model=schemas.User, dependencies=[Depends(get_db)] -) -def read_user(user_id: int): - db_user = crud.get_user(user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post( - "/users/{user_id}/items/", - response_model=schemas.Item, - dependencies=[Depends(get_db)], -) -def create_item_for_user(user_id: int, item: schemas.ItemCreate): - return crud.create_user_item(item=item, user_id=user_id) - - -@app.get("/items/", response_model=List[schemas.Item], dependencies=[Depends(get_db)]) -def read_items(skip: int = 0, limit: int = 100): - items = crud.get_items(skip=skip, limit=limit) - return items - - -@app.get( - "/slowusers/", response_model=List[schemas.User], dependencies=[Depends(get_db)] -) -def read_slow_users(skip: int = 0, limit: int = 100): - global sleep_time - sleep_time = max(0, sleep_time - 1) - time.sleep(sleep_time) # Fake long processing request - users = crud.get_users(skip=skip, limit=limit) - return users diff --git a/docs_src/sql_databases_peewee/sql_app/models.py b/docs_src/sql_databases_peewee/sql_app/models.py deleted file mode 100644 index 46bdcd009e77d..0000000000000 --- a/docs_src/sql_databases_peewee/sql_app/models.py +++ /dev/null @@ -1,21 +0,0 @@ -import peewee - -from .database import db - - -class User(peewee.Model): - email = peewee.CharField(unique=True, index=True) - hashed_password = peewee.CharField() - is_active = peewee.BooleanField(default=True) - - class Meta: - database = db - - -class Item(peewee.Model): - title = peewee.CharField(index=True) - description = peewee.CharField(index=True) - owner = peewee.ForeignKeyField(User, backref="items") - - class Meta: - database = db diff --git a/docs_src/sql_databases_peewee/sql_app/schemas.py b/docs_src/sql_databases_peewee/sql_app/schemas.py deleted file mode 100644 index d8775cb30c0c9..0000000000000 --- a/docs_src/sql_databases_peewee/sql_app/schemas.py +++ /dev/null @@ -1,49 +0,0 @@ -from typing import Any, List, Union - -import peewee -from pydantic import BaseModel -from pydantic.utils import GetterDict - - -class PeeweeGetterDict(GetterDict): - def get(self, key: Any, default: Any = None): - res = getattr(self._obj, key, default) - if isinstance(res, peewee.ModelSelect): - return list(res) - return res - - -class ItemBase(BaseModel): - title: str - description: Union[str, None] = None - - -class ItemCreate(ItemBase): - pass - - -class Item(ItemBase): - id: int - owner_id: int - - class Config: - orm_mode = True - getter_dict = PeeweeGetterDict - - -class UserBase(BaseModel): - email: str - - -class UserCreate(UserBase): - password: str - - -class User(UserBase): - id: int - is_active: bool - items: List[Item] = [] - - class Config: - orm_mode = True - getter_dict = PeeweeGetterDict diff --git a/docs_src/static_files/__init__.py b/docs_src/static_files/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/static_files/tutorial001.py b/docs_src/static_files/tutorial001_py310.py similarity index 100% rename from docs_src/static_files/tutorial001.py rename to docs_src/static_files/tutorial001_py310.py diff --git a/docs_src/stream_data/__init__.py b/docs_src/stream_data/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/stream_data/tutorial001_py310.py b/docs_src/stream_data/tutorial001_py310.py new file mode 100644 index 0000000000000..2e91ec9ac9c09 --- /dev/null +++ b/docs_src/stream_data/tutorial001_py310.py @@ -0,0 +1,65 @@ +from collections.abc import AsyncIterable, Iterable + +from fastapi import FastAPI +from fastapi.responses import StreamingResponse + +app = FastAPI() + + +message = """ +Rick: (stumbles in drunkenly, and turns on the lights) Morty! You gotta come on. You got--... you gotta come with me. +Morty: (rubs his eyes) What, Rick? What's going on? +Rick: I got a surprise for you, Morty. +Morty: It's the middle of the night. What are you talking about? +Rick: (spills alcohol on Morty's bed) Come on, I got a surprise for you. (drags Morty by the ankle) Come on, hurry up. (pulls Morty out of his bed and into the hall) +Morty: Ow! Ow! You're tugging me too hard! +Rick: We gotta go, gotta get outta here, come on. Got a surprise for you Morty. +""" + + +@app.get("/story/stream", response_class=StreamingResponse) +async def stream_story() -> AsyncIterable[str]: + for line in message.splitlines(): + yield line + + +@app.get("/story/stream-no-async", response_class=StreamingResponse) +def stream_story_no_async() -> Iterable[str]: + for line in message.splitlines(): + yield line + + +@app.get("/story/stream-no-annotation", response_class=StreamingResponse) +async def stream_story_no_annotation(): + for line in message.splitlines(): + yield line + + +@app.get("/story/stream-no-async-no-annotation", response_class=StreamingResponse) +def stream_story_no_async_no_annotation(): + for line in message.splitlines(): + yield line + + +@app.get("/story/stream-bytes", response_class=StreamingResponse) +async def stream_story_bytes() -> AsyncIterable[bytes]: + for line in message.splitlines(): + yield line.encode("utf-8") + + +@app.get("/story/stream-no-async-bytes", response_class=StreamingResponse) +def stream_story_no_async_bytes() -> Iterable[bytes]: + for line in message.splitlines(): + yield line.encode("utf-8") + + +@app.get("/story/stream-no-annotation-bytes", response_class=StreamingResponse) +async def stream_story_no_annotation_bytes(): + for line in message.splitlines(): + yield line.encode("utf-8") + + +@app.get("/story/stream-no-async-no-annotation-bytes", response_class=StreamingResponse) +def stream_story_no_async_no_annotation_bytes(): + for line in message.splitlines(): + yield line.encode("utf-8") diff --git a/docs_src/stream_data/tutorial002_py310.py b/docs_src/stream_data/tutorial002_py310.py new file mode 100644 index 0000000000000..aa8bcee3a925e --- /dev/null +++ b/docs_src/stream_data/tutorial002_py310.py @@ -0,0 +1,54 @@ +import base64 +from collections.abc import AsyncIterable, Iterable +from io import BytesIO + +from fastapi import FastAPI +from fastapi.responses import StreamingResponse + +image_base64 = "iVBORw0KGgoAAAANSUhEUgAAAB0AAAAdCAYAAABWk2cPAAAAbnpUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHjadYzRDYAwCET/mcIRDoq0jGOiJm7g+NJK0vjhS4DjIEfHfZ20DKqSrrWZmyFQV5ctRMOLACxglNCcXk7zVqFzJzF8kV6R5vOJ97yVH78HjfYAtg0ged033ZgAAAoCaVRYdFhNTDpjb20uYWRvYmUueG1wAAAAAAA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/Pgo8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJYTVAgQ29yZSA0LjQuMC1FeGl2MiI+CiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogIDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiCiAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyIKICAgIHhtbG5zOnRpZmY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vdGlmZi8xLjAvIgogICBleGlmOlBpeGVsWERpbWVuc2lvbj0iMjkiCiAgIGV4aWY6UGl4ZWxZRGltZW5zaW9uPSIyOSIKICAgdGlmZjpJbWFnZVdpZHRoPSIyOSIKICAgdGlmZjpJbWFnZUxlbmd0aD0iMjkiCiAgIHRpZmY6T3JpZW50YXRpb249IjEiLz4KIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAKPD94cGFja2V0IGVuZD0idyI/PnQkBZAAAAAEc0JJVAgICAh8CGSIAAABoklEQVRIx8VXwY7FIAjE5iXWU+P/f6RHPNW9LIaOoHYP+0yMShVkwNGG1lqjfy4HfaF0oyEEt+oSQqBaa//m9Wd6PlqhhbRMDiEQM3e59FNKw5qZHpnQfuPaW6lazsztvu/eElFj5j63lNLlMz2ttbZtVMu1MTGo5Sujn93gMzOllKiUQjHGB9QxxneZhJ5iwZ1rL2fwenoGeL0q3wVGhBPHMz0PeFccIfASEeWcO8xEROd50q6eAV6s1s5XXoncas1EKqVQznnwUBdJJmm1l3hmmdlOMrGO8Vl5gZ56Y0y8IZF0BuqkQWM4B6HXrRCKa1SEqyzEo7KK59RT/VHDjX3ZvSefeW3CO6O6vsiA1NrwVkxxAcYTCcHyTjZmJd00pugBQoTnzjvn+kzLBh9GtRDjhleZFwbx3kugP3GvFzdkqRlbDYw0u/HxKjuOw2QxZCGL5V5f4l7cd6qsffUa1DcLM9N1XcTMvep5ul1e4jNPtZfWGIkE6dI8MquXg/dS2CGVJQ2ushd5GmlxFdOw+1tRa32MY4zDQ9yaZ60J3/iX+QG4U3qGrFHmswAAAABJRU5ErkJggg==" +binary_image = base64.b64decode(image_base64) + + +def read_image() -> BytesIO: + return BytesIO(binary_image) + + +app = FastAPI() + + +class PNGStreamingResponse(StreamingResponse): + media_type = "image/png" + + +@app.get("/image/stream", response_class=PNGStreamingResponse) +async def stream_image() -> AsyncIterable[bytes]: + with read_image() as image_file: + for chunk in image_file: + yield chunk + + +@app.get("/image/stream-no-async", response_class=PNGStreamingResponse) +def stream_image_no_async() -> Iterable[bytes]: + with read_image() as image_file: + for chunk in image_file: + yield chunk + + +@app.get("/image/stream-no-async-yield-from", response_class=PNGStreamingResponse) +def stream_image_no_async_yield_from() -> Iterable[bytes]: + with read_image() as image_file: + yield from image_file + + +@app.get("/image/stream-no-annotation", response_class=PNGStreamingResponse) +async def stream_image_no_annotation(): + with read_image() as image_file: + for chunk in image_file: + yield chunk + + +@app.get("/image/stream-no-async-no-annotation", response_class=PNGStreamingResponse) +def stream_image_no_async_no_annotation(): + with read_image() as image_file: + for chunk in image_file: + yield chunk diff --git a/docs_src/stream_json_lines/__init__.py b/docs_src/stream_json_lines/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/stream_json_lines/tutorial001_py310.py b/docs_src/stream_json_lines/tutorial001_py310.py new file mode 100644 index 0000000000000..4fbe7c69cc650 --- /dev/null +++ b/docs_src/stream_json_lines/tutorial001_py310.py @@ -0,0 +1,42 @@ +from collections.abc import AsyncIterable, Iterable + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + description: str | None + + +items = [ + Item(name="Plumbus", description="A multi-purpose household device."), + Item(name="Portal Gun", description="A portal opening device."), + Item(name="Meeseeks Box", description="A box that summons a Meeseeks."), +] + + +@app.get("/items/stream") +async def stream_items() -> AsyncIterable[Item]: + for item in items: + yield item + + +@app.get("/items/stream-no-async") +def stream_items_no_async() -> Iterable[Item]: + for item in items: + yield item + + +@app.get("/items/stream-no-annotation") +async def stream_items_no_annotation(): + for item in items: + yield item + + +@app.get("/items/stream-no-async-no-annotation") +def stream_items_no_async_no_annotation(): + for item in items: + yield item diff --git a/docs_src/strict_content_type/__init__.py b/docs_src/strict_content_type/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/strict_content_type/tutorial001_py310.py b/docs_src/strict_content_type/tutorial001_py310.py new file mode 100644 index 0000000000000..a44f4b1386962 --- /dev/null +++ b/docs_src/strict_content_type/tutorial001_py310.py @@ -0,0 +1,14 @@ +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI(strict_content_type=False) + + +class Item(BaseModel): + name: str + price: float + + +@app.post("/items/") +async def create_item(item: Item): + return item diff --git a/docs_src/sub_applications/__init__.py b/docs_src/sub_applications/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/sub_applications/tutorial001.py b/docs_src/sub_applications/tutorial001_py310.py similarity index 100% rename from docs_src/sub_applications/tutorial001.py rename to docs_src/sub_applications/tutorial001_py310.py diff --git a/docs_src/templates/__init__.py b/docs_src/templates/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/templates/static/__init__.py b/docs_src/templates/static/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/templates/templates/__init__.py b/docs_src/templates/templates/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/docs_src/templates/templates/item.html b/docs_src/templates/templates/item.html index a70287e77d345..27994ca994b00 100644 --- a/docs_src/templates/templates/item.html +++ b/docs_src/templates/templates/item.html @@ -4,6 +4,6 @@ -